A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
'use strict';
// `verifySpec`'s role check proved only that a role ROW exists carrying the SDK marker, never what
// it GRANTS. A role created with the wrong access — or one whose privilege write failed after the
// row landed — verified clean. This is a metadata read, not a runtime check.
const { test } = require('node:test');
const assert = require('node:assert');
const { declaredPrivileges, compareRolePrivileges, compileRolePrivileges, depthFromMask } = require('../lib/role-privileges.js');
const { verifySpec } = require('../lib/verify-spec.js');
// A realistic privilege set as EntityDefinitions returns it.
const privsFor = (entity, id) => [
{ Name: `prvRead${entity}`, PrivilegeId: `${id}-read`, PrivilegeType: 'Read' },
{ Name: `prvWrite${entity}`, PrivilegeId: `${id}-write`, PrivilegeType: 'Write' },
{ Name: `prvCreate${entity}`, PrivilegeId: `${id}-create`, PrivilegeType: 'Create' },
];
const persona = (over = {}) => ({
persona: 'Field Technician',
jobs: [{ name: 'Complete work orders', privileges: [{ entity: 'msdyn_workorder', access: ['read', 'write'], scope: 'businessUnit' }] }],
...over,
});
test('declaredPrivileges flattens jobs and folds in the appmodule read appAccess injects', () => {
const d = declaredPrivileges(persona());
assert.deepStrictEqual(d.sort((a, b) => `${a.entity}${a.access}`.localeCompare(`${b.entity}${b.access}`)), [
{ entity: 'appmodule', access: 'read', scope: 'organization' },
{ entity: 'msdyn_workorder', access: 'read', scope: 'businessUnit' },
{ entity: 'msdyn_workorder', access: 'write', scope: 'businessUnit' },
]);
});
test('appAccess:false drops the appmodule privilege (a data-only role)', () => {
assert.ok(!declaredPrivileges(persona({ appAccess: false })).some((d) => d.entity === 'appmodule'));
});
// Mirrors the builder's union rule, so the expectation matches what is actually written.
test('the MAX scope wins when several jobs declare the same entity+access', () => {
const p = persona({ jobs: [
{ name: 'a', privileges: [{ entity: 'account', access: ['read'], scope: 'user' }] },
{ name: 'b', privileges: [{ entity: 'account', access: ['read'], scope: 'organization' }] },
] });
const acct = declaredPrivileges(p).filter((d) => d.entity === 'account');
assert.deepStrictEqual(acct, [{ entity: 'account', access: 'read', scope: 'organization' }]);
});
test('additionalPrivileges are folded in like a job\'s privileges', () => {
const d = declaredPrivileges(persona({ additionalPrivileges: [{ entity: 'product', access: ['read'], scope: 'organization' }] }));
assert.ok(d.some((x) => x.entity === 'product' && x.access === 'read'));
});
// --- comparison ---------------------------------------------------------------------------------
const entityPrivs = () => new Map([['msdyn_workorder', privsFor('Workorder', 'wo')], ['appmodule', privsFor('AppModule', 'app')]]);
const heldAll = () => new Map([['wo-read', 'Local'], ['wo-write', 'Local'], ['app-read', 'Global']]);
test('a role holding every declared privilege at the declared depth passes', () => {
const r = compareRolePrivileges(declaredPrivileges(persona()), entityPrivs(), heldAll());
assert.deepStrictEqual(r, { ok: true, missing: [] });
});
// The structural version of the bug this catches. `appendTo` was keyed in ACCESS_TYPE with its
// camelCase App Spec spelling while the lookup lowercases, so it resolved to `undefined` and every
// declared appendTo privilege was reported as "the table exposes no such privilege" — a FALSE
// FAILURE on a correctly granted role, which is worse than no check at all.
//
// Driven from the validator's OWN allow-list rather than a hand-written list: any access token the
// App Spec starts accepting is covered automatically, so the next multi-word token cannot repeat
// this. A hand-listed test would have had to be remembered, and this one was not.
test('EVERY access token the App Spec accepts resolves through ACCESS_TYPE (casing included)', () => {
const { ACCESS_LEVELS } = require('../lib/app-spec.js');
const tokens = [...ACCESS_LEVELS];
assert.ok(tokens.length >= 8, `expected the full access-level set, got ${tokens.length}`);
// One table exposing one privilege per access token, with the PrivilegeType spelling Dataverse
// returns — which is the capitalized token, i.e. exactly what ACCESS_TYPE must map to.
const typeFor = (t) => t.charAt(0).toUpperCase() + t.slice(1);
const privileges = new Map([['msdyn_workorder', tokens.map((t) => ({ Name: `prv${typeFor(t)}Workorder`, PrivilegeId: `wo-${t.toLowerCase()}`, PrivilegeType: typeFor(t) }))]]);
const held = new Map(tokens.map((t) => [`wo-${t.toLowerCase()}`, 'Global']));
const declared = tokens.map((t) => ({ entity: 'msdyn_workorder', access: t, scope: 'organization' }));
const r = compareRolePrivileges(declared, privileges, held);
assert.deepStrictEqual(r, { ok: true, missing: [] },
`these tokens did not resolve: ${r.missing.map((m) => m.access).join(', ')}`);
});
// SUBSET semantics: a deeper grant satisfies a shallower declaration. Equality would false-fail on
// the builder's own max-scope union and on shared Dataverse privileges.
test('a DEEPER grant than declared still passes', () => {
const held = new Map([['wo-read', 'Global'], ['wo-write', 'Global'], ['app-read', 'Global']]);
assert.strictEqual(compareRolePrivileges(declaredPrivileges(persona()), entityPrivs(), held).ok, true);
});
test('extra privileges the spec never declared are NOT a finding', () => {
const held = heldAll();
held.set('some-other-privilege', 'Global');
assert.strictEqual(compareRolePrivileges(declaredPrivileges(persona()), entityPrivs(), held).ok, true);
});
// THE regression this check exists for.
test('a privilege the role does not hold is reported by name', () => {
const held = heldAll();
held.delete('wo-write');
const r = compareRolePrivileges(declaredPrivileges(persona()), entityPrivs(), held);
assert.strictEqual(r.ok, false);
assert.strictEqual(r.missing.length, 1);
assert.strictEqual(r.missing[0].access, 'write');
assert.match(r.missing[0].reason, /role does not hold prvWriteWorkorder/);
});
test('a privilege held at too SHALLOW a depth is reported with both depths', () => {
const held = heldAll();
held.set('wo-write', 'Basic'); // declared businessUnit => Local
const r = compareRolePrivileges(declaredPrivileges(persona()), entityPrivs(), held);
assert.strictEqual(r.ok, false);
assert.match(r.missing[0].reason, /at Basic, below the declared Local/);
});
// Fail closed: an unreadable table must not read as "nothing missing".
test('an entity whose privilege metadata could not be read is a finding, not a skip', () => {
const r = compareRolePrivileges(declaredPrivileges(persona()), new Map(), heldAll());
assert.strictEqual(r.ok, false);
assert.ok(r.missing.every((m) => /could not read privilege metadata/.test(m.reason)));
});
test('an access level the table does not expose is reported', () => {
const p = persona({ jobs: [{ name: 'a', privileges: [{ entity: 'msdyn_workorder', access: ['delete'] }] }], appAccess: false });
const r = compareRolePrivileges(declaredPrivileges(p), entityPrivs(), heldAll());
assert.strictEqual(r.ok, false);
assert.match(r.missing[0].reason, /exposes no 'delete' privilege/);
});
// --- verifySpec wiring --------------------------------------------------------------------------
const SDK_MARKER = 'Authored by @maker-studio/cds-maker-sdk (persona/security role).';
const specWith = (p) => ({ solution: { uniqueName: 'S' }, app: { name: 'A' }, entities: [], views: [], charts: [], forms: [], appShell: { areas: [] }, personas: [p] });
function readerWith({ rolePrivileges, entityPrivileges } = {}) {
const base = {
findTable: async () => null,
findColumns: async () => [],
sitemapXml: async () => '',
queryRecords: async (set) => {
if (set === 'businessunit') return [{ businessunitid: '11111111-1111-1111-1111-111111111111' }];
if (set === 'role') return [{ roleid: 'role-1', description: SDK_MARKER, ismanaged: false }];
return [];
},
};
if (rolePrivileges) base.rolePrivileges = rolePrivileges;
if (entityPrivileges) base.entityPrivileges = entityPrivileges;
return base;
}
// Reader-gated, exactly like entityRelationships / commandBar: an existence-only reader must behave
// as it did before this check existed.
test('verifySpec does NOT emit a role-privileges check when the reader lacks the methods', async () => {
const r = await verifySpec(specWith(persona()), readerWith());
assert.ok(r.checks.some((c) => c.kind === 'role'), 'the existing role check still runs');
assert.ok(!r.checks.some((c) => c.kind === 'role-privileges'), 'no privilege check without the readers');
});
test('verifySpec PASSES the privilege check when the role holds everything declared', async () => {
const r = await verifySpec(specWith(persona()), readerWith({
rolePrivileges: async () => [{ privilegeId: 'wo-read', depth: 'Local' }, { privilegeId: 'wo-write', depth: 'Local' }, { privilegeId: 'app-read', depth: 'Global' }],
entityPrivileges: async (e) => entityPrivs().get(e) || null,
}));
const c = r.checks.find((x) => x.kind === 'role-privileges');
assert.ok(c && c.present, JSON.stringify(c));
});
test('verifySpec FAILS when the role is missing a declared privilege', async () => {
const r = await verifySpec(specWith(persona()), readerWith({
rolePrivileges: async () => [{ privilegeId: 'wo-read', depth: 'Local' }, { privilegeId: 'app-read', depth: 'Global' }],
entityPrivileges: async (e) => entityPrivs().get(e) || null,
}));
const c = r.checks.find((x) => x.kind === 'role-privileges');
assert.ok(c && !c.present);
assert.match(c.detail, /msdyn_workorder\.write/);
assert.strictEqual(r.ok, false);
});
test('verifySpec fails CLOSED when the role privileges cannot be read', async () => {
const r = await verifySpec(specWith(persona()), readerWith({
rolePrivileges: async () => { throw new Error('429 throttled'); },
entityPrivileges: async (e) => entityPrivs().get(e) || null,
}));
const c = r.checks.find((x) => x.kind === 'role-privileges');
assert.ok(c && !c.present);
assert.match(c.detail, /could not read/);
});
// -- depthFromMask ----------------------------------------------------------------------------
// Review finding: privilegedepthmask is a BITMASK, not an enum. It can carry several bits at once,
// and an exact-match lookup mapped every combined value to '' -- which ranks 0, which made
// compareRolePrivileges report a CORRECTLY configured role as missing or too shallow.
test('depthFromMask: single bits map to their depth', () => {
assert.strictEqual(depthFromMask(1), 'Basic');
assert.strictEqual(depthFromMask(2), 'Local');
assert.strictEqual(depthFromMask(4), 'Deep');
assert.strictEqual(depthFromMask(8), 'Global');
});
test('depthFromMask: COMBINED masks resolve to the highest bit, not to empty', () => {
// Depth is cumulative -- a role granted Global can also do everything Basic allows -- so the
// effective depth is the deepest bit present.
assert.strictEqual(depthFromMask(3), 'Local'); // Basic|Local
assert.strictEqual(depthFromMask(7), 'Deep'); // Basic|Local|Deep
assert.strictEqual(depthFromMask(15), 'Global'); // all four
assert.strictEqual(depthFromMask(12), 'Global'); // Deep|Global
assert.strictEqual(depthFromMask(6), 'Deep'); // Local|Deep
});
test('depthFromMask: a combined mask satisfies a declared scope instead of false-failing', () => {
// The end-to-end point of the fix: a role holding mask 15 must satisfy a declared organization
// scope. Before, it decoded to '' and was reported as too shallow.
const declared = [{ entity: 'account', access: 'read', scope: 'organization' }];
const entityPrivileges = new Map([['account', [{ Name: 'prvReadAccount', PrivilegeId: 'p1', PrivilegeType: 'Read' }]]]);
const actual = new Map([['p1', depthFromMask(15)]]);
const cmp = compareRolePrivileges(declared, entityPrivileges, actual);
assert.strictEqual(cmp.ok, true, JSON.stringify(cmp.missing));
});
test('depthFromMask: fails closed on an undecodable mask', () => {
// An unreadable mask is not evidence of a grant.
for (const bad of [0, -1, null, undefined, '', 'abc', NaN, 16]) {
assert.strictEqual(depthFromMask(bad), '', String(bad) + ' should not decode');
}
});
test('depthFromMask: tolerates a numeric string', () => {
assert.strictEqual(depthFromMask('8'), 'Global');
assert.strictEqual(depthFromMask('7'), 'Deep');
});
// compileRolePrivileges compiles a persona's requests as the vendored SDK does before ReplacePrivilegesRole: what the managed
// download's persona proof (lib/persona-restore.js) compares a role's held privileges to. The privileges are getEntityPrivileges rows.
const sdkPrivs = (entity, id, scopes = ['user', 'businessUnit', 'parentChild', 'organization']) => [
{ name: `prvRead${entity}`, privilegeId: `{${id}-read}`, privilegeType: 'Read', scopes },
{ name: `prvWrite${entity}`, privilegeId: `${id}-write`, privilegeType: 'Write', scopes },
];
const compiled = (m) => Object.fromEntries([...m].map(([id, v]) => [id, v.depth]));
test('compileRolePrivileges keys each privilege by its bare id at the depth its scope maps to, user scope by default', () => {
const tables = new Map([['account', sdkPrivs('Account', 'A')], ['contact', sdkPrivs('Contact', 'C')]]);
const m = compileRolePrivileges([{ entity: 'account', access: ['read', 'write'] }, { entity: 'contact', access: ['read'], scope: 'organization' }], tables);
assert.deepStrictEqual(compiled(m), { 'a-read': 'Basic', 'a-write': 'Basic', 'c-read': 'Global' });
assert.strictEqual(m.get('a-read').name, 'prvReadAccount');
});
test('compileRolePrivileges merges a privilege tables share at one scope, takes the deeper scope for one table, and refuses two tables at two', () => {
const shared = (entity) => [{ name: 'prvReadActivity', privilegeId: 'S-read', privilegeType: 'Read', scopes: ['user', 'organization'] }];
const tables = new Map([['email', shared('email')], ['task', shared('task')]]);
assert.deepStrictEqual(compiled(compileRolePrivileges([{ entity: 'email', access: ['read'] }, { entity: 'task', access: ['read'] }], tables)), { 's-read': 'Basic' });
assert.deepStrictEqual(compiled(compileRolePrivileges([{ entity: 'email', access: ['read'] }, { entity: 'email', access: ['read'], scope: 'organization' }], tables)), { 's-read': 'Global' });
assert.throws(() => compileRolePrivileges([{ entity: 'email', access: ['read'] }, { entity: 'task', access: ['read'], scope: 'organization' }], tables), /share the privilege 'prvReadActivity' at different scopes/);
});
test('compileRolePrivileges refuses what a build would refuse: no access, an unknown scope or access, an access or scope the table lacks', () => {
const tables = new Map([['account', sdkPrivs('Account', 'A')], ['flow', sdkPrivs('Flow', 'F', ['organization'])]]);
assert.throws(() => compileRolePrivileges([{ entity: 'account', access: [] }], tables), /asks for no access/);
assert.throws(() => compileRolePrivileges([{ entity: 'account', access: ['read'], scope: 'global' }], tables), /unknown scope 'global'/);
assert.throws(() => compileRolePrivileges([{ entity: 'account', access: ['own'] }], tables), /unknown access 'own'/);
assert.throws(() => compileRolePrivileges([{ entity: 'account', access: ['delete'] }], tables), /does not support 'delete' access/);
assert.throws(() => compileRolePrivileges([{ entity: 'flow', access: ['read'] }], tables), /does not support the 'user' scope/);
assert.throws(() => compileRolePrivileges([{ entity: 'lead', access: ['read'] }], tables), /privileges of 'lead' are not known/);
});