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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | 3x 3x 3x 3x 3x 3x 3x 134x 134x 134x 134x 134x 444x 144x 90x 48x 48x 12x 48x 48x 17x 17x 17x 51x 48x 144x 48x 144x 144x 163x 10x 10x 11x 11x 11x 10x 5x 5x 5x 15x 5x 5x 5x 12x 4x 4x 16x 16x 5x 3x | /**
* Entity-specific roles auto-created for a restricted entity (UC-RBAC-008.1).
*
* Role ids are derived from the entity id, so re-restricting an entity never
* duplicates them: only a role deleted meanwhile is written again.
*/
const { createHash } = require('crypto')
const { QueryCommand, PutCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const { normalizeName } = require('./nameUniqueness')
// Every language the UI supports (flows-ui's SUPPORTED_UI_LANGUAGES) — a role
// name missing one would fall back to English there.
const ROLE_NAME_LANGUAGES = ['en', 'fr', 'es']
const READER_PERMISSIONS = ['read', 'items:list', 'items:read']
const CONTRIBUTOR_PERMISSIONS = [
...READER_PERMISSIONS,
'items:create',
'items:update',
'items:delete'
]
const ROLE_TIERS = [
{
tier: 'reader',
label: { en: 'Reader', fr: 'Lecteur', es: 'Lector' },
description: {
en: 'Read the restricted entity "{name}" and its items',
fr: 'Lire l’entité restreinte « {name} » et ses items',
es: 'Leer la entidad restringida «{name}» y sus elementos'
},
actions: READER_PERMISSIONS
},
{
tier: 'contributor',
label: { en: 'Contributor', fr: 'Contributeur', es: 'Colaborador' },
description: {
en: 'Read, create, edit and delete the items of the restricted entity "{name}"',
fr: 'Lire, créer, modifier et supprimer les items de l’entité restreinte « {name} »',
es: 'Leer, crear, editar y eliminar los elementos de la entidad restringida «{name}»'
},
actions: CONTRIBUTOR_PERMISSIONS
},
{
tier: 'manager',
label: { en: 'Manager', fr: 'Gestionnaire', es: 'Gestor' },
description: {
en: 'Full control of the restricted entity "{name}", its schema and its items',
fr: 'Contrôle total de l’entité restreinte « {name} », de son schéma et de ses items',
es: 'Control total de la entidad restringida «{name}», su esquema y sus elementos'
},
actions: ['*']
}
]
/**
* A role id derived from the entity id and tier, formatted as a name-based
* (version 5 style) UUID: stable so re-restricting never duplicates a role,
* and a UUID because API Gateway validates `roleIds` as `format: uuid`
* (role assignment, invitations, API keys) — randomUUID() can't be used here.
*/
function restrictedEntityRoleId(entityId, tier) {
const bytes = createHash('sha1').update(`restricted-entity-role:${entityId}:${tier}`).digest()
bytes[6] = (bytes[6] & 0x0f) | 0x50 // version 5
bytes[8] = (bytes[8] & 0x3f) | 0x80 // RFC 4122 variant
const hex = bytes.subarray(0, 16).toString('hex')
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
}
function perLanguage(translate) {
return Object.fromEntries(ROLE_NAME_LANGUAGES.map((language) => [language, translate(language)]))
}
function localizedEntityName(name, language) {
if (typeof name === 'string') return name
return name?.[language] || name?.en || Object.values(name || {})[0] || ''
}
/**
* First name in `{base}`, `{base} (2)`, `{base} (3)`… not taken in the flow —
* compared the way findRoleNameConflict compares (English, case-insensitive).
*/
function uniqueRoleName(baseName, takenNames) {
let candidate = baseName
for (let suffix = 2; takenNames.has(normalizeName(candidate)); suffix++) {
candidate = perLanguage((language) => `${baseName[language]} (${suffix})`)
}
takenNames.add(normalizeName(candidate))
return candidate
}
/**
* The role records missing for `entity`, given the flow's current roles.
* @param {{ entity: { id: string, name: unknown }, flowId: string, existingRoles: object[],
* createdBy: string, now: string }} params
* @returns {object[]} RolesTable items to write
*/
function buildMissingRestrictedEntityRoles({ entity, flowId, existingRoles, createdBy, now }) {
const existingRoleIds = new Set(existingRoles.map((role) => role.roleId))
const takenNames = new Set(existingRoles.map((role) => normalizeName(role.name)))
return ROLE_TIERS.filter(
({ tier }) => !existingRoleIds.has(restrictedEntityRoleId(entity.id, tier))
).map(({ tier, label, description, actions }) => {
const roleId = restrictedEntityRoleId(entity.id, tier)
const entityName = perLanguage((language) => localizedEntityName(entity.name, language))
return {
PK: `FLOW#${flowId}`,
SK: `ROLE#${roleId}`,
flowId,
roleId,
name: uniqueRoleName(
perLanguage((language) => `${entityName[language]} — ${label[language]}`),
takenNames
),
description: perLanguage((language) =>
description[language].replace('{name}', entityName[language])
),
permissions: actions.map((action) => `entities-${entity.id}:${action}`),
isSystemRole: false,
createdBy,
createdAt: now,
updatedAt: now
}
})
}
async function listFlowRoles(docClient, rolesTableName, flowId) {
const roles = []
let ExclusiveStartKey
do {
const result = await docClient.send(
new QueryCommand({
TableName: rolesTableName,
KeyConditionExpression: 'PK = :pk AND begins_with(SK, :sk)',
ExpressionAttributeValues: { ':pk': `FLOW#${flowId}`, ':sk': 'ROLE#' },
ExclusiveStartKey
})
)
roles.push(...(result.Items || []))
ExclusiveStartKey = result.LastEvaluatedKey
} while (ExclusiveStartKey)
return roles
}
/**
* TransactWrite items creating the roles of a brand-new restricted entity and
* assigning its Manager role to the creator — appended to the entity's own
* Put so all of it lands atomically (UC-RBAC-008.1 AC-3).
*/
async function buildRestrictedEntityCreationWrites({
docClient,
rolesTableName,
membershipsTableName,
flowId,
entity,
userId,
now
}) {
const existingRoles = await listFlowRoles(docClient, rolesTableName, flowId)
const roles = buildMissingRestrictedEntityRoles({
entity,
flowId,
existingRoles,
createdBy: userId,
now
})
return [
...roles.map((role) => ({
Put: {
TableName: rolesTableName,
Item: role,
ConditionExpression: 'attribute_not_exists(PK)'
}
})),
{
Update: {
TableName: membershipsTableName,
Key: { userId, flowId },
UpdateExpression:
'SET roleIds = list_append(if_not_exists(roleIds, :empty), :managerRoleIds), updatedAt = :now',
ConditionExpression: 'attribute_exists(userId)',
ExpressionAttributeValues: {
':empty': [],
':managerRoleIds': [restrictedEntityRoleId(entity.id, 'manager')],
':now': now
}
}
}
]
}
/**
* For an existing entity switched to restricted: writes whichever of its roles
* are missing and assigns its Manager role to `userId` unless already held.
* Each write is conditional and idempotent, so a concurrent identical switch
* never fails nor duplicates anything.
*/
async function ensureRestrictedEntityRoles({
docClient,
rolesTableName,
membershipsTableName,
flowId,
entity,
userId,
now
}) {
const existingRoles = await listFlowRoles(docClient, rolesTableName, flowId)
const roles = buildMissingRestrictedEntityRoles({
entity,
flowId,
existingRoles,
createdBy: userId,
now
})
for (const role of roles) {
await ignoreConditionalCheckFailure(
docClient.send(
new PutCommand({
TableName: rolesTableName,
Item: role,
ConditionExpression: 'attribute_not_exists(PK)'
})
)
)
}
const managerRoleId = restrictedEntityRoleId(entity.id, 'manager')
await ignoreConditionalCheckFailure(
docClient.send(
new UpdateCommand({
TableName: membershipsTableName,
Key: { userId, flowId },
UpdateExpression:
'SET roleIds = list_append(if_not_exists(roleIds, :empty), :managerRoleIds), updatedAt = :now',
// No membership row is ever created here, and the role is never listed twice.
ConditionExpression: 'attribute_exists(userId) AND NOT contains(roleIds, :managerRoleId)',
ExpressionAttributeValues: {
':empty': [],
':managerRoleIds': [managerRoleId],
':managerRoleId': managerRoleId,
':now': now
}
})
)
)
}
async function ignoreConditionalCheckFailure(promise) {
try {
await promise
} catch (error) {
if (error.name !== 'ConditionalCheckFailedException') throw error
}
}
module.exports = {
ROLE_TIERS,
restrictedEntityRoleId,
buildMissingRestrictedEntityRoles,
buildRestrictedEntityCreationWrites,
ensureRestrictedEntityRoles
}
|