@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
@@ -80,10 +80,61 @@ export interface WorkloadManifestOptions {
80
80
  };
81
81
  /** Secret name providing control-plane credentials (merged into WASI environment). */
82
82
  controlSecretName?: string;
83
+ /**
84
+ * Digest of the control token written on this deploy. Rendered as
85
+ * DI_CONTROL_TOKEN_REVISION so a rotated token changes the template and rolls the workload.
86
+ */
87
+ controlTokenRevision?: string;
83
88
  /** Explicit environment config values (string map for localResources.environment.config). */
84
89
  environment?: Record<string, string>;
85
90
  }
86
91
  export declare function renderWorkloadManifest(project: WasmcloudProject, connection: ClusterConnection, image: string, requirements?: readonly WitRequirement[], bindings?: readonly BindingRecord[], options?: WorkloadManifestOptions | boolean, cronJobs?: readonly DiscoveredCronJob[], queueHandlers?: readonly DiscoveredQueueHandler[]): string;
92
+ /** Appended to a deploy failure that happened after the control Secret was rewritten. */
93
+ export declare const CONTROL_TOKEN_ROTATED_NOTICE = "the control token was rotated; re-run deploy to roll the workload onto it";
94
+ /**
95
+ * The control Secret after a deploy: its name and, when deploy wrote a new token, a digest that
96
+ * identifies it. `revision` is undefined when deploy kept the Secret as it was.
97
+ */
98
+ export type ControlSecretWrite = {
99
+ name: string;
100
+ revision?: string;
101
+ };
102
+ /** The keys the CLI owns in every control Secret. */
103
+ export declare const CONTROL_SECRET_CLI_KEYS: readonly ["DI_CONTROL_TOKEN", "DI_CONTROL_IDENTITY"];
104
+ /**
105
+ * The control Secret document. The CLI's keys hold `token` and the workload name; `appData`
106
+ * (already base64, as in a Secret's `data`) carries app-owned keys over, and `resourceVersion`
107
+ * makes the update conditional.
108
+ */
109
+ export declare function controlSecretDocument(workloadName: string, namespace: string, token: string, appData?: Readonly<Record<string, string>>, resourceVersion?: string): Record<string, unknown>;
110
+ /**
111
+ * Writes the workload's control Secret on deploy and returns whether the token rotated.
112
+ *
113
+ * The Secret holds the CLI's `DI_CONTROL_TOKEN` and `DI_CONTROL_IDENTITY` plus the app-owned keys
114
+ * the project declares in `controlSecretKeys` (cli-extensions#69). Any other key is refused: the
115
+ * Secret is injected whole into the workload's environment, so an undeclared key is either a
116
+ * mistake or a value nobody vouched for.
117
+ *
118
+ * - A new Secret is created with the CLI's keys and a fresh token.
119
+ * - An existing Secret the caller may read (an admin) is read, checked for undeclared keys, and
120
+ * updated with a fresh token and its declared keys carried over, conditional on the
121
+ * `resourceVersion` that was read.
122
+ * - Tenant developers may create, update and delete Secrets but never get, list, watch or patch
123
+ * them (platform#112), and the platform's `tenant-secret-update` admission policy refuses an
124
+ * update that drops a key. So an existing Secret is replaced blind with the CLI's keys and a
125
+ * fresh token. When that is refused because the Secret holds more keys, a dry-run update that
126
+ * also names every declared key asks the same policy whether all of the extra keys are
127
+ * declared. If they are, the Secret is kept as it is, token included, since a blind writer
128
+ * cannot carry over values it cannot read; otherwise deploy stops.
129
+ *
130
+ * Every request goes through `--raw`: `kubectl replace -f` would GET the object first.
131
+ */
132
+ export declare function writeControlSecret(project: WasmcloudProject, connection: ClusterConnection, deps: WasmcloudDeps): Promise<ControlSecretWrite>;
133
+ /**
134
+ * Deletes the control Secret by name. A label-selected delete would LIST Secrets and the
135
+ * default `--wait=true` would GET it afterwards, both forbidden to tenant developers.
136
+ */
137
+ export declare function deleteControlSecret(project: WasmcloudProject, connection: ClusterConnection, deps: WasmcloudDeps): Promise<void>;
87
138
  export declare function applyWorkload(project: WasmcloudProject, connection: ClusterConnection, image: string, io: CliIo, deps: WasmcloudDeps): Promise<string>;
88
139
  export declare function deleteWorkload(project: WasmcloudProject, connection: ClusterConnection, io: CliIo, deps: WasmcloudDeps): Promise<void>;
