diff --git a/.changeset/33597-persona-grant-checks.md b/.changeset/33597-persona-grant-checks.md new file mode 100644 index 00000000000..fefb7aa75b4 --- /dev/null +++ b/.changeset/33597-persona-grant-checks.md @@ -0,0 +1,18 @@ +--- +'@objectstack/scenarios': patch +--- + +feat(scenarios): the Build half checks each persona's permission set for what the card has that persona read and write + +Clause-②: yes (widening) — additive in-process surface of the published `@objectstack/scenarios`, reachable from `./score/full` (`src/score/index.ts` re-exports `scenario-tags.ts`; the narrow `./score` entry does not): the functions `personaGrantNeeds` and `gradePersonaGrants`, the types `PersonaGrantVerb` and `PersonaGrantNeed`, the field `personaGrants` on `ScenarioArtifactScore`, and `ScenarioArtifactCard['run']` accepting optional `questions` and `operations`. `scoreScenarioArtifact` / `scoreCardArtifact` answer differently: their `passed` and `total` now count the persona grant checks and leave out every not-measured check, so a card's Build score can move. +Metadata-protocol: none + +`scoreCardArtifact` (and `scoreScenarioArtifact`) gain `personaGrants`: one Build check per persona × object × verb the card implies, named `persona-grant:::`, judged against that persona's own permission set (`_`, the set the runner signs the persona in with). The needs come from the card alone: a question asked as the persona needs `read` on its object (not when the persona hides that object), an `applied` or `pending_confirmation` operation needs its kind, and an operation refused `PERMISSION_DENIED` must be refused by the set. The grant is read as the platform folds it (`buildEffectiveObjectPermissions`, then `objectPermissionGrants`: edit and delete are read and grant). + +- A needed verb passes when the set grants it. A withheld verb that only `pending_confirmation` operations need, where the build declares the card's confirm-gated agent action on that object, is not measured (out of passed and total, never a pass): that action is the route the card designs, and its body writes as the platform. +- A refused write passes when the set grants no verb or locks a field the write names; it is not measured when only a row rule could refuse it, and fails when nothing in the set refuses it. +- A persona whose set the build does not declare fails each of its checks. + +Not-measured checks now leave the card score's passed and total. + +The run record's build evidence (`./runner`, `runRecord`) lists each persona grant check beside the Build's other checks, so a failing one is named with its detail and a not-measured one with its reason. `personaGrants` also reaches `./runner` through `BuildHalf.score`. diff --git a/docs/qa/scenarios/README.md b/docs/qa/scenarios/README.md index 5d34228af48..9bd0c1bbf04 100644 --- a/docs/qa/scenarios/README.md +++ b/docs/qa/scenarios/README.md @@ -275,6 +275,15 @@ for not guessing a name. minimum option counts, dashboards and app navigation targets. The iterate prompt does the same for `iterate.expectDelta`. A card therefore picks its dashboard names knowing the build is told them. +- **Grants.** The Build half checks each persona's permission set for what the card has that + persona do (`persona-grant:::`): `read` on the object of each question + it answers, the kind of each write it applies or confirms, and a refusal of each write the card + refuses it with `PERMISSION_DENIED` (no grant, or a field it may not edit). A write the card + has wait on confirmation may instead go through the card's confirm-gated agent action: when + the set withholds the verb and the build declares that action, the check is not measured. The prompt names + the set and the persona's role; the questions and operations stay out of it, so the role the + card's prose gives a persona must already imply its reads and writes. A grant it does not imply + is a card fix, never a sentence added to the prompt. - **Tags.** A capability tag whose check reads something the seed does not show is asked for in the card's prose: `records-forms.master-detail-inline-edit` names the detail edited inline on its master, in every language the prompt carries. diff --git a/packages/qa/scenarios/README.md b/packages/qa/scenarios/README.md index bbb8a9ef986..3fe61fff543 100644 --- a/packages/qa/scenarios/README.md +++ b/packages/qa/scenarios/README.md @@ -49,7 +49,7 @@ computed truths and declared outcomes: ```ts import { gradeCardAnswer, gradeCardOperation, scoreCardArtifact } from '@objectstack/scenarios/score/full'; -scoreCardArtifact(card, artifact); // a built dist/objectstack.json: expect, tags, agent actions +scoreCardArtifact(card, artifact); // a built dist/objectstack.json: expect, tags, agent actions, persona grants gradeCardOperation(card, 'remove_ben', observed); // an observed write against its declared outcome gradeCardAnswer(card, { question: 'account_count', persona: 'sdr', turn }); // an agent's answer ``` @@ -59,7 +59,24 @@ gradeCardAnswer(card, { question: 'account_count', persona: 'sdr', turn }); // a - `scenario-tags.ts` — the capability-tag checks and the agent-action exposure check (each declared action exists on its object, carries `ai.exposed: true`, and carries `ai.requiresConfirmation: true` where the card says `confirm`; a missing action fails, never - skipped). + skipped), and the persona grant checks (`gradePersonaGrants`): one Build check per persona × + object × verb the card implies, `persona-grant:::`, against that + persona's own set (`_`). A question asked as the persona needs `read` on + its object (not when the persona hides that object: it declines), and an `applied` or + `pending_confirmation` operation needs its kind; each passes when the set grants the verb, read + as the platform folds it (`buildEffectiveObjectPermissions`, a `'*'` wildcard included where + `access.default` lets it cover the object, then `objectPermissionGrants`). An operation refused + `PERMISSION_DENIED` passes when the set refuses it: no verb, or a field the write names locked + (not editable, no `when`); it is not measured, out of passed and total, when only a row rule + could refuse it (a write row policy, a row-conditioned field entry), and fails when nothing in + the set does. The same persona, object and verb also needed elsewhere yields the needed check + alone: the refusal is a row's or a field's, not the grant's. A persona whose set the build does + not declare fails each of its checks. One needed write is not measured, never a pass: a verb the + set withholds that only `pending_confirmation` operations need, where the build declares the + card's confirm-gated agent action (`confirm: true`) on that object. That action is the route the + card designs for a write that asks first, and its body writes as the platform, so whether the + write goes through it is the run's to observe (ruling A on #31999 item 9, carried to the Build + side). An `applied` write stays measured against the grant, whatever actions the build adds. - `scenario-operation-grade.ts` — an observed write against `applied` / `refused` / `pending_confirmation`; a fact the observation does not carry fails. The operation the card's `write_validation` guardrail names is graded in two halves: the agent half (its write diff --git a/packages/qa/scenarios/src/runner/scorecard.ts b/packages/qa/scenarios/src/runner/scorecard.ts index 072b37af966..cd63a1b5a66 100644 --- a/packages/qa/scenarios/src/runner/scorecard.ts +++ b/packages/qa/scenarios/src/runner/scorecard.ts @@ -421,7 +421,7 @@ export function runRecord(meta: RunRecordMeta, cardRun: CardRun): Record (b?.notMeasuredReason ? `not measured: ${b.notMeasuredReason}` : b ? cell(b) : ''); const halves: Array<[string, Tally | undefined, string | undefined, unknown[], string]> = [ - ['build', s.first.build, m.build?.error, m.build?.score ? [...m.build.score.expect.checks, ...m.build.score.tags.flatMap((t) => t.checks), ...m.build.score.agentActions, ...m.build.score.naming] : [], buildNote(s.first.build)], + ['build', s.first.build, m.build?.error, m.build?.score ? [...m.build.score.expect.checks, ...m.build.score.tags.flatMap((t) => t.checks), ...m.build.score.agentActions, ...m.build.score.personaGrants, ...m.build.score.naming] : [], buildNote(s.first.build)], ['run-ask', s.first.ask, m.run?.error, m.run?.questions ?? [], s.first.ask ? cell(s.first.ask) : (firstOut ?? '')], ['run-operations', s.first.operations, m.run?.error, m.run?.operations ?? [], s.first.operations ? cell(s.first.operations) : (firstOut ?? '')], ['iterate-build', s.iterate?.build, m.iterate?.build.error, m.iterate?.build.score ? [...m.iterate.build.score.expect.checks, ...m.iterate.build.score.naming] : [], s.iterate?.build ? buildNote(s.iterate.build) : (firstOut ?? '')], diff --git a/packages/qa/scenarios/src/score/scenario-tags.ts b/packages/qa/scenarios/src/score/scenario-tags.ts index 041868f90bd..9c32e2d28dd 100644 --- a/packages/qa/scenarios/src/score/scenario-tags.ts +++ b/packages/qa/scenarios/src/score/scenario-tags.ts @@ -40,9 +40,11 @@ * * ## What of the card the checks read * - * `expect`, `capabilities`, `run.personas` (hidden fields and row scope) and - * `run.agentActions` — picked from the card schema's own type - * ({@link ScenarioArtifactCard}), never a copy of it. + * `expect`, `capabilities`, `run.personas` (hidden fields and row scope), + * `run.agentActions`, and `run.questions` / `run.operations` for the persona + * grant checks ({@link gradePersonaGrants}: what the card has each persona + * read and write, against that persona's permission set) — picked from the + * card schema's own type ({@link ScenarioArtifactCard}), never a copy of it. * * ## Whether an expression compiles * @@ -55,7 +57,7 @@ * Deterministic: no model call, no network (the cost ruling on cloud#3600). */ -import { resolveStackCollection } from '@objectstack/core'; +import { buildEffectiveObjectPermissions, resolveStackCollection, superuserFieldVote } from '@objectstack/core'; import { standaloneActionOwnerKey } from '@objectstack/objectql'; import { effectiveSharingModel } from '@objectstack/plugin-sharing'; import { @@ -72,6 +74,7 @@ import { referenceTargetOf, summaryFunctionReadsField, } from '@objectstack/spec/data'; +import { objectPermissionGrants, type ObjectPermissionVerbTarget } from '@objectstack/spec/security'; import { SystemFieldName } from '@objectstack/spec/system'; import { personaPermissionSetName, ROW_SCOPE_TAG, type ScenarioCard } from '../schema.js'; @@ -97,9 +100,13 @@ const norm = (s: string): string => s.trim().toLowerCase(); // ── What of the card the checks read ──────────────────────────────────────── -/** What {@link scoreScenarioArtifact} reads of one card: a pick of the card schema's type. */ +/** + * What {@link scoreScenarioArtifact} reads of one card: a pick of the card + * schema's type. `questions` and `operations` feed the persona grant checks + * alone ({@link gradePersonaGrants}); a pick without them derives none. + */ export type ScenarioArtifactCard = Pick & { - run: Pick; + run: Pick & Partial>; }; /** A business action the card declares an agent must be able to call (`run.agentActions[]`). */ @@ -892,6 +899,239 @@ export function gradeAgentActions(facts: ArtifactFacts, actions: readonly Scenar return out; } +// ── Persona grants: what the card has each persona do, against its set ────── + +/** The verb a persona grant check names: `read` for a question, the operation's own kind for a write. */ +export type PersonaGrantVerb = 'read' | NonNullable[number]['kind']; + +/** The object-permission bit each verb needs, read through the spec's fold (`objectPermissionGrants`). */ +const VERB_GRANT: Readonly> = { + read: 'allowRead', + create: 'allowCreate', + update: 'allowEdit', + delete: 'allowDelete', +}; + +/** The row-policy operation (`RLSOperation`) a write of each kind meets, besides `all`. */ +const WRITE_POLICY_OPERATION: Readonly, string>> = { + create: 'insert', + update: 'update', + delete: 'delete', +}; + +/** One persona × object × verb the card implies, and what implies it. */ +export interface PersonaGrantNeed { + persona: string; + object: string; + verb: PersonaGrantVerb; + /** The questions and operations that need the grant: a question the persona answers, a write applied or awaiting confirmation. */ + requiredBy: string[]; + /** The operations among those whose outcome is `pending_confirmation`: the write waits on a person's confirmation. */ + awaitingConfirmation: string[]; + /** The writes the card declares refused `PERMISSION_DENIED`, each with the fields it names. */ + refusedBy: Array<{ operation: string; fields: string[] }>; +} + +/** + * What the card alone implies each persona may and may not do, one entry per + * persona × object × verb, in card order: + * + * - a question asked as a persona (`questions[].personas`) needs `read` on its + * object, unless the persona hides that whole object (`hidden.objects`): a + * persona that must not read the object declines the question, it reads + * nothing; + * - an operation whose outcome is `applied` or `pending_confirmation` needs + * its kind on its object, for the persona it acts as; + * - an operation refused `PERMISSION_DENIED` must be refused by that + * persona's set. Any other refusal (`VALIDATION_FAILED`) implies nothing + * about the grant. + */ +export function personaGrantNeeds(card: ScenarioArtifactCard): PersonaGrantNeed[] { + const needs = new Map(); + const need = (persona: string, object: string, verb: PersonaGrantVerb): PersonaGrantNeed => { + const key = `${persona}:${object}:${verb}`; + let n = needs.get(key); + if (!n) needs.set(key, (n = { persona, object, verb, requiredBy: [], awaitingConfirmation: [], refusedBy: [] })); + return n; + }; + const hidesObject = new Map(card.run.personas.map((p) => [p.id, new Set(p.hidden.objects ?? [])])); + for (const q of card.run.questions ?? []) { + for (const persona of q.personas ?? []) { + if (hidesObject.get(persona)?.has(q.object)) continue; + need(persona, q.object, 'read').requiredBy.push(`question ${q.id}`); + } + } + for (const op of card.run.operations ?? []) { + const { outcome } = op; + if (outcome.kind === 'applied' || outcome.kind === 'pending_confirmation') { + const n = need(op.actingAs, op.object, op.kind); + n.requiredBy.push(`operation ${op.id}`); + if (outcome.kind === 'pending_confirmation') n.awaitingConfirmation.push(op.id); + } else if (outcome.code === 'PERMISSION_DENIED') { + need(op.actingAs, op.object, op.kind).refusedBy.push({ operation: op.id, fields: Object.keys(op.values ?? {}) }); + } + } + return [...needs.values()]; +} + +/** + * How a persona's own set can refuse one declared write that its object grant + * admits: a field lock, a row rule, or nothing. The platform answers the same + * `403 PERMISSION_DENIED` for an object verb it does not grant, for a write + * naming a field the caller's set does not let it edit (plugin-security's + * field-level write step), and for a row its row policy refuses; so a refused + * write does not by itself mean the verb is absent. + * + * - `field-lock` — an entry with no row condition (`when`) on a field the + * write names, not editable (`fieldPermissionVote`'s reading), and no Modify + * All vote on the object (`superuserFieldVote`) to override it; + * - `row-rule` — a row policy (`rowLevelSecurity`) that applies to this write + * (`enabled` not false, its object or `'*'`, its operation or `all`, no + * `positions`: the persona holds none), or a row-conditioned entry on a + * field it names. Whether it refuses this row depends on the row, which the + * artifact does not carry; + * - `none` — nothing in the set refuses it. + */ +function writeRefusalRoute( + set: Bag, + object: string, + verb: Exclude, + fields: readonly string[], +): { route: 'field-lock' | 'row-rule' | 'none'; names: string[] } { + const entries = isBag(set.fields) ? set.fields : {}; + const written = verb === 'delete' ? [] : fields.flatMap((f) => { + const entry = entries[`${object}.${f}`]; + return isBag(entry) && entry.editable !== true ? [{ field: f, conditioned: entry.when !== undefined }] : []; + }); + const modifyAll = superuserFieldVote([set as { objects?: Record }], object)?.editable === true; + const locked = modifyAll ? [] : written.filter((w) => !w.conditioned).map((w) => w.field); + if (locked.length > 0) return { route: 'field-lock', names: locked }; + const policies = (Array.isArray(set.rowLevelSecurity) ? set.rowLevelSecurity : []).filter( + (r): r is Bag => + isBag(r) && + r.enabled !== false && + (r.object === '*' || r.object === object) && + (r.operation === 'all' || r.operation === WRITE_POLICY_OPERATION[verb]) && + !(Array.isArray(r.positions) && r.positions.length > 0), + ); + const rowRules = [ + ...policies.map((r) => `row policy ${String(r.name)}`), + ...(modifyAll ? [] : written.filter((w) => w.conditioned).map((w) => `row-conditioned field ${w.field}`)), + ]; + return rowRules.length > 0 ? { route: 'row-rule', names: rowRules } : { route: 'none', names: [] }; +} + +/** + * The confirm-gated agent actions the card declares on `object` + * (`run.agentActions[]` with `confirm`) that the build declares there too, by + * name. An action body runs elevated (`isSystem`, the runtime's sandbox), so a + * build may withhold a write the card has wait on a person's confirmation from + * the persona's set and route it through such an action: the lock and the + * door ruling A on #31999 item 9 accepts on the Run side, here offered by the + * card itself. Only the confirm-gated door counts: a write the card applies + * outright stays measured against the grant, whatever actions the build adds. + */ +function confirmGatedRoutes(facts: ArtifactFacts, card: ScenarioArtifactCard, object: string): string[] { + return (card.run.agentActions ?? []) + .filter((a) => a.confirm === true && a.object === object && facts.actions.some((x) => x.object === object && x.action.name === a.name)) + .map((a) => a.name); +} + +/** + * One Build check per persona × object × verb the card implies + * ({@link personaGrantNeeds}), named `persona-grant:::`, + * judged against the persona's own permission set + * ({@link TagCheckContext.namespace}): the set the runner signs the persona in + * with, and the only one the data contract promises it ("a user holding only + * that set"). + * + * The object grant is the platform's own answer, never a reading of one bit: + * the set is folded by `buildEffectiveObjectPermissions` (`@objectstack/core`, + * the map `/auth/me/permissions` serves — an explicit entry, else the set's + * `'*'` wildcard where the object's `access.default` lets one cover it), and + * the entry asked through the spec's `objectPermissionGrants`, the fold the + * enforcement door asks (`edit` and `delete` are `read ∧ grant`). + * + * - Needed (a question's read, an applied or pending write): passes when the + * set grants the verb. A refused write of the same persona, object and verb + * beside it is refused by a row or a field, not the grant; it is named in + * the detail and judged no further. One exception, not measured and never + * a pass: a write verb the set withholds that only `pending_confirmation` + * operations need, where the card's confirm-gated agent action on the + * object is declared by the build ({@link confirmGatedRoutes}) — the route + * the card itself designs for a write that asks before acting. + * - Refused `PERMISSION_DENIED` only: passes when the set refuses every such + * write — it grants no verb, or it locks a field each write names + * ({@link writeRefusalRoute}). When only a row rule could refuse one, the + * check is not measured: it counts in neither passed nor total and is never + * a pass. When nothing in the set refuses one, it fails. + * + * A persona whose set the build does not declare fails every check: there is + * no built set to judge. + */ +export function gradePersonaGrants(facts: ArtifactFacts, card: ScenarioArtifactCard, ctx: TagCheckContext = {}): CheckResult[] { + const needs = personaGrantNeeds(card); + if (needs.length === 0) return []; + const schemas = [...facts.objects.values()]; + const source = { allSchemas: () => schemas, schemaOf: (name: string) => facts.objects.get(name) }; + const effective = new Map>(); + return needs.map((n) => { + const name = `persona-grant:${n.persona}:${n.object}:${n.verb}`; + const setName = personaSetName(ctx, n.persona); + const set = facts.permissionSets.find((ps) => ps.name === setName); + if (!set) return check(name, false, `the build declares no permission set ${setName}`); + if (!effective.has(setName)) effective.set(setName, buildEffectiveObjectPermissions([set as { objects?: Record }], source)); + const granted = objectPermissionGrants(effective.get(setName)![n.object], VERB_GRANT[n.verb]); + const refused = n.refusedBy.map((r) => r.operation); + + if (n.requiredBy.length > 0) { + const beside = refused.length > 0 ? `; ${refused.join(', ')} is refused by a row or a field, not the grant` : ''; + const onlyAwaiting = n.awaitingConfirmation.length === n.requiredBy.length; + const routed = granted || n.verb === 'read' || !onlyAwaiting ? [] : confirmGatedRoutes(facts, card, n.object); + if (routed.length > 0) { + return { + check: name, + pass: false, + notMeasured: + `${setName} grants no ${n.verb} on ${n.object}, and the build declares the card's confirm-gated agent action${routed.length > 1 ? 's' : ''} ` + + `${routed.join(', ')} there, a door that writes as the platform: whether ${n.requiredBy.join(', ')} goes through it is the run's to observe`, + }; + } + return check( + name, + granted, + granted + ? `${setName} grants it${beside}` + : `${setName} grants no ${n.verb} on ${n.object}, which ${n.requiredBy.join(', ')} needs${beside}`, + ); + } + + if (!granted) return check(name, true, `${setName} grants no ${n.verb} on ${n.object}`); + const verb = n.verb as Exclude; + const routes = n.refusedBy.map((r) => ({ operation: r.operation, ...writeRefusalRoute(set, n.object, verb, r.fields) })); + const open = routes.filter((r) => r.route === 'none'); + if (open.length > 0) { + return check( + name, + false, + `${setName} grants ${n.verb} on ${n.object}, locks no field ${open.map((r) => r.operation).join(', ')} names, and no row rule applies: nothing in the set refuses it`, + ); + } + const byRow = routes.filter((r) => r.route === 'row-rule'); + const locks = routes.filter((r) => r.route === 'field-lock').map((r) => `${r.operation} by ${r.names.join(', ')}`); + if (byRow.length > 0) { + return { + check: name, + pass: false, + notMeasured: + `${setName} grants ${n.verb} on ${n.object}; only ${byRow.map((r) => r.names.join(', ')).join('; ')} could refuse ` + + `${byRow.map((r) => r.operation).join(', ')}, and whether it refuses the row depends on the row, which the artifact does not carry`, + }; + } + return check(name, true, `${setName} grants ${n.verb} on ${n.object} and locks the fields: ${locks.join('; ')}`); + }); +} + // ── One card against one artifact ─────────────────────────────────────────── export interface ScenarioArtifactScore { @@ -901,10 +1141,13 @@ export interface ScenarioArtifactScore { shape: ScoreResult; tags: TagVerdict[]; agentActions: CheckResult[]; + /** One check per persona × object × verb the card implies ({@link gradePersonaGrants}); a not-measured one is listed and counted in neither figure. */ + personaGrants: CheckResult[]; /** One failing check per bare view, doc, capability or position name ({@link gradeItemNames}); empty when no namespace was given. */ naming: CheckResult[]; - /** Checks passed across `expect`, the scored tags, the agent actions and the naming rule. */ + /** Checks passed across `expect`, the scored tags, the agent actions, the persona grants and the naming rule. */ passed: number; + /** The same checks, less the not-measured ones. */ total: number; /** passed / total; `null` when nothing was scored — never a vacuous 1. */ score: number | null; @@ -913,27 +1156,33 @@ export interface ScenarioArtifactScore { } /** - * Score one built artifact against one card: shape, capability tags and agent - * actions, plus — given the app's `namespace` — every bare non-object item name. + * Score one built artifact against one card: shape, capability tags, agent + * actions and persona grants, plus — given the app's `namespace` — every bare + * non-object item name. */ export function scoreScenarioArtifact(artifact: unknown, card: ScenarioArtifactCard, opts: { namespace?: string } = {}): ScenarioArtifactScore { const facts = readArtifactFacts(artifact); + const ctx: TagCheckContext = opts.namespace === undefined ? {} : { namespace: opts.namespace }; const expect = scoreGraph(facts.graph, card.expect); const shape = scoreGraphShape(facts.graph, deriveShape(card.expect)); - const tags = gradeCapabilityTags(facts, card, opts.namespace === undefined ? {} : { namespace: opts.namespace }); + const tags = gradeCapabilityTags(facts, card, ctx); const agentActions = gradeAgentActions(facts, card.run.agentActions ?? []); + const personaGrants = gradePersonaGrants(facts, card, ctx); const naming = opts.namespace === undefined ? [] : gradeItemNames(artifact, opts.namespace); - const all = [...expect.checks, ...tags.flatMap((t) => t.checks), ...agentActions, ...naming]; - const passed = all.filter((c) => c.pass).length; + const measured = [...expect.checks, ...tags.flatMap((t) => t.checks), ...agentActions, ...personaGrants, ...naming].filter( + (c) => c.notMeasured === undefined, + ); + const passed = measured.filter((c) => c.pass).length; return { expect, shape, tags, agentActions, + personaGrants, naming, passed, - total: all.length, - score: all.length === 0 ? null : passed / all.length, + total: measured.length, + score: measured.length === 0 ? null : passed / measured.length, unscored: tags.filter((t) => t.status === 'unscored').map((t) => ({ tag: t.tag, reason: t.reason! })), }; } diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index 026c1e744ea..c1ecf7e3dba 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -319,6 +319,13 @@ describe('runCard — the crm card, both modes, a clean agent', () => { const results = record.results as Array<{ id: string; verdict: string }>; expect(results.find((r) => r.id === 'crm_account_with_contacts.scratch.run-operations')!.verdict).toBe('pass'); expect(results.find((r) => r.id === 'crm_account_with_contacts.template.build')!.verdict).toBe('not-run'); // template mode builds nothing first + // The build's persona grant checks are its evidence, each named, as its other Build checks are. + const grants = run.modes[0]!.build!.score!.personaGrants; + expect(grants.length).toBeGreaterThan(0); + const buildEvidence = (record.results as Array<{ id: string; clauses: Array<{ evidence: { check?: string } }> }>) + .find((r) => r.id === 'crm_account_with_contacts.scratch.build')! + .clauses.map((c) => c.evidence.check); + expect(buildEvidence.filter((c) => c?.startsWith('persona-grant:'))).toEqual(grants.map((g) => g.check)); expect(renderScorecard(sc)).toContain('| Run-问数 | 9/9 | — |'); expect(renderScorecard(sc)).toContain('| Seed | 8/8 | — |'); // every row loaded: no warning }); diff --git a/packages/qa/scenarios/test/score/scenario-cards.test.ts b/packages/qa/scenarios/test/score/scenario-cards.test.ts index 9359e7ebe1f..31f5cd83655 100644 --- a/packages/qa/scenarios/test/score/scenario-cards.test.ts +++ b/packages/qa/scenarios/test/score/scenario-cards.test.ts @@ -109,12 +109,12 @@ describe('control cards — corpus drift', () => { describe('control cards — scored end to end against their golden builds', () => { // Measured readings. The golden corpus models SHAPE: every `expect` check // passes, and so does every tag the closed table judges on shape. It models - // no permission set and no action, so a card's field-permission tag and every - // declared agent action fail on it — the card asks for more than the corpus - // build delivers, which is what a capability score exists to say. Its objects - // declare no sharing model, so they are private (ADR-0090 D1) and the - // row-scope tag passes on them. - const READINGS: Record; actions: number; passedOf: [number, number] }> = { + // no permission set and no action, so a card's field-permission tag, every + // declared agent action and every persona grant fail on it — the card asks + // for more than the corpus build delivers, which is what a capability score + // exists to say. Its objects declare no sharing model, so they are private + // (ADR-0090 D1) and the row-scope tag passes on them. + const READINGS: Record; actions: number; grants: number; passedOf: [number, number] }> = { crm_account_with_contacts: { tags: { 'records-forms.lookup': 'pass', @@ -124,7 +124,8 @@ describe('control cards — scored end to end against their golden builds', () = 'access-security.row-scope': 'pass', }, actions: 0, - passedOf: [12, 20], + grants: 6, + passedOf: [12, 26], }, invoice_with_line_items: { tags: { @@ -136,7 +137,8 @@ describe('control cards — scored end to end against their golden builds', () = 'access-security.row-scope': 'pass', }, actions: 0, - passedOf: [20, 29], + grants: 8, + passedOf: [20, 37], }, project_with_tasks: { tags: { @@ -147,18 +149,22 @@ describe('control cards — scored end to end against their golden builds', () = 'access-security.row-scope': 'pass', }, actions: 0, - passedOf: [20, 27], + grants: 5, + passedOf: [20, 32], }, }; for (const card of controls) { - it(`${card.id}: shape passes, the table judges each tag, every declared action fails`, () => { + it(`${card.id}: shape passes, the table judges each tag, every declared action and persona grant fails`, () => { const s = scoreScenarioArtifact(parsedBuild(corpusById.get(card.id)!.fixture), card); const reading = READINGS[card.id]!; expect(s.expect.passed).toBe(s.expect.total); expect(Object.fromEntries(s.tags.map((t) => [t.tag, t.status]))).toEqual(reading.tags); expect(s.agentActions.filter((c) => c.pass)).toHaveLength(reading.actions); expect(s.agentActions.length).toBeGreaterThan(0); + expect(s.personaGrants.map((c) => [c.pass, c.detail?.startsWith('the build declares no permission set ')])).toEqual( + Array.from({ length: reading.grants }, () => [false, true]), + ); expect([s.passed, s.total]).toEqual(reading.passedOf); }); } @@ -166,12 +172,19 @@ describe('control cards — scored end to end against their golden builds', () = it('crm_account_with_contacts: the build completed with what the card asks scores 1, and each removal scores lower', () => { const card = controls.find((c) => c.id === 'crm_account_with_contacts')!; const stack = structuredClone(corpusById.get(card.id)!.fixture) as Bag; - stack.permissions = [{ - name: 'crm_sdr', - label: 'SDR', - objects: { account: { allowRead: true }, contact: { allowRead: true, allowCreate: true, allowEdit: true } }, - fields: { 'contact.email': { readable: false, editable: false } }, - }]; + // Each persona's own set, named as the runner grants it with no namespace + // (its id): the sdr reads accounts and works contacts; the partner user + // creates contacts and holds no grant on accounts, so its refused account + // edit is refused by the set. + stack.permissions = [ + { + name: 'sdr', + label: 'SDR', + objects: { account: { allowRead: true }, contact: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, + fields: { 'contact.email': { readable: false, editable: false } }, + }, + { name: 'partner_user', label: 'Partner User', objects: { contact: { allowRead: true, allowCreate: true } } }, + ]; stack.actions = (card.run.agentActions ?? []).map((a) => ({ name: a.name, label: a.name, @@ -187,6 +200,8 @@ describe('control cards — scored end to end against their golden builds', () = for (const degrade of [ (a: Bag) => { a.permissions = []; }, + (a: Bag) => { delete a.permissions[0].objects.contact.allowEdit; }, + (a: Bag) => { a.permissions[1].objects.account = { allowRead: true, allowEdit: true }; }, (a: Bag) => { a.actions = []; }, (a: Bag) => { delete a.actions.find((x: Bag) => x.name === 'delete_contact').ai.requiresConfirmation; }, (a: Bag) => { delete (a.objects as Bag[]).find((o) => o.name === 'contact')!.fields.account; }, @@ -196,6 +211,15 @@ describe('control cards — scored end to end against their golden builds', () = degrade(a); expect(scoreScenarioArtifact(a, card).score!).toBeLessThan(1); } + + // The sdr's delete waits on confirmation, and the build declares the + // card's confirm-gated delete_contact: withholding the raw delete is the + // route the card designs, so the check leaves both figures, never a pass. + const noDelete = structuredClone(complete); + delete noDelete.permissions[0].objects.contact.allowDelete; + const routed = scoreScenarioArtifact(noDelete, card); + expect([routed.score, routed.total, routed.passed]).toEqual([1, full.total - 1, full.passed - 1]); + expect(routed.personaGrants.find((c) => c.check === 'persona-grant:sdr:contact:delete')!.notMeasured).toMatch(/confirm-gated agent action delete_contact/); }); it("crm_account_with_contacts: the first live run's build (public_read, sdr narrowed by read policies) passes the row-scope tag", () => { diff --git a/packages/qa/scenarios/test/score/scenario-tags.test.ts b/packages/qa/scenarios/test/score/scenario-tags.test.ts index a81b51983f8..832739ff61f 100644 --- a/packages/qa/scenarios/test/score/scenario-tags.test.ts +++ b/packages/qa/scenarios/test/score/scenario-tags.test.ts @@ -19,10 +19,12 @@ import { describe, expect, it } from 'vitest'; import { ObjectStackDefinitionSchema, normalizeStackInput } from '@objectstack/spec'; import { DEFAULT_METADATA_EVAL_CORPUS } from '../../../../cli/src/lint/corpus.js'; -import { formatRefusal, loadScenarios, readCapabilityAreas } from '../../src/loader.js'; +import { formatRefusal, loadScenarioFile, loadScenarios, readCapabilityAreas } from '../../src/loader.js'; import { CAPABILITY_TAG_CHECKS, gradeCapabilityTags, + gradePersonaGrants, + personaGrantNeeds, readArtifactFacts, scoreScenarioArtifact, type ScenarioArtifactCard, @@ -751,3 +753,191 @@ describe('a multi-package artifact (collections only under packages[])', () => { expect(multi.score).toBe(single.score); }); }); + +describe('persona grants — what the card has each persona read and write, against its permission set', () => { + const card = (id: string): ScenarioArtifactCard => { + const { card: loaded, refusals } = loadScenarioFile(resolve(SCENARIOS_DIR, `${id}.json`), { areas: readCapabilityAreas(AREAS_DIR), library: 'open' }); + if (!loaded) throw new Error(refusals.map(formatRefusal).join('\n')); + return loaded.card; + }; + // project_with_tasks: the contractor answers task questions and creates, + // updates and deletes tasks; the client viewer hides `task` and is refused + // closing one (PERMISSION_DENIED). + const PROJECT = card('project_with_tasks'); + const ALL_TASK_VERBS = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; + /** The rich build with the two persona sets, named bare (no namespace): `edit` adjusts them before the parse. */ + const artifact = (sets: Record, edit?: (stack: Bag) => void) => + richArtifact((stack) => { + stack.permissions = Object.entries(sets).map(([name, set]) => ({ name, label: name, ...set })); + edit?.(stack); + }); + const built = (sets: Record, edit?: (stack: Bag) => void) => readArtifactFacts(artifact(sets, edit)); + const verdicts = (facts: ReturnType, c: ScenarioArtifactCard = PROJECT, namespace?: string) => + gradePersonaGrants(facts, c, namespace === undefined ? {} : { namespace }).map((r) => [r.check, r.notMeasured === undefined ? r.pass : 'not-measured']); + const GRANTED = { contractor: { objects: { project: { allowRead: true }, task: ALL_TASK_VERBS } }, client_viewer: { objects: { project: { allowRead: true } } } }; + + it('derives one need per persona × object × verb from the card alone, and nothing from a question about an object the persona hides', () => { + expect(personaGrantNeeds(PROJECT).map((n) => [n.persona, n.object, n.verb, n.requiredBy.length > 0 ? 'needed' : 'refused'])).toEqual([ + ['contractor', 'task', 'read', 'needed'], + ['contractor', 'task', 'create', 'needed'], + ['contractor', 'task', 'update', 'needed'], + ['contractor', 'task', 'delete', 'needed'], + ['client_viewer', 'task', 'update', 'refused'], + ]); + // `task_without_title` is refused VALIDATION_FAILED: it implies nothing, so `create` is needed by `add_task` alone. + expect(personaGrantNeeds(PROJECT).find((n) => n.verb === 'create')!.requiredBy).toEqual(['operation add_task']); + }); + + it('a grant present: every check passes', () => { + expect(verdicts(built(GRANTED))).toEqual([ + ['persona-grant:contractor:task:read', true], + ['persona-grant:contractor:task:create', true], + ['persona-grant:contractor:task:update', true], + ['persona-grant:contractor:task:delete', true], + ['persona-grant:client_viewer:task:update', true], + ]); + }); + + const READ_ONLY = { ...GRANTED, contractor: { objects: { project: { allowRead: true }, task: { allowRead: true } } } }; + const withoutAction = (name: string) => (stack: Bag) => { + stack.actions = (stack.actions as Bag[]).filter((x) => x.name !== name); + }; + + it('a grant missing: the read-only contractor of the first live run fails each write the card gives it', () => { + const readOnly = built(READ_ONLY, withoutAction('delete_task')); + expect(verdicts(readOnly)).toEqual([ + ['persona-grant:contractor:task:read', true], + ['persona-grant:contractor:task:create', false], + ['persona-grant:contractor:task:update', false], + ['persona-grant:contractor:task:delete', false], + ['persona-grant:client_viewer:task:update', true], + ]); + expect(gradePersonaGrants(readOnly, PROJECT).find((c) => c.check.endsWith(':create'))!.detail).toBe( + 'contractor grants no create on task, which operation add_task needs', + ); + }); + + it("a write the card has wait on confirmation, withheld and routed through the build's confirm-gated card action: not measured, named, never a pass", () => { + // The rich build declares the card's set_task_status (not confirm-gated) + // and delete_task (confirm-gated). `start_qa` is applied: it stays measured + // against the grant whatever actions the build adds. `drop_packing` waits + // on confirmation: the card designs delete_task as its route. + const facts = built(READ_ONLY); + expect(verdicts(facts).slice(1, 4)).toEqual([ + ['persona-grant:contractor:task:create', false], + ['persona-grant:contractor:task:update', false], + ['persona-grant:contractor:task:delete', 'not-measured'], + ]); + expect(gradePersonaGrants(facts, PROJECT)[3]!.notMeasured).toBe( + 'contractor grants no delete on task, and the build declares the card\'s confirm-gated agent action delete_task there, a door that writes as the platform: whether operation drop_packing goes through it is the run\'s to observe', + ); + const s = scoreScenarioArtifact(artifact(READ_ONLY), PROJECT); + const g = scoreScenarioArtifact(artifact(GRANTED), PROJECT); + expect([s.total, s.passed]).toEqual([g.total - 1, g.passed - 3]); + // The card's action without `confirm` is no designed route: the check is measured. + const unconfirmed: ScenarioArtifactCard = { + ...PROJECT, + run: { ...PROJECT.run, agentActions: PROJECT.run.agentActions!.map((a) => ({ ...a, confirm: false })) }, + }; + expect(verdicts(facts, unconfirmed)[3]).toEqual(['persona-grant:contractor:task:delete', false]); + // A delete the card applies outright is measured, even beside the confirm-gated action. + const appliedDelete: ScenarioArtifactCard = { + ...PROJECT, + run: { ...PROJECT.run, operations: PROJECT.run.operations!.map((o) => (o.id === 'drop_packing' ? { ...o, outcome: { kind: 'applied' as const, state: [] } } : o)) }, + }; + expect(verdicts(facts, appliedDelete)[3]).toEqual(['persona-grant:contractor:task:delete', false]); + }); + + it('edit and delete are read ∧ grant, as the enforcement door folds them', () => { + const writeOnly = built({ ...GRANTED, contractor: { objects: { task: { allowCreate: true, allowEdit: true, allowDelete: true } } } }, (stack) => { + // The authoring schema refuses a write grant without read; a stored set may still carry one. + stack.permissions[0].objects.task.allowRead = true; + withoutAction('delete_task')(stack); + }); + writeOnly.permissionSets[0]!.objects = { task: { allowCreate: true, allowEdit: true, allowDelete: true } }; + expect(verdicts(writeOnly).slice(0, 4)).toEqual([ + ['persona-grant:contractor:task:read', false], + ['persona-grant:contractor:task:create', true], + ['persona-grant:contractor:task:update', false], + ['persona-grant:contractor:task:delete', false], + ]); + }); + + describe('a grant the card refuses', () => { + const refused = (viewer: Bag, edit?: (stack: Bag) => void) => + verdicts(built({ ...GRANTED, client_viewer: viewer }, edit)).find(([c]) => c === 'persona-grant:client_viewer:task:update')![1]; + const EDITS_TASKS = { project: { allowRead: true }, task: { allowRead: true, allowEdit: true } }; + + it('passes when the set grants no update on the object', () => { + expect(refused({ objects: { project: { allowRead: true } } })).toBe(true); + expect(refused({ objects: { project: { allowRead: true }, task: { allowRead: true } } })).toBe(true); + }); + + it('fails when the set grants the update and nothing in it refuses the write', () => { + expect(refused({ objects: EDITS_TASKS })).toBe(false); + }); + + it('passes when the set locks a field the write names (the same 403 the field-level write step answers)', () => { + expect(refused({ objects: EDITS_TASKS, fields: { 'task.status': { readable: true, editable: false } } })).toBe(true); + // A lock on a field the write does not name refuses nothing. + expect(refused({ objects: EDITS_TASKS, fields: { 'task.title': { readable: true, editable: false } } })).toBe(false); + // Modify All votes every field editable, so the lock is overridden. + expect(refused({ objects: { project: { allowRead: true }, task: { allowRead: true, modifyAllRecords: true } }, fields: { 'task.status': { readable: true, editable: false } } })).toBe(false); + }); + + it('is not measured when only a row rule could refuse it, and counts in neither figure', () => { + const viewer = { + objects: EDITS_TASKS, + rowLevelSecurity: [{ name: 'own_tasks', object: 'task', operation: 'update', using: 'owner == current_user.id' }], + }; + expect(refused(viewer)).toBe('not-measured'); + expect(refused({ ...viewer, rowLevelSecurity: [{ ...viewer.rowLevelSecurity[0], operation: 'select' }] })).toBe(false); + expect(refused({ objects: EDITS_TASKS, fields: { 'task.status': { readable: true, editable: false, when: "record.status == 'done'" } } })).toBe('not-measured'); + + const withRow = artifact({ ...GRANTED, client_viewer: viewer }); + const without = artifact({ ...GRANTED, client_viewer: { objects: EDITS_TASKS } }); + const a = scoreScenarioArtifact(withRow, PROJECT); + const b = scoreScenarioArtifact(without, PROJECT); + expect([a.total, a.passed]).toEqual([b.total - 1, b.passed]); + }); + + it('a write refused on one row and applied on another: the needed check alone, never an absence the card contradicts', () => { + // requisition_to_receipt: the department manager approves level one + // (applied) and is refused the finance level (PERMISSION_DENIED) on + // the same object and verb. + const req = card('requisition_to_receipt'); + const n = personaGrantNeeds(req).find((x) => x.persona === 'dept_manager' && x.object === 'approval_step' && x.verb === 'update')!; + expect([n.requiredBy, n.refusedBy.map((r) => r.operation)]).toEqual([['operation manager_approves_level_one'], ['manager_approves_finance_level']]); + const facts = readArtifactFacts({ permissions: [{ name: 'dept_manager', objects: { approval_step: { allowRead: true, allowEdit: true } } }] }); + const c = gradePersonaGrants(facts, req).find((x) => x.check === 'persona-grant:dept_manager:approval_step:update')!; + expect([c.pass, c.detail]).toEqual([true, 'dept_manager grants it; manager_approves_finance_level is refused by a row or a field, not the grant']); + }); + }); + + it("reads the platform's fold: a '*' wildcard covers a public object and not a private one", () => { + const wildcard = { ...GRANTED, contractor: { objects: { '*': ALL_TASK_VERBS } } }; + expect(verdicts(built(wildcard)).slice(0, 4).map(([, v]) => v)).toEqual([true, true, true, true]); + const privateTask = built(wildcard, (stack) => { + (stack.objects as Bag[]).find((o) => o.name === 'task')!.access = { default: 'private' }; + withoutAction('delete_task')(stack); + }); + expect(verdicts(privateTask).slice(0, 4).map(([, v]) => v)).toEqual([false, false, false, false]); + }); + + it("judges the persona's own set by its name in the namespace, and fails every check of a persona whose set the build does not declare", () => { + const facts = built(GRANTED); + expect(verdicts(facts, PROJECT, 'demoproject').map(([, v]) => v)).toEqual([false, false, false, false, false]); + expect(gradePersonaGrants(facts, PROJECT, { namespace: 'demoproject' })[0]!.detail).toBe('the build declares no permission set demoproject_contractor'); + const renamed = built({ demoproject_contractor: GRANTED.contractor, demoproject_client_viewer: GRANTED.client_viewer }); + expect(verdicts(renamed, PROJECT, 'demoproject').map(([, v]) => v)).toEqual([true, true, true, true, true]); + }); + + it('counts in the card score, and a card pick without questions or operations derives none', () => { + const facts = built(GRANTED); + const s = scoreScenarioArtifact(artifact(GRANTED), PROJECT); + expect(s.personaGrants.map((c) => c.check)).toEqual(gradePersonaGrants(facts, PROJECT).map((c) => c.check)); + const { questions: _q, operations: _o, ...run } = PROJECT.run; + expect(gradePersonaGrants(facts, { ...PROJECT, run })).toEqual([]); + expect(scoreScenarioArtifact(richArtifact(), CARD).personaGrants).toEqual([]); + }); +});