Skip to content

Permissions (CASL) ​

Luna's permission system utilises CASL to define roles/permissions.

Roles ​

Roles are managed via an authenticated endpoint on the auth service - PUT /user-roles/{userRoleId} (updateUserRole) - which reads and writes individual role rows directly in the {env}-user-roles-table. The endpoint is itself guarded by checkPermissions on the UserRoles subject, so only users with permission to update roles can call it.

A role has the below structure:

{
  "roleName": "PeopleLead",
  "type": "role",
  "permissions": []
}

Roles are assigned to an ANDi in the {env}-andis-table via the roles attribute, which is an array - one ANDi can have multiple roles.

When using the lower environments - you will need to assign roles to an ANDi in the development-andis-table - this is because the auth for the lower environments uses this table to generate the JWT tokens. This is only for assigning roles to an ANDi - the actual role + permission(s) need to exist in the lower environment's {env}-user-roles-table (via the updateUserRole endpoint)


Permissions ​

Permissions are subject based, and can be stacked together to create multiple permissions for one subject.

Permissions have the below properties:

PropertyTypeRequiredDescription
actionstringYesThe CRUD operation you are allowing
subjectstringYesThe subject/item you are allowing the action for
fieldsarrayNoLimit the action to certain fields. If left empty will grant access to all possible fields.
conditionsobjectNoOnly apply this permission when the specified conditions are met.
invertedbooleanNoIf true, this disallows the action from being taken on the subject.

Examples ​

This would give the user permission to read all data for any Andi:

{
  action: 'read',
  subject: 'Andi'
}

This would give the user permission to read any Andi, but only firstName or email would be allowed.

{
  action: 'read',
  subject: 'Andi',
  fields: [
    'firstName',
    'email'
  ]
}

This would give the user permission to read any Andi where their businessUnit is "Club Newton"

{
  action: 'read',
  subject: 'Andi',
  conditions: {
    businessUnit: 'Club Newton'
  }
}

These two permissions combined would give the user permission to read any Andi's firstName, but not their lastName IF the Andi's level is 3 or above.

[
  {
    action: 'read',
    subject: 'Andi',
    fields: [
      'firstName',
    ]
  },
  {
    action: 'read',
    subject: 'Andi',
    conditions: {
      level: { '$gte': 3 }
    }
    inverted: true,
  }
]

Conditions ​

Conditions follow the MongoDB query syntax - CASL provides a list of supported operators within conditions.

If multiple properties are specified under the conditions property, both conditions need to be met in order for the permission to allow the action.

If you need to have logic where condition X OR condition Y is met, you need to create two permission items. For example, with the below permissions, they would allow an Andi to be updated as long as the Andi's businessUnit is "Club Newton" OR their jobTitle contains "Developer":

[
  {
    action: 'update',
    subject: 'Andi',
    conditions: {
      businessUnit: 'Club Newton'
    }
  },
  {
    action: 'update',
    subject: 'Andi',
    conditions: {
      jobTitle: { '$in': 'Developer' }
    }
  }
]

Within conditions, you can also access properties of the logged in user's identity, using $_identity as a variable inside string(s), along with a $ as the last character of the string.

For example, the below permission will allow birthday to be read when the Andi's lineManager's ID matches the logged in user's ID - if the logged in user is the Andi's line manager:

{
  action: 'read',
  subject: 'Andi',
  fields: [
    'birthday'
  ],
  conditions: {
    'lineManager.id': '$_identity.userID$',
  }
}

Only the roles held by the identity are interpolated. If a permission references an identity property the user doesn't have, only that permission is affected and a warning is logged - the rest of the user's permissions are still returned. A regular permission is dropped. An inverted permission is kept as an unconditional deny (its conditions are removed) so a restriction is never lost.


Restricting Access ​

Once the permissions are set up, they will automatically be included during the auth process, and saved within the user's id_token JWT token, that is available in the frontend and is passed to backend in every request.

CASL provides a plugin that uses the .can syntax, this returns a true/false value to say whether or not the permissions are available for the desired action. CASL also provides .cannot for checking the reverse.

Can takes 3 properties: action, subject and field - similar to permissions above. field is optional and can only be 1 field to check against for each .can().

For example, the below checks that the user can read the andi's personal field.

user.can('read', subjectCreator('Andi', andi), 'personal')

CASL requires the use of subjectCreator for non class objects, to set the subject name (which should match the permission subject).

In the example above, if there was a permission with conditions, it would check that the andi being passed into the subjectCreator meets those conditions.

Both the front and backend have a helper function for checking permissions - checkPermissions - both work by passing in the logged in user, an array of permissions to check and optionally an item to run the permissions against.

The array of permissions to pass in should be the action that you want to check is allowed, such as the below example, which would check that the user has the permission to update any Andi for both firstName and lastName fields:

const REQUEST_ACTIONS = [
  {
    action: 'update',
    subject: 'Andi',
    fields: [
      'firstName',
      'lastName'
    ],
  },
];

await checkPermissions(identity, REQUEST_ACTIONS);

If the third argument was passed in, this would check that the user has the permission to update the specified Andi, still checking both firstName and lastName fields:

await checkPermissions(identity, REQUEST_ACTIONS, andi);

It's important to note that when you pass in the third argument, that item needs to contain all fields where there may be conditions to check against. If you only get a subset of attributes for the item, but the conditions require an attribute that doesn't exist - you will always get a false result.

Frontend implementation ​

In the frontend, user can be obtained via the AbilityContext:

import {
  AbilityContext,
  checkPermissions,
  SubjectCreator
} from '@src/utils/auth';

const user = useContext(AbilityContext);

checkPermissions() will return true/false in the frontend.

Backend implementation ​

In the backend, identity is obtained by calling authoriseRequest with the incoming event, and is then passed into checkPermissions:

import {
  authoriseRequest,
  checkPermissions,
  subjectCreator,
} from '@bhag-business-platform/luna-auth';

const identity = await authoriseRequest(event, publicKeyAlias);
const user = await checkPermissions(identity, REQUEST_ACTIONS);

checkPermissions() will throw a 403 - Forbidden error in the backend if the identity doesn't have the desired permissions.

Made with ❤️ by the Luna team