All files / utils permissionFormat.js

100% Statements 7/7
100% Branches 4/4
100% Functions 3/3
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44                                        3x     96x               49x   34x 4x       3x          
/**
 * Validates the *shape* of a permission string, independent of privilege escalation
 * checks (see validateRolePermissions.js) and of whether the permission actually
 * matches anything at runtime. Mirrors the grammar documented in
 * docs/architecture/requirements/rbac.req.md ("Permission string format"):
 *
 *   - `*:*`                                — the untyped global admin wildcard
 *   - `{resource}:{verb}`                  — collection-level or flat-shorthand
 *                                             (e.g. `entities:list`, `items:read`)
 *   - `entities-{id|*}:{verb}`             — resource-scoped
 *   - `entities-{id|*}:items:{verb}`       — sub-resource, scoped to its parent id
 *   - `entities-{id|*}:items:transition:{fieldId}:{from}:{to}`
 *                                           — one protected workflow transition
 *                                             (ids may contain `_` and uppercase)
 *
 * `{resource}`/`{verb}` are lowercase words or `*`; `{id}` is a lowercase
 * alphanumeric/dash id (matching the `randomUUID()` ids entities are created with)
 * or `*` for "any entity".
 */
const PERMISSION_FORMAT_REGEX =
  /^\*:\*$|^[a-z]+:(\*|[a-z]+)$|^entities-(\*|[a-z0-9-]+):(\*|[a-z]+)$|^entities-(\*|[a-z0-9-]+):items:(\*|[a-z]+)$|^entities-(\*|[a-z0-9-]+):items:transition:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+$/
 
function isValidPermissionFormat(permission) {
  return typeof permission === 'string' && PERMISSION_FORMAT_REGEX.test(permission)
}
 
/**
 * @param {string[]} permissions
 * @throws {Error} listing every malformed permission, if any
 */
function validatePermissionFormat(permissions) {
  const invalid = permissions.filter((permission) => !isValidPermissionFormat(permission))
 
  if (invalid.length > 0) {
    throw new Error(`Invalid permission format: ${invalid.join(', ')}`)
  }
}
 
module.exports = {
  PERMISSION_FORMAT_REGEX,
  isValidPermissionFormat,
  validatePermissionFormat
}