@bakers-build/core 0.14.0 → 0.14.1-next.2

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.
@@ -4,6 +4,7 @@ import { dirname, join, resolve } from 'node:path';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { shellQuote } from '../core/shell.js';
6
6
  import { findConfigProjectBbDir, homeBbDir, stemForConfigFile, } from './bakers-dir.js';
7
+ import { protectedPathProblems } from './config-protected-paths.js';
7
8
  import { configRecheckCommand, finalizeConfigReport, } from './config-report.js';
8
9
  import { inspectConfigSource, } from './config-source.js';
9
10
  import { checkConfigText } from './config-validate.js';
@@ -390,6 +391,12 @@ export function inventoryConfig(options = {}) {
390
391
  });
391
392
  }
392
393
  }
394
+ if (kind === 'project' && projectRoot) {
395
+ const flagged = new Set(report.findings.slice(startFindings).map((finding) => finding.key));
396
+ for (const problem of protectedPathProblems(source, sources.get(machinePath), projectRoot))
397
+ if (!flagged.has(problem.key))
398
+ add('invalid_value', problem.key, problem.expected, problem.remediation, 'schema', 'error', problem.property);
399
+ }
393
400
  const findings = report.findings.slice(startFindings);
394
401
  if (findings.some((finding) => finding.severity === 'error'))
395
402
  file.state = 'partial';