89
140
  export declare function waitForReady(project: WasmcloudProject, connection: ClusterConnection, deps: WasmcloudDeps, io?: CliIo): Promise<void>;
package/dist/workload.js CHANGED
@@ -1,16 +1,20 @@
1
- import { randomBytes } from 'node:crypto';
2
- import { mkdirSync, writeFileSync } from 'node:fs';
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
3
4
  import { join } from 'node:path';
4
- import { CommandFailure } from '@di-framework/cli-extension';
5
+ import { CommandFailure, isCommandFailure, } from '@di-framework/cli-extension';
5
6
  import { discoverActors } from './actors.js';
6
7
  import { discoverBindings, requirementsFromBindings } from './bindings.js';
8
+ import { sanitizePublicText } from './console/errors.js';
7
9
  import { discoverScheduledJobs } from './cron.js';
8
10
  import { applyWorkloadEgress, removeWorkloadEgress, reportEgressStatus, usesPlatformEgress, warnIfTenantHostLacksTls, } from './egress.js';
9
11
  import { hostInterfacesFromRequirements, renderHostInterfacesYaml } from './host-interface.js';
10
12
  import { captureKubectl, runKubectl } from './kubernetes.js';
11
13
  import { applyManagedBindings, cleanupManagedBindings } from './managed-bindings.js';
12
- import { asWitIdentifier } from './project.js';
14
+ import { EXCLUSIVE_INSTANCE_KEY, isWithin, PGLITE_DATA_DIR_ENV, warnIfHostIgnoresExclusive, } from './pglite.js';
15
+ import { asWitIdentifier, CONFIG_FILE_NAME } from './project.js';
13
16
  import { discoverQueueHandlers, isQueueWorkerProject } from './queues.js';
17
+ import { kubectlStatusReason, SECRET_UPDATE_KEYS_MESSAGE } from './secret-admission.js';
14
18
  import { defaultProjectRequirements, guestLoggingRequirement, queueProjectRequirements, } from './wit.js';
15
19
  export const MANAGED_BY_LABEL = 'di-framework';
16
20
  export const WAIT_ATTEMPTS = 30;
