Files
stack/packages/organization/tests/copy-grant-writer.test.mjs
jason.woltje d5aa963893 feat(bus): copy credential issue CB2, Gitea verified live (#1873)
An owner-issued Gitea token for an agent copy is staged inactive in the
self-only store, proved live against the copy's Gitea (token scopes by
semantic comparison with all and admin refused, the copy's dedicated
per-org/copy/service account, every reachable repository, expiry), then
committed under the writer's generation, revision, decision, copyId,
incarnation and definition-pin recheck. The grant record holds only an
opaque grant id and rotate date. Vikunja refuses
credential-scope-unverified. Copies still cannot launch (CB3).
2026-11-11 17:13:04 -06:00

216 lines
15 KiB
JavaScript

// #1873 CB2 (design section 5 steps 4 to 6, section 8 row CB2): the grant metadata a verified copy
// credential leaves on its binding record, and the writer's two writes around the remote work. The
// bus side (verifier, slot, broker) is packages/bus/tests/copy-grant.test.mjs.
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { hireDecisions } from '../src/hire-decisions.mjs';
import { organizationWriter } from '../src/organization.mjs';
import { checkRootAgents } from '../src/agent-levels.mjs';
import { materializeCopies } from '../src/agent-copies.mjs';
import { readTemplate } from '../src/definitions.mjs';
import { activateOrg, reserveOrg } from '../src/org-registry.mjs';
import * as bindings from '../src/copy-bindings.mjs';
import { businessDoc, rolesCopy, writeJson } from './helpers.mjs';
const { definitionPin, validateCopyBindings } = bindings;
const OWNER = { actor: 'jason', agent: false, rights: ['org.hire'], owner: true, instanceOwner: true, subject: { provider: 'test', iss: 'https://test', sub: 'owner' } };
const FUTURE = '2099-01-01T00:00:00.000Z';
const ID1 = '11111111-1111-4111-8111-111111111111', ID2 = '22222222-2222-4222-8222-222222222222', ID3 = '33333333-3333-4333-8333-333333333333';
const GITEA = { gitea: { scopes: ['read:repository', 'read:user'], projects: ['stack'] } };
const SECRET = 'sk-test-NOT-A-SECRET-1234';
const repoRoles = join(new URL('../../..', import.meta.url).pathname, 'roles');
const INC = 'a'.repeat(32);
const granted = (over = {}) => ({
copyId: 'c'.repeat(32), orgIncarnation: INC, source: { level: 'root', name: 'rev', project: null },
definition: definitionPin('reviewer', { rolesDir: repoRoles, readTemplate }), generation: 3, state: 'bound',
services: {
gitea: { slot: 'self', scopes: ['read:repository'], resources: { projects: ['stack'] }, rotateBy: '2099-01-01', grantId: 'gitea:5:7', grantGeneration: 1 },
vikunja: { slot: 'self', scopes: { tasks: ['read_one'] }, resources: { projects: ['stack'] }, rotateBy: '2099-01-01', grantId: 'vikunja:2:9', grantGeneration: 2 },
},
decision: ID1, ...over,
});
const withGitea = (patch, over = {}) => { const r = granted(over); r.services.gitea = { ...r.services.gitea, ...patch }; for (const k of Object.keys(patch)) if (patch[k] === undefined) delete r.services.gitea[k]; return r; };
test('CB2 schema: grant fields come together, name their own service and are ids only', () => {
assert.doesNotThrow(() => validateCopyBindings({ rev: granted() }));
// After a stage: pending, the grant gone, its generation kept.
assert.doesNotThrow(() => validateCopyBindings({ rev: withGitea({ rotateBy: undefined, grantId: undefined }, { state: 'pending' }) }));
const refused = [
withGitea({ grantId: undefined }),
withGitea({ rotateBy: undefined }),
withGitea({ grantGeneration: undefined }),
withGitea({ grantId: 'vikunja:5:7' }),
withGitea({ grantId: 'gitea:5' }),
withGitea({ grantId: 'gitea:0:7' }),
withGitea({ grantId: `gitea:${SECRET}` }),
withGitea({ grantId: 'gitea:5:7:' + 'f'.repeat(40) }),
withGitea({ grantGeneration: 0 }),
withGitea({ grantGeneration: 1.5 }),
withGitea({ rotateBy: '2099-02-30' }),
withGitea({ rotateBy: '2099-1-01' }),
withGitea({ token: SECRET }),
withGitea({ account: 'mosaic-copy-x' }),
withGitea({ sha256: 'f'.repeat(64) }),
];
for (const r of refused) assert.throws(() => validateCopyBindings({ rev: r }), e => e.name === 'BusinessError' && !e.message.includes(SECRET) && !e.message.includes('/'), JSON.stringify(r.services.gitea));
});
test('CB2 schema: grant fields are optional per service; one grant id per organization', () => {
// The schema keeps CB0's shape: a service without a grant is valid in any state. Only the
// verifier's commit writes bound, and only when every service holds a grant (bus copy-grant tests).
assert.doesNotThrow(() => validateCopyBindings({ rev: withGitea({ rotateBy: undefined, grantId: undefined }) }));
assert.throws(() => validateCopyBindings({ rev: granted({ services: {} }) }));
const other = { ...granted({ copyId: 'd'.repeat(32), source: { level: 'root', name: 'other', project: null } }) };
other.services = structuredClone(other.services);
other.services.vikunja.grantId = 'vikunja:3:3';
assert.throws(() => validateCopyBindings({ rev: granted(), other }), /grant another binding uses/);
other.services.gitea.grantId = 'gitea:5:8';
assert.doesNotThrow(() => validateCopyBindings({ rev: granted(), other }));
});
test('CB2 the login a copy grant must belong to is per organization, copy and service', () => {
const { copyBotLogin } = bindings;
assert.equal(typeof copyBotLogin, 'function');
const a = copyBotLogin(INC, 'c'.repeat(32), 'gitea');
assert.match(a, /^mosaic-copy-[0-9a-f]{24}$/);
assert.ok(a.length <= 40);
assert.equal(copyBotLogin(INC, 'c'.repeat(32), 'gitea'), a);
for (const other of [copyBotLogin('b'.repeat(32), 'c'.repeat(32), 'gitea'), copyBotLogin(INC, 'd'.repeat(32), 'gitea'), copyBotLogin(INC, 'c'.repeat(32), 'vikunja')])
assert.notEqual(other, a);
for (const bad of [[null, 'c'.repeat(32), 'gitea'], [INC, 'x', 'gitea'], [INC, 'c'.repeat(32), 'host.ops'], [INC, 'c'.repeat(32), 'model']])
assert.equal(copyBotLogin(...bad), null);
});
function setup(t) {
const root = mkdtempSync(join(tmpdir(), 'cb2o-'));
t.after(() => rmSync(root, { recursive: true, force: true }));
const roles = rolesCopy(root);
const doc = { ...businessDoc(root, 'demo'), plugins: { harness: ['pi'] } };
doc.projects.stack.agents = { checker: { definition: 'reviewer' } };
const file = writeJson(join(root, 'businesses/demo.json'), doc);
const dataRoot = join(root, 'data'); mkdirSync(dataRoot, { mode: 0o700 });
const ctx = { configDir: root, dataRoot, instance: 'test' };
const ready = (async () => { await reserveOrg(ctx, 'demo'); await activateOrg(ctx, 'demo'); })();
const snapshot = materializeCopies({ orgId: 'demo', doc, root: { state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents: { rev: { definition: 'reviewer' } } }, { rolesDir: roles }) }, rolesDir: roles });
const writer = organizationWriter({ dir: root, rolesDir: roles });
const service = hireDecisions({ writer, rolesDir: roles, configDir: root, dataRoot, assertClean: () => {}, copies: id => snapshot.org === id ? snapshot : null });
const bind = async (input, id) => {
await ready;
const p = await service.prepare('demo', { op: 'change', reason: 'Bind', binding: { services: GITEA }, ...input }, { id, expiresAt: FUTURE });
await service.apply('demo', p.id, { ...OWNER, digest: p.digest });
};
const rec = name => writer.read('demo').document.copyBindings[name];
const opFor = (name, service = 'gitea') => { const r = rec(name); return { instance: name, service, copyId: r.copyId, generation: r.generation, decision: r.decision, incarnation: r.orgIncarnation }; };
const log = () => readFileSync(join(root, 'businesses/.history/demo/changes.jsonl'), 'utf8');
return { root, roles, file, writer, bind, rec, opFor, log, revision: () => writer.read('demo').revision };
}
const AS = { actor: 'jason', owner: true };
test('CB2 writer: the stage deactivates, the commit binds; the receipts name the verbs, never a grant', async t => {
const f = setup(t);
await f.bind({ level: 'root', name: 'rev' }, ID1);
const op = f.opFor('rev');
assert.equal(f.rec('rev').state, 'pending');
const staged = f.writer.stageCopyGrant('demo', op, { revision: f.revision(), ...AS });
assert.equal(staged.generation, op.generation + 1);
assert.deepEqual({ state: f.rec('rev').state, generation: f.rec('rev').generation }, { state: 'pending', generation: op.generation + 1 });
const done = f.writer.commitCopyGrant('demo', { ...op, generation: staged.generation }, { grantId: 'gitea:5:9', rotateBy: '2099-01-01', revision: staged.revision, ...AS });
assert.equal(done.state, 'bound');
const r = f.rec('rev');
assert.deepEqual({ state: r.state, generation: r.generation, gitea: r.services.gitea }, {
state: 'bound', generation: op.generation + 2,
gitea: { slot: 'self', scopes: ['read:repository', 'read:user'], resources: { projects: ['stack'] }, rotateBy: '2099-01-01', grantId: 'gitea:5:9', grantGeneration: 1 },
});
const log = f.log();
assert.ok(log.includes('binding.stage') && log.includes('binding.grant'));
assert.ok(!log.includes('gitea:5:9') && !log.includes('2099-01-01'), 'the receipts are paths only');
// A new issue stages again: use closes before any remote work, the grant generation stays.
f.writer.stageCopyGrant('demo', f.opFor('rev'), { revision: f.revision(), ...AS });
assert.deepEqual({ state: f.rec('rev').state, gitea: f.rec('rev').services.gitea }, {
state: 'pending', gitea: { slot: 'self', scopes: ['read:repository', 'read:user'], resources: { projects: ['stack'] }, grantGeneration: 1 },
});
const again = f.writer.commitCopyGrant('demo', f.opFor('rev'), { grantId: 'gitea:5:10', rotateBy: '2099-02-01', revision: f.revision(), ...AS });
assert.equal(again.state, 'bound');
assert.equal(f.rec('rev').services.gitea.grantGeneration, 2);
});
test('CB2 writer: a stale generation, revision, decision, copy or incarnation, and a second commit, write nothing', async t => {
const f = setup(t);
await f.bind({ level: 'root', name: 'rev' }, ID1);
const op = f.opFor('rev');
const rev0 = f.revision();
const staged = f.writer.stageCopyGrant('demo', op, { revision: rev0, ...AS });
const after = { ...op, generation: staged.generation };
const grant = { grantId: 'gitea:5:9', rotateBy: '2099-01-01', ...AS };
const before = readFileSync(f.file);
for (const [bad, code] of [
[{ ...after, generation: op.generation }, 'credential-binding-changed'],
[{ ...after, copyId: 'e'.repeat(32) }, 'credential-binding-changed'],
[{ ...after, decision: ID3 }, 'credential-binding-changed'],
[{ ...after, instance: 'checker.stack' }, 'credential-binding-changed'],
[{ ...after, service: 'vikunja' }, 'credential-binding-changed'],
[{ ...after, incarnation: 'b'.repeat(32) }, 'decision-stale'],
]) assert.throws(() => f.writer.commitCopyGrant('demo', bad, { ...grant, revision: staged.revision }), { code }, JSON.stringify(bad));
assert.throws(() => f.writer.commitCopyGrant('demo', after, { ...grant, revision: rev0 }), { code: 'revision-conflict' });
assert.deepEqual(readFileSync(f.file), before);
f.writer.commitCopyGrant('demo', after, { ...grant, revision: staged.revision });
const bound = readFileSync(f.file);
assert.throws(() => f.writer.commitCopyGrant('demo', after, { ...grant, revision: f.revision() }), { code: 'credential-binding-changed' });
assert.throws(() => f.writer.commitCopyGrant('demo', { ...after, generation: after.generation + 1 }, { ...grant, grantId: 'gitea:5:10', revision: f.revision() }), { code: 'credential-binding-changed' });
assert.deepEqual(readFileSync(f.file), bound);
// A new binding decision between the stage and the commit wins: the commit refuses.
f.writer.stageCopyGrant('demo', f.opFor('rev'), { revision: f.revision(), ...AS });
const pinned = f.opFor('rev');
await f.bind({ level: 'root', name: 'rev', binding: { services: { gitea: { scopes: ['read:user'], projects: ['stack'] } } } }, ID2);
assert.throws(() => f.writer.commitCopyGrant('demo', pinned, { ...grant, grantId: 'gitea:5:11', revision: f.revision() }), { code: 'credential-binding-changed' });
assert.deepEqual(f.rec('rev').services.gitea, { slot: 'self', scopes: ['read:user'], resources: { projects: ['stack'] } });
assert.equal(f.rec('rev').state, 'pending');
});
test('CB2 writer: only the owner stages or commits; no agent, tester or member identity', async t => {
const f = setup(t);
await f.bind({ level: 'root', name: 'rev' }, ID1);
const op = f.opFor('rev');
const before = readFileSync(f.file);
for (const who of [{ actor: 'jason', owner: false }, { actor: 'tester', owner: true }, { actor: 'rev', owner: true }, { actor: 'chief', owner: true }, { actor: 'checker.stack', owner: true }, { actor: 'reviewer.checker.stack', owner: true }]) {
assert.throws(() => f.writer.stageCopyGrant('demo', op, { revision: f.revision(), ...who }), { code: 'human-required' }, who.actor);
assert.throws(() => f.writer.commitCopyGrant('demo', op, { grantId: 'gitea:5:9', rotateBy: '2099-01-01', revision: f.revision(), ...who }), { code: 'human-required' }, who.actor);
}
assert.throws(() => f.writer.stageCopyGrant('demo', { ...op, generation: 'x' }, { revision: f.revision(), ...AS }), { code: 'invalid-request' });
assert.deepEqual(readFileSync(f.file), before);
});
test('CB2 writer: another copy\'s grant id never moves here; a definition change refuses the commit', async t => {
const f = setup(t);
await f.bind({ level: 'root', name: 'rev' }, ID1);
await f.bind({ level: 'project', project: 'stack', name: 'checker' }, ID2);
const a = f.writer.stageCopyGrant('demo', f.opFor('rev'), { revision: f.revision(), ...AS });
f.writer.commitCopyGrant('demo', { ...f.opFor('rev') }, { grantId: 'gitea:5:9', rotateBy: '2099-01-01', revision: f.revision(), ...AS });
assert.ok(a);
f.writer.stageCopyGrant('demo', f.opFor('checker.stack'), { revision: f.revision(), ...AS });
const before = readFileSync(f.file);
assert.throws(() => f.writer.commitCopyGrant('demo', f.opFor('checker.stack'), { grantId: 'gitea:5:9', rotateBy: '2099-01-01', revision: f.revision(), ...AS }), { code: 'credential-identity-refused' });
assert.deepEqual(readFileSync(f.file), before);
// The reviewer template changes between the stage and the commit: its pin no longer matches.
const template = join(f.roles, 'reviewer.json');
const role = JSON.parse(readFileSync(template, 'utf8'));
writeFileSync(template, JSON.stringify({ ...role, title: role.title + ' changed' }, null, 2));
assert.throws(() => f.writer.commitCopyGrant('demo', f.opFor('checker.stack'), { grantId: 'gitea:6:1', rotateBy: '2099-01-01', revision: f.revision(), ...AS }), { code: 'credential-role-changed' });
assert.deepEqual(readFileSync(f.file), before);
});
test('CB2 writer: a generic write never adds or changes grant fields', async t => {
const f = setup(t);
await f.bind({ level: 'root', name: 'rev' }, ID1);
const { document, revision } = f.writer.read('demo');
const next = structuredClone(document);
next.copyBindings.rev.services.gitea = { ...next.copyBindings.rev.services.gitea, rotateBy: '2099-01-01', grantId: 'gitea:5:9', grantGeneration: 1 };
next.copyBindings.rev.state = 'bound';
assert.throws(() => f.writer.write('demo', next, { revision, actor: 'jason' }), { code: 'organization-bindings-protected' });
assert.equal(f.rec('rev').state, 'pending');
});