@@ -0,0 +1,9 @@
1
+ import type { ConfigSourceInspection, ConfigSourceProperty } from './config-source.js';
2
+ export interface ProtectedPathProblem {
3
+ key: string;
4
+ expected: string;
5
+ remediation: string;
6
+ property: ConfigSourceProperty;
7
+ }
8
+ /** Statically visible faults the conductor would refuse at start or dispatch. */
9
+ export declare function protectedPathProblems(project: ConfigSourceInspection, machine: ConfigSourceInspection | undefined, projectRoot: string): ProtectedPathProblem[];
@@ -0,0 +1,59 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { unprotectedEntryPoints } from '../core/host-commands.js';
4
+ const DOCS = 'https://bakers.build/provision/hooks#protect-host-executed-files';
5
+ const staticStrings = (source, pattern) => [...(source?.properties.values() ?? [])].filter((p) => pattern.test(p.key) &&
6
+ p.staticallyDetermined &&
7
+ typeof p.value === 'string');
8
+ /**
9
+ * shortcut: offline cannot import addons to read `isolates`, so any catalog
10
+ * runtime or `addon-runtime-*` addon counts as isolating (every shipped one
11
+ * does); upgrade once runtime addons declare `isolates` in package metadata.
12
+ */
13
+ function isolating(project, machine) {
14
+ const machineRuntime = staticStrings(machine, /^runtime\.catalog\[\d+\]\.use$/).length > 0 ||
15
+ staticStrings(machine, /^addons\[\d+\](\.use)?$/).some((p) => String(p.value).includes('addon-runtime-'));
16
+ if (!machineRuntime)
17
+ return false;
18
+ if (!project.properties.has('runtime.enabled'))
19
+ return true;
20
+ return staticStrings(project, /^runtime\.enabled\[\d+\]$/).some((p) => p.value !== 'system');
21
+ }
22
+ /** Statically visible faults the conductor would refuse at start or dispatch. */
23
+ export function protectedPathProblems(project, machine, projectRoot) {
24
+ const problems = [];
25
+ const readOnly = staticStrings(project, /^runtime\.read_only\[\d+\]$/);
26
+ for (const property of readOnly) {
27
+ if (!existsSync(join(projectRoot, String(property.value))))
28
+ problems.push({
29
+ key: property.key,
30
+ expected: `runtime.read_only path ${property.value} exists in ${projectRoot}`,
31
+ remediation: `Create ${property.value} in ${projectRoot} or remove it from runtime.read_only.`,
32
+ property,
33
+ });
34
+ }
35
+ // A computed runtime block hides read_only or enabled: judge no hook against a guess.
36
+ const runtimeComputed = project.unknownKeys ||
37
+ [...project.properties.values()].some((p) => (p.key === 'runtime' ||
38
+ p.key.startsWith('runtime.read_only') ||
39
+ p.key.startsWith('runtime.enabled')) &&
40
+ !p.staticallyDetermined);
41
+ if (runtimeComputed || !isolating(project, machine))
42
+ return problems;
43
+ const commands = new Map();
44
+ for (const property of staticStrings(project, /^hooks\.[^.[\]]+(\.[^.[\]]+)?(\.command)?$/)) {
45
+ // Only `hooks.<name>.<key>.command` is an entry's field; `hooks.<name>.command` is an entry.
46
+ const key = property.key.split('.').length === 4
47
+ ? property.key.replace(/\.command$/, '')
48
+ : property.key;
49
+ commands.set(key, property);
50
+ }
51
+ for (const { key, roots } of unprotectedEntryPoints([...commands].map(([key, p]) => [key, String(p.value)]), readOnly.map((p) => String(p.value))))
52
+ problems.push({
53
+ key,
54
+ expected: `${key}: under an isolating runtime a host command starts with a script in a protected path (${roots.join(', ')})`,
55
+ remediation: `Move the command into a script under .bakers (or a runtime.read_only path) and call it with bash; see ${DOCS}.`,
56
+ property: commands.get(key),
57
+ });
58
+ return problems;
59
+ }
@@ -0,0 +1,12 @@
1
+ /** The script a host command starts: its first word, or the word after `bash`, `sh` or `node`. */
2
+ export declare function hostCommandEntry(command: string): string | undefined;
3
+ /**
4
+ * The `[key, command]` pairs whose entry point lies outside `.bakers` and
5
+ * `protectedPaths`, with the roots they were checked against. Only the entry
6
+ * is checked: what that script calls is the project's responsibility.
7
+ */
8
+ export declare function unprotectedEntryPoints(commands: Iterable<readonly [key: string, command: string]>, protectedPaths: readonly string[]): {
9
+ key: string;
10
+ command: string;
11
+ roots: string[];
12
+ }[];
@@ -0,0 +1,29 @@
1
+ // Under an isolating runtime the host runs only code the run cannot write:
2
+ // every project hook and provision command must start in a protected path.
3
+ import { posix } from 'node:path';
4
+ const INTERPRETERS = new Set(['bash', 'sh', 'node']);
5
+ /** The script a host command starts: its first word, or the word after `bash`, `sh` or `node`. */
6
+ export function hostCommandEntry(command) {
7
+ const [first, second] = command
8
+ .trim()
9
+ .split(/[\s;&|]+/)
10
+ .filter(Boolean);
11
+ return first !== undefined && INTERPRETERS.has(first) ? second : first;
12
+ }
13
+ /**
14
+ * The `[key, command]` pairs whose entry point lies outside `.bakers` and
15
+ * `protectedPaths`, with the roots they were checked against. Only the entry
16
+ * is checked: what that script calls is the project's responsibility.
17
+ */
18
+ export function unprotectedEntryPoints(commands, protectedPaths) {
19
+ const roots = ['.bakers', ...protectedPaths].map((path) => posix.normalize(path));
20
+ const found = [];
21
+ for (const [key, command] of commands) {
22
+ const entry = hostCommandEntry(command);
23
+ const path = entry === undefined ? undefined : posix.normalize(entry);
24
+ if (path === undefined ||
25
+ !roots.some((root) => path === root || path.startsWith(`${root}/`)))
26
+ found.push({ key, command, roots });
27
+ }
28
+ return found;
29
+ }
@@ -65,16 +65,18 @@ export type VerifyOutcome = {
65
65
  */
66
66
  export declare function verifyConductorProcess(input: VerifyProcessInput): VerifyOutcome;
67
67
  export declare function signalVerifiedProcess(input: SignalVerifiedInput): SignalOutcome;
68
+ /** Runs a command and returns its stdout; throws on a non-zero exit. */
69
+ export type RunCommand = (file: string, args: string[]) => string;
68
70
  /**
69
71
  * The real probe: `/proc/<pid>/cmdline` and the owning uid of `/proc/<pid>`
70
- * itself on Linux.
72
+ * on Linux; one `ps -ww -o uid= -o command= -p <pid>` line on macOS (`-ww`
73
+ * keeps the command untruncated, so the markers are always in it).
71
74
  *
72
- * Only Linux is claimed as supported. macOS could shell out to `ps`, but a
73
- * wrong answer here signals the wrong process, so an unimplemented platform
74
- * reports `supported: false` and stop degrades with a message rather than
75
- * guessing. Start is unaffected everywhere.
75
+ * Any other platform reports `supported: false`: a wrong answer here signals
76
+ * the wrong process, so stop degrades with a message rather than guessing.
77
+ * Start is unaffected everywhere.
76
78
  */
77
- export declare function defaultProcProbe(): ProcProbe;
79
+ export declare function defaultProcProbe(platform?: NodeJS.Platform, run?: RunCommand): ProcProbe;
78
80
  /** What `killRunProcesses` needs from the platform, injected for tests. */
79
81
  export interface RunProcessProbe {
80
82
  readonly supported: boolean;
@@ -85,7 +87,8 @@ export interface RunProcessProbe {
85
87
  uidOf(pid: number): number | undefined;
86
88
  send(pid: number, signal: NodeJS.Signals): void;
87
89
  }
88
- export declare function defaultRunProcessProbe(): RunProcessProbe;
90
+ /** Linux only: it lists and reads `/proc`. */
91
+ export declare function defaultRunProcessProbe(platform?: NodeJS.Platform): RunProcessProbe;
89
92
  /**
90
93
  * Ends every process of this OS user that carries `BAKERS_RUN_UUID=<runUuid>`:
91
94
  * the run's agent, its sandbox and background commands that outlive the
@@ -1,3 +1,4 @@
1
+ import { execFileSync } from 'node:child_process';
1
2
  import { readdirSync, readFileSync, statSync } from 'node:fs';
2
3
  /**
3
4
  * Substrings a live bakers-conductor foreground process's command line must all
@@ -113,17 +114,52 @@ export function signalVerifiedProcess(input) {
113
114
  }
114
115
  return { ok: true, pid: identified.pid, signal: input.signal };
115
116
  }
117
+ const runCommand = (file, args) => execFileSync(file, args, {
118
+ encoding: 'utf8',
119
+ stdio: ['ignore', 'pipe', 'ignore'],
120
+ });
116
121
  /**
117
122
  * The real probe: `/proc/<pid>/cmdline` and the owning uid of `/proc/<pid>`
118
- * itself on Linux.
123
+ * on Linux; one `ps -ww -o uid= -o command= -p <pid>` line on macOS (`-ww`
124
+ * keeps the command untruncated, so the markers are always in it).
119
125
  *
120
- * Only Linux is claimed as supported. macOS could shell out to `ps`, but a
121
- * wrong answer here signals the wrong process, so an unimplemented platform
122
- * reports `supported: false` and stop degrades with a message rather than
123
- * guessing. Start is unaffected everywhere.
126
+ * Any other platform reports `supported: false`: a wrong answer here signals
127
+ * the wrong process, so stop degrades with a message rather than guessing.
128
+ * Start is unaffected everywhere.
124
129
  */
125
- export function defaultProcProbe() {
126
- const supported = process.platform === 'linux';
130
+ export function defaultProcProbe(platform = process.platform, run = runCommand) {
131
+ const send = (pid, signal) => {
132
+ process.kill(pid, signal);
133
+ };
134
+ if (platform === 'darwin') {
135
+ const psOf = (pid) => {
136
+ try {
137
+ const match = /^\s*(\d+)\s+(\S.*)$/.exec(run('ps', [
138
+ '-ww',
139
+ '-o',
140
+ 'uid=',
141
+ '-o',
142
+ 'command=',
143
+ '-p',
144
+ String(pid),
145
+ ]).trim());
146
+ return match
147
+ ? { uid: Number(match[1]), command: match[2] }
148
+ : undefined;
149
+ }
150
+ catch {
151
+ // ps exits non-zero when the pid is gone.
152
+ return undefined;
153
+ }
154
+ };
155
+ return {
156
+ supported: true,
157
+ cmdlineOf: (pid) => psOf(pid)?.command,
158
+ uidOf: (pid) => psOf(pid)?.uid,
159
+ send,
160
+ };
161
+ }
162
+ const supported = platform === 'linux';
127
163
  return {
128
164
  supported,
129
165
  cmdlineOf(pid) {
@@ -152,17 +188,17 @@ export function defaultProcProbe() {
152
188
  return undefined;
153
189
  }
154
190
  },
155
- send(pid, signal) {
156
- process.kill(pid, signal);
157
- },
191
+ send,
158
192
  };
159
193
  }
160
- export function defaultRunProcessProbe() {
161
- const base = defaultProcProbe();
194
+ /** Linux only: it lists and reads `/proc`. */
195
+ export function defaultRunProcessProbe(platform = process.platform) {
196
+ const base = defaultProcProbe(platform);
197
+ const supported = platform === 'linux';
162
198
  return {
163
- supported: base.supported,
199
+ supported,
164
200
  pids() {
165
- if (!base.supported)
201
+ if (!supported)
166
202
  return [];
167
203
  return readdirSync('/proc')
168
204
  .filter((name) => /^\d+$/.test(name))
@@ -20,6 +20,7 @@ export type { ConnectionConfig, MachineConfig, ProjectConfig, } from './config-t
20
20
  export { configHomeOf, defaultRootGitExec, deriveCheckoutRoot, type RootGitExec, } from './core/checkout-root.js';
21
21
  export { CommandRunner, ExecError, exec, setDefaultCommandRunner, } from './core/exec.js';
22
22
  export { type GitSandboxPaths, gitSandboxPaths, withoutGitDirs, } from './core/git-sandbox.js';
23
+ export { hostCommandEntry, unprotectedEntryPoints, } from './core/host-commands.js';
23
24
  export { changedProtectedPaths, refreshRunTarget, runCloneTip, transferIsolatedCommit, } from './core/isolated-git.js';
24
25
  export { type ConductorLiveness, type ConductorLivenessInput, deriveConductorLiveness, toUnixSeconds, } from './core/liveness.js';
25
26
  export { type ConductorLogger, createLogger } from './core/logger.js';
package/dist/src/index.js CHANGED
@@ -21,6 +21,7 @@ export { discoverBbWorkspaces, loadReadyBbConnection, resolveWorkspaceSelector,
21
21
  export { configHomeOf, defaultRootGitExec, deriveCheckoutRoot, } from './core/checkout-root.js';
22
22
  export { CommandRunner, ExecError, exec, setDefaultCommandRunner, } from './core/exec.js';
23
23
  export { gitSandboxPaths, withoutGitDirs, } from './core/git-sandbox.js';
24
+ export { hostCommandEntry, unprotectedEntryPoints, } from './core/host-commands.js';
24
25
  export { changedProtectedPaths, refreshRunTarget, runCloneTip, transferIsolatedCommit, } from './core/isolated-git.js';
25
26
  export { deriveConductorLiveness, toUnixSeconds, } from './core/liveness.js';
26
27
  export { createLogger } from './core/logger.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/core",
3
- "version": "0.14.0",
3
+ "version": "0.14.1-next.2",
4
4
  "description": "bakers.build surface-agnostic kernel: host contract, split-config helpers, addon preset/discovery machinery, shared primitives.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -40,7 +40,7 @@
40
40
  "yaml": "^2.7.0"
41
41
  },
42
42
  "bakersBuild": {
43
- "commit": "9f7275a341fe96e9792bce6cd1bbc7b7afc1dcd0",
44
- "channel": "latest"
43
+ "commit": "3f4e6a91f380b3a2aaa69324ba3400e4cadf3e17",
44
+ "channel": "next"
45
45
  }
46
46
  }