diff --git a/packages/bus/tests/provider-repoint-guard.test.mjs b/packages/bus/tests/provider-repoint-guard.test.mjs new file mode 100644 index 000000000..9ae27d69d --- /dev/null +++ b/packages/bus/tests/provider-repoint-guard.test.mjs @@ -0,0 +1,48 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import {join} from 'node:path'; +import {tmpdir} from 'node:os'; +import {DatabaseSync} from 'node:sqlite'; +import {startBroker} from '../src/runtime.mjs'; +import {businessDoc,rolesCopy,systemFor,writeJson} from '../../business/tests/helpers.mjs'; +const authority=JSON.parse(fs.readFileSync('./roles/chief-of-staff.json','utf8')).authority; +const oldEntry={provider:'zai',model:'fixture-old'}; +const newEntry={provider:'zai',model:'fixture-new'}; +const offer={key:'zai-fixture-new',module:'cliproxy',upstream:'zai',provider:'zai',model:'fixture-new',label:'Fixture',available:true,reason:null,harnesses:['pi']}; +async function fixture(t, options={}) { + const root=fs.mkdtempSync(join(tmpdir(),'repoint-'));t.after(()=>fs.rmSync(root,{recursive:true,force:true})); + const rolesDir=rolesCopy(root),doc=businessDoc(root,'demo'),file=join(root,'businesses/demo.json'); + doc.plugins={...doc.plugins,harness:['pi'],'model-provider':['cliproxy']}; + doc.roles.coder.vars={...doc.roles.coder.vars,harness:'pi',thinking:'low'}; + doc.launch.models['existing-alias']=options.existingNew?newEntry:oldEntry; + if(options.selected)doc.roles.coder.vars.model='existing-alias'; + if(options.fallback)Object.assign(doc.roles.coder.vars,{'fallback.harness':'pi','fallback.model':'existing-alias','fallback.thinking':'low'}); + writeJson(file,doc);fs.mkdirSync(join(root,'data'),{mode:0o700}); + const modelCatalogue={invalidate(){},read:async()=>({status:'ready',models:[offer],notices:[]})}; + const bus=await startBroker({dataRoot:join(root,'data'),businesses:{demo:{id:'demo',human:'jason',arbiters:{technical:'coder',delivery:'coder'},roles:{...Object.fromEntries(Object.keys(doc.roles).map(key=>[key,{authority:{withinRole:[],crossRole:[]}}])),chief:{definition:'chief-of-staff',authority}}}},organization:{dir:root,rolesDir,system:systemFor(root)},modelCatalogue});t.after(()=>bus.close()); + const db=new DatabaseSync(join(root,'data/bus/bus.sqlite'),{readOnly:true});t.after(()=>db.close()); + const count=()=>db.prepare("SELECT count(*) AS n FROM events WHERE kind='action.allowed' AND json_extract(body,'$.action')='organization.change'").get().n; + const human=bus.broker.bindHuman({business:'demo',human:'jason',via:'cli',outsideAgent:true}); + const role=bus.broker.bindLaunch({business:'demo',role:'chief',run:'independent-chief',harness:'pi'});bus.broker.request(role,{verb:'role.claim'}); + const view=()=>bus.broker.request(human,{verb:'limits'}); + const request=args=>Promise.resolve().then(()=>bus.broker.request(role,{verb:'organization.set',args})); + return {view,request,count,bytes:()=>fs.readFileSync(file,'utf8')}; +} +test('role can change a legacy entry shape without changing its resolved identity',async t=>{ + const f=await fixture(t,{existingNew:true}),v=f.view(); + const equivalent={provider:'proxy',route:'glm',model:'fixture-new'}; + await f.request({revision:v.revision,models:{...v.models,'existing-alias':equivalent}}); + assert.deepEqual(JSON.parse(f.bytes()).launch.models['existing-alias'],equivalent); + assert.equal(f.count(),1); +}); +for(const [name,options] of [['unselected',{}],['selected primary',{selected:true}],['selected fallback',{fallback:true}]]) { + test('REQUIRED: role must not repoint existing legacy key to new catalogue identity: '+name,async t=>{ + const f=await fixture(t,options),v=f.view(),before=f.bytes(); + const args={revision:v.revision,models:{...v.models,'existing-alias':newEntry}}; + let error;try{await f.request(args);}catch(e){error=e.code;} + t.diagnostic(JSON.stringify({case:name,error:error??null,businessChanged:f.bytes()!==before,authorityConsumed:f.count(),persisted:JSON.parse(f.bytes()).launch.models['existing-alias']})); + assert.equal(error,'organization-model-provider-human-only'); + assert.equal(f.bytes(),before);assert.equal(f.count(),0); + }); +} diff --git a/packages/business/src/launch-settings.mjs b/packages/business/src/launch-settings.mjs index 6aa39b2b4..992da2185 100644 --- a/packages/business/src/launch-settings.mjs +++ b/packages/business/src/launch-settings.mjs @@ -234,13 +234,16 @@ export function launchSettings({ dir, rolesDir, system, sessions = () => [], now if (actor !== old.document.human && plain(args.models)) { for (const [key, entry] of Object.entries(args.models)) { if (entry?.module && canonicalJson(entry) !== canonicalJson(old.document.launch.models[key] ?? null)) throw new OrganizationError('organization-model-provider-human-only'); - // A new legacy-shaped entry can resolve to the same catalogue identity as an - // explicit entry. Use the trusted module resolver, not caller-supplied fields - // or the catalogue key, since legacy aliases may use any table key. - if (!own(old.document.launch.models, key) && plain(entry) && !entry.module && old.document.plugins?.['model-provider']?.length) { + // Resolve changed legacy entries with the trusted module resolver; a table key + // alone does not authorize introducing a different catalogue identity. + const previous = old.document.launch.models[key]; + if (canonicalJson(entry) !== canonicalJson(previous ?? null) && plain(entry) && !entry.module && old.document.plugins?.['model-provider']?.length) { if (catalogue?.status !== 'ready' || typeof catalogue.resolveLegacy !== 'function' || !Array.isArray(catalogue.models)) throw new OrganizationError('model-provider-unavailable'); const mapping = catalogue.resolveLegacy(entry); - if (mapping && catalogue.models.some(model => model.module === mapping.module && model.upstream === mapping.upstream && model.model === entry.model)) { + const prior = previous?.module + ? { module: previous.module, upstream: previous.upstream, model: previous.model } + : plain(previous) ? catalogue.resolveLegacy(previous) : null; + if (mapping && canonicalJson(mapping) !== canonicalJson(prior) && catalogue.models.some(model => model.module === mapping.module && model.upstream === mapping.upstream && model.model === entry.model)) { throw new OrganizationError('organization-model-provider-human-only'); } }