@olivervea/pipelines 2.0.0-beta.30 → 2.0.0-beta.32

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/README.md CHANGED
@@ -333,6 +333,7 @@ This section is everything the C# side needs in order to run the binary.
333
333
  | `OLVE_RUN` | run | Run number (integer ≥ 0). Written into produced file refs. Default 0. |
334
334
  | `OLVE_ATTEMPT` | run | Attempt number (integer ≥ 1). Written into produced file refs. Default 1. |
335
335
  | `OLVE_VERSION_STAMP` | run | Derived version, e.g. `2026.10.21.412` → `ctx.run.version`. |
336
+ | `OLVE_SECRETS` | run | The step's declared secret names, comma-separated: the values the binary masks in its output (above). Unset or empty: no masking. |
336
337
  | `OLVE_CELL` | run | Only for a matrix step: the cell, as compact JSON in axis order (`{"os":"linux","arch":"x64"}`) → `ctx.cell`. Missing, or not one of the step's cells → exit 65. `ctx.run.step` and produced file refs carry the cell's name, `build-cli[os=linux,arch=x64]`. |
337
338
  | `OLVE_CASES` | run | Only for a step inside a `select`: a JSON array of the case conditions it sits in (`["target.prod.kind=ssh"]`); `run <step>` uses it to pick the variant of a name several cases use. |
338
339
  | `<SECRET_NAME>` | per step | Each declared secret as an env var of the **same name**: `secretKeyRef` key = name. Mount only the step's `secrets` (for poll triggers, the poll's `secrets`). Child processes inherit them. The mount is optional: an unset secret leaves the variable unset and `ctx.secrets.<NAME>` throws on access, so a handler can check `process.env.<NAME>` first and skip. |
@@ -344,6 +345,10 @@ This section is everything the C# side needs in order to run the binary.
344
345
 
345
346
  `OLVE_RESULT_URL`, `OLVE_FILE_URLS`, `OLVE_FILES_TOKEN` and `OLVE_CALLBACK_URLS` are removed from the environment of child processes. URLs are never logged past `?`.
346
347
 
348
+ **Secret masking** (`run`): with `OLVE_SECRETS` set, the binary runs the step as its own child and replaces every value of those secrets with `***` in the child's stdout and stderr, a line at a time, from the pipeline's first import to its exit. That covers every way of printing: logs, `console`, direct writes, commands and the processes they start. The envelope's failure message, skip reason and links are masked too; outputs and files are data and aren't. A multi-line value is masked line by line, and values (or lines) shorter than 4 characters are left alone. Not masked: a value the step transforms before printing (escaped, encoded, cut short) and a process writing to the pod's stdout directly (`/proc/1/fd/1`).
349
+
350
+ An error nothing catches (a rejected promise, a throw in a timer) fails the step.
351
+
347
352
  `ctx.files.fetch` looks for a file in this order:
348
353
 
349
354
  1. the attempt's own `work/files`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@olivervea/pipelines",
3
- "version": "2.0.0-beta.30",
3
+ "version": "2.0.0-beta.32",
4
4
  "description": "Olve.Pipelines v2 SDK: typed pipeline authoring, the step harness, and the build tool.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -61,8 +61,11 @@ export function generateEntry(
61
61
  writeFileSync(
62
62
  entry,
63
63
  `// GENERATED by olve-build — do not edit. Entry point of the step binary.\n` +
64
- `import pipeline from ${JSON.stringify(relPosix(gen, project.pipelineFile))};\n` +
65
- `import { runHarness } from "@olivervea/pipelines/harness";\n\n` +
64
+ `import { runHarness, supervise } from "@olivervea/pipelines/harness";\n\n` +
65
+ `// Secret masking starts before the pipeline's code runs: the masked child imports it.\n` +
66
+ `const supervised = await supervise(process.argv.slice(2));\n` +
67
+ `if (supervised !== undefined) process.exit(supervised);\n` +
68
+ `const { default: pipeline } = await import(${JSON.stringify(relPosix(gen, project.pipelineFile))});\n` +
66
69
  `process.exit(await runHarness(${config}, process.argv.slice(2)));\n`,
67
70
  );
68
71
  return entry;
@@ -7,6 +7,7 @@ export {
7
7
  type HarnessIO,
8
8
  } from './main.ts';
9
9
  export { EXIT } from './exit.ts';
10
+ export { supervise } from './supervise.ts';
10
11
  export { ENV, paths, runInfoFromEnv } from './env.ts';
