Skip to main content

Securing distributed locks

Distributed locks manage access to shared resources to transact data in order. The @secureDistributedLock decorator secures locks.

Distributed locks resolve race conditions by locking access to shared resources to a single client at a time. By default, clients are denied access to distributed locks. Use the @secureDistributedLock() decorator in the SquidService class in the Squid backend to authorize client access to the lock.

To allow all clients access to lock any distributed lock, use a security function with the following format:

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

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

When a client tries to use a distributed lock, the mutex value they are using is passed to the Squid backend in the DistributedLockContext. The following security function shows how you could secure the lock based on mutex value where the allUsers mutex is available to all authenticated users, and the admin mutex is available only to users with the admin attribute in their auth token:

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
}

To view an example of an app that uses a distributed lock, check out this blog post.