hammerkit 2.0.0-next.17 → 2.0.0-next.19

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.
@@ -114,15 +114,21 @@ class RegistryClient {
114
114
  // on some Node versions.
115
115
  async request(method, urlOrPath, init = {}) {
116
116
  const url = urlOrPath.startsWith('http') ? urlOrPath : this.url(urlOrPath);
117
+ // the credentials are the registry's: an upload location or a next page elsewhere (another
118
+ // host, another port, or http in place of https) gets none, as fetch does on a redirect
119
+ const own = new URL(url).origin === new URL(this.url('')).origin;
117
120
  const send = () => fetch(url, {
118
121
  method,
119
- headers: { ...(init.headers ?? {}), ...(this.authorization ? { authorization: this.authorization } : {}) },
122
+ headers: {
123
+ ...(init.headers ?? {}),
124
+ ...(own && this.authorization ? { authorization: this.authorization } : {}),
125
+ },
120
126
  // BodyInit of Node's fetch, also when the dashboard checks these types with the DOM's
121
127
  body: init.body?.(),
122
128
  redirect: init.redirect ?? 'follow',
123
129
  });
124
130
  let response = await send();
125
- if (response.status === 401 && (await this.authenticate(response.headers.get('www-authenticate')))) {
131
+ if (own && response.status === 401 && (await this.authenticate(response.headers.get('www-authenticate')))) {
126
132
  await response.body?.cancel();
127
133
  response = await send();
128
134
  }
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.logStream = exports.awaitStream = void 0;
4
- const log_1 = require("../log");
4
+ const line_splitter_1 = require("../utils/line-splitter");
5
5
  async function awaitStream(status, stream) {
6
6
  return new Promise((resolve, reject) => {
7
7
  logStream(status, stream);
@@ -12,15 +12,23 @@ async function awaitStream(status, stream) {
12
12
  }
13
13
  exports.awaitStream = awaitStream;
14
14
  function logStream(status, stream) {
15
- demuxStream(stream, writeLog(status, 'stdout'), writeLog(status, 'stderr'));
15
+ const stdout = writeLog(status, 'stdout');
16
+ const stderr = writeLog(status, 'stderr');
17
+ demuxStream(stream, (buffer) => stdout.write(buffer), (buffer) => stderr.write(buffer));
18
+ // what is left of a last line without a line feed
19
+ const end = () => {
20
+ stdout.end();
21
+ stderr.end();
22
+ };
23
+ const events = stream;
24
+ events.on('end', end);
25
+ events.on('close', end);
16
26
  }
17
27
  exports.logStream = logStream;
28
+ // A line docker split between two frames is logged once it ends, whole: a secret value in it
29
+ // is masked per line.
18
30
  function writeLog(status, level) {
19
- return async (buffer) => {
20
- for (const log of (0, log_1.getLogs)(buffer)) {
21
- status.console(level, log.endsWith('\n') ? log.substring(0, log.length - 1) : log);
22
- }
23
- };
31
+ return (0, line_splitter_1.lineSplitter)((line) => status.console(level, line));
24
32
  }
25
33
  function demuxStream(stream, stdoutFn, stderrFn) {
26
34
  let nextDataType = null;
@@ -7,7 +7,7 @@ const INTERPOLATION = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
7
7
  // an empty string is set, as in a shell: CI providers leave many empty (a merge
8
8
  // request id on a branch pipeline).
9
9
  function resolveReference(name, environment, context, fromProcess) {
10
- const processValue = environment.processEnvs[name];
10
+ const processValue = (environment.hosted?.buildFileEnvs ?? environment.processEnvs)[name];
11
11
  if (processValue !== undefined && processValue !== null) {
12
12
  fromProcess?.add(name);
13
13
  return processValue;
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.executeCommand = exports.processEnv = void 0;
4
4
  const child_process_1 = require("child_process");
5
5
  const os_1 = require("os");
6
- const log_1 = require("../log");
6
+ const line_splitter_1 = require("../utils/line-splitter");
7
7
  const abort_1 = require("./abort");
8
8
  const abort_event_1 = require("../utils/abort-event");
9
9
  const environment_config_1 = require("../utils/environment-config");
@@ -43,25 +43,19 @@ async function executeCommand(status, abortSignal, cwd, command, envs, environme
43
43
  // they would keep running and holding the output open
44
44
  detached: !windows,
45
45
  });
46
- // decode across chunk boundaries, so a multi-byte character split between
47
- // two chunks stays intact
48
- ps.stdout?.setEncoding('utf8');
49
- ps.stderr?.setEncoding('utf8');
50
- ps.stdout?.on('data', async (data) => {
51
- for (const log of (0, log_1.getLogs)(data)) {
52
- status.console('stdout', log);
53
- }
54
- });
55
- ps.stderr?.on('data', async (data) => {
56
- for (const log of (0, log_1.getLogs)(data)) {
57
- status.console('stderr', log);
58
- }
59
- });
46
+ // a line that two chunks split is logged once it ends, whole: a multi-byte character
47
+ // stays intact, and so does a secret value, which is masked per line
48
+ const stdout = (0, line_splitter_1.lineSplitter)((line) => status.console('stdout', line));
49
+ const stderr = (0, line_splitter_1.lineSplitter)((line) => status.console('stderr', line));
50
+ ps.stdout?.on('data', (data) => stdout.write(data));
51
+ ps.stderr?.on('data', (data) => stderr.write(data));
60
52
  ps.on('error', (err) => {
61
53
  reject(err);
62
54
  });
63
55
  ps.on('close', (code) => {
64
56
  abortListener.close();
57
+ stdout.end();
58
+ stderr.end();
65
59
  if (abortSignal.aborted) {
66
60
  reject(new abort_1.AbortError());
67
61
  return;
@@ -36,12 +36,7 @@ exports.hasShell = hasShell;
36
36
  */
37
37
  async function connectServer(environment, options) {
38
38
  const config = await (0, host_config_1.readHostConfig)(environment);
39
- const name = options.server ?? config.run.on;
40
- if (!name || !(0, host_config_1.hasServer)(config.servers, name)) {
41
- throw new Error(options.server
42
- ? `server ${options.server} is not registered, add it with: hammerkit remote add ${options.server} <url> --issuer <url>`
43
- : 'name a server (HAMMERKIT_SERVER or --server), or set a default with: hammerkit remote use <name>');
44
- }
39
+ const name = (0, host_config_1.chooseServer)(config, options.server || undefined, 'with HAMMERKIT_SERVER or --server');
45
40
  if (!options.build) {
46
41
  throw new Error('name the published version of the build file whose tasks run on the sandbox by its hash (HAMMERKIT_BUILD or --build), as hammerkit remote publish printed it');
47
42
  }
@@ -25,7 +25,7 @@ function registerMcpCommand(remote, environment, input = process.stdin) {
25
25
  remote
26
26
  .command('mcp')
27
27
  .description('serve the files, shell and tasks of a sandbox on a server as MCP tools over stdio (experimental)')
28
- .addOption(new commander_1.Option('--server <name>', 'registered server (default: hammerkit remote use)').env('HAMMERKIT_SERVER'))
28
+ .addOption(new commander_1.Option('--server <name>', 'registered server (default: hammerkit remote use, or the only registered server)').env('HAMMERKIT_SERVER'))
29
29
  .addOption(new commander_1.Option('--sandbox <id>', 'a sandbox of yours on the server').env('HAMMERKIT_SANDBOX'))
30
30
  .addOption(new commander_1.Option('--repo <repo>', 'create a sandbox of this repository').env('HAMMERKIT_REPO'))
31
31
  .addOption(new commander_1.Option('--ref <ref>', 'at this branch').env('HAMMERKIT_REF'))
@@ -42,6 +42,18 @@ directory) {
42
42
  }
43
43
  exports.getCheckKeys = getCheckKeys;
44
44
  // Every provider and account name resolves, to a definition nothing runs.
45
+ // A record that holds an entry under any name, as its own property: the catalog is looked up by
46
+ // own properties only.
47
+ function anyRecord(make) {
48
+ const entry = (name) => (typeof name === 'string' ? make(name) : undefined);
49
+ return new Proxy({}, {
50
+ get: (_target, name) => entry(name),
51
+ has: (_target, name) => typeof name === 'string',
52
+ getOwnPropertyDescriptor: (_target, name) => typeof name === 'string'
53
+ ? { value: make(name), writable: false, enumerable: true, configurable: true }
54
+ : undefined,
55
+ });
56
+ }
45
57
  function anyCatalog() {
46
58
  const provider = (name) => ({
47
59
  name,
@@ -54,12 +66,12 @@ function anyCatalog() {
54
66
  const account = (name) => ({
55
67
  name,
56
68
  default: false,
57
- providers: new Proxy({}, { get: () => ({ env: {} }) }),
69
+ providers: anyRecord(() => ({ env: {} })),
58
70
  declaredIn: 'the server',
59
71
  });
60
72
  return {
61
- providers: new Proxy({}, { get: (_target, name) => (typeof name === 'string' ? provider(name) : undefined) }),
62
- accounts: new Proxy({}, { get: (_target, name) => (typeof name === 'string' ? account(name) : undefined) }),
73
+ providers: anyRecord(provider),
74
+ accounts: anyRecord(account),
63
75
  explicitAccounts: true,
64
76
  };
65
77
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.stateKeyDigest = exports.getStateKey = exports.getWorkItemCheckoutStats = exports.getWorkItemCacheStats = exports.getWorkCacheStats = void 0;
3
+ exports.stateKeyDigest = exports.encodeStateEntries = exports.getStateKey = exports.getWorkItemCheckoutStats = exports.getWorkItemCacheStats = exports.getWorkCacheStats = void 0;
4
4
  const calculate_checksum_1 = require("./calculate-checksum");
5
5
  const path_1 = require("path");
6
6
  const crypto_1 = require("crypto");
@@ -39,9 +39,11 @@ async function visitPath(cwd, path, matcher, context, root) {
39
39
  if (!matcher(path)) {
40
40
  return { type: 'none' };
41
41
  }
42
- const checksum = (0, crypto_1.createHash)('sha256')
42
+ // `l` and the digest of its target, a kind of entry of its own: no checksum of a file
43
+ // starts with a letter past `f`
44
+ const checksum = `l${(0, crypto_1.createHash)('sha256')
43
45
  .update(`link:${await (0, promises_1.readlink)(path)}`)
44
- .digest('hex');
46
+ .digest('hex')}`;
45
47
  return { type: 'file', key, lastModified: link.mtimeMs, checksum };
46
48
  }
47
49
  }
@@ -121,20 +123,30 @@ function dependencyOutputs(item) {
121
123
  return [...outputs];
122
124
  }
123
125
  function getStateKey(stats, cacheMethod) {
124
- const contents = [];
126
+ const entries = [];
125
127
  // Sorted: the walk follows the filesystem's listing order, which differs
126
128
  // between machines (ext4 and overlayfs list in hash order).
127
129
  for (const key of Object.keys(stats.files).sort()) {
128
130
  if (cacheMethod === 'checksum') {
129
- contents.push(`${key}:${stats.files[key].checksum}`);
131
+ entries.push([key, stats.files[key].checksum]);
130
132
  }
131
133
  else if (cacheMethod === 'modify-date') {
132
- contents.push(`${key}:${stats.files[key].lastModified}`);
134
+ entries.push([key, `${stats.files[key].lastModified}`]);
133
135
  }
134
136
  }
135
- return stateKeyDigest(contents.join(','));
137
+ return stateKeyDigest(encodeStateEntries(entries));
136
138
  }
137
139
  exports.getStateKey = getStateKey;
140
+ // The paths and values of a tree as one text that names no other tree. `path:value,...` as
141
+ // before while no path holds `:` or `,` (a value is hex digits or a date), so those keys stay
142
+ // what they were; else JSON after a NUL, which no path holds.
143
+ function encodeStateEntries(entries) {
144
+ if (entries.some(([path]) => /[:,]/.test(path))) {
145
+ return `\0${JSON.stringify(entries)}`;
146
+ }
147
+ return entries.map(([path, value]) => `${path}:${value}`).join(',');
148
+ }
149
+ exports.encodeStateEntries = encodeStateEntries;
138
150
  // A state key is also the value of the `hammerkit.dev/state` label on Kubernetes, which
139
151
  // takes at most 63 characters: the sha256 in base 36 has 50.
140
152
  function stateKeyDigest(content) {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.storedCacheDescription = exports.getWorkServiceCacheIdentity = exports.getWorkTaskCacheDescription = void 0;
3
+ exports.storedCacheDescription = exports.getWorkServiceCacheIdentity = exports.getSecretSources = exports.getWorkTaskCacheDescription = void 0;
4
4
  const os_1 = require("os");
5
5
  const crypto_1 = require("crypto");
6
6
  const replace_env_variables_1 = require("../environment/replace-env-variables");
@@ -24,6 +24,7 @@ function getWorkTaskCacheDescription(item) {
24
24
  .filter((secret) => secret.cache)
25
25
  .map((secret) => `${(0, work_secret_1.getPortableSecretName)(task.projectRoot, secret)}=${secret.digest()}`)
26
26
  .sort();
27
+ const secretSources = getSecretSources(task.projectRoot, task.secrets);
27
28
  return {
28
29
  shell: task.shell ?? undefined,
29
30
  platform: task.type === 'container-task' ? task.image : (0, os_1.platform)(),
@@ -44,11 +45,26 @@ function getWorkTaskCacheDescription(item) {
44
45
  cwd: portable(task.cwd),
45
46
  deps: item.deps.length > 0 ? item.deps.map((dep) => dep.id()).sort() : undefined,
46
47
  secrets: cachedSecrets.length > 0 ? cachedSecrets : undefined,
48
+ secretSources: secretSources.length > 0 ? secretSources : undefined,
47
49
  claimLayout: (0, claim_layout_1.hasPathsEndingAlike)(item) || (0, claim_layout_1.hasOutputsFlatteningAlike)(item) ? 2 : undefined,
48
50
  needs: item.needs.length > 0 ? getNeedsIdentities(item) : undefined,
49
51
  };
50
52
  }
51
53
  exports.getWorkTaskCacheDescription = getWorkTaskCacheDescription;
54
+ // The secrets without `cache: true`, by name and source: `NAME<env:VAR`, `NAME<gcp:ref as
55
+ // account`, `NAME<file` (a path of the machine, which differs between machines). Their values
56
+ // stay out of the key, as before: what a provider returns may change on every read.
57
+ function getSecretSources(projectRoot, secrets) {
58
+ return secrets
59
+ .filter((secret) => !secret.cache)
60
+ .map((secret) => {
61
+ const source = secret.source;
62
+ const from = source.type === 'file' ? 'file' : (0, work_secret_1.describeSecretSource)(secret);
63
+ return `${(0, work_secret_1.getPortableSecretName)(projectRoot, secret)}<${from}`;
64
+ })
65
+ .sort();
66
+ }
67
+ exports.getSecretSources = getSecretSources;
52
68
  // `visiting` holds the services on the way here: services that need each other in a loop
53
69
  // fail to plan (checkForLoop), the identity only has to come back to say so
54
70
  function getNeedsIdentities(item, visiting = new Set()) {
@@ -78,6 +94,10 @@ function getWorkServiceCacheIdentity(item, visiting = new Set()) {
78
94
  .filter((secret) => secret.cache)
79
95
  .map((secret) => `${(0, work_secret_1.getPortableSecretName)(service.projectRoot, secret)}=${secret.digest()}`)
80
96
  .sort(),
97
+ // left out when it reads none, so the identity of such a service stays what it was
98
+ ...(service.secrets.some((secret) => !secret.cache)
99
+ ? { secretSources: getSecretSources(service.projectRoot, service.secrets) }
100
+ : {}),
81
101
  // as declared: arguments after -- of a run of the init leave the service as it is
82
102
  init: service.init ? (0, work_cache_id_1.getDeclaredWorkTaskId)(service.init.task) : null,
83
103
  }
@@ -96,16 +116,25 @@ exports.getWorkServiceCacheIdentity = getWorkServiceCacheIdentity;
96
116
  // The form written to disk: description.json in a cache entry (pushed to remote
97
117
  // backends, readable by everyone who can pull) and the local explain record.
98
118
  // Env is where tokens get passed, so each value is stored as a digest; the task
99
- // id is still hashed from the values themselves.
119
+ // id is still hashed from the values themselves. So are where its secrets come from: who may
120
+ // pull an entry need not know which secrets of which provider a task reads.
100
121
  function storedCacheDescription(description) {
101
- if (!description.envs) {
122
+ if (!description.envs && !description.secretSources) {
102
123
  return description;
103
124
  }
104
- const envs = {};
105
- for (const [key, value] of Object.entries(description.envs)) {
106
- envs[key] = `sha256:${(0, crypto_1.createHash)('sha256').update(value).digest('hex')}`;
125
+ const digest = (value) => `sha256:${(0, crypto_1.createHash)('sha256').update(value).digest('hex')}`;
126
+ const stored = { ...description };
127
+ if (description.envs) {
128
+ const envs = {};
129
+ for (const [key, value] of Object.entries(description.envs)) {
130
+ envs[key] = digest(value);
131
+ }
132
+ stored.envs = envs;
133
+ }
134
+ if (description.secretSources) {
135
+ stored.secretSources = description.secretSources.map(digest);
107
136
  }
108
- return { ...description, envs };
137
+ return stored;
109
138
  }
110
139
  exports.storedCacheDescription = storedCacheDescription;
111
140
  //# sourceMappingURL=work-task-cache-description.js.map
@@ -115,7 +115,7 @@ function parseService(workTree, service, environment, context) {
115
115
  caching,
116
116
  // set once the service is planned, see appendServiceInit
117
117
  init: null,
118
- secrets: (0, work_secret_1.parseWorkSecrets)(service.cwd, context.projectRoot, service.schema.secrets, envs, environment, context.secrets, service.schema.account),
118
+ secrets: (0, work_secret_1.parseWorkSecrets)(service.cwd, context.projectRoot, service.schema.secrets, envs, environment, context.secrets, `service ${service.relativeName}`, service.schema.account),
119
119
  resources: (0, work_resources_1.parseWorkResources)(service.schema.resources),
120
120
  volumeSize: service.schema.volumeSize ?? null,
121
121
  restarts: service.schema.restarts ?? null,
@@ -80,7 +80,7 @@ function parseTask(cwd, task, environment, context) {
80
80
  caching: (0, resolve_cache_1.resolveCache)(task.schema.cache ?? null, context.caches, task.relativeName),
81
81
  shell: task.schema.shell ? (0, template_value_1.templateValue)(task.schema.shell, envs) : '/bin/sh',
82
82
  timeout: task.schema.timeout ? (0, units_1.parseDuration)(task.schema.timeout) : null,
83
- secrets: (0, work_secret_1.parseWorkSecrets)(cwd, context.projectRoot, task.schema.secrets, envs, environment, context.secrets, task.schema.account),
83
+ secrets: (0, work_secret_1.parseWorkSecrets)(cwd, context.projectRoot, task.schema.secrets, envs, environment, context.secrets, `task ${task.relativeName}`, task.schema.account),
84
84
  resources: (0, work_resources_1.parseWorkResources)(task.schema.resources),
85
85
  network: (0, work_network_1.parseWorkNetwork)(task.schema.network),
86
86
  networkCeiling: null,
@@ -8,6 +8,7 @@ const normalize_path_1 = require("./utils/normalize-path");
8
8
  const template_value_1 = require("./utils/template-value");
9
9
  const portable_path_1 = require("./utils/portable-path");
10
10
  const abort_1 = require("../executer/abort");
11
+ const secret_catalog_1 = require("../secrets/secret-catalog");
11
12
  const provider_values_1 = require("../secrets/provider-values");
12
13
  // Where the value comes from, for messages and for what makes a service
13
14
  // different: never the value.
@@ -30,6 +31,8 @@ function getPortableSecretName(projectRoot, secret) {
30
31
  }
31
32
  exports.getPortableSecretName = getPortableSecretName;
32
33
  function parseWorkSecrets(cwd, projectRoot, secrets, envs, environment, catalog,
34
+ // what the secrets belong to, for messages: `task build` or `service db`
35
+ owner,
33
36
  // the service account of the task or service the secrets belong to
34
37
  account) {
35
38
  return (secrets ?? []).map((secret) => {
@@ -38,7 +41,7 @@ account) {
38
41
  ? { type: 'env', name: secret.env }
39
42
  : { type: 'file', path: (0, normalize_path_1.normalizePath)(cwd, cwd, (0, template_value_1.templateValue)(secret.path ?? '', envs)) };
40
43
  const name = target.type === 'env' ? target.name : secret.path;
41
- const source = parseSecretSource(secret, ref, cwd, envs, catalog, account, `secret ${name}`);
44
+ const source = parseSecretSource(secret, ref, cwd, envs, catalog, account, owner, `secret ${name}`);
42
45
  const workSecret = {
43
46
  source,
44
47
  target,
@@ -49,7 +52,7 @@ account) {
49
52
  });
50
53
  }
51
54
  exports.parseWorkSecrets = parseWorkSecrets;
52
- function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, label) {
55
+ function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, owner, label) {
53
56
  const kind = secret.from.substring(0, secret.from.indexOf(':'));
54
57
  if (kind === 'env') {
55
58
  return { type: 'env', name: ref };
@@ -57,30 +60,29 @@ function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, label)
57
60
  if (kind === 'file') {
58
61
  return { type: 'file', path: (0, normalize_path_1.normalizePath)(cwd, (0, os_1.homedir)(), (0, template_value_1.templateValue)(ref, envs)) };
59
62
  }
60
- const provider = catalog.providers[kind];
63
+ const reads = `${owner} reads ${label} from ${secret.from}`;
64
+ const provider = (0, secret_catalog_1.declared)(catalog.providers, kind);
61
65
  if (!provider) {
62
- const declared = Object.keys(catalog.providers);
63
- throw new Error(`${label}: unknown secret provider ${kind}, ${declared.length > 0 ? `declared: ${declared.join(', ')}` : 'none is declared'}`);
66
+ throw new Error(unknownProviderMessage(catalog, reads, kind));
64
67
  }
65
68
  const providerRef = (0, template_value_1.templateValue)(ref, envs);
66
69
  if (providerRef.length === 0 || providerRef.startsWith('-')) {
67
- throw new Error(`${label}: a reference for ${kind} must not be empty or start with -`);
70
+ throw new Error(`${reads}: a reference for ${kind} must not be empty or start with -`);
68
71
  }
69
72
  const accountName = catalog.explicitAccounts
70
73
  ? secret.account
71
74
  : secret.account ?? taskAccount ?? Object.values(catalog.accounts).find((a) => a.default)?.name;
72
75
  if (!accountName) {
73
- throw new Error(catalog.explicitAccounts
74
- ? `${label}: ${kind}:${providerRef} needs account: on the secret, a server uses neither a task's account nor a default`
75
- : `${label}: ${kind}:${providerRef} needs an account, and none is named or marked default: true`);
76
+ throw new Error(missingAccountMessage(catalog, reads, owner));
76
77
  }
77
- const account = catalog.accounts[accountName];
78
+ const account = (0, secret_catalog_1.declared)(catalog.accounts, accountName);
78
79
  if (!account) {
79
- throw new Error(`${label}: unknown secret account ${accountName}, declared: ${Object.keys(catalog.accounts).join(', ') || 'none'}`);
80
+ const namedBy = secret.account ? 'the account: of the secret' : `the account: of ${owner}`;
81
+ throw new Error(unknownAccountMessage(catalog, reads, owner, accountName, namedBy, kind));
80
82
  }
81
- const credentials = account.providers[kind];
83
+ const credentials = (0, secret_catalog_1.declared)(account.providers, kind);
82
84
  if (!credentials) {
83
- throw new Error(`${label}: account ${accountName} has no credentials for provider ${kind}`);
85
+ throw new Error(missingCredentialsMessage(catalog, reads, account, kind));
84
86
  }
85
87
  return {
86
88
  type: 'provider',
@@ -90,6 +92,126 @@ function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, label)
90
92
  binding: { definition: provider, account: { name: accountName, env: credentials.env } },
91
93
  };
92
94
  }
95
+ // The messages below say what is wrong, where the names come from and what to write: a
96
+ // person who only ran a task should not need to know how secrets are declared. On a
97
+ // server the build file can only change what it names, the operator declares the rest.
98
+ const SECRET_PROVIDERS_DOCS = 'https://hammerkit.dev/docs/task/secret-providers';
99
+ // `tests, dev in ~/.hammerkit/config.yaml and ci in .hammerkit.yaml`, or `none`
100
+ function listDeclared(definitions, server) {
101
+ if (definitions.length === 0) {
102
+ return 'none';
103
+ }
104
+ if (server) {
105
+ return definitions.map((d) => d.name).join(', ');
106
+ }
107
+ const byFile = new Map();
108
+ for (const definition of definitions) {
109
+ byFile.set(definition.declaredIn, [...(byFile.get(definition.declaredIn) ?? []), definition.name]);
110
+ }
111
+ return [...byFile.entries()].map(([file, names]) => `${names.join(', ')} in ${file}`).join(' and ');
112
+ }
113
+ // A build file is checked as a whole when it is read, so one wrong secret stops
114
+ // the tasks that don't read it, too.
115
+ function seeDocs(anchor) {
116
+ return `Every task of the build file is checked when it is read, so this stops other tasks too. See ${SECRET_PROVIDERS_DOCS}#${anchor}`;
117
+ }
118
+ function hostConfigOf(catalog) {
119
+ return catalog.hostConfig ?? 'the host config';
120
+ }
121
+ function indent(lines) {
122
+ return lines.map((line) => ` ${line}`).join('\n');
123
+ }
124
+ // A variable of this machine to hold the credential, for snippets: `${OPERATOR_CREDENTIALS}`
125
+ function credentialVariable(account, key, keys) {
126
+ const prefix = account.toUpperCase().replace(/[^A-Z0-9]+/g, '_');
127
+ return `\${${prefix}_${keys === 1 ? 'CREDENTIALS' : key}}`;
128
+ }
129
+ // The credential variables a provider's command reads, as another account passes them;
130
+ // a placeholder when no account has credentials for the provider yet
131
+ function credentialLines(catalog, account, provider) {
132
+ const sibling = Object.values(catalog.accounts).find((a) => (0, secret_catalog_1.declared)(a.providers, provider));
133
+ const keys = sibling ? Object.keys(sibling.providers[provider].env) : [];
134
+ if (keys.length === 0) {
135
+ return [`<VARIABLE>: \${<VARIABLE OF THIS MACHINE>} # what ${provider} reads its credential from`];
136
+ }
137
+ return keys.map((key) => `${key}: ${credentialVariable(account, key, keys.length)}`);
138
+ }
139
+ function unknownProviderMessage(catalog, reads, kind) {
140
+ const declaredProviders = listDeclared(Object.values(catalog.providers), !!catalog.explicitAccounts);
141
+ if (catalog.explicitAccounts) {
142
+ return (`${reads}, but this server has no secret provider ${kind} (it has: ${declaredProviders}). ` +
143
+ `Use one of its providers, or ask the operator of the server to add ${kind} to its config.`);
144
+ }
145
+ return [
146
+ `${reads}, but no secret provider ${kind} is declared (declared: ${declaredProviders}).`,
147
+ `A provider is the command that prints a secret's value. Declare it in the host config, ${hostConfigOf(catalog)}:`,
148
+ '',
149
+ indent(['secretProviders:', ` ${kind}:`, ` command: [<command>, <its arguments>, '{{ref}}']`]),
150
+ '',
151
+ seeDocs('providers'),
152
+ ].join('\n');
153
+ }
154
+ function missingAccountMessage(catalog, reads, owner) {
155
+ const declaredAccounts = listDeclared(Object.values(catalog.accounts), !!catalog.explicitAccounts);
156
+ if (catalog.explicitAccounts) {
157
+ return (`${reads}, but names no account. A server reads every secret as the account the secret names, ` +
158
+ `never as the account of a task or a default: add account: to the secret (this server has: ${declaredAccounts}).`);
159
+ }
160
+ return [
161
+ `${reads}, but neither the secret nor ${owner} names an account, and no account is marked default: true (declared: ${declaredAccounts}).`,
162
+ `An account says which credential a secret is read with. Name one with account: on the secret or on ${owner}, ` +
163
+ `or mark one as the default in ${hostConfigOf(catalog)}:`,
164
+ '',
165
+ indent(['secretAccounts:', ' <account>:', ' default: true']),
166
+ '',
167
+ seeDocs('accounts'),
168
+ ].join('\n');
169
+ }
170
+ function unknownAccountMessage(catalog, reads, owner, account, namedBy, provider) {
171
+ const declaredAccounts = listDeclared(Object.values(catalog.accounts), !!catalog.explicitAccounts);
172
+ if (catalog.explicitAccounts) {
173
+ return (`${reads} as account ${account}, but this server has no account ${account} (it has: ${declaredAccounts}). ` +
174
+ `Name one of its accounts with account: on the secret, or ask the operator of the server to add ${account} to its config.`);
175
+ }
176
+ return [
177
+ `${reads} as account ${account} (${namedBy}), but no account ${account} is declared (declared: ${declaredAccounts}).`,
178
+ `An account says which credential a secret is read with, and each machine declares its own in its host config, ` +
179
+ `${hostConfigOf(catalog)}. Add ${account} there:`,
180
+ '',
181
+ indent([
182
+ 'secretAccounts:',
183
+ ` ${account}:`,
184
+ ' providers:',
185
+ ` ${provider}:`,
186
+ ' env:',
187
+ ...credentialLines(catalog, account, provider).map((line) => ` ${line}`),
188
+ ]),
189
+ '',
190
+ `Or read the secret as one of the declared accounts with account: on the secret${namedBy === 'the account: of the secret' ? '' : ` or on ${owner}`}.`,
191
+ seeDocs('accounts'),
192
+ ].join('\n');
193
+ }
194
+ function missingCredentialsMessage(catalog, reads, account, provider) {
195
+ if (catalog.explicitAccounts) {
196
+ return (`${reads} as account ${account.name}, but that account of this server has no credentials for ${provider}. ` +
197
+ `Ask the operator of the server to add them to its config.`);
198
+ }
199
+ return [
200
+ `${reads} as account ${account.name}, but account ${account.name} (in ${account.declaredIn}) has no credentials for provider ${provider}.`,
201
+ `Add the variables that make ${provider} act as ${account.name}:`,
202
+ '',
203
+ indent([
204
+ 'secretAccounts:',
205
+ ` ${account.name}:`,
206
+ ' providers:',
207
+ ` ${provider}:`,
208
+ ' env:',
209
+ ...credentialLines(catalog, account.name, provider).map((line) => ` ${line}`),
210
+ ]),
211
+ '',
212
+ seeDocs('accounts'),
213
+ ].join('\n');
214
+ }
93
215
  function readSecretValueSync(secret, environment) {
94
216
  if (secret.source.type === 'env') {
95
217
  const value = environment.processEnvs[secret.source.name];
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.pinLogin = exports.setDefaultLocation = exports.removeServer = exports.addServer = exports.normalizeServerUrl = exports.validateServerName = exports.writeHostConfig = exports.readHostConfig = exports.getHostConfigPath = exports.getRegisteredServer = exports.getTokenCommand = exports.hasServer = exports.hostConfigSchema = exports.hostServerSchema = exports.RESERVED_SERVER_NAMES = void 0;
3
+ exports.pinLogin = exports.setDefaultLocation = exports.removeServer = exports.addServer = exports.normalizeServerUrl = exports.validateServerName = exports.writeHostConfig = exports.readHostConfig = exports.getHostConfigPath = exports.chooseServer = exports.notRegisteredMessage = exports.getRegisteredServer = exports.getTokenCommand = exports.hasServer = exports.hostConfigSchema = exports.hostServerSchema = exports.RESERVED_SERVER_NAMES = void 0;
4
4
  const path_1 = require("path");
5
5
  const zod_1 = require("zod");
6
6
  const yaml_1 = require("yaml");
@@ -69,6 +69,52 @@ function getRegisteredServer(config, name) {
69
69
  return { ...config.servers[name], ...(tokenCommand ? { tokenCommand } : {}) };
70
70
  }
71
71
  exports.getRegisteredServer = getRegisteredServer;
72
+ // `a, b and c`
73
+ function listNames(names) {
74
+ return names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}` : names.join('');
75
+ }
76
+ // `(registered: a and b)`, for a name that is not one of them
77
+ function registeredNote(config) {
78
+ const names = Object.keys(config.servers).sort();
79
+ return names.length === 0 ? '(no server is registered yet)' : `(registered: ${listNames(names)})`;
80
+ }
81
+ // `server nope is not registered (registered: a and b)`, with how to add it unless it is being removed
82
+ function notRegisteredMessage(config, name, howToAdd = true) {
83
+ const add = howToAdd ? `, add it with: hammerkit remote add ${name} <url> --issuer <url>` : '';
84
+ return `server ${name} is not registered ${registeredNote(config)}${add}`;
85
+ }
86
+ exports.notRegisteredMessage = notRegisteredMessage;
87
+ // The server a remote command talks to: the one it names, else the default of `remote use`,
88
+ // else the only one registered. With several and no default, the person names one.
89
+ // A default that names a server no longer registered is an error, as it is for `hammerkit run`:
90
+ // a call never goes to another server than the one chosen. `how` says how a name is given,
91
+ // for the message: `with --server <name>`.
92
+ function chooseServer(config, name, how = 'as the last argument') {
93
+ if (name !== undefined) {
94
+ if (!hasServer(config.servers, name)) {
95
+ throw new Error(notRegisteredMessage(config, name));
96
+ }
97
+ return name;
98
+ }
99
+ const on = config.run.on;
100
+ if (on && !exports.RESERVED_SERVER_NAMES.includes(on)) {
101
+ if (!hasServer(config.servers, on)) {
102
+ throw new Error(`the default of remote use, server ${on}, is not registered ${registeredNote(config)}; ` +
103
+ `pick another with: hammerkit remote use <name>, or add it with: hammerkit remote add ${on} <url> --issuer <url>`);
104
+ }
105
+ return on;
106
+ }
107
+ const names = Object.keys(config.servers).sort();
108
+ if (names.length === 1) {
109
+ return names[0];
110
+ }
111
+ if (names.length === 0) {
112
+ throw new Error('no server is registered, add one with: hammerkit remote add <name> <url> --issuer <url>');
113
+ }
114
+ throw new Error(`${names.length} servers are registered (${listNames(names)}), name one ${how}, ` +
115
+ `or make one the default with: hammerkit remote use <name>`);
116
+ }
117
+ exports.chooseServer = chooseServer;
72
118
  function setTokenCommand(config, name, entry) {
73
119
  const commands = { ...(config.tokenCommands ?? {}) };
74
120
  if (entry) {
@@ -201,7 +247,7 @@ exports.addServer = addServer;
201
247
  async function removeServer(environment, name) {
202
248
  const config = await readHostConfig(environment);
203
249
  if (!hasServer(config.servers, name)) {
204
- throw new Error(`server "${name}" is not registered`);
250
+ throw new Error(notRegisteredMessage(config, name, false));
205
251
  }
206
252
  delete config.servers[name];
207
253
  setTokenCommand(config, name, undefined);
@@ -216,7 +262,7 @@ exports.removeServer = removeServer;
216
262
  async function setDefaultLocation(environment, on) {
217
263
  const config = await readHostConfig(environment);
218
264
  if (!exports.RESERVED_SERVER_NAMES.includes(on) && !hasServer(config.servers, on)) {
219
- throw new Error(`server "${on}" is not registered; add it with: hammerkit remote add ${on} <url> --issuer <url>`);
265
+ throw new Error(notRegisteredMessage(config, on));
220
266
  }
221
267
  config.run.on = on;
222
268
  await writeHostConfig(environment, config);
@@ -14,7 +14,7 @@ async function resolveRunLocation(workTree, environment, options = {}) {
14
14
  const config = await (0, host_config_1.readHostConfig)(environment);
15
15
  const explicit = options.local ? 'local' : options.on ?? (environment.processEnvs.HAMMERKIT_ON || undefined);
16
16
  if (explicit && explicit !== 'auto') {
17
- return explicit === 'local' ? { type: 'local' } : lookup(config.servers, explicit);
17
+ return explicit === 'local' ? { type: 'local' } : lookup(config, explicit);
18
18
  }
19
19
  const runners = getTaskRunners(workTree);
20
20
  if (runners.length > 1) {
@@ -24,13 +24,13 @@ async function resolveRunLocation(workTree, environment, options = {}) {
24
24
  if (!requested || requested === 'local' || requested === 'auto') {
25
25
  return { type: 'local' };
26
26
  }
27
- return lookup(config.servers, requested);
27
+ return lookup(config, requested);
28
28
  }
29
29
  exports.resolveRunLocation = resolveRunLocation;
30
- function lookup(servers, name) {
31
- const server = (0, host_config_1.hasServer)(servers, name) ? servers[name] : undefined;
30
+ function lookup(config, name) {
31
+ const server = (0, host_config_1.hasServer)(config.servers, name) ? config.servers[name] : undefined;
32
32
  if (!server) {
33
- throw new Error(`server ${name} is not registered, add it with: hammerkit remote add ${name} <url> --issuer <url>`);
33
+ throw new Error((0, host_config_1.notRegisteredMessage)(config, name));
34
34
  }
35
35
  return { type: 'server', name, server };
36
36
  }
@@ -94,21 +94,17 @@ passthrough = []) {
94
94
  await (0, host_config_1.setDefaultLocation)(environment, location);
95
95
  environment.stdout.write(`default location: ${location}\n`);
96
96
  }));
97
- const getServer = async (name) => {
97
+ // a command that takes a server: the named one, the default or the only one, see chooseServer
98
+ const getServer = async (name, how) => {
98
99
  const config = await (0, host_config_1.readHostConfig)(environment);
99
- const chosen = name ?? config.run.on;
100
- if (!chosen || !(0, host_config_1.hasServer)(config.servers, chosen)) {
101
- throw new Error(name
102
- ? `server ${name} is not registered, add it with: hammerkit remote add ${name} <url> --issuer <url>`
103
- : 'name a server, or set one as the default with: hammerkit remote use <name>');
104
- }
100
+ const chosen = (0, host_config_1.chooseServer)(config, name, how);
105
101
  return { name: chosen, server: (0, host_config_1.getRegisteredServer)(config, chosen) };
106
102
  };
107
103
  remote
108
- .command('login <name>')
109
- .description('sign in to a registered server with your identity provider (device code, works headless)')
110
- .action(guarded('Remote login was not successful', async (name) => {
111
- const { server } = await getServer(name);
104
+ .command('login [name]')
105
+ .description('sign in to a registered server with your identity provider (device code, works headless); the name can be left out when only one server is registered or one is set with remote use')
106
+ .action(guarded('Remote login was not successful', async (given) => {
107
+ const { name, server } = await getServer(given);
112
108
  if (server.tokenCommand) {
113
109
  // a sign-in would never be used: the command's token goes first
114
110
  throw new Error(`${name} takes its tokens from its token command (${server.tokenCommand}), it needs no sign-in; ` +
@@ -145,9 +141,11 @@ passthrough = []) {
145
141
  }
146
142
  }));
147
143
  remote
148
- .command('logout <name>')
149
- .description('forget the sign-in to a server')
150
- .action(guarded('Remote logout was not successful', async (name) => {
144
+ .command('logout [name]')
145
+ .description('forget the sign-in to a server; the name can be left out as for login')
146
+ .action(guarded('Remote logout was not successful', async (given) => {
147
+ // a sign-in outlives its server's registration, so a name given is taken as it is
148
+ const name = given ?? (0, host_config_1.chooseServer)(await (0, host_config_1.readHostConfig)(environment), undefined);
151
149
  const removed = await (0, credentials_1.removeToken)(environment, name);
152
150
  environment.stdout.write(removed ? `signed out of ${name}\n` : `not signed in to ${name}\n`);
153
151
  }));
@@ -186,8 +186,8 @@ function registerWorkCommands(remote, context) {
186
186
  }
187
187
  return { type: 'ref', repo, ref, ...(commit ? { commit } : {}) };
188
188
  };
189
- const connect = async (name) => {
190
- const chosen = await getServer(name);
189
+ const connect = async (name, how) => {
190
+ const chosen = await getServer(name, how);
191
191
  // a CI job or an agent brings its own token, a person signs in
192
192
  const token = await (0, token_source_1.getTokenSource)(environment, chosen.name, chosen.server).token();
193
193
  return { ...chosen, token };
@@ -340,7 +340,7 @@ function registerWorkCommands(remote, context) {
340
340
  remote
341
341
  .command('run <tasks...>')
342
342
  .description('run tasks of a published build file on a server from a git ref, print their output and exit as they did')
343
- .addOption(new commander_1.Option('--server <name>', 'the server to run on; the default of remote use when left out'))
343
+ .addOption(new commander_1.Option('--server <name>', 'the server to run on; when left out, the default of remote use or the only registered server'))
344
344
  .addOption(new commander_1.Option('--build <hash>', 'the published version to run (sha256:...), or HAMMERKIT_BUILD; the hash of the build file here when left out'))
345
345
  .addOption(new commander_1.Option('--repo <host/path>', 'the repository, such as github.com/corp/payments; origin of the checkout here when left out'))
346
346
  .addOption(new commander_1.Option('--ref <ref>', 'the branch or tag to run; the branch checked out here when left out'))
@@ -355,7 +355,7 @@ function registerWorkCommands(remote, context) {
355
355
  const { definition, local } = await runDefinition(options);
356
356
  const source = await refSource(options);
357
357
  const ref = source.ref;
358
- const { name: serverName, server } = await getServer(options.server);
358
+ const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
359
359
  const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
360
360
  const runOptions = {};
361
361
  for (const key of ['env', 'cache', 'timeout', 'maxTimeout']) {
@@ -407,7 +407,7 @@ function registerWorkCommands(remote, context) {
407
407
  .command('up <services...>')
408
408
  .description('start services of a published build file on a server from a git ref and keep them up until their ttl ends, ' +
409
409
  'with their endpoints at addresses of their own behind the sign-in of the server')
410
- .addOption(new commander_1.Option('--server <name>', 'the server to run on; the default of remote use when left out'))
410
+ .addOption(new commander_1.Option('--server <name>', 'the server to run on; when left out, the default of remote use or the only registered server'))
411
411
  .addOption(new commander_1.Option('--endpoint <service:port>', 'publish this port of a service, such as web:8080; may be given more than once').argParser(collectOption))
412
412
  .addOption(new commander_1.Option('--ttl <duration>', 'how long they stay once ready, such as 2h, then they are removed; the server default when left out'))
413
413
  .addOption(new commander_1.Option('--sleep-ttl <duration>', 'how long they stay up without a request, such as 30m, then they sleep until the next request wakes them; ' +
@@ -424,7 +424,7 @@ function registerWorkCommands(remote, context) {
424
424
  const { definition, local } = await runDefinition(options);
425
425
  const endpoints = (options.endpoint ?? []).map(service_tools_1.parseEndpoint);
426
426
  const source = await refSource(options);
427
- const { name: serverName, server } = await getServer(options.server);
427
+ const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
428
428
  const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
429
429
  const submitted = await submitPublishing({ serverName, server, connection }, {
430
430
  definition,
@@ -687,7 +687,7 @@ function registerWorkCommands(remote, context) {
687
687
  .command('verify <tasks...>')
688
688
  .description('check that the server already passed tasks for the files checked out here, without running them; ' +
689
689
  'exits 1 at once for any it did not')
690
- .addOption(new commander_1.Option('--server <name>', 'the server to ask; the default of remote use when left out'))
690
+ .addOption(new commander_1.Option('--server <name>', 'the server to ask; when left out, the default of remote use or the only registered server'))
691
691
  .addOption(new commander_1.Option('--repo <host/path>', 'the repository, such as github.com/corp/payments; origin of the checkout here when left out'))
692
692
  .addOption(new commander_1.Option('--env <name>', 'the environment of the build file, as --env of run'))
693
693
  .action(guarded('Remote verify was not successful', async (tasks, options) => {
@@ -709,7 +709,7 @@ function registerWorkCommands(remote, context) {
709
709
  keys.push({ task, key: found.key });
710
710
  }
711
711
  }
712
- const { name: serverName, server, token } = await connect(options.server);
712
+ const { name: serverName, server, token } = await connect(options.server, 'with --server <name>');
713
713
  const answer = keys.length > 0
714
714
  ? await (0, server_client_1.callServer)(server, token, 'POST', '/v1/checks/lookup', { repo, keys })
715
715
  : { body: { checks: [] } };
@@ -1,10 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.collectSecretCatalog = exports.emptySecretCatalog = void 0;
3
+ exports.collectSecretCatalog = exports.emptySecretCatalog = exports.declared = void 0;
4
4
  const merge_environment_variables_1 = require("../environment/merge-environment-variables");
5
5
  const replace_env_variables_1 = require("../environment/replace-env-variables");
6
6
  const units_1 = require("../utils/units");
7
7
  const DEFAULT_TIMEOUT = '30s';
8
+ // What a record of the catalog holds under a name a build file or a config gives, only when it
9
+ // was declared there: `constructor` or `toString` is no provider or account of any catalog.
10
+ function declared(record, name) {
11
+ return Object.prototype.hasOwnProperty.call(record, name) ? record[name] : undefined;
12
+ }
13
+ exports.declared = declared;
8
14
  function emptySecretCatalog() {
9
15
  return { providers: {}, accounts: {} };
10
16
  }
@@ -51,6 +57,7 @@ function collectSecretCatalog(files, environment, context, host) {
51
57
  }
52
58
  }
53
59
  if (host) {
60
+ catalog.hostConfig = host.fileName;
54
61
  // the host config has no envs of its own: `${NAME}` is read from the process
55
62
  for (const [name, provider] of Object.entries(host.secretProviders ?? {})) {
56
63
  catalog.providers[name] = toProvider(name, provider, {}, host.fileName);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.inspectBundle = exports.planBundle = exports.getCredentialReads = exports.PLAIN_SERVER_ENVS = exports.DefinitionError = void 0;
3
+ exports.inspectBundle = exports.planBundle = exports.getCredentialReads = exports.withSymbolicValues = exports.PLAIN_SERVER_ENVS = exports.DefinitionError = void 0;
4
4
  const promises_1 = require("fs/promises");
5
5
  const os_1 = require("os");
6
6
  const path_1 = require("path");
@@ -25,6 +25,17 @@ exports.DefinitionError = DefinitionError;
25
25
  // Variables of a server that hold no credential (FR-008): a task may read these and
26
26
  // still take arguments, or reach any network. The ones of the run's source are set for each run.
27
27
  exports.PLAIN_SERVER_ENVS = ['PATH', 'HOME', 'CI', ...run_source_envs_1.RUN_SOURCE_ENVS];
28
+ // The environment of runs as a build file is read before anybody runs it (a publish, a
29
+ // proposal, POST /v1/definitions/plan): each variable but the plain ones stands for its name,
30
+ // `${NAME}`. What the server answers about a build file, a description or an image that reads
31
+ // `$NAME` included, then never holds a value a run would see. The tasks of a run read the values.
32
+ function withSymbolicValues(processEnvs) {
33
+ return Object.fromEntries(Object.entries(processEnvs).map(([name, value]) => [
34
+ name,
35
+ value === undefined || exports.PLAIN_SERVER_ENVS.includes(name.toUpperCase()) ? value : `\${${name}}`,
36
+ ]));
37
+ }
38
+ exports.withSymbolicValues = withSymbolicValues;
28
39
  // What an item holds that its command must not hand out: its secrets, and the variables
29
40
  // of the server its `envs` read, but the plain ones.
30
41
  function getCredentialReads(item) {
@@ -256,6 +267,15 @@ function findItemPolicyProblems(item, policy, root) {
256
267
  problems.push(`${item.name}: volume ${volume.name} is not a volume name, a path of the server can't be mounted`);
257
268
  }
258
269
  }
270
+ if (policy.readableEnvs) {
271
+ const allowed = policy.readableEnvs;
272
+ const refusedEnvs = ('envs' in data ? data.envs.processNames ?? [] : []).filter((name) => !exports.PLAIN_SERVER_ENVS.includes(name.toUpperCase()) && !allowed.includes(name));
273
+ if (refusedEnvs.length > 0) {
274
+ problems.push(`${item.name}: reads ${refusedEnvs
275
+ .map((name) => `$${name}`)
276
+ .join(', ')} of the server, which it does not list in ${policy.envsFrom ?? 'runs.env.allow'}`);
277
+ }
278
+ }
259
279
  for (const secret of secretsOf(item)) {
260
280
  const source = secret.source;
261
281
  if (policy.backend === 'kubernetes' && source.type === 'provider') {
@@ -341,6 +361,7 @@ function toPlan(root, item) {
341
361
  deps: item.deps.map((dep) => dep.name).sort(),
342
362
  // by their names in the plan, not the names the task reaches them at (`postgres` of an include)
343
363
  needs: item.needs.map((need) => need.service.name).sort(),
364
+ ...((0, work_service_1.isContainerWorkService)(data) && data.init ? { init: data.init.task.name } : {}),
344
365
  accounts,
345
366
  secrets,
346
367
  serverEnvs: 'envs' in data ? data.envs.processNames ?? [] : [],
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decideRun = exports.sandboxRepos = exports.decideSandbox = exports.sandboxPushBranches = exports.sandboxBranchType = exports.endpointLevel = exports.getGrant = exports.usedAccounts = exports.mayYank = exports.canUse = exports.maySeeDefinitions = exports.mayPublish = exports.mayPropose = exports.mayReadChecks = exports.mayRun = exports.matches = exports.subjectName = void 0;
3
+ exports.decideRun = exports.sandboxRepos = exports.decideSandbox = exports.sandboxPushBranches = exports.sandboxBranchType = exports.endpointLevel = exports.getGrant = exports.usedAccounts = exports.mayYank = exports.accountLevel = exports.canUse = exports.maySeeDefinitions = exports.mayPublish = exports.mayPropose = exports.mayReadChecks = exports.mayRun = exports.matches = exports.subjectName = void 0;
4
4
  const repo_1 = require("./repo");
5
5
  const BUILDS_ORDER = ['run', 'propose', 'publish'];
6
6
  // The name an entitlement gives a subject, for the pages to name its runs by when its tokens
@@ -47,9 +47,15 @@ function maySeeDefinitions(grant) {
47
47
  exports.maySeeDefinitions = maySeeDefinitions;
48
48
  // `use` includes deciding about the runs others request on the account.
49
49
  function canUse(grant, account) {
50
- return grant.accounts[account] === 'use';
50
+ return accountLevel(grant, account) === 'use';
51
51
  }
52
52
  exports.canUse = canUse;
53
+ // The level the caller has for an account, only when an entitlement names it: an account
54
+ // called `constructor` or `toString` is not found on the prototype of the record.
55
+ function accountLevel(grant, account) {
56
+ return Object.prototype.hasOwnProperty.call(grant.accounts, account) ? grant.accounts[account] : undefined;
57
+ }
58
+ exports.accountLevel = accountLevel;
53
59
  // Pulling a version back is a safe thing to do, so it is open to who publishes the build
54
60
  // file, and to who uses an account the version works with: they are the ones who
55
61
  // answer for what runs as it.
@@ -58,13 +64,14 @@ function mayYank(grant, version) {
58
64
  }
59
65
  exports.mayYank = mayYank;
60
66
  function usedAccounts(grant) {
61
- return Object.keys(grant.accounts).filter((account) => grant.accounts[account] === 'use');
67
+ return Object.keys(grant.accounts).filter((account) => canUse(grant, account));
62
68
  }
63
69
  exports.usedAccounts = usedAccounts;
64
70
  // Default deny: a caller without a matching entitlement gets nothing.
65
71
  function getGrant(entitlements, principal) {
66
72
  const matched = [];
67
- const accounts = {};
73
+ // no prototype: an account named like one of its properties (`__proto__`) is a key like any other
74
+ const accounts = Object.create(null);
68
75
  const repos = [];
69
76
  const sandboxes = [];
70
77
  const endpoints = [];
@@ -79,7 +86,7 @@ function getGrant(entitlements, principal) {
79
86
  checks = checks || entitlement.checks === 'read';
80
87
  observe = observe || entitlement.observe === true;
81
88
  for (const [account, level] of Object.entries(entitlement.accounts)) {
82
- if (accounts[account] !== 'use') {
89
+ if (accountLevel({ accounts }, account) !== 'use') {
83
90
  accounts[account] = level;
84
91
  }
85
92
  }
@@ -233,11 +240,11 @@ function decideRun(input) {
233
240
  }
234
241
  const request = [];
235
242
  for (const account of accounts) {
236
- const level = grant.accounts[account];
243
+ const level = accountLevel(grant, account);
237
244
  if (level === undefined) {
238
245
  return { type: 'refuse', status: 403, error: `you may not use the account ${account}, it needs use or request` };
239
246
  }
240
- const rules = catalog[account];
247
+ const rules = Object.prototype.hasOwnProperty.call(catalog, account) ? catalog[account] : undefined;
241
248
  // a sandbox holds changes nobody reviewed: an account takes its runs only when it says so
242
249
  const sources = rules?.source ?? ['ref', 'upload'];
243
250
  if (!sources.includes(source.type)) {
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RepoAccess = void 0;
4
4
  const redact_1 = require("../utils/redact");
5
5
  const provider_values_1 = require("../secrets/provider-values");
6
+ const secret_catalog_1 = require("../secrets/secret-catalog");
6
7
  const git_checkout_1 = require("./git-checkout");
7
8
  const repo_1 = require("./repo");
8
9
  // A token is read again after this long, so a short-lived one (a GitHub App
@@ -119,9 +120,9 @@ class RepoAccess {
119
120
  const catalog = this.environment.hosted?.catalog;
120
121
  const kind = secret.from.substring(0, secret.from.indexOf(':'));
121
122
  const ref = secret.from.substring(secret.from.indexOf(':') + 1);
122
- const provider = catalog.providers[kind];
123
- const account = catalog.accounts[secret.account];
124
- const credentials = account?.providers[kind];
123
+ const provider = (0, secret_catalog_1.declared)(catalog.providers, kind);
124
+ const account = (0, secret_catalog_1.declared)(catalog.accounts, secret.account);
125
+ const credentials = account ? (0, secret_catalog_1.declared)(account.providers, kind) : undefined;
125
126
  if (!provider || !credentials) {
126
127
  throw new Error(`the source credential ${secret.from} as ${secret.account} is not defined`);
127
128
  }
@@ -594,8 +594,9 @@ exports.serverConfigSchema = zod_1.z
594
594
  // the most open network a task or service of a run on a sandbox gets, written as
595
595
  // a task's `network`: only the services it needs by default
596
596
  network: network_schema_1.networkSchema.default('none'),
597
- // the variables of `runs.env.allow` an `env:` secret of a run on a sandbox may
598
- // read: none by default, a sandbox holds code nobody reviewed
597
+ // the variables of runs (`runs.env.allow` and `runs.env.set`) an `env:` secret and the
598
+ // `envs` of a build file of a run on a sandbox may read, besides PATH, HOME and CI:
599
+ // none by default, a sandbox holds code nobody reviewed
599
600
  env: zod_1.z
600
601
  .object({ allow: zod_1.z.array(zod_1.z.string().regex(/^[A-Za-z_][A-Za-z0-9_()]*$/)).default([]) })
601
602
  .strict()
@@ -788,11 +789,11 @@ exports.serverConfigSchema = zod_1.z
788
789
  });
789
790
  }
790
791
  config.sandboxes.env.allow.forEach((name, index) => {
791
- if (!config.runs.env.allow.includes(name)) {
792
+ if (!config.runs.env.allow.includes(name) && !Object.prototype.hasOwnProperty.call(config.runs.env.set, name)) {
792
793
  ctx.addIssue({
793
794
  code: zod_1.z.ZodIssueCode.custom,
794
795
  path: ['sandboxes', 'env', 'allow', index],
795
- message: `${name} is not in runs.env.allow, no run can read it`,
796
+ message: `${name} is not in runs.env.allow or runs.env.set, no run can read it`,
796
797
  });
797
798
  }
798
799
  });
@@ -38,6 +38,7 @@ const sandbox_storage_1 = require("./sandbox-storage");
38
38
  const kubernetes_sandbox_storage_1 = require("./kubernetes-sandbox-storage");
39
39
  const sandbox_docker_1 = require("./sandbox-docker");
40
40
  const sandboxes_api_1 = require("./sandboxes-api");
41
+ const plan_1 = require("./plan");
41
42
  const endpoints_1 = require("./endpoints");
42
43
  const service_runs_1 = require("./service-runs");
43
44
  const units_1 = require("../utils/units");
@@ -152,7 +153,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
152
153
  const grant = (0, policy_1.getGrant)(config.entitlements, principal);
153
154
  const run = registry.cancel(principal, id, accountsOf(config, principal), (up) => (0, service_runs_1.mayPublishEndpoints)(grant, up));
154
155
  log(`cancel iss=${principal.iss} sub=${principal.sub} run=${id} found=${Boolean(run)}`);
155
- run ? (0, http_2.send)(res, 200, toRunResponse(run)) : (0, http_2.send)(res, 404, { error: 'not found' });
156
+ run ? (0, http_2.send)(res, 200, answerRun(config, principal, run)) : (0, http_2.send)(res, 404, { error: 'not found' });
156
157
  }
157
158
  else if (action === 'extend') {
158
159
  if (method !== 'POST') {
@@ -180,7 +181,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
180
181
  (0, http_2.send)(res, 409, { error: result.reason });
181
182
  }
182
183
  else {
183
- (0, http_2.send)(res, 200, toRunResponse(result.run));
184
+ (0, http_2.send)(res, 200, answerRun(config, principal, result.run));
184
185
  }
185
186
  }
186
187
  else if (method !== 'GET') {
@@ -268,9 +269,18 @@ async function extendRun(config, registry, log, principal, id, req, res) {
268
269
  (0, http_2.send)(res, 409, { error: `the run is ${result.state}, only a service run that is up can be extended` });
269
270
  }
270
271
  else {
271
- (0, http_2.send)(res, 200, toRunResponse(result.run));
272
+ (0, http_2.send)(res, 200, answerRun(config, principal, result.run));
272
273
  }
273
274
  }
275
+ // What a stop, an extend or a wake answers: the run whole for who may read it (its owner, who
276
+ // decides about it, `observe`), else what the list shows of it. Who may only open or publish
277
+ // endpoints of its repository is told how it stands, not its arguments, plan or log.
278
+ function answerRun(config, principal, run) {
279
+ const viewer = (0, overview_1.getViewer)(config, principal);
280
+ return (0, overview_1.mayRead)(viewer, run)
281
+ ? toRunResponse(run, undefined, !(0, overview_1.owns)(viewer, run), viewer.nameOf)
282
+ : (0, overview_1.toListedRun)(viewer, run);
283
+ }
274
284
  // Why the owner of a service run that sleeps may no longer run it, with the entitlements of
275
285
  // the moment: a wake is started by who opens an endpoint, but runs as the owner, as a new
276
286
  // run of theirs would.
@@ -816,9 +826,14 @@ async function startServer(config, environment, options = {}) {
816
826
  },
817
827
  };
818
828
  const storage = config.storage.directory ?? (0, path_1.join)((0, get_cache_directory_1.getHammerkitDirectory)(), 'server');
819
- const definitions = new definitions_1.DefinitionStore((0, path_1.join)(storage, 'definitions'), planning.environment, {
820
- policy: planning.policy,
821
- });
829
+ // a build file nobody ran yet is read with the names of the variables, not their values
830
+ const definitions = new definitions_1.DefinitionStore((0, path_1.join)(storage, 'definitions'), {
831
+ ...planning.environment,
832
+ hosted: {
833
+ ...planning.environment.hosted,
834
+ buildFileEnvs: (0, plan_1.withSymbolicValues)(planning.environment.processEnvs),
835
+ },
836
+ }, { policy: planning.policy });
822
837
  await definitions.load();
823
838
  const repos = new repo_access_1.RepoAccess(config, planning.environment, options.repos);
824
839
  const sandboxRuntimes = (0, server_config_1.getSandboxRuntimes)(config);
@@ -847,6 +862,8 @@ async function startServer(config, environment, options = {}) {
847
862
  ...planning.policy,
848
863
  envs: config.sandboxes.env.allow,
849
864
  envsFrom: 'sandboxes.env.allow',
865
+ // and what its build files read of the run's variables, `$NAME` in its `envs`
866
+ readableEnvs: config.sandboxes.env.allow,
850
867
  runtimes: sandboxRuntimes,
851
868
  capabilities: config.sandboxes.capabilities,
852
869
  capabilitiesFrom: 'sandboxes.capabilities',
@@ -38,7 +38,9 @@ function containerPorts(plan) {
38
38
  * Why the endpoints of a service run can't be published, or null. Each is a port its
39
39
  * service declares, of a service the run starts. Under a `runs.secretNetwork` below `open`
40
40
  * a service behind an endpoint may not read a secret or a credential of the server: a page
41
- * is a way out that no mask of the log covers.
41
+ * is a way out that no mask of the log covers. Nor may what it is made from or talks to: a
42
+ * task it depends on (its init task too) can leave a value in a file the service serves,
43
+ * and a service it needs can hand one over the connection it answers on.
42
44
  */
43
45
  function refuseEndpoints(request, plan, secretNetworkOpen) {
44
46
  for (const endpoint of request.endpoints) {
@@ -50,14 +52,50 @@ function refuseEndpoints(request, plan, secretNetworkOpen) {
50
52
  const ports = containerPorts(item);
51
53
  return `${endpoint.service} has no port ${endpoint.port}${ports.length > 0 ? `, its ports are ${ports.join(', ')}` : ', it declares none'}`;
52
54
  }
53
- const reads = (0, plan_1.getCredentialReads)(item);
54
- if (!secretNetworkOpen && reads.length > 0) {
55
- return `${endpoint.service} reads ${reads.join(', ')}, it can not be behind an endpoint on this server (runs.secretNetwork): a page could show it`;
55
+ if (secretNetworkOpen) {
56
+ continue;
57
+ }
58
+ for (const { name, path } of reachedFrom(endpoint.service, plan)) {
59
+ const reads = (0, plan_1.getCredentialReads)(plan[name]);
60
+ if (reads.length === 0) {
61
+ continue;
62
+ }
63
+ const what = reads.join(', ');
64
+ if (path.length === 0) {
65
+ return `${name} reads ${what}, it can not be behind an endpoint on this server (runs.secretNetwork): a page could show it`;
66
+ }
67
+ // the way from the service to what reads it: `web needs api, which needs vault`
68
+ const way = path.map((step, index) => `${index === 0 ? '' : ', which '}${step.relation} ${step.name}`).join('');
69
+ return (`${endpoint.service} ${way}, which reads ${what}: ` +
70
+ 'it can not be behind an endpoint on this server (runs.secretNetwork), a page could show it');
56
71
  }
57
72
  }
58
73
  return null;
59
74
  }
60
75
  exports.refuseEndpoints = refuseEndpoints;
76
+ function reachedFrom(service, plan) {
77
+ if (!plan[service]) {
78
+ return [];
79
+ }
80
+ const reached = [{ name: service, path: [] }];
81
+ const seen = new Set([service]);
82
+ for (let index = 0; index < reached.length; index++) {
83
+ const { name, path } = reached[index];
84
+ const item = plan[name];
85
+ const next = [
86
+ ...(item.init ? [{ relation: 'is initialized by', name: item.init }] : []),
87
+ ...(item.deps ?? []).map((dep) => ({ relation: 'depends on', name: dep })),
88
+ ...(item.needs ?? []).map((need) => ({ relation: 'needs', name: need })),
89
+ ];
90
+ for (const step of next) {
91
+ if (plan[step.name] && !seen.has(step.name)) {
92
+ seen.add(step.name);
93
+ reached.push({ name: step.name, path: [...path, step] });
94
+ }
95
+ }
96
+ }
97
+ return reached;
98
+ }
61
99
  function toRunEndpoints(endpoints, hosts, url) {
62
100
  return endpoints.map((endpoint, index) => ({
63
101
  service: endpoint.service,
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.lineSplitter = exports.MAX_LINE_CHARS = void 0;
4
+ const string_decoder_1 = require("string_decoder");
5
+ // The most of a line that is held back for its end: a longer one is passed on in parts.
6
+ exports.MAX_LINE_CHARS = 64 * 1024;
7
+ /**
8
+ * The lines of output that arrives in chunks, split where getLogs splits a chunk: at a line
9
+ * feed, with a CR before it. A line that two chunks (or two frames of docker) split is passed
10
+ * on whole once it ends, so the mask of the secrets of a run (SecretRegistry.redact, which
11
+ * works per line) covers a value that was split between them. Empty lines are left out, as
12
+ * getLogs does. A line of more than `maxChars` is passed on in parts of that length.
13
+ */
14
+ function lineSplitter(onLine, maxChars = exports.MAX_LINE_CHARS) {
15
+ // a character split between two chunks stays whole
16
+ const decoder = new string_decoder_1.StringDecoder('utf8');
17
+ let pending = '';
18
+ const take = (text) => {
19
+ const lines = (pending + text).split(/\r?\n/);
20
+ pending = lines.pop() ?? '';
21
+ for (const line of lines) {
22
+ if (line) {
23
+ onLine(line);
24
+ }
25
+ }
26
+ while (pending.length > maxChars) {
27
+ onLine(pending.slice(0, maxChars));
28
+ pending = pending.slice(maxChars);
29
+ }
30
+ };
31
+ let ended = false;
32
+ return {
33
+ write(chunk) {
34
+ if (!ended) {
35
+ take(typeof chunk === 'string' ? chunk : decoder.write(chunk));
36
+ }
37
+ },
38
+ end() {
39
+ if (ended) {
40
+ return;
41
+ }
42
+ ended = true;
43
+ take(decoder.end());
44
+ if (pending) {
45
+ onLine(pending);
46
+ pending = '';
47
+ }
48
+ },
49
+ };
50
+ }
51
+ exports.lineSplitter = lineSplitter;
52
+ //# sourceMappingURL=line-splitter.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hammerkit",
3
3
  "description": "Containerized build tool with incremental caching that runs the same build file locally, in Docker and on Kubernetes.",
4
- "version": "2.0.0-next.17",
4
+ "version": "2.0.0-next.19",
5
5
  "keywords": [
6
6
  "build",
7
7
  "build-tool",