All files / realm/blong-access/adapter/db accessAuthorizationMerge.ts

99.27% Statements 411/414
58.18% Branches 32/55
100% Functions 2/2
99.27% Lines 411/414

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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 4151x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 22x 109x 109x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 109x 22x 35x 35x 35x 20x 151x 151x 151x 151x 151x 151x 151x 151x 151x 313x 313x 313x 313x 313x 313x 313x 313x 313x 313x 313x 313x 313x 313x 313x 313x 151x 20x 35x 35x 35x 11x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 60x 60x 60x 60x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 11x 35x 35x 35x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 35x 35x 35x 35x 35x 35x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x   18x 18x 18x 18x 18x 18x 18x 35x 35x 35x 35x 35x 35x 15x 15x 15x 15x 30x 15x 15x 15x 15x 15x 30x 15x 35x 35x 35x 35x 35x 35x 35x 35x 35x 13x 22x 22x 22x 22x 22x   22x 22x 22x 22x 22x 14x 14x 14x 14x 14x 14x 8x 8x 8x 8x 8x   8x 22x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 22x 13x 35x 35x 35x 10x 1x  
import {handler} from './handlerGroup.ts';
 
import {type EnsuredRole} from './accessModel.ts';
import {type CredentialParams} from './password.ts';
 
type KnexQb = any;
 
/**
 * The sentinel graph node a wildcard ACL rule (`targetKind: 'all'`) is anchored
 * on — it stands for "every record" and gives the rule a real resource to point
 * at, so the FK and the ACL Rules page stay uniform.
 */
const ANY_TARGET_TYPE = 'access.any';
const ANY_TARGET_NAME = '(all records)';
 
/**
 * Resolve an existing graph node by its display name + type — seeds never
 * create the principals or targets they reference.
 */
async function resourceByName(qb: KnexQb, name: string, typeAlias: string): Promise<string> {
    const row = (await qb('core_resource as r')
        .join('core_type as t', 't.typeId', 'r.typeId')
        .where('t.typeAlias', typeAlias)
        .where('r.resourceName', name)
        .first('r.resourceId')) as {resourceId: Buffer} | undefined;
    if (!row) throw new Error(`Seed references an unknown ${typeAlias} named "${name}"`);
    // Dashed UUID from the binary column — the group library's `bufToUuid`, spelled
    // out because this helper runs outside the handler factory.
    return row.resourceId
        .toString('hex')
        .replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');
}
 
