forked from unimatrix/web
Map explicit department and branch policies with audited idempotent bootstrap
This commit is contained in:
parent
85339bc152
commit
35dd7f8dca
5 changed files with 113 additions and 0 deletions
|
|
@ -96,3 +96,5 @@ Cash conversion is reserved for the future in-game GUI + central API in both
|
|||
directions. No cash web page, redeem code flow or game changes in this batch.
|
||||
|
||||
Effective-access preview: GET /api/admin/organisation/effective?userId=UUID requires web.ranks.manage and computes explicit new-model grants with provenance. Branch Leads inherit their own Officer policy. Missing policies and blocked unsafe grants are reported. Staff Directory has an Access preview tab; User context does not. Payroll requires a pinned Big Four control principal (Dev service exception), never an Executive title alone. No live rank mutation or native projection is activated by this endpoint.
|
||||
|
||||
Default policies now enumerate 22 function mappings (nine branches with Officer/Lead, two Department Heads, Owner/Executive). Native permission editors are excluded for humans; official bank management remains departmental/executive, payroll requires pinned control identity. bootstrap-organisation-policies.mjs defaults to a plan; explicit --apply --actor=UUID requires an active control principal, retains existing policies, versions each scope and audits inserts atomically. It stores preparation data only, with no legacy rank replacement, user appointments or native group projection.
|
||||
|
|
|
|||
40
website/node/organisation-default-policies.mjs
Normal file
40
website/node/organisation-default-policies.mjs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import {NODES} from './permissions.mjs';
|
||||
import {ORGANISATION} from './organisation-model.mjs';
|
||||
import {validatePolicyNodes} from './organisation-management.mjs';
|
||||
const staff=['web.menu.staffmanual','web.mail.internal.view'];
|
||||
const branchNodes={
|
||||
customer_support:['web.menu.tickets','web.tickets.staff','web.accounts.view','dune.tickets.staff','dune.staff.open','dune.staff.history'],
|
||||
sales_accounts:['web.menu.tickets','web.tickets.staff','web.shop.support','web.accounts.view','web.bank.staff.view'],
|
||||
content_creative:['web.menu.items','web.items.manage','web.menu.inventory','web.quests.view','web.quests.manage','dune.items.give','dune.quests.view','dune.quests.admin','dune.atelier.view','dune.atelier.redeem'],
|
||||
news_media:['web.menu.posts','web.posts.view','web.posts.edit'],
|
||||
trust_safety:['web.menu.bans','web.bans.view','web.bans.manage','web.bans.evidence','web.bans.tickets','web.tickets.appeals','web.menu.forum','web.forum.moderate','web.menu.tickets','web.tickets.staff','dune.staff.open','dune.staff.history','dune.staff.kick','dune.staff.warn','dune.staff.mute','dune.staff.ban.local','dune.ban.local','dune.unban.local','dune.moderation.ban','dune.moderation.unban','duneprotect.inspect','duneprotect.lookup'],
|
||||
it_operations:['web.menu.servers','web.servers.view','web.servers.logs','web.servers.power','web.servers.console','duneprotect.inspect','duneprotect.lookup','duneprotect.regions'],
|
||||
engineering:['web.menu.items','web.items.manage','web.menu.servers','web.servers.view','web.servers.logs','web.luckperms.view','web.quests.view'],
|
||||
people_operations:['web.accounts.view','web.menu.staffmanual','web.menu.tickets','web.tickets.staff'],
|
||||
legal_compliance:['web.accounts.view','web.menu.tickets','web.tickets.staff','web.tickets.appeals','web.bans.view']
|
||||
};
|
||||
const leadNodes={
|
||||
customer_support:['web.tickets.admin'],sales_accounts:['web.bank.projects.approve'],
|
||||
content_creative:['duneprotect.worldedit','duneprotect.rollback','duneprotect.restore'],
|
||||
news_media:['web.posts.publish'],trust_safety:['dune.staff.ban.network','dune.ban.global','dune.unban.global'],
|
||||
it_operations:['web.git.admin'],engineering:['web.menu.permissions','web.ranks.manage','web.accounts.assign'],
|
||||
people_operations:['web.accounts.assign','web.accounts.revoke'],legal_compliance:[]
|
||||
};
|
||||
const unique=nodes=>[...new Set(nodes)].sort();
|
||||
export function defaultOrganisationPolicies(){
|
||||
const result=[];
|
||||
for(const department of ORGANISATION){
|
||||
const departmentNodes=[...staff,'web.bank.staff.view','web.bank.staff.manage','web.bank.staff.deposit','web.bank.projects.approve'];
|
||||
for(const branch of department.branches){
|
||||
const officer=unique([...staff,...branchNodes[branch.key]]),lead=unique(leadNodes[branch.key]);
|
||||
result.push({scopeType:'branch',scopeKey:branch.key,role:'officer',nodes:officer},{scopeType:'branch',scopeKey:branch.key,role:'branch_lead',nodes:lead});
|
||||
departmentNodes.push(...officer,...lead);
|
||||
}
|
||||
result.push({scopeType:'department',scopeKey:department.key,role:'department_head',nodes:unique(departmentNodes)});
|
||||
}
|
||||
// Enumerated catalogue snapshot, never '*' or OP. Native privilege editors stay Dev-only.
|
||||
const executives=Object.keys(NODES).filter(n=>!['web.luckperms.edit','cp.luckperms.edit','luckperms.editor','luckperms.applyedits','luckperms.trusteditor'].includes(n)&&!/(^|\.)op($|\.)/.test(n));
|
||||
for(const role of ['owner_ceo','executive'])result.push({scopeType:'organisation',scopeKey:'dunerealms',role,nodes:unique(executives)});
|
||||
for(const policy of result)validatePolicyNodes(policy.nodes,policy.scopeType,policy.role);
|
||||
return result;
|
||||
}
|
||||
32
website/scripts/bootstrap-organisation-policies.mjs
Normal file
32
website/scripts/bootstrap-organisation-policies.mjs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import {resolve} from 'node:path';
|
||||
import {openDatabase} from '../node/mysql.mjs';
|
||||
import {initializeOrganisation} from '../node/organisation-model.mjs';
|
||||
import {defaultOrganisationPolicies} from '../node/organisation-default-policies.mjs';
|
||||
export async function bootstrapPolicies(db,{actorId,apply=false,clock=Date.now}={}){
|
||||
if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(actorId||''))throw Error('An existing control actor UUID is required.');
|
||||
const templates=defaultOrganisationPolicies();
|
||||
if(!apply)return {applied:false,templates,permissionsChanged:false};
|
||||
return db.transaction(async tx=>{
|
||||
const actor=await tx.first("SELECT a.id,p.principal_kind FROM site_accounts a JOIN org_control_principals p ON p.user_id=a.id WHERE a.id=? AND a.password_hash NOT LIKE '!%' FOR SHARE",[actorId]);
|
||||
if(!actor||!['owner','executive','service'].includes(actor.principal_kind))throw Error('Current control principal required.');
|
||||
let created=0,retained=0;
|
||||
for(const p of templates){
|
||||
await tx.query('INSERT IGNORE INTO org_scope_versions(scope_type,scope_key,version) VALUES(?,?,1)',[p.scopeType,p.scopeKey]);
|
||||
await tx.first('SELECT version FROM org_scope_versions WHERE scope_type=? AND scope_key=? FOR UPDATE',[p.scopeType,p.scopeKey]);
|
||||
const existing=await tx.first('SELECT version FROM org_role_policies WHERE scope_type=? AND scope_key=? AND role_key=? FOR UPDATE',[p.scopeType,p.scopeKey,p.role]);
|
||||
if(existing){retained++;continue;}
|
||||
const now=clock();
|
||||
await tx.query('INSERT INTO org_role_policies(scope_type,scope_key,role_key,permissions_json,version,updated_by,updated_at) VALUES(?,?,?,?,1,?,?)',[p.scopeType,p.scopeKey,p.role,JSON.stringify(p.nodes),actorId,now]);
|
||||
await tx.query('UPDATE org_scope_versions SET version=version+1 WHERE scope_type=? AND scope_key=?',[p.scopeType,p.scopeKey]);
|
||||
await tx.query('INSERT INTO org_assignment_events(id,user_id,actor_id,action,scope_type,scope_key,reason,after_json,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[randomUUID(),null,actorId,'policy-baseline',p.scopeType,p.scopeKey,'Owner-approved Great Migration explicit function mapping',JSON.stringify({role:p.role,nodes:p.nodes,permissionsChanged:false}),now]);
|
||||
created++;
|
||||
}
|
||||
return {applied:true,created,retained,permissionsChanged:false,enforcement:'preparing'};
|
||||
});
|
||||
}
|
||||
if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){
|
||||
const db=await openDatabase(process.env);
|
||||
try{await initializeOrganisation(db);console.log(JSON.stringify(await bootstrapPolicies(db,{actorId:process.argv.find(a=>a.startsWith('--actor='))?.slice(8),apply:process.argv.includes('--apply')})));}finally{await db.close();}
|
||||
}
|
||||
20
website/tests/organisation-default-policies.test.mjs
Normal file
20
website/tests/organisation-default-policies.test.mjs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {defaultOrganisationPolicies} from '../node/organisation-default-policies.mjs';
|
||||
import {effectiveOrganisationAccess} from '../node/organisation-effective.mjs';
|
||||
import {NODES} from '../node/permissions.mjs';
|
||||
const policies=defaultOrganisationPolicies();
|
||||
test('All nine branches, two departments and executive functions have registered explicit policies',()=>{
|
||||
assert.equal(policies.length,22);assert.equal(new Set(policies.map(p=>p.scopeType+':'+p.scopeKey+':'+p.role)).size,22);
|
||||
for(const p of policies)for(const n of p.nodes){assert(Object.hasOwn(NODES,n));assert(!n.includes('*'));assert(!n.endsWith('.op'));assert.notEqual(n,'web.luckperms.edit');}
|
||||
});
|
||||
test('Bank management belongs to department/executive policies and payroll only to the Big Four policy',()=>{
|
||||
for(const p of policies){if(p.scopeType==='branch')assert(!p.nodes.includes('web.bank.staff.manage'));if(p.scopeType!=='organisation')assert(!p.nodes.includes('web.payroll.manage'));}
|
||||
});
|
||||
test('Job-specific rights do not leak between news, support and technical officers',()=>{
|
||||
const by=key=>policies.find(p=>p.scopeKey===key&&p.role==='officer').nodes;
|
||||
assert(by('news_media').includes('web.posts.edit'));assert(!by('news_media').includes('web.posts.publish'));assert(!by('customer_support').includes('dune.staff.ban.network'));assert(!by('sales_accounts').includes('web.servers.console'));assert(by('it_operations').includes('web.servers.console'));
|
||||
});
|
||||
test('Lead policy plus own officer policy yields a complete branch role',()=>{
|
||||
const result=effectiveOrganisationAccess({assignments:[{id:'news',scope_type:'branch',scope_key:'news_media',role_key:'branch_lead',status:'active',starts_at:1,ends_at:null}],policies:policies.map(p=>({scope_type:p.scopeType,scope_key:p.scopeKey,role_key:p.role,permissions_json:JSON.stringify(p.nodes),version:1})),registry:NODES,now:2});
|
||||
assert(result.nodes.includes('web.posts.edit'));assert(result.nodes.includes('web.posts.publish'));assert(!result.nodes.includes('web.bank.staff.manage'));assert.equal(result.blocked.length,0);
|
||||
});
|
||||
19
website/tests/organisation-policy-bootstrap.test.mjs
Normal file
19
website/tests/organisation-policy-bootstrap.test.mjs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {bootstrapPolicies} from '../scripts/bootstrap-organisation-policies.mjs';
|
||||
const actorId='11111111-1111-4111-8111-111111111111';
|
||||
function fixture({principal='owner',auditFail=false}={}){
|
||||
const policies=new Map(),events=[];const tx={async first(sql,args){if(sql.includes('JOIN org_control_principals'))return principal?{id:actorId,principal_kind:principal}:null;if(sql.includes('FROM org_scope_versions'))return {version:1};if(sql.includes('FROM org_role_policies'))return policies.get(args.join(':'))||null;throw Error(sql);},async query(sql,args){if(sql.startsWith('INSERT INTO org_role_policies'))policies.set(args.slice(0,3).join(':'),{version:1,nodes:args[3]});if(sql.startsWith('INSERT INTO org_assignment_events')){if(auditFail)throw Error('audit failure');events.push(args);}}};
|
||||
return {policies,events,db:{async transaction(fn){const before=new Map(policies),count=events.length;try{return await fn(tx);}catch(e){policies.clear();for(const [k,v]of before)policies.set(k,v);events.length=count;throw e;}}}};
|
||||
}
|
||||
test('Policy plan does not mutate a database and requires a valid control actor ID',async()=>{
|
||||
const plan=await bootstrapPolicies(null,{actorId});assert.equal(plan.templates.length,22);assert.equal(plan.applied,false);assert.equal(plan.permissionsChanged,false);await assert.rejects(bootstrapPolicies(null,{actorId:'owner'}));
|
||||
});
|
||||
test('Policy baseline is audited and idempotent without overwriting a custom policy',async()=>{
|
||||
const f=fixture();f.policies.set('branch:news_media:officer',{version:8,nodes:'custom'});
|
||||
const result=await bootstrapPolicies(f.db,{actorId,apply:true});assert.equal(result.created,21);assert.equal(result.retained,1);assert.equal(f.events.length,21);assert.equal(f.policies.get('branch:news_media:officer').nodes,'custom');
|
||||
const again=await bootstrapPolicies(f.db,{actorId,apply:true});assert.equal(again.created,0);assert.equal(again.retained,22);assert.equal(f.events.length,21);
|
||||
});
|
||||
test('Missing principal and failed auditing cannot leave partial policy mappings',async()=>{
|
||||
const denied=fixture({principal:null});await assert.rejects(bootstrapPolicies(denied.db,{actorId,apply:true}),/principal/);assert.equal(denied.policies.size,0);
|
||||
const failed=fixture({auditFail:true});await assert.rejects(bootstrapPolicies(failed.db,{actorId,apply:true}),/audit/);assert.equal(failed.policies.size,0);
|
||||
});
|
||||
Loading…
Reference in a new issue

Staff