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

28.26% Statements 13/46
100% Branches 1/1
0% Functions 0/1
28.26% Lines 13/46

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 471x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x                                                                   10x  
import {type IMeta} from '@feasibleone/blong';
 
import {handler} from './handlerGroup.ts';
 
type KnexQb = any;
 
/**
 * `access.capability.remove` — delete a capability, its graph edges and its
 * resource row.
 */
export default handler(({lib: {binHex, listEdgeObjectIds}}) => ({
    async accessCapabilityRemove(
        params: {capabilityId?: string},
        $meta: IMeta,
    ): Promise<{success: boolean}> {
        const qb: KnexQb = this.config?.context?.queryBuilder;
        if (!qb) throw new Error('Database not available');
        const hex = binHex(params.capabilityId);
        if (!hex) return {success: true};
        const buf = Buffer.from(hex, 'hex');
        const actionIds = await listEdgeObjectIds(qb, hex, 'hasAction');
        // One transaction, one rebuild at the end of it.  The old shape rebuilt the
        // paths after removing the `hasAction` edges and then removed the
        // granted-to-role `hasCapability` edges, so those grants stayed in every
        // caller's paths until some later rebuild happened — and nothing recorded
        // that they were stale.  The rebuild also has to precede the
        // `core_resource` delete, because `core_path` holds a foreign key to it.
        await qb.transaction(async (trx: KnexQb) => {
            if (actionIds.length) {
                await trx('core_triple')
                    .where('subjectId', buf)
                    .where('predicateName', 'hasAction')
                    .del();
            }
            // A capability can be granted to roles — remove those edges too.
            await trx('core_triple')
                .where('objectId', buf)
                .where('predicateName', 'hasCapability')
                .del();
            await trx('access_capability').where('capabilityId', buf).del();
            await trx.raw('CALL access_pathRefresh()');
            await trx('core_resource').where('resourceId', buf).del();
        });
        return {success: true};
    },
}));