メインコンテンツまでスキップ

分散ロックのセキュリティ保護

分散ロックは、共有リソースへのアクセスを管理し、データを順序どおりにトランザクション処理できるようにします。@secureDistributedLock デコレータはロックをセキュリティ保護します。

分散ロックは、共有リソースへのアクセスを一度に1つのクライアントに限定してロックすることで、レースコンディションを解消します。デフォルトでは、クライアントは分散ロックへのアクセスを拒否されます。ロックへのクライアントアクセスを許可するには、Squid backend の SquidService クラスで @secureDistributedLock() デコレータを使用します。

すべてのクライアントに対して、任意の分散ロックをロックできるアクセス権を付与するには、次の形式のセキュリティ関数を使用します。

Backend code
import { secureDistributedLock, SquidService } from '@squidcloud/backend';

@secureDistributedLock()
allowAllAccessToAcquiringLock(): boolean {
return true;
}

クライアントが分散ロックを使用しようとすると、使用している mutex 値が DistributedLockContext 内で Squid backend に渡されます。次のセキュリティ関数は、mutex 値に基づいてロックを保護する方法を示しています。ここでは、allUsers mutex は認証済みユーザー全員が利用でき、admin mutex は auth token に admin 属性を持つユーザーのみが利用できます。

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
}

分散ロックを使用するアプリの例を見るには、このブログ記事 を参照してください。