11
12
  export {
12
13
  executeStep,
@@ -8,6 +8,7 @@ import { isImplementation } from '../core/handlers.ts';
8
8
  import { configRefPath, isConfigRef, unionAt } from '../core/config.ts';
9
9
  import type { AnyStep } from '../core/steps.ts';
10
10
  import { cellName, parseCell } from '../core/matrix.ts';
11
+ import { maskEnvelope, maskPatterns } from './mask.ts';
11
12
  import type { WebhookEvent } from '../core/webhooks.ts';
12
13
  import { pipelineData, type PipelineData, type StageNode } from '../builder/pipeline.ts';
13
14
  import { createCtx, formatLog } from '../ctx/index.ts';
@@ -198,6 +199,12 @@ async function runMode(
198
199
  ? parseCell(step.name, step.matrix, process.env[ENV.cell])
199
200
  : undefined;
200
201
  const cancel = cancellation();
202
+ const masks = maskPatterns(step.secrets.map((s) => process.env[s.name]));
203
+ // An error nothing caught (a rejected promise, a throw in a timer) fails the step.
204
+ let uncaught: unknown;
205
+ const onUncaught = (e: unknown) => void (uncaught ??= e);
206
+ process.on('unhandledRejection', onUncaught);
207
+ process.on('uncaughtException', onUncaught);
201
208
  try {
202
209
  let exec: Execution;
203
210
  if (!raw.ok || (cell && !cell.ok)) {
@@ -227,8 +234,18 @@ async function runMode(
227
234
  log: io.stderr,
228
235
  });
229
236
  }
230
- return await finish(exec, io);
237
+ if (uncaught !== undefined && exec.envelope.status !== 'failed') {
238
+ const message = `step '${step.name}' failed: an error nothing caught: ${uncaught instanceof Error ? uncaught.message : String(uncaught)}`;
239
+ io.stderr(message);
240
+ exec = {
241
+ envelope: { status: 'failed', error: { kind: 'handler', message } },
242
+ exitCode: EXIT.handlerFailed,
243
+ };
244
+ }
245
+ return await finish({ ...exec, envelope: maskEnvelope(exec.envelope, masks) }, io);
231
246
  } finally {
247
+ process.off('unhandledRejection', onUncaught);
248
+ process.off('uncaughtException', onUncaught);
232
249
  cancel.dispose();
233
250
  }
234
251
  }
