@di-framework/cli-plugin-platform 6.1.1 → 6.2.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.
Files changed (43) hide show
  1. package/README.md +259 -2
  2. package/dist/assets/http-adapter.js +6 -6
  3. package/dist/assets/sqlite/BUILD-INFO.txt +1 -1
  4. package/dist/assets/wit/deps/di-framework-pglite/package.wit +175 -0
  5. package/dist/bindings.js +7 -6
  6. package/dist/build.d.ts +31 -0
  7. package/dist/build.js +192 -12
  8. package/dist/console/catalog.js +2 -1
  9. package/dist/console/cluster.d.ts +3 -0
  10. package/dist/console/cluster.js +57 -4
  11. package/dist/control/auth.js +14 -2
  12. package/dist/deploy.d.ts +6 -0
  13. package/dist/deploy.js +27 -5
  14. package/dist/deps.js +1 -1
  15. package/dist/environment-names.d.ts +6 -0
  16. package/dist/environment-names.js +10 -0
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/node-compat/console.js +16 -1
  20. package/dist/node-compat/crypto-subtle.d.ts +6 -0
  21. package/dist/node-compat/crypto-subtle.js +41 -4
  22. package/dist/node-compat/crypto.d.ts +3 -2
  23. package/dist/node-compat/crypto.js +66 -17
  24. package/dist/node-compat/fs.d.ts +24 -2
  25. package/dist/node-compat/fs.js +137 -15
  26. package/dist/node-compat/node-errors.d.ts +20 -0
  27. package/dist/node-compat/node-errors.js +73 -0
  28. package/dist/node-compat/storage.d.ts +3 -3
  29. package/dist/node-compat/wasi-random.d.ts +21 -1
  30. package/dist/node-compat/wasi-random.js +45 -12
  31. package/dist/pglite-encryption.d.ts +79 -0
  32. package/dist/pglite-encryption.js +196 -0
  33. package/dist/pglite.d.ts +153 -0
  34. package/dist/pglite.js +423 -0
  35. package/dist/project.d.ts +18 -0
  36. package/dist/project.js +49 -1
  37. package/dist/secret-admission.d.ts +21 -0
  38. package/dist/secret-admission.js +29 -0
  39. package/dist/wit.d.ts +3 -0
  40. package/dist/wit.js +12 -0
  41. package/dist/workload.d.ts +51 -0
  42. package/dist/workload.js +320 -40
  43. package/package.json +2 -2
package/dist/build.js CHANGED
@@ -10,6 +10,8 @@ import { discoverScheduledJobs, renderCronAdapterModule, renderCronInvokerModule
10
10
  import { DEFAULT_DEPS } from './deps.js';
11
11
  import { renderGuestsModule } from './guests.js';
12
12
  import { OCI_ARTIFACT_PLATFORM } from './oci.js';
13
+ import { DI_PGLITE_PACKAGE, DI_PGLITE_VERSION, PGLITE_ENCFS_WASM_FILE, PGLITE_ENCRYPTED_WASM_FILE, PGLITE_KEY_ENV, PGLITE_WASM_FILE, resolvePgliteComponent, resolvePgliteEncryption, } from './pglite.js';
14
+ import { ENCFS_SECTION, encfsSection, encryptionComposition, LAYER_PACKAGE, PROVIDER_PACKAGE, planWiring, worldInterfaces, } from './pglite-encryption.js';
13
15
  import { loadProject } from './project.js';
14
16
  import { discoverQueueHandlers, isQueueWorkerProject } from './queues.js';
15
17
  import { renderQueuesModule } from './queues-module.js';
@@ -20,6 +22,13 @@ export { COMPONENT_MODEL, WASI_HTTP_INTERFACE, WASI_HTTP_VERSION };
20
22
  export const BUILD_PROFILE_NAME = 'wasmcloud-http';
21
23
  export const CRON_BUILD_PROFILE_NAME = 'wasmcloud-cron';
22
24
  export { BUILD_PROFILE_NAME as BUILD_PROFILE };
25
+ function originOf(component) {
26
+ return {
27
+ source: component.source,
28
+ ...(component.image === undefined ? {} : { image: component.image }),
29
+ ...(component.path === undefined ? {} : { path: component.path }),
30
+ };
31
+ }
23
32
  export function requirementsForProject(project, deps = DEFAULT_DEPS) {
24
33
  const bindings = discoverBindings(project, deps);
25
34
  const queueHandlers = discoverQueueHandlers(project);
@@ -129,12 +138,8 @@ async function composeComponentProvider(project, deps, io, provider, namedImport
129
138
  failureCode: 'WASMCLOUD_COMPONENT_COMPOSE_FAILED',
130
139
  });
131
140
  }
