@di-framework/cli-plugin-platform 6.1.2 → 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.
package/dist/project.js CHANGED
@@ -2,9 +2,42 @@ import { accessSync, constants, existsSync, readFileSync, realpathSync } from 'n
2
2
  import { isIP } from 'node:net';
3
3
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
4
4
  import { CommandFailure } from '@di-framework/cli-extension';
5
+ import { RENDERED_ENVIRONMENT_KEYS } from './environment-names.js';
5
6
  import { parsePgliteConfig } from './pglite.js';
6
7
  import { discoverWorkloadEntry } from './workload-members.js';
7
8
  export const CONFIG_FILE_NAME = 'di-framework.config.json';
9
+ /** A key the control Secret may carry for the app: an environment variable name. */
10
+ const CONTROL_SECRET_KEY = /^[A-Za-z_][A-Za-z0-9_]{0,252}$/;
11
+ /**
12
+ * The `DI_*` keys a project may declare. Every other `DI_*` name belongs to the framework: the CLI
13
+ * owns it in the control Secret or renders it into the workload's environment config, and a
14
+ * Secret key must not shadow either.
15
+ */
16
+ const DECLARABLE_DI_KEYS = ['DI_PGLITE_KEY', 'DI_PGLITE_KEY_PREVIOUS'];
17
+ /** Why `name` cannot be declared in `controlSecretKeys`, or undefined when it can. */
18
+ export function controlSecretKeyProblem(name) {
19
+ if (typeof name !== 'string' || !CONTROL_SECRET_KEY.test(name))
20
+ return `${JSON.stringify(name)} is not an environment variable name`;
21
+ if (name.startsWith('DI_') && !DECLARABLE_DI_KEYS.includes(name))
22
+ return `${name} is reserved for the framework; of the DI_* names only ${DECLARABLE_DI_KEYS.join(' and ')} may be declared`;
23
+ if (RENDERED_ENVIRONMENT_KEYS.includes(name))
24
+ return `${name} is rendered by the CLI`;
25
+ return undefined;
26
+ }
27
+ function parseControlSecretKeys(value, configPath) {
28
+ if (value === undefined)
29
+ return undefined;
30
+ if (!Array.isArray(value))
31
+ configInvalid(`${CONFIG_FILE_NAME} "controlSecretKeys" must be an array of names`, configPath);
32
+ for (const [index, name] of value.entries()) {
33
+ const problem = controlSecretKeyProblem(name);
34
+ if (problem !== undefined)
35
+ configInvalid(`${CONFIG_FILE_NAME} "controlSecretKeys"[${index}]: ${problem}`, configPath);
36
+ if (value.indexOf(name) !== index)
37
+ configInvalid(`${CONFIG_FILE_NAME} "controlSecretKeys" repeats ${name}`, configPath);
38
+ }
39
+ return value.length > 0 ? [...value] : undefined;
40
+ }
8
41
  export function findUp(startDirectory, fileName) {
9
42
  let previous = '';
10
43
  let current = resolve(startDirectory);
@@ -123,6 +156,7 @@ export function loadProject(startDirectory) {
123
156
  const cronMode = config.cronMode === 'external' ? 'external' : undefined;
124
157
  const persistentStorage = config.persistentStorage === true;
125
158
  const pglite = parsePgliteConfig(config.pglite, configPath, (path) => resolveRealInside(projectRoot, path, 'pglite.wasm', configPath));
159
+ const controlSecretKeys = parseControlSecretKeys(config.controlSecretKeys, configPath);
126
160
  return {
127
161
  applicationName: config.name,
128
162
  ...(workload ? { workload, workloadEntry } : {}),
@@ -131,6 +165,7 @@ export function loadProject(startDirectory) {
131
165
  ...(persistentStorage ? { persistentStorage: true } : {}),
132
166
  ...(config.logs === false ? { logs: false } : {}),
133
167
  ...(pglite ? { pglite } : {}),
168
+ ...(controlSecretKeys ? { controlSecretKeys } : {}),
134
169
  ...(config.allowedIpNameLookups === undefined
135
170
  ? {}
136
171
  : { allowedIpNameLookups: config.allowedIpNameLookups }),
@@ -91,21 +91,43 @@ export interface WorkloadManifestOptions {
91
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
92
  /** Appended to a deploy failure that happened after the control Secret was rewritten. */
93
93
  export declare const CONTROL_TOKEN_ROTATED_NOTICE = "the control token was rotated; re-run deploy to roll the workload onto it";
94
- /** Control Secret written on deploy: its name and a digest that identifies the token. */
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
+ */
95
98
  export type ControlSecretWrite = {
96
99
  name: string;
97
- revision: string;
100
+ revision?: string;
98
101
  };
99
- /** The full control Secret the CLI owns; nothing in it is read back from the cluster. */
100
- export declare function controlSecretDocument(workloadName: string, namespace: string, token: string): Record<string, unknown>;
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>;
101
110
  /**
102
- * Tenant developers may create, update and delete Secrets but never get, list, watch or
103
- * patch them (platform#112). The control Secret is therefore written blind: POST the full
104
- * document and, if it already exists, PUT the same document without a resourceVersion. A
105
- * Secret allows such an unconditional update, so no read is needed to learn the version,
106
- * and the Secret never disappears the way delete-then-create would make it. Both requests
107
- * go through `--raw` because `kubectl replace -f` GETs the object first to fill in its
108
- * resourceVersion. The token is regenerated on every deploy since the old one cannot be read.
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.
109
131
  */
110
132
  export declare function writeControlSecret(project: WasmcloudProject, connection: ClusterConnection, deps: WasmcloudDeps): Promise<ControlSecretWrite>;
111
133
  /**
package/dist/workload.js CHANGED
@@ -12,7 +12,7 @@ import { hostInterfacesFromRequirements, renderHostInterfacesYaml } from './host
12
12
  import { captureKubectl, runKubectl } from './kubernetes.js';
13
13
  import { applyManagedBindings, cleanupManagedBindings } from './managed-bindings.js';
14
14
  import { EXCLUSIVE_INSTANCE_KEY, isWithin, PGLITE_DATA_DIR_ENV, warnIfHostIgnoresExclusive, } from './pglite.js';
15
- import { asWitIdentifier } from './project.js';
15
+ import { asWitIdentifier, CONFIG_FILE_NAME } from './project.js';
16
16
  import { discoverQueueHandlers, isQueueWorkerProject } from './queues.js';
17
17
  import { kubectlStatusReason, SECRET_UPDATE_KEYS_MESSAGE } from './secret-admission.js';
18
18
  import { defaultProjectRequirements, guestLoggingRequirement, queueProjectRequirements, } from './wit.js';
@@ -350,8 +350,14 @@ ${labels.replace(/^/gm, ' ')}
350
350
  }
351
351
  /** Appended to a deploy failure that happened after the control Secret was rewritten. */
352
352
  export const CONTROL_TOKEN_ROTATED_NOTICE = 'the control token was rotated; re-run deploy to roll the workload onto it';
353
- /** The full control Secret the CLI owns; nothing in it is read back from the cluster. */
354
- export function controlSecretDocument(workloadName, namespace, token) {
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) {
355
361
  const encode = (value) => Buffer.from(value, 'utf8').toString('base64');
356
362
  return {
357
363
  apiVersion: 'v1',
@@ -363,9 +369,11 @@ export function controlSecretDocument(workloadName, namespace, token) {
363
369
  'app.kubernetes.io/managed-by': MANAGED_BY_LABEL,
364
370
  'app.kubernetes.io/name': workloadName,
365
371
  },
372
+ ...(resourceVersion === undefined ? {} : { resourceVersion }),
366
373
  },
367
374
  type: 'Opaque',
368
375
  data: {
376
+ ...appData,
369
377
  DI_CONTROL_TOKEN: encode(token),
370
378
  DI_CONTROL_IDENTITY: encode(workloadName),
371
379
  },
@@ -376,56 +384,207 @@ function secretsPath(namespace, name) {
376
384
  return name === undefined ? collection : `${collection}/${encodeURIComponent(name)}`;
377
385
  }
378
386
  /**
379
- * Tenant developers may create, update and delete Secrets but never get, list, watch or
380
- * patch them (platform#112). The control Secret is therefore written blind: POST the full
381
- * document and, if it already exists, PUT the same document without a resourceVersion. A
382
- * Secret allows such an unconditional update, so no read is needed to learn the version,
383
- * and the Secret never disappears the way delete-then-create would make it. Both requests
384
- * go through `--raw` because `kubectl replace -f` GETs the object first to fill in its
385
- * resourceVersion. The token is regenerated on every deploy since the old one cannot be read.
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.
386
407
  */
387
408
  export async function writeControlSecret(project, connection, deps) {
388
409
  const workloadName = deploymentResourceName(project);
389
410
  const name = controlSecretResourceName(workloadName);
411
+ const declared = project.controlSecretKeys ?? [];
390
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];
391
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);
392
427
  try {
393
- const path = join(directory, 'secret.json');
394
- writeFileSync(path, JSON.stringify(controlSecretDocument(workloadName, connection.namespace, token)), { mode: 0o600 });
395
- const created = await captureKubectl(deps, connection, ['create', '--raw', secretsPath(connection.namespace), '-f', path], project.projectRoot);
396
- if (created.exitCode !== 0) {
397
- if (kubectlStatusReason(created.stderr) !== 'AlreadyExists') {
398
- throw controlSecretWriteFailed('kubectl create', name, connection, created, token);
399
- }
400
- const replaced = await captureKubectl(deps, connection, ['replace', '--raw', secretsPath(connection.namespace, name), '-f', path], project.projectRoot);
401
- if (replaced.exitCode !== 0) {
402
- throw controlSecretWriteFailed('kubectl replace', name, connection, replaced, token);
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);
403
490
  }
404
491
  }
492
+ return { name };
405
493
  }
406
494
  finally {
407
495
  rmSync(directory, { recursive: true, force: true });
408
496
  }
409
- return { name, revision: createHash('sha256').update(token).digest('hex').slice(0, 16) };
410
497
  }
411
498
  /**
412
- * A failed control Secret write, with kubectl's reason. Kubernetes errors for these requests
413
- * name the object, not its data, but the stderr is still scrubbed of the token (raw and
414
- * base64) and of credential-shaped text before it is shown, in case a response echoes the body.
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.
415
503
  */
416
- function controlSecretWriteFailed(command, name, connection, result, token) {
417
- const stderr = sanitizePublicText([token, Buffer.from(token, 'utf8').toString('base64')]
418
- .reduce((text, secret) => text.split(secret).join('[redacted]'), result.stderr)
419
- .trim());
420
- if (stderr.includes(SECRET_UPDATE_KEYS_MESSAGE)) {
421
- // The platform's `tenant-secret-update` policy refuses a replace that drops a key, so a
422
- // control Secret someone added keys to can no longer be rotated in place.
423
- return new CommandFailure('WASMCLOUD_CONTROL_SECRET_FOREIGN_KEYS', `The control Secret ${name} has keys this CLI didn't write; delete it with ` +
424
- `\`kubectl delete secret ${name} --namespace ${connection.namespace}\` and redeploy`, 2, { name, namespace: connection.namespace, command, exitCode: result.exitCode, stderr });
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 });
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 });
425
574
  }