@@ -0,0 +1,76 @@
1
+ import type { Envelope } from './execute.ts';
2
+
3
+ /**
4
+ * Masks secret values in text: a stream a line at a time, so a value split across two writes is
5
+ * still found; a multi-line value (a key file) line by line.
6
+ */
7
+
8
+ export const MASK = '***';
9
+ /** Shorter values (and lines of multi-line values) are left alone: they would mask ordinary text. */
10
+ export const MIN_MASKED_LENGTH = 4;
11
+ /** A line longer than this is masked and written without waiting for its end. */
12
+ const MAX_PENDING = 64 * 1024;
13
+
14
+ /** The strings to mask for these secret values, longest first. */
15
+ export function maskPatterns(values: readonly (string | undefined)[]): string[] {
16
+ const patterns = new Set<string>();
17
+ for (const value of values)
18
+ for (const line of (value ?? '').split(/\r\n|\r|\n/))
19
+ if (line.trim().length >= MIN_MASKED_LENGTH) patterns.add(line.trim());
20
+ return [...patterns].sort((a, b) => b.length - a.length);
21
+ }
22
+
23
+ export function maskText(text: string, patterns: readonly string[]): string {
24
+ let out = text;
25
+ for (const p of patterns) if (out.includes(p)) out = out.split(p).join(MASK);
26
+ return out;
27
+ }
28
+
29
+ /** A writer that masks complete lines and holds back the unfinished one until it ends or `flush`. */
30
+ export function lineMasker(patterns: readonly string[], write: (text: string) => void) {
31
+ const decoder = new TextDecoder();
32
+ let pending = '';
33
+ return {
34
+ write(chunk: string | Uint8Array) {
35
+ pending +=
36
+ typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
37
+ const end = Math.max(pending.lastIndexOf('\n'), pending.lastIndexOf('\r'));
38
+ if (end >= 0) {
39
+ write(maskText(pending.slice(0, end + 1), patterns));
40
+ pending = pending.slice(end + 1);
41
+ }
42
+ if (pending.length > MAX_PENDING) {
43
+ // Keep enough back that a value cut here is whole in what follows.
44
+ const keep = Math.max(0, (patterns[0]?.length ?? 1) - 1);
45
+ write(maskText(pending.slice(0, pending.length - keep), patterns));
46
+ pending = pending.slice(pending.length - keep);
47
+ }
48
+ },
49
+ flush() {
50
+ pending += decoder.decode();
51
+ if (pending) write(maskText(pending, patterns));
52
+ pending = '';
53
+ },
54
+ };
55
+ }
56
+
57
+ /** The envelope with its failure message or skip reason masked; outputs are data and stay as they are. */
58
+ export function maskEnvelope(envelope: Envelope, patterns: readonly string[]): Envelope {
59
+ if (envelope.links)
60
+ envelope = {
61
+ ...envelope,
62
+ links: envelope.links.map((l) => ({
63
+ ...l,
64
+ url: maskText(l.url, patterns),
65
+ ...(l.label !== undefined ? { label: maskText(l.label, patterns) } : {}),
66
+ })),
67
+ };
68
+ if (envelope.status === 'failed')
69
+ return {
70
+ ...envelope,
71
+ error: { ...envelope.error, message: maskText(envelope.error.message, patterns) },
72
+ };
73
+ if (envelope.status === 'skipped')
74
+ return { ...envelope, reason: maskText(envelope.reason, patterns) };
75
+ return envelope;
76
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Secret masking for `run`: when the service names the step's secrets (`OLVE_SECRETS`), the binary
3
+ * runs itself as a child and masks the child's stdout and stderr bytes, so every way of printing is
4
+ * covered, from the pipeline's first import to its last timer. It runs before the pipeline module
5
+ * is imported.
6
+ */
7
+ import { readFileSync } from 'node:fs';
8
+ import { constants } from 'node:os';
9
+ import { lineMasker, maskPatterns } from './mask.ts';
10
+
11
+ const SUPERVISED = 'OLVE_SUPERVISED';
12
+ const FORWARDED = ['SIGTERM', 'SIGINT', 'SIGHUP'] as const;
13
+
14
+ /** The secret values this run must not print, from `OLVE_SECRETS` (names, comma-separated). */
15
+ export function secretPatterns(env: NodeJS.ProcessEnv = process.env): string[] {
16
+ const names = (env.OLVE_SECRETS ?? '').split(',').filter(Boolean);
17
+ return maskPatterns(names.map((n) => env[n]));
18
+ }
19
+
20
+ /** This process's own command line, loader included (`ld-linux … /olve/step run x` in a pod). */
21
+ function ownArgv(): string[] {
22
+ try {
23
+ const argv = readFileSync('/proc/self/cmdline', 'utf8').split('\0').filter(Boolean);
24
+ if (argv.length > 0) return argv;
25
+ } catch {
26
+ // not Linux
27
+ }
28
+ return [process.execPath, ...process.argv.slice(1)];
29
+ }
30
+
31
+ /**
32
+ * Runs the step as a masked child and answers its exit code, or undefined when this process should
33
+ * run the step itself: it is the child, the mode isn't `run`, or there is nothing to mask.
34
+ */
35
+ export async function supervise(argv: readonly string[]): Promise<number | undefined> {
36
+ if (argv[0] !== 'run' || process.env[SUPERVISED]) return undefined;
37
+ const patterns = secretPatterns();
38
+ if (patterns.length === 0) return undefined;
39
+
40
+ const child = Bun.spawn(ownArgv(), {
41
+ env: { ...process.env, [SUPERVISED]: '1' },
42
+ stdin: 'inherit',
43
+ stdout: 'pipe',
44
+ stderr: 'pipe',
45
+ });
46
+ const forward = (signal: NodeJS.Signals) => () => child.kill(signal);
47
+ for (const s of FORWARDED) process.on(s, forward(s));
48
+
49
+ const pump = async (stream: ReadableStream<Uint8Array>, fd: 1 | 2) => {
50
+ const out = fd === 1 ? process.stdout : process.stderr;
51
+ const masker = lineMasker(patterns, (text) => void out.write(text));
52
+ for await (const chunk of stream) masker.write(chunk);
53
+ masker.flush();
54
+ };
55
+ const pumps = Promise.all([pump(child.stdout, 1), pump(child.stderr, 2)]);
56
+ await child.exited;
57
+ // A detached grandchild may hold the pipes open: don't wait for it long.
58
+ await Promise.race([pumps, Bun.sleep(5000)]);
59
+ const signal = child.signalCode
60
+ ? constants.signals[child.signalCode as NodeJS.Signals]
61
+ : undefined;
62
+ return child.exitCode ?? (signal ? 128 + signal : 1);
63
+ }