@@ -83,8 +87,11 @@ export function renderWorkloadManifest(project, connection, image, requirements
83
87
  const resolvedHandlers = queueHandlers.length > 0 ? queueHandlers : discoverQueueHandlers(project);
84
88
  const isWorker = isQueueWorkerProject(project, resolvedHandlers);
85
89
  const hasQueues = resolvedHandlers.length > 0;
86
- const needsPersistentStorage = opts.hasPersistentStorage ??
87
- (hasActors || hasQueues || isWorker || project.persistentStorage === true);
90
+ const pglite = project.pglite;
91
+ // An embedded PostgreSQL data directory needs persistent storage whatever the caller says.
92
+ const needsPersistentStorage = pglite !== undefined ||
93
+ (opts.hasPersistentStorage ??
94
+ (hasActors || hasQueues || isWorker || project.persistentStorage === true));
88
95
  const needsControlHttp = hasActors || cronJobs.length > 0 || hasQueues || isWorker;
89
96
  const publicIngress = project.ingress !== false && !isWorker;
90
97
  // Cluster Service is required for cron invokers and queue/actor control even when
@@ -92,7 +99,9 @@ export function renderWorkloadManifest(project, connection, image, requirements
92
99
  const hasHttp = publicIngress || needsControlHttp || needsPersistentStorage;
93
100
  if (needsPersistentStorage) {
94
101
  if (opts.replicas !== undefined && opts.replicas !== 1) {
95
- throw new CommandFailure('WASMCLOUD_STORAGE_REPLICA_CONSTRAINT', 'SQLite-backed workloads require replicas: 1 because the WASI VFS lacks file locking', 2, { replicas: opts.replicas });
102
+ throw new CommandFailure('WASMCLOUD_STORAGE_REPLICA_CONSTRAINT', pglite === undefined
103
+ ? 'SQLite-backed workloads require replicas: 1 because the WASI VFS lacks file locking'
104
+ : 'PGlite workloads require replicas: 1 because each database directory allows one opener', 2, { replicas: opts.replicas });
96
105
  }
97
106
  }
98
107
  const name = deploymentResourceName(project);
@@ -104,7 +113,11 @@ export function renderWorkloadManifest(project, connection, image, requirements
104
113
  ].join('\n');
105
114
  const volumeName = opts.storageVolume?.volumeName ?? 'app-storage';
106
115
  const mountPath = opts.storageVolume?.mountPath ??
116
+ pglite?.storageMount ??
107
117
  (hasActors ? `${DEFAULT_STORAGE_MOUNT}/actors` : DEFAULT_STORAGE_MOUNT);
118
+ if (pglite !== undefined && !isWithin(pglite.dataDir, mountPath)) {
119
+ throw new CommandFailure('WASMCLOUD_PGLITE_STORAGE_MISMATCH', `pglite.dataDir ${pglite.dataDir} is outside the storage mount ${mountPath}`, 2, { dataDir: pglite.dataDir, mountPath });
120
+ }
108
121
  const hostPath = opts.storageVolume?.hostPath ?? hostStoragePath(storageDirectoryName(project));
109
122
  const platformStorage = needsPersistentStorage && usesPlatformStorage(connection);
110
123
  if (platformStorage && !PLATFORM_STORAGE_MOUNTS.includes(mountPath)) {
@@ -125,6 +138,8 @@ export function renderWorkloadManifest(project, connection, image, requirements
125
138
  }
126
139
  if (hasActors)
127
140
  environment.ACTOR_STORAGE_DIR = mountPath;
141
+ if (pglite !== undefined)
142
+ environment[PGLITE_DATA_DIR_ENV] = pglite.dataDir;
128
143
  if (needsPersistentStorage && !hasActors) {
129
144
  environment.QUEUE_DB_PATH = `${mountPath}/queue.db`;
130
145
  environment.MIGRATION_DB_PATH = `${mountPath}/migrations.db`;
@@ -132,6 +147,9 @@ export function renderWorkloadManifest(project, connection, image, requirements
132
147
  const controlSecretName = opts.controlSecretName ?? (hasHttp ? controlSecretResourceName(name) : undefined);
133
148
  const clusterHttpHost = `${name}.${connection.namespace}.svc.cluster.local`;
134
149
  const advertisedHttpHost = publicIngress ? project.applicationName : clusterHttpHost;
150
+ if (controlSecretName !== undefined && opts.controlTokenRevision !== undefined) {
151
+ environment.DI_CONTROL_TOKEN_REVISION = opts.controlTokenRevision;
152
+ }
135
153
  if (hasHttp) {
136
154
  environment.DI_CONTROL_REJECT_FORWARDED = '1';
137
155
  environment.DI_CONTROL_HTTP_HOST = [name, clusterHttpHost].join(',');
@@ -194,6 +212,11 @@ spec:
194
212
  else if (ipNameLookups !== undefined) {
195
213
  localResourcesLines.push(' localResources:');
196
214
  }
215
+ // The component itself is the exclusive unit (#140): never the service, which admission
216
+ // rejects, and never a separately linked provider, which the host refuses to load.
217
+ if (pglite !== undefined) {
218
+ localResourcesLines.push(' config:', ` ${EXCLUSIVE_INSTANCE_KEY}: "true"`);
219
+ }
197
220
  if (needsPersistentStorage && !platformStorage) {
198
221
  localResourcesLines.push(' volumeMounts:');
199
222
  localResourcesLines.push(` - name: ${volumeName}`);
@@ -325,30 +348,255 @@ ${labels.replace(/^/gm, ' ')}
325
348
  }
326
349
  return sections.join('\n---\n') + '\n';
327
350
  }
328
- async function ensureControlSecret(project, connection, deps) {
329
- const name = deploymentResourceName(project);
330
- const secretName = controlSecretResourceName(name);
331
- const existing = await captureKubectl(deps, connection, ['get', 'secret', secretName], project.projectRoot);
332
- if (existing.exitCode !== 0) {
333
- const token = randomBytes(32).toString('base64url');
334
- await runKubectl(deps, connection, [
335
- 'create',
336
- 'secret',
337
- 'generic',
338
- secretName,
339
- `--from-literal=DI_CONTROL_TOKEN=${token}`,
340
- `--from-literal=DI_CONTROL_IDENTITY=${name}`,
341
- ], project.projectRoot);
351
+ /** Appended to a deploy failure that happened after the control Secret was rewritten. */
352
+ export const CONTROL_TOKEN_ROTATED_NOTICE = 'the control token was rotated; re-run deploy to roll the workload onto it';
353
+ /** The keys the CLI owns in every control Secret. */
354
+ export const CONTROL_SECRET_CLI_KEYS = ['DI_CONTROL_TOKEN', 'DI_CONTROL_IDENTITY'];
355
+ /**
356
+ * The control Secret document. The CLI's keys hold `token` and the workload name; `appData`
357
+ * (already base64, as in a Secret's `data`) carries app-owned keys over, and `resourceVersion`
358
+ * makes the update conditional.
359
+ */
360
+ export function controlSecretDocument(workloadName, namespace, token, appData = {}, resourceVersion) {
361
+ const encode = (value) => Buffer.from(value, 'utf8').toString('base64');
362
+ return {
363
+ apiVersion: 'v1',
364
+ kind: 'Secret',
365
+ metadata: {
366
+ name: controlSecretResourceName(workloadName),
367
+ namespace,
368
+ labels: {
369
+ 'app.kubernetes.io/managed-by': MANAGED_BY_LABEL,
370
+ 'app.kubernetes.io/name': workloadName,
371
+ },
372
+ ...(resourceVersion === undefined ? {} : { resourceVersion }),
373
+ },
374
+ type: 'Opaque',
375
+ data: {
376
+ ...appData,
377
+ DI_CONTROL_TOKEN: encode(token),
378
+ DI_CONTROL_IDENTITY: encode(workloadName),
379
+ },
380
+ };
381
+ }
382
+ function secretsPath(namespace, name) {
383
+ const collection = `/api/v1/namespaces/${encodeURIComponent(namespace)}/secrets`;
384
+ return name === undefined ? collection : `${collection}/${encodeURIComponent(name)}`;
385
+ }
386
+ /**
387
+ * Writes the workload's control Secret on deploy and returns whether the token rotated.
388
+ *
389
+ * The Secret holds the CLI's `DI_CONTROL_TOKEN` and `DI_CONTROL_IDENTITY` plus the app-owned keys
390
+ * the project declares in `controlSecretKeys` (cli-extensions#69). Any other key is refused: the
391
+ * Secret is injected whole into the workload's environment, so an undeclared key is either a
392
+ * mistake or a value nobody vouched for.
393
+ *
394
+ * - A new Secret is created with the CLI's keys and a fresh token.
395
+ * - An existing Secret the caller may read (an admin) is read, checked for undeclared keys, and
396
+ * updated with a fresh token and its declared keys carried over, conditional on the
397
+ * `resourceVersion` that was read.
398
+ * - Tenant developers may create, update and delete Secrets but never get, list, watch or patch
399
+ * them (platform#112), and the platform's `tenant-secret-update` admission policy refuses an
400
+ * update that drops a key. So an existing Secret is replaced blind with the CLI's keys and a
401
+ * fresh token. When that is refused because the Secret holds more keys, a dry-run update that
402
+ * also names every declared key asks the same policy whether all of the extra keys are
403
+ * declared. If they are, the Secret is kept as it is, token included, since a blind writer
404
+ * cannot carry over values it cannot read; otherwise deploy stops.
405
+ *
406
+ * Every request goes through `--raw`: `kubectl replace -f` would GET the object first.
407
+ */
408
+ export async function writeControlSecret(project, connection, deps) {
409
+ const workloadName = deploymentResourceName(project);
410
+ const name = controlSecretResourceName(workloadName);
411
+ const declared = project.controlSecretKeys ?? [];
412
+ const token = randomBytes(32).toString('base64url');
413
+ const rotated = { name, revision: createHash('sha256').update(token).digest('hex').slice(0, 16) };
414
+ /** Values that must never appear in an error: the token and any value read from the cluster. */
415
+ const secrets = [token];
416
+ const directory = mkdtempSync(join(tmpdir(), 'di-control-secret-'));
417
+ let written = 0;
418
+ const send = async (verb, document, query = '') => {
419
+ const path = join(directory, `secret-${written++}.json`);
420
+ writeFileSync(path, JSON.stringify(document), { mode: 0o600 });
421
+ const target = verb === 'create'
422
+ ? secretsPath(connection.namespace)
423
+ : secretsPath(connection.namespace, name);
424
+ return captureKubectl(deps, connection, [verb, '--raw', `${target}${query}`, '-f', path], project.projectRoot);
425
+ };
426
+ const failed = (command, result) => controlSecretWriteFailed(command, name, connection, result, secrets);
427
+ try {
428
+ const document = controlSecretDocument(workloadName, connection.namespace, token);
429
+ const created = await send('create', document);
430
+ if (created.exitCode === 0)
431
+ return rotated;
432
+ if (kubectlStatusReason(created.stderr) !== 'AlreadyExists') {
433
+ throw failed('kubectl create', created);
434
+ }
435
+ const stored = await readControlSecret(project, connection, deps, name, secrets);
436
+ if (stored !== undefined) {
437
+ const undeclared = Object.keys(stored.data).filter((key) => !CONTROL_SECRET_CLI_KEYS.includes(key) && !declared.includes(key));
438
+ if (undeclared.length > 0)
439
+ throw controlSecretForeignKeys(name, connection, undeclared);
440
+ const appData = Object.fromEntries(Object.entries(stored.data).filter(([key]) => declared.includes(key)));
441
+ const merged = controlSecretDocument(workloadName, connection.namespace, token, appData, stored.resourceVersion);
442
+ const updated = await send('replace', merged);
443
+ if (updated.exitCode !== 0)
444
+ throw failed('kubectl replace', updated);
445
+ return rotated;
446
+ }
447
+ /**
448
+ * Asks the `tenant-secret-update` policy, with a dry run that stores nothing, whether an
449
+ * update holding only `keys` would drop a key of the stored Secret. Values are placeholders:
450
+ * the policy compares key names only. True when the policy refuses it.
451
+ */
452
+ const dropsAKey = async (keys) => {
453
+ const probe = controlSecretDocument(workloadName, connection.namespace, token);
454
+ const data = {};
455
+ for (const key of keys)
456
+ data[key] = '';
457
+ probe.data = data;
458
+ const checked = await send('replace', probe, '?dryRun=All');
459
+ if (checked.exitCode === 0)
460
+ return false;
461
+ if (checked.stderr.includes(SECRET_UPDATE_KEYS_MESSAGE))
462
+ return true;
463
+ throw failed('kubectl replace --dry-run', checked);
464
+ };
465
+ // With app keys declared, a blind update must never be the one to find out that the policy
466
+ // does not protect them (a caller that is not `di-user-*`, a namespace outside the policy, an
467
+ // older platform): it would succeed and drop them. The policy must first refuse a dry run
468
+ // that keeps only DI_CONTROL_IDENTITY, which it does exactly when it applies and the Secret
469
+ // holds another key.
470
+ if (declared.length > 0 && !(await dropsAKey(['DI_CONTROL_IDENTITY']))) {
471
+ throw controlSecretUnguarded(name, connection);
472
+ }
473
+ const replaced = await send('replace', document);
474
+ if (replaced.exitCode === 0)
475
+ return rotated;
476
+ if (!replaced.stderr.includes(SECRET_UPDATE_KEYS_MESSAGE)) {
477
+ throw failed('kubectl replace', replaced);
478
+ }
479
+ if (declared.length === 0)
480
+ throw controlSecretForeignKeys(name, connection);
481
+ if (await dropsAKey([...CONTROL_SECRET_CLI_KEYS, ...declared])) {
482
+ throw controlSecretForeignKeys(name, connection);
483
+ }
484
+ // Kept as it is, so the CLI's keys must be there: a workload without its token would have
485
+ // no control credentials. Leaving one out must drop a key, which proves it is stored.
486
+ for (const key of CONTROL_SECRET_CLI_KEYS) {
487
+ const others = CONTROL_SECRET_CLI_KEYS.filter((other) => other !== key);
488
+ if (!(await dropsAKey([...others, ...declared]))) {
489
+ throw controlSecretIncomplete(name, connection, key);
490
+ }
491
+ }
492
+ return { name };
493
+ }
494
+ finally {
495
+ rmSync(directory, { recursive: true, force: true });
496
+ }
497
+ }
498
+ /**
499
+ * The stored control Secret's keys (base64 values) and `resourceVersion` when the caller may read
500
+ * it, or undefined when it may not. `kubectl auth can-i` asks first, so a tenant developer never
501
+ * sends a Secret read the platform forbids. Values read here are added to `secrets` so no error
502
+ * can show them; nothing read is ever printed.
503
+ */
504
+ async function readControlSecret(project, connection, deps, name, secrets) {
505
+ const allowed = await captureKubectl(deps, connection, ['auth', 'can-i', 'get', `secrets/${name}`], project.projectRoot);
506
+ if (allowed.exitCode !== 0 || allowed.stdout.trim() !== 'yes')
507
+ return undefined;
508
+ const read = await captureKubectl(deps, connection, ['get', '--raw', secretsPath(connection.namespace, name)], project.projectRoot);
509
+ if (read.exitCode !== 0) {
510
+ throw controlSecretWriteFailed('kubectl get', name, connection, read, secrets);
511
+ }
512
+ let stored;
513
+ try {
514
+ stored = JSON.parse(read.stdout);
515
+ }
516
+ catch {
517
+ throw new CommandFailure('WASMCLOUD_TOOL_FAILED', `kubectl get returned a control Secret ${name} that is not JSON`, 3, { command: 'kubectl get', name });
342
518
  }
519
+ const data = {};
520
+ if (stored.data !== null && typeof stored.data === 'object') {
521
+ for (const [key, value] of Object.entries(stored.data)) {
522
+ // The API only returns strings. Anything else cannot be carried over, so fail closed.
523
+ if (typeof value !== 'string') {
524
+ throw new CommandFailure('WASMCLOUD_TOOL_FAILED', `kubectl get returned a control Secret ${name} whose ${key} is not a string`, 3, { command: 'kubectl get', name, key });
525
+ }
526
+ data[key] = value;
527
+ secrets.push(value, Buffer.from(value, 'base64').toString('utf8'));
528
+ }
529
+ }
530
+ const resourceVersion = stored.metadata?.resourceVersion;
531
+ return typeof resourceVersion === 'string' ? { data, resourceVersion } : { data };
532
+ }
533
+ /** The `tenant-secret-update` policy did not protect the Secret, so a blind update could drop keys. */
534
+ function controlSecretUnguarded(name, connection) {
535
+ return new CommandFailure('WASMCLOUD_CONTROL_SECRET_UNGUARDED', `Refusing to replace the control Secret ${name} blind: the platform accepted a dry-run ` +
536
+ 'update that drops DI_CONTROL_TOKEN, so either its tenant-secret-update policy does not ' +
537
+ 'apply to this caller or the Secret has no DI_CONTROL_TOKEN. A replace could then drop ' +
538
+ 'the declared app keys, which this caller cannot read back. Deploy as a tenant developer ' +
539
+ '(di-user-*) or as a caller that may read Secrets, or have the app tooling write ' +
540
+ `DI_CONTROL_TOKEN and DI_CONTROL_IDENTITY into ${name} in ${connection.namespace}`, 2, { name, namespace: connection.namespace });
541
+ }
542
+ /** The Secret holds declared app keys but lacks one of the CLI's keys. */
543
+ function controlSecretIncomplete(name, connection, key) {
544
+ return new CommandFailure('WASMCLOUD_CONTROL_SECRET_INCOMPLETE', `The control Secret ${name} holds declared app keys but no ${key}, so the workload would ` +
545
+ 'have no control credentials. The tooling that writes the app keys must also write ' +
546
+ 'non-empty DI_CONTROL_TOKEN and DI_CONTROL_IDENTITY (the workload name); fix the Secret, ' +
547
+ `or delete it with \`kubectl delete secret ${name} --namespace ${connection.namespace}\` and redeploy`, 2, { name, namespace: connection.namespace, key });
548
+ }
549
+ /**
550
+ * The control Secret holds keys that are neither the CLI's nor declared in `controlSecretKeys`.
551
+ * `keys` names them when the Secret could be read; a tenant developer only learns that some exist.
552
+ */
553
+ function controlSecretForeignKeys(name, connection, keys) {
554
+ const which = keys === undefined ? "keys this CLI didn't write" : `undeclared keys ${keys.join(', ')}`;
555
+ return new CommandFailure('WASMCLOUD_CONTROL_SECRET_FOREIGN_KEYS', `The control Secret ${name} has ${which}; declare app-owned keys in "controlSecretKeys" ` +
556
+ `of ${CONFIG_FILE_NAME}, or delete the Secret with ` +
557
+ `\`kubectl delete secret ${name} --namespace ${connection.namespace}\` and redeploy`, 2, { name, namespace: connection.namespace, ...(keys === undefined ? {} : { keys: [...keys] }) });
558
+ }
559
+ /**
560
+ * A failed control Secret request, with kubectl's reason. Kubernetes errors for these requests
561
+ * name the object, not its data, but the stderr is still scrubbed of `secrets` (the token raw and
562
+ * base64, and any value read from the cluster) and of credential-shaped text before it is shown,
563
+ * in case a response echoes the body.
564
+ */
565
+ function controlSecretWriteFailed(command, name, connection, result, secrets) {
566
+ const scrub = [
567
+ ...new Set(secrets.flatMap((secret) => [secret, Buffer.from(secret, 'utf8').toString('base64')])),
568
+ ]
569
+ .filter((secret) => secret.length > 0)
570
+ .sort((a, b) => b.length - a.length);
571
+ const stderr = sanitizePublicText(scrub.reduce((text, secret) => redact(text, secret), result.stderr).trim());
572
+ if (kubectlStatusReason(stderr) === 'Conflict') {
573
+ return new CommandFailure('WASMCLOUD_CONTROL_SECRET_CHANGED', `The control Secret ${name} in ${connection.namespace} changed while deploy was updating it; re-run deploy`, 3, { name, namespace: connection.namespace, command, exitCode: result.exitCode, stderr });
574
+ }
575
+ const reason = stderr.length > 0 ? `: ${stderr}` : '';
576
+ return new CommandFailure('WASMCLOUD_TOOL_FAILED', `${command} failed with exit code ${result.exitCode}${reason}`, 3, { command, exitCode: result.exitCode, stderr });
577
+ }
578
+ /** Shorter values are only redacted as whole tokens, so `on` does not blank every `json`. */
579
+ const SHORT_SECRET = 4;
580
+ const TOKEN_CHARACTER = '[A-Za-z0-9+/=_.-]';
581
+ /** `text` with every occurrence of `secret` replaced by `[redacted]`. */
582
+ function redact(text, secret) {
583
+ if (secret.length >= SHORT_SECRET)
584
+ return text.split(secret).join('[redacted]');
585
+ const escaped = secret.replace(/[.*+?^${}()|[\]\\/-]/g, '\\$&');
586
+ return text.replace(new RegExp(`(?<!${TOKEN_CHARACTER})${escaped}(?!${TOKEN_CHARACTER})`, 'g'), '[redacted]');
587
+ }
588
+ /**
589
+ * Deletes the control Secret by name. A label-selected delete would LIST Secrets and the
590
+ * default `--wait=true` would GET it afterwards, both forbidden to tenant developers.
591
+ */
592
+ export async function deleteControlSecret(project, connection, deps) {
343
593
  await runKubectl(deps, connection, [
344
- 'label',
594
+ 'delete',
345
595
  'secret',
346
- secretName,
347
- `app.kubernetes.io/managed-by=${MANAGED_BY_LABEL}`,
348
- `app.kubernetes.io/name=${name}`,
349
- '--overwrite',
596
+ controlSecretResourceName(deploymentResourceName(project)),
597
+ '--ignore-not-found',
598
+ '--wait=false',
350
599
  ], project.projectRoot);
351
- return secretName;
352
600
  }
353
601
  export async function applyWorkload(project, connection, image, io, deps) {
354
602
  const bindings = discoverBindings(project, deps);
@@ -356,7 +604,10 @@ export async function applyWorkload(project, connection, image, io, deps) {
356
604
  const isWorker = isQueueWorkerProject(project, queueHandlers);
357
605
  const hasActors = discoverActors(project).length > 0 || project.actors === true;
358
606
  const cronJobs = discoverScheduledJobs(project.projectRoot);
359
- const hasPersistentStorage = hasActors || queueHandlers.length > 0 || project.persistentStorage === true;
607
+ const hasPersistentStorage = hasActors ||
608
+ queueHandlers.length > 0 ||
609
+ project.persistentStorage === true ||
610
+ project.pglite !== undefined;
360
611
  const needsHttp = (project.ingress !== false && !isWorker) ||
361
612
  hasActors ||
362
613
  cronJobs.length > 0 ||
@@ -380,6 +631,7 @@ export async function applyWorkload(project, connection, image, io, deps) {
380
631
  source: 'workload-service',
381
632
  });
382
633
  await warnIfTenantHostLacksTls(project, connection, io, deps);
634
+ await warnIfHostIgnoresExclusive(project, connection, io, deps);
383
635
  const associations = await applyManagedBindings(project, connection, bindings, deps);
384
636
  const egress = await applyWorkloadEgress(project, connection, deps);
385
637
  if (egress !== undefined)
@@ -389,17 +641,31 @@ export async function applyWorkload(project, connection, image, io, deps) {
389
641
  hasQueues: queueHandlers.length > 0,
390
642
  hasPersistentStorage,
391
643
  });
392
- const controlSecretName = needsHttp
393
- ? await ensureControlSecret(project, connection, deps)
394
- : undefined;
395
- const manifest = renderWorkloadManifest(project, connection, image, requirements, bindings, { hasActors, hasPersistentStorage, controlSecretName }, cronJobs, queueHandlers);
396
- const path = generatedManifestPath(project);
397
- mkdirSync(join(project.projectRoot, '.di-framework', 'deploy'), { recursive: true });
398
- writeFileSync(path, manifest);
399
- const name = deploymentResourceName(project);
400
- io.stdout.write(`Applying WorkloadDeployment ${name} in ${connection.namespace}...\n`);
401
- await runKubectl(deps, connection, ['apply', '-f', path], project.projectRoot);
402
- await waitForReady(project, connection, deps, io);
644
+ const controlSecret = needsHttp ? await writeControlSecret(project, connection, deps) : undefined;
645
+ if (controlSecret !== undefined && controlSecret.revision === undefined) {
646
+ io.stdout.write(`Kept control Secret ${controlSecret.name}: it holds declared app keys this deploy cannot read, so the control token was not rotated\n`);
647
+ }
648
+ // From here on the cron invokers already use the new token, which the running workload
649
+ // rejects until it rolls out with this manifest.
650
+ let path;
651
+ try {
652
+ const manifest = renderWorkloadManifest(project, connection, image, requirements, bindings, {
653
+ hasActors,
654
+ hasPersistentStorage,
655
+ controlSecretName: controlSecret?.name,
656
+ controlTokenRevision: controlSecret?.revision,
657
+ }, cronJobs, queueHandlers);
658
+ path = generatedManifestPath(project);
659
+ mkdirSync(join(project.projectRoot, '.di-framework', 'deploy'), { recursive: true });
660
+ writeFileSync(path, manifest);
661
+ const name = deploymentResourceName(project);
662
+ io.stdout.write(`Applying WorkloadDeployment ${name} in ${connection.namespace}...\n`);
663
+ await runKubectl(deps, connection, ['apply', '-f', path], project.projectRoot);
664
+ await waitForReady(project, connection, deps, io);
665
+ }
666
+ catch (error) {
667
+ throw controlSecret?.revision === undefined ? error : withRotatedTokenNotice(error);
668
+ }
403
669
  await cleanupManagedBindings(project, connection, associations, deps);
404
670
  if (egress === undefined)
405
671
  await removeWorkloadEgress(project, connection, deps);
@@ -407,6 +673,18 @@ export async function applyWorkload(project, connection, image, io, deps) {
407
673
  await reportEgressStatus(project, connection, io, deps);
408
674
  return path;
409
675
  }
676
+ /**
677
+ * A deploy that fails after the control Secret was written leaves the running workload on the
678
+ * old token while its cron invokers (which read the Secret when they start) carry the new one,
679
+ * so every cron invocation is refused until a deploy succeeds. Say so in the failure.
680
+ */
681
+ function withRotatedTokenNotice(error) {
682
+ if (!isCommandFailure(error))
683
+ return error;
684
+ // Every failure on this path (kubectl, readiness) carries an object of details.
685
+ const details = error.details;
686
+ return new CommandFailure(error.code, `${error.message}; ${CONTROL_TOKEN_ROTATED_NOTICE}`, error.exitCode, { ...details, controlTokenRotated: true });
687
+ }
410
688
  async function assertStorageOwnership(project, connection, deps, flags) {
411
689
  if (!flags.hasActors && !flags.hasQueues && !flags.hasPersistentStorage)
412
690
  return;
@@ -441,13 +719,15 @@ export async function deleteWorkload(project, connection, io, deps) {
441
719
  io.stdout.write(`Removing WorkloadDeployment ${name} from ${connection.namespace}...\n`);
442
720
  await runKubectl(deps, connection, [
443
721
  'delete',
444
- `${WORKLOAD_DEPLOYMENT_RESOURCE},service,cronjob,secret`,
722
+ `${WORKLOAD_DEPLOYMENT_RESOURCE},service,cronjob`,
445
723
  '-l',
446
724
  `app.kubernetes.io/name=${name}`,
447
725
  '--ignore-not-found',
448
726
  '--wait=true',
449
727
  '--timeout=180s',
450
728
  ], project.projectRoot);
729
+ // After the workload and its cron invokers are gone, so nothing still mounts the token.
730
+ await deleteControlSecret(project, connection, deps);
451
731
  await cleanupManagedBindings(project, connection, new Set(), deps);
452
732
  await removeWorkloadEgress(project, connection, deps);
453
733
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@di-framework/cli-plugin-platform",
3
- "version": "6.1.1",
3
+ "version": "6.2.0",
4
4
  "description": "di-framework CLI extension that builds, serves, and deploys DI Framework apps as platform WebAssembly components.",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -41,7 +41,7 @@
41
41
  "dependencies": {
42
42
  "@bytecodealliance/jco": "1.33.0",
43
43
  "@di-framework/cli-extension": "^5",
44
- "@di-framework/componentize-qjs": "0.4.4-di.4",
44
+ "@di-framework/componentize-qjs": "0.4.4-di.5",
45
45
  "@noble/ciphers": "2.4.0",
46
46
  "@noble/curves": "2.4.0",
47
47
  "@noble/hashes": "2.4.0",