Files
mtusi2026lab6/scripts/provision-openobserve-accounts.ts

54 lines
8.0 KiB
TypeScript

import {createAccountHTTP} from './lib/openobserve-account-http';
import {createAccountBootstrap,accountEmail,type AccountKey,type Account,type Intent} from './lib/openobserve-bootstrap';
import {mkdir,readFile,writeFile,link,open} from 'node:fs/promises';
import {resolve} from 'node:path';
const root=resolve(import.meta.dir,'..'),local=resolve(root,'.local');
if(process.argv.includes('--dry-run')){console.log('Validated native fixed localhost service-account provisioning invocation; no credential reads or mutations.');process.exit(0);}
const endpoint='http://127.0.0.1:28406';
const inspect=Bun.spawnSync(['docker','inspect','mtuci-vp6-medvedev-openobserve-1'],{stdout:'pipe',stderr:'pipe'});
if(inspect.exitCode!==0)throw new Error('own OpenObserve missing');
const n=JSON.parse(new TextDecoder().decode(inspect.stdout))[0];
if(!n.State.Running||n.Config.Labels['com.docker.compose.project']!=='mtuci-vp6-medvedev'||n.Image!=='sha256:26618f379c86b253c0d91624c487dd14b71293699845ecbc8457c94dca14819f')throw new Error('own OpenObserve identity mismatch');
const output=resolve(local,'openobserve-accounts-'+crypto.randomUUID());
await mkdir(output,{mode:0o700});
await writeFile(resolve(output,'CLAIM.json'),JSON.stringify({claimedAt:new Date().toISOString(),scope:'isolated default organization; owned ingest/query service accounts'})+'\n',{flag:'wx',mode:0o600});
const owner=JSON.parse(await readFile(resolve(local,'openobserve_root-v2.json'),'utf8'));
const ownerAuth='Basic '+Buffer.from(owner.email+':'+owner.password).toString('base64');
let responseSequence=0;
const accountHTTP=createAccountHTTP({request:async input=>{const response=await fetch(endpoint+input.path,{method:input.method,headers:{Authorization:input.auth,'Content-Type':'application/json'},body:input.body===undefined?undefined:JSON.stringify(input.body),signal:AbortSignal.timeout(10_000)});return{status:response.status,chunks:response.body??(async function*(){})()};},capture:async capture=>{
if(!/^(response-[0-9]{3}|create-(ingest|query))$/.test(capture.captureId))throw new Error('Invalid private capture identity');
const prefix=resolve(output,capture.captureId);
const raw=await open(prefix+'.raw.private','wx',0o600);try{await raw.writeFile(capture.raw);await raw.sync();}finally{await raw.close();}
try{await writeFile(prefix+'.meta.json',JSON.stringify({status:capture.status,outcome:capture.outcome,complete:capture.complete,bytes:capture.raw.length})+'\n',{flag:'wx',mode:0o600});}catch{/* Durable raw capture owns the primary outcome. */}
}},1_048_576);
async function call(path:string,method='GET',body?:unknown,auth=ownerAuth,captureId='response-'+String(++responseSequence).padStart(3,'0')){return accountHTTP({path,method,body,auth,captureId});}
async function readPrivate(path:string){try{return JSON.parse(await readFile(path,'utf8'));}catch(error){if((error as any).code==='ENOENT')return undefined;throw new Error('Private bootstrap record is malformed; preserve it and inspect privately');}}
// Fully written and synced bytes become visible atomically; an earlier claim is never overwritten.
async function publish(path:string,value:unknown){const text=JSON.stringify(value)+'\n';const staged=resolve(output,'staged-'+crypto.randomUUID()+'.private');const file=await open(staged,'wx',0o600);try{await file.writeFile(text);await file.sync();}finally{await file.close();}try{await link(staged,path);}catch(error){if((error as any).code!=='EEXIST')throw error;const previous=await readPrivate(path);if(JSON.stringify(previous)!==JSON.stringify(value))throw new Error('Private bootstrap record conflicts; no overwrite or POST retry');}}
const accountsFile=resolve(local,'openobserve-accounts.json');
const checkpoint=(key:AccountKey)=>resolve(local,'openobserve-account-'+key+'.json');
const intentFile=(key:AccountKey)=>resolve(local,'openobserve-account-'+key+'.intent.json');
function members(body:any){const result=body?.data??body?.list??body;if(!Array.isArray(result))throw new Error('Native account list shape unexpected');return result;}
const initial=await call('/api/default/service_accounts');if(initial.status!==200)throw new Error('Native service-account list unavailable');
const initialMembers=members(initial.body);
const users=await call('/api/default/users');if(users.status!==200||!members(users.body).some((u:any)=>u.email===owner.email&&u.role==='root'))throw new Error('Native owner/root role readback required');
const run=createAccountBootstrap({
readIndex:()=>readPrivate(accountsFile),readAccount:key=>readPrivate(checkpoint(key)),readIntent:key=>readPrivate(intentFile(key)),
makeIntent:key=>({email:accountEmail(key),rawFile:resolve(output,'create-'+key+'.raw.private'),captureId:'create-'+key}),
claimIntent:async(key,intent)=>{if(initialMembers.some((u:any)=>u.email===intent.email))throw new Error('Native account exists without an owned credential or creation intent; no POST retry');await publish(intentFile(key),intent);},
readCaptured:async(intent:Intent)=>{if(!intent.rawFile.startsWith(local+'/openobserve-accounts-')||!intent.rawFile.endsWith('/'+intent.captureId+'.raw.private')||!/^create-(ingest|query)$/.test(intent.captureId))throw new Error('Private creation capture path outside owned operation');const body=await readPrivate(intent.rawFile);if(body===undefined)return undefined;const meta=await readPrivate(intent.rawFile.replace('.raw.private','.meta.json'));return{body,status:meta?.status??null};},
create:(key,intent)=>call('/api/default/service_accounts','POST',{email:accountEmail(key),first_name:'VP6 '+key,last_name:'synthetic'},ownerAuth,intent.captureId),
saveAccount:(key,account)=>publish(checkpoint(key),account),
verify:async(key,account:Account)=>{const roles=await call('/api/default/service_accounts');if(roles.status!==200)throw new Error('Native account role readback failed');const role=members(roles.body).find((u:any)=>u.email===account.email)?.role;if(role!=='service_account')throw new Error('Native account role is not service_account; no administrative probe');
const auth='Basic '+Buffer.from(account.email+':'+account.token).toString('base64'),event='owned_'+key+'_positive_control';
const ingest=await call('/api/default/identity_probe/_json','POST',[{event}],auth);
let search:any={status:0,body:null};if(ingest.status===200){for(let attempt=0;attempt<6;attempt++){search=await call('/api/default/_search?type=logs','POST',{query:{sql:'SELECT event FROM "identity_probe" WHERE event=\''+event+'\' LIMIT 1',start_time:(Date.now()-60_000)*1000,end_time:(Date.now()+1000)*1000,size:1}},auth);if(search.status!==200||search.body?.hits?.some((row:any)=>row.event===event))break;if(attempt<5)await Bun.sleep(400);}}
const rotate=await call('/api/default/service_accounts/'+encodeURIComponent(accountEmail('query'))+'?rotateToken=true','PUT',{first_name:'VP6 query',last_name:'synthetic'},auth);
return{role,searchHTTP:search.status,searchHasRows:Array.isArray(search.body?.hits)&&search.body.hits.some((row:any)=>row.event===event),ingestHTTP:ingest.status,adminRotateHTTP:rotate.status};},
publishIndex:accounts=>publish(accountsFile,accounts),
publishDerived:async()=>{const rendered=Bun.spawnSync([process.execPath,resolve(root,'scripts/render-openobserve-credentials.ts')],{cwd:root,stdout:'pipe',stderr:'pipe'});if(rendered.exitCode!==0){await writeFile(resolve(output,'render-stderr.private'),rendered.stderr,{flag:'wx',mode:0o600});throw new Error('Dedicated credential render failed; core startup must stop');}},
});
const {proofs}=await run();const result={checkedAt:new Date().toISOString(),endpoint,organization:'default',createRoute:'POST /api/{org}/service_accounts',createRequestFields:['email','first_name','last_name'],createResponseFields:['code','message','token','user'],probes:proofs,privateCredentials:accountsFile,output,strictCapabilitiesVerified:true,durablePerAccountCheckpoints:true};
await writeFile(resolve(output,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});
console.log(JSON.stringify({checkedAt:result.checkedAt,probes:proofs,receipt:resolve(output,'RESULT.json'),credentialsPrinted:false}));