132
- /**
133
- * Plugs one provider component into the built guest: `wac plug`, or the
134
- * componentize-qjs composer when the guest has named imports to preserve.
135
- */
136
- async function composeProvider(project, deps, io, options) {
137
- const composed = `${project.outputPath}.composed`;
141
+ /** `wac` on PATH, else the SQLite toolchain's, and the PATH to run it with. */
142
+ function wacTool(deps) {
138
143
  const toolsBin = sqliteToolsBin();
139
144
  const envPath = [toolsBin, process.env.PATH ?? ''].filter(Boolean).join(':');
140
145
  const wac = deps.capture('wac', ['--version']) !== undefined
@@ -142,20 +147,50 @@ async function composeProvider(project, deps, io, options) {
142
147
  : toolsBin
143
148
  ? join(toolsBin, 'wac')
144
149
  : 'wac';
150
+ return { wac, envPath };
151
+ }
152
+ /** Whether `error` is a spawn failure because the executable does not exist. */
153
+ function isMissingExecutable(error) {
154
+ const code = error?.code;
155
+ return (code === 'ENOENT' ||
156
+ (error instanceof Error && /ENOENT|Executable not found/i.test(error.message)));
157
+ }
158
+ /** Runs `wac` (or `command`), mapping a missing `wac` binary to `WASMCLOUD_WAC_REQUIRED`. */
159
+ async function runWac(project, deps, args, command) {
160
+ const { wac, envPath } = wacTool(deps);
161
+ try {
162
+ return await deps.runCaptured(command ?? wac, args, {
163
+ cwd: project.projectRoot,
164
+ env: { ...process.env, PATH: envPath },
165
+ });
166
+ }
167
+ catch (error) {
168
+ // A missing componentize-qjs compiler surfaces as it is; only wac has an install hint here.
169
+ if (command !== undefined || !isMissingExecutable(error))
170
+ throw error;
171
+ throw new CommandFailure('WASMCLOUD_WAC_REQUIRED', 'wac is required to compose components; install it (https://github.com/bytecodealliance/wac/releases, or `scripts/install-tools.sh --wac-only` in di-framework/platform `platform/sqlite-component`) and put it on PATH', 3, { application: project.applicationName, tool: 'wac' });
172
+ }
173
+ }
174
+ /**
175
+ * Plugs one provider component into the built guest: `wac plug`, or the
176
+ * componentize-qjs composer when the guest has named imports to preserve.
177
+ */
178
+ async function composeProvider(project, deps, io, options) {
179
+ const composed = `${project.outputPath}.composed`;
145
180
  io.stdout.write(`Composing ${options.label} provider...\n`);
146
181
  const compiler = options.namedImports ? deps.componentizeQjsPath() : undefined;
147
182
  if (options.namedImports && !compiler)
148
- throw new CommandFailure('WASMCLOUD_COMPILER_REQUIRED', 'Managed PostgreSQL requires componentize-qjs 0.4.4-di.3 or newer', 3);
149
- const result = await deps.runCaptured(compiler ?? wac, compiler
183
+ throw new CommandFailure('WASMCLOUD_COMPILER_REQUIRED', 'Managed PostgreSQL needs componentize-qjs 0.4.4-di.3 or newer for named-import composition', 3);
184
+ const result = await runWac(project, deps, compiler
150
185
  ? ['compose', project.outputPath, '--definition', options.wasm, '-o', composed]
151
- : ['plug', '--plug', options.wasm, project.outputPath, '-o', composed], { cwd: project.projectRoot, env: { ...process.env, PATH: envPath } });
186
+ : ['plug', '--plug', options.wasm, project.outputPath, '-o', composed], compiler);
152
187
  if (result.exitCode !== 0) {
153
188
  throw new CommandFailure(options.failureCode, `Composition of ${options.label} failed: ${result.stderr || result.stdout}`, 3, { application: project.applicationName, exitCode: result.exitCode });
154
189
  }
155
190
  writeFileSync(project.outputPath, readFileSync(composed));
156
191
  rmSync(composed, { force: true });
157
192
  }
158
- async function inspectComponentImports(project, requirements, deps) {
193
+ async function inspectComponentImports(project, requirements, deps, composedAway = []) {
159
194
  if (!isWasmMagic(project.outputPath))
160
195
  return;
161
196
  const captured = await deps.runCaptured(requireNodeBinary(deps.nodeBinaryPath()), [deps.jcoCliPath(), 'wit', project.outputPath], { cwd: project.projectRoot });
@@ -163,6 +198,11 @@ async function inspectComponentImports(project, requirements, deps) {
163
198
  throw new CommandFailure('WASMCLOUD_COMPONENT_IMPORTS_UNREADABLE', `Could not inspect component imports for ${project.applicationName}`, 3, { application: project.applicationName });
164
199
  }
165
200
  const wit = `${captured.stdout}\n${captured.stderr}`;
201
+ for (const provider of composedAway) {
202
+ if (wit.includes(`${provider.package}/`)) {
203
+ throw new CommandFailure(provider.failureCode, `Composed component still imports ${provider.package}; the provider was not plugged in`, 3, { application: project.applicationName, package: provider.package });
204
+ }
205
+ }
166
206
  for (const requirement of requirements) {
167
207
  if (requirement.direction !== 'import')
168
208
  continue;
@@ -174,8 +214,108 @@ async function inspectComponentImports(project, requirements, deps) {
174
214
  }
175
215
  }
176
216
  }
217
+ /** The world of a component, as `jco wit` prints it. */
218
+ async function componentWorld(project, deps, path, label) {
219
+ const captured = await deps.runCaptured(requireNodeBinary(deps.nodeBinaryPath()), [deps.jcoCliPath(), 'wit', path], { cwd: project.projectRoot });
220
+ if (captured.exitCode !== 0 && /Cannot find module/.test(captured.stderr)) {
221
+ throw new CommandFailure('WASMCLOUD_JCO_REQUIRED', `jco is required to read the WIT world of the ${label}, but ${deps.jcoCliPath()} could not be loaded; reinstall @di-framework/cli-plugin-platform (it depends on @bytecodealliance/jco)`, 3, { application: project.applicationName, tool: 'jco' });
222
+ }
223
+ if (captured.exitCode !== 0) {
224
+ throw new CommandFailure('WASMCLOUD_COMPONENT_IMPORTS_UNREADABLE', `Could not read the WIT world of the ${label}: ${(captured.stderr || captured.stdout).trim()}`, 3, { application: project.applicationName, path });
225
+ }
226
+ return worldInterfaces(captured.stdout);
227
+ }
228
+ function notInterposed(project, problem) {
229
+ return new CommandFailure('WASMCLOUD_PGLITE_ENCRYPTION_NOT_INTERPOSED', `The PGlite encryption layer would not sit between the provider and the host filesystem: ` +
230
+ `${problem}. PGlite would write its data directory in plaintext, so the build stops. ` +
231
+ 'Use a layer built for the WASI versions the pinned provider imports.', 3, { application: project.applicationName });
232
+ }
233
+ /**
234
+ * Composes the encryption layer into the provider and writes the result to `output`, which the
235
+ * build then plugs into the guest instead of the provider.
236
+ *
237
+ * `wac plug` silently skips a layer export whose name matches but whose type is not a subtype of
238
+ * the provider's import, and exits 0 when anything else plugged, so it cannot prove the layer is
239
+ * in the path. Instead the build reads both worlds with `jco wit`, plans which layer export each
240
+ * provider import takes (every `wasi:filesystem/*` import must have one), and composes a WAC
241
+ * document that passes each of them as a named instantiation argument (`wac compose`). wac
242
+ * type-checks every argument, so a layer that does not fit fails the build here rather than
243
+ * being bypassed. The document is kept at `.di-framework/pglite-encryption.wac`.
244
+ *
245
+ * Wiring cannot show that the layer encrypts: a pass-through layer wires the same way. So the
246
+ * layer must also carry the platform's `di-framework:pglite-encfs` custom section. That marker
247
+ * catches the wrong artifact (a no-op or debug layer, a stale local build); it is forgeable, so
248
+ * what the layer actually does rests on the digest pin.
249
+ */
250
+ export async function encryptProvider(project, deps, io, provider, layer, output) {
251
+ if (encfsSection(readFileSync(layer)) === undefined) {
252
+ throw new CommandFailure('WASMCLOUD_PGLITE_ENCRYPTION_LAYER_UNMARKED', `The PGlite encryption layer ${layer} has no ${ENCFS_SECTION} custom section, so it is not ` +
253
+ "the platform's pglite-encfs component; pin the published ghcr.io/di-framework/pglite-encfs image", 3, { application: project.applicationName, path: layer });
254
+ }
255
+ const providerWorld = await componentWorld(project, deps, provider, 'PGlite provider');
256
+ const layerWorld = await componentWorld(project, deps, layer, 'PGlite encryption layer');
257
+ const plan = planWiring(providerWorld, layerWorld);
258
+ if (plan.problem !== undefined)
259
+ throw notInterposed(project, plan.problem);
260
+ const document = join(dirname(output), 'pglite-encryption.wac');
261
+ writeFileSync(document, encryptionComposition(plan.wires, providerWorld.exports));
262
+ rmSync(output, { force: true });
263
+ io.stdout.write('Composing the PGlite encryption layer into the provider...\n');
264
+ const result = await runWac(project, deps, [
265
+ 'compose',
266
+ document,
267
+ '--dep',
268
+ `${LAYER_PACKAGE}=${layer}`,
269
+ '--dep',
270
+ `${PROVIDER_PACKAGE}=${provider}`,
271
+ '-o',
272
+ output,
273
+ ]);
274
+ if (result.exitCode !== 0 || !existsSync(output)) {
275
+ const reason = (result.stderr || result.stdout).trim() || 'wac wrote no component';
276
+ throw notInterposed(project, `wac compose refused the wiring: ${reason}`);
277
+ }
278
+ }
279
+ /**
280
+ * The encryption layer reads its key from `DI_PGLITE_KEY`, which reaches the guest only through
281
+ * the control Secret, and deploy keeps only the keys the project declares there.
282
+ */
283
+ function assertPgliteKeyDeclared(project) {
284
+ if (project.pglite?.encryption === undefined)
285
+ return;
286
+ if (project.controlSecretKeys?.includes(PGLITE_KEY_ENV))
287
+ return;
288
+ throw new CommandFailure('WASMCLOUD_PGLITE_KEY_UNDECLARED', `${project.applicationName} turns on "pglite.encryption", whose layer reads its key from ` +
289
+ `${PGLITE_KEY_ENV} in the workload's control Secret; add "${PGLITE_KEY_ENV}" to ` +
290
+ `"controlSecretKeys" in di-framework.config.json`, 2, { application: project.applicationName });
291
+ }
292
+ /**
293
+ * The PGlite provider for a guest that imports `di-framework:pglite/database`. The config
294
+ * and the import must agree: the deploy marks the component exclusive and gives it storage
295
+ * from the config alone, so a config without the import (or the reverse) is refused.
296
+ */
297
+ async function resolvePglite(project, imported, io, deps, deploy) {
298
+ if (imported && project.pglite === undefined) {
299
+ throw new CommandFailure('WASMCLOUD_PGLITE_NOT_CONFIGURED', `${project.applicationName} imports ${DI_PGLITE_PACKAGE}/database@${DI_PGLITE_VERSION}; pin the provider in di-framework.config.json: "pglite": { "image": "ghcr.io/di-framework/pglite-component@sha256:<digest>" }`, 2, { application: project.applicationName });
300
+ }
301
+ if (project.pglite === undefined)
302
+ return undefined;
303
+ if (!imported) {
304
+ throw new CommandFailure('WASMCLOUD_PGLITE_UNUSED', `di-framework.config.json configures "pglite", but ${project.applicationName} does not import ${DI_PGLITE_PACKAGE}/database@${DI_PGLITE_VERSION}; remove "pglite" or import it`, 2, { application: project.applicationName });
305
+ }
306
+ return resolvePgliteComponent(project.pglite, io, deps, project.projectRoot, { deploy });
307
+ }
308
+ /** The encryption layer for the provider, when `pglite.encryption` is set. */
309
+ async function resolveEncryption(project, io, deps, deploy) {
310
+ const encryption = project.pglite?.encryption;
311
+ if (encryption === undefined)
312
+ return undefined;
313
+ return resolvePgliteEncryption(encryption, io, deps, project.projectRoot, { deploy });
314
+ }
177
315
  /** The disposable `.di-framework/` build directory: WIT world, bundle, and manifests. */
178
316
  export async function buildComponent(project, io, deps, options = {}) {
317
+ // A config check: before bundling and before anything is pulled.
318
+ assertPgliteKeyDeclared(project);
179
319
  const generatedDirectory = join(project.projectRoot, '.di-framework');
180
320
  const generatedWit = join(generatedDirectory, 'wit');
181
321
  const bundledJavaScript = join(generatedDirectory, 'component.js');
@@ -281,6 +421,19 @@ export async function buildComponent(project, io, deps, options = {}) {
281
421
  lock = buildWitLock(finalRequirements, join(generatedWit, 'deps'));
282
422
  writeFileSync(join(generatedDirectory, 'wit.lock.json'), `${JSON.stringify(lock, null, 2)}\n`);
283
423
  }
424
+ const needsPglite = finalRequirements.some((requirement) => requirement.package === DI_PGLITE_PACKAGE && requirement.direction === 'import');
425
+ const pglite = await resolvePglite(project, needsPglite, io, deps, options.deploy === true);
426
+ const encryption = pglite === undefined
427
+ ? undefined
428
+ : await resolveEncryption(project, io, deps, options.deploy === true);
429
+ // Plug private copies of the verified bytes: the shared cache may change after verification.
430
+ const pgliteWasm = join(generatedDirectory, PGLITE_WASM_FILE);
431
+ const encfsWasm = join(generatedDirectory, PGLITE_ENCFS_WASM_FILE);
432
+ const encryptedWasm = join(generatedDirectory, PGLITE_ENCRYPTED_WASM_FILE);
433
+ if (pglite !== undefined)
434
+ writeFileSync(pgliteWasm, pglite.bytes);
435
+ if (encryption !== undefined)
436
+ writeFileSync(encfsWasm, encryption.bytes);
284
437
  const componentize = await runComponentize(project, generatedWit, bundledJavaScript, deps);
285
438
  if (componentize.exitCode !== 0) {
286
439
  throw toolFailed(componentize.tool, componentize.exitCode);
@@ -294,13 +447,32 @@ export async function buildComponent(project, io, deps, options = {}) {
294
447
  for (const provider of composedProviders) {
295
448
  await composeComponentProvider(project, deps, io, provider, namedImports);
296
449
  }
450
+ if (pglite !== undefined) {
451
+ if (encryption !== undefined)
452
+ await encryptProvider(project, deps, io, pgliteWasm, encfsWasm, encryptedWasm);
453
+ await composeProvider(project, deps, io, {
454
+ label: `${DI_PGLITE_PACKAGE}@${DI_PGLITE_VERSION}`,
455
+ wasm: encryption === undefined ? pgliteWasm : encryptedWasm,
456
+ namedImports,
457
+ failureCode: 'WASMCLOUD_PGLITE_COMPOSE_FAILED',
458
+ });
459
+ }
297
460
  const composedPackages = new Set(composedProviders.map((provider) => provider.package));
461
+ if (pglite !== undefined)
462
+ composedPackages.add(DI_PGLITE_PACKAGE);
298
463
  await inspectComponentImports(project, finalRequirements.filter((requirement) => !(requirement.direction === 'import' &&
299
464
  (requirement.package === 'di-framework:sqlite' ||
300
- composedPackages.has(requirement.package)))), deps);
465
+ composedPackages.has(requirement.package)))), deps, pglite === undefined
466
+ ? []
467
+ : [{ package: DI_PGLITE_PACKAGE, failureCode: 'WASMCLOUD_PGLITE_COMPOSE_FAILED' }]);
301
468
  const deploymentDigest = canonicalBuildDigest(bundledJavaScript, generatedWit, join(generatedDirectory, 'oci-config.json'), lock, profile, needsSqliteCompose
302
469
  ? join(deps.assetsDirectory(), 'sqlite', 'di-framework-sqlite.wasm')
303
- : undefined, composedProviders.map((provider) => provider.wasm));
470
+ : undefined, [
471
+ ...composedProviders.map((provider) => provider.wasm),
472
+ // The raw provider and layer bytes, never wac's output, so only the inputs set the key.
473
+ ...(pglite === undefined ? [] : [pgliteWasm]),
474
+ ...(encryption === undefined ? [] : [encfsWasm]),
475
+ ]);
304
476
  const artifactDigest = digestBytes(readFileSync(project.outputPath));
305
477
  const summary = {
306
478
  application: project.applicationName,
@@ -311,6 +483,14 @@ export async function buildComponent(project, io, deps, options = {}) {
311
483
  entry: relative(project.projectRoot, project.entryPath),
312
484
  profile,
313
485
  ...(actors.length > 0 ? { actors: actors.map((a) => a.actorName) } : {}),
486
+ ...(pglite === undefined
487
+ ? {}
488
+ : {
489
+ pglite: {
490
+ ...originOf(pglite),
491
+ ...(encryption === undefined ? {} : { encryption: originOf(encryption) }),
492
+ },
493
+ }),
314
494
  };
315
495
  writeFileSync(join(generatedDirectory, 'build.json'), `${JSON.stringify({ schemaVersion: 1, ...summary }, null, 2)}\n`);
316
496
  io.stdout.write(`Built ${summary.component}\n`);
@@ -1,3 +1,4 @@
1
+ import { RENDERED_ENVIRONMENT_KEYS } from '../environment-names.js';
1
2
  import { STORAGE_HOSTGROUP } from '../workload.js';
2
3
  import { ConsoleError, platformSentence, sanitizePublicText } from './errors.js';
3
4
  const RESOURCE_NAME = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/;
@@ -5,7 +6,7 @@ const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
5
6
  const HOST_NAME = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/i;
6
7
  const SENSITIVE_KEY = /(TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|PRIVATE|API_KEY|_KEY$)/i;
7
8
  const USERINFO = /:\/\/[^/\s:]+:[^/\s@]+@/;
8
- const HIDDEN_CONFIG = /^(DI_CONTROL_|DI_QUEUE_|DI_CRON_|DI_SQLITE_|DI_STORAGE_)|^(ACTOR_STORAGE_DIR|QUEUE_DB_PATH|MIGRATION_DB_PATH)$/;
9
+ const HIDDEN_CONFIG = new RegExp(`^(DI_CONTROL_|DI_QUEUE_|DI_CRON_|DI_SQLITE_|DI_STORAGE_)|^(${RENDERED_ENVIRONMENT_KEYS.join('|')})$`);
9
10
  const PLATFORM_CONTRACTS = new Set([
10
11
  'wasi:http',
11
12
  'wasi:cli',
@@ -1,6 +1,9 @@
1
1
  import type { WasmcloudDeps } from '../deps.js';
2
2
  import type { ClusterConnection } from '../target.js';
3
3
  import type { BindingDocument, HostFailure, JsonPatchOp, WorkloadDocument } from './catalog.js';
4
+ /** True for a Secret the platform manages; a tenant user may not replace it. */
5
+ export declare function isPlatformManagedSecretName(name: string): boolean;
6
+ export { MANAGED_SECRET_DENIALS, SECRET_UPDATE_KEYS_MESSAGE } from '../secret-admission.js';
4
7
  export type SignalView = {
5
8
  success: number;
6
9
  error: number;
@@ -4,11 +4,26 @@ import { join } from 'node:path';
4
4
  import { EGRESS_BINDING_NAME, egressResourceName } from '../egress.js';
5
5
  import { captureKubectl } from '../kubernetes.js';
6
6
  import { associationName } from '../managed-bindings.js';
7
+ import { kubectlStatusReason, MANAGED_SECRET_DENIALS, SECRET_UPDATE_KEYS_MESSAGE, } from '../secret-admission.js';
7
8
  import { MANAGED_BY_LABEL, WORKLOAD_DEPLOYMENT_RESOURCE } from '../workload.js';
8
9
  import { ConsoleError, sanitizePublicText } from './errors.js';
9
10
  const BINDING_RESOURCE = 'servicebindings.platform.di-framework.dev';
10
11
  /** Published by the platform controller in each tenant namespace (contract C-ROUTES). */
11
12
  const ROUTES_CONFIG_MAP = 'di-platform-routes';
13
+ /**
14
+ * Secret names the platform controller owns. Mirrors `isManagedSecretName` (`di-binding-*`,
15
+ * `di-bs-*`) and the Secret names of the `backend-config` admission policy (`di-tenant-stock`,
16
+ * `di-platform-routes`), both in di-framework/platform `platform/platform/src/tenancy/admission.ts`.
17
+ */
18
+ const MANAGED_SECRET_PREFIXES = ['di-binding-', 'di-bs-'];
19
+ const MANAGED_SECRET_NAMES = new Set(['di-tenant-stock', ROUTES_CONFIG_MAP]);
20
+ /** True for a Secret the platform manages; a tenant user may not replace it. */
21
+ export function isPlatformManagedSecretName(name) {
22
+ return (MANAGED_SECRET_NAMES.has(name) ||
23
+ MANAGED_SECRET_PREFIXES.some((prefix) => name.startsWith(prefix)));
24
+ }
25
+ // Denial messages of the platform's Secret admission policies; see `../secret-admission`.
26
+ export { MANAGED_SECRET_DENIALS, SECRET_UPDATE_KEYS_MESSAGE } from '../secret-admission.js';
12
27
  export function createKubectlConsoleCluster(deps, log = () => undefined) {
13
28
  const label = `app.kubernetes.io/managed-by=${MANAGED_BY_LABEL}`;
14
29
  return {
@@ -39,16 +54,54 @@ export function createKubectlConsoleCluster(deps, log = () => undefined) {
39
54
  async patchWorkload(connection, name, ops) {
40
55
  await kubectlOk(deps, connection, ['patch', WORKLOAD_DEPLOYMENT_RESOURCE, name, '--type=json', `-p=${JSON.stringify(ops)}`], log, 'The application could not be updated.');
41
56
  },
57
+ // Tenant developers can update Secrets but not read or patch them (platform#112), so the
58
+ // credential is written as a whole Secret with an unconditional PUT. A Secret is not
59
+ // created by an update, so a missing one still answers NotFound. The console cannot see
60
+ // the Secret's keys, so the platform's `tenant-secret-update` admission policy refuses a
61
+ // replace that would drop any (409) or that targets a platform-managed name (403), and the
62
+ // API server refuses one that would change a non-Opaque Secret's type (409). Errors are
63
+ // classified by their Status reason, never by the free text that carries the name.
42
64
  async reassignSecret(connection, name, value) {
65
+ if (isPlatformManagedSecretName(name)) {
66
+ throw new ConsoleError(403, 'SECRET_MANAGED', `${name} is managed by the platform and cannot be reassigned.`);
67
+ }
43
68
  const directory = mkdtempSync(join(tmpdir(), 'di-console-secret-'));
44
69
  try {
45
- const path = join(directory, 'patch.json');
46
- writeFileSync(path, JSON.stringify({ stringData: { credential: value } }), { mode: 0o600 });
47
- const result = await captureKubectl(deps, connection, ['patch', 'secret', name, '--type=merge', `--patch-file=${path}`], deps.cwd());
48
- if (result.exitCode !== 0 && /not ?found/i.test(result.stderr)) {
70
+ const path = join(directory, 'secret.json');
71
+ const document = {
72
+ apiVersion: 'v1',
73
+ kind: 'Secret',
74
+ metadata: { name, namespace: connection.namespace },
75
+ type: 'Opaque',
76
+ data: { credential: Buffer.from(value, 'utf8').toString('base64') },
77
+ };
78
+ writeFileSync(path, JSON.stringify(document), { mode: 0o600 });
79
+ const uri = `/api/v1/namespaces/${encodeURIComponent(connection.namespace)}/secrets/${encodeURIComponent(name)}`;
80
+ const result = await captureKubectl(deps, connection, ['replace', '--raw', uri, '-f', path], deps.cwd());
81
+ const reason = result.exitCode === 0 ? undefined : kubectlStatusReason(result.stderr);
82
+ if (reason === 'NotFound') {
49
83
  log(sanitizePublicText(result.stderr));
50
84
  throw new ConsoleError(404, 'SECRET_NOT_FOUND', `No credential named ${name}.`);
51
85
  }
86
+ if (result.exitCode !== 0 && result.stderr.includes(SECRET_UPDATE_KEYS_MESSAGE)) {
87
+ log(sanitizePublicText(result.stderr));
88
+ throw new ConsoleError(409, 'SECRET_NOT_SINGLE_KEY', `${name} holds values other than a single credential, so it cannot be reassigned here.`);
89
+ }
90
+ if (result.exitCode !== 0 &&
91
+ MANAGED_SECRET_DENIALS.some((message) => result.stderr.includes(message))) {
92
+ log(sanitizePublicText(result.stderr));
93
+ throw new ConsoleError(403, 'SECRET_MANAGED', `${name} is managed by the platform and cannot be reassigned.`);
94
+ }
95
+ // A Secret's type is immutable, so a non-Opaque Secret cannot take the Opaque document.
96
+ if (reason === 'Invalid' &&
97
+ /\btype: Invalid value:.*field is immutable/.test(result.stderr)) {
98
+ log(sanitizePublicText(result.stderr));
99
+ throw new ConsoleError(409, 'SECRET_TYPE_MISMATCH', `${name} is not a plain (Opaque) Secret and its type cannot change, so it cannot be reassigned here.`);
100
+ }
101
+ if (reason === 'Forbidden') {
102
+ log(sanitizePublicText(result.stderr));
103
+ throw new ConsoleError(403, 'WRITES_FORBIDDEN', 'This credential cannot change the application.');
104
+ }
52
105
  if (result.exitCode !== 0) {
53
106
  log(sanitizePublicText(result.stderr || result.stdout || 'request failed'));
54
107
  throw new ConsoleError(502, 'REQUEST_FAILED', 'The credential could not be reassigned.');
@@ -1,5 +1,5 @@
1
1
  /** Cluster-private control-plane authentication for cron/queue/actor admin APIs. */
2
- /** Unconfigured local/dev only. Never includes `admin`. */
2
+ /** Unconfigured local/dev only (never a deployed workload). Never includes `admin`. */
3
3
  const ANONYMOUS_IDENTITY = { id: 'anonymous', token: '', roles: ['invoke'] };
4
4
  function isIdentityEntry(entry) {
5
5
  if (entry === null || typeof entry !== 'object')
@@ -46,7 +46,19 @@ function parseIdentities() {
46
46
  return { identities: singleTokenIdentities(), configured: true };
47
47
  }
48
48
  const identities = singleTokenIdentities();
49
- return { identities, configured: identities.length > 0 };
49
+ return { identities, configured: identities.length > 0 || isDeployed() };
50
+ }
51
+ /**
52
+ * A deployed workload: deploy renders the control host settings, and the control Secret supplies
53
+ * `DI_CONTROL_IDENTITY`. Such a workload without a usable token fails closed instead of falling
54
+ * back to anonymous invoke, so a control Secret that lost `DI_CONTROL_TOKEN` (for example one
55
+ * rewritten by app tooling) cannot open cron, queue and actor endpoints.
56
+ */
57
+ function isDeployed() {
58
+ return (process.env.DI_CONTROL_REJECT_FORWARDED === '1' ||
59
+ (process.env.DI_CONTROL_HTTP_HOST ?? '').trim() !== '' ||
60
+ process.env.DI_CONTROL_IDENTITY !== undefined ||
61
+ process.env.DI_CONTROL_TOKEN !== undefined);
50
62
  }
51
63
  function hasRequiredRole(identity, requiredRoles) {
52
64
  return !requiredRoles.some((role) => !identity.roles.includes(role) && !identity.roles.includes('admin'));
package/dist/deploy.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { CliIo, CommandResult } from '@di-framework/cli-extension';
2
+ import { type BuildSummary } from './build.js';
2
3
  import { type WasmcloudDeps } from './deps.js';
3
4
  import type { RegistryLocation } from './registry.js';
4
5
  export type WasmcloudDeployData = {
@@ -21,6 +22,11 @@ export type WasmcloudDeployData = {
21
22
  host: string;
22
23
  };
23
24
  endpoints?: Record<string, string>;
25
+ /**
26
+ * Where the composed PGlite provider came from (a digest pin or a local file) and, when
27
+ * `pglite.encryption` is set, its encryption layer.
28
+ */
29
+ pglite?: BuildSummary['pglite'];
24
30
  };
25
31
  export type WasmcloudDeployResult = Omit<CommandResult, 'data' | 'text'> & {
26
32
  data: WasmcloudDeployData;
package/dist/deploy.js CHANGED
@@ -4,6 +4,7 @@ import { discoverScheduledJobs } from './cron.js';
4
4
  import { DEFAULT_DEPS } from './deps.js';
5
5
  import { discoverProjects, resolveApplication } from './discovery.js';
6
6
  import { loadDeployManifest } from './manifest.js';
7
+ import { assertDistinctPgliteRoots } from './pglite.js';
7
8
  import { publishComponent } from './publish.js';
8
9
  import { resolveConnection, resolveTarget } from './target.js';
9
10
  import { applyWorkload, deploymentResourceName } from './workload.js';
@@ -14,10 +15,12 @@ export async function runWasmcloudDeploy(args, io, deps = DEFAULT_DEPS) {
14
15
  const target = resolveTarget(manifest, options.target);
15
16
  const project = resolveApplication(deps.cwd(), options.name, manifest.workspaceRoot, manifest.discovery);
16
17
  if (project.workload) {
17
- const path = writeWorkloadManifest(manifest.workspaceRoot, project.workload, discoverProjects(manifest.workspaceRoot, manifest.discovery).values());
18
+ const members = [...discoverProjects(manifest.workspaceRoot, manifest.discovery).values()];
19
+ assertDistinctPgliteRoots(project.workload, members);
20
+ const path = writeWorkloadManifest(manifest.workspaceRoot, project.workload, members);
18
21
  io.stdout.write(`Generated workload manifest ${path}\n`);
19
22
  }
20
- const build = await buildComponent(project, io, deps);
23
+ const build = await buildComponent(project, io, deps, { deploy: true });
21
24
  const connection = await resolveConnection(target, manifest.workspaceRoot, manifest.path, deps);
22
25
  io.stdout.write(`Deploying ${project.applicationName} to target ${connection.target}...\n`);
23
26
  const image = await publishComponent(project, connection, io, deps, build.deploymentDigest);
@@ -40,6 +43,7 @@ export async function runWasmcloudDeploy(args, io, deps = DEFAULT_DEPS) {
40
43
  ? { http: { url: connection.endpoints.http, host: project.applicationName } }
41
44
  : {}),
42
45
  ...(connection.endpoints === undefined ? {} : { endpoints: connection.endpoints }),
46
+ ...(build.pglite === undefined ? {} : { pglite: build.pglite }),
43
47
  ...(cronJobs.length > 0
44
48
  ? {
45
49
  cronJobs: cronJobs.map((j) => ({
@@ -50,8 +54,26 @@ export async function runWasmcloudDeploy(args, io, deps = DEFAULT_DEPS) {
50
54
  }
51
55
  : {}),
52
56
  },
53
- text: `Deployed ${project.applicationName} to ${connection.target} (namespace ${connection.namespace}, ${image.pullReference}).${hasHttp && connection.endpoints?.http !== undefined
54
- ? ` HTTP: ${connection.endpoints.http} with Host: ${project.applicationName}`
55
- : ''}${cronJobs.length > 0 ? ` Scheduled jobs (${cronJobs.length}): ${cronJobs.map((j) => j.jobId).join(', ')}` : ''}`,
57
+ text: [
58
+ `Deployed ${project.applicationName} to ${connection.target} (namespace ${connection.namespace}, ${image.pullReference}).`,
59
+ hasHttp && connection.endpoints?.http !== undefined
60
+ ? ` HTTP: ${connection.endpoints.http} with Host: ${project.applicationName}`
61
+ : '',
62
+ pgliteText(build.pglite),
63
+ cronJobs.length > 0
64
+ ? ` Scheduled jobs (${cronJobs.length}): ${cronJobs.map((j) => j.jobId).join(', ')}`
65
+ : '',
66
+ ].join(''),
56
67
  };
57
68
  }
69
+ function originText(origin) {
70
+ return origin.path === undefined ? `${origin.image}` : `local ${origin.path} (unverified)`;
71
+ }
72
+ function pgliteText(pglite) {
73
+ if (pglite === undefined)
74
+ return '';
75
+ const encryption = pglite.encryption === undefined
76
+ ? ''
77
+ : `, encrypted at rest by ${originText(pglite.encryption)}`;
78
+ return ` PGlite: ${originText(pglite)}${encryption}.`;
79
+ }
package/dist/deps.js CHANGED
@@ -106,7 +106,7 @@ const packageRoot = resolve(dirname(realpathSync(fileURLToPath(import.meta.url))
106
106
  export function componentizeQjsPlatformPackageName() {
107
107
  return COMPONENTIZE_QJS_PACKAGE;
108
108
  }
109
- export function componentizeQjsPlatformPackageVersion(platform = process.platform, arch = process.arch, wrapperVersion = '0.4.4-di.4') {
109
+ export function componentizeQjsPlatformPackageVersion(platform = process.platform, arch = process.arch, wrapperVersion = '0.4.4-di.5') {
110
110
  return `${wrapperVersion}-${platform}-${arch}`;
111
111
  }
112
112
  function platformPackageBinMatches(packageDirectory, platform, arch) {
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Environment names the CLI renders into a workload's `localResources.environment.config`
3
+ * without a `DI_` prefix (every `DI_*` name is the framework's as well). The console hides them,
4
+ * and `controlSecretKeys` may not declare them, so a Secret key never shadows one.
5
+ */
6
+ export declare const RENDERED_ENVIRONMENT_KEYS: readonly string[];
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Environment names the CLI renders into a workload's `localResources.environment.config`
3
+ * without a `DI_` prefix (every `DI_*` name is the framework's as well). The console hides them,
4
+ * and `controlSecretKeys` may not declare them, so a Secret key never shadows one.
5
+ */
6
+ export const RENDERED_ENVIRONMENT_KEYS = [
7
+ 'ACTOR_STORAGE_DIR',
8
+ 'QUEUE_DB_PATH',
9
+ 'MIGRATION_DB_PATH',
10
+ ];
package/dist/index.d.ts CHANGED
@@ -29,6 +29,6 @@ export { BACKING_SERVICE_API_VERSION, BACKING_SERVICE_KIND, BACKING_SERVICE_RESO
29
29
  export { resolveConnection, resolveTarget } from './target.js';
30
30
  export { renderWashDevYaml, writeWashDevConfig } from './wash-dev.js';
31
31
  export { aggregateRequirements, COMPONENT_MODEL, DI_QUEUES_INTERFACE, DI_QUEUES_PACKAGE, DI_QUEUES_VERSION, defaultProjectRequirements, HTTP_ADAPTER_REQUIREMENTS, QUEUE_ADAPTER_REQUIREMENTS, QUEUE_ADAPTER_SOURCE, queueProjectRequirements, renderWorldWit, runtimeRequirementsFromJavaScript, socketRequirementsFromJavaScript, type WitRequirement, } from './wit.js';
32
- export { applyWorkload, CRON_INVOKER_IMAGE, controlSecretResourceName, DEFAULT_STORAGE_MOUNT, deleteWorkload, HOST_STORAGE_ROOT, hostStoragePath, isReady, renderWorkloadManifest, STORAGE_HOSTGROUP, type WorkloadManifestOptions, } from './workload.js';
32
+ export { applyWorkload, CONTROL_SECRET_CLI_KEYS, type ControlSecretWrite, CRON_INVOKER_IMAGE, controlSecretDocument, controlSecretResourceName, DEFAULT_STORAGE_MOUNT, deleteControlSecret, deleteWorkload, HOST_STORAGE_ROOT, hostStoragePath, isReady, renderWorkloadManifest, STORAGE_HOSTGROUP, type WorkloadManifestOptions, writeControlSecret, } from './workload.js';
33
33
  declare const _default: import("@di-framework/cli-extension").ExtensionManifest;
34
34
  export default _default;
package/dist/index.js CHANGED
@@ -31,7 +31,7 @@ export { BACKING_SERVICE_API_VERSION, BACKING_SERVICE_KIND, BACKING_SERVICE_RESO
31
31
  export { resolveConnection, resolveTarget } from './target.js';
32
32
  export { renderWashDevYaml, writeWashDevConfig } from './wash-dev.js';
33
33
  export { aggregateRequirements, COMPONENT_MODEL, DI_QUEUES_INTERFACE, DI_QUEUES_PACKAGE, DI_QUEUES_VERSION, defaultProjectRequirements, HTTP_ADAPTER_REQUIREMENTS, QUEUE_ADAPTER_REQUIREMENTS, QUEUE_ADAPTER_SOURCE, queueProjectRequirements, renderWorldWit, runtimeRequirementsFromJavaScript, socketRequirementsFromJavaScript, } from './wit.js';
34
- export { applyWorkload, CRON_INVOKER_IMAGE, controlSecretResourceName, DEFAULT_STORAGE_MOUNT, deleteWorkload, HOST_STORAGE_ROOT, hostStoragePath, isReady, renderWorkloadManifest, STORAGE_HOSTGROUP, } from './workload.js';
34
+ export { applyWorkload, CONTROL_SECRET_CLI_KEYS, CRON_INVOKER_IMAGE, controlSecretDocument, controlSecretResourceName, DEFAULT_STORAGE_MOUNT, deleteControlSecret, deleteWorkload, HOST_STORAGE_ROOT, hostStoragePath, isReady, renderWorkloadManifest, STORAGE_HOSTGROUP, writeControlSecret, } from './workload.js';
35
35
  export default defineExtension({
36
36
  schemaVersion: 1,
37
37
  name: 'platform',
@@ -1,15 +1,30 @@
1
1
  import { log } from 'wasi:logging/logging@0.1.0-draft';
2
2
  /** Context passed with every guest console line; the host tags it with the workload. */
3
3
  export const CONSOLE_LOG_CONTEXT = 'console';
4
+ /**
5
+ * WIT s64/u64 values (SQLite integers, row counts, timestamps) arrive as BigInt since
6
+ * componentize-qjs 0.4.4-di.5, and JSON.stringify throws on BigInt.
7
+ *
8
+ * Convention: a top-level BigInt prints as Node's console does (`42n`). A BigInt nested
9
+ * in an object or array prints as the JSON string `"42n"` (`{"id":"42n"}`, where Node
10
+ * would print `{ id: 42n }`), so each line stays valid JSON for log consumers. A JSON
11
+ * reader therefore cannot tell BigInt `42n` from the string `"42n"`; treat a string
12
+ * matching `/^-?\d+n$/` as a BigInt when that matters.
13
+ */
14
+ function bigintReplacer(_key, value) {
15
+ return typeof value === 'bigint' ? `${value}n` : value;
16
+ }
4
17
  function formatValue(value) {
5
18
  if (typeof value === 'string')
6
19
  return value;
7
20
  if (value instanceof Error)
8
21
  return value.stack ?? `${value.name}: ${value.message}`;
22
+ if (typeof value === 'bigint')
23
+ return `${value}n`;
9
24
  if (typeof value !== 'object' || value === null)
10
25
  return String(value);
11
26
  try {
12
- return JSON.stringify(value);
27
+ return JSON.stringify(value, bigintReplacer);
13
28
  }
14
29
  catch {
15
30
  return String(value);
@@ -16,6 +16,12 @@ export type GuestCryptoKey = {
16
16
  bytes: Uint8Array;
17
17
  };
18
18
  export declare function algorithmName(algorithm: AlgorithmIdentifier): string;
19
+ /** Web Crypto's per-call `getRandomValues` quota, in bytes. */
20
+ export declare const GET_RANDOM_VALUES_MAX = 65536;
21
+ /**
22
+ * Like Node v22's `crypto.getRandomValues`: integer-type typed arrays only
23
+ * (`TypeMismatchError`), at most 65,536 bytes (`QuotaExceededError`).
24
+ */
19
25
  export declare function getRandomValues<T extends ArrayBufferView>(array: T): T;
20
26
  export declare function randomUUID(): string;
21
27
  declare function digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise<ArrayBuffer>;