426
575
  const reason = stderr.length > 0 ? `: ${stderr}` : '';
427
576
  return new CommandFailure('WASMCLOUD_TOOL_FAILED', `${command} failed with exit code ${result.exitCode}${reason}`, 3, { command, exitCode: result.exitCode, stderr });
428
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
+ }
429
588
  /**
430
589
  * Deletes the control Secret by name. A label-selected delete would LIST Secrets and the
431
590
  * default `--wait=true` would GET it afterwards, both forbidden to tenant developers.
@@ -483,6 +642,9 @@ export async function applyWorkload(project, connection, image, io, deps) {
483
642
  hasPersistentStorage,
484
643
  });
485
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
+ }
486
648
  // From here on the cron invokers already use the new token, which the running workload
487
649
  // rejects until it rolls out with this manifest.
488
650
  let path;
@@ -502,7 +664,7 @@ export async function applyWorkload(project, connection, image, io, deps) {
502
664
  await waitForReady(project, connection, deps, io);
503
665
  }
504
666
  catch (error) {
505
- throw controlSecret === undefined ? error : withRotatedTokenNotice(error);
667
+ throw controlSecret?.revision === undefined ? error : withRotatedTokenNotice(error);
506
668
  }
507
669
  await cleanupManagedBindings(project, connection, associations, deps);
508
670
  if (egress === undefined)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@di-framework/cli-plugin-platform",
3
- "version": "6.1.2",
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",