fix(orchestration): provision explicit Stage owner Gate1 review access

Preserve independent proposer checks, canonical Admin UUID allowlist and deny ordinary admins. Revalidate pinned owner in read-only CI preflight; expose server-advertised card decisions and distinguish reservation from unknown real cost. Verified backend 42 HTTP/service/config tests and build; admin 18 relevant tests, app tsc and Vite build; 3 CI config tests and bash syntax.
This commit is contained in:
devops committed 2026-10-24 04:25:09 +00:00
1 parent bfb1841370
commit dfe5162832
11 files changed
+172 -11

No files matched your search

@@ -2,6 +2,7 @@ import {
PrepareWorkflowService,
PREPARE_WORKFLOW_CONFIG,
} from './prepare-workflow.service';
import { workflowConfig } from './workflow-config';
import { Module } from '@nestjs/common';
import { PrismaModule } from '../prisma/prisma.module';
import { KillSwitchService } from './kill-switch.service';
@@ -18,7 +19,7 @@ import { OrchestrationService } from './orchestration.service';
PrepareWorkflowService,
{
provide: PREPARE_WORKFLOW_CONFIG,
useValue: { workerIds: [], stageCiIds: [] },
useFactory: () => workflowConfig(process.env),
},
],
exports: [
@@ -6,7 +6,26 @@ describe('owner Gate1 hold operation', () => {
beforeEach(()=>{
task={id:'t',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',metadata:{workflowScope:'STAGE_PREPARE',createdBy:'proposer'}};
tx={$queryRaw:jest.fn().mockResolvedValue([]),orchestrationTask:{findUnique:jest.fn(async()=>task),update:jest.fn(async({data}:any)=>(task={...task,state:data.state,version:task.version+1}))},orchestrationEvent:{findUnique:jest.fn(),create:jest.fn()},orchestrationApprovalDecision:{create:jest.fn()}};
service=new PrepareWorkflowService({$transaction:async(cb:any)=>cb(tx)}, {workerIds:[],stageCiIds:[]});
service=new PrepareWorkflowService({$transaction:async(cb:any)=>cb(tx)}, {workerIds:[],stageCiIds:[],ownerReviewerIds:['12345678-1234-1234-1234-123456789012']} as any);
});
it('advertises and permits the pinned canonical Admin independent reviewer only',async()=>{
const owner={id:'12345678-1234-1234-1234-123456789012',role:'Admin'};
expect(service.project(task,owner).availableActions).toEqual(['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1']);
await expect(service.transition('t',hold,owner)).resolves.toMatchObject({state:'GATE1_HELD'});
await expect(service.decide('t',1,{decision:'APPROVED',expectedVersion:3,idempotencyKey:'owner-approve',expiresAt:new Date(Date.now()+60000).toISOString()},owner)).resolves.toMatchObject({state:'GATE1_APPROVED'});
expect(tx.orchestrationApprovalDecision.create).toHaveBeenCalledWith({data:expect.objectContaining({actorId:owner.id})});
});
it.each(['Admin','SUPER_ADMIN'])('never permits proposer self-review even if allowlisted: %s',async role=>{
const actor={id:'12345678-1234-1234-1234-123456789012',role}; task.metadata.createdBy=actor.id;
expect(service.project(task,actor).availableActions).toEqual([]);
await expect(service.transition('t',hold,actor)).rejects.toMatchObject({status:403});
await expect(service.decide('t',1,{decision:'REJECTED',expectedVersion:2,idempotencyKey:'self',expiresAt:new Date(Date.now()+60000).toISOString()},actor)).rejects.toMatchObject({status:403});
expect(tx.orchestrationTask.update).not.toHaveBeenCalled();
});
it.each([{id:'other',role:'Admin'},{id:'12345678-1234-1234-1234-123456789012',role:'User'},{id:'12345678-1234-1234-1234-123456789012',role:'ADMIN'}])('denies noncanonical or ungranted reviewer %j',async actor=>{
expect(service.project(task,actor).availableActions).toEqual([]);
await expect(service.decide('t',1,{decision:'REJECTED',expectedVersion:2,idempotencyKey:'deny',expiresAt:new Date(Date.now()+60000).toISOString()},actor)).rejects.toMatchObject({status:403});
expect(tx.orchestrationTask.update).not.toHaveBeenCalled();
});
const hold={toState:'GATE1_HELD',expectedVersion:2,idempotencyKey:'hold-t',reason:'Need revised budget'};
it('advertises hold only to independent owner reviewer',()=>{
@@ -0,0 +1,48 @@
import {Test} from '@nestjs/testing';
import {INestApplication} from '@nestjs/common';
import request from 'supertest';
import {OrchestrationController} from './orchestration.controller';
import {OrchestrationService} from './orchestration.service';
import {PrepareWorkflowService} from './prepare-workflow.service';
import {JwtAuthGuard} from '../auth/jwt-auth.guard';
import {RolesGuard} from '../common/guards/roles.guard';
describe('configured owner real workflow HTTP authorization',()=>{
const owner='12345678-1234-1234-1234-123456789012';
let app:INestApplication,task:any,tx:any;
beforeAll(async()=>{
tx={$queryRaw:jest.fn(async()=>[]),orchestrationTask:{findUnique:async()=>task,update:jest.fn(async({data}:any)=>(task={...task,state:data.state,version:task.version+1}))},orchestrationEvent:{findUnique:jest.fn(),create:jest.fn()},orchestrationApprovalDecision:{create:jest.fn()}};
const workflow=new PrepareWorkflowService({$transaction:async(cb:any)=>cb(tx)},{workerIds:[],stageCiIds:[],ownerReviewerIds:[owner]});
const m=await Test.createTestingModule({controllers:[OrchestrationController],providers:[{provide:OrchestrationService,useValue:{findAll:async()=>[task],findOne:async()=>task}},{provide:PrepareWorkflowService,useValue:workflow},RolesGuard]})
.overrideGuard(JwtAuthGuard).useValue({canActivate(c:any){const r=c.switchToHttp().getRequest();if(!r.headers.authorization)return false;r.user={sub:r.headers.authorization,role:'ADMIN'};return true;}}).compile();
app=m.createNestApplication();await app.init();
});
beforeEach(()=>{jest.clearAllMocks();task={id:'t',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',metadata:{workflowScope:'STAGE_PREPARE',createdBy:'pmo'}};});
afterAll(async()=>{await app.close();});
it.each(['APPROVED','REJECTED'])('advertises and executes %s only for verified granted JWT subject',async decision=>{
const r=await request(app.getHttpServer()).get('/admin/orchestration/tasks').set('Authorization',owner).expect(200);
expect(r.body[0].availableActions).toEqual(['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1']);
await request(app.getHttpServer()).post('/admin/orchestration/tasks/t/gates/1/decide').set('Authorization',owner).send({decision,expectedVersion:2,idempotencyKey:'decision',expiresAt:new Date(Date.now()+60000).toISOString(),notes:'Delegated system testing by independent owner'}).expect(201);
expect(tx.orchestrationApprovalDecision.create).toHaveBeenCalledWith({data:expect.objectContaining({actorId:owner,decision})});
expect(tx.orchestrationEvent.create).toHaveBeenCalledWith({data:expect.objectContaining({actorId:owner,payload:expect.objectContaining({fingerprint:expect.stringContaining('Delegated system testing')})})});
});
it('holds via canonicalized ADMIN without granting proposer powers',async()=>{
await request(app.getHttpServer()).put('/admin/orchestration/tasks/t/transition').set('Authorization',owner).send({toState:'GATE1_HELD',expectedVersion:2,idempotencyKey:'hold',reason:'Independent owner needs evidence'}).expect(200);
expect(tx.orchestrationApprovalDecision.create).not.toHaveBeenCalled();
});
it.each(['ordinary-admin','pmo'])('denies ungranted subject %s and body impersonation',async subject=>{
const r=await request(app.getHttpServer()).get('/admin/orchestration/tasks').set('Authorization',subject).expect(200);
expect(r.body[0].availableActions).toEqual([]);
const body={decision:'APPROVED',expectedVersion:2,idempotencyKey:'deny',expiresAt:new Date(Date.now()+60000).toISOString()};
await request(app.getHttpServer()).post('/admin/orchestration/tasks/t/gates/1/decide').set('Authorization',subject).send(body).expect(403);
await request(app.getHttpServer()).post('/admin/orchestration/tasks/t/gates/1/decide').set('Authorization',subject).send({...body,actorId:owner}).expect(400);
await request(app.getHttpServer()).put('/admin/orchestration/tasks/t/transition').set('Authorization',subject).send({toState:'GATE1_HELD',expectedVersion:2,idempotencyKey:'hold',reason:'hold'}).expect(403);
expect(tx.orchestrationTask.update).not.toHaveBeenCalled();
});
it('denies grant holder self review, Gate2 and release',async()=>{
task.metadata.createdBy=owner;
await request(app.getHttpServer()).post('/admin/orchestration/tasks/t/gates/1/decide').set('Authorization',owner).send({decision:'APPROVED',expectedVersion:2,idempotencyKey:'self',expiresAt:new Date(Date.now()+60000).toISOString()}).expect(403);
await request(app.getHttpServer()).post('/admin/orchestration/tasks/t/gates/2/decide').set('Authorization',owner).send({}).expect(403);
await request(app.getHttpServer()).post('/admin/orchestration/tasks/t/commands/RELEASE_AUTHORIZE').set('Authorization',owner).send({}).expect(403);
expect(tx.orchestrationTask.update).not.toHaveBeenCalled();
});
});
@@ -14,6 +14,7 @@ export interface WorkflowIdentity {
role: string;
}
export interface WorkflowConfig {
ownerReviewerIds?: string[];
workerIds: string[];
stageCiIds: string[];
}
@@ -34,6 +35,11 @@ export class PrepareWorkflowService {
)
throw new ForbiddenException('Authenticated workflow identity required');
}
private reviewer(a: WorkflowIdentity) {
return typeof a?.id === 'string' && !!a.id && a.id.length <= 100 &&
(a.role === 'SUPER_ADMIN' ||
(a.role === 'Admin' && (this.config.ownerReviewerIds ?? []).includes(a.id)));
}
private worker(a: WorkflowIdentity) {
this.identity(a, ['WORKFLOW_WORKER']);
if (!this.config.workerIds.includes(a.id))
@@ -199,7 +205,7 @@ export class PrepareWorkflowService {
if (await this.replay(tx, dto.idempotencyKey, fingerprint)) return t;
this.version(t, dto);
if (dto.toState === 'GATE1_HELD') {
if (a.role !== 'SUPER_ADMIN' || t.metadata.createdBy === a.id || t.state !== 'GATE1_PENDING')
if (!this.reviewer(a) || t.metadata.createdBy === a.id || t.state !== 'GATE1_PENDING')
throw new ForbiddenException('Independent Gate1 reviewer and pending proposal required');
if (typeof dto.reason !== 'string' || !dto.reason.trim() || dto.reason.length > 2000)
throw new BadRequestException('Hold requires reason of 1..2000 characters');
@@ -237,7 +243,8 @@ export class PrepareWorkflowService {
});
}
async decide(id: string, gate: number, dto: any, a: WorkflowIdentity) {
this.identity(a, ['SUPER_ADMIN']);
if (!this.reviewer(a))
throw new ForbiddenException('Provisioned independent Gate1 reviewer required');
if (gate !== 1)
throw new ForbiddenException(
'Gate2 decisions and release remain disabled',
@@ -543,7 +550,7 @@ export class PrepareWorkflowService {
actions.push('QUEUE_PREPARE');
if (
safe &&
a?.role === 'SUPER_ADMIN' &&
this.reviewer(a) &&
t.metadata?.createdBy !== a.id &&
['GATE1_PENDING', 'GATE1_HELD'].includes(t.state)
) {
@@ -0,0 +1,11 @@
import { workflowConfig } from './workflow-config';
describe('startup owner reviewer configuration',()=>{
it('defaults denied, accepts explicit UUID only in staging',()=>{
expect(workflowConfig({}).ownerReviewerIds).toEqual([]);
expect(workflowConfig({NODE_ENV:'production',CANINA_WORKFLOW_OWNER_REVIEWER_IDS:'12345678-1234-1234-1234-123456789012'})).toMatchObject({ownerReviewerIds:[]});
expect(workflowConfig({CANINA_ENV:'staging',CANINA_WORKFLOW_OWNER_REVIEWER_IDS:'12345678-1234-1234-1234-123456789012'}).ownerReviewerIds).toEqual(['12345678-1234-1234-1234-123456789012']);
});
it.each(['*','admin','12345678-1234-1234-1234-123456789012,'])('fails startup on malformed explicit grant %s',ids=>{
expect(()=>workflowConfig({CANINA_ENV:'staging',CANINA_WORKFLOW_OWNER_REVIEWER_IDS:ids})).toThrow('Invalid owner reviewer UUID allowlist');
});
});
@@ -0,0 +1,9 @@
import type { WorkflowConfig } from './prepare-workflow.service';
/** Startup-only configuration; HTTP payloads can never supply reviewer grants. */
export function workflowConfig(env: NodeJS.ProcessEnv): WorkflowConfig {
const raw = env.CANINA_ENV === 'staging' ? env.CANINA_WORKFLOW_OWNER_REVIEWER_IDS ?? '' : '';
const ids = raw ? raw.split(',') : [];
if (ids.length > 20 || ids.some(id => !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(id)))
throw new Error('Invalid owner reviewer UUID allowlist');
return {workerIds:[],stageCiIds:[],ownerReviewerIds:[...new Set(ids)]};
}
@@ -116,3 +116,17 @@ it('separates human evidence from server workflow scope without inventing a mark
expect(await screen.findByText('محدوده و معیارهای پذیرش گزارش‌شده از سرور')).toBeInTheDocument();
expect(screen.getByText('محدوده گردش کار سرور: در نمای امن در دسترس نیست.')).toBeInTheDocument();
});
it('shows advertised decisions directly on pending card and labels reservation not measured cost',async()=>{
const ownerTask={...task,budgetLimitCents:20,availableActions:['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1']};
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[ownerTask]:ownerTask}));
render(<OrchestrationCommandCenter/>);
const card=await screen.findByRole('region',{name:'منتظر تصمیم شما'});
expect(await within(card).findByRole('button',{name:'تأیید کار محدود در Gate1'})).toBeEnabled();
expect(within(card).getByRole('button',{name:'رد کار در Gate1'})).toBeEnabled();
expect(within(card).getByRole('button',{name:'تعویق تصمیم Gate1'})).toBeEnabled();
expect(within(card).getByText('رزرو آزمایشی؛ هزینه واقعی نامشخص')).toBeInTheDocument();
fireEvent.click(within(card).getByRole('button',{name:'تعویق تصمیم Gate1'}));
expect(await screen.findByRole('region',{name:'جزئیات وظیفه'})).toBeInTheDocument();
expect(api.post).not.toHaveBeenCalled(); expect(api.put).not.toHaveBeenCalled();
});
@@ -64,10 +64,10 @@ export default function OrchestrationCommandCenter() {
{success&&<p role="status">{success}</p>}
{section==='وظیفه‌ها و تأییدها'&&capabilities.mutations&&<CreateOrchestrationTask onCreated={()=>void loadTasks()}/>}
{section==='نمای کلی'&&<section aria-label="منتظر تصمیم شما" className="border-2 border-purple-300 bg-purple-50 rounded-2xl p-5 space-y-4">
<h2 className="text-xl font-black">منتظر تصمیم شما</h2><p>تصمیم Gate1 برای کار محدود؛ تأیید به‌معنای انتشار یا اجرای Production نیست. اقدام‌ها پس از دریافت جزئیات از سرور نمایش داده می‌شوند.</p>
<h2 className="text-xl font-black">منتظر تصمیم شما</h2><p>تصمیم Gate1 برای کار محدود؛ تأیید به‌معنای انتشار یا اجرای Production نیست. دکمه‌ها فقط اقدام‌های مجاز اعلام‌شده توسط سرور هستند؛ برای بررسی و تصمیم، جزئیات را باز کنید.</p>
<label>فیلتر تصمیم‌ها<select aria-label="فیلتر تصمیم‌ها" value={decisionFilter} onChange={e=>setDecisionFilter(e.target.value)} className="border rounded p-2 m-2"><option value="ALL">در انتظار و به‌تعویق‌افتاده</option><option value="GATE1_PENDING">در انتظار تصمیم</option><option value="GATE1_HELD">به‌تعویق‌افتاده</option></select></label>
{!loading&&!error&&!tasks.some(t=>['GATE1_PENDING','GATE1_HELD'].includes(t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter))&&<p>تصمیمی در این فیلتر منتظر نیست.</p>}
{!loading&&!error&&tasks.filter(t=>['GATE1_PENDING','GATE1_HELD'].includes(t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter)).map(t=><article key={t.id} className="bg-white border rounded-xl p-4 space-y-3"><button disabled={!!pending||busy} className="font-bold text-purple-700 underline" onClick={()=>void select(t)}>{t.title}</button><p>{label(t.department)} · {label(t.state)} · سقف بودجه: {t.budgetLimitCents??'نامشخص'} سنت</p>{selected?.id!==t.id&&<><p>محدوده: {typeof t.metadata?.scope==='string'?t.metadata.scope:'گزارش نشده؛ جزئیات را بررسی کنید'}</p><h3>معیارهای پذیرش</h3>{Array.isArray(t.metadata?.acceptanceCriteria)&&t.metadata.acceptanceCriteria.every(c=>typeof c==='string')?<ul className="list-disc list-inside">{(t.metadata.acceptanceCriteria as string[]).map((c,i)=><li key={i}>{c}</li>)}</ul>:<p>گزارش نشده؛ جزئیات را بررسی کنید</p>}</>}</article>)}
{!loading&&!error&&tasks.filter(t=>['GATE1_PENDING','GATE1_HELD'].includes(t.state)&&(decisionFilter==='ALL'||t.state===decisionFilter)).map(t=><article key={t.id} className="bg-white border rounded-xl p-4 space-y-3"><button disabled={!!pending||busy} className="font-bold text-purple-700 underline" onClick={()=>void select(t)}>{t.title}</button><p>{label(t.department)} · {label(t.state)} · سقف بودجه: {t.budgetLimitCents??'نامشخص'} سنت</p><p>رزرو آزمایشی؛ هزینه واقعی نامشخص</p><div className="flex flex-wrap gap-2">{t.availableActions.filter(a=>['APPROVE_GATE1','REJECT_GATE1','HOLD_GATE1'].includes(a.id)).map(a=><Button key={a.id} disabled={!capabilities.mutations||!!pending||busy||!!actionBlockReason(t,a)} onClick={()=>void select(t)}>{actionLabel(a)}</Button>)}</div>{selected?.id!==t.id&&<><p>محدوده: {typeof t.metadata?.scope==='string'?t.metadata.scope:'گزارش نشده؛ جزئیات را بررسی کنید'}</p><h3>معیارهای پذیرش</h3>{Array.isArray(t.metadata?.acceptanceCriteria)&&t.metadata.acceptanceCriteria.every(c=>typeof c==='string')?<ul className="list-disc list-inside">{(t.metadata.acceptanceCriteria as string[]).map((c,i)=><li key={i}>{c}</li>)}</ul>:<p>گزارش نشده؛ جزئیات را بررسی کنید</p>}</>}</article>)}
</section>}
{section==='نمای کلی'&&!loading&&!error&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">فهرست وظیفه‌های ثبت‌شده</h2><p>{tasks.length} وظیفه از سرور دریافت شد. این فهرست نشان‌دهنده سلامت عامل یا وضعیت زنده اجرا نیست.</p><div className="flex flex-wrap gap-3">{[...new Set(tasks.map(t=>t.state))].map(state=><span key={state} className="border rounded-xl p-3">{label(state)}: {tasks.filter(t=>t.state===state).length}</span>)}</div></section>}
{(['نمای کلی','وظیفه‌ها و تأییدها','اجراها و خروجی‌ها'] as Section[]).includes(section)&&<section className="bg-white border rounded-2xl p-5 space-y-4"><label>جست‌وجوی وظیفه‌ها<input className="border rounded-lg p-2 m-2" value={search} onChange={e=>setSearch(e.target.value)}/></label>
@@ -78,7 +78,7 @@ export default function OrchestrationCommandCenter() {
<h3 className="font-bold">اقدام‌های مجاز اعلام‌شده توسط سرور</h3>{!selected.availableActions.length&&<p>اقدامی اعلام نشده است. این نما فقط خواندنی است؛ مرورگر مجوز یا تغییر وضعیت ایجاد نمی‌کند.</p>}<div className="flex flex-wrap gap-2">{selected.availableActions.map(a=><Button key={a.id} disabled={!capabilities.mutations||!!actionBlockReason(selected,a)} title={!capabilities.mutations?'تغییرات از طرف سرور مجاز نیست':actionBlockReason(selected,a)} onClick={()=>open(selected,a)}>{actionLabel(a)}</Button>)}</div>
<h3 className="font-bold">تصمیم‌های تأیید تغییرناپذیر</h3><Json value={selected.decisions??[]}/>
<h3 className="font-bold">اجراها و خروجی‌های ثبت‌شده</h3>{!selected.runs?.length&&<p>اجرای ثبت‌شده‌ای وجود ندارد.</p>}{selected.runs?.map(r=><article key={r.id} className="border rounded-xl p-3 space-y-2"><h4>{r.id} · {label(r.status)}</h4><p>کامیت: {r.commitSha} · محیط: {r.environment}</p>{r.artifacts.map(a=><Json key={a.id} value={a}/>)}</article>)}
<h3 className="font-bold">دفتر بودجه (سنت؛ نه مصرف تخمینی)</h3><Json value={selected.budgetLedger??[]}/><h3 className="font-bold">رویدادهای ممیزی به‌ترتیب</h3><Json value={selected.events??[]}/>
<p>رزرو آزمایشی؛ هزینه واقعی نامشخص</p><h3 className="font-bold">دفتر بودجه (سنت؛ رزرو با هزینه واقعی متفاوت است)</h3><Json value={selected.budgetLedger??[]}/><h3 className="font-bold">رویدادهای ممیزی به‌ترتیب</h3><Json value={selected.events??[]}/>
</section>}
{snapshot&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2>{section}</h2><p>زمان دریافت از سرور: {snapshot.measuredAt}</p>{!snapshot.items.length&&<p>رکوردی از سرور دریافت نشد.</p>}<div className="grid md:grid-cols-2 gap-3">{snapshot.items.map(item=><article key={item.id} className="border rounded-xl p-4"><h3 className="font-bold">{item.title??item.id}</h3><dl>{Object.entries(item).filter(([k])=>k!=='id'&&k!=='title').map(([k,v])=><div key={k} className="flex justify-between gap-3"><dt>{label(k)}</dt><dd>{String(v??'نامشخص')}</dd></div>)}</dl></article>)}</div><p>تغییر تنظیمات فقط با فرمان مجاز سرور ممکن است؛ مرورگر فرمانی ایجاد نمی‌کند.</p></section>}
{section==='توقف اضطراری'&&!capabilities.killSwitch&&<p>کنترل توقف اضطراری در این نسخه در دسترس نیست؛ مسیر سرور اجازه تغییر نمی‌دهد.</p>}
+15 -3
View File
@@ -5,6 +5,7 @@ stage_runtime_provision() {
[ "${GITHUB_ACTIONS:-${GITEA_ACTIONS:-}}" = true ]
[ "${STAGE_PROVISION_ENABLED:-}" = true ]
export DEPLOY_SHA STAGE_PROVISION_APPROVED_SHA="$DEPLOY_SHA" CI=true
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s scripts -p test_stage_owner_review.py
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s infra/hermes-editorial/tests
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s scripts -p test_editorial_provision.py
PYTHONDONTWRITEBYTECODE=1 python3 - <<'PY'
@@ -59,11 +60,14 @@ root=Path('/opt/services/canina/stage-runtime')
query="""const {PrismaClient}=require('@prisma/client');const p=new PrismaClient();
(async()=>{try{const rows=await p.$transaction(async tx=>{
await tx.$executeRawUnsafe('SET TRANSACTION READ ONLY');
return tx.$queryRawUnsafe(\"SELECT id::text FROM users WHERE lower(replace(replace(role::text, '_', ''), '-', '')) IN ('admin','superadmin') ORDER BY id LIMIT 1001\");
return tx.$queryRawUnsafe(\"SELECT id::text, role::text FROM users WHERE lower(replace(replace(role::text, '_', ''), '-', '')) IN ('admin','superadmin') ORDER BY id LIMIT 1001\");
});process.stdout.write(JSON.stringify(rows));}catch{process.exitCode=1;}finally{await p.$disconnect();}})();"""
rows=json.loads(docker('exec','-w','/app','canino_backend_stage','node','-e',query))
if not 1<=len(rows)<=1000 or any(not isinstance(r,dict) or set(r)!={'id'} or not isinstance(r['id'],str) or not re.fullmatch('[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}',r['id']) for r in rows):
if not 1<=len(rows)<=1000 or any(not isinstance(r,dict) or set(r)!={'id','role'} or not isinstance(r['id'],str) or not re.fullmatch('[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}',r['id']) for r in rows):
raise ValueError('Verified admin subjects required')
spec=importlib.util.spec_from_file_location('owner','scripts/stage-owner-review.py')
owner=importlib.util.module_from_spec(spec);spec.loader.exec_module(owner)
owner_ids=owner.verified_owner_ids(rows)
m.provision(root,uid,gid)
spec=importlib.util.spec_from_file_location('editorial','scripts/provision-editorial-runtime.py')
editorial=importlib.util.module_from_spec(spec);spec.loader.exec_module(editorial)
@@ -74,7 +78,7 @@ dest=root/'snapshots'/capture
m.export_snapshot(db,dest,'default',uid,gid)
grants=root/'snapshots'/(capture+'-grants.json')
m.write_private(grants,json.dumps({r['id']:['default'] for r in rows}),uid,gid)
Path('.stage-runtime.json').write_text(json.dumps({'snapshot':str(dest),'grants':str(grants)}))
Path('.stage-runtime.json').write_text(json.dumps({'snapshot':str(dest),'grants':str(grants),'ownerReviewerIds':owner_ids}))
print('Stage projected snapshot captured; existing admin grants verified; no executor started')
PY
}
@@ -93,6 +97,14 @@ from pathlib import Path
p=Path('.stage-runtime-merged.json');c=json.loads(p.read_text())
b=c['services']['backend_stage']
b.setdefault('environment',{})['CANINA_RUNTIME_READ_ENABLED']='true'
owner_ids=json.loads(Path('.stage-runtime.json').read_text())['ownerReviewerIds']
spec_path=Path('scripts/stage-owner-review.py')
import importlib.util
spec=importlib.util.spec_from_file_location('owner',spec_path)
owner=importlib.util.module_from_spec(spec);spec.loader.exec_module(owner)
assert owner_ids==[owner.STAGE_OWNER_SUBJECT], 'Explicit verified owner required'
b['environment']['CANINA_ENV']='staging'
b['environment']['CANINA_WORKFLOW_OWNER_REVIEWER_IDS']=','.join(owner_ids)
b.setdefault('networks',{})['traefik_public']=None
b.setdefault('labels',{})['traefik.docker.network']='traefik_public'
c['secrets']['hermes_runtime_grants']['file']=json.loads(Path('.stage-runtime.json').read_text())['grants']
+8
View File
@@ -0,0 +1,8 @@
# Stage-only named grant: explicit user-authorized owner, not discovery of all admins.
# Parent verified this exact persisted subject read-only; CI rechecks before rendering.
STAGE_OWNER_SUBJECT='12345678-1234-1234-1234-123456789012'
def verified_owner_ids(rows):
matches=[r for r in rows if r.get('id')==STAGE_OWNER_SUBJECT]
if len(matches)!=1 or matches[0].get('role','').lower().replace('_','').replace('-','')!='admin':
raise ValueError('Pinned Stage owner must exist with Admin role')
return [STAGE_OWNER_SUBJECT]
+32
View File
@@ -0,0 +1,32 @@
import importlib.util
import unittest
from pathlib import Path
spec=importlib.util.spec_from_file_location('owner',Path(__file__).with_name('stage-owner-review.py'))
owner=importlib.util.module_from_spec(spec);spec.loader.exec_module(owner)
class OwnerReviewTests(unittest.TestCase):
def test_verified_pinned_admin_only(self):
self.assertEqual(owner.verified_owner_ids([{'id':owner.STAGE_OWNER_SUBJECT,'role':'ADMIN'},{'id':'other','role':'ADMIN'}]),[owner.STAGE_OWNER_SUBJECT])
def test_missing_wrong_role_denied(self):
for rows in [[],[{'id':'other','role':'ADMIN'}],[{'id':owner.STAGE_OWNER_SUBJECT,'role':'SUPER_ADMIN'}],[{'id':owner.STAGE_OWNER_SUBJECT,'role':'User_PetOwner'}]]:
with self.subTest(rows=rows),self.assertRaises(ValueError):owner.verified_owner_ids(rows)
def test_actual_ci_render_sets_only_pinned_backend_reviewer(self):
import json, os, tempfile, subprocess
script=Path(__file__).with_name('rollout-stage.sh').read_text()
render=script.split('stage_runtime_render() {',1)[1].split("python3 - <<'PY'",1)[1].split('\nPY',1)[0]
with tempfile.TemporaryDirectory(dir=Path(__file__).parent.parent) as d:
root=Path(d);(root/'scripts').mkdir()
(root/'scripts/stage-owner-review.py').write_text(Path(__file__).with_name('stage-owner-review.py').read_text())
compose={'services':{'db_stage':{},'redis_stage':{},'frontend_stage':{},'backend_stage':{},'runtime-inventory':{}},'secrets':{'hermes_runtime_grants':{}},'networks':{'hermes_inventory_backend':{'internal':True},'traefik_public':{'external':True}}}
def write(ids):
(root/'.stage-runtime-merged.json').write_text(json.dumps(compose))
(root/'.stage-runtime.json').write_text(json.dumps({'grants':'/verified/grants','ownerReviewerIds':ids}))
write([owner.STAGE_OWNER_SUBJECT])
subprocess.run(['python3','-c',render],cwd=root,check=True,env={**os.environ,'PYTHONDONTWRITEBYTECODE':'1'})
result=json.loads((root/'.stage-compose.json').read_text())
self.assertEqual(result['services']['backend_stage']['environment']['CANINA_WORKFLOW_OWNER_REVIEWER_IDS'],owner.STAGE_OWNER_SUBJECT)
self.assertEqual(result['services']['backend_stage']['environment']['CANINA_ENV'],'staging')
self.assertNotIn('environment',result['services']['frontend_stage'])
write(['another-admin'])
rejected=subprocess.run(['python3','-c',render],cwd=root,capture_output=True)
self.assertNotEqual(rejected.returncode,0)