MC/website/tests/organisation-management.test.mjs
2026-11-27 23:43:05 +00:00

88 lines
9.6 KiB
JavaScript

import test from 'node:test';import assert from 'node:assert/strict';
import {canAssignRole,validatePolicyNodes,createOrganisationManagement} from '../node/organisation-management.mjs';
import {bootstrapControl} from '../scripts/bootstrap-organisation-control.mjs';
const owner='11111111-1111-4111-8111-111111111111',target='22222222-2222-4222-8222-222222222222';
const position=(scope_type,scope_key,role_key)=>({scope_type,scope_key,role_key,status:'active'});
test('branch and department managers cannot escalate outside their own scope',()=>{
const head={assignments:[position('department','community_operations','department_head')]};
assert.equal(canAssignRole(head,'branch','customer_support','branch_lead'),true);
assert.equal(canAssignRole(head,'branch','engineering','officer'),false);
assert.equal(canAssignRole(head,'department','community_operations','department_head'),false);
const lead={assignments:[position('branch','news_media','branch_lead')]};
assert.equal(canAssignRole(lead,'branch','news_media','officer'),true);assert.equal(canAssignRole(lead,'branch','news_media','branch_lead'),false);assert.equal(canAssignRole(lead,'branch','customer_support','officer'),false);
assert.equal(canAssignRole({assignments:[position('branch','news_media','officer')]},'branch','news_media','officer'),false);
});
test('Big Four and service control are organisation-wide; Owner office stays protected',()=>{
for(const principal of ['owner','executive','service']){const auth={principal,assignments:[]};assert.equal(canAssignRole(auth,'organisation','dunerealms','executive'),true);assert.equal(canAssignRole(auth,'branch','engineering','branch_lead'),true);assert.equal(canAssignRole(auth,'organisation','dunerealms','owner_ceo'),false);assert.equal(canAssignRole(auth,'branch','invented','officer'),false);}
});
test('policy mapping rejects native editors, unregistered permissions and excessive bank power',()=>{
assert.throws(()=>validatePolicyNodes(['*'],'organisation','executive'));
assert.throws(()=>validatePolicyNodes(['web.luckperms.edit'],'organisation','executive'));
assert.throws(()=>validatePolicyNodes(['web.bank.staff.manage'],'branch','officer'));
assert.deepEqual(validatePolicyNodes(['web.bank.staff.manage'],'department','department_head'),['web.bank.staff.manage']);
assert.deepEqual(validatePolicyNodes(['web.posts.view','web.posts.view'],'branch','officer'),['web.posts.view']);
});
function fixture({principal='owner',positions=[],scopeVersion=1,current=[],existing=null,service=false,authenticated=true,allowed=true,auditFail=false,dbError=null,active=false}={}){
const writes=[];
const tx={async first(sql,args){if(sql.includes('directory_number_sequence'))return{next_number:2};if(sql.includes('directory_personnel'))return null;
if(sql.includes('SELECT a.id,p.game_link_exempt'))return {id:target,game_link_exempt:service?1:0};
if(sql.includes('FROM site_accounts'))return {id:owner};
if(sql.includes('FROM org_control_principals'))return principal?{principal_kind:principal}:null;
if(sql.includes('FROM org_scope_versions'))return {version:scopeVersion};
if(sql.includes('SELECT * FROM org_assignments'))return existing;
if(sql.includes('FROM org_role_policies'))return null;
throw Error('Unexpected SQL: '+sql);
},async query(sql,args){
if(sql.startsWith('SELECT scope_type'))return positions;
if(sql.startsWith('SELECT id,user_id,role_key'))return current;
if(auditFail&&sql.includes('INSERT INTO org_assignment_events'))throw Error('audit unavailable');
writes.push({sql,args});return [];
}};
const db={organisationAccessEnabled:active,async transaction(fn){if(dbError)throw Object.assign(new Error('Concurrent transaction'),{code:dbError});const start=writes.length;try{return await fn(tx);}catch(e){writes.splice(start);throw e;}},prepare(){return {bind(){return this;},all:async()=>({results:[]})};}};
const api=createOrganisationManagement(db,{authenticate:async()=>authenticated?{id:owner}:null,authorize:async()=>allowed,clock:()=>100});return {api,writes};
}
const body=(extra={})=>({action:'assign',userId:target,scopeType:'branch',scopeKey:'news_media',role:'officer',scopeVersion:1,reason:'Approved appointment',...extra});
const request=(data,options={})=>new Request('https://cp.dunerealms.com/api/admin/organisation/'+(options.policy?'policies':'assignments'),{method:'POST',headers:{'Origin':options.origin||'https://cp.dunerealms.com','Content-Type':'application/json'},body:JSON.stringify(data)});
test('assignment creates an audited register record without activating live permissions',async()=>{
const f=fixture();const r=await f.api(request(body()));assert.equal(r.status,200);const result=await r.json();assert.equal(result.permissionsChanged,false);assert.equal(result.scopeVersion,2);
assert.ok(f.writes.some(w=>w.sql.startsWith('INSERT INTO org_assignments')));assert.ok(f.writes.some(w=>w.sql.startsWith('INSERT INTO org_assignment_events')));assert.ok(f.writes.every(w=>!w.sql.includes('cp_account_ranks')&&!w.sql.includes('UPDATE site_accounts')));
});
test('fresh transaction authority defeats stale or missing scope grants',async()=>{
const f=fixture({principal:null});assert.equal((await f.api(request(body()))).status,403);assert.equal(f.writes.length,0);
const scoped=fixture({principal:null,positions:[position('branch','customer_support','branch_lead')]});assert.equal((await scoped.api(request(body()))).status,403);
});
test('stale versions, duplicates and a second lead roll back completely',async()=>{
for(const [options,b]of [[{scopeVersion:2},body()],[{current:[{user_id:target,role_key:'officer'}]},body()],[{current:[{user_id:owner,role_key:'branch_lead'}]},body({role:'branch_lead'})]]){const f=fixture(options);assert.equal((await f.api(request(b))).status,409);assert.equal(f.writes.length,0);}
});
test('automatic assignments cannot be revoked from the manual editor',async()=>{
const id='33333333-3333-4333-8333-333333333333';const f=fixture({existing:{id,user_id:target,scope_type:'branch',scope_key:'news_media',role_key:'officer',source_kind:'system',status:'active',version:1}});
assert.equal((await f.api(request(body({action:'revoke',assignmentId:id,version:1})))).status,403);assert.equal(f.writes.length,0);
});
test('service identities stay outside staff appointments and cross-origin writes are denied',async()=>{
const f=fixture({service:true});assert.equal((await f.api(request(body()))).status,403);assert.equal(f.writes.length,0);
const g=fixture();assert.equal((await g.api(request(body(),{origin:'https://evil.example'}))).status,403);assert.equal(g.writes.length,0);
});
test('denials and forged request metadata never write to the register',async()=>{
for(const [options,status]of [[{authenticated:false},401],[{allowed:false},403]]){const f=fixture(options);assert.equal((await f.api(request(body()))).status,status);assert.equal(f.writes.length,0);}
for(const b of [body({source:'election'}),body({reason:' '}),body({userId:'wrong'}),body({scopeVersion:0})]){const f=fixture();assert.equal((await f.api(request(b))).status,400);assert.equal(f.writes.length,0);}
});
test('audit failure prevents a partial assignment commit',async()=>{
const f=fixture({auditFail:true});await assert.rejects(()=>f.api(request(body())),/audit unavailable/);assert.equal(f.writes.length,0);
});
test('policy changes share the scope version and record their exact node set',async()=>{
const f=fixture({principal:'executive'});const {action,userId,...b}=body({nodes:['web.posts.view']});const r=await f.api(request(b,{policy:true}));assert.equal(r.status,200);assert.ok(f.writes.some(w=>w.sql.includes('INSERT INTO org_role_policies')));assert.ok(f.writes.some(w=>w.sql.includes('INSERT INTO org_assignment_events')));
});
test('database lock races are reported as refreshable conflicts, never partial success',async()=>{
for(const dbError of ['ER_LOCK_DEADLOCK','ER_LOCK_WAIT_TIMEOUT']){const f=fixture({dbError});const r=await f.api(request(body()));assert.equal(r.status,409);assert.equal(f.writes.length,0);assert.match((await r.json()).message,/Refresh/);}
});
test('control bootstrap pins existing identities, is idempotent and rejects conflicting principals',async()=>{
const rows=[['unimatrix999','f3ffda37-01e4-41ea-b89d-fbeda82e453e'],['dev','f7b88778-f0bc-41cc-9227-d8ef2f52264d'],['grmacken',owner],['richwjr',target],['mr_blueray','33333333-3333-4333-8333-333333333333']].map(([username,id])=>({username,id}));
let commits=0;const principals=new Map();
const db={prepare(sql){return{bind(){return this;},async all(){return{results:rows};},async first(){return{game_link_exempt:1,service_uuid:'00000000-0000-4000-8000-00000000de01'};}};},async transaction(work){return work({async first(sql,args){if(sql.includes('org_control_principals'))return principals.has(args[0])?{principal_kind:principals.get(args[0])}:null;return rows.find(r=>r.id===args[0]);},async query(sql,args){if(sql.startsWith('INSERT INTO org_control_principals')){principals.set(args[0],args[1]);commits++;}}});}};
assert.equal((await bootstrapControl(db)).applied,false);assert.equal(commits,0);
await bootstrapControl(db,{apply:true});await bootstrapControl(db,{apply:true});assert.equal(commits,5);
principals.set(owner,'owner');await assert.rejects(()=>bootstrapControl(db,{apply:true}),/differs/);
rows[0].id=target;await assert.rejects(()=>bootstrapControl(db),/identities/);
});
test('Activated assignment change queues the native sync in the same transaction',async()=>{const f=fixture({active:true});const r=await f.api(request(body()));assert.equal(r.status,200);const data=await r.json();assert.equal(data.permissionsChanged,true);assert.equal(data.enforcement,'active');assert.equal(data.nativeSyncPending,true);assert(f.writes.some(w=>w.sql.startsWith('INSERT INTO native_sync_outbox')));});