Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a5f227e9fc | ||
|
|
ce066123b0 | ||
|
|
5dbd7e72d3 | ||
|
|
d23673cd3e |
No files matched your search
@@ -6488,7 +6488,9 @@ export class Broker {
|
||||
if(!['hire','change','fire'].includes(input?.op))fail('invalid-request');
|
||||
if(this.#classification(s,input.op==='fire'?'role.fire':'role.hire')!=='within-role')fail('not-authorized');
|
||||
};
|
||||
if(immediate) { const c=this.#hireCaller(s); if(!c.rights.includes('org.hire'))fail('right-required'); }
|
||||
// #1873 CB1: a copy credential binding is owner-only. A person raising one in one step must be
|
||||
// the organization's owner; a member with org.hire is not.
|
||||
if(immediate) { const c=this.#hireCaller(s); if(!c.rights.includes('org.hire'))fail('right-required'); if(input?.binding!==undefined && c.owner!==true)fail('human-required'); }
|
||||
else chiefAllowed();
|
||||
if(!this.#hires)fail('not-configured');
|
||||
const did=randomUUID(), at=this.#now(), expiresAt=new Date(Date.parse(at)+7*86400000).toISOString();
|
||||
@@ -6497,12 +6499,14 @@ export class Broker {
|
||||
if(!immediate)chiefAllowed();
|
||||
else {
|
||||
const caller=this.#hireCaller(s);
|
||||
if(((p.flagged.length || p.credentialLines.length) && !caller.owner) || (p.level==='root' && !caller.instanceOwner))fail('hire-owner-required');
|
||||
if(p.binding && caller.owner!==true)fail('human-required');
|
||||
if(!p.binding && (((p.flagged.length || p.credentialLines.length) && !caller.owner) || (p.level==='root' && !caller.instanceOwner)))fail('hire-owner-required');
|
||||
}
|
||||
const action=`role.${p.op}`;
|
||||
const level=decisionAutonomy('authority',b.autonomy);
|
||||
let route='human';
|
||||
if(!immediate && level!=='in the loop' && p.level!=='root' && !p.flagged.length && !p.credentialLines.length) {
|
||||
// A binding always goes to the owner; no autonomy level moves it (design section 4).
|
||||
if(!immediate && !p.binding && level!=='in the loop' && p.level!=='root' && !p.flagged.length && !p.credentialLines.length) {
|
||||
if(level==='out of the loop')fail('authority-limits-unavailable');
|
||||
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition');
|
||||
route=b.autonomy?.authorityResolver;
|
||||
@@ -6512,7 +6516,7 @@ export class Broker {
|
||||
this.#store.transaction(()=>{
|
||||
const raiser=immediate?'human':s.role;
|
||||
this.#store.run('INSERT INTO decisions(id,at,business,project,raised_by_role,raised_by_run,class,action,route_to,question,options,recommendation,blocking) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',
|
||||
did,at,s.business,p.project??null,raiser,immediate?'human-console':s.run,'gated',action,route,`${p.op} ${p.name} at ${p.level} level?`,JSON.stringify([{key:'yes',text:'Approve'},{key:'no',text:'Deny'}]),'no',0);
|
||||
did,at,s.business,p.project??null,raiser,immediate?'human-console':s.run,'gated',action,route,p.binding?`${p.binding.after===null?'unbind':'bind'} credentials for copy ${p.binding.instance}?`:`${p.op} ${p.name} at ${p.level} level?`,JSON.stringify([{key:'yes',text:'Approve'},{key:'no',text:'Deny'}]),'no',0);
|
||||
this.#event(s,'action.allowed',{operation:'decision.raise',decision:did,action,approvalChoice:'yes',target:p.name,hire:p,autonomyLevel:level},did);
|
||||
});
|
||||
if(immediate) return this.#hireConsole(s,'hire.resolve.console',{id:did,choice:'yes',digest:p.digest});
|
||||
@@ -6531,6 +6535,7 @@ export class Broker {
|
||||
const validate=()=>{
|
||||
this.#agent(s);
|
||||
if(d.route_to!==s.role || d.raised_by_role===s.role || resolverSubject(this.#business(s.business),s.role,p?.name))fail('not-resolver');
|
||||
if(p?.binding)fail('human-required');
|
||||
if(!p || p.level==='root' || p.flagged.length || p.credentialLines.length)fail('hire-owner-required');
|
||||
if(this.#closed(d.id))fail('decision-closed');
|
||||
if(this.#expireHire(s,d,p))fail('decision-expired');
|
||||
@@ -6581,6 +6586,7 @@ export class Broker {
|
||||
if(closed)fail(closed.by==='expiry'?'decision-expired':'decision-closed');
|
||||
if(this.#expireHire(s,d,p))fail('decision-expired');
|
||||
if(!caller.rights.includes('org.hire'))fail('right-required');
|
||||
if(p.binding && caller.owner!==true)fail('human-required');
|
||||
if(a.adjust!==undefined) {
|
||||
if(!this.#hires?.preview)fail('not-configured');
|
||||
p=await this.#hires.preview(s.business,d.id,{...caller,adjust:a.adjust});
|
||||
|
||||
@@ -16,6 +16,13 @@ group("confirmation-required", "R5/R12: person confirms the arbiter resolution",
|
||||
group("decision-reversed reverse-window-closed", "R2/R12: one-use reverse within the owner's window", "Inspect the reversal trail. After the window, raise an ordinary new decision through the normal approval path; never replay the old approval.");
|
||||
group("definition-shared hire-resolution-required hire-owner-required decision-expired right-required", "R5/R8/R9: digest-bound hire approval by a permitted person", "Use the hire Console path with org.hire. Flagged, credential and root decisions need their owner; expired decisions need a fresh proposal.");
|
||||
group("root-fire-shared", "R3/R8: root fire must revoke every copy's grants", "Other organizations may retain running copies and grants. Ask the owner to coordinate revocation across those organizations before removing the root agent.");
|
||||
// #1873 CB1: copy credential bindings (design sections 4 and 6). Approval is owner-only; nothing here
|
||||
// names a token, a slot path or a file path.
|
||||
group("organization-bindings-protected", "R1/R8: copy bindings change only through an owner-approved decision", "Ask the chief to raise a binding decision for the copy; only the organization owner approves it. No other write path changes copyBindings.");
|
||||
group("credential-binding-changed credential-role-changed credential-definition-unpinned", "R1/R8: binding approval pinned to the current copy, definition and generation", "Read the copy's current binding and definition, then ask the chief to raise a fresh binding decision for the owner; an old approval never carries over.");
|
||||
group("credential-scope-exceeded", "R1/R8: effective access is the role intersected with the approval", "Narrow the requested scopes and projects to what the copy's role and admitted projects allow, or change the role through its own decision first.");
|
||||
group("credential-unbound", "R1/R8: launch needs an approved, verified binding", "Ask the chief to raise a binding decision for the missing service; the owner approves it. A pending binding is not usable until verification exists.");
|
||||
group("copy-unavailable copy-refused", "R3/R8: one active, unambiguous copy identity", "Read the organization's copies. Ask the owner to resolve the definition collision or restore the copy's source before raising a binding decision.");
|
||||
group("copy-stale", "R3: root policy changed since this bus booted", "Ask the owner to restart the organization bus to load the approved root policy, then launch a fresh copy.");
|
||||
group("root-policy-unreadable", "R3: root policy evidence must be readable", "Ask the owner to inspect root agent receipt metadata and restart the bus after repairing the read failure.");
|
||||
group("plugin-disabled", "R3/R6/R10: installed, pinned and enabled plugin capabilities", "Ask the instance owner to verify the installed plugin and the organization owner to enable it. A replacement of an already loaded package needs a host restart; then relaunch the agent.");
|
||||
|
||||
@@ -912,7 +912,9 @@ export async function startBroker({
|
||||
autonomy: organization ? autonomyHost({writer:organizationWriter({dir:organization.dir,rolesDir:organization.rolesDir,dataRoot:instanceRoot??dataRoot}),dataRoot,business:id=>businesses[id],countsAccount:levels.countsAccount,hires:{reverse:(...args)=>broker.hireReverse(...args)},reload,processing}) : null,
|
||||
hires: organization ? (()=>{
|
||||
const service=hireDecisions({writer:organizationWriter({dir:organization.dir,rolesDir:organization.rolesDir,dataRoot:instanceRoot??dataRoot}),rolesDir:organization.rolesDir,configDir:organization.dir,dataRoot,
|
||||
system:organization.system,levels,catalogueFor:async(id,doc)=>doc.plugins?.['model-provider']?.length?catalogueFor(id,{fresh:true}):null,assertClean:value=>credentials.assertClean(value),scanDefinition:(name,entry)=>scanDefinitions({[name]:entry},value=>credentials.assertClean(value)),registryFor:doc=>organizationPlugins(instanceRoot??dataRoot,doc.plugins).registry});
|
||||
system:organization.system,levels,catalogueFor:async(id,doc)=>doc.plugins?.['model-provider']?.length?catalogueFor(id,{fresh:true}):null,assertClean:value=>credentials.assertClean(value),scanDefinition:(name,entry)=>scanDefinitions({[name]:entry},value=>credentials.assertClean(value)),registryFor:doc=>organizationPlugins(instanceRoot??dataRoot,doc.plugins).registry,
|
||||
// #1873 CB1: a copy binding names a copy this bus booted with; no snapshot, no binding.
|
||||
copies:id=>copies?.org===id?copies:null});
|
||||
return authorityHost(service,{modelKeys,reload,proxyOrganization});
|
||||
})() : null,
|
||||
roleFile: organization ? (name) => loadRole(organization.rolesDir, name) : null,
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
// #1873 CB1: a copy credential binding through the broker. Only the chief raises one; only the
|
||||
// organization owner resolves it; no autonomy level, member right, resolver agent, tester or reader
|
||||
// moves it. The written record stays pending, so nothing launches on it in CB1.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { Broker } from '../src/broker.mjs';
|
||||
import { Store } from '../src/store.mjs';
|
||||
import { REFUSALS } from '../src/refusals.mjs';
|
||||
import { hireDecisions } from '../../organization/src/hire-decisions.mjs';
|
||||
import { organizationWriter } from '../../organization/src/organization.mjs';
|
||||
import { loadBusiness } from '../../organization/src/organization-config.mjs';
|
||||
import { checkRootAgents } from '../../organization/src/agent-levels.mjs';
|
||||
import { materializeCopies } from '../../organization/src/agent-copies.mjs';
|
||||
import { activateOrg, reserveOrg } from '../../organization/src/org-registry.mjs';
|
||||
import { businessDoc, rolesCopy, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
|
||||
const SUBJECT = { provider: 'test', iss: 'https://issuer.test', sub: 'owner' };
|
||||
const GITEA = { gitea: { scopes: ['read:repository'], projects: ['stack'] } };
|
||||
const SECRET = 'sk-test-NOT-A-SECRET-1234';
|
||||
|
||||
async function fixture(t, edit = d => d) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'cb1-bus-')), rolesDir = rolesCopy(root);
|
||||
const base = { ...businessDoc(root, 'demo'), plugins: { harness: ['pi'] }, vars: { 'bus.tester': true } };
|
||||
base.projects.stack.agents = { checker: { definition: 'reviewer' } };
|
||||
const doc = edit(base);
|
||||
const file = writeJson(join(root, 'businesses/demo.json'), doc);
|
||||
const storeRoot = join(root, 'data'); mkdirSync(storeRoot, { mode: 0o700 });
|
||||
const ctx = { configDir: root, dataRoot: storeRoot, instance: 'test' };
|
||||
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 }) }, rolesDir });
|
||||
const writer = organizationWriter({ dir: root, rolesDir }), store = new Store(storeRoot);
|
||||
const service = hireDecisions({ writer, rolesDir, dataRoot: storeRoot, configDir: root, assertClean: v => { if (JSON.stringify(v).includes(SECRET)) throw Object.assign(new Error('x'), { code: 'definition-holds-credential' }); }, copies: id => snapshot.org === id ? snapshot : null });
|
||||
const loaded = () => { const d = loadBusiness('demo', { dir: root, rolesDir }); return { ...d, roles: Object.fromEntries(Object.entries(d.roles).map(([n, e]) => [n, { ...d.definitions[e.definition], ...e }])) }; };
|
||||
let writes = 0;
|
||||
const b = new Broker({ store, businesses: { demo: loaded() }, hires: { ...service, apply: async (...args) => { writes++; const r = await service.apply(...args); b.reloadBusiness('demo', loaded()); return r; } } });
|
||||
const owner = b.bindConsole({ business: 'demo', human: 'jason', subject: SUBJECT });
|
||||
const member = (rights, extra = {}) => b.bindHireConsole({ business: 'demo', actor: 'member', subject: { ...SUBJECT, sub: 'member' }, rights, ...extra });
|
||||
const caps = { chief: b.bindLaunch({ business: 'demo', role: 'chief', run: 'chief-run', harness: 'pi' }), coder: b.bindLaunch({ business: 'demo', role: 'coder', run: 'coder-run', harness: 'pi' }) };
|
||||
b.request(caps.chief, { verb: 'role.claim' }); b.request(caps.coder, { verb: 'role.claim' });
|
||||
const call = (cap, verb, args = {}) => Promise.resolve().then(() => b.request(cap, { verb, args }));
|
||||
const bind = (extra = {}) => ({ op: 'change', level: 'root', name: 'rev', reason: 'Bind the reviewer copy', binding: { services: GITEA }, ...extra });
|
||||
const raise = extra => call(caps.chief, 'hire.raise', bind(extra));
|
||||
t.after(() => { store.close(); rmSync(root, { recursive: true, force: true }); });
|
||||
const bindings = () => JSON.parse(readFileSync(file, 'utf8')).copyBindings ?? {};
|
||||
return { root, rolesDir, file, b, store, writer, service, owner, member, caps, call, bind, raise, bindings, writes: () => writes, loaded };
|
||||
}
|
||||
|
||||
test('CB1 bus: only the chief raises a binding; the decision names the copy and holds no token or path', async t => {
|
||||
const f = await fixture(t);
|
||||
await assert.rejects(f.call(f.caps.coder, 'hire.raise', f.bind()), { code: 'role-not-chief' });
|
||||
assert.equal(f.store.get('SELECT count(*) n FROM decisions').n, 0);
|
||||
const d = await f.raise();
|
||||
assert.equal(d.route_to, 'human');
|
||||
assert.equal(d.question, 'bind credentials for copy rev?');
|
||||
assert.equal(d.hire.binding.instance, 'rev');
|
||||
const text = JSON.stringify(d);
|
||||
for (const bad of [SECRET, f.root, 'token']) assert.ok(!text.includes(bad), bad);
|
||||
assert.equal(f.writes(), 0);
|
||||
assert.deepEqual(f.bindings(), {});
|
||||
});
|
||||
|
||||
test('CB1 bus: no autonomy level routes a binding away from the owner', async t => {
|
||||
for (const authority of ['near the loop', 'out of the loop']) {
|
||||
const f = await fixture(t, doc => {
|
||||
doc.definitions = { resolver: { rev: 1, role: { tools: ['read'], network: 'none', authority: { withinRole: ['decision.resolve.technical', 'decision.resolve.authority'], crossRole: [] }, credentials: [] }, instructions: 'Resolve independent decisions.' } };
|
||||
doc.roles.cto = { definition: 'org:resolver' };
|
||||
doc.plugins['limit-check'] = ['token-limit']; doc.launch.limits = { tokens: { providers: { zai: { limit: 100000, since: '2026-01-01T00:00:00.000Z' } } } };
|
||||
doc.autonomy = { authority, authorityResolver: 'cto', notices: true };
|
||||
return doc;
|
||||
});
|
||||
const live = f.loaded(); live.roles.cto.authority = { withinRole: ['decision.resolve.authority'], crossRole: [] }; f.b.reloadBusiness('demo', live);
|
||||
const resolver = f.b.bindLaunch({ business: 'demo', role: 'cto', run: 'cto-run', harness: 'pi' }); f.b.request(resolver, { verb: 'role.claim' });
|
||||
const d = await f.raise();
|
||||
assert.equal(d.route_to, 'human', authority);
|
||||
// The authority resolver cannot take it, nor can the chief through the agent verb.
|
||||
await assert.rejects(f.call(resolver, 'decision.resolve', { id: d.id, choice: 'yes' }), { code: 'hire-resolution-required' }, authority);
|
||||
await assert.rejects(f.call(f.caps.chief, 'decision.resolve', { id: d.id, choice: 'yes' }), { code: 'hire-resolution-required' }, authority);
|
||||
assert.equal(f.writes(), 0, authority);
|
||||
assert.deepEqual(f.bindings(), {}, authority);
|
||||
// A project-level unbind is not root; it lists the lines it removes and still goes to the owner.
|
||||
if (authority === 'near the loop') {
|
||||
await f.call(f.owner, 'hire.start.console', { op: 'change', level: 'project', project: 'stack', name: 'checker', reason: 'Bind', binding: { services: GITEA } });
|
||||
const u = await f.raise({ level: 'project', project: 'stack', name: 'checker', binding: { services: null } });
|
||||
assert.equal(u.hire.level, 'project');
|
||||
assert.equal(u.route_to, 'human');
|
||||
await assert.rejects(f.call(resolver, 'decision.resolve', { id: u.id, choice: 'yes' }), { code: 'hire-resolution-required' });
|
||||
assert.equal(f.bindings()['checker.stack'].state, 'pending');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('CB1 bus: members with org.hire or decide, the tester and a reader cannot resolve; the owner can, once', async t => {
|
||||
const f = await fixture(t);
|
||||
const d = await f.raise();
|
||||
const digest = d.hire.digest;
|
||||
await assert.rejects(f.call(f.member(['org.hire']), 'hire.resolve.console', { id: d.id, choice: 'yes', digest }), { code: 'human-required' });
|
||||
await assert.rejects(f.call(f.member(['org.hire', 'decide'], { instanceOwner: true }), 'hire.resolve.console', { id: d.id, choice: 'yes', digest }), { code: 'human-required' });
|
||||
await assert.rejects(f.call(f.member(['decide']), 'hire.resolve.console', { id: d.id, choice: 'yes', digest }), { code: 'right-required' });
|
||||
await assert.rejects(f.call(f.b.bindTester({ business: 'demo' }), 'hire.resolve.console', { id: d.id, choice: 'yes', digest }), { code: 'human-required' });
|
||||
await assert.rejects(f.call(f.b.bindReader({ business: 'demo' }), 'hire.resolve.console', { id: d.id, choice: 'yes', digest }), { code: 'human-required' });
|
||||
await assert.rejects(f.call(f.owner, 'decision.resolve', { id: d.id, choice: 'yes' }), { code: 'human-required' });
|
||||
assert.equal(f.writes(), 0);
|
||||
assert.deepEqual(f.bindings(), {});
|
||||
await assert.rejects(f.call(f.owner, 'hire.resolve.console', { id: d.id, choice: 'yes', digest: '0'.repeat(64) }), { code: 'decision-stale' });
|
||||
await f.call(f.owner, 'hire.resolve.console', { id: d.id, choice: 'yes', digest });
|
||||
assert.equal(f.writes(), 1);
|
||||
const rec = f.bindings().rev;
|
||||
assert.equal(rec.state, 'pending');
|
||||
assert.equal(rec.decision, d.id);
|
||||
await assert.rejects(f.call(f.owner, 'hire.resolve.console', { id: d.id, choice: 'yes', digest }), { code: 'decision-closed' });
|
||||
assert.equal(f.writes(), 1);
|
||||
});
|
||||
|
||||
test('CB1 bus: a one-step Console binding is owner-only; a member is refused before any decision is saved', async t => {
|
||||
const f = await fixture(t);
|
||||
await assert.rejects(f.call(f.member(['org.hire'], { instanceOwner: true }), 'hire.start.console', f.bind()), { code: 'human-required' });
|
||||
assert.equal(f.store.get('SELECT count(*) n FROM decisions').n, 0);
|
||||
await f.call(f.owner, 'hire.start.console', f.bind());
|
||||
assert.equal(f.bindings().rev.state, 'pending');
|
||||
// Unbind is owner-only too.
|
||||
await assert.rejects(f.call(f.member(['org.hire']), 'hire.start.console', f.bind({ binding: { services: null } })), { code: 'human-required' });
|
||||
await f.call(f.owner, 'hire.start.console', f.bind({ binding: { services: null } }));
|
||||
assert.equal(f.bindings().rev.state, 'unbound');
|
||||
});
|
||||
|
||||
test('CB1 bus: every new refusal has a table entry with a next step', () => {
|
||||
for (const code of ['organization-bindings-protected', 'credential-binding-changed', 'credential-role-changed', 'credential-definition-unpinned', 'credential-scope-exceeded', 'credential-unbound', 'copy-unavailable', 'copy-refused']) {
|
||||
assert.ok(Object.hasOwn(REFUSALS, code), code);
|
||||
assert.ok(REFUSALS[code].nextStep?.length > 20, code);
|
||||
assert.ok(!/(^|[\s("'`])(\/|~\/)/.test(REFUSALS[code].nextStep), code);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,2 @@
|
||||
// Old path of packages/organization/src/copy-bindings.mjs (rename design r2, stage B).
|
||||
export * from "../../organization/src/copy-bindings.mjs";
|
||||
@@ -0,0 +1,318 @@
|
||||
// Copy credential bindings, slices CB0 and CB1 (#1873; design
|
||||
// docs/plans/2026-11-11_copy-credential-binding-design.md sections 3, 5 and 7).
|
||||
//
|
||||
// An organization binds a service to one concrete copy (a root agent's copy or a project agent's
|
||||
// copy) through a record under the organization file's top-level `copyBindings`, keyed by the
|
||||
// copy's instance name. A record holds identities, known scope names, project ids and integers:
|
||||
// never a token, a token fragment or digest, a path or an environment name.
|
||||
//
|
||||
// { copyId, orgIncarnation, source: { level, name, project }, definition: { ref, rev, sha256 },
|
||||
// generation, state, services: { gitea?: { slot, scopes, resources }, vikunja?: {...} },
|
||||
// decision, tracker? }
|
||||
//
|
||||
// copyId is 128 random bits minted on the first approval for that copy; it is kept, with the
|
||||
// generation counting up, through every later change and the unbound tombstone. orgIncarnation is
|
||||
// the registry's (org-registry.mjs): a record copied from another organization, or from a removed
|
||||
// organization with the same id, never matches. `source` is the copy's level, name and project, so
|
||||
// a dotted-name collision or a reused source name never inherits a record. `definition` pins the
|
||||
// copy's definition identity: an org definition by its rev and the hash of its whole entry
|
||||
// (composition, instructions and personality), a role template by the hash readTemplate takes over
|
||||
// its file and contract.
|
||||
//
|
||||
// States: `pending` is approved and not verified. Only a verifier (slice CB2, not built) may turn a
|
||||
// record `bound`, and only `bound` resolves. `unbound` is the tombstone an unbind leaves. Nothing
|
||||
// in CB1 writes `bound`, so no copy binding resolves and no copy launches with one.
|
||||
//
|
||||
// Everything here is pure: no file is read, no secret, no slot.
|
||||
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { refuse } from "./errors.mjs";
|
||||
import { GITEA_SCOPE_CATEGORIES, HOST_SERVICE, ID_PATTERN, SERVICES, VIKUNJA_GRANTABLE } from "./vocabulary.mjs";
|
||||
import { ORG_PREFIX } from "./definitions.mjs";
|
||||
import { canonicalJson, isPlainObject, sha256 } from "./util.mjs";
|
||||
|
||||
export const COPY_ID = /^[0-9a-f]{32}$/;
|
||||
export const INCARNATION = /^[0-9a-f]{32}$/;
|
||||
const SHA256 = /^[0-9a-f]{64}$/;
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
||||
const BOT_NAME = /^bot-[a-z0-9][a-z0-9._-]{0,60}$/;
|
||||
const GITEA_SCOPE = /^(read|write):([a-z]+)$/;
|
||||
const RECORD_KEYS = ["copyId", "orgIncarnation", "source", "definition", "generation", "state", "services", "decision", "tracker"];
|
||||
const SERVICE_KEYS = ["slot", "scopes", "resources"];
|
||||
export const BINDING_STATES = Object.freeze(["pending", "bound", "unbound"]);
|
||||
// CB1 binds the core services (vocabulary SERVICES) only. A plugin service has no verifier design yet.
|
||||
export const BINDABLE_SERVICES = SERVICES;
|
||||
export const MAX_BINDINGS = 256;
|
||||
|
||||
export const newCopyId = () => randomBytes(16).toString("hex");
|
||||
|
||||
// Fixed text for every binding refusal. `service` is a registered service label or null, never a
|
||||
// submitted value.
|
||||
const TEXT = {
|
||||
"human-required": () => "Only the organization owner can approve credential binding.",
|
||||
"credential-unbound": (s) => `credentials.${s} needs an owner-approved binding.`,
|
||||
"credential-scope-exceeded": (s) => `credentials.${s}.scopes exceeds the approved role.`,
|
||||
"credential-scope-unverified": (s) => `credentials.${s} permissions could not be verified.`,
|
||||
"credential-binding-changed": (s) => `credentials.${s} changed; read and approve again.`,
|
||||
"credential-role-changed": (s) => `credentials.${s} no longer matches the approved definition; the owner must review the binding.`,
|
||||
"copy-unavailable": () => "copy is no longer active in this organization.",
|
||||
"copy-refused": () => "copy identity is ambiguous; the owner must resolve the definition collision.",
|
||||
};
|
||||
const label = (service) => (BINDABLE_SERVICES.includes(service) ? service : "service");
|
||||
export function bindingText(code, service = null) {
|
||||
const text = TEXT[code];
|
||||
return text ? text(label(service)) : code;
|
||||
}
|
||||
|
||||
export class CopyBindingError extends Error {
|
||||
constructor(code, service = null) {
|
||||
super(bindingText(code, service));
|
||||
this.name = "CopyBindingError";
|
||||
this.code = code;
|
||||
if (service !== null) this.service = label(service);
|
||||
}
|
||||
}
|
||||
export const bindingFail = (code, service = null) => { throw new CopyBindingError(code, service); };
|
||||
|
||||
// ---- Definition pin ----
|
||||
|
||||
// The identity a binding pins for a copy's definition. `definitions` is the merged root and org
|
||||
// definition map as the boot snapshot holds it; `readTemplate` reads a role template (definitions.mjs).
|
||||
// An org definition: its rev and the hash of its canonical entry. A template: rev null and the
|
||||
// template hash. A version 1 template has no contract and cannot be pinned: null.
|
||||
export function definitionPin(ref, { definitions = {}, rolesDir, readTemplate }) {
|
||||
if (typeof ref !== "string") return null;
|
||||
if (ref.startsWith(ORG_PREFIX)) {
|
||||
const name = ref.slice(ORG_PREFIX.length);
|
||||
const entry = Object.hasOwn(definitions, name) ? definitions[name] : null;
|
||||
if (!isPlainObject(entry) || !Number.isSafeInteger(entry.rev) || entry.rev < 1) return null;
|
||||
return { ref, rev: entry.rev, sha256: sha256(canonicalJson(entry)) };
|
||||
}
|
||||
if (!ID_PATTERN.test(ref) || typeof readTemplate !== "function") return null;
|
||||
try {
|
||||
return { ref, rev: null, sha256: readTemplate(rolesDir, ref).sha256 };
|
||||
} catch (error) {
|
||||
if (error?.name === "BusinessError") return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
export const samePin = (a, b) => isPlainObject(a) && isPlainObject(b) && a.ref === b.ref && a.rev === b.rev && a.sha256 === b.sha256;
|
||||
|
||||
// ---- Scope semantics ----
|
||||
|
||||
// Gitea: {category: "read"|"write"}, one level per category. admin and all are never granted.
|
||||
function giteaLevels(scopes) {
|
||||
if (!Array.isArray(scopes)) return null;
|
||||
const out = {};
|
||||
for (const scope of scopes) {
|
||||
const m = typeof scope === "string" ? GITEA_SCOPE.exec(scope) : null;
|
||||
if (!m || !GITEA_SCOPE_CATEGORIES.includes(m[2]) || Object.hasOwn(out, m[2])) return null;
|
||||
out[m[2]] = m[1];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const RANK = { read: 1, write: 2 };
|
||||
// Vikunja: the set of "group verb" pairs, each one VIKUNJA_GRANTABLE lists.
|
||||
function vikunjaPairs(scopes) {
|
||||
if (!isPlainObject(scopes)) return null;
|
||||
const out = new Set();
|
||||
for (const [group, verbs] of Object.entries(scopes)) {
|
||||
if (!Object.hasOwn(VIKUNJA_GRANTABLE, group) || !Array.isArray(verbs) || verbs.length === 0) return null;
|
||||
for (const verb of verbs) {
|
||||
if (typeof verb !== "string" || !VIKUNJA_GRANTABLE[group].includes(verb) || out.has(`${group} ${verb}`)) return null;
|
||||
out.add(`${group} ${verb}`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
export function validScopes(service, scopes) {
|
||||
if (service === "gitea") { const l = giteaLevels(scopes); return l !== null && Object.keys(l).length > 0; }
|
||||
if (service === "vikunja") { const p = vikunjaPairs(scopes); return p !== null && p.size > 0; }
|
||||
return false;
|
||||
}
|
||||
|
||||
// Whether `approved` is within `role` for the service, compared by the service's semantics: Gitea
|
||||
// read is narrower than write in one category and categories are independent; Vikunja compares
|
||||
// each group and verb pair. A missing category or group is no permission. Never a string compare.
|
||||
export function scopesWithin(service, approved, role) {
|
||||
if (service === "gitea") {
|
||||
const a = giteaLevels(approved), r = giteaLevels(role);
|
||||
if (!a || !r) return false;
|
||||
return Object.entries(a).every(([category, level]) => Object.hasOwn(r, category) && RANK[level] <= RANK[r[category]]);
|
||||
}
|
||||
if (service === "vikunja") {
|
||||
const a = vikunjaPairs(approved), r = vikunjaPairs(role);
|
||||
if (!a || !r) return false;
|
||||
return [...a].every((pair) => r.has(pair));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// effective(V) = role-declared(V) intersect approved(V), as scopes of the service's own shape.
|
||||
// Null when the intersection is empty.
|
||||
export function intersectScopes(service, approved, role) {
|
||||
if (service === "gitea") {
|
||||
const a = giteaLevels(approved), r = giteaLevels(role);
|
||||
if (!a || !r) return null;
|
||||
const out = Object.keys(a).filter((c) => Object.hasOwn(r, c)).sort()
|
||||
.map((c) => `${RANK[a[c]] <= RANK[r[c]] ? a[c] : r[c]}:${c}`);
|
||||
return out.length ? out : null;
|
||||
}
|
||||
if (service === "vikunja") {
|
||||
const a = vikunjaPairs(approved), r = vikunjaPairs(role);
|
||||
if (!a || !r) return null;
|
||||
const out = {};
|
||||
for (const pair of [...a].filter((p) => r.has(p)).sort()) {
|
||||
const [group, verb] = pair.split(" ");
|
||||
(out[group] ??= []).push(verb);
|
||||
}
|
||||
return Object.keys(out).length ? out : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// The role's declared scopes per bindable service. A host service is bound per host elsewhere and
|
||||
// is not a copy binding; a service outside the core pair cannot be bound in CB1.
|
||||
export function roleServices(role) {
|
||||
const out = {};
|
||||
for (const c of role?.credentials ?? []) {
|
||||
if (c.service === HOST_SERVICE) continue;
|
||||
out[c.service] = c.scopes;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- Record schema ----
|
||||
|
||||
// The positional refusal for record `i` (1-based): it never names a submitted key or value.
|
||||
const at = (i, field) => `copyBindings entry ${i} ${field} field is invalid`;
|
||||
|
||||
// Checks the whole `copyBindings` value of an organization document. `trackers` is the list of
|
||||
// {bot, botId} the document's instances and its tracker sync already use; a copy's tracker bot is
|
||||
// unique against them and against other copies. Throws a BusinessError with a positional message.
|
||||
export function validateCopyBindings(value, { trackers = [] } = {}) {
|
||||
if (value === undefined) return;
|
||||
if (!isPlainObject(value)) refuse("copyBindings field is invalid");
|
||||
const keys = Object.keys(value);
|
||||
if (keys.length > MAX_BINDINGS) refuse("copyBindings field is invalid");
|
||||
const bots = new Set(trackers.map((t) => t.bot)), botIds = new Set(trackers.map((t) => t.botId)), copyIds = new Set();
|
||||
keys.forEach((instance, n) => {
|
||||
const i = n + 1, r = value[instance];
|
||||
if (!ID_PATTERN.test(instance)) refuse(`copyBindings entry ${i} name is invalid`);
|
||||
if (!isPlainObject(r)) refuse(`copyBindings entry ${i} is invalid`);
|
||||
const unknown = Object.keys(r).some((k) => !RECORD_KEYS.includes(k));
|
||||
if (unknown) refuse(`copyBindings entry ${i} has an unknown field`);
|
||||
if (typeof r.copyId !== "string" || !COPY_ID.test(r.copyId)) refuse(at(i, "copyId"));
|
||||
if (copyIds.has(r.copyId)) refuse(at(i, "copyId"));
|
||||
copyIds.add(r.copyId);
|
||||
if (typeof r.orgIncarnation !== "string" || !INCARNATION.test(r.orgIncarnation)) refuse(at(i, "orgIncarnation"));
|
||||
const s = r.source;
|
||||
if (!isPlainObject(s) || Object.keys(s).sort().join(",") !== "level,name,project"
|
||||
|| !["root", "project"].includes(s.level) || typeof s.name !== "string" || !ID_PATTERN.test(s.name)
|
||||
|| (s.level === "root" ? s.project !== null : typeof s.project !== "string" || !ID_PATTERN.test(s.project))
|
||||
|| (s.level === "root" ? s.name : `${s.name}.${s.project}`) !== instance) refuse(at(i, "source"));
|
||||
const d = r.definition;
|
||||
if (!isPlainObject(d) || Object.keys(d).sort().join(",") !== "ref,rev,sha256" || typeof d.ref !== "string"
|
||||
|| typeof d.sha256 !== "string" || !SHA256.test(d.sha256)
|
||||
|| (d.ref.startsWith(ORG_PREFIX)
|
||||
? !ID_PATTERN.test(d.ref.slice(ORG_PREFIX.length)) || !Number.isSafeInteger(d.rev) || d.rev < 1
|
||||
: !ID_PATTERN.test(d.ref) || d.rev !== null)) refuse(at(i, "definition"));
|
||||
if (!Number.isSafeInteger(r.generation) || r.generation < 1) refuse(at(i, "generation"));
|
||||
if (!BINDING_STATES.includes(r.state)) refuse(at(i, "state"));
|
||||
if (typeof r.decision !== "string" || !UUID.test(r.decision)) refuse(at(i, "decision"));
|
||||
if (!isPlainObject(r.services)) refuse(at(i, "services"));
|
||||
const services = Object.keys(r.services);
|
||||
if ((r.state === "unbound") !== (services.length === 0)) refuse(at(i, "services"));
|
||||
for (const service of services) {
|
||||
const v = r.services[service];
|
||||
if (!BINDABLE_SERVICES.includes(service) || !isPlainObject(v) || Object.keys(v).sort().join(",") !== SERVICE_KEYS.slice().sort().join(",")
|
||||
|| v.slot !== "self" || !validScopes(service, v.scopes)) refuse(at(i, "services"));
|
||||
const p = v.resources;
|
||||
if (!isPlainObject(p) || Object.keys(p).join(",") !== "projects" || !Array.isArray(p.projects) || p.projects.length === 0
|
||||
|| p.projects.some((x) => typeof x !== "string" || !ID_PATTERN.test(x)) || new Set(p.projects).size !== p.projects.length
|
||||
|| (s.level === "project" && (p.projects.length !== 1 || p.projects[0] !== s.project))) refuse(at(i, "services"));
|
||||
}
|
||||
if (r.tracker !== undefined) {
|
||||
const t = r.tracker;
|
||||
if (!services.includes("vikunja") || !isPlainObject(t) || Object.keys(t).sort().join(",") !== "bot,botId"
|
||||
|| typeof t.bot !== "string" || !BOT_NAME.test(t.bot) || !Number.isSafeInteger(t.botId) || t.botId < 1) refuse(at(i, "tracker"));
|
||||
if (bots.has(t.bot) || botIds.has(t.botId)) refuse(`copyBindings entry ${i} tracker field uses a bot another instance uses`);
|
||||
bots.add(t.bot);
|
||||
botIds.add(t.botId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Resolver (CB0) ----
|
||||
|
||||
// What a copy's binding grants in this organization, from plain inputs only:
|
||||
// orgId, incarnation the organization and its live registry incarnation (null: none)
|
||||
// snapshot the boot snapshot materializeCopies made for orgId
|
||||
// instance the copy's instance name
|
||||
// record copyBindings[instance] from the organization document, or undefined
|
||||
// pin definitionPin of the copy's current definition (null: cannot pin)
|
||||
// role the copy's current resolved role ({credentials: [...]})
|
||||
// projects the project ids that admit this copy now: for a root copy, the projects
|
||||
// whose union holds it (an excluded or refusing project is left out), not
|
||||
// the organization's whole project list
|
||||
// Returns { ok: true, copyId, generation, services: { V: { scopes, projects } } } when every
|
||||
// service the role needs is bound, or { ok: false, code, service } with the first refusal. Only a
|
||||
// `bound` record resolves; pending, partial, tombstoned, foreign and stale records never do.
|
||||
export function resolveCopyBinding({ orgId, incarnation, snapshot, instance, record, pin, role, projects = [] }) {
|
||||
const no = (code, service = null) => ({ ok: false, code, service: service === null ? null : label(service) });
|
||||
if (!snapshot || snapshot.org !== orgId) return no("copy-unavailable");
|
||||
const copy = Object.hasOwn(snapshot.copies ?? {}, instance) ? snapshot.copies[instance] : null;
|
||||
// An org instance of the same name shadows the copy, and a removed or excluded source makes none.
|
||||
if (!copy) return no("copy-unavailable");
|
||||
if (copy.state === "refused") return no(copy.claims ? "copy-refused" : "copy-unavailable");
|
||||
const needed = roleServices(role);
|
||||
const first = Object.keys(needed).sort()[0] ?? null;
|
||||
if (record === undefined || record === null) return no("credential-unbound", first);
|
||||
if (typeof incarnation !== "string" || !INCARNATION.test(incarnation) || record.orgIncarnation !== incarnation) return no("credential-unbound", first);
|
||||
const source = { level: copy.level, name: copy.name, project: copy.project };
|
||||
if (canonicalJson(record.source) !== canonicalJson(source)) return no("credential-unbound", first);
|
||||
if (!pin || !samePin(record.definition, pin) || record.definition.ref !== copy.definition) return no("credential-role-changed", first);
|
||||
if (record.state !== "bound") return no("credential-unbound", first);
|
||||
const approved = record.services ?? {};
|
||||
for (const service of Object.keys(approved).sort()) {
|
||||
if (!Object.hasOwn(needed, service)) return no("credential-scope-exceeded", service);
|
||||
if (!scopesWithin(service, approved[service].scopes, needed[service])) return no("credential-scope-exceeded", service);
|
||||
}
|
||||
const admitted = new Set(copy.level === "project" ? (projects.includes(copy.project) ? [copy.project] : []) : projects);
|
||||
const services = {};
|
||||
for (const service of Object.keys(needed).sort()) {
|
||||
if (!BINDABLE_SERVICES.includes(service) || !Object.hasOwn(approved, service)) return no("credential-unbound", service);
|
||||
const scopes = intersectScopes(service, approved[service].scopes, needed[service]);
|
||||
const reach = approved[service].resources.projects.filter((p) => admitted.has(p)).sort();
|
||||
if (!scopes || reach.length === 0) return no("credential-unbound", service);
|
||||
services[service] = { scopes, projects: reach };
|
||||
}
|
||||
if (!Object.keys(services).length) return no("credential-unbound", first);
|
||||
return { ok: true, copyId: record.copyId, generation: record.generation, services };
|
||||
}
|
||||
|
||||
// ---- Proposal checks (CB1) ----
|
||||
|
||||
// The binding payload a chief proposes: { service: { scopes, projects } } for a bind, or null for
|
||||
// an unbind. Each service must be one the copy's role declares, its scopes within the role and its
|
||||
// projects admitted for the copy (`projects`: for a root copy, the projects whose union holds it).
|
||||
// Never trims a broader request. Returns the normalized services.
|
||||
export function checkBindingRequest(services, { copy, role, projects }) {
|
||||
if (services === null) return null;
|
||||
if (!isPlainObject(services) || Object.keys(services).length === 0) refuse("binding services field is invalid");
|
||||
const needed = roleServices(role);
|
||||
const out = {};
|
||||
for (const service of Object.keys(services).sort()) {
|
||||
if (!BINDABLE_SERVICES.includes(service)) refuse("binding services field is invalid");
|
||||
const v = services[service];
|
||||
if (!isPlainObject(v) || Object.keys(v).sort().join(",") !== "projects,scopes") refuse("binding services field is invalid");
|
||||
if (!validScopes(service, v.scopes)) refuse("binding scopes field is invalid");
|
||||
if (!Object.hasOwn(needed, service) || !scopesWithin(service, v.scopes, needed[service])) bindingFail("credential-scope-exceeded", service);
|
||||
if (!Array.isArray(v.projects) || v.projects.length === 0 || v.projects.some((p) => typeof p !== "string" || !ID_PATTERN.test(p))
|
||||
|| new Set(v.projects).size !== v.projects.length) refuse("binding projects field is invalid");
|
||||
const allowed = copy.level === "project" ? [copy.project] : projects;
|
||||
if (v.projects.some((p) => !allowed.includes(p))) bindingFail("credential-scope-exceeded", service);
|
||||
out[service] = { slot: "self", scopes: structuredClone(v.scopes), resources: { projects: [...v.projects].sort() } };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -13,14 +13,29 @@ import { OrganizationError } from './organization.mjs';
|
||||
import { resolveInstance } from './resolve.mjs';
|
||||
import { checkRoutes } from './launch-settings.mjs';
|
||||
import { VERB_RIGHTS } from './org-rights.mjs';
|
||||
import { readRegistry, withRegistryWriter } from './org-registry.mjs';
|
||||
import { ensureOrgIncarnation, orgIncarnation, readRegistry, withRegistryWriter } from './org-registry.mjs';
|
||||
import { checkDefinitions } from './definitions.mjs';
|
||||
import { loadRole } from './role.mjs';
|
||||
import { copyInstanceName } from './agent-copies.mjs';
|
||||
import { resolveAgentLevels } from './agent-levels.mjs';
|
||||
import { bindingFail, checkBindingRequest, definitionPin, newCopyId, samePin } from './copy-bindings.mjs';
|
||||
const fail = code => { throw new OrganizationError(code); };
|
||||
const hash = x => createHash('sha256').update(canonicalJson(x)).digest('hex');
|
||||
const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
||||
const keys = (x, allowed, required = []) => { if (!isPlainObject(x) || Object.keys(x).some(k => !allowed.includes(k)) || required.some(k => !Object.hasOwn(x,k))) fail('invalid-request'); };
|
||||
const id = x => { if (typeof x !== 'string' || !ID_PATTERN.test(x) || ['human','tester','user'].includes(x)) fail('invalid-request'); };
|
||||
const requestKeys = ['op','level','project','name','role','credentials','personality','route','reason'];
|
||||
const requestKeys = ['op','level','project','name','role','credentials','personality','route','reason','binding'];
|
||||
// #1873 CB1: a copy credential binding (bind or unbind) is owner-only. No agent resolves it, whatever
|
||||
// authority decision or resolver it carries; a person needs org.hire and must be the current owner
|
||||
// of the organization. An instance operator alone is not.
|
||||
const bindingOwnerOnly = () => fail('human-required');
|
||||
export function authorizeHire(proposal, caller) {
|
||||
if(proposal?.binding!==undefined) {
|
||||
if(!caller || caller.agent!==false)bindingOwnerOnly();
|
||||
if(!caller.rights?.includes(VERB_RIGHTS['hire.resolve.console']))fail('right-required');
|
||||
if(caller.owner!==true)bindingOwnerOnly();
|
||||
return;
|
||||
}
|
||||
if(caller?.agent===true) {
|
||||
if(typeof caller.authorityDecision!=='string' || typeof caller.resolver!=='string')fail('human-required');
|
||||
if(caller.authorityDecision!==proposal.id || !caller.rights?.includes('decision.resolve.authority') || proposal.flagged.length || proposal.credentialLines.length || proposal.level==='root' || caller.resolver===proposal.name)fail('hire-owner-required');
|
||||
@@ -38,12 +53,16 @@ export function credentialLines(credentials) {
|
||||
const publicOf = p => ({ id:p.id, revision:p.revision, op:p.request.op, level:p.request.level, name:p.request.name,
|
||||
...(p.request.project === undefined ? {} : {project:p.request.project}), route:p.request.route ?? null,
|
||||
...(p.entry ? {role:structuredClone(p.entry.role)} : {}),
|
||||
// #1873 CB1: ids, scope names, project ids and integers. Never a token, a slot path or a file path.
|
||||
...(p.kind === 'binding' ? {binding:structuredClone(p.binding)} : {}),
|
||||
// reason and all free text stay in the private proposal as well.
|
||||
flagged:p.flagged, credentialLines:p.credentialLines, expiresAt:p.expiresAt, digest:hash(p) });
|
||||
// org-defscan (#1873): `scanDefinition(name, entry)` is the bus's definition check on the approved
|
||||
// entry; it throws (definition-holds-credential, naming the definition and key) when the live store
|
||||
// holds text in it. Without one, the entry still goes through assertClean whole.
|
||||
export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertClean, scanDefinition, system = {}, levels = () => null, catalogueFor = async () => null, registryFor = () => buildRegistry() }) {
|
||||
// `copies(business)` (#1873 CB1) is the bus's boot snapshot of this organization's copies
|
||||
// (agent-copies.mjs materializeCopies). A bus without one refuses every binding: copy-unavailable.
|
||||
export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertClean, scanDefinition, system = {}, levels = () => null, catalogueFor = async () => null, registryFor = () => buildRegistry(), copies = () => null }) {
|
||||
const scanEntry = (name, entry) => {
|
||||
if (typeof scanDefinition === 'function') return scanDefinition(name, structuredClone(entry));
|
||||
if (typeof assertClean !== 'function') fail('definition-secret-check-required');
|
||||
@@ -83,12 +102,97 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
}
|
||||
const location = value => { if (!UUID.test(value)) fail('invalid-request'); return join(home,`${value}.json`); };
|
||||
const read = value => { try { return readJsonFile(location(value),'private hire proposal',st=>{if(st.uid!==process.getuid() || st.mode&0o077 || st.nlink!==1)fail('decision-stale');}); } catch { fail('decision-stale'); } };
|
||||
// ---- #1873 CB1: copy credential binding subtype ----
|
||||
// The copy, its pinned definition and role, as this bus booted them and the file holds them now.
|
||||
// Every refusal is a fixed code; nothing names a token, a slot or a path.
|
||||
const bindingFacts = (business, request, doc) => {
|
||||
const snapshot = copies(business);
|
||||
const project = request.level === 'project' ? request.project : null;
|
||||
const instance = copyInstanceName(request.name, project);
|
||||
const copy = instance !== null && snapshot?.org === business && Object.hasOwn(snapshot.copies ?? {}, instance) ? snapshot.copies[instance] : null;
|
||||
if (!copy || copy.name !== request.name || copy.project !== project || copy.level !== request.level) fail('copy-unavailable');
|
||||
if (copy.state === 'refused') fail(copy.claims ? 'copy-refused' : 'copy-unavailable');
|
||||
// A root copy is only as fresh as its root receipts: removed, replaced or unreadable since boot refuses.
|
||||
if (copy.level === 'root') { const stale = rootRefusal(copy.name); if (stale) fail(stale); }
|
||||
// A named instance added since boot shadows the copy (design section 6).
|
||||
if (Object.hasOwn(doc.roles ?? {}, instance)) fail('copy-unavailable');
|
||||
const definitions = { ...(snapshot.definitions ?? {}), ...(doc.definitions ?? {}) };
|
||||
const pin = definitionPin(copy.definition, { definitions, rolesDir, readTemplate });
|
||||
if (!pin) fail('credential-definition-unpinned');
|
||||
const role = copy.definition.startsWith('org:') ? checkDefinitions(definitions, 'copy definitions')[copy.definition] : loadRole(rolesDir, copy.definition);
|
||||
if (!role) fail('credential-definition-unpinned');
|
||||
// The projects that admit this copy now. A root copy reaches only the projects whose union,
|
||||
// recomputed from this document and the boot's root agents, still holds it: an exclude entry or a
|
||||
// refusing union bars it, and a request naming that project refuses (credential-scope-exceeded).
|
||||
const code = Object.keys(doc.projects ?? {}).filter(p => doc.projects[p]?.kind !== 'library');
|
||||
let projects = code;
|
||||
if (copy.level === 'root') {
|
||||
let levels;
|
||||
try { levels = resolveAgentLevels({ orgId: business, doc: { ...doc, definitions }, root: { agents: snapshot.rootAgents ?? {} }, rolesDir }); }
|
||||
catch (error) { if (error?.name === 'BusinessError') fail('copy-unavailable'); throw error; }
|
||||
projects = code.filter(p => levels.unions[p]?.ok && levels.unions[p].agents.some(a => a.level === 'root' && a.name === copy.name));
|
||||
}
|
||||
return { instance, copy, pin, role, definitions, projects, source: { level: copy.level, name: copy.name, project } };
|
||||
};
|
||||
const bindingLines = services => credentialLines(Object.entries(services ?? {}).map(([service, v]) => ({ service, scopes: v.scopes })));
|
||||
async function prepareBinding(business, input, { id: decision, expiresAt }) {
|
||||
if (input.op !== 'change' || !['root','project'].includes(input.level) || ['role','route','credentials','personality'].some(k => k in input)) fail('invalid-request');
|
||||
if (input.level === 'project') id(input.project); else if ('project' in input) fail('invalid-request');
|
||||
keys(input.binding, ['services'], ['services']);
|
||||
const { document: doc, revision } = writer.read(business);
|
||||
const facts = bindingFacts(business, input, doc);
|
||||
let after;
|
||||
try { after = checkBindingRequest(input.binding.services, { copy: facts.copy, role: facts.role, projects: facts.projects }); }
|
||||
catch (error) { if (error?.name === 'CopyBindingError') fail(error.code); fail('invalid-request'); }
|
||||
const current = doc.copyBindings?.[facts.instance] ?? null;
|
||||
if (current && canonicalJson(current.source) !== canonicalJson(facts.source)) fail('credential-binding-changed');
|
||||
if (after === null && (!current || current.state === 'unbound')) fail('credential-unbound');
|
||||
// An org reserved before CB0 gets its incarnation here, under the registry lock.
|
||||
const incarnation = ensureOrgIncarnation(configDir, business);
|
||||
if (incarnation === null) fail('copy-unavailable');
|
||||
if (current && current.orgIncarnation !== incarnation) fail('credential-binding-changed');
|
||||
const binding = {
|
||||
instance: facts.instance, source: facts.source, copyId: current?.copyId ?? newCopyId(), fresh: !current, orgIncarnation: incarnation,
|
||||
definition: facts.pin, before: current && current.state !== 'unbound' ? structuredClone(current.services) : null, after, generation: current?.generation ?? 0,
|
||||
};
|
||||
// Only the structured fields are kept. The free-text reason is never written to the proposal or
|
||||
// covered by its digest: a chief may paste a path or a token fragment there by mistake.
|
||||
const request = { op: input.op, level: input.level, name: input.name, ...(input.level === 'project' ? { project: input.project } : {}), binding: { services: structuredClone(input.binding.services) } };
|
||||
const p = { id: decision, business, kind: 'binding', prior: null, revision, rootRevision: null, request, entry: null, definition: null,
|
||||
binding, flagged: [], credentialLines: bindingLines(after ?? binding.before), expiresAt };
|
||||
mkdirSync(home, { recursive: true, mode: 0o700 });
|
||||
const st = lstatSync(home); if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid() || st.mode & 0o077) fail('organization-refused');
|
||||
const fd = openSync(location(decision), 'wx', 0o600);
|
||||
try { writeFileSync(fd, JSON.stringify(p)); fsyncSync(fd); } finally { closeSync(fd); }
|
||||
return publicOf(p);
|
||||
}
|
||||
// Everything the approval pinned, read again before any effect: the file revision, the copy, its
|
||||
// definition, the registry incarnation, the generation and the requested scopes.
|
||||
async function checkBinding(business, p) {
|
||||
const { document: doc, revision } = writer.read(business);
|
||||
if (revision !== p.revision) fail('decision-stale');
|
||||
const facts = bindingFacts(business, p.request, doc);
|
||||
const b = p.binding;
|
||||
if (facts.instance !== b.instance || canonicalJson(facts.source) !== canonicalJson(b.source)) fail('credential-binding-changed');
|
||||
if (!samePin(facts.pin, b.definition)) fail('credential-role-changed');
|
||||
if (orgIncarnation(await readRegistry({ configDir }), business) !== b.orgIncarnation) fail('decision-stale');
|
||||
const current = doc.copyBindings?.[b.instance] ?? null;
|
||||
if ((current?.generation ?? 0) !== b.generation || (current ? current.copyId !== b.copyId : !b.fresh)) fail('credential-binding-changed');
|
||||
if (b.after !== null) {
|
||||
let after;
|
||||
try { after = checkBindingRequest(p.request.binding.services, { copy: facts.copy, role: facts.role, projects: facts.projects }); }
|
||||
catch (error) { if (error?.name === 'CopyBindingError') fail(error.code); fail('invalid-request'); }
|
||||
if (canonicalJson(after) !== canonicalJson(b.after)) fail('decision-stale');
|
||||
}
|
||||
return facts;
|
||||
}
|
||||
async function prepare(business, input, { id: decision, expiresAt }) {
|
||||
keys(input,requestKeys,['op','level','name','reason']); id(input.name);
|
||||
if (!['hire','fire','change'].includes(input.op) || !['org','project','root'].includes(input.level)) fail('invalid-request');
|
||||
if (typeof input.reason!=='string' || input.reason.trim().length===0 || input.reason.length>500) fail('invalid-request');
|
||||
if (typeof assertClean!=='function') fail('definition-secret-check-required');
|
||||
assertClean(input);
|
||||
if ('binding' in input) return prepareBinding(business, input, { id: decision, expiresAt });
|
||||
if (input.level==='project') id(input.project); else if ('project' in input) fail('invalid-request');
|
||||
if (input.op!=='fire') {
|
||||
keys(input.route,['harness','model','thinking'],['harness','model']);
|
||||
@@ -169,6 +273,8 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
// issued after the proposal refuses it here, before preview, check or apply goes further.
|
||||
if(p.entry)scanEntry(p.definition,p.entry);
|
||||
if(adjust===undefined)return p;
|
||||
// A binding is never adjusted: narrowing or replacing it is a new decision (design section 4).
|
||||
if(p.kind==='binding')fail('invalid-request');
|
||||
keys(adjust,['role','credentials','route']);
|
||||
if(!p.entry)fail('invalid-request');
|
||||
assertClean(adjust);
|
||||
@@ -212,6 +318,7 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
if (p.business!==business || caller.digest!==view.digest)fail('decision-stale');
|
||||
if(Date.parse(p.expiresAt)<=(caller.now??Date.now)())fail('decision-expired');
|
||||
authorizeHire(view,caller);
|
||||
if(p.kind==='binding'){await checkBinding(business,p);return p;}
|
||||
if(writer.read(business).revision!==p.revision)fail('decision-stale');
|
||||
// Re-run composition against current policy and scan private text again before any effect.
|
||||
if(p.entry) {
|
||||
@@ -229,6 +336,14 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
}
|
||||
async function apply(business, decision, caller) {
|
||||
const p=await check(business,decision,caller);
|
||||
if(p.kind==='binding') {
|
||||
const facts=await checkBinding(business,p);
|
||||
// A root copy's receipts are read again under the organization lock, before the write and
|
||||
// before publication, so a removal or replacement after checkBinding still refuses.
|
||||
const fresh=()=>{if(facts.copy.level==='root'){const stale=rootRefusal(facts.copy.name);if(stale)fail(stale);}};
|
||||
return writer.applyCopyBindingDecision(business,{...p,digest:publicOf(p).digest},{actor:caller.actor,owner:caller.owner===true,definitions:facts.definitions,
|
||||
beforeWrite:()=>{fresh();caller.beforeWrite?.();},beforePublish:()=>{fresh();caller.beforePublish?.();}});
|
||||
}
|
||||
const r=p.request;
|
||||
const vars=r.route ? {harness:r.route.harness,model:r.route.model,...(r.route.thinking?{thinking:r.route.thinking}:{})} : {};
|
||||
const currentDoc=r.level==='root'?(await readRootAgentsFile(configDir)).document:writer.read(business).document;
|
||||
@@ -248,7 +363,7 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
return writer.applyHireDecision(business,p,{actor:caller.actor,assertClean,beforeWrite:caller.beforeWrite,beforePublish:caller.beforePublish,authorityDecision:caller.authorityDecision});
|
||||
}
|
||||
async function reverse(business,decision,caller) {
|
||||
const p=read(decision);if(p.business!==business || !p.prior || p.request.level==='root')fail('decision-stale');
|
||||
const p=read(decision);if(p.business!==business || p.kind==='binding' || !p.prior || p.request.level==='root')fail('decision-stale');
|
||||
const r=p.request,old=writer.read(business),current=r.level==='org'?old.document.roles[r.name]:old.document.projects[r.project]?.agents?.[r.name];
|
||||
// A later approved change must not be overwritten by an earlier inverse.
|
||||
if(r.op==='fire') {
|
||||
|
||||
@@ -50,9 +50,19 @@ async function readPrivate(file) {
|
||||
async function privateDir(path, what = 'a directory') { const st = await fs.lstat(path).catch(rethrow(what)); if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o077)) fail('org-mismatch', 'unsafe private directory', path); }
|
||||
function validateRegistry(doc, file) {
|
||||
if (!doc || doc.version !== 1 || typeof doc.instance !== 'string' || !doc.orgs || typeof doc.orgs !== 'object' || Array.isArray(doc.orgs)) fail('org-mismatch', 'invalid registry', file);
|
||||
for (const [id, entry] of Object.entries(doc.orgs)) { idCheck(id); if (!entry || entry.id !== id || typeof entry.root !== 'string' || !['reserved', 'active', 'deleting', 'archived'].includes(entry.state) || !Number.isSafeInteger(entry.revision) || entry.revision < 1 || typeof entry.created !== 'string') fail('org-mismatch', 'invalid registry entry', file); }
|
||||
for (const [id, entry] of Object.entries(doc.orgs)) { idCheck(id); if (!entry || entry.id !== id || typeof entry.root !== 'string' || !['reserved', 'active', 'deleting', 'archived'].includes(entry.state) || !Number.isSafeInteger(entry.revision) || entry.revision < 1 || typeof entry.created !== 'string' || (entry.incarnation !== undefined && (typeof entry.incarnation !== 'string' || !INCARNATION.test(entry.incarnation)))) fail('org-mismatch', 'invalid registry entry', file); }
|
||||
return doc;
|
||||
}
|
||||
// Registry incarnation (CB0, #1873): 128 random bits minted when an id is
|
||||
// reserved. A removed and recreated organization with the same id gets a new
|
||||
// value, so metadata bound to the old one never matches. An entry reserved
|
||||
// before this field existed has none; nothing binds to it (orgIncarnation
|
||||
// returns null and every binding refuses).
|
||||
export const INCARNATION = /^[0-9a-f]{32}$/;
|
||||
export function orgIncarnation(registry, id) {
|
||||
const value = registry?.orgs && Object.hasOwn(registry.orgs, id) ? registry.orgs[id]?.incarnation : undefined;
|
||||
return typeof value === 'string' && INCARNATION.test(value) ? value : null;
|
||||
}
|
||||
export async function readRegistry({ configDir }) {
|
||||
await safeDir(configDir, false, CONFIG); await privateDir(configDir, CONFIG); const file = join(configDir, 'org-runtime.json'); let doc;
|
||||
try { doc = await readPrivate(file); } catch (e) { if (e.code === 'ENOENT') return null; if (e instanceof OrgError) throw e; fail('org-mismatch', `invalid registry: ${e instanceof SyntaxError ? e.message : quiet(e, 'registry file').message}`); }
|
||||
@@ -126,6 +136,17 @@ export function withRegistryWriter(configDir, fn) {
|
||||
return result;
|
||||
} finally { if (!pending) release(); }
|
||||
}
|
||||
// An active entry reserved before CB0 has no incarnation. The first binding proposal for it mints
|
||||
// one under the registry lock; no binding can exist before that, so none is orphaned. A removed and
|
||||
// recreated id is reserved afresh and gets a new value. Returns null for any entry not active.
|
||||
export function ensureOrgIncarnation(configDir, id) {
|
||||
return withRegistryWriter(configDir, (registry, publish) => {
|
||||
const entry = registry?.orgs && Object.hasOwn(registry.orgs, id) ? registry.orgs[id] : null;
|
||||
if (!entry || entry.state !== 'active') return null;
|
||||
if (orgIncarnation(registry, id) === null) { entry.incarnation = randomBytes(16).toString('hex'); publish(); }
|
||||
return entry.incarnation;
|
||||
});
|
||||
}
|
||||
export async function reserveOrg(ctx, id) {
|
||||
const root = orgRoot(ctx.dataRoot, id);
|
||||
return withRegistry(ctx, async registry => {
|
||||
@@ -135,7 +156,7 @@ export async function reserveOrg(ctx, id) {
|
||||
await safeDir(dirname(root), true, 'org-runtime under the data root'); await privateDir(dirname(root), 'org-runtime under the data root');
|
||||
try { await fs.mkdir(root, { mode: 0o700 }); } catch (e) { if (e.code === 'EEXIST') fail('org-exists', 'organization root already exists', root); throw quiet(e, 'the organization root'); }
|
||||
await fs.writeFile(join(root, '.mosaic-org.json'), JSON.stringify({ instance: ctx.instance, id }) + '\n', { mode: 0o600, flag: 'wx' }).catch(rethrow('the organization marker'));
|
||||
const entry = { id, root, state: 'reserved', created: new Date().toISOString(), revision: 1 }; registry.orgs[id] = entry; return { ...entry };
|
||||
const entry = { id, root, state: 'reserved', created: new Date().toISOString(), revision: 1, incarnation: randomBytes(16).toString('hex') }; registry.orgs[id] = entry; return { ...entry };
|
||||
});
|
||||
}
|
||||
export async function resolveOrg(ctx, id) {
|
||||
|
||||
@@ -9,7 +9,7 @@ import { ID_PATTERN } from './vocabulary.mjs';
|
||||
import { OrgError, orgRoot, quiet, readRegistry, reserveOrg, resolveOrg, withRegistry, withOrgLifecycle } from './org-registry.mjs';
|
||||
import { loadInstalled } from '../../plugins/src/loader.mjs';
|
||||
import { BINDING_NAME } from '../../discord/src/binding.mjs';
|
||||
import { parseJsonFileText } from './util.mjs';
|
||||
import { canonicalJson, parseJsonFileText } from './util.mjs';
|
||||
const rolesDir = resolve(dirname(fileURLToPath(import.meta.url)), '../../../roles');
|
||||
const owner = Object.freeze({ provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner' });
|
||||
const fail = (code, message, path) => { throw new OrgError(code, message, path); };
|
||||
@@ -38,6 +38,9 @@ async function receipts(root) {
|
||||
}
|
||||
function normalizeDoc(ctx, id, input, existing) {
|
||||
if (!input || input.id !== id) fail('org-invalid', 'document id must match organization id', '$.id');
|
||||
// #1873 CB1: copy bindings change only through the owner-approved binding decision's writer.
|
||||
// A create or a whole-document update that adds, edits or drops one is refused.
|
||||
if (canonicalJson(input.copyBindings ?? null) !== canonicalJson(existing?.copyBindings ?? null)) fail('organization-bindings-protected', 'copyBindings change only through an owner-approved binding decision', '$.copyBindings');
|
||||
const doc = structuredClone(input); const root = orgRoot(ctx.dataRoot, id);
|
||||
for (const [project, entry] of Object.entries(doc.projects ?? {})) {
|
||||
checkId(project); if (!entry || entry.kind === 'library') fail('org-invalid', 'configured projects must be Git projects', `$.projects.${project}`);
|
||||
|
||||
@@ -20,6 +20,7 @@ import { checkMapping } from "../../library/src/mapping.mjs";
|
||||
import { forkProblem, giteaName, parseGiteaUrl, HOST_SERVICE, CREATIVE_DEFINITIONS } from "./vocabulary.mjs";
|
||||
import { checkAppearance } from "./appearance.mjs";
|
||||
import { checkProjectAgents } from "./agent-levels.mjs";
|
||||
import { validateCopyBindings } from "./copy-bindings.mjs";
|
||||
import {
|
||||
requireObject, rejectUnknownKeys, requireId, requirePositiveInt, requireString, requireDistinctList, readJsonFile, deepFreeze,
|
||||
} from "./util.mjs";
|
||||
@@ -28,7 +29,7 @@ const BOT_NAME = /^bot-[a-z0-9][a-z0-9._-]{0,60}$/;
|
||||
// How long a thread's session stays up with no turn before the launcher stops
|
||||
// it, when launch.threadIdleSeconds is absent (REQ-THREAD-2, row 121).
|
||||
export const THREAD_IDLE_SECONDS = 900;
|
||||
const TOP_KEYS = ["businessVersion", "id", "human", "arbiters", "projects", "vars", "tracker", "roles", "launch", "plugins", "hosts", "retired", "replyLimits", "usage", "appearance", "definitions", "autonomy"];
|
||||
const TOP_KEYS = ["businessVersion", "id", "human", "arbiters", "projects", "vars", "tracker", "roles", "launch", "plugins", "hosts", "retired", "replyLimits", "usage", "appearance", "definitions", "autonomy", "copyBindings"];
|
||||
|
||||
// The config directory: next to the system config, $MOSAIC_CONFIG or
|
||||
// ~/.config/mosaic-dev/config.json, the same rule mosaic-config.mjs uses.
|
||||
@@ -344,6 +345,10 @@ export function validateOrganizationDocument(document, file, { rolesDir, dataRoo
|
||||
refuse(`${file} tracker.sync must use its own bot, not the one roles.${instance} uses`);
|
||||
}
|
||||
}
|
||||
// #1873 CB1: copy credential bindings. Each copy's tracker bot is unique against every named
|
||||
// instance's bot, the tracker sync bot and the other copies.
|
||||
validateCopyBindings(document.copyBindings, { trackers: [...Object.values(roles).map((r) => r.tracker).filter(Boolean), ...(tracker ? [tracker.sync] : [])] });
|
||||
const copyBindings = document.copyBindings === undefined ? undefined : structuredClone(document.copyBindings);
|
||||
const launch = document.launch === undefined ? null : checkLaunch(document.launch, roles, definitions, file);
|
||||
// REQ-PLUG-1: the module names switched on per kind. The names are checked
|
||||
// here; whether each module loads is the loader's check, at load time.
|
||||
@@ -372,6 +377,7 @@ export function validateOrganizationDocument(document, file, { rolesDir, dataRoo
|
||||
return deepFreeze({
|
||||
businessVersion: 1, id: document.id, file, human, arbiters, projects, vars, tracker, roles, launch, plugins, definitions,
|
||||
...(autonomy === undefined ? {} : { autonomy }), ...(retired ? { retired } : {}), ...(usage === undefined ? {} : { usage }), ...(appearance === undefined ? {} : { appearance }),
|
||||
...(copyBindings === undefined ? {} : { copyBindings }),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -12,9 +12,10 @@ import { isDailyModelQuota } from "../../plugins/src/model-quota.mjs";
|
||||
import { checkReplyLimits } from "../../library/src/limits.mjs";
|
||||
import { ADDITION_VERB, additionProblem } from "./project-bootstrap.mjs";
|
||||
import { remoteProblem, remoteTarget } from "./project-remotes.mjs";
|
||||
import { withRegistryWriter } from "./org-registry.mjs";
|
||||
import { orgIncarnation, withRegistryWriter } from "./org-registry.mjs";
|
||||
import { bindingText, definitionPin, samePin } from "./copy-bindings.mjs";
|
||||
import { entryForm, projectAgentProblem, rootForProjectCheck } from "./agent-levels-write.mjs";
|
||||
import { checkDefinition, checkDefinitionName, instancesNaming } from "./definitions.mjs";
|
||||
import { checkDefinition, checkDefinitionName, instancesNaming, readTemplate } from "./definitions.mjs";
|
||||
|
||||
export class OrganizationError extends Error {
|
||||
constructor(code, message = code) {
|
||||
@@ -27,6 +28,15 @@ const fail = (code, message) => {
|
||||
throw new OrganizationError(code, message);
|
||||
};
|
||||
|
||||
// #1873 CB1: the capability only applyCopyBindingDecision holds. Every other commit refuses a change
|
||||
// to `copyBindings`, whatever options its caller spreads in (write() passes its caller's options).
|
||||
const BINDING_WRITE = Symbol("copy-binding-write");
|
||||
const bindingsFence = (old, document, capability) => {
|
||||
if (capability !== BINDING_WRITE && canonicalJson(document?.copyBindings ?? null) !== canonicalJson(old.copyBindings ?? null)) {
|
||||
fail("organization-bindings-protected", "copyBindings change only through an owner-approved binding decision");
|
||||
}
|
||||
};
|
||||
|
||||
function regular(file) {
|
||||
let fd;
|
||||
try {
|
||||
@@ -282,7 +292,7 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
||||
// the old document, for a writer that builds what it publishes from what it read under the lock.
|
||||
// #1873 A2: `pathsOnly` logs each change's path and presence without its values, for a verb whose
|
||||
// values can hold a var a person typed (a secret pasted in the wrong place must not reach evidence).
|
||||
function commit(id, document, { revision, actor, detail, context, beforeWrite = null, beforePublish = null, guard, pathsOnly = false }) {
|
||||
function commit(id, document, { revision, actor, detail, context, beforeWrite = null, beforePublish = null, guard, pathsOnly = false, capability = null, incarnation = undefined }) {
|
||||
requireId(actor, "authenticated actor");
|
||||
requireId(id, "organization id");
|
||||
let revoked = false;
|
||||
@@ -297,9 +307,13 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
||||
fail('org-mismatch', 'organization document and registry disagree');
|
||||
}
|
||||
if (revision !== before) fail("revision-conflict", "organization revision changed; read again");
|
||||
// #1873 CB1: a binding names the registry incarnation it was approved in. A removed and
|
||||
// recreated organization with the same id, or a legacy entry with none, never matches.
|
||||
if (incarnation !== undefined && (!entry || orgIncarnation(registry, id) === null || orgIncarnation(registry, id) !== incarnation)) fail("decision-stale", "organization incarnation changed; raise the decision again");
|
||||
const old = parseJsonFileText(oldBytes, file, "organization file");
|
||||
if (typeof document === "function") document = document(old);
|
||||
guard(old, document);
|
||||
bindingsFence(old, document, capability);
|
||||
replyLimitsFence(old, document, actor);
|
||||
modelQuotaFence(old, document, actor);
|
||||
usageFence(old, document, actor);
|
||||
@@ -311,6 +325,7 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
||||
// can't carry (a Date, a Map) serializes as something else (row 131, sage-0314).
|
||||
const written = JSON.parse(bytes);
|
||||
guard(old, written);
|
||||
bindingsFence(old, written, capability);
|
||||
replyLimitsFence(old, written, actor);
|
||||
modelQuotaFence(old, written, actor);
|
||||
usageFence(old, written, actor);
|
||||
@@ -373,7 +388,7 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
||||
if (canonicalJson(document?.definitions ?? {}) !== canonicalJson(old.definitions ?? {})) fail("organization-definitions-protected");
|
||||
};
|
||||
function write(id, document, options) {
|
||||
return commit(id, document, { ...options, guard: (old, next) => { projectsProtected(old, next); definitionsProtected(old, next); } });
|
||||
return commit(id, document, { ...options, capability: null, incarnation: undefined, guard: (old, next) => { projectsProtected(old, next); definitionsProtected(old, next); } });
|
||||
}
|
||||
|
||||
// #1873 T1: the only writer of `definitions`. `next(current)` returns the new entry without its
|
||||
@@ -532,6 +547,53 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
||||
},context:{decision:proposal.id,digest:proposal.digest??null},detail:{verb:'hire.apply',decision:proposal.id,op:r.op,agent:r.name}});
|
||||
}
|
||||
|
||||
// #1873 CB1 (design sections 3 and 4): the only writer of `copyBindings`, one copy per call. The
|
||||
// broker has consumed the owner's approval of this exact digest before it gets here; the writer
|
||||
// still refuses the tester, every agent identity and a caller that is not the owner, and rechecks
|
||||
// under the locks the registry incarnation, the document revision, the copy's binding generation
|
||||
// and copyId, and its definition pin. A bind writes `pending` (approved, not verified: nothing
|
||||
// resolves or launches it until a verifier exists); an unbind writes the `unbound` tombstone. The
|
||||
// record holds ids, scope names and integers only; the receipt holds paths only.
|
||||
// `definitions` is the boot snapshot's merged definition map, for a root copy whose definition
|
||||
// is not in this file.
|
||||
function applyCopyBindingDecision(id, proposal, { actor, owner = false, definitions = {}, beforeWrite = null, beforePublish = null }) {
|
||||
const { binding: b, revision } = proposal ?? {};
|
||||
if (typeof proposal?.id !== "string" || proposal.kind !== "binding" || !b || typeof b.instance !== "string") fail("invalid-request");
|
||||
const humanOnly = () => fail("human-required", bindingText("human-required"));
|
||||
// Before the lock: no owner, no write. The agent identities are checked again under it.
|
||||
if (owner !== true || actor === "tester") humanOnly();
|
||||
const build = old => {
|
||||
const agents = [
|
||||
...Object.entries(old.roles ?? {}).flatMap(([n, e]) => [n, `${e?.definition}.${n}`]),
|
||||
...Object.entries(old.projects ?? {}).flatMap(([p, v]) => Object.entries(v?.agents ?? {}).flatMap(([n, e]) => [n, `${n}.${p}`, `${e?.definition}.${n}.${p}`])),
|
||||
...Object.keys(old.copyBindings ?? {}), ...Object.keys(definitions ?? {}), b.instance, b.source?.name,
|
||||
];
|
||||
if (owner !== true || actor === "tester" || agents.includes(actor)) humanOnly();
|
||||
const current = old.copyBindings?.[b.instance];
|
||||
if ((current?.generation ?? 0) !== b.generation || (current ? current.copyId !== b.copyId : b.fresh !== true)
|
||||
|| (current && canonicalJson(current.source) !== canonicalJson(b.source))) fail("credential-binding-changed", bindingText("credential-binding-changed", Object.keys(b.after ?? b.before ?? {})[0] ?? null));
|
||||
if (b.after === null && (!current || current.state === "unbound")) fail("credential-binding-changed", bindingText("credential-binding-changed"));
|
||||
const pin = definitionPin(b.definition.ref, { definitions: { ...(definitions ?? {}), ...(old.definitions ?? {}) }, rolesDir, readTemplate });
|
||||
if (!samePin(pin, b.definition)) fail("credential-role-changed", bindingText("credential-role-changed", Object.keys(b.after ?? b.before ?? {})[0] ?? null));
|
||||
const record = {
|
||||
copyId: b.copyId, orgIncarnation: b.orgIncarnation, source: structuredClone(b.source), definition: structuredClone(b.definition),
|
||||
generation: b.generation + 1, state: b.after === null ? "unbound" : "pending",
|
||||
services: b.after === null ? {} : structuredClone(b.after), decision: proposal.id,
|
||||
};
|
||||
return { ...structuredClone(old), copyBindings: { ...(old.copyBindings ?? {}), [b.instance]: record } };
|
||||
};
|
||||
return commit(id, build, {
|
||||
revision, actor, beforeWrite, beforePublish, pathsOnly: true, capability: BINDING_WRITE, incarnation: b.orgIncarnation,
|
||||
guard: (old, next) => {
|
||||
if (canonicalJson(next) !== canonicalJson(build(old))) fail("organization-bindings-protected", "copyBindings change only through an owner-approved binding decision");
|
||||
projectsProtected(old, next);
|
||||
definitionsProtected(old, next);
|
||||
},
|
||||
context: { decision: proposal.id, digest: proposal.digest ?? null },
|
||||
detail: { verb: b.after === null ? "binding.unbind" : "binding.apply", decision: proposal.id, agent: b.instance, generation: b.generation + 1 },
|
||||
});
|
||||
}
|
||||
|
||||
// AU inverse, from an immutable private proposal. It touches only the named instance and
|
||||
// definition; writer validation, fresh revision and owner fence still apply. Bindings never restore.
|
||||
function reverseHireDecision(id,p,{actor,beforeWrite,beforePublish}) {
|
||||
@@ -637,5 +699,5 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
||||
});
|
||||
}
|
||||
|
||||
return { logFile, read, readRaw, write, addProject, setProjectRemote, setProjectAgent, setDefinition, applyHireDecision, reverseHireDecision, hold, holdAsync, findAddition, record, recover: id => withLock(id, () => recover(id)) };
|
||||
return { logFile, read, readRaw, write, addProject, setProjectRemote, setProjectAgent, setDefinition, applyHireDecision, reverseHireDecision, applyCopyBindingDecision, hold, holdAsync, findAddition, record, recover: id => withLock(id, () => recover(id)) };
|
||||
}
|
||||
@@ -0,0 +1,480 @@
|
||||
// #1873 copy credential binding, slices CB0 and CB1 (design
|
||||
// docs/plans/2026-11-11_copy-credential-binding-design.md section 8, rows CB0 and CB1).
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { hireDecisions, authorizeHire } from '../src/hire-decisions.mjs';
|
||||
import { organizationWriter } from '../src/organization.mjs';
|
||||
import { checkRootAgents } from '../src/agent-levels.mjs';
|
||||
import { copyRefusal, loadWithCopies, materializeCopies } from '../src/agent-copies.mjs';
|
||||
import { readTemplate } from '../src/definitions.mjs';
|
||||
import { validateBusinessDocument } from '../src/organization-config.mjs';
|
||||
import { activateOrg, ensureOrgIncarnation, orgIncarnation, orgRoot, readRegistry, reserveOrg, withRegistryWriter } from '../src/org-registry.mjs';
|
||||
import { definitionPin, intersectScopes, resolveCopyBinding, validateCopyBindings } from '../src/copy-bindings.mjs';
|
||||
import { businessDoc, rolesCopy, writeJson } from './helpers.mjs';
|
||||
import { createOrg, showOrg, templateRender, updateOrg } from '../src/org-service.mjs';
|
||||
|
||||
const SECRET = 'sk-test-NOT-A-SECRET-1234';
|
||||
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'], projects: ['stack'] } };
|
||||
const sha = b => createHash('sha256').update(b).digest('hex');
|
||||
|
||||
// ---- CB0: pure resolver fixtures ----
|
||||
|
||||
const rolesDir = join(new URL('../../..', import.meta.url).pathname, 'roles');
|
||||
const rootOf = agents => ({ state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents }, { rolesDir }) });
|
||||
const reviewer = () => JSON.parse(readFileSync(join(rolesDir, 'reviewer.json'), 'utf8'));
|
||||
const pinOf = (ref, definitions = {}) => definitionPin(ref, { definitions, rolesDir, readTemplate });
|
||||
const INC_A = 'a'.repeat(32), INC_B = 'b'.repeat(32);
|
||||
const docFor = (id, edit = d => d) => edit({ id, roles: {}, projects: { stack: {}, web: {} } });
|
||||
const record = (over = {}) => ({
|
||||
copyId: 'c'.repeat(32), orgIncarnation: INC_A, source: { level: 'root', name: 'rev', project: null },
|
||||
definition: pinOf('reviewer'), generation: 2, state: 'bound',
|
||||
services: { gitea: { slot: 'self', scopes: ['read:repository', 'write:issue'], resources: { projects: ['stack'] } },
|
||||
vikunja: { slot: 'self', scopes: { tasks: ['read_one'] }, resources: { projects: ['stack'] } } },
|
||||
decision: ID1, ...over,
|
||||
});
|
||||
const resolve = (over = {}) => {
|
||||
const snapshot = over.snapshot ?? materializeCopies({ orgId: 'acme', doc: docFor('acme'), root: rootOf({ rev: { definition: 'reviewer' } }), rolesDir });
|
||||
return resolveCopyBinding({ orgId: 'acme', incarnation: INC_A, snapshot, instance: 'rev', record: record(), pin: pinOf('reviewer'), role: reviewer(), projects: ['stack', 'web'], ...over });
|
||||
};
|
||||
|
||||
test('CB0 a bound record resolves to effective = role intersect approved, only on admitted projects', () => {
|
||||
const r = resolve();
|
||||
assert.equal(r.ok, true);
|
||||
// The role declares write:issue, write:repository and read:user; the owner approved less.
|
||||
assert.deepEqual(r.services.gitea, { scopes: ['write:issue', 'read:repository'], projects: ['stack'] });
|
||||
assert.deepEqual(r.services.vikunja, { scopes: { tasks: ['read_one'] }, projects: ['stack'] });
|
||||
assert.deepEqual(intersectScopes('gitea', ['write:repository', 'read:issue'], ['read:repository', 'write:issue']), ['read:issue', 'read:repository']);
|
||||
// A project no longer admitted drops out of the reach; none left, no binding.
|
||||
assert.equal(resolve({ projects: ['web'] }).code, 'credential-unbound');
|
||||
// Approved broader than the role (the role narrowed): never widened, refused.
|
||||
const wide = record(); wide.services.gitea.scopes = ['write:admin'];
|
||||
assert.equal(resolve({ record: wide }).ok, false);
|
||||
const extra = record(); extra.services.gitea.scopes = ['write:repository', 'write:organization'];
|
||||
assert.deepEqual([resolve({ record: extra }).code, resolve({ record: extra }).service], ['credential-scope-exceeded', 'gitea']);
|
||||
});
|
||||
|
||||
test('CB0 pending, partial and tombstoned records never resolve', () => {
|
||||
assert.equal(resolve({ record: record({ state: 'pending' }) }).code, 'credential-unbound');
|
||||
assert.equal(resolve({ record: record({ state: 'unbound', services: {} }) }).code, 'credential-unbound');
|
||||
const partial = record(); delete partial.services.vikunja;
|
||||
assert.deepEqual([resolve({ record: partial }).code, resolve({ record: partial }).service], ['credential-unbound', 'vikunja']);
|
||||
assert.equal(resolve({ record: undefined }).code, 'credential-unbound');
|
||||
});
|
||||
|
||||
test('CB0 identical root copies in two organizations never share a binding', () => {
|
||||
const root = rootOf({ rev: { definition: 'reviewer' } });
|
||||
const a = materializeCopies({ orgId: 'acme', doc: docFor('acme'), root, rolesDir });
|
||||
const b = materializeCopies({ orgId: 'beta', doc: docFor('beta'), root, rolesDir });
|
||||
assert.deepEqual({ ...a.copies.rev }, { ...b.copies.rev }, 'the same copy shape in both');
|
||||
assert.equal(resolve({ snapshot: a }).ok, true);
|
||||
// A's record copied into B carries A's incarnation.
|
||||
assert.equal(resolveCopyBinding({ orgId: 'beta', incarnation: INC_B, snapshot: b, instance: 'rev', record: record(), pin: pinOf('reviewer'), role: reviewer(), projects: ['stack'] }).code, 'credential-unbound');
|
||||
// A's snapshot never answers for B.
|
||||
assert.equal(resolveCopyBinding({ orgId: 'beta', incarnation: INC_A, snapshot: a, instance: 'rev', record: record(), pin: pinOf('reviewer'), role: reviewer(), projects: ['stack'] }).code, 'copy-unavailable');
|
||||
});
|
||||
|
||||
test('CB0 project dotted-name collisions never attach a record', () => {
|
||||
const root = rootOf({});
|
||||
// project "a.b" agent "c" and project "b" agent "c.a" both make instance c.a.b: both refuse.
|
||||
const both = materializeCopies({ orgId: 'acme', doc: docFor('acme', d => ({ ...d, projects: { 'a.b': { agents: { c: { definition: 'reviewer' } } }, b: { agents: { 'c.a': { definition: 'reviewer' } } } } })), root, rolesDir });
|
||||
assert.equal(both.copies['c.a.b'].state, 'refused');
|
||||
const old = record({ source: { level: 'project', name: 'c.a', project: 'b' }, services: { gitea: { slot: 'self', scopes: ['read:repository'], resources: { projects: ['b'] } } } });
|
||||
const args = { orgId: 'acme', incarnation: INC_A, instance: 'c.a.b', record: old, pin: pinOf('reviewer'), role: reviewer(), projects: ['a.b', 'b'] };
|
||||
assert.equal(resolveCopyBinding({ ...args, snapshot: both }).code, 'copy-refused');
|
||||
// Project b drops its agent; project a.b's "c" now owns c.a.b alone. b's record never attaches.
|
||||
const one = materializeCopies({ orgId: 'acme', doc: docFor('acme', d => ({ ...d, projects: { 'a.b': { agents: { c: { definition: 'reviewer' } } }, b: {} } })), root, rolesDir });
|
||||
assert.equal(one.copies['c.a.b'].state, 'unbound');
|
||||
assert.equal(resolveCopyBinding({ ...args, snapshot: one, record: { ...old, state: 'bound' } }).code, 'credential-unbound');
|
||||
// A root agent named like a project copy: the root record never attaches to the project copy.
|
||||
const proj = materializeCopies({ orgId: 'acme', doc: docFor('acme', d => ({ ...d, projects: { stack: { agents: { checker: { definition: 'reviewer' } } } } })), root, rolesDir });
|
||||
const rootRecord = record({ source: { level: 'root', name: 'checker.stack', project: null } });
|
||||
assert.equal(resolveCopyBinding({ ...args, instance: 'checker.stack', snapshot: proj, record: rootRecord, projects: ['stack'] }).code, 'credential-unbound');
|
||||
});
|
||||
|
||||
test('CB0 an organization instance shadows the copy; its record never resolves', () => {
|
||||
const snapshot = materializeCopies({ orgId: 'acme', doc: docFor('acme', d => ({ ...d, roles: { rev: { definition: 'reviewer' } } })), root: rootOf({ rev: { definition: 'reviewer' } }), rolesDir });
|
||||
assert.equal(Object.hasOwn(snapshot.copies, 'rev'), false);
|
||||
assert.equal(resolve({ snapshot }).code, 'copy-unavailable');
|
||||
});
|
||||
|
||||
test('CB0 a removed and recreated organization has a new incarnation; the old record never resolves', async t => {
|
||||
const base = mkdtempSync(join(tmpdir(), 'cb0-')); t.after(() => rmSync(base, { recursive: true, force: true }));
|
||||
const c = { configDir: join(base, 'config'), dataRoot: join(base, 'data'), instance: 'test' };
|
||||
mkdirSync(c.configDir, { mode: 0o700 }); mkdirSync(c.dataRoot, { mode: 0o700 });
|
||||
const first = await reserveOrg(c, 'acme');
|
||||
assert.match(first.incarnation, /^[0-9a-f]{32}$/);
|
||||
assert.notEqual((await reserveOrg(c, 'beta')).incarnation, first.incarnation);
|
||||
withRegistryWriter(c.configDir, (registry, publish) => { delete registry.orgs.acme; publish(); });
|
||||
rmSync(orgRoot(c.dataRoot, 'acme'), { recursive: true });
|
||||
const again = await reserveOrg(c, 'acme');
|
||||
assert.notEqual(again.incarnation, first.incarnation);
|
||||
assert.equal(orgIncarnation(await readRegistry(c), 'acme'), again.incarnation);
|
||||
assert.equal(resolve({ incarnation: again.incarnation, record: record({ orgIncarnation: first.incarnation }) }).code, 'credential-unbound');
|
||||
assert.equal(resolve({ incarnation: null }).code, 'credential-unbound', 'no incarnation, no binding');
|
||||
// An invalid incarnation in the registry refuses the registry.
|
||||
withRegistryWriter(c.configDir, (registry, publish) => { registry.orgs.acme.incarnation = 'x'; publish(); });
|
||||
await assert.rejects(readRegistry(c), { code: 'org-mismatch' });
|
||||
});
|
||||
|
||||
test('CB0 a reused source name with another definition or level never inherits a record', () => {
|
||||
// Root "rev" was a reviewer; it is removed and a new root "rev" is a coder.
|
||||
const snapshot = materializeCopies({ orgId: 'acme', doc: docFor('acme'), root: rootOf({ rev: { definition: 'coder' } }), rolesDir });
|
||||
const coder = JSON.parse(readFileSync(join(rolesDir, 'coder.json'), 'utf8'));
|
||||
assert.equal(resolve({ snapshot, pin: pinOf('coder'), role: coder }).code, 'credential-role-changed');
|
||||
// An org definition changed in place (same name, new rev or text) changes the pin.
|
||||
const defs = { d: { rev: 1, role: { template: 'reviewer' } } };
|
||||
const before = pinOf('org:d', defs), after = pinOf('org:d', { d: { ...defs.d, instructions: 'other' } });
|
||||
assert.ok(before && after && before.sha256 !== after.sha256);
|
||||
// The copyId is kept only with its own record: a record for another copyId does not move.
|
||||
assert.equal(resolve({ record: record({ source: { level: 'project', name: 'rev', project: 'stack' } }) }).code, 'credential-unbound');
|
||||
});
|
||||
|
||||
test('CB0 copyBindings schema: ids and scope names only, every refusal positional', () => {
|
||||
const ok = { rev: record() };
|
||||
assert.doesNotThrow(() => validateCopyBindings(ok));
|
||||
const cases = [
|
||||
{ rev: { ...record(), token: SECRET } },
|
||||
{ rev: { ...record(), services: { gitea: { ...record().services.gitea, file: '/x/token' } } } },
|
||||
{ rev: { ...record(), services: { gitea: { ...record().services.gitea, slot: '/srv/token' } } } },
|
||||
{ rev: { ...record(), copyId: SECRET } },
|
||||
{ rev: { ...record(), orgIncarnation: 'z' } },
|
||||
{ rev: { ...record(), generation: 0 } },
|
||||
{ rev: { ...record(), state: 'active' } },
|
||||
{ rev: { ...record(), source: { level: 'root', name: 'other', project: null } } },
|
||||
{ rev: { ...record(), state: 'unbound' } },
|
||||
{ rev: record(), other: { ...record(), source: { level: 'root', name: 'other', project: null } } },
|
||||
];
|
||||
for (const value of cases) {
|
||||
assert.throws(() => validateCopyBindings(value), e => e.name === 'BusinessError' && !e.message.includes(SECRET) && !e.message.includes('/'));
|
||||
}
|
||||
});
|
||||
|
||||
// ---- CB1: decision subtype, guarded writer ----
|
||||
|
||||
function setup(t, { incarnation = true, edit = d => d } = {}) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'cb1-'));
|
||||
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' } };
|
||||
edit(doc);
|
||||
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');
|
||||
if (!incarnation) withRegistryWriter(root, (registry, publish) => { delete registry.orgs.demo.incarnation; publish(); });
|
||||
})();
|
||||
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: v => { if (JSON.stringify(v).includes(SECRET)) throw Object.assign(new Error('x'), { code: 'definition-holds-credential' }); }, copies: id => snapshot.org === id ? snapshot : null });
|
||||
const bind = (services = GITEA, extra = {}) => ({ op: 'change', level: 'root', name: 'rev', reason: 'Bind the reviewer copy', binding: { services }, ...extra });
|
||||
const prepare = async (input = bind(), id = ID1, expiresAt = FUTURE) => { await ready; return service.prepare('demo', input, { id, expiresAt }); };
|
||||
const bytes = () => readFileSync(file);
|
||||
return { root, roles, file, writer, service, snapshot, bind, prepare, bytes, ready, ctx, dataRoot };
|
||||
}
|
||||
|
||||
test('CB1 owner binds and unbinds; the record holds ids only and stays pending; receipts are paths only', async t => {
|
||||
const f = setup(t);
|
||||
const p = await f.prepare();
|
||||
assert.equal(p.binding.instance, 'rev');
|
||||
assert.deepEqual(p.credentialLines, [{ service: 'gitea', scope: 'read:repository' }]);
|
||||
await f.service.apply('demo', p.id, { ...OWNER, digest: p.digest });
|
||||
const rec = f.writer.read('demo').document.copyBindings.rev;
|
||||
assert.equal(rec.state, 'pending');
|
||||
assert.equal(rec.generation, 1);
|
||||
assert.deepEqual(rec.services, { gitea: { slot: 'self', scopes: ['read:repository'], resources: { projects: ['stack'] } } });
|
||||
assert.deepEqual(rec.source, { level: 'root', name: 'rev', project: null });
|
||||
assert.equal(rec.orgIncarnation, orgIncarnation(await readRegistry(f.ctx), 'demo'));
|
||||
assert.deepEqual(rec.definition, definitionPin('reviewer', { rolesDir: f.roles, readTemplate }));
|
||||
assert.equal(rec.decision, p.id);
|
||||
const text = JSON.stringify(rec);
|
||||
for (const bad of [SECRET, f.root, '/', 'token']) assert.ok(!text.includes(bad), bad);
|
||||
const log = readFileSync(join(f.root, 'businesses/.history/demo/changes.jsonl'), 'utf8');
|
||||
assert.ok(log.includes(p.id)); assert.ok(log.includes('binding.apply'));
|
||||
assert.ok(!log.includes('read:repository'), 'paths only: the receipt holds no scope value');
|
||||
// The owner unbinds through the same decision kind; a tombstone stays with the same copyId.
|
||||
const u = await f.prepare(f.bind(null), ID2);
|
||||
await f.service.apply('demo', u.id, { ...OWNER, digest: u.digest });
|
||||
const tomb = f.writer.read('demo').document.copyBindings.rev;
|
||||
assert.deepEqual({ state: tomb.state, services: tomb.services, generation: tomb.generation, copyId: tomb.copyId }, { state: 'unbound', services: {}, generation: 2, copyId: rec.copyId });
|
||||
assert.ok(readFileSync(join(f.root, 'businesses/.history/demo/changes.jsonl'), 'utf8').includes('binding.unbind'));
|
||||
// Unbinding a tombstone refuses.
|
||||
await assert.rejects(f.prepare(f.bind(null), ID3), { code: 'credential-unbound' });
|
||||
});
|
||||
|
||||
test('CB1 a project copy binds only its own project; a role-exceeding request refuses, never trims', async t => {
|
||||
const f = setup(t);
|
||||
const project = (services, id) => f.prepare({ op: 'change', level: 'project', project: 'stack', name: 'checker', reason: 'Bind', binding: { services } }, id);
|
||||
const p = await project(GITEA, ID1);
|
||||
assert.equal(p.binding.instance, 'checker.stack');
|
||||
await assert.rejects(project({ gitea: { scopes: ['write:admin'], projects: ['stack'] } }, ID2), { code: 'invalid-request' });
|
||||
await assert.rejects(project({ gitea: { scopes: ['write:organization'], projects: ['stack'] } }, ID2), { code: 'credential-scope-exceeded' });
|
||||
await assert.rejects(project({ gitea: { scopes: ['read:repository'], projects: ['other'] } }, ID2), { code: 'credential-scope-exceeded' });
|
||||
await assert.rejects(f.prepare(f.bind({ gitea: { scopes: ['read:repository'], projects: ['stack'], token: SECRET } }), ID2), e => !JSON.stringify(e).includes(SECRET) && !e.message.includes(SECRET));
|
||||
// A copy the bus did not boot, and an org instance, are not copies.
|
||||
await assert.rejects(f.prepare({ ...f.bind(), name: 'nobody' }, ID2), { code: 'copy-unavailable' });
|
||||
await assert.rejects(f.prepare({ ...f.bind(), name: 'coder' }, ID2), { code: 'copy-unavailable' });
|
||||
// A binding is only ever a change of a root or project copy, with no role, route or credentials.
|
||||
for (const extra of [{ op: 'hire' }, { level: 'org' }, { route: { harness: 'pi', model: 'm' } }, { credentials: {} }]) {
|
||||
await assert.rejects(f.prepare({ ...f.bind(), ...extra }, ID2), { code: 'invalid-request' });
|
||||
}
|
||||
});
|
||||
|
||||
test('CB1 only the owner resolves: member with org.hire or decide, chief, arbiter, subject, tester and reader all fail', async t => {
|
||||
const plain = { binding: {}, flagged: [], credentialLines: [], level: 'root', id: ID1, name: 'rev' };
|
||||
const member = { ...OWNER, owner: false, instanceOwner: false };
|
||||
assert.throws(() => authorizeHire(plain, member), { code: 'human-required' });
|
||||
assert.throws(() => authorizeHire(plain, { ...member, instanceOwner: true }), { code: 'human-required' }, 'an instance operator alone is not the owner');
|
||||
assert.throws(() => authorizeHire(plain, { ...OWNER, rights: ['decide'] }), { code: 'right-required' });
|
||||
assert.throws(() => authorizeHire(plain, { ...OWNER, rights: [] }), { code: 'right-required' }, 'reader');
|
||||
for (const agent of ['chief', 'cto', 'rev', 'tester']) {
|
||||
// An agent, even one carrying an authority decision and the authority right, never resolves.
|
||||
assert.throws(() => authorizeHire(plain, { actor: agent, agent: true, rights: ['org.hire', 'decision.resolve.authority'], owner: true, authorityDecision: ID1, resolver: agent }), { code: 'human-required' });
|
||||
}
|
||||
assert.doesNotThrow(() => authorizeHire(plain, OWNER));
|
||||
// Through the service: each refused caller leaves the file byte-identical.
|
||||
const f = setup(t);
|
||||
const p = await f.prepare();
|
||||
const before = f.bytes();
|
||||
for (const caller of [member, { ...OWNER, rights: ['decide'] }, { ...OWNER, rights: [] },
|
||||
{ actor: 'chief', agent: true, rights: ['org.hire'], owner: true }, { actor: 'cto', agent: true, rights: ['decision.resolve.authority', 'org.hire'], authorityDecision: p.id, resolver: 'cto' },
|
||||
{ actor: 'rev', agent: true, rights: ['org.hire'] }, { actor: 'tester', agent: true, rights: ['org.hire'] }]) {
|
||||
await assert.rejects(f.service.apply('demo', p.id, { ...caller, digest: p.digest }));
|
||||
}
|
||||
assert.deepEqual(f.bytes(), before);
|
||||
// The writer refuses the tester and every agent identity even when told owner:true.
|
||||
const full = { ...JSON.parse(readFileSync(join(f.dataRoot, 'authority-proposals', `${p.id}.json`), 'utf8')), digest: p.digest };
|
||||
for (const actor of ['tester', 'chief', 'rev', 'checker.stack', 'reviewer', 'pm']) {
|
||||
assert.throws(() => f.writer.applyCopyBindingDecision('demo', full, { actor, owner: true }), { code: 'human-required' }, actor);
|
||||
}
|
||||
assert.throws(() => f.writer.applyCopyBindingDecision('demo', full, { actor: 'jason', owner: false }), { code: 'human-required' });
|
||||
assert.deepEqual(f.bytes(), before);
|
||||
});
|
||||
|
||||
test('CB1 generic writes never change copyBindings, whatever options they pass', async t => {
|
||||
const f = setup(t); await f.ready;
|
||||
const { document, revision } = f.writer.read('demo');
|
||||
const forged = { ...document, copyBindings: { rev: { ...record(), orgIncarnation: orgIncarnation(await readRegistry(f.ctx), 'demo'), state: 'bound' } } };
|
||||
assert.doesNotThrow(() => validateBusinessDocument(forged, f.file, { rolesDir: f.roles }), 'a valid document is still refused by the writer');
|
||||
const before = f.bytes();
|
||||
for (const options of [{}, { capability: Symbol('copy-binding-write') }, { capability: Symbol.for('copy-binding-write'), incarnation: forged.copyBindings.rev.orgIncarnation }, { guard: () => {} }]) {
|
||||
assert.throws(() => f.writer.write('demo', forged, { revision, actor: 'jason', ...options }), { code: 'organization-bindings-protected' });
|
||||
}
|
||||
assert.throws(() => f.writer.write('demo', old => ({ ...old, copyBindings: forged.copyBindings }), { revision, actor: 'jason' }), { code: 'organization-bindings-protected' });
|
||||
assert.deepEqual(f.bytes(), before);
|
||||
// Once a record exists, a generic write can neither remove nor edit it.
|
||||
const p = await f.prepare(); await f.service.apply('demo', p.id, { ...OWNER, digest: p.digest });
|
||||
const now = f.writer.read('demo');
|
||||
const { copyBindings: _, ...stripped } = now.document;
|
||||
assert.throws(() => f.writer.write('demo', stripped, { revision: now.revision, actor: 'jason' }), { code: 'organization-bindings-protected' });
|
||||
const promoted = structuredClone(now.document); promoted.copyBindings.rev.state = 'bound';
|
||||
assert.throws(() => f.writer.write('demo', promoted, { revision: now.revision, actor: 'jason' }), { code: 'organization-bindings-protected' });
|
||||
// An unrelated write keeps the record.
|
||||
const edited = structuredClone(now.document); edited.vars['tracker.pollSeconds'] = 61;
|
||||
f.writer.write('demo', edited, { revision: now.revision, actor: 'jason' });
|
||||
assert.deepEqual(f.writer.read('demo').document.copyBindings, now.document.copyBindings);
|
||||
});
|
||||
|
||||
test('CB1 stale revision, digest or generation, expiry, replay and a wrong incarnation activate nothing', async t => {
|
||||
const f = setup(t);
|
||||
// Digest.
|
||||
const p = await f.prepare();
|
||||
const before = f.bytes();
|
||||
await assert.rejects(f.service.apply('demo', p.id, { ...OWNER, digest: '0'.repeat(64) }), { code: 'decision-stale' });
|
||||
// Expiry.
|
||||
await assert.rejects(f.service.apply('demo', p.id, { ...OWNER, digest: p.digest, now: () => Date.parse('2099-06-01T00:00:00Z') }), { code: 'decision-expired' });
|
||||
assert.deepEqual(f.bytes(), before);
|
||||
// Revision: any change to the file after the proposal.
|
||||
const q = await f.prepare(f.bind(), ID2);
|
||||
const r = f.writer.read('demo'), edited = structuredClone(r.document); edited.vars['tracker.pollSeconds'] = 61;
|
||||
f.writer.write('demo', edited, { revision: r.revision, actor: 'jason' });
|
||||
await assert.rejects(f.service.apply('demo', q.id, { ...OWNER, digest: q.digest }), { code: 'decision-stale' });
|
||||
assert.equal(f.writer.read('demo').document.copyBindings, undefined);
|
||||
// Replay: applying the same approval twice changes nothing the second time.
|
||||
const s = await f.prepare(f.bind(), ID3);
|
||||
await f.service.apply('demo', s.id, { ...OWNER, digest: s.digest });
|
||||
const once = f.bytes();
|
||||
await assert.rejects(f.service.apply('demo', s.id, { ...OWNER, digest: s.digest }), { code: 'decision-stale' });
|
||||
const full = { ...JSON.parse(readFileSync(join(f.dataRoot, 'authority-proposals', `${s.id}.json`), 'utf8')), digest: s.digest };
|
||||
// Generation: the writer refuses a proposal at an old generation even with a fresh revision.
|
||||
assert.throws(() => f.writer.applyCopyBindingDecision('demo', { ...full, revision: f.writer.read('demo').revision }, { actor: 'jason', owner: true }), { code: 'credential-binding-changed' });
|
||||
assert.deepEqual(f.bytes(), once);
|
||||
// Wrong incarnation: the organization was recreated under the same id after approval.
|
||||
const u = await f.prepare(f.bind(null), '44444444-4444-4444-8444-444444444444');
|
||||
withRegistryWriter(f.root, (registry, publish) => { registry.orgs.demo.incarnation = 'f'.repeat(32); publish(); });
|
||||
await assert.rejects(f.service.apply('demo', u.id, { ...OWNER, digest: u.digest }), { code: 'decision-stale' });
|
||||
const uf = { ...JSON.parse(readFileSync(join(f.dataRoot, 'authority-proposals', `${u.id}.json`), 'utf8')), digest: u.digest };
|
||||
assert.throws(() => f.writer.applyCopyBindingDecision('demo', uf, { actor: 'jason', owner: true }), { code: 'decision-stale' });
|
||||
assert.deepEqual(f.bytes(), once);
|
||||
// A changed definition pin refuses too.
|
||||
assert.throws(() => f.writer.applyCopyBindingDecision('demo', { ...uf, binding: { ...uf.binding, orgIncarnation: 'f'.repeat(32), definition: { ...uf.binding.definition, sha256: '0'.repeat(64) } } }, { actor: 'jason', owner: true }), { code: 'credential-role-changed' });
|
||||
// A binding is never reversed through the AU inverse, and never adjusted.
|
||||
await assert.rejects(f.service.reverse('demo', s.id, OWNER), { code: 'decision-stale' });
|
||||
await assert.rejects(f.service.check('demo', u.id, { ...OWNER, digest: u.digest, adjust: { role: {} } }), { code: 'invalid-request' });
|
||||
});
|
||||
|
||||
test('CB1 a legacy organization gets its incarnation at the first proposal, under the registry lock', async t => {
|
||||
const f = setup(t, { incarnation: false });
|
||||
await f.ready;
|
||||
assert.equal(orgIncarnation(await readRegistry(f.ctx), 'demo'), null);
|
||||
const p = await f.prepare();
|
||||
const inc = orgIncarnation(await readRegistry(f.ctx), 'demo');
|
||||
assert.match(inc, /^[0-9a-f]{32}$/);
|
||||
assert.equal(p.binding.orgIncarnation, inc);
|
||||
assert.equal(ensureOrgIncarnation(f.root, 'demo'), inc, 'minted once');
|
||||
assert.equal(ensureOrgIncarnation(f.root, 'nobody'), null);
|
||||
});
|
||||
|
||||
test('CB1 a pending or partial binding never launches the copy', async t => {
|
||||
const f = setup(t);
|
||||
const p = await f.prepare();
|
||||
await f.service.apply('demo', p.id, { ...OWNER, digest: p.digest });
|
||||
const business = loadWithCopies('demo', { dir: f.root, rolesDir: f.roles, snapshot: f.snapshot });
|
||||
assert.equal(copyRefusal(business, 'rev').code, 'credential-unbound');
|
||||
assert.equal(Object.hasOwn(business.roles, 'rev'), false);
|
||||
const rec = business.copyBindings.rev;
|
||||
assert.equal(rec.state, 'pending');
|
||||
const pin = definitionPin('reviewer', { rolesDir: f.roles, readTemplate });
|
||||
const role = JSON.parse(readFileSync(join(f.roles, 'reviewer.json'), 'utf8'));
|
||||
const args = { orgId: 'demo', incarnation: rec.orgIncarnation, snapshot: f.snapshot, instance: 'rev', pin, role, projects: ['stack'] };
|
||||
assert.equal(resolveCopyBinding({ ...args, record: rec }).code, 'credential-unbound');
|
||||
// Even forced to bound, gitea alone is partial for a role that also needs vikunja.
|
||||
assert.deepEqual(resolveCopyBinding({ ...args, record: { ...rec, state: 'bound' } }), { ok: false, code: 'credential-unbound', service: 'vikunja' });
|
||||
// A pending record that covers every service the role needs is still not a binding; bound, it is.
|
||||
const whole = { ...rec, services: { ...rec.services, vikunja: { slot: 'self', scopes: { tasks: ['read_one'] }, resources: { projects: ['stack'] } } } };
|
||||
assert.equal(resolveCopyBinding({ ...args, record: { ...whole, state: 'bound' } }).ok, true);
|
||||
assert.deepEqual(resolveCopyBinding({ ...args, record: whole }), { ok: false, code: 'credential-unbound', service: 'gitea' });
|
||||
});
|
||||
|
||||
test('CB1 no proposal, record, receipt or refusal names a token or a path', async t => {
|
||||
const f = setup(t);
|
||||
const p = await f.prepare();
|
||||
await f.service.apply('demo', p.id, { ...OWNER, digest: p.digest });
|
||||
const texts = [JSON.stringify(p), readFileSync(join(f.root, 'businesses/.history/demo/changes.jsonl'), 'utf8'),
|
||||
...readdirSync(join(f.dataRoot, 'authority-proposals')).map(n => readFileSync(join(f.dataRoot, 'authority-proposals', n), 'utf8'))];
|
||||
for (const text of texts) {
|
||||
assert.ok(!text.includes(SECRET)); assert.ok(!text.includes(join(f.root, 'secrets')));
|
||||
}
|
||||
const refusals = [];
|
||||
for (const args of [[f.bind({ gitea: { scopes: ['write:organization'], projects: ['stack'] } }), ID2], [{ ...f.bind(), name: 'gone' }, ID3]]) {
|
||||
await f.prepare(...args).catch(e => refusals.push(e));
|
||||
}
|
||||
const t2 = { ...JSON.parse(readFileSync(join(f.dataRoot, 'authority-proposals', `${p.id}.json`), 'utf8')) };
|
||||
try { f.writer.applyCopyBindingDecision('demo', { ...t2, revision: f.writer.read('demo').revision }, { actor: 'chief', owner: true }); } catch (e) { refusals.push(e); }
|
||||
assert.equal(refusals.length, 3);
|
||||
for (const e of refusals) assert.ok(!e.message.includes('/') && !e.message.includes(SECRET), e.message);
|
||||
assert.equal(refusals[2].message, 'Only the organization owner can approve credential binding.');
|
||||
void sha;
|
||||
});
|
||||
|
||||
test('CB1 fix: the free-text reason is never written to a binding proposal', async t => {
|
||||
const f = setup(t);
|
||||
const leak = '/home/someone/.config/mosaic-dev/secrets/gitea tok-fragment-9f8e';
|
||||
const p = await f.prepare(f.bind(GITEA, { reason: `Bind; see ${leak}` }));
|
||||
const stored = readFileSync(join(f.dataRoot, 'authority-proposals', `${p.id}.json`), 'utf8');
|
||||
assert.ok(!stored.includes(leak) && !stored.includes('tok-fragment') && !stored.includes('"reason"'), 'no reason text on disk');
|
||||
assert.deepEqual(Object.keys(JSON.parse(stored).request).sort(), ['binding', 'level', 'name', 'op']);
|
||||
assert.ok(!JSON.stringify(p).includes('tok-fragment'));
|
||||
// The proposal still applies on its digest.
|
||||
await f.service.apply('demo', p.id, { ...OWNER, digest: p.digest });
|
||||
assert.equal(f.writer.read('demo').document.copyBindings.rev.state, 'pending');
|
||||
assert.ok(!readFileSync(join(f.root, 'businesses/.history/demo/changes.jsonl'), 'utf8').includes('tok-fragment'));
|
||||
});
|
||||
|
||||
test('CB1 fix: a root copy removed or replaced since boot refuses at prepare, at apply and before publication', async t => {
|
||||
const receipts = root => join(root, 'agents-receipts.jsonl');
|
||||
const add = (root, row) => writeFileSync(receipts(root), JSON.stringify(row) + '\n', { flag: 'a', mode: 0o600 });
|
||||
// Removed since boot: prepare refuses instance-fired; replaced: copy-stale.
|
||||
for (const [verb, code] of [['root.agent.remove', 'instance-fired'], ['root.agent.set', 'copy-stale']]) {
|
||||
const f = setup(t); await f.ready;
|
||||
add(f.root, { agent: 'rev', verb, at: FUTURE });
|
||||
await assert.rejects(f.prepare(), { code }, verb);
|
||||
let saved = []; try { saved = readdirSync(join(f.dataRoot, 'authority-proposals')); } catch (e) { if (e.code !== 'ENOENT') throw e; }
|
||||
assert.deepEqual(saved, [], verb);
|
||||
}
|
||||
// Prepared while fresh, then the root copy is removed: apply refuses and writes nothing.
|
||||
{
|
||||
const f = setup(t); const p = await f.prepare(); const before = f.bytes();
|
||||
add(f.root, { agent: 'rev', verb: 'root.agent.remove', at: FUTURE });
|
||||
await assert.rejects(f.service.apply('demo', p.id, { ...OWNER, digest: p.digest }), { code: 'instance-fired' });
|
||||
assert.deepEqual(f.bytes(), before);
|
||||
}
|
||||
// The change lands after checkBinding, under the lock: the publication fence still refuses.
|
||||
{
|
||||
const f = setup(t); const p = await f.prepare(); const before = f.bytes();
|
||||
let wrote = false;
|
||||
const late = () => { if (!wrote) { wrote = true; add(f.root, { agent: 'rev', verb: 'root.agent.set', at: FUTURE }); } };
|
||||
await assert.rejects(f.service.apply('demo', p.id, { ...OWNER, digest: p.digest, beforeWrite: late }), { code: 'copy-stale' });
|
||||
assert.equal(wrote, true);
|
||||
assert.deepEqual(f.bytes(), before);
|
||||
}
|
||||
// A receipt for another root agent leaves this copy fresh; an unreadable receipts file refuses.
|
||||
{
|
||||
const f = setup(t); await f.ready;
|
||||
add(f.root, { agent: 'other', verb: 'root.agent.remove', at: FUTURE });
|
||||
const p = await f.prepare();
|
||||
writeFileSync(receipts(f.root), 'not json\n', { mode: 0o600 });
|
||||
await assert.rejects(f.service.apply('demo', p.id, { ...OWNER, digest: p.digest }), { code: 'root-policy-unreadable' });
|
||||
}
|
||||
// A project copy does not read root receipts.
|
||||
{
|
||||
const f = setup(t); await f.ready;
|
||||
add(f.root, { agent: 'checker', verb: 'root.agent.remove', at: FUTURE });
|
||||
const p = await f.prepare({ op: 'change', level: 'project', project: 'stack', name: 'checker', reason: 'Bind', binding: { services: GITEA } });
|
||||
await f.service.apply('demo', p.id, { ...OWNER, digest: p.digest });
|
||||
assert.equal(f.writer.read('demo').document.copyBindings['checker.stack'].state, 'pending');
|
||||
}
|
||||
});
|
||||
|
||||
test('CB1 the org service refuses copyBindings on create and on a whole-document update', async t => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'cb1-svc-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
const c = { configDir: join(root, 'config'), dataRoot: join(root, 'data'), instance: 'test', principal: { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner' } };
|
||||
mkdirSync(c.configDir, { mode: 0o700 }); mkdirSync(c.dataRoot, { mode: 0o700 });
|
||||
const forged = { rev: { ...record(), state: 'bound' } };
|
||||
await assert.rejects(createOrg(c, 'alpha', { ...await templateRender('alpha'), copyBindings: forged }), { code: 'organization-bindings-protected' });
|
||||
await createOrg(c, 'alpha', await templateRender('alpha'));
|
||||
const current = await showOrg(c, 'alpha');
|
||||
await assert.rejects(updateOrg(c, 'alpha', { ...current.doc, copyBindings: forged }, { ifRevision: current.revision }), { code: 'organization-bindings-protected' });
|
||||
assert.equal((await showOrg(c, 'alpha')).doc.copyBindings, undefined);
|
||||
await updateOrg(c, 'alpha', current.doc, { ifRevision: current.revision });
|
||||
});
|
||||
|
||||
test('CB1 fix: a root copy binds only projects whose union still admits it', async t => {
|
||||
const f = setup(t, { edit: doc => { doc.projects.web = { root: doc.projects.stack.root }; doc.projects.stack.agents.rev = { exclude: true }; } });
|
||||
// stack excludes rev: a request naming it refuses whole, never trimmed to web.
|
||||
await assert.rejects(f.prepare(f.bind({ gitea: { scopes: ['read:repository'], projects: ['stack', 'web'] } })), { code: 'credential-scope-exceeded' });
|
||||
await assert.rejects(f.prepare(f.bind({ gitea: { scopes: ['read:repository'], projects: ['stack'] } }, {}), ID2), { code: 'credential-scope-exceeded' });
|
||||
// web still admits it.
|
||||
const p = await f.prepare(f.bind({ gitea: { scopes: ['read:repository'], projects: ['web'] } }), ID3);
|
||||
assert.deepEqual(p.binding.after.gitea.resources.projects, ['web']);
|
||||
});
|
||||
|
||||
test('CB1 fix: a named instance added after boot shadows the copy at proposal time', async t => {
|
||||
const f = setup(t); await f.ready;
|
||||
const r = f.writer.read('demo'), edited = structuredClone(r.document);
|
||||
const like = Object.values(edited.roles).find(e => e.definition === 'reviewer');
|
||||
edited.roles.rev = { ...structuredClone(like), tracker: { bot: 'bot-demo-rev', botId: 977 } };
|
||||
f.writer.write('demo', edited, { revision: r.revision, actor: 'jason' });
|
||||
await assert.rejects(f.prepare(), { code: 'copy-unavailable' });
|
||||
});
|
||||
|
||||
test('CB1 fix: the loader refuses a copyBindings record holding a token, naming neither the value nor a path', t => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'cb1-load-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
const roles = rolesCopy(root);
|
||||
const doc = { ...businessDoc(root, 'demo'), copyBindings: { rev: { ...record(), state: 'pending', token: SECRET } } };
|
||||
const file = join(root, 'businesses/demo.json');
|
||||
assert.throws(() => validateBusinessDocument(doc, file, { rolesDir: roles }), e => e.name === 'BusinessError' && !e.message.includes(SECRET) && !e.message.includes(root));
|
||||
// The same document without the token loads.
|
||||
const { token: _, ...clean } = doc.copyBindings.rev;
|
||||
validateBusinessDocument({ ...doc, copyBindings: { rev: clean } }, file, { rolesDir: roles });
|
||||
});
|
||||
@@ -18,6 +18,7 @@
|
||||
// POST /api/orgs/ID/setup/bus C3 busStart mosaic bus start --detach
|
||||
// POST /api/orgs/ID/restart/bus C3 busRestart mosaic bus restart (F3; busStart when stopped;
|
||||
// busRevive for a host that died, dev-local owner only, D2)
|
||||
// POST /api/orgs/ID/stop/bus C3 busStop mosaic bus stop (a stopped bus answers state stopped)
|
||||
//
|
||||
// GET /api/orgs (the list) and other /api/orgs/ID/... routes are S5's; this
|
||||
// handler returns false for them.
|
||||
@@ -35,7 +36,7 @@ const ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
||||
const KEY = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
||||
const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
|
||||
const MAX_BODY = 64 * 1024;
|
||||
const ROUTE = /^\/api\/orgs\/([^/]+)\/(admin|setup|delete|archive|restore|restart)(?:\/(queue|bus|project\/([^/]+)|records\/([^/]+)))?$/;
|
||||
const ROUTE = /^\/api\/orgs\/([^/]+)\/(admin|setup|delete|archive|restore|restart|stop)(?:\/(queue|bus|project\/([^/]+)|records\/([^/]+)))?$/;
|
||||
// The org-template placeholder (packages/organization/src/org-service.mjs templateRender).
|
||||
export const placeholderRoot = (id, project) => `/__mosaic_org__/${id}/projects/${project}`;
|
||||
// Project fields the server owns. The browser never sees or sends them. `agents` (#1873 A1) is
|
||||
@@ -54,6 +55,7 @@ export function verbFor(step, id, opts = {}) {
|
||||
if (step === 'records') return `mosaic project init ${id} ${opts.project}`;
|
||||
if (step === 'bus') return `mosaic bus start ${id} --dev-local-owner --detach`;
|
||||
if (step === 'bus-restart') return `mosaic bus restart ${id}`;
|
||||
if (step === 'bus-stop') return `mosaic bus stop ${id}`;
|
||||
if (step === 'bus-revive') return `mosaic bus recover ${id}; mosaic bus start ${id} --dev-local-owner --detach`;
|
||||
throw new Error(`unknown step ${step}`);
|
||||
}
|
||||
@@ -246,6 +248,10 @@ export function toCanonical(id, doc, stored = null) {
|
||||
};
|
||||
for (const [name, role] of Object.entries(stored?.roles ?? {})) if (out.roles?.[name] && role?.credentials) { out.roles[name].credentials ??= {}; restore(out.roles[name].credentials, role.credentials); }
|
||||
if (stored?.tracker?.sync?.credentials && out.tracker?.sync) { out.tracker.sync.credentials ??= {}; restore(out.tracker.sync.credentials, stored.tracker.sync.credentials); }
|
||||
// #1873 CB1: copy bindings are server-held on an update. Only an owner-approved binding decision
|
||||
// changes them, so the stored ones go back whatever the browser sent. A create passes the
|
||||
// browser's value through and the service refuses any binding there.
|
||||
if (stored) { if (Object.hasOwn(stored, 'copyBindings')) out.copyBindings = structuredClone(stored.copyBindings); else delete out.copyBindings; }
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -518,6 +524,7 @@ async function route(req, res, { path, search, org, admin, principal, write, log
|
||||
try { return json(res, 200, await readSetup(admin, ctx, id)); } catch (e) { return refusal(res, e, { step: 'setup', id }); }
|
||||
}
|
||||
if (kind === 'restart') return restartBus(req, res, { sub, write, id, ctx, service, admin, log, trail, by });
|
||||
if (kind === 'stop') return stopBus(req, res, { sub, write, id, ctx, service, admin, log, trail, by });
|
||||
if (kind !== 'setup' || !sub || !write) return json(res, 404, { error: 'not found' });
|
||||
|
||||
// Every setup write reads the step back first and never overwrites.
|
||||
@@ -609,6 +616,64 @@ async function restartBus(req, res, { sub, write, id, ctx, service, admin, log,
|
||||
return json(res, 200, { outcome: 'done', step, restarted: running, healthy, receipt: forReceipt(ctx, receipt), verb: running ? verbFor('bus-restart', id) : verbFor('bus', id) });
|
||||
}
|
||||
|
||||
// Stop bus: the same owner, origin, --send and trail rules as Restart bus. C3 busStop sends SIGTERM
|
||||
// to the proven host and waits for it to exit; the host's close() removes host.json and host.lock,
|
||||
// and the broker's store removes writer.lock, so a clean stop leaves no lock behind (an offline
|
||||
// migrate-schema run can follow). The bus state is read back after the stop: a host or lock still
|
||||
// there, or state that does not check out, is a failure, not a done receipt. A host whose state
|
||||
// cannot be proven refuses before anything changes; there is no recovery path here, unlike Restart
|
||||
// bus on the dev Console. A bus that is already stopped answers done with state stopped.
|
||||
async function stopBus(req, res, { sub, write, id, ctx, service, admin, log, trail, by }) {
|
||||
const step = 'bus-stop';
|
||||
if (sub !== 'bus' || !write) return json(res, 404, { error: 'not found' });
|
||||
const body = await readBody(req); strictKeys(body, []);
|
||||
try { await service.showOrg(ctx, id); } catch (e) { return refusal(res, e, { step, id }); }
|
||||
const bus = await need(admin, 'bus', res, step); if (!bus) return;
|
||||
if (typeof bus.busStop !== 'function') return json(res, 503, { error: 'not-configured', step, message: 'bus control cannot stop a bus on this Console yet' });
|
||||
if (!trail) return json(res, 503, { error: 'trail-unavailable', step, message: 'this Console has no action trail, so it does not stop buses' });
|
||||
// The dev Console's start-up revive may be bringing this bus back; the press acts on the result.
|
||||
await revivePending(id);
|
||||
let status;
|
||||
try { status = await bus.busStatus(ctx, id); }
|
||||
catch (e) {
|
||||
if (['org-unknown', 'org-mismatch', 'org-unavailable', 'org-archived'].includes(e?.code)) return refusal(res, e, { step, id });
|
||||
if (isCliError(e)) {
|
||||
// Refused before anything changed, but the owner asked: the trail records the attempt.
|
||||
try { trail({ by, action: 'bus.stop', org: id, outcome: 'refused', running: null }); } catch { log(`org-admin: ${id} bus stop: trail write failed after refused`); }
|
||||
return json(res, 409, { error: 'bus-refused', step, message: `${plainMessage(ctx, e.message)}. Inspect it with mosaic bus status ${id}; mosaic bus recover ${id} clears a host that died.` });
|
||||
}
|
||||
return refusal(res, e, { step, id });
|
||||
}
|
||||
const running = Number.isSafeInteger(status?.pid);
|
||||
try { trail({ by, action: 'bus.stop', org: id, outcome: 'requested', running }); }
|
||||
catch { return json(res, 500, { error: 'trail-unavailable', step, message: 'the action trail could not be written, so nothing was stopped' }); }
|
||||
const note = outcome => { try { trail({ by, action: 'bus.stop', org: id, outcome }); } catch { log(`org-admin: ${id} bus stop: trail write failed after ${outcome}`); } };
|
||||
if (!running) {
|
||||
note('done');
|
||||
return json(res, 200, { outcome: 'done', step, stopped: false, state: 'stopped', receipt: { org: id, stopped: false }, verb: verbFor('bus-stop', id) });
|
||||
}
|
||||
let receipt;
|
||||
try { receipt = await bus.busStop(ctx, id); }
|
||||
catch (e) {
|
||||
// Only exit 3 comes before the signal; a timeout or an unexpected error may follow SIGTERM.
|
||||
note(isCliError(e) && e.exitCode === 3 ? 'refused' : 'failed');
|
||||
if (!isCliError(e)) return refusal(res, e, { step, id, unknownOk: true });
|
||||
return json(res, 409, { error: e.exitCode === 3 ? 'bus-refused' : 'bus-failed', step, message: `${plainMessage(ctx, e.message)}. Inspect it with mosaic bus status ${id}.` });
|
||||
}
|
||||
// Read the state back: the stop is done only when no host and no lock is left.
|
||||
let after = null, left = 'a bus host still runs';
|
||||
try { after = await bus.busStatus(ctx, id); }
|
||||
catch (e) { if (!isCliError(e)) { note('failed'); return refusal(res, e, { step, id, unknownOk: true }); } left = plainMessage(ctx, e.message); }
|
||||
if (!after || Number.isSafeInteger(after.pid)) {
|
||||
note('failed');
|
||||
return json(res, 409, { error: 'bus-failed', step, message: `the bus host was stopped, but ${left}. Inspect it with mosaic bus status ${id}; mosaic bus recover ${id} clears a host that died.` });
|
||||
}
|
||||
note('done');
|
||||
log(`org-admin: ${id} bus stopped`);
|
||||
// A host that exited on its own between the read and the stop was not stopped by this press.
|
||||
return json(res, 200, { outcome: 'done', step, stopped: receipt?.stopped === true, state: 'stopped', receipt: forReceipt(ctx, { org: id, ...receipt }), verb: verbFor('bus-stop', id) });
|
||||
}
|
||||
|
||||
// The dev-local owner exactly (packages/cli/src/dev-local-owner.mjs). A signed-in session carries
|
||||
// its provider's issuer, so no SSO user matches.
|
||||
const isDevOwner = by => by?.provider === DEV_OWNER.provider && by.iss === DEV_OWNER.iss && by.sub === DEV_OWNER.sub;
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
const clock = () => new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||
let config = null, boot = null, reconnecting = false, planned = false;
|
||||
let restartState = 'idle', restartReceipt = '', busReceipt = '', busBusy = false;
|
||||
let restartState = 'idle', restartReceipt = '', busReceipt = '', busBusy = false, busAction = 'restart';
|
||||
|
||||
const readConfig = () => nativeFetch('/api/config', { cache: 'no-store', redirect: 'manual' })
|
||||
.then(r => (r.type === 'opaqueredirect' ? null : r.ok ? r.json() : null));
|
||||
@@ -119,11 +119,17 @@
|
||||
else if (e.target.id === 'console-restart-go' && restartState === 'confirm') restartConsole();
|
||||
});
|
||||
|
||||
// The org bus restart control, offered on the organization's own pages to its owner.
|
||||
// The org bus restart control, offered on the organization's own pages to its owner. With
|
||||
// { stop: true } (the organization header) a Stop bus button sits beside it: one press, like
|
||||
// Restart bus, sharing its receipt and busy state. glyph is the caller's own icon markup, kept
|
||||
// inside the restart button so it stays on the button whatever width the receipt takes.
|
||||
const busAllowed = () => !!window.MosaicOrg && config?.orgSetup === true;
|
||||
function busButton(label = 'Restart bus') {
|
||||
function busButton(label = 'Restart bus', { stop = false, glyph = '' } = {}) {
|
||||
if (!busAllowed()) return '';
|
||||
return `<span class="bus-restart"><button type="button" class="btn" data-bus-restart data-label="${esc(label)}"${busBusy ? ' disabled' : ''}>${esc(busBusy ? 'Restarting…' : label)}</button> <span role="status" data-bus-restart-receipt>${esc(busReceipt)}</span></span>`;
|
||||
const off = busBusy ? ' disabled' : '';
|
||||
const restart = `<button type="button" class="btn" data-bus-restart data-label="${esc(label)}"${stop ? ' data-stop' : ''}${off}>${glyph}${esc(busBusy && busAction === 'restart' ? 'Restarting…' : label)}</button>`;
|
||||
const buttons = stop ? `<span class="bus-buttons">${restart} <button type="button" class="btn" data-bus-stop${off}>${busBusy && busAction === 'stop' ? 'Stopping…' : 'Stop bus'}</button></span>` : restart;
|
||||
return `<span class="bus-restart">${buttons} <span role="status" data-bus-restart-receipt>${esc(busReceipt)}</span></span>`;
|
||||
}
|
||||
async function attachBus(box, label) {
|
||||
await ready;
|
||||
@@ -133,14 +139,16 @@
|
||||
box.insertAdjacentHTML('beforeend', ` ${busButton(label)}`);
|
||||
}
|
||||
const paintBus = () => document.querySelectorAll('.bus-restart').forEach(el => {
|
||||
const label = el.querySelector('[data-bus-restart]')?.dataset.label;
|
||||
el.outerHTML = busButton(label);
|
||||
const button = el.querySelector('[data-bus-restart]');
|
||||
el.outerHTML = busButton(button?.dataset.label, { stop: button?.hasAttribute('data-stop'), glyph: button?.querySelector('svg')?.outerHTML || '' });
|
||||
});
|
||||
document.addEventListener('click', async e => {
|
||||
const button = e.target.closest?.('[data-bus-restart]');
|
||||
const button = e.target.closest?.('[data-bus-restart],[data-bus-stop]');
|
||||
if (!button || button.disabled || busBusy || !busAllowed()) return;
|
||||
const id = window.MosaicOrg.id;
|
||||
busAction = button.hasAttribute('data-bus-stop') ? 'stop' : 'restart';
|
||||
busBusy = true; busReceipt = ''; paintBus();
|
||||
if (busAction === 'stop') return stopBus(id);
|
||||
try {
|
||||
const response = await nativeFetch(`/api/orgs/${encodeURIComponent(id)}/restart/bus`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}', cache: 'no-store', redirect: 'manual' });
|
||||
if (response.type === 'opaqueredirect') throw new Error('Sign in again, then retry.');
|
||||
@@ -170,5 +178,23 @@
|
||||
} finally { busBusy = false; paintBus(); }
|
||||
});
|
||||
|
||||
// Stop bus: the bus host stops cleanly and leaves no lock behind. An already stopped bus answers
|
||||
// done with state stopped. The page reads the list and its send flags again, as after a restart.
|
||||
async function stopBus(id) {
|
||||
try {
|
||||
const response = await nativeFetch(`/api/orgs/${encodeURIComponent(id)}/stop/bus`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}', cache: 'no-store', redirect: 'manual' });
|
||||
if (response.type === 'opaqueredirect') throw new Error('Sign in again, then retry.');
|
||||
const body = await response.json();
|
||||
if (!response.ok || body.outcome !== 'done' || body.step !== 'bus-stop' || body.state !== 'stopped') throw new Error(body.message || 'The stop was refused. Nothing was retried.');
|
||||
busReceipt = body.stopped ? `Bus stopped at ${clock()}. Restart bus starts it again.` : `The bus was already stopped at ${clock()}. Nothing changed.`;
|
||||
$('bus-restart-done')?.remove();
|
||||
await Promise.resolve(window.MosaicOrg.refreshList?.()).catch(() => {});
|
||||
const fresh = await window.fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => (r.ok ? r.json() : null)).catch(() => null);
|
||||
if (fresh) { config = fresh; document.dispatchEvent(new CustomEvent('mosaic-config', { detail: fresh })); }
|
||||
} catch (error) {
|
||||
busReceipt = error instanceof SyntaxError || error?.name === 'TypeError' ? 'Outcome unknown. Check the bus with mosaic bus status before retrying.' : error.message;
|
||||
} finally { busBusy = false; paintBus(); }
|
||||
}
|
||||
|
||||
window.MosaicConsole = Object.freeze({ ready, settingsMarkup, busButton, attachBus, get busRestart() { return busAllowed(); }, get config() { return config; } });
|
||||
})();
|
||||
@@ -431,16 +431,16 @@ html[data-organizations] .ws-org-row .ws-dot{font-size:12.5px;font-weight:500}
|
||||
html[data-organizations] .ws-org-row .ws-dot.s-offline,html[data-organizations] .ws-org-row .ws-dot.s-error{color:var(--text)}
|
||||
html[data-organizations] .ws-org-row .ws-dot.s-offline b{color:var(--muted)}
|
||||
html[data-organizations] .ws-org-row .ws-dot.s-error b{color:var(--danger)}
|
||||
html[data-organizations] .ws-btn,html[data-organizations] .ws-busctl [data-bus-restart]{display:inline-flex;align-items:center;gap:6px;min-height:0;border:1px solid var(--line);background:var(--surface);border-radius:var(--r);padding:4px 10px;font:600 13px/1.4 var(--font);color:var(--strong);text-decoration:none;white-space:nowrap;cursor:pointer;box-shadow:none}
|
||||
html[data-organizations] .ws-btn:hover:not(:disabled),html[data-organizations] .ws-busctl [data-bus-restart]:hover:not(:disabled){background:var(--raised)}
|
||||
html[data-organizations] .ws-btn:disabled,html[data-organizations] .ws-busctl [data-bus-restart]:disabled{color:var(--muted);cursor:not-allowed;opacity:1}
|
||||
html[data-organizations] .ws-btn,html[data-organizations] .ws-busctl [data-bus-restart],html[data-organizations] .ws-busctl [data-bus-stop]{display:inline-flex;align-items:center;gap:6px;min-height:0;border:1px solid var(--line);background:var(--surface);border-radius:var(--r);padding:4px 10px;font:600 13px/1.4 var(--font);color:var(--strong);text-decoration:none;white-space:nowrap;cursor:pointer;box-shadow:none}
|
||||
html[data-organizations] .ws-btn:hover:not(:disabled),html[data-organizations] .ws-busctl [data-bus-restart]:hover:not(:disabled),html[data-organizations] .ws-busctl [data-bus-stop]:hover:not(:disabled){background:var(--raised)}
|
||||
html[data-organizations] .ws-btn:disabled,html[data-organizations] .ws-busctl [data-bus-restart]:disabled,html[data-organizations] .ws-busctl [data-bus-stop]:disabled{color:var(--muted);cursor:not-allowed;opacity:1}
|
||||
html[data-organizations] .ws-btn svg.i{width:15px;height:15px}
|
||||
/* The live bus restart is console-restart.js's own button; its icon sits beside it, outside the
|
||||
part that file repaints. */
|
||||
html[data-organizations] .ws-busctl{position:relative;display:inline-flex;flex-direction:column;align-items:flex-end}
|
||||
/* The live bus restart is console-restart.js's own button; it carries its icon through repaints,
|
||||
so the icon stays on the button however wide the receipt below it is. */
|
||||
html[data-organizations] .ws-busctl{display:inline-flex;flex-direction:column;align-items:flex-end}
|
||||
html[data-organizations] .ws-busctl .bus-restart{display:inline-flex;flex-direction:column;align-items:flex-end;gap:4px}
|
||||
html[data-organizations] .ws-busctl [data-bus-restart]{padding-left:31px}
|
||||
html[data-organizations] .ws-busctl .ws-busicon{position:absolute;left:11px;top:7px;width:15px;height:15px;pointer-events:none;color:var(--strong);z-index:1}
|
||||
html[data-organizations] .ws-busctl .bus-buttons{display:inline-flex;flex-wrap:wrap;gap:6px;justify-content:flex-end}
|
||||
html[data-organizations] .ws-busctl [data-bus-restart] svg.i{width:15px;height:15px}
|
||||
html[data-organizations] .ws-busctl [data-bus-restart-receipt]{font-size:12px;color:var(--muted);max-width:28em;text-align:right}
|
||||
html[data-organizations] .ws-busctl [data-bus-restart-receipt]:empty{display:none}
|
||||
html[data-organizations] .ws-chips{display:flex;flex-wrap:wrap;align-items:center;gap:6px}
|
||||
@@ -689,6 +689,7 @@ html[data-organizations] #copy-status:empty{display:none}
|
||||
html[data-organizations] .ws-orghead .ws-right{margin-left:0}
|
||||
html[data-organizations] .ws-busctl,html[data-organizations] .ws-busctl .bus-restart{align-items:flex-start}
|
||||
html[data-organizations] .ws-busctl [data-bus-restart-receipt]{text-align:left}
|
||||
html[data-organizations] .ws-busctl .bus-buttons{justify-content:flex-start}
|
||||
html[data-organizations] .ws-typechips .ws-label,html[data-organizations] .ws-docrow .ws-label{min-width:0}
|
||||
html[data-organizations] .ws-levels{grid-template-columns:minmax(0,1fr)!important}
|
||||
html[data-organizations] .ws-levels>div{border-right:0}
|
||||
|
||||
@@ -219,9 +219,10 @@
|
||||
|
||||
// Header: the bus restart is console-restart.js's button where the Console allows it, otherwise
|
||||
// the same control, present and disabled, with the reason.
|
||||
const restart = pane ? '' : window.MosaicConsole?.busButton?.('Restart bus') || '';
|
||||
const restart = pane ? '' : window.MosaicConsole?.busButton?.('Restart bus', { stop: true, glyph: icon('restart') }) || '';
|
||||
const offTitle = pane ? "Restart the bus from this organization's full view" : "Restarting the bus is the owner's trailed action, on a Console started with send and the action trail";
|
||||
const bus = restart ? `<span class="ws-busctl" data-dashboard-bus>${icon('restart', 'ws-busicon')}${restart}</span>` : `<span data-dashboard-bus><button type="button" class="ws-btn" data-bus-restart-off data-focus-key="bus-restart-off" disabled title="${esc(offTitle)}">${icon('restart')}Restart bus</button></span>`;
|
||||
const stopTitle = pane ? "Stop the bus from this organization's full view" : "Stopping the bus is the owner's trailed action, on a Console started with send and the action trail";
|
||||
const bus = restart ? `<span class="ws-busctl" data-dashboard-bus>${restart}</span>` : `<span data-dashboard-bus><button type="button" class="ws-btn" data-bus-restart-off data-focus-key="bus-restart-off" disabled title="${esc(offTitle)}">${icon('restart')}Restart bus</button> <button type="button" class="ws-btn" data-bus-stop-off data-focus-key="bus-stop-off" disabled title="${esc(stopTitle)}">Stop bus</button></span>`;
|
||||
const reload = `<button type="button" class="ws-btn" data-org-reload data-focus-key="org-reload" disabled aria-describedby="${esc(why)}" title="Reload arrives with the cross-org update">${icon('doc')}Reload organization file</button>`;
|
||||
const [bcls, bglyph] = state(org);
|
||||
const meta = `<p class="ws-meta"><span>Kind not recorded</span><span>id <code>${esc(id)}</code></span><span>Tracker: ${tracker ? esc(titleCase(tracker)) : 'not set'}</span><span>${dot(bcls, bglyph, org.busHealthy ? `bus running, read ${clock()}` : `bus unavailable, read ${clock()}`, true)}</span><span id="${esc(why)}">Restart is a trailed human action; reload arrives with the cross-org update.</span></p>`;
|
||||
|
||||
@@ -828,7 +828,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
for (const registerRoutes of routes) registerRoutes(registered);
|
||||
registered.add('GET', '/api/themes', (req, res) => themesHTTP(req, res, { log }), { publicRead: true });
|
||||
const adminRoute = (req, res, context) => orgAdminHTTP(req, res, { ...context, admin: orgAdmin ??= defaultOrgAdmin(), log, trail });
|
||||
for (const path of ['/api/org-template', '/api/org-presets', '/api/org-validate', '/api/org-admin', /^\/api\/orgs\/[^/]+\/(?:admin|setup|delete|archive|restore|restart)(?:\/(?:queue|bus|project\/[^/]+|records\/[^/]+))?$/]) {
|
||||
for (const path of ['/api/org-template', '/api/org-presets', '/api/org-validate', '/api/org-admin', /^\/api\/orgs\/[^/]+\/(?:admin|setup|delete|archive|restore|restart|stop)(?:\/(?:queue|bus|project\/[^/]+|records\/[^/]+))?$/]) {
|
||||
for (const method of ['GET', 'POST']) registered.add(method, path, adminRoute);
|
||||
}
|
||||
registered.add('POST', '/api/orgs', adminRoute);
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
// Stop bus (#1873, bus-stop): the Console's POST /api/orgs/ID/stop/bus stops one organization's bus
|
||||
// host the way `mosaic bus stop` does, with SIGTERM and a clean close, so no host.lock or writer.lock
|
||||
// is left and an offline schema migration can open the store straight after. A real scratch instance
|
||||
// (bootstrap.sh), a real bus host and a real dev-owner Console on port 0.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { request } from 'node:http';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { humanEnv } from '../../cli/tests/helpers.mjs';
|
||||
import { busStatus, busStop } from '../../cli/src/org-bus.mjs';
|
||||
import { consoleStart, consoleStop } from '../../cli/src/org-console.mjs';
|
||||
import { createOrg, templateRender } from '../../organization/src/org-service.mjs';
|
||||
|
||||
const REPO = new URL('../../../', import.meta.url).pathname;
|
||||
const MOSAIC = join(REPO, 'scripts/mosaic');
|
||||
const MIGRATE = join(REPO, 'packages/bus/src/migrate-schema.mjs');
|
||||
const DEV = { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner' };
|
||||
const FORBIDDEN = [7332, 7340, 7341, 33223, 17450, 17443, 44307, 7350];
|
||||
|
||||
function mosaic(env, args, timeout = 60000) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(MOSAIC, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let stdout = '', stderr = '';
|
||||
child.stdout.setEncoding('utf8').on('data', c => { stdout += c; });
|
||||
child.stderr.setEncoding('utf8').on('data', c => { stderr += c; });
|
||||
const timer = setTimeout(() => child.kill('SIGKILL'), timeout);
|
||||
child.on('error', reject);
|
||||
child.on('close', status => { clearTimeout(timer); resolve({ status, stdout, stderr }); });
|
||||
});
|
||||
}
|
||||
// A request the way the page sends it to its own Console.
|
||||
function post(port, path) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const host = `127.0.0.1:${port}`;
|
||||
const req = request({ host: '127.0.0.1', port, path, method: 'POST', headers: { host, origin: `http://${host}`, 'sec-fetch-site': 'same-origin', 'content-type': 'application/json', 'content-length': 2 } }, res => {
|
||||
let text = ''; res.setEncoding('utf8'); res.on('data', c => { text += c; });
|
||||
res.on('end', () => { let body = null; try { body = JSON.parse(text); } catch { /* not JSON */ } resolve({ status: res.statusCode, body, text }); });
|
||||
});
|
||||
req.on('error', reject); req.end('{}');
|
||||
});
|
||||
}
|
||||
// Every file under the bus state directories, with its content hash.
|
||||
function snapshot(root) {
|
||||
const out = {};
|
||||
for (const dir of ['bus-host', 'bus']) {
|
||||
const base = join(root, dir);
|
||||
if (!existsSync(base)) continue;
|
||||
for (const name of readdirSync(base).sort()) {
|
||||
const p = join(base, name), st = statSync(p);
|
||||
out[`${dir}/${name}`] = st.isFile() ? createHash('sha256').update(readFileSync(p)).digest('hex') : st.isDirectory() ? 'dir' : 'other';
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
test('Stop bus stops a live bus cleanly: no locks, an offline migration runs, a second press answers stopped, setup starts it again', { timeout: 180000 }, async t => {
|
||||
const home = mkdtempSync(join(tmpdir(), 'bs-'));
|
||||
const env = humanEnv({ HOME: home, MOSAIC_CONFIG: join(home, '.config/mosaic-bstop/config.json') });
|
||||
const setup = spawnSync(join(REPO, 'scripts/bootstrap.sh'), ['--instance', 'bstop'], { env, encoding: 'utf8' });
|
||||
assert.equal(setup.status, 0, setup.stderr);
|
||||
const ctx = { configDir: join(home, '.config/mosaic-bstop'), dataRoot: join(home, '.mosaic-bstop'), instance: 'bstop', env };
|
||||
t.after(async () => {
|
||||
try { await busStop(ctx, 'alpha'); } catch {}
|
||||
try { await consoleStop(ctx, { warn: () => {} }); } catch {}
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
});
|
||||
await createOrg({ ...ctx, principal: DEV }, 'alpha', await templateRender('alpha', { fixture: 'local' }));
|
||||
const started = await mosaic(env, ['bus', 'start', 'alpha', '--no-launch', '--dev-local-owner', '--detach']);
|
||||
assert.equal(started.status, 0, started.stderr);
|
||||
const first = await busStatus(ctx, 'alpha');
|
||||
assert.equal(first.healthy, true);
|
||||
const root = first.root;
|
||||
const hostLock = join(root, 'bus-host', 'host.lock'), writerLock = join(root, 'bus', 'writer.lock');
|
||||
// A live bus holds both locks, so their absence afterwards is the stop's doing.
|
||||
assert.ok(existsSync(hostLock), 'a live bus holds host.lock'); assert.ok(existsSync(writerLock), 'a live bus holds writer.lock');
|
||||
const run = await consoleStart(ctx, { devLocalOwner: true, detach: true, port: 'auto', warn: () => {} });
|
||||
const port = Number(new URL(run.url).port);
|
||||
assert.ok(port > 0 && !FORBIDDEN.includes(port), String(port));
|
||||
|
||||
const stop = await post(port, '/api/orgs/alpha/stop/bus');
|
||||
assert.equal(stop.status, 200, stop.text);
|
||||
assert.equal(stop.body.step, 'bus-stop'); assert.equal(stop.body.state, 'stopped'); assert.equal(stop.body.stopped, true);
|
||||
assert.equal(stop.body.receipt.pid, first.pid);
|
||||
assert.ok(!stop.text.includes(home), 'the receipt names no host path');
|
||||
assert.ok(!existsSync(`/proc/${first.pid}`) || !readFileSync(`/proc/${first.pid}/cmdline`, 'utf8').includes('--internal-host'), 'the host process is gone');
|
||||
assert.ok(!existsSync(hostLock), 'no host.lock left'); assert.ok(!existsSync(writerLock), 'no writer.lock left');
|
||||
const status = await busStatus(ctx, 'alpha');
|
||||
assert.equal(status.healthy, false); assert.equal(status.pid ?? null, null);
|
||||
|
||||
// The offline schema migration opens the store straight after (it refuses writer-locked otherwise).
|
||||
const migrate = spawnSync(process.execPath, [MIGRATE, root], { env: { PATH: process.env.PATH }, encoding: 'utf8' });
|
||||
assert.equal(migrate.status, 0, migrate.stderr);
|
||||
assert.match(migrate.stdout, /bus schema \S+ ready/);
|
||||
assert.ok(!existsSync(writerLock), 'the migration released the store');
|
||||
|
||||
// A second press finds it stopped and changes nothing.
|
||||
const quiet = snapshot(root);
|
||||
const again = await post(port, '/api/orgs/alpha/stop/bus');
|
||||
assert.equal(again.status, 200, again.text);
|
||||
assert.deepEqual([again.body.step, again.body.state, again.body.stopped], ['bus-stop', 'stopped', false]);
|
||||
assert.deepEqual(snapshot(root), quiet);
|
||||
|
||||
// A host lock this Console cannot prove (a live pid that is not the recorded process) refuses,
|
||||
// and every bus file stays as it was.
|
||||
writeFileSync(hostLock, JSON.stringify({ pid: process.pid, startTime: '1', business: 'alpha', startedAt: new Date().toISOString() }));
|
||||
const unproven = snapshot(root);
|
||||
const refused = await post(port, '/api/orgs/alpha/stop/bus');
|
||||
assert.equal(refused.status, 409, refused.text); assert.equal(refused.body.error, 'bus-refused');
|
||||
assert.match(refused.body.message, /^stale bus host lock\. Inspect it with mosaic bus status alpha/);
|
||||
assert.deepEqual(snapshot(root), unproven);
|
||||
rmSync(hostLock);
|
||||
|
||||
// The setup step starts it again.
|
||||
const up = await post(port, '/api/orgs/alpha/setup/bus');
|
||||
assert.equal(up.status, 201, up.text); assert.equal(up.body.step, 'bus');
|
||||
const back = await busStatus(ctx, 'alpha');
|
||||
assert.equal(back.healthy, true); assert.notEqual(back.pid, first.pid);
|
||||
assert.ok(existsSync(hostLock)); assert.ok(existsSync(writerLock));
|
||||
// And stops again from the page.
|
||||
const last = await post(port, '/api/orgs/alpha/stop/bus');
|
||||
assert.equal(last.status, 200, last.text); assert.equal(last.body.stopped, true);
|
||||
assert.ok(!existsSync(hostLock)); assert.ok(!existsSync(writerLock));
|
||||
});
|
||||
@@ -39,6 +39,7 @@ function fakes() {
|
||||
busStart: async (ctx, id, opts) => { calls.push(['busStart', id, opts]); running = id; return { org: id, pid: 4242, socket: '/run/s', root: `/data/org-runtime/${id}` }; },
|
||||
busStopForDelete: async (ctx, id) => { calls.push(['busStopForDelete', id]); running = null; return { stopped: false, reason: 'no host runs' }; },
|
||||
busRestart: async (ctx, id) => { calls.push(['busRestart', id]); running = id; return { org: id, pid: 4343, socket: '/run/s', root: `/data/org-runtime/${id}` }; },
|
||||
busStop: async (ctx, id) => { calls.push(['busStop', id]); const was = running === id; running = null; return was ? { stopped: true, business: id, pid: 4242 } : { stopped: false, reason: 'no host runs' }; },
|
||||
};
|
||||
const admin = createOrgAdmin({ service, registry, bus, context: async () => ({ configDir: '/cfg', dataRoot: '/data', instance: 'test' }) });
|
||||
return { admin, orgs, calls, fail, service };
|
||||
@@ -371,6 +372,18 @@ test('toCanonical keeps library projects free of a root', () => {
|
||||
assert.deepEqual(out.projects, { lib: { kind: 'library' }, work: { root: '/__mosaic_org__/acme/projects/work' } });
|
||||
});
|
||||
|
||||
// #1873 CB1: copy bindings are server-held. An update keeps the stored ones whatever the browser
|
||||
// sent, and drops any the browser invented when none are stored.
|
||||
test('toCanonical keeps stored copyBindings and drops browser-sent ones on an update', () => {
|
||||
const stored = { id: 'acme', projects: { work: {} }, copyBindings: { rev: { state: 'pending', generation: 1 } } };
|
||||
const kept = toCanonical('acme', { projects: { work: {} }, copyBindings: { rev: { state: 'bound', generation: 9 } } }, stored);
|
||||
assert.deepEqual(kept.copyBindings, stored.copyBindings);
|
||||
const dropped = toCanonical('acme', { projects: { work: {} }, copyBindings: { rev: { state: 'bound' } } }, { id: 'acme', projects: { work: {} } });
|
||||
assert.equal(Object.hasOwn(dropped, 'copyBindings'), false);
|
||||
const removed = toCanonical('acme', { projects: { work: {} } }, stored);
|
||||
assert.deepEqual(removed.copyBindings, stored.copyBindings);
|
||||
});
|
||||
|
||||
test('the Settings page ships the organization assets', async t => {
|
||||
const c = await console_(t);
|
||||
const index = await c.call('GET', '/');
|
||||
@@ -674,3 +687,197 @@ test('D2: a press during the Console start-up revive waits for it and acts on th
|
||||
assert.equal(r.status, 200, r.raw); assert.equal(r.body.restarted, true);
|
||||
assert.deepEqual(c.calls.filter(x => x[0] === 'busRestart'), [['busRestart', 'acme']]);
|
||||
});
|
||||
|
||||
// Stop bus: the owner stops one organization's bus from its page. Same owner, origin, --send and
|
||||
// trail rules as Restart bus; a stopped bus answers state stopped and nothing changes.
|
||||
const STOP = '/api/orgs/acme/stop/bus';
|
||||
const STOP_DONE = { outcome: 'done', step: 'bus-stop', stopped: true, state: 'stopped', receipt: { org: 'acme', stopped: true, business: 'acme', pid: 4242 }, verb: 'mosaic bus stop acme' };
|
||||
|
||||
test('stop: the owner stops a running bus, a second press answers stopped, and setup starts it again', async t => {
|
||||
const tr = trailIn(t);
|
||||
const c = await console_(t, { trail: tr.trail });
|
||||
assert.equal((await c.call('POST', '/api/orgs', { id: 'acme', doc: browserDoc('acme') })).status, 201);
|
||||
assert.equal((await c.call('POST', '/api/orgs/acme/setup/bus', {})).status, 201);
|
||||
let r = await c.call('POST', STOP, {});
|
||||
assert.equal(r.status, 200, r.raw);
|
||||
assert.deepEqual(r.body, STOP_DONE);
|
||||
r = await c.call('POST', STOP, {});
|
||||
assert.equal(r.status, 200, r.raw);
|
||||
assert.deepEqual(r.body, { outcome: 'done', step: 'bus-stop', stopped: false, state: 'stopped', receipt: { org: 'acme', stopped: false }, verb: 'mosaic bus stop acme' });
|
||||
// The second press changed nothing: busStop ran once.
|
||||
assert.deepEqual(c.calls.filter(x => x[0] === 'busStop'), [['busStop', 'acme']]);
|
||||
const up = await c.call('POST', '/api/orgs/acme/setup/bus', {});
|
||||
assert.equal(up.status, 201, up.raw); assert.equal(up.body.step, 'bus');
|
||||
assert.equal(c.calls.filter(x => x[0] === 'busStart').length, 2);
|
||||
assert.deepEqual(tr.lines(), [
|
||||
{ by: DEV, action: 'bus.stop', org: 'acme', outcome: 'requested', running: true },
|
||||
{ by: DEV, action: 'bus.stop', org: 'acme', outcome: 'done' },
|
||||
{ by: DEV, action: 'bus.stop', org: 'acme', outcome: 'requested', running: false },
|
||||
{ by: DEV, action: 'bus.stop', org: 'acme', outcome: 'done' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('stop: another origin or site, no owner or --send, a body, GET or no organization is refused like Restart bus', async t => {
|
||||
const tr = trailIn(t);
|
||||
const c = await console_(t, { trail: tr.trail });
|
||||
await c.call('POST', '/api/orgs', { id: 'acme', doc: browserDoc('acme') });
|
||||
await c.call('POST', '/api/orgs/acme/setup/bus', {});
|
||||
for (const headers of [{ origin: null }, { origin: 'http://evil.example' }, { origin: `http://localhost:${c.port + 1}` }, { 'sec-fetch-site': null }, { 'sec-fetch-site': 'cross-site' }, { 'sec-fetch-site': 'same-site' }, { 'x-mosaic-tester': '1' }]) {
|
||||
const [stop, restart] = [await c.call('POST', STOP, {}, headers), await c.call('POST', '/api/orgs/acme/restart/bus', {}, headers)];
|
||||
assert.equal(stop.status, 403, JSON.stringify(headers));
|
||||
assert.deepEqual([stop.status, stop.body?.error], [restart.status, restart.body?.error], JSON.stringify(headers));
|
||||
}
|
||||
assert.equal((await c.call('POST', STOP, {}, { 'content-type': 'text/plain' })).status, 415);
|
||||
assert.equal((await c.call('POST', STOP, { now: true })).status, 400);
|
||||
assert.equal((await c.call('GET', STOP)).status, 404);
|
||||
assert.equal((await c.call('POST', '/api/orgs/acme/stop/queue', {})).status, 404);
|
||||
assert.equal((await c.call('POST', '/api/orgs/acme/stop', {})).status, 404);
|
||||
const unknown = await c.call('POST', '/api/orgs/ghost/stop/bus', {});
|
||||
assert.equal(unknown.status, 404); assert.equal(unknown.body.error, 'org-unavailable');
|
||||
const readOnly = await console_(t, { trail: tr.trail, send: null });
|
||||
const ro = await readOnly.call('POST', STOP, {});
|
||||
assert.equal(ro.status, 403); assert.equal(ro.body.error, 'read-only');
|
||||
const anon = await console_(t, { trail: tr.trail, sso: null, send: null });
|
||||
const a = await anon.call('POST', STOP, {});
|
||||
assert.equal(a.status, 403); assert.equal(a.body.error, 'owner-only');
|
||||
assert.equal(c.calls.filter(x => ['busStop', 'busRestart'].includes(x[0])).length, 0);
|
||||
assert.deepEqual(tr.lines(), []);
|
||||
});
|
||||
|
||||
test('stop: on a deployed (signed-in) Console a granted user is refused like Restart bus, and the owner stops the bus', async t => {
|
||||
const { createSsoSession } = await import('./helpers/sso-session.mjs');
|
||||
const { consoleAccess } = await import('../src/access.mjs');
|
||||
const tr = trailIn(t);
|
||||
const access = { accessVersion: 1, revision: 1, users: [{ id: 'alice', home: 'local', subjects: [{ provider: 'writer', sub: 'alice-sub' }] }],
|
||||
grants: [{ id: 'g-1', user: 'alice', business: 'acme', projects: ['*'], instances: ['assistant'], level: 'collaborator' }] };
|
||||
const s = await createSsoSession(t, { users: consoleAccess({ load: () => access, business: () => 'acme' }) });
|
||||
const f = fakes();
|
||||
await f.service.createOrg({}, 'acme', template('acme'));
|
||||
const bus = await f.admin.bus();
|
||||
await bus.busStart({}, 'acme', {});
|
||||
const server = await startServer({ port: 0, board: 'http://127.0.0.1:9', sso: s.sso, send: async () => ({}), orgAdmin: f.admin, log: () => {}, trail: tr.trail });
|
||||
t.after(() => close(server));
|
||||
const port = server.address().port;
|
||||
const post = (path, cookie, headers = {}) => new Promise((resolve, reject) => {
|
||||
const all = { ...s.writeHeaders(cookie), 'content-length': 2, ...headers };
|
||||
const req = request({ host: '127.0.0.1', port, method: 'POST', path, headers: all }, res => { let raw = ''; res.on('data', x => raw += x); res.on('end', () => { let json = null; try { json = JSON.parse(raw); } catch {} resolve({ status: res.statusCode, body: json, raw }); }); });
|
||||
req.on('error', reject); req.end('{}');
|
||||
});
|
||||
const alice = await s.signIn(port, { sub: 'alice-sub' });
|
||||
for (const cookie of [null, alice]) {
|
||||
const [stop, restart] = [await post(STOP, cookie), await post('/api/orgs/acme/restart/bus', cookie)];
|
||||
assert.ok(stop.status === 401 || stop.status === 403 || stop.status === 404, stop.raw);
|
||||
assert.deepEqual([stop.status, stop.body?.error], [restart.status, restart.body?.error]);
|
||||
}
|
||||
assert.equal(f.calls.filter(x => ['busStop', 'busRestart'].includes(x[0])).length, 0);
|
||||
assert.deepEqual(tr.lines(), []);
|
||||
// The signed-in owner from another origin is refused too; from the Console's own origin the bus stops.
|
||||
const owner = await s.signIn(port);
|
||||
const cross = await post(STOP, owner, { origin: 'https://evil.example' });
|
||||
assert.equal(cross.status, 403);
|
||||
const ok = await post(STOP, owner);
|
||||
assert.equal(ok.status, 200, ok.raw); assert.equal(ok.body.state, 'stopped'); assert.equal(ok.body.stopped, true);
|
||||
assert.deepEqual(tr.lines().map(e => [e.by.provider, e.by.sub, e.action, e.outcome]), [['writer', 'owner-sub', 'bus.stop', 'requested'], ['writer', 'owner-sub', 'bus.stop', 'done']]);
|
||||
});
|
||||
|
||||
test('stop: a signed-in operator who is not the owner is refused before any bus call', async t => {
|
||||
const { Readable } = await import('node:stream');
|
||||
const tr = trailIn(t);
|
||||
const f = fakes();
|
||||
await f.service.createOrg({}, 'acme', template('acme'));
|
||||
for (const path of [STOP, '/api/orgs/acme/restart/bus']) {
|
||||
const req = Object.assign(Readable.from([Buffer.from('{}')]), { method: 'POST', headersDistinct: { origin: ['http://console.example'], 'sec-fetch-site': ['same-origin'], 'content-type': ['application/json'] } });
|
||||
const res = { writeHead(status) { this.status = status; }, end(body) { this.body = JSON.parse(body); } };
|
||||
await orgAdminHTTP(req, res, { path, admin: f.admin, session: { provider: 'fixture', iss: 'https://issuer.example', sub: 'op', rootOwner: false, instanceRole: 'operator' }, owner: false, send: true, origin: 'http://console.example', trail: tr.trail });
|
||||
assert.equal(res.status, 403, path); assert.equal(res.body.error, 'owner-only', path);
|
||||
}
|
||||
assert.equal(f.calls.filter(x => x[0].startsWith('bus')).length, 0);
|
||||
assert.deepEqual(tr.lines(), []);
|
||||
});
|
||||
|
||||
test('stop: no trail, or a trail that cannot be written, stops nothing', async t => {
|
||||
const c = await console_(t);
|
||||
await c.call('POST', '/api/orgs', { id: 'acme', doc: browserDoc('acme') });
|
||||
await c.call('POST', '/api/orgs/acme/setup/bus', {});
|
||||
const r = await c.call('POST', STOP, {});
|
||||
assert.equal(r.status, 503); assert.equal(r.body.error, 'trail-unavailable');
|
||||
const broken = await console_(t, { trail: () => { throw new Error('disk full'); } });
|
||||
await broken.call('POST', '/api/orgs', { id: 'acme', doc: browserDoc('acme') });
|
||||
await broken.call('POST', '/api/orgs/acme/setup/bus', {});
|
||||
const b = await broken.call('POST', STOP, {});
|
||||
assert.equal(b.status, 500); assert.equal(b.body.error, 'trail-unavailable');
|
||||
for (const x of [c, broken]) assert.equal(x.calls.filter(y => y[0] === 'busStop').length, 0);
|
||||
});
|
||||
|
||||
test('stop: a host that cannot be proven refuses with nothing changed, on the dev Console too', async t => {
|
||||
const tr = trailIn(t);
|
||||
const c = await console_(t, { trail: tr.trail });
|
||||
await c.call('POST', '/api/orgs', { id: 'acme', doc: browserDoc('acme') });
|
||||
const bus = await c.admin.bus();
|
||||
bus.busRevive = async () => assert.fail('Stop bus reached busRevive');
|
||||
for (const reason of ['stale bus host lock', 'bus host identity mismatch', 'bus host lock does not match host state', 'stale bus writer lock']) {
|
||||
bus.busStatus = async () => { throw cliError(reason); };
|
||||
const r = await c.call('POST', STOP, {});
|
||||
assert.equal(r.status, 409, reason); assert.equal(r.body.error, 'bus-refused');
|
||||
assert.equal(r.body.message, `${reason}. Inspect it with mosaic bus status acme; mosaic bus recover acme clears a host that died.`);
|
||||
}
|
||||
assert.equal(c.calls.filter(x => x[0] === 'busStop').length, 0);
|
||||
assert.deepEqual(tr.lines(), Array(4).fill({ by: DEV, action: 'bus.stop', org: 'acme', outcome: 'refused', running: null }));
|
||||
});
|
||||
|
||||
test('stop: a stop that is refused, times out or leaves state behind is a visible failure', async t => {
|
||||
const tr = trailIn(t);
|
||||
const c = await console_(t, { trail: tr.trail });
|
||||
await c.call('POST', '/api/orgs', { id: 'acme', doc: browserDoc('acme') });
|
||||
await c.call('POST', '/api/orgs/acme/setup/bus', {});
|
||||
const bus = await c.admin.bus();
|
||||
const live = async () => ({ org: 'acme', healthy: true, pid: 4242, root: '/data/org-runtime/acme' });
|
||||
bus.busStatus = live;
|
||||
bus.busStop = async () => { throw cliError('pid 4242 is not a bus host; refusing to signal it'); };
|
||||
let r = await c.call('POST', STOP, {});
|
||||
assert.equal(r.status, 409); assert.equal(r.body.error, 'bus-refused');
|
||||
assert.equal(r.body.message, 'pid 4242 is not a bus host; refusing to signal it. Inspect it with mosaic bus status acme.');
|
||||
bus.busStop = async () => { throw Object.assign(new Error('bus host pid 4242 did not stop within 60 s'), { name: 'CliError', exitCode: 1 }); };
|
||||
r = await c.call('POST', STOP, {});
|
||||
assert.equal(r.status, 409); assert.equal(r.body.error, 'bus-failed');
|
||||
// An unexpected error may come after the signal: the outcome is unknown and the trail says failed.
|
||||
bus.busStop = async () => { throw new Error('EPERM'); };
|
||||
r = await c.call('POST', STOP, {});
|
||||
assert.equal(r.status, 502, r.raw); assert.equal(r.body.error, 'outcome-unknown');
|
||||
// The host was signalled and exited, but a lock is left, or the host is still recorded.
|
||||
let after;
|
||||
bus.busStop = async () => { bus.busStatus = after; return { stopped: true, business: 'acme', pid: 4242 }; };
|
||||
after = async () => { throw cliError('stale bus writer lock'); };
|
||||
r = await c.call('POST', STOP, {});
|
||||
assert.equal(r.status, 409); assert.equal(r.body.error, 'bus-failed');
|
||||
assert.equal(r.body.message, 'the bus host was stopped, but stale bus writer lock. Inspect it with mosaic bus status acme; mosaic bus recover acme clears a host that died.');
|
||||
bus.busStatus = live; after = live;
|
||||
r = await c.call('POST', STOP, {});
|
||||
assert.equal(r.status, 409); assert.equal(r.body.error, 'bus-failed');
|
||||
assert.match(r.body.message, /^the bus host was stopped, but a bus host still runs\./);
|
||||
assert.deepEqual(tr.lines().map(e => e.outcome), ['requested', 'refused', 'requested', 'failed', 'requested', 'failed', 'requested', 'failed', 'requested', 'failed']);
|
||||
// The host exited on its own between the read and the stop: done, but this press stopped nothing.
|
||||
bus.busStatus = live;
|
||||
bus.busStop = async () => { bus.busStatus = async () => ({ org: 'acme', healthy: false, pid: null }); return { stopped: false, reason: 'no host runs' }; };
|
||||
r = await c.call('POST', STOP, {});
|
||||
assert.equal(r.status, 200, r.raw);
|
||||
assert.deepEqual([r.body.outcome, r.body.state, r.body.stopped, r.body.receipt.stopped], ['done', 'stopped', false, false]);
|
||||
});
|
||||
|
||||
test('stop: an archived organization, or a Console whose bus control has no stop, refuses', async t => {
|
||||
const tr = trailIn(t);
|
||||
const c = await console_(t, { trail: tr.trail });
|
||||
await c.call('POST', '/api/orgs', { id: 'acme', doc: browserDoc('acme') });
|
||||
const bus = await c.admin.bus();
|
||||
const busStop = bus.busStop; delete bus.busStop;
|
||||
const n = await c.call('POST', STOP, {});
|
||||
assert.equal(n.status, 503); assert.equal(n.body.error, 'not-configured');
|
||||
bus.busStop = busStop;
|
||||
bus.busStatus = async () => { throw new OrgError('org-archived', 'organization acme is archived'); };
|
||||
const a = await c.call('POST', STOP, {});
|
||||
const ra = await c.call('POST', '/api/orgs/acme/restart/bus', {});
|
||||
assert.deepEqual([a.status, a.body.error], [422, 'org-archived'], a.raw);
|
||||
assert.deepEqual([ra.status, ra.body.error], [422, 'org-archived'], ra.raw);
|
||||
assert.equal(c.calls.filter(x => ['busStop', 'busRestart'].includes(x[0])).length, 0);
|
||||
assert.deepEqual(tr.lines(), []);
|
||||
});
|
||||
@@ -3,6 +3,10 @@ import assert from 'node:assert/strict';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
import { createOrgAdmin } from '../src/org-admin.mjs';
|
||||
import { actionTrail } from '../src/action-trail.mjs';
|
||||
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { browser } from './browser.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
@@ -202,7 +206,7 @@ test('organization dashboard presents sections and honest unavailable controls',
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-org-reload]").disabled'),true);
|
||||
});
|
||||
|
||||
test('each header control is present, reload is disabled, and restart is refused without the owner', async t => {
|
||||
test('each header control is present, reload is disabled, and restart and stop are refused without the owner', async t => {
|
||||
const owner = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), organizations: workspaceOrgs(), orgAdmin: refusingAdmin(), log: () => {} }); t.after(() => close(owner));
|
||||
const readOnly = await startServer({ port: 0, sso: createDevOwner(), organizations: workspaceOrgs(), orgAdmin: refusingAdmin(), log: () => {} }); t.after(() => close(readOnly));
|
||||
const signedOut = await startServer({ port: 0, organizations: workspaceOrgs(), orgAdmin: refusingAdmin(), log: () => {} }); t.after(() => close(signedOut));
|
||||
@@ -210,27 +214,69 @@ test('each header control is present, reload is disabled, and restart is refused
|
||||
const wait = waitFor(b);
|
||||
const header = server => b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/organization`).then(() => wait('document.querySelector("[data-org-dashboard] [data-org-settings]")')).then(() => b.evaluate(`(() => {
|
||||
const h = document.querySelector('[data-org-dashboard] .ws-orghead'), live = h.querySelector('[data-bus-restart]'), off = h.querySelector('[data-bus-restart-off]'), reload = h.querySelector('[data-org-reload]');
|
||||
const stop = h.querySelector('[data-bus-stop]'), stopOff = h.querySelector('[data-bus-stop-off]');
|
||||
return { live: live ? [live.textContent, live.disabled] : null, off: off ? [off.textContent, off.disabled, !!off.title] : null,
|
||||
stop: stop ? [stop.textContent, stop.disabled, stop.closest('.bus-restart') === live.closest('.bus-restart')] : null, stopOff: stopOff ? [stopOff.textContent, stopOff.disabled, !!stopOff.title] : null,
|
||||
reload: [reload.textContent, reload.disabled, reload.title, document.getElementById(reload.getAttribute('aria-describedby'))?.textContent] };
|
||||
})()`));
|
||||
const RELOAD = ['Reload organization file', true, 'Reload arrives with the cross-org update', 'Restart is a trailed human action; reload arrives with the cross-org update.'];
|
||||
// The owner on a Console started with --send gets console-restart.js's restart button.
|
||||
assert.deepEqual(await header(owner), { live: ['Restart bus', false], off: null, reload: RELOAD });
|
||||
// Stop bus sits beside it, in the same control, and is one press like Restart bus.
|
||||
assert.deepEqual(await header(owner), { live: ['Restart bus', false], off: null, stop: ['Stop bus', false, true], stopOff: null, reload: RELOAD });
|
||||
// Without --send, or with nobody signed in, the control is present and disabled, and the route refuses.
|
||||
const post = 'fetch("/api/orgs/ddigital/restart/bus", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }).then(async r => [r.status, (await r.json()).error])';
|
||||
assert.deepEqual(await header(readOnly), { live: null, off: ['Restart bus', true, true], reload: RELOAD });
|
||||
const stopPost = post.replace('/restart/bus', '/stop/bus');
|
||||
assert.deepEqual(await header(readOnly), { live: null, off: ['Restart bus', true, true], stop: null, stopOff: ['Stop bus', true, true], reload: RELOAD });
|
||||
assert.deepEqual(await b.evaluate(post), [403, 'read-only']);
|
||||
assert.deepEqual(await b.evaluate(stopPost), [403, 'read-only']);
|
||||
// With nobody signed in the organization list is not readable, so the dashboard reads nothing and
|
||||
// shows no controls at all.
|
||||
await b.navigate(`http://127.0.0.1:${signedOut.address().port}/#/orgs/ddigital/organization`);
|
||||
await wait('document.querySelector("[data-org-unavailable]")');
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-bus-restart], [data-bus-restart-off], [data-org-reload]")'), null);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-bus-restart], [data-bus-restart-off], [data-bus-stop], [data-bus-stop-off], [data-org-reload]")'), null);
|
||||
// With nobody signed in, the server refuses every per-org route before the admin hooks run.
|
||||
assert.deepEqual(await b.evaluate(post), [404, 'org-unavailable']);
|
||||
assert.deepEqual(await b.evaluate(stopPost), [404, 'org-unavailable']);
|
||||
// There is no reload route.
|
||||
assert.equal(await b.evaluate('fetch("/api/orgs/ddigital/reload", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }).then(r => r.ok)'), false);
|
||||
});
|
||||
|
||||
test('the owner presses Stop bus once: the bus stops, a second press says it was already stopped, and the restart icon stays on its button', async t => {
|
||||
// A fake bus behind the real route: busStop is the only thing a press reaches.
|
||||
let running = true; const stops = [];
|
||||
const bus = {
|
||||
busStatus: async (ctx, id) => ({ org: id, healthy: running, pid: running ? 4242 : null }),
|
||||
busStop: async (ctx, id) => { stops.push(id); const was = running; running = false; return was ? { stopped: true, business: id, pid: 4242 } : { stopped: false, reason: 'no host runs' }; },
|
||||
};
|
||||
const orgAdmin = createOrgAdmin({ service: { showOrg: async (ctx, id) => ({ id, revision: 1, doc: {} }) }, registry: { listOrgs: async () => [] }, bus, context: async () => ({ configDir: '/cfg', dataRoot: '/data', instance: 'test' }) });
|
||||
const root = mkdtempSync(join(tmpdir(), 'bus-stop-trail-')); t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
const trail = actionTrail(join(root, 'console'));
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), organizations: workspaceOrgs({ send: true }), orgAdmin, trail, log: () => {} }); t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
const wait = waitFor(b);
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/organization`);
|
||||
await wait('document.querySelector("[data-org-dashboard] [data-bus-stop]")');
|
||||
// The icon is part of the restart button, so it moves with it whatever width the receipt takes.
|
||||
const icon = () => b.evaluate(`(() => { const r = document.querySelector('[data-org-dashboard] [data-bus-restart]'), i = r.querySelector('svg'); if (!i) return null; const a = r.getBoundingClientRect(), c = i.getBoundingClientRect(); return c.left >= a.left && c.right <= a.right && c.top >= a.top && c.bottom <= a.bottom; })()`);
|
||||
assert.equal(await icon(), true);
|
||||
await b.evaluate('document.querySelector("[data-org-dashboard] [data-bus-stop]").click()');
|
||||
await wait('/^Bus stopped at \\d/.test(document.querySelector("[data-org-dashboard] [data-bus-restart-receipt]")?.textContent || "")');
|
||||
assert.deepEqual(stops, ['ddigital']);
|
||||
assert.equal(await icon(), true, 'the repaint keeps the icon on the restart button');
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-org-dashboard] .bus-buttons button")].map(x => [x.textContent, x.disabled])'), [['Restart bus', false], ['Stop bus', false]]);
|
||||
await b.evaluate('document.querySelector("[data-org-dashboard] [data-bus-stop]").click()');
|
||||
await wait('/^The bus was already stopped at \\d/.test(document.querySelector("[data-org-dashboard] [data-bus-restart-receipt]")?.textContent || "")');
|
||||
// The second press reached the route, which found no host and stopped nothing.
|
||||
assert.deepEqual(stops, ['ddigital']);
|
||||
assert.equal(await icon(), true);
|
||||
// Each press is the owner's trailed action.
|
||||
const lines = readFileSync(join(root, 'console', 'actions.jsonl'), 'utf8').split('\n').filter(Boolean).map(l => { const { at, by, ...e } = JSON.parse(l); return e; });
|
||||
assert.deepEqual(lines, [
|
||||
{ action: 'bus.stop', org: 'ddigital', outcome: 'requested', running: true }, { action: 'bus.stop', org: 'ddigital', outcome: 'done' },
|
||||
{ action: 'bus.stop', org: 'ddigital', outcome: 'requested', running: false }, { action: 'bus.stop', org: 'ddigital', outcome: 'done' },
|
||||
]);
|
||||
});
|
||||
|
||||
// Tab from the first sidebar link through the dashboard and return each stop's region and box.
|
||||
async function tabStops(b, start) {
|
||||
await b.evaluate(`(${start}).focus()`);
|
||||
@@ -268,8 +314,9 @@ test('keyboard focus follows visual order and survives a data refresh', async t
|
||||
assertVisualOrder(wide.filter(s => s.region !== 'other'), regions, '1440');
|
||||
const keys = wide.map(s => s.key);
|
||||
for (const key of ['org:forge', 'proj:ddigital:spring-launch', 'doc:spring-launch:docs/north-star.md', 'docs-all', 'agents-all', 'queue-open', 'set:Identity', 'set:Archive or delete']) assert.ok(keys.includes(key), `Tab never reaches ${key}`);
|
||||
// The disabled reload is not a tab stop; the restart button is.
|
||||
// The disabled reload is not a tab stop; the restart button is, and Stop bus follows it.
|
||||
assert.ok(!keys.includes('org-reload')); assert.ok(keys.includes('Restart bus'));
|
||||
assert.equal(keys.indexOf('Stop bus'), keys.indexOf('Restart bus') + 1);
|
||||
await b.viewport(390, 844);
|
||||
await wait('document.querySelector("[data-org-dashboard]")');
|
||||
const narrow = (await tabStops(b, 'document.querySelector("[data-org-dashboard] .ws-crumb a")')).filter(s => s.region !== 'other');
|
||||
|
||||
Reference in new issue
Block a user