@xlinklight/testkit 0.0.0-stage → 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 -0
- package/README.md +168 -2
- package/content/platform-baseline.sql +273 -0
- package/package.json +274 -3
- package/src/acceptance-oracle.d.mts +24 -0
- package/src/acceptance-oracle.mjs +79 -0
- package/src/architecture-database.d.mts +36 -0
- package/src/architecture-database.mjs +64 -0
- package/src/artifact-build.d.mts +3 -0
- package/src/artifact-build.mjs +35 -0
- package/src/artifact-declarations.mjs +24 -0
- package/src/artifact-graphs.mjs +61 -0
- package/src/artifact-lock.mjs +32 -0
- package/src/artifact-observation.mjs +50 -0
- package/src/artifact-publisher.d.mts +30 -0
- package/src/artifact-publisher.mjs +84 -0
- package/src/browser-lifecycle.mjs +45 -0
- package/src/browser-operation-owner.mjs +28 -0
- package/src/cloudflare-browser.d.mts +14 -0
- package/src/cloudflare-browser.mjs +41 -0
- package/src/cloudflare-build.d.mts +19 -0
- package/src/cloudflare-build.mjs +61 -0
- package/src/cloudflare-http.d.mts +5 -0
- package/src/cloudflare-http.mjs +65 -0
- package/src/cloudflare-pages.d.mts +34 -0
- package/src/cloudflare-pages.mjs +170 -0
- package/src/cloudflare-provider-http.d.mts +8 -0
- package/src/cloudflare-provider-http.mjs +32 -0
- package/src/cloudflare-worker-package.d.mts +6 -0
- package/src/cloudflare-worker-package.mjs +24 -0
- package/src/cloudflare-worker-qualification.d.mts +4 -0
- package/src/cloudflare-worker-qualification.mjs +63 -0
- package/src/cloudflare-workers.d.mts +37 -0
- package/src/cloudflare-workers.mjs +90 -0
- package/src/cluster-directory.d.mts +16 -0
- package/src/cluster-directory.mjs +90 -0
- package/src/core-publishing.d.mts +75 -0
- package/src/core-publishing.mjs +214 -0
- package/src/dev-command-runner.mjs +97 -0
- package/src/fixture-path.mjs +19 -0
- package/src/function-admission.d.mts +1 -0
- package/src/function-admission.mjs +58 -0
- package/src/host-artifact.mjs +32 -0
- package/src/host-stop.mjs +15 -0
- package/src/independent-artifact-qualification.mjs +67 -0
- package/src/independent-runtime-qualification.mjs +647 -0
- package/src/isolated-browser-child.mjs +29 -0
- package/src/isolated-browser.mjs +69 -0
- package/src/lifecycle-trace.mjs +32 -0
- package/src/managed-native-fixture.d.mts +84 -0
- package/src/managed-native-fixture.mjs +209 -0
- package/src/native-fixture.mjs +125 -0
- package/src/native-platform.mjs +56 -0
- package/src/operator-accounts.mjs +103 -0
- package/src/operator-vault.d.mts +2 -0
- package/src/operator-vault.mjs +9 -0
- package/src/owned-process.mjs +75 -0
- package/src/owner-build-cli.d.mts +1 -0
- package/src/owner-build-cli.mjs +31 -0
- package/src/owner-database.mjs +215 -0
- package/src/owner-operator-build.d.mts +1 -0
- package/src/owner-operator-build.mjs +33 -0
- package/src/owner-package-build.d.mts +2 -0
- package/src/owner-package-build.mjs +29 -0
- package/src/owner-production-browser.mjs +215 -0
- package/src/owner-production-instances.mjs +41 -0
- package/src/owner-production.d.mts +104 -0
- package/src/owner-production.mjs +338 -0
- package/src/owner-release.mjs +41 -0
- package/src/owner-worker-build.d.mts +3 -0
- package/src/owner-worker-build.mjs +83 -0
- package/src/prebuilt-build.d.mts +8 -0
- package/src/prebuilt-build.mjs +69 -0
- package/src/prebuilt-output.d.mts +2 -0
- package/src/prebuilt-output.mjs +104 -0
- package/src/production-hosts.mjs +38 -0
- package/src/publisher-acceptance-host-cli.mjs +23 -0
- package/src/publisher-acceptance-owner.mjs +116 -0
- package/src/publisher-acceptance-runner.mjs +250 -0
- package/src/publisher-acceptance-service.mjs +49 -0
- package/src/publisher-acceptance.d.mts +61 -0
- package/src/publisher-acceptance.mjs +3 -0
- package/src/publishing-source.d.mts +11 -0
- package/src/publishing-source.mjs +32 -0
- package/src/qualification-function-host.mjs +26 -0
- package/src/qualification-route-owner.mjs +64 -0
- package/src/qualification-transport.mjs +18 -0
- package/src/registry-core-selection.mjs +41 -0
- package/src/release-artifact.d.mts +17 -0
- package/src/release-artifact.mjs +113 -0
- package/src/release-build.d.mts +12 -0
- package/src/release-build.mjs +71 -0
- package/src/release-cli.d.mts +27 -0
- package/src/release-cli.mjs +79 -0
- package/src/release-control.mjs +45 -0
- package/src/release-coordinator.d.mts +9 -0
- package/src/release-coordinator.mjs +222 -0
- package/src/release-credentials.d.mts +8 -0
- package/src/release-credentials.mjs +97 -0
- package/src/release-environment.mjs +60 -0
- package/src/release-mutex.d.mts +10 -0
- package/src/release-mutex.mjs +38 -0
- package/src/release-operator.d.mts +6 -0
- package/src/release-operator.mjs +59 -0
- package/src/release-supabase.d.mts +7 -0
- package/src/release-supabase.mjs +37 -0
- package/src/release-vercel.d.mts +22 -0
- package/src/release-vercel.mjs +51 -0
- package/src/release-writer.d.mts +6 -0
- package/src/release-writer.mjs +172 -0
- package/src/retained-postgres-shutdown.d.mts +51 -0
- package/src/retained-postgres-shutdown.mjs +262 -0
- package/src/schema-snapshot.mjs +51 -0
- package/src/static-ui-artifact.mjs +54 -0
- package/src/static-ui-routes.mjs +3 -0
- package/src/temporary-acquisition.mjs +62 -0
- package/src/temporary-scope.d.mts +47 -0
- package/src/temporary-scope.mjs +268 -0
- package/src/unscoped-read.mjs +14 -0
- package/src/worker-artifact.mjs +214 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 zopenge
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,169 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Link Light testkit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
## Independent acceptance service
|
|
4
|
+
|
|
5
|
+
Run one project-scoped Node service behind the team's HTTPS ingress. Install the owner's immutable acceptance bundle and the lockfile-selected Testkit on a supported Linux or NTFS host. Configure an existing private browser scratch directory and a persistent state directory with room for the journal and browser evidence. Start the service from the team's process manager, which delivers SIGTERM for graceful shutdown.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm exec link-light-acceptance-runner --config /absolute/private/acceptance.mjs
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The private module exports a default `PublisherAcceptanceServiceOptions` from `@xlinklight/testkit/publisher-acceptance`. It supplies the external `origin`, loopback `port`, `publisherOrigin`, `projectId`, `solutionId`, `publisherKey` (the Publisher's Ed25519 verification key), `receiptKey` (the separately authorized project receipt signer), the absolute `root` and relative `stateDirectory`. Keep private keys and the two synthetic account credentials in protected configuration. The ingress forwards the exact acceptance paths to the loopback port and serves the configured HTTPS origin.
|
|
12
|
+
|
|
13
|
+
Supply `resolveArtifact` using `createInstalledOwnerAcceptance` with the version and SHA-256 of the trusted project's installed `/operator` bundle, its public `/resources` entry and registered resource definitions, the Core origin, the two explicit accounts and actor IDs, and the installed Playwright `expect` and browser host. `createOwnerAcceptanceBrowserHost` consumes the absolute, installed `@playwright/test` entry and private scratch directory. It uses the platform's already installed browser. When staging another version, complete the current job before replacing its installed operator, or supply an exact resolver for both immutable versions.
|
|
14
|
+
|
|
15
|
+
An owner entry can use `createOwnerAcceptanceServiceOptions` with its explicit public entries and `serverBinding.registration()`. Its private JSON settings file contains exactly `accounts`, `actors`, `browserDirectory`, `coreOrigin`, `operatorSha256`, `origin`, `port`, `projectId`, `publisherKey`, `publisherOrigin`, `receiptKey`, `root` and `stateDirectory`. Supply the absolute settings path through `LINK_LIGHT_ACCEPTANCE_SETTINGS_FILE` when the owner's configuration module expects it. Keys in this file use PEM strings.
|
|
16
|
+
|
|
17
|
+
The Publisher discovers an exact version's digest at `GET /v1/acceptance/artifact?version=…` and sends its signed envelope to `PUT /v1/acceptance/jobs/<job-id>`. A replay of that envelope only observes or advances the original durable work. Read the scoped job status with `GET` on the same job URL and the original envelope signature as the bearer value. The runner submits the durable signed receipt to the configured Publisher origin. Lost receipt responses are reconciled from the same job and receipt. A running claim left by an unexpected process stop remains unknown pending exact reconciliation. Preserve the journal and its evidence while resolving an unknown claim.
|
|
18
|
+
|
|
19
|
+
## Test and release tooling
|
|
20
|
+
|
|
21
|
+
Independent SQL and recovery qualification composes the owner's public `serverBinding` with the public platform Node host in a separate TLS process. This local test fixture does not use a retired owner Node deployment entry. The deployed business artifact is a separately sealed Cloudflare Worker module closure; `qualifyCloudflareWorkerArtifact` executes its actual receipt endpoint in the installed workerd with no outbound network or database credentials. A fixture-owned wake driver performs budgeted local dispatches and stops before its process/database dependencies. Actual child closure, EOF and distinct-process recovery remain required; neither local fixture establishes production acceptance.
|
|
22
|
+
|
|
23
|
+
`drainQualificationDeliveries` retains durable delivery evidence and separately reports runs blocked by current database authority. It waits for runnable work, with a default40-RunRef ceiling and at most32 delivery events per run. A frozen larger measurement recipe can explicitly select `maximumRunRefs` up to256; this does not change its latency, concurrency, closure or shared4GiB resource limits. Revoked work is never treated as successful execution.
|
|
24
|
+
|
|
25
|
+
`release-build` prepares package-name/version build metadata, a real business-library archive, server/UI receipts and the sealed Cloudflare Worker modules in fixed owned outputs. Business artifacts do not require a Git revision, Git hosting service or provider credentials. The publishing service binds the complete captured content identity to actual immutable destinations; a local build neither assigns an address nor approves a release.
|
|
26
|
+
|
|
27
|
+
`owner-database` version2 provisions only distinct application and Worker identities. Its explicit target/credential model rejects retired queue fields and polling configuration. Initialization preserves business data and refuses conflicting existing roles or Vault ownership. No credential adoption, rotation or production data reset is implicit.
|
|
28
|
+
|
|
29
|
+
`release-cli` provides bounded native CLI capture with private stdin, actual close/EOF checks and no shell. It is operator/build tooling; do not import it into an application or Worker.
|
|
30
|
+
|
|
31
|
+
`release-cli.runPackageScript` lets a repository keep long local command lists in a formal task script while package.json contains short entrypoints. The owner declares ordered `node`/`pnpm` argument arrays; additional CLI arguments reach only the final command. Terminal I/O is inherited, the first failing exit code stops the sequence, and interruption uses the existing owned-process closure path. It adds no shell expansion, package installation, hidden test selection or work deadline; each declared tool and its existing outer owner retain their original limits.
|
|
32
|
+
|
|
33
|
+
Version6 supplies `link-light-build` for `build-info`, `build-package`, `build-operator`, `build-worker` and `build-static-ui`. Business publication uses the separate `@xlinklight/publishing` executable `link-light-release` and an explicitly owned `deployment/publishing.mjs` producer. `runOwnerSourcePreparation` executes declared checks/builds/post-build checks through the owned process boundary and reports honest process/pipe closure; unknown source work cannot be rerun. Developers install a project credential, while the replaceable publishing service owns provider credentials, deployment, durable recovery and actual acceptance.
|
|
34
|
+
|
|
35
|
+
`link-light-build` accepts only the five local build commands above. Project authorization and publication use `link-light-release` from `@xlinklight/publishing`; database preparation remains an explicitly authorized operator/service concern through the owned database APIs. The build executable does not configure provider credentials, upload artifacts or act as another publication controller.
|
|
36
|
+
|
|
37
|
+
`release-build` exposes `writeOwnerBuildInfo`, `prepareOwnerPackageBuild`, `prepareOwnerOperatorBuild`, `prepareOwnerCloudflareWorkerBuild` and `prepareOwnerStaticUiBuild` with an explicit owner root. Worker bundling uses that owner's explicitly selected Wrangler4.158.0 installation; the public resource reader and AOT catalog bind original resource bytes. `owner-database.runOwnerDatabaseCommand` reuses the owner's existing schema contract and preparation gates. `owner-release.loadOwnerInfrastructure` receives the public platform database/relations/metadata verifiers from the owner's composition; it preserves TLS, ordinary role and runtime-key checks.
|
|
38
|
+
|
|
39
|
+
`release-credentials` prepares an operator-only `.env.release.local` through bounded hidden terminal input and verifies actual access to the selected active Hobby team before creating it. It never overwrites an existing file, reads general application environment files or changes global settings. The file is plaintext local configuration, excluded from Git and deployment; use normal protected environment configuration when available. `runReleaseWithToken` gives an explicit `VERCEL_TOKEN` priority, passes the credential only to the injected public Foundation publisher and restores its process environment after success/failure. Local recovery and retirement remain usable without reading this file. Token validation proves team access, not exclusive token scope or remaining quota; the operator selects the team scope on the provider's token page.
|
|
40
|
+
|
|
41
|
+
The Core release operator forwards `recover`, `recover --run-id <exact-uuid> --discard-checkout` and `retire --run-id <exact-uuid>` to the public Foundation publisher. Checkout discard requires a matching run, verified cessation and no attempted provider writes. The SDK owns disposition from the original evidence. Keep bound journals in `state/forge-vercel-release/` and `state/release-slot/`. Disposable release outputs use `tmp/`.
|
|
42
|
+
|
|
43
|
+
`release-supabase` accepts both the pinned CLI's normal JSON row array and its optional agent-mode `rows` envelope. Ordinary terminal publication does not require agent detection or an AI host environment. Invalid JSON and malformed rows still fail; SQL and private CLI output remain outside public error messages.
|
|
44
|
+
|
|
45
|
+
Version4.1 adds `releaseOperatorFailure(error, {stage, publisher}?)` to `release-credentials`. It returns an `ok: false` report with a safe operator error code and stage. When outer coordination fails after an SDK result exists, the optional `publisher` projection preserves only validated run/slot/source identity, stage, error classification and closure status. It never serializes raw Error causes, CLI output or credentials. A successful inner publisher result does not make a failed outer operation successful. This helper changes diagnosis only; it grants no recovery, replay or publication authority.
|
|
46
|
+
|
|
47
|
+
`release-vercel` creates a bounded operator client from the caller's explicit checkout and declared Vercel64.7.0 CLI. It uses the public bin and authenticated CLI, with no token-store access or private Foundation implementation. API helpers accept only relative endpoints and GET/POST/PATCH. Secret bodies are passed through stdin and raw output stays private in memory; publish selected metadata only. This helper does not replace the Foundation publisher or authorize a deployment, deletion, cost increase or database operation.
|
|
48
|
+
|
|
49
|
+
`release-supabase` uses the caller's pinned Supabase CLI 3.2.0 for bounded SQL stdin and private key inspection. An explicit project reference selects the hosted Management API path using the existing CLI login. Query rows, key results and error causes are private. Select and validate only the fields needed by the operator. This path is for administrative releases. `operator-vault` supplies the common SQL isolation guard.
|
|
50
|
+
|
|
51
|
+
`release-coordinator` serializes check/publish/verify through one live PostgreSQL session, using a dedicated publication-only login without application or Vault access. First publish initializes that role and its encrypted operator credential atomically from committed target configuration; a first standalone check requires prior setup. It registers an idle generation before calling the injected public publisher; `enterReleaseWriter` claims only from an SDK-managed prepare/acceptance job. A lost pre-SDK acknowledgment cannot strand held publication. Monotonic fencing rejects stale acquisition/release. Standalone verification always obtains coordination and the public original selection before acceptance. Connection loss aborts work without clearing the durable writer. Held/uncertain rows have no expiry or PID takeover. Fixed `state/release-writer/` recovery storage holds at most32 immutable8KiB records; successful records are immediately removed. Resolve any old writer through its original version before upgrading; the new path does not clear a held remote writer. Local recovery runs before provider access; unresolved settlement returns `coordination.status: HELD`. Retirement never clears held coordination. `function-admission` uses bounded public GETs to require active Hobby, the exact Git-unlinked basic/Fluid project, a current writer and finite free Node24 settings. Remaining quota explicitly stays UNKNOWN; quota refusal pauses without purchase, upgrade or mutation retry. These controls do not replace the Foundation seal, managed completion or real production acceptance.
|
|
52
|
+
|
|
53
|
+
Coordination matches the public SDK's canonical root-relative `configPath` together with its exact `sourceRoot` and candidate. Absolute, escaped or alternative configuration spellings cannot settle a writer. A closed failure before any remote mutation may settle through the SDK's failed receipt; explicit public recovery still requires closed, settled, same-candidate proof. No local file deletion, process absence or path normalization invents that proof.
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
With the pinned public Foundation publisher, pending completion also retains coordination. Completed evidence must bind the exact team/project/source/configuration/artifact/deployment before settlement. `runReleaseWithToken` forwards `--retry-completion` only for explicit original-full-SHA verification; its preliminary status read never receives that flag. Operator failure exposes a coordinated pnpm `nextCommand`, preserves the SDK's original evidence and never turns unproved completion into success. Completion admission repeats the Hobby/finite-Function/current-writer checks for both publish and explicit verify.
|
|
57
|
+
|
|
58
|
+
`release-artifact` provides deterministic file/hash receipts for actual build outputs. `writeReleaseArtifact` hashes explicit files/trees within one checkout, enforces byte/file limits and rejects linked escapes, duplicates and self-reference. `traceReleaseServerArtifact` uses the caller's pinned tracer and explicit resources, rejects unresolved edges/UI dependencies, and does not expand resolver-directory aliases into every package export. `verifyReleaseArtifact` checks the same actual bytes. Output replacement is explicit and requires an existing valid receipt of the same kind; unrelated files remain protected. Receipts contain no timestamps or absolute paths and grant no approval. These helpers are build/operator tooling. Production runtimes use the public platform SDK's `verifyIndependentNodeServerArtifact`; testkit stays outside runtime dependency graphs.
|
|
59
|
+
|
|
60
|
+
`@xlinklight/testkit` is a development dependency for synthetic acceptance tests. It is not a runtime core package and contains no business defaults or sibling-source discovery.
|
|
61
|
+
|
|
62
|
+
`native-fixture` exports `startNativeFixture({root, runtimeRoot, label, domains, ...options})`. Supply the business repository root, the explicit installation root containing native dependencies, a stable lowercase label of at most 48 characters, and each domain's public schema entry, tables and schema owner. The returned fixture retains its original process, pool, evidence, queue, close and dispose ports. Host installations are separate: `host-artifact` loads the fixed built public Worker testing entry under the explicitly supplied installation root, or `LINK_LIGHT_TEST_HOST_ARTIFACT_ROOT`. It checks the neutral Worker entry and public archive inventory; it does not require Web/UI outputs or old static assembly tooling. Independent browser acceptance supplies its owner's separate UI archive explicitly.
|
|
63
|
+
|
|
64
|
+
Lifecycle helpers are available through `temporary-scope`, `owned-process`, `native-platform`, `cluster-directory`, `managed-native-fixture`, `retained-postgres-shutdown` and `host-stop`. Managed native fixtures require an explicit repository `root`; environment authority, fixed slots, ownership journals, closure proofs and byte budgets remain mandatory.
|
|
65
|
+
|
|
66
|
+
`artifact-graphs` qualifies actual installed JavaScript: `qualifyBrowserBundle({root,entry,cacheDirectory})` compiles the UI with Vite while rejecting Node/server imports, external source paths and config/environment discovery. `qualifyServerGraph({root,entry,uiEntry})` follows owned JavaScript edges and rejects UI/React/Web imports, cycles, unresolved dependencies and consumer escapes. External npm edges stay visible without traversing their internals; real Worker acceptance remains separate.
|
|
67
|
+
|
|
68
|
+
`artifact-declarations` writes a strict TypeScript public API probe from an explicit consumer-local configuration. Run the probe through the consumer module fence with its installed compiler. It audits the real paths of every source file returned by the compiler and rejects ancestor or linked external declarations; the core public-package gate exercises a real ancestor-import rejection.
|
|
69
|
+
|
|
70
|
+
`worker-artifact` exports `prepareWorkerArtifact({root, entry, output, trace, additionalEntries, resources, maximumBytes, maximumFiles, ignore})`. The publisher supplies its pinned tracer, compiled entry, dynamically loaded server entries and owned resources. It emits one source-free runtime under an absent `.local/` slot, with relative package links and a deterministic file/hash receipt. All resolved paths stay inside the explicit checkout. Missing dependencies, UI framework dependencies, external links and byte/file overflow reject before publication. The default 16 MiB/4096-file budget includes the receipt; existing output is never overwritten. Root package metadata retains runtime identity/exports without development dependencies. The result reports trace/write durations, not image size or provider upload performance. This is a build-time tool; no testkit dependency is copied into the runtime.
|
|
71
|
+
|
|
72
|
+
`emitVercelWorkerFunctions` adds exact finite Worker routes to a completed Build Output v3 tree. Verified relative package links and their complete traced targets stay inside each Function, preserving Node's realpath-based transitive dependency resolution. All payload and link bytes count toward the output budget. Existing Web routes remain intact. Conflicting output and native Windows payloads fail before publication; Linux native-runtime compatibility still requires its own acceptance.
|
|
73
|
+
|
|
74
|
+
`prebuilt-build` prepares offline project settings from an explicit prebuilt release configuration for the pinned official Vercel CLI. It refuses foreign project files and linked roots, and never pulls cloud environment variables or reads previous task directories. Foundation's public release module owns staging, candidate proof and promotion. Preparing settings alone does not prove a real Vercel build or production release.
|
|
75
|
+
|
|
76
|
+
`parsePrebuiltCandidateContext` validates the protected publisher context against the selected team, project, full source revision, configuration, artifact, deployment and immutable version origin. Owners require `versionAliasVerified: true` before accessing publishing credentials. It does not assign an alias, verify provider ownership or grant runtime authority. `observePrebuiltMarkers` can also bind the expected configuration digest; matching markers alone never replace Foundation's provider proof.
|
|
77
|
+
|
|
78
|
+
For an independently hosted frame it may write the two declared public HTTPS frame origins into its own marked build environment file. Private/foreign files, extra keys and conflicting inherited origins are refused. Normal dependencies have already been installed by the managed source phase; the service producer checks the existing package manager rather than installing again. Explicit `.vercelignore` rules exclude local verification payloads, independently of Git ignores.
|
|
79
|
+
|
|
80
|
+
`prebuilt-output` finalizes the official producer's complete Build Output after all Functions have been added. Resolver links may use only already emitted trace mirrors in that exact Function; it never copies an entire installed package or adds untraced files. It makes every link relative and internal, verifies hashes and budgets before replacement, rejects cycles and incompatible native bytes, and leaves interrupted staging/source trees for explicit recovery. The old output is reclaimed only after replacement succeeds. Foundation0.7.0 binds portable internal relative links and their complete target closure and uses official CLI tgz transport. Complete output cannot contain unmaterialized empty payload directories. Final publisher admission requires its clean committed managed check; these consumer helpers do not replace it or alter a sealed artifact. Actual Linux and production acceptance remain separate requirements.
|
|
81
|
+
|
|
82
|
+
Independent archive acceptance supplies owner-owned `artifactAcceptance: {program,declarations}` to `verifyIndependentOwnerArchive`. Each string is bounded to 128 KiB. `artifact-lock` projects the installation's frozen registry closure onto the selected public tarballs, retaining unambiguous peer-qualified snapshots; installation stays offline with `--frozen-lockfile`, and the lock bytes must remain unchanged. The fixture checks every installed archive byte before executing the program, runs the owner's literal domain/resource assertions from two working directories, checks strict declarations with exact owner-selected compiler/type versions, bundles the UI, checks the server graph, and rejects six damaged payload variants before import. Runtime imports and the actual TypeScript source-file closure must remain inside the consumer, including resolved links. Qualification requires Node 22.15 or newer for synchronous module hooks. Temporary consumers own their dependencies and retire after actual child closure. The program is test input from the owner; production core never installs or executes business archives.
|
|
83
|
+
|
|
84
|
+
Independent runtime fixtures use explicit archives, actual `serverArtifact`/`uiArtifact` JSON receipts, TLS inputs and one fixed, shared 4 GiB budget. `ownerArchive` binds the installed package identity; the server receipt binds the release server digest. The retired `uiEntry` input is rejected. Browser qualification defaults to eight cumulative profiles. Measurement may explicitly select `maximumProfiles:20`, with at most ten pending or active contexts; `closeProfile()` closes only the initial context, while `close()` closes the whole browser. `trackCommitTimestamp:true` enables PostgreSQL commit timestamps only for explicit measurement. `ownerConfig` contains synthetic bootstrap credentials for independent observation; never copy it to reports.
|
|
85
|
+
|
|
86
|
+
Browser callers supply `browserFixture:{coreOrigin,uiOrigin,uiFiles}`; `captureQualificationBrowserFixture({root,uiOrigin?})` reads the owner's bounded target configuration and captures once through the public `captureOwnerStaticUiFiles` API. The default logical UI origin is the reserved fixture authority `https://ui.qualification.invalid`; an override must be canonical HTTPS and distinct from Core. The fixture signs that exact UI authority into its release and publisher UI origins and uses it for the iframe and SDK peer. Native-only fixtures do not require this input and keep their original physical origins. A private raw-byte/header snapshot checks the original UI receipt, each file hash and complete closure, including the byte-identical public receipt. The existing 256 MiB payload bound remains finite; no standalone archive is extracted or Next server launched. Pages publishing, actual deployment observation and the local static fixture share the same raw/served pathname mapping, without remounting a version path onto root bytes.
|
|
87
|
+
|
|
88
|
+
The browser uses the configured logical Core origin, profile cookies and bridge hash unchanged. Contexts block service workers and intercept both exact logical origins to fixed local TLS fixtures, preserving method/body/Origin/cookies with zero redirects/retries, a finite timeout and disposal of fulfilled response bodies. Neither logical origin reaches public network. Held privacy queries use that same explicit fetch seam. The physical localhost UI serves original static bytes, MIME and CSP; every other browser origin is aborted. UI readiness probes use the physical TLS authority and the actual manifest pathname. `fixture.origins` remains physical for server-to-server capabilities; `fixture.browserOrigins` identifies the logical Core/UI boundaries. Bounded browser diagnostics record redacted console errors/warnings, page errors, failed requests, response status/policy and frame URLs without URL query/hash values; diagnostics cannot replace the first exercise error. `ownerApiEvidence` records actual native TLS API health and successful signed methods, bound to the current release/server receipt. These are controlled local fixture results, not production Core/browser acceptance.
|
|
89
|
+
|
|
90
|
+
Each intercepted request owns a private Playwright request context through fetch, fulfillment and disposal. Profile `reload(options)` and `close()` register cancellation before invoking the actual browser action and await the same pending requests. Browser callbacks settle locally; unexpected transport failures enter the fixture's failure channel, stop new fixture calls, cancel profiles and await the original exercise before normal disposal. Direct browser consumers may observe `view.failure`; the public qualification runner owns this channel automatically. `browserRoutes` retains bounded per-profile settlement counts. The same `current-results.json` is written as `RUNNING` before producer admission, bound to the current scope owner and candidate receipt/helper bytes; ordinary failures, including falsy thrown values, finish as `FAIL`.
|
|
91
|
+
|
|
92
|
+
Browser qualification and production browser checks launch the pinned Playwright entry in a dedicated child with private temporary/configuration directories. They never change the calling runner's environment or user/system settings. Chrome receives an explicit disposable user-data directory through Playwright; no browser installer runs. Closure waits for both the browser server and launch child, including their output pipes. A child environment is not a filesystem sandbox or evidence of production acceptance.
|
|
93
|
+
|
|
94
|
+
Recovery may explicitly capture `captureRuntimeIdentity()` and reuse it through `runtimeIdentity` across sequential fresh fixtures. This preserves finite local endpoints and matching Ed25519 identities without retaining databases or passwords. Browser identities additionally retain `browserOrigins:{core,ui}`; restoring requires the same explicit logical origins and browser snapshot inputs. Native identities retain their original shape and physical-origin contract. A `restore(owner, metadata)` callback replaces normal registry seeding, must return the exact `releaseDigest`, and completes before ingress opens. Its metadata includes the selected manifests, publisher and `protectSecret`; register restored session keys or other synthetic credentials for redaction before inserting them. Captured private keys and private snapshots belong only in bounded disposable memory/files, never in reports. The fixture also exposes `protectSecret` for caller-owned test service credentials. `reserveBytes` reserves up to 64 MiB for caller-owned backup and log growth before producer admission; it reduces the native allowance within the same 4 GiB total.
|
|
95
|
+
|
|
96
|
+
Ordinary PostgreSQL shutdown uses `pg_ctl stop -m fast -w` with a 60-second deadline. Success still requires producer and controller closure, both output EOFs and listener release. Explicit `terminationGraceMs` fault bounds may be shorter (1..60000 ms); a timeout preserves UNKNOWN even if the processes exit later. PostgreSQL has no forced-kill fallback, and other owned processes keep their separate shutdown policy.
|
|
97
|
+
|
|
98
|
+
`dev-command-runner` exposes `createDevCommandRunner`, `createProcessControl`, `findProcessByPort`, `killProcess`, `normalizeProcessInfo`, `parsePort` and `looksLikeNextDev`. It uses the declared Forge providers with process identities, bounded identity acquisition and shutdown, and cancellation. Bare PID termination is rejected; the caller selects its provider and owns any running command.
|
|
99
|
+
|
|
100
|
+
`lifecycle-trace` exports `createLifecycleTrace({directory, fixture, enabled})` for a caller-owned existing evidence directory and a safe fixture label. Its fixed NDJSON file is limited to 64 KiB, bound to the opened file identity, and contains only timestamps, actor/producer identity, phase, outcome and a bounded error code. It never copies error messages, SQL or credentials. Native fixtures record initialization, running and shutdown through this implementation. Trace failures remain visible while normal PostgreSQL shutdown still runs; successful ordinary verification removes its fixed slot, while explicit retained evidence remains owned by its caller.
|
|
101
|
+
|
|
102
|
+
Run `pnpm --filter @xlinklight/testkit build` before packing. Its build script copies the authoritative `infra/database/supabase/migrations/20260928105130_platform_baseline.sql` into the fixed ignored `content/platform-baseline.sql` only when bytes differ. The packed `platform-baseline` export contains that resource; installed fixtures never read another repository's infrastructure source. Run `pnpm --filter @xlinklight/testkit test` for controlled public API checks. Actual PostgreSQL, Worker and browser acceptance still require their explicit fixture dependencies and authorization.
|
|
103
|
+
Browser views expose `closeBrowser()` to quiesce Chrome before unrelated recovery producers. This awaits the owned client and launch process; the fixture's native API stays available until fixture shutdown. The finite disk census still rejects incomplete observations.
|
|
104
|
+
|
|
105
|
+
`assertUnscoped()` requires zero visible rows or an explicit `42501` raised by the platform authorization fence. Missing relation privileges, missing tables and unrelated database errors remain failures; successful authorized business queries and writes qualify privileges separately.
|
|
106
|
+
|
|
107
|
+
# Explicit architecture database fixtures
|
|
108
|
+
|
|
109
|
+
`@xlinklight/testkit/architecture-database` uses the same owned native PostgreSQL driver as `native-fixture`. Callers provide absolute `root` and `runtimeRoot`, an explicit `migrations: [{name, sql}]` list, and any `prerequisiteSql`; the fixture does not scan a checkout or select business schemas. `domains: []` is an explicit neutral selection in the native driver. The wrapper records migration digests, supports independent connections and real transactions, and waits for owned process closure, both output EOFs and listener shutdown before cleanup.
|
|
110
|
+
|
|
111
|
+
Run `pnpm test:architecture-native` for its real PostgreSQL migration, rollback, independent connection and cleanup test. SQL and business assertions stay in their owning repositories.
|
|
112
|
+
# Independent cloud release builds
|
|
113
|
+
|
|
114
|
+
`@xlinklight/testkit` supplies build/test and explicitly selected service-adapter tools. The public `@xlinklight/publishing/node` workflow owns ordinary business publication: the local `PublishingSourceProducer` checks/builds and captures exact opaque package bytes, while the separately configured service owns provider credentials, persistent operation claims, deployment and actual acceptance. Developers install one publishing-project authorization through bounded non-TTY stdin. A Git branch, GitHub account, Docker or developer-held provider/database credential is not a client prerequisite. Complete `content.manifestSha256` identifies the captured artifact; Git provenance is optional.
|
|
115
|
+
|
|
116
|
+
The client keeps private authorization, frozen source bytes and original request claims in `state/solution-publishing/`; the service supplies a durable journal with real CAS and an exclusive project lease. Host admission must account for all retained logical state and actual storage/plan/rollout capacity. `status`, `recover` and `verify` observe the original request. Recovery does not rebuild source or repeat a claimed unknown mutation; missing evidence remains unknown. An uploaded artifact, ready provider service or local check is not an active release. Actual owner acceptance and a signed, independently verified activation receipt are required.
|
|
117
|
+
|
|
118
|
+
Use the installed public executables directly, or owner scripts that invoke them:
|
|
119
|
+
|
|
120
|
+
```sh
|
|
121
|
+
pnpm exec link-light-build build-info
|
|
122
|
+
pnpm exec link-light-release check
|
|
123
|
+
pnpm exec link-light-release publish --no-wait
|
|
124
|
+
pnpm exec link-light-release publish --wait-ms 300000
|
|
125
|
+
pnpm exec link-light-release status
|
|
126
|
+
pnpm exec link-light-release recover
|
|
127
|
+
pnpm exec link-light-release verify
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
`publish --no-wait` returns after submission; `--wait-ms` bounds read-only status waiting. Pending or timed-out results are not success. Pipe the private `{configuration, credential}` authorization into `pnpm exec link-light-release credentials --stdin`; protect the client journal and never pass secrets in command arguments or source-build environments. Explicit abandonment and a later `--new-preparation` remain subject to proven original closure and current policy. The source APIs described here do not establish a completed production deployment.
|
|
131
|
+
|
|
132
|
+
The `artifact-build`, `artifact-publisher`, `artifact-observation` and `core-publishing` entries serve explicitly configured operator compositions. The Core adapter supplies six separate durable operations for origin admission, registration, drain, activation, actual owner acceptance and the final signed publishing receipt. Provider stages and Core stages share the public publishing worker; there is one operation journal and no second release controller.
|
|
133
|
+
|
|
134
|
+
The operator-only release entries are deliberately separate from runtime imports:
|
|
135
|
+
|
|
136
|
+
- `function-admission` and `release-coordinator` cover the core host's finite Function path. Retired Git-binding and Daemon admission APIs are removed. Existing Vercel OCI data retains its separate approval/reference/storage constraints; this core path produces or deletes no image. Independent owners publish declared Cloudflare Worker modules and separate Pages UI assets.
|
|
137
|
+
- `release-control` provides bounded exact-origin operator/test HTTP sessions and revokes the original cookie even on failure.
|
|
138
|
+
- `owner-release` supplies explicitly authorized infrastructure checks and finite API/Worker readiness probes bound to exact release/resource digests. `artifact-observation` verifies all deployed opaque asset/receipt bytes and declared response policy. `artifact-publisher` inspects a schema2 pinned Vault identity and signs exact candidates or original publishing activations; it contains no legacy identity migration or key rotation.
|
|
139
|
+
- `owner-production` exercises dedicated owned Auth actors through real deployed instances, public queries/tasks, persistent results/events/outbox, shared membership and disable/re-enable. The installed owner supplies domain inputs, value oracles and any explicitly approved provider setup through the same six ordered phases for local and durable execution: `setup`, `personal-first`, `personal-second`, `authorization`, `browser` and `cleanup`. Only the final cleanup phase can produce the completed proof, after checking browser evidence and disabling every tracked synthetic instance; each phase retains its bounded HTTP accounting and original state. Its explicit browser host drives the real core page and distinct-origin deployed iframe; the selected Cloudflare Browser Run adapter verifies actual session closure. This module is an acceptance driver, not proof that a caller has run it.
|
|
140
|
+
- `acceptance-oracle` defines one immutable registry of named, bounded statements. Installed operators export their owned `oracles`; the production driver combines them with the neutral budget and committed-run statements and exposes only `fixture.oracle.query(descriptor, values)`. The operator receives an explicit `oracle` query port. Local qualification passes the same declaration's `{name,text,values}` to its owned PG connection; a private publisher selects a fixed typed function using the registered statement identity, its `sha256:` digest and the current release context. Raw SQL strings, cloned declarations, unexpected columns and unconfirmed DML counts are rejected. Private adapter errors are masked. Budget observations follow creation of the primary instance and all explicit provider links, before provider preparation; all tracked queries must settle before instance/session cleanup.
|
|
141
|
+
- `schema-snapshot` reads bounded catalog definitions without business rows. Owner scope rejects platform/provider schemas. The explicit platform scope admits only the two neutral platform schemas for a core operator's forward migration. `owner-database` verifies exact owned schema contracts/predecessors, scopes object GRANTs to the application login, and prepares two distinct ordinary application/Worker logins without rotating unknown credentials or deleting data.
|
|
142
|
+
- `release-environment` configures only declared production Secret keys. Matching digest comments are insufficient: an encrypted Vault receipt must also match the current provider variable ID and timestamp. `operator-accounts` prepares only the explicitly scoped synthetic actors, authenticates them and revokes sessions; it never adopts unrelated users or deploys administrative credentials.
|
|
143
|
+
|
|
144
|
+
The supported Supabase operator query limit is256KiB, including catalog guards and DDL. Outputs/errors can contain private material internally and must not be logged wholesale. Public-package code does not discover another repository, private implementation or historical temporary environment.
|
|
145
|
+
|
|
146
|
+
`@xlinklight/testkit/release-build` supplies the local `build-info`, `build-package`, `build-operator`, `build-static-ui` and `build-worker` operations. The local library tarball and its SHA-512 integrity bind the exact Worker build. `prepareOwnerOperatorBuild` emits a static public oracle library with explicit Core ports for the owner runner. `prepareOwnerCloudflareWorkerBuild` seals raw Data resources, AOT validators and a separate Text receipt through the selected Wrangler dry run. Build hosts declare the platform and solution SDK peers explicitly. The package sent to Publisher contains the release descriptor, UI snapshots and declared Worker modules. The builder rejects archive identity or integrity changes before freezing those bytes for source-free recovery.
|
|
147
|
+
|
|
148
|
+
Browser continuation requires the original checkpoint, the closed session and
|
|
149
|
+
the exact synthetic instances. When a browser submission already committed,
|
|
150
|
+
the runner checks the historical commit evidence and reads its original run
|
|
151
|
+
through current Core authorization. It then checks the browser-visible value
|
|
152
|
+
and reloads the deployed UI. A recovered checkbox can be bound to a verified
|
|
153
|
+
visible fact fingerprint and its exact accessible name. The locator must still
|
|
154
|
+
resolve to exactly one control. An owner with a provider link refreshes its
|
|
155
|
+
provider fixture in bounded requests before the browser resumes. New browser
|
|
156
|
+
submissions are checked by the separate committed-run oracle.
|
|
157
|
+
|
|
158
|
+
Provider adapters are explicitly selected service dependencies. Their SDK peers are required only by the host selecting those adapters, not by a publishing client. Pages uses bounded lazy UI reads and an explicitly owned fetch transport. Workers uploads exact declared modules, compatibility settings and host-owned bindings, then observes the original immutable provider version and its reported Version URL. Unknown effects never authorize another upload. Runtime secret versions bind both a host-owned immutable reference and a secret hash into the opaque configuration digest; redacted provider readback proves identity and binding, not a cleartext secret.
|
|
159
|
+
|
|
160
|
+
Provider factories require an explicit `createHttpTransport({signal})` returning an owned `fetch` and `close` pair. The adapter awaits actual pending requests and transport closure. The public Node transport's fulfilled void close result represents its actual completed close contract; a Worker transport must return `{status:'closed',activeRequests:0}`. An explicit unconfirmed result or remaining request is preserved as unconfirmed. These ports do not read ambient credentials or select a proxy from the host environment.
|
|
161
|
+
|
|
162
|
+
The Workers receipt supplies the provider-reported immutable `origin` and exact `runtimeUrl` ending in `/runtime`. The Pages receipt supplies its immutable `origin` and exact `uiUrl` from the declared entry's canonical served route. Core publication consumes those two exact URLs; no version directory, origin prefix or guessed address is substituted. Origin admission and current signed-release authorization remain separate checks.
|
|
163
|
+
|
|
164
|
+
`@xlinklight/testkit/cloudflare-build` supplies `bundleCloudflareWorker` through the selected installed Wrangler4.158.0 public CLI. It runs only the official `deploy --dry-run` bundle path with `nodejs_compat`; it does not upload, install, discover provider credentials or modify host settings. The caller supplies an existing private scope, explicit trusted entry/tool paths and a direct-child output name. An explicit empty compiler configuration and tool working directory share the private control directory, so host TypeScript paths cannot override public package conditions or generated Worker resource ports. Tool logs, caches and child-only configuration remain in that scope. The result preserves exact output bytes, the official dependency graph and actual process/EOF closure receipts. Scope cleanup remains with the original caller. An unconfirmed process cannot become successful closure by a deadline.
|
|
165
|
+
|
|
166
|
+
The replaced artifact controller, its separate state engine and developer provider-credential fan-out are removed. Ordinary owner publication uses the public publishing workflow and selected service stages, without a compatibility forwarding path. The remaining generic operator helpers retain their own authorization and acceptance contracts.
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
Worker packaging retains its default refusal to overwrite an existing output. An explicit `replace:true` reuses a closed build-only slot only when every old file/link, byte/hash, package identity and directory belongs to its valid receipt. It refuses unrelated, changed or partial outputs. The complete new candidate is traced and checked against budgets before the old slot is reclaimed. Callers must close consumers and serialize builds; this option grants no permission to retry a policy-refused cleanup. Publication/recovery reports live outside this disposable payload. Interrupted incomplete outputs remain for exact inspection rather than being silently erased.
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
-- Fresh neutral baseline. No legacy schemas, data or industry tables are inputs.
|
|
2
|
+
BEGIN;
|
|
3
|
+
CREATE ROLE platform_schema_owner NOLOGIN NOSUPERUSER NOBYPASSRLS;
|
|
4
|
+
CREATE ROLE platform_identity_reader NOLOGIN NOSUPERUSER NOBYPASSRLS;
|
|
5
|
+
CREATE ROLE platform_runtime NOLOGIN NOSUPERUSER NOBYPASSRLS;
|
|
6
|
+
CREATE SCHEMA platform AUTHORIZATION platform_schema_owner;
|
|
7
|
+
CREATE SCHEMA platform_private AUTHORIZATION platform_schema_owner;
|
|
8
|
+
REVOKE ALL ON SCHEMA platform, platform_private FROM PUBLIC;
|
|
9
|
+
CREATE TABLE platform_private.instances (
|
|
10
|
+
tenant_id text NOT NULL, instance_id text NOT NULL UNIQUE, solution_id text NOT NULL,
|
|
11
|
+
solution_version text NOT NULL, enabled boolean NOT NULL, authorization_revision text NOT NULL CHECK(authorization_revision ~ '^(0|[1-9][0-9]{0,63})$'),
|
|
12
|
+
catalog_digest text NOT NULL CHECK(catalog_digest ~ '^sha256:[0-9a-f]{64}$'), PRIMARY KEY(tenant_id,instance_id));
|
|
13
|
+
CREATE TABLE platform_private.access (
|
|
14
|
+
tenant_id text NOT NULL, instance_id text NOT NULL, principal_id text NOT NULL, active boolean NOT NULL,
|
|
15
|
+
action_ids text[] NOT NULL, resource_ids text[] NOT NULL, PRIMARY KEY(tenant_id,instance_id,principal_id),
|
|
16
|
+
FOREIGN KEY(tenant_id,instance_id) REFERENCES platform_private.instances);
|
|
17
|
+
CREATE TABLE platform_private.sessions (
|
|
18
|
+
session_key text PRIMARY KEY, principal_id text NOT NULL, locale text NOT NULL, active boolean NOT NULL, expires_at timestamptz NOT NULL);
|
|
19
|
+
CREATE TABLE platform_private.input_state (
|
|
20
|
+
tenant_id text NOT NULL, instance_id text NOT NULL, snapshot_id text NOT NULL, revision text NOT NULL CHECK(revision ~ '^(0|[1-9][0-9]{0,63})$'), rule_version text NOT NULL,
|
|
21
|
+
PRIMARY KEY(tenant_id,instance_id), FOREIGN KEY(tenant_id,instance_id) REFERENCES platform_private.instances);
|
|
22
|
+
CREATE TABLE platform.records (
|
|
23
|
+
tenant_id text NOT NULL, instance_id text NOT NULL, kind text NOT NULL CHECK(kind IN ('result','evidence','snapshot','object','search','model')),
|
|
24
|
+
id text NOT NULL CHECK(length(id) BETWEEN 1 AND 512), revision text NOT NULL CHECK(revision ~ '^(0|[1-9][0-9]{0,63})$'),
|
|
25
|
+
digest text NOT NULL CHECK(digest ~ '^sha256:[0-9a-f]{64}$'), payload jsonb NOT NULL, provenance jsonb NOT NULL CHECK(jsonb_typeof(provenance)='object'),
|
|
26
|
+
PRIMARY KEY(tenant_id,instance_id,kind,id,revision), FOREIGN KEY(tenant_id,instance_id) REFERENCES platform_private.instances);
|
|
27
|
+
CREATE TABLE platform.outbox (
|
|
28
|
+
tenant_id text NOT NULL, instance_id text NOT NULL, event_id text NOT NULL, event_type text NOT NULL, payload jsonb NOT NULL,
|
|
29
|
+
PRIMARY KEY(tenant_id,instance_id,event_id), FOREIGN KEY(tenant_id,instance_id) REFERENCES platform_private.instances);
|
|
30
|
+
ALTER TABLE platform_private.instances OWNER TO platform_schema_owner;
|
|
31
|
+
ALTER TABLE platform_private.access OWNER TO platform_schema_owner;
|
|
32
|
+
ALTER TABLE platform_private.sessions OWNER TO platform_schema_owner;
|
|
33
|
+
ALTER TABLE platform_private.input_state OWNER TO platform_schema_owner;
|
|
34
|
+
ALTER TABLE platform.records OWNER TO platform_schema_owner;
|
|
35
|
+
ALTER TABLE platform.outbox OWNER TO platform_schema_owner;
|
|
36
|
+
GRANT USAGE ON SCHEMA platform_private TO platform_identity_reader,platform_runtime;
|
|
37
|
+
GRANT USAGE ON SCHEMA platform TO platform_runtime;
|
|
38
|
+
GRANT SELECT, UPDATE ON platform_private.sessions,platform_private.instances,platform_private.access TO platform_identity_reader;
|
|
39
|
+
GRANT SELECT ON platform_private.input_state TO platform_identity_reader;
|
|
40
|
+
-- This small identity oracle owns no exposed records and cannot bypass their RLS.
|
|
41
|
+
CREATE FUNCTION platform_private.resolve_session(key text, instance text) RETURNS jsonb
|
|
42
|
+
LANGUAGE sql SECURITY DEFINER SET search_path=pg_catalog AS $$
|
|
43
|
+
SELECT jsonb_build_object('principalId',s.principal_id,'tenantId',i.tenant_id,'instanceId',i.instance_id,
|
|
44
|
+
'solutionId',i.solution_id,'solutionVersion',i.solution_version,'authorizationRevision',i.authorization_revision,
|
|
45
|
+
'catalogDigest',i.catalog_digest,'locale',s.locale,'enabled',i.enabled,'sessionActive',s.active AND s.expires_at>clock_timestamp(),
|
|
46
|
+
'membershipActive',a.active,'actionIds',a.action_ids,'resourceIds',a.resource_ids)
|
|
47
|
+
FROM platform_private.sessions s JOIN platform_private.access a ON a.principal_id=s.principal_id
|
|
48
|
+
JOIN platform_private.instances i USING(tenant_id,instance_id) WHERE s.session_key=key AND i.instance_id=instance;
|
|
49
|
+
$$;
|
|
50
|
+
ALTER FUNCTION platform_private.resolve_session(text,text) OWNER TO platform_identity_reader;
|
|
51
|
+
CREATE FUNCTION platform_private.permits(tenant text, instance text, action text, resource text) RETURNS boolean
|
|
52
|
+
LANGUAGE sql SECURITY DEFINER SET search_path=pg_catalog AS $$
|
|
53
|
+
SELECT EXISTS(SELECT 1 FROM platform_private.sessions s JOIN platform_private.access a ON a.principal_id=s.principal_id
|
|
54
|
+
JOIN platform_private.instances i USING(tenant_id,instance_id)
|
|
55
|
+
WHERE s.session_key=current_setting('link_light.session_key',true) AND s.active AND s.expires_at>clock_timestamp()
|
|
56
|
+
AND a.active AND i.enabled AND i.tenant_id=tenant AND i.instance_id=instance
|
|
57
|
+
AND i.instance_id=current_setting('link_light.instance_id',true)
|
|
58
|
+
AND i.authorization_revision=current_setting('link_light.authorization_revision',true)
|
|
59
|
+
AND action=ANY(a.action_ids) AND resource=ANY(a.resource_ids));
|
|
60
|
+
$$;
|
|
61
|
+
ALTER FUNCTION platform_private.permits(text,text,text,text) OWNER TO platform_identity_reader;
|
|
62
|
+
CREATE FUNCTION platform_private.lock_authorization() RETURNS void
|
|
63
|
+
LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog AS $$
|
|
64
|
+
BEGIN
|
|
65
|
+
PERFORM 1 FROM platform_private.sessions s JOIN platform_private.access a ON a.principal_id=s.principal_id
|
|
66
|
+
JOIN platform_private.instances i USING(tenant_id,instance_id)
|
|
67
|
+
WHERE s.session_key=current_setting('link_light.session_key',true) AND i.instance_id=current_setting('link_light.instance_id',true)
|
|
68
|
+
AND s.active AND s.expires_at>clock_timestamp() AND a.active AND i.enabled
|
|
69
|
+
AND i.authorization_revision=current_setting('link_light.authorization_revision',true) FOR SHARE OF s,a,i;
|
|
70
|
+
IF NOT FOUND THEN RAISE EXCEPTION 'authorization changed' USING ERRCODE='42501'; END IF;
|
|
71
|
+
END $$;
|
|
72
|
+
ALTER FUNCTION platform_private.lock_authorization() OWNER TO platform_identity_reader;
|
|
73
|
+
-- Use one scalar subquery per statement, then recheck row scope/GUCs/clock below.
|
|
74
|
+
-- Authority rows stay locked through the caller's transaction; no table grants leak.
|
|
75
|
+
CREATE FUNCTION platform_private.locked_authorization_scope(action text, resource text) RETURNS jsonb
|
|
76
|
+
LANGUAGE sql VOLATILE SECURITY DEFINER SET search_path=pg_catalog AS $$
|
|
77
|
+
SELECT jsonb_build_object('sessionKey',s.session_key,'tenantId',i.tenant_id,'instanceId',i.instance_id,
|
|
78
|
+
'authorizationRevision',i.authorization_revision,'expiresAt',s.expires_at)
|
|
79
|
+
FROM platform_private.sessions s JOIN platform_private.access a ON a.principal_id=s.principal_id
|
|
80
|
+
JOIN platform_private.instances i USING(tenant_id,instance_id)
|
|
81
|
+
WHERE s.session_key=current_setting('link_light.session_key',true) AND s.active AND s.expires_at>clock_timestamp()
|
|
82
|
+
AND a.active AND i.enabled AND i.instance_id=current_setting('link_light.instance_id',true)
|
|
83
|
+
AND i.authorization_revision=current_setting('link_light.authorization_revision',true)
|
|
84
|
+
AND action=ANY(a.action_ids) AND resource=ANY(a.resource_ids) FOR SHARE OF s,a,i;
|
|
85
|
+
$$;
|
|
86
|
+
ALTER FUNCTION platform_private.locked_authorization_scope(text,text) OWNER TO platform_identity_reader;
|
|
87
|
+
CREATE FUNCTION platform_private.authorization_scope_current(scope jsonb, tenant text, instance text, revision text) RETURNS boolean
|
|
88
|
+
LANGUAGE plpgsql VOLATILE SECURITY INVOKER SET search_path=pg_catalog AS $$
|
|
89
|
+
BEGIN
|
|
90
|
+
-- Policy scopes come from the oracle; malformed direct timestamps error closed.
|
|
91
|
+
-- Avoid a per-row EXCEPTION subtransaction on this hot authorization path.
|
|
92
|
+
IF scope IS NULL OR jsonb_typeof(scope) IS DISTINCT FROM 'object'
|
|
93
|
+
OR jsonb_typeof(scope->'expiresAt') IS DISTINCT FROM 'string' OR length(scope->>'expiresAt')>128 THEN RETURN false; END IF;
|
|
94
|
+
RETURN coalesce(tenant=scope->>'tenantId' AND instance=scope->>'instanceId' AND revision=scope->>'authorizationRevision'
|
|
95
|
+
AND scope->>'sessionKey'=nullif(current_setting('link_light.session_key',true),'')
|
|
96
|
+
AND scope->>'instanceId'=nullif(current_setting('link_light.instance_id',true),'')
|
|
97
|
+
AND scope->>'authorizationRevision'=nullif(current_setting('link_light.authorization_revision',true),'')
|
|
98
|
+
AND (scope->>'expiresAt')::timestamptz>clock_timestamp(),false);
|
|
99
|
+
END $$;
|
|
100
|
+
ALTER FUNCTION platform_private.authorization_scope_current(jsonb,text,text,text) OWNER TO platform_identity_reader;
|
|
101
|
+
REVOKE ALL ON FUNCTION platform_private.locked_authorization_scope(text,text),platform_private.authorization_scope_current(jsonb,text,text,text) FROM PUBLIC;
|
|
102
|
+
GRANT EXECUTE ON FUNCTION platform_private.locked_authorization_scope(text,text),platform_private.authorization_scope_current(jsonb,text,text,text) TO platform_runtime;
|
|
103
|
+
CREATE FUNCTION platform_private.current_input(tenant text, instance text, snapshot text) RETURNS jsonb
|
|
104
|
+
LANGUAGE sql SECURITY DEFINER SET search_path=pg_catalog AS $$
|
|
105
|
+
SELECT jsonb_build_object('inputSnapshotRef',jsonb_build_object('snapshotId',snapshot_id,'revision',revision),'ruleVersion',rule_version)
|
|
106
|
+
FROM platform_private.input_state WHERE tenant_id=tenant AND instance_id=instance
|
|
107
|
+
AND platform_private.permits(tenant,instance,'snapshot.read','snapshot:'||snapshot);
|
|
108
|
+
$$;
|
|
109
|
+
ALTER FUNCTION platform_private.current_input(text,text,text) OWNER TO platform_identity_reader;
|
|
110
|
+
CREATE FUNCTION platform_private.reference_current(binding jsonb) RETURNS boolean
|
|
111
|
+
LANGUAGE plpgsql SECURITY INVOKER SET search_path=pg_catalog AS $$
|
|
112
|
+
BEGIN
|
|
113
|
+
IF NOT (binding ? 'expiresAt') THEN RETURN true; END IF;
|
|
114
|
+
IF jsonb_typeof(binding->'expiresAt') <> 'string' OR length(binding->>'expiresAt')>128
|
|
115
|
+
OR (binding->>'expiresAt') !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?Z$' THEN RETURN false; END IF;
|
|
116
|
+
RETURN (binding->>'expiresAt')::timestamptz>clock_timestamp();
|
|
117
|
+
EXCEPTION WHEN datetime_field_overflow OR invalid_datetime_format THEN RETURN false;
|
|
118
|
+
END $$;
|
|
119
|
+
ALTER FUNCTION platform_private.reference_current(jsonb) OWNER TO platform_schema_owner;
|
|
120
|
+
REVOKE ALL ON FUNCTION platform_private.reference_current(jsonb) FROM PUBLIC;
|
|
121
|
+
GRANT EXECUTE ON FUNCTION platform_private.reference_current(jsonb) TO platform_runtime;
|
|
122
|
+
REVOKE ALL ON FUNCTION platform_private.resolve_session(text,text), platform_private.permits(text,text,text,text), platform_private.lock_authorization(),platform_private.current_input(text,text,text) FROM PUBLIC;
|
|
123
|
+
GRANT EXECUTE ON FUNCTION platform_private.resolve_session(text,text), platform_private.permits(text,text,text,text), platform_private.lock_authorization(),platform_private.current_input(text,text,text) TO platform_runtime;
|
|
124
|
+
ALTER TABLE platform.records ENABLE ROW LEVEL SECURITY;
|
|
125
|
+
ALTER TABLE platform.records FORCE ROW LEVEL SECURITY;
|
|
126
|
+
ALTER TABLE platform.outbox ENABLE ROW LEVEL SECURITY;
|
|
127
|
+
ALTER TABLE platform.outbox FORCE ROW LEVEL SECURITY;
|
|
128
|
+
CREATE POLICY record_read ON platform.records FOR SELECT TO platform_runtime USING(platform_private.permits(tenant_id,instance_id,kind||'.read',kind||':'||id)
|
|
129
|
+
AND platform_private.reference_current(provenance)
|
|
130
|
+
AND provenance->>'authorizationRevision'=current_setting('link_light.authorization_revision',true)
|
|
131
|
+
AND provenance->>'catalogDigest'=(platform_private.resolve_session(current_setting('link_light.session_key',true),instance_id)->>'catalogDigest')
|
|
132
|
+
AND (kind<>'result' OR (provenance->'inputSnapshotRef'=(platform_private.current_input(tenant_id,instance_id,provenance->'inputSnapshotRef'->>'snapshotId')->'inputSnapshotRef')
|
|
133
|
+
AND provenance->>'ruleVersion'=(platform_private.current_input(tenant_id,instance_id,provenance->'inputSnapshotRef'->>'snapshotId')->>'ruleVersion'))));
|
|
134
|
+
CREATE POLICY record_write ON platform.records FOR INSERT TO platform_runtime WITH CHECK(kind='result' AND platform_private.permits(tenant_id,instance_id,'result.write','result:'||id)
|
|
135
|
+
AND provenance->>'authorizationRevision'=current_setting('link_light.authorization_revision',true)
|
|
136
|
+
AND provenance->>'catalogDigest'=(platform_private.resolve_session(current_setting('link_light.session_key',true),instance_id)->>'catalogDigest'));
|
|
137
|
+
CREATE POLICY outbox_write ON platform.outbox FOR INSERT TO platform_runtime WITH CHECK(platform_private.permits(tenant_id,instance_id,'result.write','result:'||(payload->>'resultId')));
|
|
138
|
+
GRANT SELECT,INSERT ON platform.records TO platform_runtime;
|
|
139
|
+
GRANT INSERT ON platform.outbox TO platform_runtime;
|
|
140
|
+
CREATE VIEW platform.result_view WITH(security_invoker=true) AS SELECT tenant_id,instance_id,id,revision,payload FROM platform.records WHERE kind='result';
|
|
141
|
+
ALTER VIEW platform.result_view OWNER TO platform_schema_owner;
|
|
142
|
+
CREATE FUNCTION platform.read_result(result_id text, result_revision text) RETURNS TABLE(payload jsonb)
|
|
143
|
+
LANGUAGE sql SECURITY INVOKER SET search_path=pg_catalog AS $$ SELECT r.payload FROM platform.records r WHERE r.kind='result' AND r.id=result_id AND r.revision=result_revision $$;
|
|
144
|
+
ALTER FUNCTION platform.read_result(text,text) OWNER TO platform_schema_owner;
|
|
145
|
+
REVOKE ALL ON FUNCTION platform.read_result(text,text) FROM PUBLIC;
|
|
146
|
+
GRANT SELECT ON platform.result_view TO platform_runtime;
|
|
147
|
+
GRANT EXECUTE ON FUNCTION platform.read_result(text,text) TO platform_runtime;
|
|
148
|
+
-- PostgREST verifies the JWT and switches to platform_runtime before this hook.
|
|
149
|
+
-- The JWT identifies a server session; scope/revision claims confer no authority.
|
|
150
|
+
CREATE FUNCTION platform_private.bind_data_api_request() RETURNS void
|
|
151
|
+
LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog AS $$
|
|
152
|
+
DECLARE
|
|
153
|
+
claims jsonb := nullif(current_setting('request.jwt.claims',true),'')::jsonb;
|
|
154
|
+
headers jsonb := nullif(current_setting('request.headers',true),'')::jsonb;
|
|
155
|
+
session_key text := claims->>'sid';
|
|
156
|
+
instance text := headers->>'x-link-light-instance';
|
|
157
|
+
context jsonb;
|
|
158
|
+
method text := current_setting('request.method',true);
|
|
159
|
+
request_path text := current_setting('request.path',true);
|
|
160
|
+
BEGIN
|
|
161
|
+
PERFORM set_config('link_light.session_key','',true),set_config('link_light.instance_id','',true),set_config('link_light.authorization_revision','',true);
|
|
162
|
+
IF current_setting('role',true) <> 'platform_runtime'
|
|
163
|
+
OR jsonb_typeof(claims->'sid') IS DISTINCT FROM 'string'
|
|
164
|
+
OR jsonb_typeof(claims->'sub') IS DISTINCT FROM 'string'
|
|
165
|
+
OR session_key IS NULL OR length(session_key) NOT BETWEEN 1 AND 512
|
|
166
|
+
OR instance IS NULL OR length(instance) NOT BETWEEN 1 AND 512 THEN
|
|
167
|
+
RAISE EXCEPTION 'Data API authorization denied' USING ERRCODE='42501'; END IF;
|
|
168
|
+
-- REST writes cannot bypass the host's domain/result/outbox transaction.
|
|
169
|
+
IF method NOT IN ('GET','HEAD') AND NOT (method='POST' AND request_path='/rpc/read_result') THEN
|
|
170
|
+
RAISE EXCEPTION 'Data API writes are not available' USING ERRCODE='42501'; END IF;
|
|
171
|
+
context := platform_private.resolve_session(session_key,instance);
|
|
172
|
+
IF context IS NULL OR (context->>'principalId') IS DISTINCT FROM (claims->>'sub')
|
|
173
|
+
OR context->>'sessionActive' IS DISTINCT FROM 'true'
|
|
174
|
+
OR context->>'membershipActive' IS DISTINCT FROM 'true'
|
|
175
|
+
OR context->>'enabled' IS DISTINCT FROM 'true' THEN
|
|
176
|
+
RAISE EXCEPTION 'Data API authorization denied' USING ERRCODE='42501'; END IF;
|
|
177
|
+
PERFORM set_config('link_light.session_key',session_key,true),set_config('link_light.instance_id',context->>'instanceId',true),set_config('link_light.authorization_revision',context->>'authorizationRevision',true);
|
|
178
|
+
END $$;
|
|
179
|
+
ALTER FUNCTION platform_private.bind_data_api_request() OWNER TO platform_identity_reader;
|
|
180
|
+
REVOKE ALL ON FUNCTION platform_private.bind_data_api_request() FROM PUBLIC;
|
|
181
|
+
GRANT EXECUTE ON FUNCTION platform_private.bind_data_api_request() TO platform_runtime;
|
|
182
|
+
-- Execution is private to the host; never part of the exposed Data API schema.
|
|
183
|
+
CREATE TABLE platform_private.execution_runs (
|
|
184
|
+
tenant_id text NOT NULL, instance_id text NOT NULL, principal_id text NOT NULL,
|
|
185
|
+
operation_id text NOT NULL, idempotency_key text NOT NULL, run_id text NOT NULL UNIQUE,
|
|
186
|
+
payload jsonb NOT NULL CHECK(jsonb_typeof(payload)='object'),
|
|
187
|
+
PRIMARY KEY(tenant_id,instance_id,principal_id,operation_id,idempotency_key),
|
|
188
|
+
FOREIGN KEY(tenant_id,instance_id) REFERENCES platform_private.instances);
|
|
189
|
+
CREATE TABLE platform_private.execution_budgets (
|
|
190
|
+
tenant_id text NOT NULL, instance_id text NOT NULL, principal_id text NOT NULL,
|
|
191
|
+
currency text NOT NULL, budget_limit numeric(58,18) NOT NULL, reservation numeric(58,18) NOT NULL,
|
|
192
|
+
reserved numeric(58,18) NOT NULL DEFAULT 0, spent numeric(58,18) NOT NULL DEFAULT 0,
|
|
193
|
+
CHECK(budget_limit>=0 AND reservation>=0 AND reserved>=0 AND spent>=0 AND reserved+spent<=budget_limit),
|
|
194
|
+
PRIMARY KEY(tenant_id,instance_id,principal_id),
|
|
195
|
+
FOREIGN KEY(tenant_id,instance_id) REFERENCES platform_private.instances);
|
|
196
|
+
CREATE TABLE platform_private.execution_events (
|
|
197
|
+
cursor bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
198
|
+
tenant_id text NOT NULL, instance_id text NOT NULL, operation_id text NOT NULL,
|
|
199
|
+
run_id text NOT NULL, revision text NOT NULL, payload jsonb NOT NULL,
|
|
200
|
+
FOREIGN KEY(run_id) REFERENCES platform_private.execution_runs(run_id));
|
|
201
|
+
CREATE TABLE platform_private.execution_delivery (
|
|
202
|
+
event_id text PRIMARY KEY, tenant_id text NOT NULL, instance_id text NOT NULL, operation_id text NOT NULL,
|
|
203
|
+
run_id text NOT NULL, delivered boolean NOT NULL DEFAULT false, next_after timestamptz NOT NULL DEFAULT '-infinity',
|
|
204
|
+
FOREIGN KEY(run_id) REFERENCES platform_private.execution_runs(run_id));
|
|
205
|
+
CREATE TABLE platform_private.execution_results (
|
|
206
|
+
run_id text PRIMARY KEY, tenant_id text NOT NULL, instance_id text NOT NULL, operation_id text NOT NULL,
|
|
207
|
+
revision text NOT NULL, payload jsonb NOT NULL,
|
|
208
|
+
FOREIGN KEY(run_id) REFERENCES platform_private.execution_runs(run_id));
|
|
209
|
+
ALTER TABLE platform_private.execution_runs OWNER TO platform_schema_owner;
|
|
210
|
+
ALTER TABLE platform_private.execution_budgets OWNER TO platform_schema_owner;
|
|
211
|
+
ALTER TABLE platform_private.execution_events OWNER TO platform_schema_owner;
|
|
212
|
+
ALTER TABLE platform_private.execution_delivery OWNER TO platform_schema_owner;
|
|
213
|
+
ALTER TABLE platform_private.execution_results OWNER TO platform_schema_owner;
|
|
214
|
+
ALTER SEQUENCE platform_private.execution_events_cursor_seq OWNER TO platform_schema_owner;
|
|
215
|
+
ALTER TABLE platform_private.execution_runs ENABLE ROW LEVEL SECURITY;
|
|
216
|
+
ALTER TABLE platform_private.execution_runs FORCE ROW LEVEL SECURITY;
|
|
217
|
+
ALTER TABLE platform_private.execution_budgets ENABLE ROW LEVEL SECURITY;
|
|
218
|
+
ALTER TABLE platform_private.execution_budgets FORCE ROW LEVEL SECURITY;
|
|
219
|
+
ALTER TABLE platform_private.execution_events ENABLE ROW LEVEL SECURITY;
|
|
220
|
+
ALTER TABLE platform_private.execution_events FORCE ROW LEVEL SECURITY;
|
|
221
|
+
ALTER TABLE platform_private.execution_delivery ENABLE ROW LEVEL SECURITY;
|
|
222
|
+
ALTER TABLE platform_private.execution_delivery FORCE ROW LEVEL SECURITY;
|
|
223
|
+
ALTER TABLE platform_private.execution_results ENABLE ROW LEVEL SECURITY;
|
|
224
|
+
CREATE POLICY execution_run_scope ON platform_private.execution_runs TO platform_runtime
|
|
225
|
+
USING(platform_private.permits(tenant_id,instance_id,operation_id,operation_id)
|
|
226
|
+
AND principal_id=(platform_private.resolve_session(current_setting('link_light.session_key',true),instance_id)->>'principalId'))
|
|
227
|
+
WITH CHECK(platform_private.permits(tenant_id,instance_id,operation_id,operation_id)
|
|
228
|
+
AND principal_id=(platform_private.resolve_session(current_setting('link_light.session_key',true),instance_id)->>'principalId'));
|
|
229
|
+
CREATE POLICY execution_budget_scope ON platform_private.execution_budgets TO platform_runtime
|
|
230
|
+
USING(platform_private.permits(tenant_id,instance_id,'execution.budget','capability:execution.budget')
|
|
231
|
+
AND principal_id=(platform_private.resolve_session(current_setting('link_light.session_key',true),instance_id)->>'principalId')
|
|
232
|
+
AND instance_id=current_setting('link_light.instance_id',true));
|
|
233
|
+
CREATE POLICY execution_event_scope ON platform_private.execution_events TO platform_runtime USING(platform_private.permits(tenant_id,instance_id,operation_id,operation_id) AND EXISTS(SELECT 1 FROM platform_private.execution_runs r WHERE r.run_id=execution_events.run_id));
|
|
234
|
+
CREATE POLICY execution_delivery_scope ON platform_private.execution_delivery TO platform_runtime USING(platform_private.permits(tenant_id,instance_id,operation_id,operation_id));
|
|
235
|
+
CREATE POLICY execution_result_scope ON platform_private.execution_results TO platform_runtime USING(platform_private.permits(tenant_id,instance_id,operation_id,operation_id) AND EXISTS(SELECT 1 FROM platform_private.execution_runs r WHERE r.run_id=execution_results.run_id));
|
|
236
|
+
ALTER TABLE platform_private.execution_results FORCE ROW LEVEL SECURITY;
|
|
237
|
+
GRANT SELECT,INSERT,UPDATE ON platform_private.execution_runs,platform_private.execution_delivery TO platform_runtime;
|
|
238
|
+
GRANT SELECT,UPDATE(reserved,spent) ON platform_private.execution_budgets TO platform_runtime;
|
|
239
|
+
GRANT SELECT,INSERT ON platform_private.execution_events,platform_private.execution_results TO platform_runtime;
|
|
240
|
+
GRANT USAGE ON SEQUENCE platform_private.execution_events_cursor_seq TO platform_runtime;
|
|
241
|
+
CREATE ROLE platform_worker NOLOGIN NOSUPERUSER NOBYPASSRLS;
|
|
242
|
+
CREATE ROLE platform_execution_reader NOLOGIN NOSUPERUSER NOBYPASSRLS;
|
|
243
|
+
GRANT USAGE ON SCHEMA platform_private TO platform_execution_reader,platform_worker;
|
|
244
|
+
GRANT EXECUTE ON FUNCTION platform_private.resolve_session(text,text) TO platform_execution_reader;
|
|
245
|
+
GRANT SELECT ON platform_private.execution_runs,platform_private.execution_delivery TO platform_execution_reader;
|
|
246
|
+
CREATE POLICY execution_worker_lookup ON platform_private.execution_runs FOR SELECT TO platform_execution_reader USING(true);
|
|
247
|
+
CREATE POLICY execution_worker_delivery ON platform_private.execution_delivery FOR SELECT TO platform_execution_reader USING(true);
|
|
248
|
+
CREATE FUNCTION platform_private.worker_run(run text, instance text) RETURNS jsonb
|
|
249
|
+
LANGUAGE sql SECURITY DEFINER SET search_path=pg_catalog AS $$
|
|
250
|
+
SELECT payload FROM platform_private.execution_runs WHERE run_id=run AND instance_id=instance
|
|
251
|
+
$$;
|
|
252
|
+
ALTER FUNCTION platform_private.worker_run(text,text) OWNER TO platform_execution_reader;
|
|
253
|
+
REVOKE ALL ON FUNCTION platform_private.worker_run(text,text) FROM PUBLIC;
|
|
254
|
+
GRANT EXECUTE ON FUNCTION platform_private.worker_run(text,text) TO platform_worker;
|
|
255
|
+
CREATE FUNCTION platform_private.worker_delivery() RETURNS TABLE(event_id text,run_id text,instance_id text)
|
|
256
|
+
LANGUAGE sql SECURITY DEFINER SET search_path=pg_catalog AS $$
|
|
257
|
+
SELECT d.event_id,d.run_id,d.instance_id FROM platform_private.execution_delivery d JOIN platform_private.execution_runs r USING(run_id)
|
|
258
|
+
CROSS JOIN LATERAL platform_private.resolve_session(r.payload->>'sessionKey',r.instance_id) a(context)
|
|
259
|
+
WHERE d.next_after<=clock_timestamp() AND (NOT d.delivered OR r.payload->'view'->>'status'='queued'
|
|
260
|
+
OR (r.payload->'view'->>'status'='running' AND (r.payload->'attempt'->>'leaseExpiresAt')::timestamptz<=clock_timestamp()))
|
|
261
|
+
AND r.payload->'view'->>'status' IN ('queued','running')
|
|
262
|
+
AND a.context->>'enabled'='true' AND a.context->>'sessionActive'='true' AND a.context->>'membershipActive'='true'
|
|
263
|
+
AND a.context->>'authorizationRevision'=r.payload->>'authorizationRevision'
|
|
264
|
+
AND a.context->>'catalogDigest'=r.payload->'view'->>'catalogDigest'
|
|
265
|
+
AND a.context->>'principalId'=r.principal_id
|
|
266
|
+
AND (a.context->'actionIds') ? r.operation_id AND (a.context->'resourceIds') ? r.operation_id
|
|
267
|
+
AND (a.context->'actionIds') ? 'execution.budget' AND (a.context->'resourceIds') ? 'capability:execution.budget'
|
|
268
|
+
ORDER BY d.event_id LIMIT 100
|
|
269
|
+
$$;
|
|
270
|
+
ALTER FUNCTION platform_private.worker_delivery() OWNER TO platform_execution_reader;
|
|
271
|
+
REVOKE ALL ON FUNCTION platform_private.worker_delivery() FROM PUBLIC;
|
|
272
|
+
GRANT EXECUTE ON FUNCTION platform_private.worker_delivery() TO platform_worker;
|
|
273
|
+
COMMIT;
|