@xlinklight/testkit 7.0.0-rc.0 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +169 -169
- package/package.json +4 -4
- package/src/architecture-database.d.mts +36 -36
- package/src/architecture-database.mjs +64 -64
- package/src/artifact-observation.mjs +50 -50
- package/src/browser-lifecycle.mjs +45 -45
- package/src/cloudflare-browser.mjs +41 -41
- package/src/cloudflare-pages.d.mts +34 -34
- package/src/cloudflare-pages.mjs +170 -170
- package/src/cloudflare-provider-http.mjs +32 -32
- package/src/cluster-directory.d.mts +16 -16
- package/src/cluster-directory.mjs +90 -90
- package/src/core-publishing.d.mts +75 -75
- package/src/core-publishing.mjs +214 -214
- package/src/dev-command-runner.mjs +97 -97
- package/src/fixture-path.mjs +19 -19
- package/src/function-admission.d.mts +1 -1
- package/src/function-admission.mjs +58 -58
- package/src/host-artifact.mjs +32 -32
- package/src/host-stop.mjs +15 -15
- package/src/lifecycle-trace.mjs +32 -32
- package/src/managed-native-fixture.d.mts +84 -84
- package/src/managed-native-fixture.mjs +209 -209
- package/src/native-fixture.mjs +125 -125
- package/src/native-platform.mjs +56 -56
- package/src/operator-accounts.mjs +103 -103
- package/src/owned-process.mjs +75 -75
- package/src/owner-database.mjs +215 -215
- package/src/owner-operator-build.mjs +33 -33
- package/src/owner-production-browser.mjs +215 -215
- package/src/owner-production-instances.mjs +41 -41
- package/src/owner-production.d.mts +104 -104
- package/src/owner-production.mjs +338 -338
- package/src/owner-worker-build.mjs +83 -83
- package/src/prebuilt-output.d.mts +2 -2
- package/src/prebuilt-output.mjs +104 -104
- package/src/production-hosts.mjs +38 -38
- package/src/release-build.mjs +71 -71
- package/src/release-control.mjs +45 -45
- package/src/release-coordinator.d.mts +9 -9
- package/src/release-coordinator.mjs +222 -222
- package/src/release-credentials.d.mts +8 -8
- package/src/release-credentials.mjs +97 -97
- package/src/release-mutex.mjs +38 -38
- package/src/release-operator.d.mts +6 -6
- package/src/release-operator.mjs +59 -59
- package/src/release-supabase.d.mts +7 -7
- package/src/release-supabase.mjs +37 -37
- package/src/release-vercel.d.mts +22 -22
- package/src/release-vercel.mjs +51 -51
- package/src/release-writer.d.mts +6 -6
- package/src/release-writer.mjs +172 -172
- package/src/retained-postgres-shutdown.d.mts +51 -51
- package/src/retained-postgres-shutdown.mjs +262 -262
- package/src/temporary-acquisition.mjs +62 -62
- package/src/temporary-scope.d.mts +47 -47
- package/src/temporary-scope.mjs +268 -268
- package/src/worker-artifact.mjs +214 -214
package/src/owner-database.mjs
CHANGED
|
@@ -1,215 +1,215 @@
|
|
|
1
|
-
import {createHash,randomBytes} from 'node:crypto';
|
|
2
|
-
import fs from 'node:fs';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import {createRequire} from 'node:module';
|
|
5
|
-
import {isDeepStrictEqual} from 'node:util';
|
|
6
|
-
import pg from 'pg';
|
|
7
|
-
import {createSupabaseReleaseClient} from './release-supabase.mjs';
|
|
8
|
-
import {vaultIsolationGuard} from './operator-vault.mjs';
|
|
9
|
-
import {schemaSnapshotSql,readSchemaSnapshot,assertSchemaSnapshot} from './schema-snapshot.mjs';
|
|
10
|
-
|
|
11
|
-
const ownership='link-light-owner-runtime/v2';
|
|
12
|
-
const kinds=['application','worker'];
|
|
13
|
-
/** Explicit owner configuration dispatch; SQL authority remains in the existing
|
|
14
|
-
* database preparation API and the selected owner's public schema export. */
|
|
15
|
-
export async function runOwnerDatabaseCommand({root,args,environment=process.env,signal=AbortSignal.timeout(300000)}){
|
|
16
|
-
if(!Array.isArray(args)||args.length!==1||!['--contract','--inspect','--apply','--auto'].includes(args[0]))throw Error('OWNER_DATABASE_MODE_REQUIRED');
|
|
17
|
-
const mode=args[0];
|
|
18
|
-
if(mode==='--auto'&&(!['check','publish'].includes(environment.FORGE_RELEASE_COMMAND)||!/^[a-f0-9]{40}$/.test(environment.FORGE_RELEASE_SHA??'')))throw Error('RELEASE_JOB_CONTEXT_INVALID');
|
|
19
|
-
if(typeof root!=='string'||!path.isAbsolute(root)||fs.realpathSync(root)!==path.resolve(root))throw Error('OWNER_DATABASE_CONFIGURATION_INVALID');
|
|
20
|
-
root=path.resolve(root);const require=createRequire(path.join(root,'package.json')),read=relative=>JSON.parse(fs.readFileSync(path.join(root,relative),'utf8'));
|
|
21
|
-
const metadata=read('package.json'),config=read('deployment/database.json'),deployment=read('deployment/target.json');
|
|
22
|
-
if(config.schemaVersion!==1||config.target.projectRef!==deployment.projectRef||config.domain.entry!==metadata.name+'/postgres-schema')throw Error('OWNER_DATABASE_CONFIGURATION_INVALID');
|
|
23
|
-
const outputPath=path.join(root,'deployment/schema-contract.json');
|
|
24
|
-
if(mode==='--contract')return buildOwnerSchemaContract({root,target:config.target,domain:config.domain,outputPath,signal});
|
|
25
|
-
const contract=read('deployment/schema-contract.json'),schemaSql=fs.readFileSync(require.resolve(config.domain.entry),'utf8');
|
|
26
|
-
if(contract.schemaVersion!==1||contract.schemaSqlDigest!=='sha256:'+createHash('sha256').update(schemaSql).digest('hex'))throw Error('OWNER_DATABASE_CONTRACT_REBUILD_REQUIRED');
|
|
27
|
-
let upgrade={};
|
|
28
|
-
if(config.upgrade){
|
|
29
|
-
const owned=relative=>{if(typeof relative!=='string'||!relative||relative.split('/').some(part=>!part||part==='.'||part==='..')||/[\\:\0]/.test(relative))throw Error('OWNER_DATABASE_UPGRADE_INPUT');const filename=path.join(root,relative);if(fs.realpathSync(filename)!==filename||!fs.statSync(filename).isFile()||fs.statSync(filename).size>1048576)throw Error('OWNER_DATABASE_UPGRADE_INPUT');return filename;};
|
|
30
|
-
const predecessor=JSON.parse(fs.readFileSync(owned(config.upgrade.contract),'utf8')),upgradeSql=fs.readFileSync(owned(config.upgrade.sql),'utf8');
|
|
31
|
-
if(predecessor.schemaVersion!==1||predecessor.upgradeSqlDigest!=='sha256:'+createHash('sha256').update(upgradeSql).digest('hex'))throw Error('OWNER_DATABASE_UPGRADE_INPUT');
|
|
32
|
-
upgrade={previousSnapshot:predecessor.snapshot,upgradeSql};
|
|
33
|
-
}
|
|
34
|
-
return prepareOwnerDatabase({root,target:config.target,connection:config.connection,baseSnapshot:contract.snapshot,schemaSql,...upgrade,apply:mode==='--apply'||mode==='--auto'&&environment.FORGE_RELEASE_COMMAND==='publish',signal});
|
|
35
|
-
}
|
|
36
|
-
export async function buildOwnerSchemaContract({root,target,domain,outputPath,signal}){
|
|
37
|
-
validateOwnerDatabaseTarget(target);
|
|
38
|
-
if(typeof root!=='string'||!path.isAbsolute(root)||domain?.name!==target.schema||domain.owner!==target.schemaOwner||!Array.isArray(domain.tables)||typeof outputPath!=='string')throw Error('OWNER_DATABASE_CONTRACT_INPUT');
|
|
39
|
-
root=path.resolve(root);if(fs.realpathSync(root)!==root)throw Error('OWNER_DATABASE_CONTRACT_INPUT');
|
|
40
|
-
const relative=path.relative(root,outputPath);
|
|
41
|
-
if(!relative||relative.startsWith('..')||path.isAbsolute(relative)||fs.realpathSync(path.dirname(outputPath))!==path.dirname(outputPath))throw Error('OWNER_DATABASE_CONTRACT_INPUT');
|
|
42
|
-
const require=createRequire(path.join(root,'package.json')),schemaFile=require.resolve(domain.entry),sql=fs.readFileSync(schemaFile);
|
|
43
|
-
if(sql.length>65536||sql.includes(13))throw Error('OWNER_DATABASE_SCHEMA_REQUIRES_LF');
|
|
44
|
-
const {startNativeFixture}=await import('./native-fixture.mjs');
|
|
45
|
-
const fixture=await startNativeFixture({root,runtimeRoot:root,label:'release-schema-contract',domains:[domain],signal});
|
|
46
|
-
let result={status:'FAIL'};
|
|
47
|
-
try{
|
|
48
|
-
const snapshot=await readSchemaSnapshot({query:sql=>fixture.owner.query(sql)},target.schema,{signal});
|
|
49
|
-
if(snapshot?.owner!==target.schemaOwner)throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
50
|
-
const contract={schemaVersion:1,schemaSqlDigest:'sha256:'+createHash('sha256').update(sql).digest('hex'),snapshot};
|
|
51
|
-
const bytes=Buffer.from(JSON.stringify(contract,null,2)+'\n');if(bytes.length>1048576)throw Error('OWNER_DATABASE_CONTRACT_BUDGET');
|
|
52
|
-
if(fs.existsSync(outputPath)&&(!fs.lstatSync(outputPath).isFile()||fs.lstatSync(outputPath).isSymbolicLink()))throw Error('OWNER_DATABASE_CONTRACT_INPUT');
|
|
53
|
-
fs.writeFileSync(outputPath,bytes);result={status:'PASS'};
|
|
54
|
-
return {status:'SCHEMA_CONTRACT_BUILT',schema:target.schema,bytes:bytes.length,schemaSqlDigest:contract.schemaSqlDigest};
|
|
55
|
-
}catch(error){result={status:'FAIL',error:error.message};throw error;}
|
|
56
|
-
finally{await fixture.dispose(result);}
|
|
57
|
-
}
|
|
58
|
-
function identifier(value){if(typeof value!=='string'||!/^[a-z][a-z0-9_]{0,62}$/.test(value)||/^(pg_|platform(?:_|$))/.test(value)||['public','auth','storage','vault','extensions','information_schema'].includes(value))throw Error('OWNER_DATABASE_TARGET_INVALID');return value;}
|
|
59
|
-
const literal=value=>"'"+String(value).replaceAll("'","''")+"'";
|
|
60
|
-
export function validateOwnerDatabaseTarget(target){
|
|
61
|
-
if(!target||target.schemaVersion!==2||Object.keys(target).sort().join(',')!=='applicationRole,projectRef,schema,schemaOwner,schemaVersion,solutionId,workerRole'||typeof target.projectRef!=='string'||!/^[a-z]{20}$/.test(target.projectRef)||typeof target.solutionId!=='string'||!/^[a-z][a-z0-9-]{0,63}$/.test(target.solutionId))throw Error('OWNER_DATABASE_TARGET_INVALID');
|
|
62
|
-
for(const key of ['schema','schemaOwner',...kinds.map(kind=>kind+'Role')])identifier(target[key]);
|
|
63
|
-
if(new Set(['schemaOwner',...kinds.map(kind=>kind+'Role')].map(key=>target[key])).size!==3)throw Error('OWNER_DATABASE_TARGET_INVALID');
|
|
64
|
-
return target;
|
|
65
|
-
}
|
|
66
|
-
export function validateOwnerDatabaseCredentials(value,target){
|
|
67
|
-
validateOwnerDatabaseTarget(target);
|
|
68
|
-
if(!value||value.schemaVersion!==2||!isDeepStrictEqual(value.target,target)||!value.credentials||Object.keys(value.credentials).sort().join(',')!=='application,worker')throw Error('OWNER_DATABASE_CREDENTIALS_INVALID');
|
|
69
|
-
for(const kind of kinds)if(value.credentials[kind]?.role!==target[kind+'Role']||typeof value.credentials[kind].password!=='string'||!/^[a-f0-9]{64}$/.test(value.credentials[kind].password))throw Error('OWNER_DATABASE_CREDENTIALS_INVALID');
|
|
70
|
-
if(new Set(kinds.map(kind=>value.credentials[kind].password)).size!==2)throw Error('OWNER_DATABASE_CREDENTIALS_INVALID');
|
|
71
|
-
return value;
|
|
72
|
-
}
|
|
73
|
-
function namespace(target){return 'link-light/runtime/'+validateOwnerDatabaseTarget(target).solutionId+'/v2';}
|
|
74
|
-
const aclOrder=(a,b)=>Buffer.compare(Buffer.from(a.grantee+'\0'+a.privilege+'\0'+a.grantor),Buffer.from(b.grantee+'\0'+b.privilege+'\0'+b.grantor));
|
|
75
|
-
/** Keep policy membership in the neutral runtime group, but move the owner's
|
|
76
|
-
* object GRANTs to its application login. Other runtimes then fail GRANT checks
|
|
77
|
-
* before RLS; Worker identities receive no business table privileges. */
|
|
78
|
-
export function scopedSchemaSnapshot(base,applicationRole){
|
|
79
|
-
identifier(applicationRole);
|
|
80
|
-
if(!base||base.unsupported!==false)throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
81
|
-
const visit=value=>Array.isArray(value)?value.map(visit):value&&typeof value==='object'?Object.fromEntries(Object.entries(value).map(([key,item])=>[key,key==='acl'?item.map(acl=>({...acl,grantee:acl.grantee==='platform_runtime'?applicationRole:acl.grantee})).sort(aclOrder):visit(item)])):value;
|
|
82
|
-
return visit(base);
|
|
83
|
-
}
|
|
84
|
-
export function scopeSchemaPrivilegesSql(base,applicationRole){
|
|
85
|
-
identifier(base?.schemaName);identifier(applicationRole);
|
|
86
|
-
if(base.unsupported!==false||!Array.isArray(base.relations)||!Array.isArray(base.functions))throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
87
|
-
const statements=[];
|
|
88
|
-
function grants(acl,object,allowed,column){
|
|
89
|
-
if(!Array.isArray(acl))throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
90
|
-
for(const grant of acl.filter(item=>item.grantee==='platform_runtime')){
|
|
91
|
-
if(!allowed.includes(grant.privilege)||grant.grantable!==false)throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
92
|
-
const privilege=grant.privilege+(column?'('+identifier(column)+')':'');
|
|
93
|
-
statements.push(`GRANT ${privilege} ON ${object} TO ${applicationRole};REVOKE ${privilege} ON ${object} FROM platform_runtime;`);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
grants(base.acl,'SCHEMA '+base.schemaName,['USAGE','CREATE']);
|
|
97
|
-
for(const relation of base.relations){
|
|
98
|
-
identifier(relation.name);
|
|
99
|
-
if(!['r','p','v','m','S'].includes(relation.kind))throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
100
|
-
const object=(relation.kind==='S'?'SEQUENCE ':'TABLE ')+base.schemaName+'.'+relation.name;
|
|
101
|
-
grants(relation.acl,object,relation.kind==='S'?['SELECT','UPDATE','USAGE']:['SELECT','INSERT','UPDATE','DELETE','TRUNCATE','REFERENCES','TRIGGER','MAINTAIN']);
|
|
102
|
-
for(const column of relation.columns)grants(column.acl,object,['SELECT','INSERT','UPDATE','REFERENCES'],column.name);
|
|
103
|
-
}
|
|
104
|
-
for(const fn of base.functions){
|
|
105
|
-
identifier(fn.name);if(typeof fn.arguments!=='string'||!/^[a-zA-Z0-9_ [\],]*$/.test(fn.arguments))throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
106
|
-
grants(fn.acl,'FUNCTION '+base.schemaName+'.'+fn.name+'('+fn.arguments+')',['EXECUTE']);
|
|
107
|
-
}
|
|
108
|
-
return statements.join('\n');
|
|
109
|
-
}
|
|
110
|
-
function fresh(target){return {schemaVersion:2,target,credentials:Object.fromEntries(kinds.map(kind=>[kind,{role:target[kind+'Role'],password:randomBytes(32).toString('hex')}]))};}
|
|
111
|
-
export async function readOwnerDatabaseCredentials(options){
|
|
112
|
-
const {target,signal}=options;validateOwnerDatabaseTarget(target);
|
|
113
|
-
const client=options.client??createSupabaseReleaseClient(options.root,target.projectRef);
|
|
114
|
-
const observed=await client.query(`DO $isolation$ BEGIN ${vaultIsolationGuard} END $isolation$;SELECT description,decrypted_secret FROM vault.decrypted_secrets WHERE name=${literal(namespace(target))};`,{signal});
|
|
115
|
-
if(!observed.rows.length)return null;
|
|
116
|
-
if(observed.rows.length!==1||observed.rows[0].description!==ownership)throw Error('OWNER_DATABASE_OWNERSHIP_UNKNOWN');
|
|
117
|
-
let value;try{value=JSON.parse(observed.rows[0].decrypted_secret);}catch{throw Error('OWNER_DATABASE_CREDENTIALS_INVALID');}
|
|
118
|
-
return validateOwnerDatabaseCredentials(value,target);
|
|
119
|
-
}
|
|
120
|
-
function assertSqlSchema(schema,expected){
|
|
121
|
-
const sql=schemaSnapshotSql(schema).replace(/;$/,'');
|
|
122
|
-
return `IF (SELECT snapshot FROM (${sql}) observed) IS DISTINCT FROM ${expected===null?'NULL::jsonb':literal(JSON.stringify(expected))+'::jsonb'} THEN RAISE EXCEPTION 'OWNER_DATABASE_SCHEMA_CHANGED';END IF;`;
|
|
123
|
-
}
|
|
124
|
-
/** Pure transaction builder for an explicit operator. No admin credential is
|
|
125
|
-
* returned or installed in runtime; no business row is updated or deleted.
|
|
126
|
-
* @param {{target:object,credentials:object,baseSnapshot:object,observedSnapshot:object|null,schemaSql:string,previousSnapshot?:object,upgradeSql?:string}} options */
|
|
127
|
-
export function ownerDatabaseBootstrapSql({target,credentials,baseSnapshot,observedSnapshot,schemaSql,previousSnapshot=undefined,upgradeSql=undefined}){
|
|
128
|
-
validateOwnerDatabaseCredentials(credentials,target);
|
|
129
|
-
if(baseSnapshot?.schemaName!==target.schema||baseSnapshot.owner!==target.schemaOwner||baseSnapshot.unsupported!==false)throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
130
|
-
const scoped=scopedSchemaSnapshot(baseSnapshot,target.applicationRole);
|
|
131
|
-
const upgrade=previousSnapshot&&isDeepStrictEqual(previousSnapshot,observedSnapshot);
|
|
132
|
-
if(observedSnapshot!==null&&!isDeepStrictEqual(baseSnapshot,observedSnapshot)&&!isDeepStrictEqual(scoped,observedSnapshot)&&!upgrade)throw Error('SCHEMA_CONTRACT_MISMATCH');
|
|
133
|
-
let ddl='';
|
|
134
|
-
if(observedSnapshot===null||upgrade){
|
|
135
|
-
const sql=upgrade?upgradeSql:schemaSql;
|
|
136
|
-
if(typeof sql!=='string'||Buffer.byteLength(sql)>65536||!/^\s*(?:--[^\n]*\n)*BEGIN;[\s\S]+COMMIT;\s*$/.test(sql))throw Error('OWNER_DATABASE_SCHEMA_SQL_INVALID');
|
|
137
|
-
ddl=sql.replace(/^(\s*(?:--[^\n]*\n)*)BEGIN;/,'$1').replace(/COMMIT;\s*$/,'');
|
|
138
|
-
}
|
|
139
|
-
const encoded=Buffer.from(JSON.stringify(credentials)).toString('base64'),name=namespace(target),roleList=kinds.map(kind=>literal(target[kind+'Role'])).join(',');
|
|
140
|
-
return `BEGIN;SELECT pg_advisory_xact_lock(hashtextextended(${literal(ownership+'/'+target.solutionId)},0));
|
|
141
|
-
DO $preflight$ BEGIN
|
|
142
|
-
IF to_regclass('platform_private.runtime_roles') IS NULL OR to_regclass('vault.decrypted_secrets') IS NULL THEN RAISE EXCEPTION 'BOOTSTRAP_BASELINE_REQUIRED';END IF;
|
|
143
|
-
${vaultIsolationGuard}
|
|
144
|
-
${assertSqlSchema(target.schema,observedSnapshot)}
|
|
145
|
-
END $preflight$;
|
|
146
|
-
${ddl}
|
|
147
|
-
DO $credentials$ DECLARE payload jsonb:=convert_from(decode('${encoded}','base64'),'UTF8')::jsonb;BEGIN
|
|
148
|
-
IF EXISTS(SELECT 1 FROM vault.secrets WHERE name=${literal(name)}) THEN
|
|
149
|
-
IF NOT EXISTS(SELECT 1 FROM vault.decrypted_secrets WHERE name=${literal(name)} AND description=${literal(ownership)} AND decrypted_secret::jsonb=payload)
|
|
150
|
-
OR (SELECT count(*) FROM pg_roles WHERE rolname IN (${roleList}))<>2 THEN RAISE EXCEPTION 'OWNER_DATABASE_OWNERSHIP_UNKNOWN';END IF;
|
|
151
|
-
ELSE
|
|
152
|
-
IF EXISTS(SELECT 1 FROM pg_roles WHERE rolname IN (${roleList})) THEN RAISE EXCEPTION 'BOOTSTRAP_ROLE_ALREADY_EXISTS';END IF;
|
|
153
|
-
${kinds.map(kind=>`EXECUTE format('CREATE ROLE %I LOGIN INHERIT NOSUPERUSER NOBYPASSRLS NOCREATEDB NOCREATEROLE NOREPLICATION PASSWORD %L',${literal(target[kind+'Role'])},payload->'credentials'->'${kind}'->>'password');`).join('\n')}
|
|
154
|
-
PERFORM vault.create_secret(payload::text,${literal(name)},${literal(ownership)});
|
|
155
|
-
END IF;
|
|
156
|
-
IF EXISTS(SELECT 1 FROM pg_roles r WHERE rolname IN (${roleList}) AND (NOT rolcanlogin OR rolsuper OR rolbypassrls OR rolcreatedb OR rolcreaterole OR rolreplication))
|
|
157
|
-
OR NOT EXISTS(SELECT 1 FROM pg_roles r WHERE rolname=${literal(target.schemaOwner)} AND NOT(rolcanlogin OR rolsuper OR rolbypassrls OR rolcreatedb OR rolcreaterole OR rolreplication)) THEN RAISE EXCEPTION 'OWNER_DATABASE_ROLE_UNSAFE';END IF;
|
|
158
|
-
IF EXISTS(SELECT 1 FROM platform_private.runtime_roles WHERE role_name IN (${roleList}) AND solution_id<>${literal(target.solutionId)}) THEN RAISE EXCEPTION 'OWNER_DATABASE_ROLE_SCOPE_CONFLICT';END IF;
|
|
159
|
-
END $credentials$;
|
|
160
|
-
GRANT platform_runtime TO ${target.applicationRole} WITH INHERIT TRUE,SET FALSE;
|
|
161
|
-
GRANT platform_worker TO ${target.workerRole} WITH INHERIT TRUE,SET FALSE;
|
|
162
|
-
INSERT INTO platform_private.runtime_roles(role_name,solution_id) VALUES(${literal(target.applicationRole)},${literal(target.solutionId)}),(${literal(target.workerRole)},${literal(target.solutionId)}) ON CONFLICT(role_name) DO NOTHING;
|
|
163
|
-
${isDeepStrictEqual(observedSnapshot,scoped)?'':scopeSchemaPrivilegesSql(baseSnapshot,target.applicationRole)}
|
|
164
|
-
DO $verify$ BEGIN
|
|
165
|
-
IF EXISTS(SELECT 1 FROM pg_auth_members m JOIN pg_roles member ON member.oid=m.member JOIN pg_roles parent ON parent.oid=m.roleid
|
|
166
|
-
WHERE member.rolname IN (${roleList}) AND NOT (
|
|
167
|
-
member.rolname=${literal(target.applicationRole)} AND parent.rolname='platform_runtime' AND m.inherit_option AND NOT m.set_option
|
|
168
|
-
OR member.rolname=${literal(target.workerRole)} AND parent.rolname='platform_worker' AND m.inherit_option AND NOT m.set_option)) THEN RAISE EXCEPTION 'OWNER_DATABASE_ROLE_UNSAFE';END IF;
|
|
169
|
-
IF EXISTS(SELECT 1 FROM pg_namespace n JOIN pg_roles owner ON owner.oid=n.nspowner WHERE owner.rolname IN (${roleList})) THEN RAISE EXCEPTION 'OWNER_DATABASE_ROLE_UNSAFE';END IF;
|
|
170
|
-
${assertSqlSchema(target.schema,scoped)}
|
|
171
|
-
END $verify$;COMMIT;
|
|
172
|
-
SELECT 'OWNER_DATABASE_PREPARED' AS status;`;
|
|
173
|
-
}
|
|
174
|
-
export function ownerDatabaseConnections(credentials,connection){
|
|
175
|
-
const {target}=credentials;validateOwnerDatabaseCredentials(credentials,target);
|
|
176
|
-
if(!connection||connection.port!==5432||connection.database!=='postgres'||connection.ssl?.rejectUnauthorized!==true||typeof connection.ssl.ca!=='string'||!connection.ssl.ca||typeof connection.host!=='string'||!connection.host||connection.host.length>255)throw Error('OWNER_DATABASE_CONNECTION_INVALID');
|
|
177
|
-
return Object.fromEntries(kinds.map(kind=>{const credential=credentials.credentials[kind],url=new URL('postgresql://placeholder/');url.hostname=connection.host;url.port=String(connection.port);url.pathname='/'+connection.database;url.username=credential.role+'.'+target.projectRef;url.password=credential.password;return [kind,{connectionString:url.href,role:credential.role,max:kind==='application'?2:1,connectionTimeoutMs:10000,idleTimeoutMs:10000,statementTimeoutMs:10000,ssl:connection.ssl}];}));
|
|
178
|
-
}
|
|
179
|
-
/** The caller supplies its public platform verifier and owned readiness port.
|
|
180
|
-
* Pools and their ordinary TLS identities are closed before returning. */
|
|
181
|
-
export async function verifyOwnerDatabaseConnections({credentials,connection,verify,signal}){
|
|
182
|
-
if(typeof verify!=='function')throw Error('OWNER_DATABASE_VERIFIER_REQUIRED');
|
|
183
|
-
const database=ownerDatabaseConnections(credentials,connection),target=credentials.target;
|
|
184
|
-
for(const kind of kinds){
|
|
185
|
-
signal?.throwIfAborted();const config=database[kind],pool=new pg.Pool({connectionString:config.connectionString,ssl:config.ssl,max:1,connectionTimeoutMillis:10000,statement_timeout:10000,allowExitOnIdle:true});let fault;pool.on('error',error=>{fault??=error;});
|
|
186
|
-
try{await verify(pool,{kind,role:config.role,solutionId:target.solutionId});if(fault)throw Error('OWNER_DATABASE_CONNECTION_UNKNOWN',{cause:fault});}
|
|
187
|
-
finally{await pool.end();}
|
|
188
|
-
}
|
|
189
|
-
return {roles:kinds.map(kind=>target[kind+'Role']),verifiedTls:true};
|
|
190
|
-
}
|
|
191
|
-
export async function prepareOwnerDatabase(options){
|
|
192
|
-
const {target,signal}=options;validateOwnerDatabaseTarget(target);
|
|
193
|
-
const client=options.client??createSupabaseReleaseClient(options.root,target.projectRef);
|
|
194
|
-
const existing=await readOwnerDatabaseCredentials({...options,client});
|
|
195
|
-
const observedSnapshot=await readSchemaSnapshot(client,target.schema,{signal});
|
|
196
|
-
const baseSnapshot=options.baseSnapshot,scoped=scopedSchemaSnapshot(baseSnapshot,target.applicationRole);
|
|
197
|
-
const upgrade=options.previousSnapshot&&isDeepStrictEqual(options.previousSnapshot,observedSnapshot);
|
|
198
|
-
if(observedSnapshot!==null&&!isDeepStrictEqual(baseSnapshot,observedSnapshot)&&!isDeepStrictEqual(scoped,observedSnapshot)&&!upgrade)throw Error('SCHEMA_CONTRACT_MISMATCH');
|
|
199
|
-
if(!options.apply)return {status:existing&&isDeepStrictEqual(scoped,observedSnapshot)?'SCHEMA_AND_CREDENTIALS_PREPARED':upgrade?'UPGRADE_REQUIRED':'SETUP_REQUIRED',writes:0,schema:target.schema};
|
|
200
|
-
if(process.env.FORGE_RELEASE_COMMAND&&process.env.FORGE_RELEASE_COMMAND!=='publish')throw Error('OWNER_DATABASE_READ_ONLY_CHECK');
|
|
201
|
-
const credentials=existing??fresh(target);
|
|
202
|
-
ownerDatabaseConnections(credentials,options.connection);
|
|
203
|
-
await client.query(ownerDatabaseBootstrapSql({...options,credentials,observedSnapshot}),{signal});
|
|
204
|
-
const persisted=await readOwnerDatabaseCredentials({...options,client});
|
|
205
|
-
if(!persisted||!isDeepStrictEqual(persisted,credentials))throw Error('OWNER_DATABASE_COMMIT_UNKNOWN');
|
|
206
|
-
assertSchemaSnapshot(scoped,await readSchemaSnapshot(client,target.schema,{signal}));
|
|
207
|
-
// A live ordinary connection proves the pooler routing identity and TLS before
|
|
208
|
-
// any application environment receives it. The platform host does full grants.
|
|
209
|
-
for(const config of Object.values(ownerDatabaseConnections(credentials,options.connection))){
|
|
210
|
-
const db=new pg.Client({...config,connectionTimeoutMillis:10000,statement_timeout:10000});
|
|
211
|
-
try{await db.connect();const row=(await db.query('SELECT current_user AS role,session_user')).rows[0];if(row.role!==config.role||row.session_user!==config.role)throw Error('OWNER_DATABASE_LOGIN_MISMATCH');}
|
|
212
|
-
finally{await db.end();}
|
|
213
|
-
}
|
|
214
|
-
return {status:'PREPARED',writes:1,credentialWrite:!existing,schema:target.schema,roles:kinds.map(kind=>target[kind+'Role']),verifiedTls:true};
|
|
215
|
-
}
|
|
1
|
+
import {createHash,randomBytes} from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {createRequire} from 'node:module';
|
|
5
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
6
|
+
import pg from 'pg';
|
|
7
|
+
import {createSupabaseReleaseClient} from './release-supabase.mjs';
|
|
8
|
+
import {vaultIsolationGuard} from './operator-vault.mjs';
|
|
9
|
+
import {schemaSnapshotSql,readSchemaSnapshot,assertSchemaSnapshot} from './schema-snapshot.mjs';
|
|
10
|
+
|
|
11
|
+
const ownership='link-light-owner-runtime/v2';
|
|
12
|
+
const kinds=['application','worker'];
|
|
13
|
+
/** Explicit owner configuration dispatch; SQL authority remains in the existing
|
|
14
|
+
* database preparation API and the selected owner's public schema export. */
|
|
15
|
+
export async function runOwnerDatabaseCommand({root,args,environment=process.env,signal=AbortSignal.timeout(300000)}){
|
|
16
|
+
if(!Array.isArray(args)||args.length!==1||!['--contract','--inspect','--apply','--auto'].includes(args[0]))throw Error('OWNER_DATABASE_MODE_REQUIRED');
|
|
17
|
+
const mode=args[0];
|
|
18
|
+
if(mode==='--auto'&&(!['check','publish'].includes(environment.FORGE_RELEASE_COMMAND)||!/^[a-f0-9]{40}$/.test(environment.FORGE_RELEASE_SHA??'')))throw Error('RELEASE_JOB_CONTEXT_INVALID');
|
|
19
|
+
if(typeof root!=='string'||!path.isAbsolute(root)||fs.realpathSync(root)!==path.resolve(root))throw Error('OWNER_DATABASE_CONFIGURATION_INVALID');
|
|
20
|
+
root=path.resolve(root);const require=createRequire(path.join(root,'package.json')),read=relative=>JSON.parse(fs.readFileSync(path.join(root,relative),'utf8'));
|
|
21
|
+
const metadata=read('package.json'),config=read('deployment/database.json'),deployment=read('deployment/target.json');
|
|
22
|
+
if(config.schemaVersion!==1||config.target.projectRef!==deployment.projectRef||config.domain.entry!==metadata.name+'/postgres-schema')throw Error('OWNER_DATABASE_CONFIGURATION_INVALID');
|
|
23
|
+
const outputPath=path.join(root,'deployment/schema-contract.json');
|
|
24
|
+
if(mode==='--contract')return buildOwnerSchemaContract({root,target:config.target,domain:config.domain,outputPath,signal});
|
|
25
|
+
const contract=read('deployment/schema-contract.json'),schemaSql=fs.readFileSync(require.resolve(config.domain.entry),'utf8');
|
|
26
|
+
if(contract.schemaVersion!==1||contract.schemaSqlDigest!=='sha256:'+createHash('sha256').update(schemaSql).digest('hex'))throw Error('OWNER_DATABASE_CONTRACT_REBUILD_REQUIRED');
|
|
27
|
+
let upgrade={};
|
|
28
|
+
if(config.upgrade){
|
|
29
|
+
const owned=relative=>{if(typeof relative!=='string'||!relative||relative.split('/').some(part=>!part||part==='.'||part==='..')||/[\\:\0]/.test(relative))throw Error('OWNER_DATABASE_UPGRADE_INPUT');const filename=path.join(root,relative);if(fs.realpathSync(filename)!==filename||!fs.statSync(filename).isFile()||fs.statSync(filename).size>1048576)throw Error('OWNER_DATABASE_UPGRADE_INPUT');return filename;};
|
|
30
|
+
const predecessor=JSON.parse(fs.readFileSync(owned(config.upgrade.contract),'utf8')),upgradeSql=fs.readFileSync(owned(config.upgrade.sql),'utf8');
|
|
31
|
+
if(predecessor.schemaVersion!==1||predecessor.upgradeSqlDigest!=='sha256:'+createHash('sha256').update(upgradeSql).digest('hex'))throw Error('OWNER_DATABASE_UPGRADE_INPUT');
|
|
32
|
+
upgrade={previousSnapshot:predecessor.snapshot,upgradeSql};
|
|
33
|
+
}
|
|
34
|
+
return prepareOwnerDatabase({root,target:config.target,connection:config.connection,baseSnapshot:contract.snapshot,schemaSql,...upgrade,apply:mode==='--apply'||mode==='--auto'&&environment.FORGE_RELEASE_COMMAND==='publish',signal});
|
|
35
|
+
}
|
|
36
|
+
export async function buildOwnerSchemaContract({root,target,domain,outputPath,signal}){
|
|
37
|
+
validateOwnerDatabaseTarget(target);
|
|
38
|
+
if(typeof root!=='string'||!path.isAbsolute(root)||domain?.name!==target.schema||domain.owner!==target.schemaOwner||!Array.isArray(domain.tables)||typeof outputPath!=='string')throw Error('OWNER_DATABASE_CONTRACT_INPUT');
|
|
39
|
+
root=path.resolve(root);if(fs.realpathSync(root)!==root)throw Error('OWNER_DATABASE_CONTRACT_INPUT');
|
|
40
|
+
const relative=path.relative(root,outputPath);
|
|
41
|
+
if(!relative||relative.startsWith('..')||path.isAbsolute(relative)||fs.realpathSync(path.dirname(outputPath))!==path.dirname(outputPath))throw Error('OWNER_DATABASE_CONTRACT_INPUT');
|
|
42
|
+
const require=createRequire(path.join(root,'package.json')),schemaFile=require.resolve(domain.entry),sql=fs.readFileSync(schemaFile);
|
|
43
|
+
if(sql.length>65536||sql.includes(13))throw Error('OWNER_DATABASE_SCHEMA_REQUIRES_LF');
|
|
44
|
+
const {startNativeFixture}=await import('./native-fixture.mjs');
|
|
45
|
+
const fixture=await startNativeFixture({root,runtimeRoot:root,label:'release-schema-contract',domains:[domain],signal});
|
|
46
|
+
let result={status:'FAIL'};
|
|
47
|
+
try{
|
|
48
|
+
const snapshot=await readSchemaSnapshot({query:sql=>fixture.owner.query(sql)},target.schema,{signal});
|
|
49
|
+
if(snapshot?.owner!==target.schemaOwner)throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
50
|
+
const contract={schemaVersion:1,schemaSqlDigest:'sha256:'+createHash('sha256').update(sql).digest('hex'),snapshot};
|
|
51
|
+
const bytes=Buffer.from(JSON.stringify(contract,null,2)+'\n');if(bytes.length>1048576)throw Error('OWNER_DATABASE_CONTRACT_BUDGET');
|
|
52
|
+
if(fs.existsSync(outputPath)&&(!fs.lstatSync(outputPath).isFile()||fs.lstatSync(outputPath).isSymbolicLink()))throw Error('OWNER_DATABASE_CONTRACT_INPUT');
|
|
53
|
+
fs.writeFileSync(outputPath,bytes);result={status:'PASS'};
|
|
54
|
+
return {status:'SCHEMA_CONTRACT_BUILT',schema:target.schema,bytes:bytes.length,schemaSqlDigest:contract.schemaSqlDigest};
|
|
55
|
+
}catch(error){result={status:'FAIL',error:error.message};throw error;}
|
|
56
|
+
finally{await fixture.dispose(result);}
|
|
57
|
+
}
|
|
58
|
+
function identifier(value){if(typeof value!=='string'||!/^[a-z][a-z0-9_]{0,62}$/.test(value)||/^(pg_|platform(?:_|$))/.test(value)||['public','auth','storage','vault','extensions','information_schema'].includes(value))throw Error('OWNER_DATABASE_TARGET_INVALID');return value;}
|
|
59
|
+
const literal=value=>"'"+String(value).replaceAll("'","''")+"'";
|
|
60
|
+
export function validateOwnerDatabaseTarget(target){
|
|
61
|
+
if(!target||target.schemaVersion!==2||Object.keys(target).sort().join(',')!=='applicationRole,projectRef,schema,schemaOwner,schemaVersion,solutionId,workerRole'||typeof target.projectRef!=='string'||!/^[a-z]{20}$/.test(target.projectRef)||typeof target.solutionId!=='string'||!/^[a-z][a-z0-9-]{0,63}$/.test(target.solutionId))throw Error('OWNER_DATABASE_TARGET_INVALID');
|
|
62
|
+
for(const key of ['schema','schemaOwner',...kinds.map(kind=>kind+'Role')])identifier(target[key]);
|
|
63
|
+
if(new Set(['schemaOwner',...kinds.map(kind=>kind+'Role')].map(key=>target[key])).size!==3)throw Error('OWNER_DATABASE_TARGET_INVALID');
|
|
64
|
+
return target;
|
|
65
|
+
}
|
|
66
|
+
export function validateOwnerDatabaseCredentials(value,target){
|
|
67
|
+
validateOwnerDatabaseTarget(target);
|
|
68
|
+
if(!value||value.schemaVersion!==2||!isDeepStrictEqual(value.target,target)||!value.credentials||Object.keys(value.credentials).sort().join(',')!=='application,worker')throw Error('OWNER_DATABASE_CREDENTIALS_INVALID');
|
|
69
|
+
for(const kind of kinds)if(value.credentials[kind]?.role!==target[kind+'Role']||typeof value.credentials[kind].password!=='string'||!/^[a-f0-9]{64}$/.test(value.credentials[kind].password))throw Error('OWNER_DATABASE_CREDENTIALS_INVALID');
|
|
70
|
+
if(new Set(kinds.map(kind=>value.credentials[kind].password)).size!==2)throw Error('OWNER_DATABASE_CREDENTIALS_INVALID');
|
|
71
|
+
return value;
|
|
72
|
+
}
|
|
73
|
+
function namespace(target){return 'link-light/runtime/'+validateOwnerDatabaseTarget(target).solutionId+'/v2';}
|
|
74
|
+
const aclOrder=(a,b)=>Buffer.compare(Buffer.from(a.grantee+'\0'+a.privilege+'\0'+a.grantor),Buffer.from(b.grantee+'\0'+b.privilege+'\0'+b.grantor));
|
|
75
|
+
/** Keep policy membership in the neutral runtime group, but move the owner's
|
|
76
|
+
* object GRANTs to its application login. Other runtimes then fail GRANT checks
|
|
77
|
+
* before RLS; Worker identities receive no business table privileges. */
|
|
78
|
+
export function scopedSchemaSnapshot(base,applicationRole){
|
|
79
|
+
identifier(applicationRole);
|
|
80
|
+
if(!base||base.unsupported!==false)throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
81
|
+
const visit=value=>Array.isArray(value)?value.map(visit):value&&typeof value==='object'?Object.fromEntries(Object.entries(value).map(([key,item])=>[key,key==='acl'?item.map(acl=>({...acl,grantee:acl.grantee==='platform_runtime'?applicationRole:acl.grantee})).sort(aclOrder):visit(item)])):value;
|
|
82
|
+
return visit(base);
|
|
83
|
+
}
|
|
84
|
+
export function scopeSchemaPrivilegesSql(base,applicationRole){
|
|
85
|
+
identifier(base?.schemaName);identifier(applicationRole);
|
|
86
|
+
if(base.unsupported!==false||!Array.isArray(base.relations)||!Array.isArray(base.functions))throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
87
|
+
const statements=[];
|
|
88
|
+
function grants(acl,object,allowed,column){
|
|
89
|
+
if(!Array.isArray(acl))throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
90
|
+
for(const grant of acl.filter(item=>item.grantee==='platform_runtime')){
|
|
91
|
+
if(!allowed.includes(grant.privilege)||grant.grantable!==false)throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
92
|
+
const privilege=grant.privilege+(column?'('+identifier(column)+')':'');
|
|
93
|
+
statements.push(`GRANT ${privilege} ON ${object} TO ${applicationRole};REVOKE ${privilege} ON ${object} FROM platform_runtime;`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
grants(base.acl,'SCHEMA '+base.schemaName,['USAGE','CREATE']);
|
|
97
|
+
for(const relation of base.relations){
|
|
98
|
+
identifier(relation.name);
|
|
99
|
+
if(!['r','p','v','m','S'].includes(relation.kind))throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
100
|
+
const object=(relation.kind==='S'?'SEQUENCE ':'TABLE ')+base.schemaName+'.'+relation.name;
|
|
101
|
+
grants(relation.acl,object,relation.kind==='S'?['SELECT','UPDATE','USAGE']:['SELECT','INSERT','UPDATE','DELETE','TRUNCATE','REFERENCES','TRIGGER','MAINTAIN']);
|
|
102
|
+
for(const column of relation.columns)grants(column.acl,object,['SELECT','INSERT','UPDATE','REFERENCES'],column.name);
|
|
103
|
+
}
|
|
104
|
+
for(const fn of base.functions){
|
|
105
|
+
identifier(fn.name);if(typeof fn.arguments!=='string'||!/^[a-zA-Z0-9_ [\],]*$/.test(fn.arguments))throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
106
|
+
grants(fn.acl,'FUNCTION '+base.schemaName+'.'+fn.name+'('+fn.arguments+')',['EXECUTE']);
|
|
107
|
+
}
|
|
108
|
+
return statements.join('\n');
|
|
109
|
+
}
|
|
110
|
+
function fresh(target){return {schemaVersion:2,target,credentials:Object.fromEntries(kinds.map(kind=>[kind,{role:target[kind+'Role'],password:randomBytes(32).toString('hex')}]))};}
|
|
111
|
+
export async function readOwnerDatabaseCredentials(options){
|
|
112
|
+
const {target,signal}=options;validateOwnerDatabaseTarget(target);
|
|
113
|
+
const client=options.client??createSupabaseReleaseClient(options.root,target.projectRef);
|
|
114
|
+
const observed=await client.query(`DO $isolation$ BEGIN ${vaultIsolationGuard} END $isolation$;SELECT description,decrypted_secret FROM vault.decrypted_secrets WHERE name=${literal(namespace(target))};`,{signal});
|
|
115
|
+
if(!observed.rows.length)return null;
|
|
116
|
+
if(observed.rows.length!==1||observed.rows[0].description!==ownership)throw Error('OWNER_DATABASE_OWNERSHIP_UNKNOWN');
|
|
117
|
+
let value;try{value=JSON.parse(observed.rows[0].decrypted_secret);}catch{throw Error('OWNER_DATABASE_CREDENTIALS_INVALID');}
|
|
118
|
+
return validateOwnerDatabaseCredentials(value,target);
|
|
119
|
+
}
|
|
120
|
+
function assertSqlSchema(schema,expected){
|
|
121
|
+
const sql=schemaSnapshotSql(schema).replace(/;$/,'');
|
|
122
|
+
return `IF (SELECT snapshot FROM (${sql}) observed) IS DISTINCT FROM ${expected===null?'NULL::jsonb':literal(JSON.stringify(expected))+'::jsonb'} THEN RAISE EXCEPTION 'OWNER_DATABASE_SCHEMA_CHANGED';END IF;`;
|
|
123
|
+
}
|
|
124
|
+
/** Pure transaction builder for an explicit operator. No admin credential is
|
|
125
|
+
* returned or installed in runtime; no business row is updated or deleted.
|
|
126
|
+
* @param {{target:object,credentials:object,baseSnapshot:object,observedSnapshot:object|null,schemaSql:string,previousSnapshot?:object,upgradeSql?:string}} options */
|
|
127
|
+
export function ownerDatabaseBootstrapSql({target,credentials,baseSnapshot,observedSnapshot,schemaSql,previousSnapshot=undefined,upgradeSql=undefined}){
|
|
128
|
+
validateOwnerDatabaseCredentials(credentials,target);
|
|
129
|
+
if(baseSnapshot?.schemaName!==target.schema||baseSnapshot.owner!==target.schemaOwner||baseSnapshot.unsupported!==false)throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
130
|
+
const scoped=scopedSchemaSnapshot(baseSnapshot,target.applicationRole);
|
|
131
|
+
const upgrade=previousSnapshot&&isDeepStrictEqual(previousSnapshot,observedSnapshot);
|
|
132
|
+
if(observedSnapshot!==null&&!isDeepStrictEqual(baseSnapshot,observedSnapshot)&&!isDeepStrictEqual(scoped,observedSnapshot)&&!upgrade)throw Error('SCHEMA_CONTRACT_MISMATCH');
|
|
133
|
+
let ddl='';
|
|
134
|
+
if(observedSnapshot===null||upgrade){
|
|
135
|
+
const sql=upgrade?upgradeSql:schemaSql;
|
|
136
|
+
if(typeof sql!=='string'||Buffer.byteLength(sql)>65536||!/^\s*(?:--[^\n]*\n)*BEGIN;[\s\S]+COMMIT;\s*$/.test(sql))throw Error('OWNER_DATABASE_SCHEMA_SQL_INVALID');
|
|
137
|
+
ddl=sql.replace(/^(\s*(?:--[^\n]*\n)*)BEGIN;/,'$1').replace(/COMMIT;\s*$/,'');
|
|
138
|
+
}
|
|
139
|
+
const encoded=Buffer.from(JSON.stringify(credentials)).toString('base64'),name=namespace(target),roleList=kinds.map(kind=>literal(target[kind+'Role'])).join(',');
|
|
140
|
+
return `BEGIN;SELECT pg_advisory_xact_lock(hashtextextended(${literal(ownership+'/'+target.solutionId)},0));
|
|
141
|
+
DO $preflight$ BEGIN
|
|
142
|
+
IF to_regclass('platform_private.runtime_roles') IS NULL OR to_regclass('vault.decrypted_secrets') IS NULL THEN RAISE EXCEPTION 'BOOTSTRAP_BASELINE_REQUIRED';END IF;
|
|
143
|
+
${vaultIsolationGuard}
|
|
144
|
+
${assertSqlSchema(target.schema,observedSnapshot)}
|
|
145
|
+
END $preflight$;
|
|
146
|
+
${ddl}
|
|
147
|
+
DO $credentials$ DECLARE payload jsonb:=convert_from(decode('${encoded}','base64'),'UTF8')::jsonb;BEGIN
|
|
148
|
+
IF EXISTS(SELECT 1 FROM vault.secrets WHERE name=${literal(name)}) THEN
|
|
149
|
+
IF NOT EXISTS(SELECT 1 FROM vault.decrypted_secrets WHERE name=${literal(name)} AND description=${literal(ownership)} AND decrypted_secret::jsonb=payload)
|
|
150
|
+
OR (SELECT count(*) FROM pg_roles WHERE rolname IN (${roleList}))<>2 THEN RAISE EXCEPTION 'OWNER_DATABASE_OWNERSHIP_UNKNOWN';END IF;
|
|
151
|
+
ELSE
|
|
152
|
+
IF EXISTS(SELECT 1 FROM pg_roles WHERE rolname IN (${roleList})) THEN RAISE EXCEPTION 'BOOTSTRAP_ROLE_ALREADY_EXISTS';END IF;
|
|
153
|
+
${kinds.map(kind=>`EXECUTE format('CREATE ROLE %I LOGIN INHERIT NOSUPERUSER NOBYPASSRLS NOCREATEDB NOCREATEROLE NOREPLICATION PASSWORD %L',${literal(target[kind+'Role'])},payload->'credentials'->'${kind}'->>'password');`).join('\n')}
|
|
154
|
+
PERFORM vault.create_secret(payload::text,${literal(name)},${literal(ownership)});
|
|
155
|
+
END IF;
|
|
156
|
+
IF EXISTS(SELECT 1 FROM pg_roles r WHERE rolname IN (${roleList}) AND (NOT rolcanlogin OR rolsuper OR rolbypassrls OR rolcreatedb OR rolcreaterole OR rolreplication))
|
|
157
|
+
OR NOT EXISTS(SELECT 1 FROM pg_roles r WHERE rolname=${literal(target.schemaOwner)} AND NOT(rolcanlogin OR rolsuper OR rolbypassrls OR rolcreatedb OR rolcreaterole OR rolreplication)) THEN RAISE EXCEPTION 'OWNER_DATABASE_ROLE_UNSAFE';END IF;
|
|
158
|
+
IF EXISTS(SELECT 1 FROM platform_private.runtime_roles WHERE role_name IN (${roleList}) AND solution_id<>${literal(target.solutionId)}) THEN RAISE EXCEPTION 'OWNER_DATABASE_ROLE_SCOPE_CONFLICT';END IF;
|
|
159
|
+
END $credentials$;
|
|
160
|
+
GRANT platform_runtime TO ${target.applicationRole} WITH INHERIT TRUE,SET FALSE;
|
|
161
|
+
GRANT platform_worker TO ${target.workerRole} WITH INHERIT TRUE,SET FALSE;
|
|
162
|
+
INSERT INTO platform_private.runtime_roles(role_name,solution_id) VALUES(${literal(target.applicationRole)},${literal(target.solutionId)}),(${literal(target.workerRole)},${literal(target.solutionId)}) ON CONFLICT(role_name) DO NOTHING;
|
|
163
|
+
${isDeepStrictEqual(observedSnapshot,scoped)?'':scopeSchemaPrivilegesSql(baseSnapshot,target.applicationRole)}
|
|
164
|
+
DO $verify$ BEGIN
|
|
165
|
+
IF EXISTS(SELECT 1 FROM pg_auth_members m JOIN pg_roles member ON member.oid=m.member JOIN pg_roles parent ON parent.oid=m.roleid
|
|
166
|
+
WHERE member.rolname IN (${roleList}) AND NOT (
|
|
167
|
+
member.rolname=${literal(target.applicationRole)} AND parent.rolname='platform_runtime' AND m.inherit_option AND NOT m.set_option
|
|
168
|
+
OR member.rolname=${literal(target.workerRole)} AND parent.rolname='platform_worker' AND m.inherit_option AND NOT m.set_option)) THEN RAISE EXCEPTION 'OWNER_DATABASE_ROLE_UNSAFE';END IF;
|
|
169
|
+
IF EXISTS(SELECT 1 FROM pg_namespace n JOIN pg_roles owner ON owner.oid=n.nspowner WHERE owner.rolname IN (${roleList})) THEN RAISE EXCEPTION 'OWNER_DATABASE_ROLE_UNSAFE';END IF;
|
|
170
|
+
${assertSqlSchema(target.schema,scoped)}
|
|
171
|
+
END $verify$;COMMIT;
|
|
172
|
+
SELECT 'OWNER_DATABASE_PREPARED' AS status;`;
|
|
173
|
+
}
|
|
174
|
+
export function ownerDatabaseConnections(credentials,connection){
|
|
175
|
+
const {target}=credentials;validateOwnerDatabaseCredentials(credentials,target);
|
|
176
|
+
if(!connection||connection.port!==5432||connection.database!=='postgres'||connection.ssl?.rejectUnauthorized!==true||typeof connection.ssl.ca!=='string'||!connection.ssl.ca||typeof connection.host!=='string'||!connection.host||connection.host.length>255)throw Error('OWNER_DATABASE_CONNECTION_INVALID');
|
|
177
|
+
return Object.fromEntries(kinds.map(kind=>{const credential=credentials.credentials[kind],url=new URL('postgresql://placeholder/');url.hostname=connection.host;url.port=String(connection.port);url.pathname='/'+connection.database;url.username=credential.role+'.'+target.projectRef;url.password=credential.password;return [kind,{connectionString:url.href,role:credential.role,max:kind==='application'?2:1,connectionTimeoutMs:10000,idleTimeoutMs:10000,statementTimeoutMs:10000,ssl:connection.ssl}];}));
|
|
178
|
+
}
|
|
179
|
+
/** The caller supplies its public platform verifier and owned readiness port.
|
|
180
|
+
* Pools and their ordinary TLS identities are closed before returning. */
|
|
181
|
+
export async function verifyOwnerDatabaseConnections({credentials,connection,verify,signal}){
|
|
182
|
+
if(typeof verify!=='function')throw Error('OWNER_DATABASE_VERIFIER_REQUIRED');
|
|
183
|
+
const database=ownerDatabaseConnections(credentials,connection),target=credentials.target;
|
|
184
|
+
for(const kind of kinds){
|
|
185
|
+
signal?.throwIfAborted();const config=database[kind],pool=new pg.Pool({connectionString:config.connectionString,ssl:config.ssl,max:1,connectionTimeoutMillis:10000,statement_timeout:10000,allowExitOnIdle:true});let fault;pool.on('error',error=>{fault??=error;});
|
|
186
|
+
try{await verify(pool,{kind,role:config.role,solutionId:target.solutionId});if(fault)throw Error('OWNER_DATABASE_CONNECTION_UNKNOWN',{cause:fault});}
|
|
187
|
+
finally{await pool.end();}
|
|
188
|
+
}
|
|
189
|
+
return {roles:kinds.map(kind=>target[kind+'Role']),verifiedTls:true};
|
|
190
|
+
}
|
|
191
|
+
export async function prepareOwnerDatabase(options){
|
|
192
|
+
const {target,signal}=options;validateOwnerDatabaseTarget(target);
|
|
193
|
+
const client=options.client??createSupabaseReleaseClient(options.root,target.projectRef);
|
|
194
|
+
const existing=await readOwnerDatabaseCredentials({...options,client});
|
|
195
|
+
const observedSnapshot=await readSchemaSnapshot(client,target.schema,{signal});
|
|
196
|
+
const baseSnapshot=options.baseSnapshot,scoped=scopedSchemaSnapshot(baseSnapshot,target.applicationRole);
|
|
197
|
+
const upgrade=options.previousSnapshot&&isDeepStrictEqual(options.previousSnapshot,observedSnapshot);
|
|
198
|
+
if(observedSnapshot!==null&&!isDeepStrictEqual(baseSnapshot,observedSnapshot)&&!isDeepStrictEqual(scoped,observedSnapshot)&&!upgrade)throw Error('SCHEMA_CONTRACT_MISMATCH');
|
|
199
|
+
if(!options.apply)return {status:existing&&isDeepStrictEqual(scoped,observedSnapshot)?'SCHEMA_AND_CREDENTIALS_PREPARED':upgrade?'UPGRADE_REQUIRED':'SETUP_REQUIRED',writes:0,schema:target.schema};
|
|
200
|
+
if(process.env.FORGE_RELEASE_COMMAND&&process.env.FORGE_RELEASE_COMMAND!=='publish')throw Error('OWNER_DATABASE_READ_ONLY_CHECK');
|
|
201
|
+
const credentials=existing??fresh(target);
|
|
202
|
+
ownerDatabaseConnections(credentials,options.connection);
|
|
203
|
+
await client.query(ownerDatabaseBootstrapSql({...options,credentials,observedSnapshot}),{signal});
|
|
204
|
+
const persisted=await readOwnerDatabaseCredentials({...options,client});
|
|
205
|
+
if(!persisted||!isDeepStrictEqual(persisted,credentials))throw Error('OWNER_DATABASE_COMMIT_UNKNOWN');
|
|
206
|
+
assertSchemaSnapshot(scoped,await readSchemaSnapshot(client,target.schema,{signal}));
|
|
207
|
+
// A live ordinary connection proves the pooler routing identity and TLS before
|
|
208
|
+
// any application environment receives it. The platform host does full grants.
|
|
209
|
+
for(const config of Object.values(ownerDatabaseConnections(credentials,options.connection))){
|
|
210
|
+
const db=new pg.Client({...config,connectionTimeoutMillis:10000,statement_timeout:10000});
|
|
211
|
+
try{await db.connect();const row=(await db.query('SELECT current_user AS role,session_user')).rows[0];if(row.role!==config.role||row.session_user!==config.role)throw Error('OWNER_DATABASE_LOGIN_MISMATCH');}
|
|
212
|
+
finally{await db.end();}
|
|
213
|
+
}
|
|
214
|
+
return {status:'PREPARED',writes:1,credentialWrite:!existing,schema:target.schema,roles:kinds.map(kind=>target[kind+'Role']),verifiedTls:true};
|
|
215
|
+
}
|
|
@@ -1,33 +1,33 @@
|
|
|
1
|
-
import fs from 'node:fs/promises';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import {createHash} from 'node:crypto';
|
|
4
|
-
|
|
5
|
-
const fail=()=>Error('OWNER_OPERATOR_BUILD_INVALID');
|
|
6
|
-
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
7
|
-
const declaration="import {exerciseOwnerProduction,createOwnerProductionPlan} from '@xlinklight/testkit/owner-production';\nimport type {AcceptanceOracleStatement} from '@xlinklight/testkit/acceptance-oracle';\nexport type OwnerAcceptanceOptions=Omit<Parameters<typeof exerciseOwnerProduction>[0],'solutionId'|'execution'|'browser'|'providers'|'oracleStatements'>;\nexport const oracles:readonly AcceptanceOracleStatement[];\nexport function acceptOwnerRelease(options:OwnerAcceptanceOptions):ReturnType<typeof exerciseOwnerProduction>;\nexport function createOwnerAcceptancePlan(options:OwnerAcceptanceOptions):ReturnType<typeof createOwnerProductionPlan>;\n";
|
|
8
|
-
async function regular(file,maximum){const info=await fs.lstat(file);if(!info.isFile()||info.isSymbolicLink()||info.size>maximum||await fs.realpath(file)!==file)throw fail();return fs.readFile(file);}
|
|
9
|
-
/** Build the installed trusted oracle library. Public Core ports stay public
|
|
10
|
-
* imports; no provider SDK or uploaded business module is evaluated here. */
|
|
11
|
-
export async function prepareOwnerOperatorBuild({root,signal}={}){
|
|
12
|
-
if(typeof root!=='string'||!path.isAbsolute(root))throw fail();signal?.throwIfAborted();root=await fs.realpath(root);
|
|
13
|
-
const entry=path.join(root,'deployment/operator.mjs');await regular(entry,65536);
|
|
14
|
-
const {build}=await import('vite');
|
|
15
|
-
const result=await build({root,configFile:false,envDir:false,publicDir:false,logLevel:'silent',build:{write:false,emptyOutDir:false,minify:false,sourcemap:false,lib:{entry,formats:['es'],fileName:()=> 'main.mjs'},rolldownOptions:{external:id=>!id.startsWith('.')&&!path.isAbsolute(id)}}});
|
|
16
|
-
signal?.throwIfAborted();const outputs=(Array.isArray(result)?result:[result]).flatMap(value=>value.output??[]);
|
|
17
|
-
if(outputs.length!==1||outputs[0].type!=='chunk'||outputs[0].dynamicImports.length||outputs[0].fileName!=='main.mjs'||!outputs[0].exports.includes('acceptOwnerRelease')||!outputs[0].exports.includes('createOwnerAcceptancePlan')||!outputs[0].exports.includes('oracles'))throw fail();
|
|
18
|
-
const chunk=outputs[0],allowed=new Set(['@xlinklight/testkit/owner-production','@xlinklight/testkit/acceptance-oracle','@xlinklight/platform/worker','node:assert/strict']);
|
|
19
|
-
if(chunk.imports.some(value=>!allowed.has(value)))throw fail();
|
|
20
|
-
for(const id of chunk.moduleIds){if(id.startsWith('\0'))continue;const relative=path.relative(root,id);if(!relative||relative==='..'||relative.startsWith('..'+path.sep)||path.isAbsolute(relative)||relative.split(path.sep).includes('node_modules'))throw fail();}
|
|
21
|
-
const phaseDeclaration=chunk.exports.includes('productionPhaseNames')?"export const productionPhaseNames:ReturnType<typeof import('@xlinklight/testkit/owner-production').ownerProductionPhaseNames>;\n":'';
|
|
22
|
-
const files=[{path:'main.mjs',bytes:Buffer.from(chunk.code)},{path:'main.d.mts',bytes:Buffer.from(declaration+phaseDeclaration)}];if(files[0].bytes.byteLength>4194304)throw fail();
|
|
23
|
-
const output=path.join(root,'dist-operator');let exists=true;try{await fs.lstat(output);}catch(error){if(error.code!=='ENOENT')throw error;exists=false;}
|
|
24
|
-
if(exists){
|
|
25
|
-
if(await fs.realpath(output)!==output)throw fail();const names=(await fs.readdir(output)).sort();if(names.join(',')!=='main.d.mts,main.mjs,operator-build.json')throw fail();
|
|
26
|
-
const previous=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(await regular(path.join(output,'operator-build.json'),65536)));
|
|
27
|
-
if(previous.schemaVersion!==1||previous.kind!=='operator'||!Array.isArray(previous.files)||previous.files.length!==2)throw fail();
|
|
28
|
-
for(const file of files){const record=previous.files.find(value=>value.path===file.path),bytes=await regular(path.join(output,file.path),4194304);if(record?.sha256!==sha(bytes)||record.bytes!==bytes.byteLength)throw fail();}
|
|
29
|
-
}else await fs.mkdir(output);
|
|
30
|
-
const record={schemaVersion:1,kind:'operator',files:files.map(file=>({path:file.path,bytes:file.bytes.byteLength,sha256:sha(file.bytes)}))};
|
|
31
|
-
for(const file of files)await fs.writeFile(path.join(output,file.path),file.bytes);
|
|
32
|
-
await fs.writeFile(path.join(output,'operator-build.json'),JSON.stringify(record)+'\n');return {status:'OWNER_OPERATOR_BUILT',...record};
|
|
33
|
-
}
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {createHash} from 'node:crypto';
|
|
4
|
+
|
|
5
|
+
const fail=()=>Error('OWNER_OPERATOR_BUILD_INVALID');
|
|
6
|
+
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
7
|
+
const declaration="import {exerciseOwnerProduction,createOwnerProductionPlan} from '@xlinklight/testkit/owner-production';\nimport type {AcceptanceOracleStatement} from '@xlinklight/testkit/acceptance-oracle';\nexport type OwnerAcceptanceOptions=Omit<Parameters<typeof exerciseOwnerProduction>[0],'solutionId'|'execution'|'browser'|'providers'|'oracleStatements'>;\nexport const oracles:readonly AcceptanceOracleStatement[];\nexport function acceptOwnerRelease(options:OwnerAcceptanceOptions):ReturnType<typeof exerciseOwnerProduction>;\nexport function createOwnerAcceptancePlan(options:OwnerAcceptanceOptions):ReturnType<typeof createOwnerProductionPlan>;\n";
|
|
8
|
+
async function regular(file,maximum){const info=await fs.lstat(file);if(!info.isFile()||info.isSymbolicLink()||info.size>maximum||await fs.realpath(file)!==file)throw fail();return fs.readFile(file);}
|
|
9
|
+
/** Build the installed trusted oracle library. Public Core ports stay public
|
|
10
|
+
* imports; no provider SDK or uploaded business module is evaluated here. */
|
|
11
|
+
export async function prepareOwnerOperatorBuild({root,signal}={}){
|
|
12
|
+
if(typeof root!=='string'||!path.isAbsolute(root))throw fail();signal?.throwIfAborted();root=await fs.realpath(root);
|
|
13
|
+
const entry=path.join(root,'deployment/operator.mjs');await regular(entry,65536);
|
|
14
|
+
const {build}=await import('vite');
|
|
15
|
+
const result=await build({root,configFile:false,envDir:false,publicDir:false,logLevel:'silent',build:{write:false,emptyOutDir:false,minify:false,sourcemap:false,lib:{entry,formats:['es'],fileName:()=> 'main.mjs'},rolldownOptions:{external:id=>!id.startsWith('.')&&!path.isAbsolute(id)}}});
|
|
16
|
+
signal?.throwIfAborted();const outputs=(Array.isArray(result)?result:[result]).flatMap(value=>value.output??[]);
|
|
17
|
+
if(outputs.length!==1||outputs[0].type!=='chunk'||outputs[0].dynamicImports.length||outputs[0].fileName!=='main.mjs'||!outputs[0].exports.includes('acceptOwnerRelease')||!outputs[0].exports.includes('createOwnerAcceptancePlan')||!outputs[0].exports.includes('oracles'))throw fail();
|
|
18
|
+
const chunk=outputs[0],allowed=new Set(['@xlinklight/testkit/owner-production','@xlinklight/testkit/acceptance-oracle','@xlinklight/platform/worker','node:assert/strict']);
|
|
19
|
+
if(chunk.imports.some(value=>!allowed.has(value)))throw fail();
|
|
20
|
+
for(const id of chunk.moduleIds){if(id.startsWith('\0'))continue;const relative=path.relative(root,id);if(!relative||relative==='..'||relative.startsWith('..'+path.sep)||path.isAbsolute(relative)||relative.split(path.sep).includes('node_modules'))throw fail();}
|
|
21
|
+
const phaseDeclaration=chunk.exports.includes('productionPhaseNames')?"export const productionPhaseNames:ReturnType<typeof import('@xlinklight/testkit/owner-production').ownerProductionPhaseNames>;\n":'';
|
|
22
|
+
const files=[{path:'main.mjs',bytes:Buffer.from(chunk.code)},{path:'main.d.mts',bytes:Buffer.from(declaration+phaseDeclaration)}];if(files[0].bytes.byteLength>4194304)throw fail();
|
|
23
|
+
const output=path.join(root,'dist-operator');let exists=true;try{await fs.lstat(output);}catch(error){if(error.code!=='ENOENT')throw error;exists=false;}
|
|
24
|
+
if(exists){
|
|
25
|
+
if(await fs.realpath(output)!==output)throw fail();const names=(await fs.readdir(output)).sort();if(names.join(',')!=='main.d.mts,main.mjs,operator-build.json')throw fail();
|
|
26
|
+
const previous=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(await regular(path.join(output,'operator-build.json'),65536)));
|
|
27
|
+
if(previous.schemaVersion!==1||previous.kind!=='operator'||!Array.isArray(previous.files)||previous.files.length!==2)throw fail();
|
|
28
|
+
for(const file of files){const record=previous.files.find(value=>value.path===file.path),bytes=await regular(path.join(output,file.path),4194304);if(record?.sha256!==sha(bytes)||record.bytes!==bytes.byteLength)throw fail();}
|
|
29
|
+
}else await fs.mkdir(output);
|
|
30
|
+
const record={schemaVersion:1,kind:'operator',files:files.map(file=>({path:file.path,bytes:file.bytes.byteLength,sha256:sha(file.bytes)}))};
|
|
31
|
+
for(const file of files)await fs.writeFile(path.join(output,file.path),file.bytes);
|
|
32
|
+
await fs.writeFile(path.join(output,'operator-build.json'),JSON.stringify(record)+'\n');return {status:'OWNER_OPERATOR_BUILT',...record};
|
|
33
|
+
}
|