export default handler(
    ({
        handler: {'db/accessRoleEnsure': accessRoleEnsure},
        lib: {
            SHORT_TYPE_ALIASES,
            credentialPolicyParams,
            crockfordDecode,
            hashPassword,
            newUuid,
            splitNames,
            ulid,
            uuidBuf,
        },
    }) => ({
        async accessAuthorizationMerge(
            params: {
                /**
                 * A **test** seed declares the *complete* list for the capabilities and users it
                 * names: the edges those subjects hold for the predicate this call writes are
                 * retracted first, so shortening a list in the file takes effect (F-357).
                 *
                 * `core.triple.merge` is additive on purpose — `onConflict ignore` makes replaying
                 * a production seed a no-op, and no seed may delete another realm's contribution.
                 * Roles stay additive even here: a shared role's capability list is a union that
                 * several files contribute to, and the graph carries no marker saying which
                 * contribution is this file's.
                 */
                replace?: boolean;
                user?: Record<
                    string,
                    {
                        password?: string;
                        credentialSalt?: string;
                        /** Display email persisted on the access_user row. */
                        emailAddress?: string | null;
                        isActive?: boolean;
                        roles?: string;
                    }
                >;
                role?: Record<string, string>;
                capability?: Record<string, string>;
                policy?: Record<
                    string,
                    {
                        credentialType: string;
                        minLength?: number;
                        requireSpecialChar?: boolean;
                        requireNumber?: boolean;
                        requireUppercase?: boolean;
                        maxAgeDays?: number;
                        maxAttempts?: number;
                        /** Credential-function parameters (JSON) the policy dictates for this type. */
                        credentialParams?: Partial<CredentialParams>;
                        isActive?: boolean;
                    }
                >;
                /**
                 * Implicit ACL grants: `<principal> --hasScope--> <scope>`.  The
                 * principal and the scope must exist (resolve them in the same
                 * file — the handler's earlier blocks run first).
                 */
                scope?: Array<{
                    role?: string;
                    user?: string;
                    /** Scope name (unit / organization / …). */
                    scope: string;
                    /** Short type of the scope (`unit`, `organization`, …) or a full `typeAlias`. */
                    scopeType?: string;
                }>;
                /**
                 * Record-level (ACL) rules.  Principals and targets are resolved
                 * against the graph (the ACL never creates principals or targets
                 * — only actions, like any other action resource), except the
                 * wildcard target `'*'`, which is anchored on the shared
                 * `access.any` sentinel node.
                 */
                acl?: Array<{
                    /** Principal name (user / role / unit / capability). */
                    principal: string;
                    /** Short type of the principal: `user`, `role`, `unit`, `capability` — or a full `typeAlias`. */
                    principalType?: string;
                    /** Action resource name, e.g. `accessUserEdit`. */
                    action?: string;
                    /** Comma or newline separated action names — each gets its own rule. */
                    actions?: string;
                    /** Target name — a record or a scope per `targetKind`; `'*'` means every record. */
                    target: string;
                    /** Short type of the target (`unit`, `organization`, `person`, `role`, …) or a full `typeAlias`. */
                    targetType?: string;
                    /** `record` (default), `scope`, or `all` (the wildcard target). */
                    targetKind?: string;
                    /** `allow` (default) or `deny` — a deny beats a grant for a record in a scope. */
                    effect?: string;
                }>;
            },
            $meta: Record<string, unknown>,
        ): Promise<{success: boolean; message?: string}> {
            const qb: KnexQb = this.config?.context?.queryBuilder;
            if (!qb) throw new Error('Database not available');
 
            // Graph edges are batched and written via the shared `core.triple.merge`
            // helper (P3), which also refreshes `access_path` once at the end.
            const triples: Array<{
                subjectId: string;
                predicateName: string;
                objectId: string;
            }> = [];
            // The subjects this call declares, per predicate — the ones `replace` may retract the
            // edges of: a capability's action list and a user's role list are a seed's own rows.
            const declaredCapabilities = new Set<string>();
            const declaredUsers = new Set<string>();
 
            // 1. Process capabilities and their actions first
            if (params.capability) {
                for (const [capabilityName, actionList] of Object.entries(params.capability)) {
                    const actionNames = splitNames(actionList);
                    for (const actionName of actionNames) {
                        const {resourceId: actionId} = (await super.coreResourceEnsure(
                            {
                                name: actionName,
                                typeAlias: 'access.action',
                                table: 'access_action',
                                extraColumns: {description: `${actionName} action`},
                                keyName: 'actionId',
                            },
                            $meta,
                        )) as {resourceId: string};
                        const {resourceId: capabilityId} = (await super.coreResourceEnsure(
                            {
                                name: capabilityName,
                                typeAlias: 'access.capability',
                                table: 'access_capability',
                                extraColumns: {description: `${capabilityName} capability`},
                                keyName: 'capabilityId',
                            },
                            $meta,
                        )) as {resourceId: string};
                        declaredCapabilities.add(capabilityId);
                        triples.push({
                            subjectId: capabilityId,
                            predicateName: 'hasAction',
                            objectId: actionId,
                        });
                    }
                }
            }
 
            // 2. Process roles and their capabilities
            if (params.role) {
                for (const [roleName, capabilityList] of Object.entries(params.role)) {
                    const capabilityNames = splitNames(capabilityList);
                    // A role the merge names must exist: `access.role.ensure`
                    // allocates the bit when the role is new (it used to be
                    // hardcoded to 0 and silently skipped instead).
                    const {role: ensuredRole} = await accessRoleEnsure<EnsuredRole>(
                        {role: {roleName}},
                        $meta,
                    );
                    for (const capabilityName of capabilityNames) {
                        const {resourceId: capabilityId} = (await super.coreResourceEnsure(
                            {
                                name: capabilityName,
                                typeAlias: 'access.capability',
                                table: 'access_capability',
                                extraColumns: {description: `${capabilityName} capability`},
                                keyName: 'capabilityId',
                            },
                            $meta,
                        )) as {resourceId: string};
                        triples.push({
                            subjectId: ensuredRole.roleId,
                            predicateName: 'hasCapability',
                            objectId: capabilityId,
                        });
                    }
                }
            }
 
            // 3. Process users with credentials and role assignments
            if (params.user) {
                for (const [userName, userDef] of Object.entries(params.user)) {
                    const {resourceId: userId} = (await super.coreResourceEnsure(
                        {
                            name: userName,
                            typeAlias: 'access.user',
                            table: 'access_user',
                            extraColumns: {isActive: userDef.isActive ?? 1},
                            keyName: 'userId',
                        },
                        $meta,
                    )) as {resourceId: string};
                    // A user's role list is this file's to declare (`replace`).
                    declaredUsers.add(userId);
 
                    // Persist the display email even when the user already
                    // exists (coreResourceEnsure is insert-only on conflict), so
                    // seeds stay idempotent and the profile page shows a stable
                    // email across restarts.
                    if (userDef.emailAddress !== undefined) {
                        await qb('access_user')
                            .where('userId', uuidBuf(userId))
                            .update({emailAddress: userDef.emailAddress});
                    }
 
                    // Create credential if password is provided
                    if (userDef.password) {
                        const salt = userDef.credentialSalt ?? newUuid();
                        // Credential params come from the active policy; config.password is the fallback.
                        const policyParams = await credentialPolicyParams(qb, 'password');
                        const {hash, params: credentialParams} = hashPassword(
                            userDef.password,
                            salt,
                            policyParams,
                        );
                        await qb('access_credential')
                            .insert({
                                userId: uuidBuf(userId),
                                credentialType: 'password',
                                credentialHash: hash,
                                credentialSalt: salt,
                                // `*JSON` column — the knex adapter stores this object as JSON.
                                credentialParamsJSON: credentialParams,
                                isActive: userDef.isActive ?? 1,
                            })
                            .onConflict()
                            .ignore();
                    }
 
                    // Assign roles
                    if (userDef.roles) {
                        const roleNames = splitNames(userDef.roles);
                        for (const roleName of roleNames) {
                            const {role: ensuredRole} = await accessRoleEnsure<EnsuredRole>(
                                {role: {roleName}},
                                $meta,
                            );
                            triples.push({
                                subjectId: userId,
                                predicateName: 'hasRole',
                                objectId: ensuredRole.roleId,
                            });
                        }
                    }
                }
            }
 
            // 4. Process credential policies (password hashing params etc.)
            if (params.policy) {
                for (const [policyName, policyDef] of Object.entries(params.policy)) {
                    (await super.coreResourceEnsure(
                        {
                            name: policyName,
                            typeAlias: 'access.policy',
                            table: 'access_policy',
                            extraColumns: {
                                credentialType: policyDef.credentialType,
                                minLength: policyDef.minLength ?? null,
                                requireSpecialChar: policyDef.requireSpecialChar ?? null,
                                requireNumber: policyDef.requireNumber ?? null,
                                requireUppercase: policyDef.requireUppercase ?? null,
                                maxAgeDays: policyDef.maxAgeDays ?? null,
                                maxAttempts: policyDef.maxAttempts ?? null,
                                // `*JSON` column — the knex adapter stores this object as JSON.
                                credentialParamsJSON: policyDef.credentialParams ?? null,
                                isActive: policyDef.isActive ?? 1,
                            },
                            keyName: 'policyId',
                        },
                        $meta,
                    )) as {resourceId: string};
                }
            }
 
            // 4b. Implicit ACL grants: `<principal> --hasScope--> <scope>`.  The
            //     grant covers every action the principal holds and every record
            //     linked to the scope (including, through `isPartOf`, the records
            //     of its descendant scopes).
            for (const grant of params.scope ?? []) {
                const principal = grant.role ?? grant.user;
                if (!principal) continue;
                const principalId = await resourceByName(
                    qb,
                    principal,
                    grant.role ? 'access.role' : 'access.user',
                );
                const scopeId = await resourceByName(
                    qb,
                    grant.scope,
                    SHORT_TYPE_ALIASES[grant.scopeType ?? 'unit'] ??
                        grant.scopeType ??
                        'party.unit',
                );
                triples.push({
                    subjectId: principalId,
                    predicateName: 'hasScope',
                    objectId: scopeId,
                });
            }
 
            // 4c. Retract what a replacing test seed dropped: the edges the declared capabilities
            //     and users hold for the predicate this call writes (F-357).  The merge below counts
            //     itself in the durable generation, so the deferred `access_path` rebuild sees the
            //     retraction too — a dropped action stops authorizing.
            if (params.replace) {
                for (const [predicateName, ids] of [
                    ['hasAction', declaredCapabilities],
                    ['hasRole', declaredUsers],
                ] as Array<[string, Set<string>]>) {
                    if (ids.size) {
                        await qb('core_triple')
                            .where('predicateName', predicateName)
                            .whereIn('subjectId', [...ids].map(uuidBuf))
                            .delete();
                    }
                }
            }
 
            // 5. Write graph edges + refresh materialized paths via the shared
            //    `core.triple.merge` helper (P3).
            await super.coreTripleMerge({triples, refreshPath: true}, $meta);
            // 6. Record-level ACL rules.  Principals and targets are looked up
            //    (never created, except the wildcard sentinel below); the action is
            //    ensured like the RBAC steps above, so a seed may reference an
            //    action the same file grants.
            if (params.acl?.length) {
                for (const rule of params.acl) {
                    const principalId = await resourceByName(
                        qb,
                        rule.principal,
                        SHORT_TYPE_ALIASES[rule.principalType ?? 'role'] ??
                            rule.principalType ??
                            'access.role',
                    );
                    // `target: '*'` grants on *every* record: the rule still needs
                    // an anchor resource, which the shared `access.any` node is.
                    const wildcard = rule.targetKind === 'all' || rule.target === '*';
                    const targetId = wildcard
                        ? (
                              (await super.coreResourceEnsure(
                                  {name: ANY_TARGET_NAME, typeAlias: ANY_TARGET_TYPE},
                                  $meta,
                              )) as {resourceId: string}
                          ).resourceId
                        : await resourceByName(
                              qb,
                              rule.target,
                              SHORT_TYPE_ALIASES[rule.targetType ?? 'unit'] ??
                                  rule.targetType ??
                                  'party.unit',
                          );
                    for (const actionName of splitNames(rule.actions ?? rule.action ?? '')) {
                        const {resourceId: actionId} = (await super.coreResourceEnsure(
                            {
                                name: actionName,
                                typeAlias: 'access.action',
                                table: 'access_action',
                                extraColumns: {description: `${actionName} action`},
                                keyName: 'actionId',
                            },
                            $meta,
                        )) as {resourceId: string};
                        await qb('access_acl')
                            .insert({
                                aclId: Buffer.from(crockfordDecode(ulid())),
                                principalId: uuidBuf(principalId),
                                actionId: uuidBuf(actionId),
                                targetId: uuidBuf(targetId),
                                targetKind: wildcard ? 'all' : (rule.targetKind ?? 'record'),
                                effect: rule.effect ?? 'allow',
                                isActive: 1,
                            })
                            .onConflict()
                            .ignore();
                    }
                }
            }
 
            return {success: true};
        },
    }),
);