分散ロックのセキュリティ保護
分散ロックは、共有リソースへのアクセスを管理し、順序どおりにデータをトランザクション処理します。@secureDistributedLock decorator はロックをセキュリティ保護します。
分散ロックは、共有リソースへのアクセスを一度に 1 つの client にロックすることで、race condition を解決します。デフォルトでは、clients は分散ロックへのアクセスを拒否されます。lock への client access を認可するには、Squid backend の SquidService class で @secureDistributedLock() decorator を使用します。security function は boolean を返します。true は request を許可し、false は拒否します。
すべての clients に任意の分散ロックをロックするアクセスを許可するには、次の形式の security function を使用します。
- TypeScript
- Python
Backend code
import { secureDistributedLock, SquidService } from '@squidcloud/backend';
@secureDistributedLock()
allowAllAccessToAcquiringLock(): boolean {
return true;
}
Backend code
from squidcloud_backend import SquidService, secure_distributed_lock
class ExampleService(SquidService):
@secure_distributed_lock()
def allow_all_access_to_acquiring_lock(self, context: dict) -> bool:
return True
client が分散ロックを使用しようとすると、その client が使用している mutex value が DistributedLockContext(Python では mutex key を持つ dict)で Squid backend に渡されます。次の security function は、mutex value に基づいて lock をセキュリティ保護する方法を示しています。ここでは、allUsers mutex はすべての authenticated users が利用でき、admin mutex は auth token に admin attribute を持つ users のみが利用できます。
- TypeScript
- Python
Backend code
import { secureDistributedLock, SquidService, DistributedLockContext } from '@squidcloud/backend';
@secureDistributedLock()
allowAllAccessToAcquiringLock(context: DistributedLockContext): boolean {
// If the mutex is "allUsers", return true if authenticated
if (context.mutex === "allUsers") {
return this.isAuthenticated();
}
// If the mutex is "admin", return true if the user is an admin
if (context.mutex === "admin") {
const userAuth = this.getUserAuth();
return !!userAuth?.attributes['admin'];
}
return false; // all others are not allowed
}
Backend code
from squidcloud_backend import SquidService, secure_distributed_lock
class ExampleService(SquidService):
@secure_distributed_lock()
def allow_all_access_to_acquiring_lock(self, context: dict) -> bool:
# If the mutex is "allUsers", return True if authenticated
if context['mutex'] == 'allUsers':
return self.is_authenticated()
# If the mutex is "admin", return True if the user is an admin
if context['mutex'] == 'admin':
user_auth = self.get_user_auth()
return bool(user_auth and user_auth.get('attributes', {}).get('admin'))
return False # all others are not allowed
分散ロックを使用する app の例を見るには、こちらの blog postをご覧ください。