@agledger/mcp-server 3.1.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +81 -61
- package/README.md +15 -14
- package/dist/api-client.d.ts +18 -0
- package/dist/api-client.js +80 -20
- package/dist/credentials.d.ts +52 -1
- package/dist/credentials.js +184 -10
- package/dist/delegation.js +2 -1
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +18 -0
- package/dist/index.js +66 -17
- package/dist/server.d.ts +13 -1
- package/dist/server.js +245 -138
- package/dist/zod-integrity.d.ts +7 -7
- package/dist/zod-integrity.js +11 -9
- package/package.json +12 -10
package/dist/api-client.js
CHANGED
|
@@ -2,6 +2,16 @@ import { ApiKeyCredential, cutSecret } from './credentials.js';
|
|
|
2
2
|
import { namesDelegation, ON_BEHALF_OF_HEADER } from './delegation.js';
|
|
3
3
|
import { SERVER_VERSION } from './version.js';
|
|
4
4
|
const USER_AGENT = `agledger-mcp-server/${SERVER_VERSION}`;
|
|
5
|
+
/** Retry-After as seconds from now: delay-seconds, or an HTTP date. Undefined when absent or unreadable. */
|
|
6
|
+
function retryAfterSeconds(header) {
|
|
7
|
+
if (header === null)
|
|
8
|
+
return undefined;
|
|
9
|
+
const value = header.trim();
|
|
10
|
+
if (/^\d+$/.test(value))
|
|
11
|
+
return Number(value);
|
|
12
|
+
const at = Date.parse(value);
|
|
13
|
+
return Number.isNaN(at) ? undefined : Math.max(0, Math.ceil((at - Date.now()) / 1000));
|
|
14
|
+
}
|
|
5
15
|
// Strip trailing slashes with a single linear scan. A regex like /\/+$/ is
|
|
6
16
|
// O(n^2) on inputs of many slashes (CodeQL js/polynomial-redos); this is O(n).
|
|
7
17
|
function stripTrailingSlashes(s) {
|
|
@@ -10,6 +20,29 @@ function stripTrailingSlashes(s) {
|
|
|
10
20
|
end--;
|
|
11
21
|
return s.slice(0, end);
|
|
12
22
|
}
|
|
23
|
+
/** A query value the bracket form cannot carry: an object or array nested below its one level. */
|
|
24
|
+
export class QueryShapeError extends Error {
|
|
25
|
+
param;
|
|
26
|
+
constructor(param) {
|
|
27
|
+
super(`Query parameter ${param} is a nested object or array, which has no query-string form: the bracket form goes one level deep (criteriaGte[amount]=500).`);
|
|
28
|
+
this.param = param;
|
|
29
|
+
this.name = 'QueryShapeError';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A query value as text. A value below the bracket form's one level is
|
|
34
|
+
* refused rather than sent as `[object Object]`, which the Server would read
|
|
35
|
+
* as a filter on that literal string.
|
|
36
|
+
*/
|
|
37
|
+
function queryScalar(name, value) {
|
|
38
|
+
if (value instanceof Date)
|
|
39
|
+
return value.toISOString();
|
|
40
|
+
if (typeof value === 'string')
|
|
41
|
+
return value;
|
|
42
|
+
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint')
|
|
43
|
+
return String(value);
|
|
44
|
+
throw new QueryShapeError(name);
|
|
45
|
+
}
|
|
13
46
|
/**
|
|
14
47
|
* Serialize one query parameter.
|
|
15
48
|
*
|
|
@@ -30,7 +63,7 @@ function appendQueryParam(search, key, value) {
|
|
|
30
63
|
for (const item of value) {
|
|
31
64
|
if (item === undefined || item === null)
|
|
32
65
|
continue;
|
|
33
|
-
search.append(key,
|
|
66
|
+
search.append(key, queryScalar(key, item));
|
|
34
67
|
}
|
|
35
68
|
return;
|
|
36
69
|
}
|
|
@@ -38,11 +71,11 @@ function appendQueryParam(search, key, value) {
|
|
|
38
71
|
for (const [sub, subValue] of Object.entries(value)) {
|
|
39
72
|
if (subValue === undefined || subValue === null)
|
|
40
73
|
continue;
|
|
41
|
-
search.set(`${key}[${sub}]`,
|
|
74
|
+
search.set(`${key}[${sub}]`, queryScalar(`${key}[${sub}]`, subValue));
|
|
42
75
|
}
|
|
43
76
|
return;
|
|
44
77
|
}
|
|
45
|
-
search.set(key,
|
|
78
|
+
search.set(key, queryScalar(key, value));
|
|
46
79
|
}
|
|
47
80
|
export class ApiClient {
|
|
48
81
|
apiUrl;
|
|
@@ -65,15 +98,7 @@ export class ApiClient {
|
|
|
65
98
|
return this.delegation?.origin;
|
|
66
99
|
}
|
|
67
100
|
async request(method, path, options) {
|
|
68
|
-
const url =
|
|
69
|
-
// Defense-in-depth: pin every request to the configured API origin. A
|
|
70
|
-
// protocol-relative or absolute `path` (e.g. `//evil.com/x`,
|
|
71
|
-
// `https://evil.com`) resolves against the base to a different origin, which
|
|
72
|
-
// would leak the `Authorization: Bearer` header off-host. No caller
|
|
73
|
-
// may steer the client off-origin.
|
|
74
|
-
if (url.origin !== new URL(this.apiUrl).origin) {
|
|
75
|
-
throw new Error(`Refusing to send request off-origin: path "${path}" resolves to ${url.origin}, expected ${new URL(this.apiUrl).origin}.`);
|
|
76
|
-
}
|
|
101
|
+
const url = this.urlFor(path);
|
|
77
102
|
if (options?.query) {
|
|
78
103
|
for (const [k, v] of Object.entries(options.query)) {
|
|
79
104
|
if (v !== undefined && v !== null) {
|
|
@@ -112,7 +137,8 @@ export class ApiClient {
|
|
|
112
137
|
Object.assign(headers, this.credential.signBody(body));
|
|
113
138
|
}
|
|
114
139
|
// Every route that declares AGLedger-On-Behalf-Of is a POST.
|
|
115
|
-
|
|
140
|
+
const delegation = this.delegation;
|
|
141
|
+
let onBehalfOf = delegation && method.toUpperCase() === 'POST' ? await delegation.token() : undefined;
|
|
116
142
|
const withDelegation = (h) => onBehalfOf ? { ...h, [ON_BEHALF_OF_HEADER]: onBehalfOf } : h;
|
|
117
143
|
const ctx = { postAnonymous: (p, b) => this.postAnonymous(p, b) };
|
|
118
144
|
let bearer = await this.credential.bearer(ctx);
|
|
@@ -123,9 +149,9 @@ export class ApiClient {
|
|
|
123
149
|
// delegation token is re-read only when the Server names it; otherwise a
|
|
124
150
|
// cert can be revoked or expire server-side before our clock says so, and
|
|
125
151
|
// gets exactly one re-exchange. A second 401 is the answer.
|
|
126
|
-
if (onBehalfOf && namesDelegation(first.body)) {
|
|
152
|
+
if (delegation && onBehalfOf && namesDelegation(first.body)) {
|
|
127
153
|
const refused = onBehalfOf;
|
|
128
|
-
onBehalfOf = await
|
|
154
|
+
onBehalfOf = await delegation.token(refused);
|
|
129
155
|
if (onBehalfOf === refused)
|
|
130
156
|
return this.scrubbed(first, refused);
|
|
131
157
|
}
|
|
@@ -138,12 +164,33 @@ export class ApiClient {
|
|
|
138
164
|
const second = await this.send(url, method, withDelegation({ ...headers, Authorization: `Bearer ${bearer}` }), body);
|
|
139
165
|
return this.scrubbed(second, onBehalfOf);
|
|
140
166
|
}
|
|
167
|
+
/**
|
|
168
|
+
* The request URL: the base URL (with any path prefix, such as a gateway
|
|
169
|
+
* mount point) followed by `path`. `new URL(path, base)` would replace that
|
|
170
|
+
* prefix.
|
|
171
|
+
*
|
|
172
|
+
* Defense-in-depth: every request is pinned to the configured API origin. A
|
|
173
|
+
* protocol-relative or absolute `path` (e.g. `//evil.com/x`,
|
|
174
|
+
* `https://evil.com`) would send the `Authorization: Bearer` header off-host,
|
|
175
|
+
* and no caller may steer the client there.
|
|
176
|
+
*/
|
|
177
|
+
urlFor(path) {
|
|
178
|
+
const origin = new URL(this.apiUrl).origin;
|
|
179
|
+
if (!path.startsWith('/') || path.startsWith('//')) {
|
|
180
|
+
throw new Error(`Refusing to send request off-origin: path "${path}" is not an absolute path on ${origin}.`);
|
|
181
|
+
}
|
|
182
|
+
const url = new URL(this.apiUrl + path);
|
|
183
|
+
if (url.origin !== origin) {
|
|
184
|
+
throw new Error(`Refusing to send request off-origin: path "${path}" resolves to ${url.origin}, expected ${origin}.`);
|
|
185
|
+
}
|
|
186
|
+
return url;
|
|
187
|
+
}
|
|
141
188
|
/** The delegation token never comes back to a tool, even if the Server echoes it. */
|
|
142
189
|
scrubbed(res, onBehalfOf) {
|
|
143
190
|
return onBehalfOf ? { ...res, body: cutSecret(res.body, onBehalfOf) } : res;
|
|
144
191
|
}
|
|
145
192
|
async postAnonymous(path, payload) {
|
|
146
|
-
const res = await this.send(
|
|
193
|
+
const res = await this.send(this.urlFor(path), 'POST', { Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': USER_AGENT }, JSON.stringify(payload));
|
|
147
194
|
return { status: res.status, body: res.body };
|
|
148
195
|
}
|
|
149
196
|
async send(url, method, headers, body) {
|
|
@@ -157,15 +204,28 @@ export class ApiClient {
|
|
|
157
204
|
signal: controller.signal,
|
|
158
205
|
});
|
|
159
206
|
const contentType = res.headers.get('content-type') ?? '';
|
|
207
|
+
// Text first: `res.json()` throws on an empty body, which turned a
|
|
208
|
+
// successful 204 write into an error the caller could retry. An empty body
|
|
209
|
+
// is `{}`, and a body that does not parse under a JSON content type is
|
|
210
|
+
// handed back as the text it was.
|
|
211
|
+
const text = await res.text();
|
|
160
212
|
let parsed;
|
|
161
|
-
if (
|
|
162
|
-
parsed =
|
|
213
|
+
if (text === '') {
|
|
214
|
+
parsed = {};
|
|
215
|
+
}
|
|
216
|
+
else if (contentType.includes('json')) {
|
|
217
|
+
try {
|
|
218
|
+
parsed = JSON.parse(text);
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
parsed = { _raw: text, _contentType: contentType };
|
|
222
|
+
}
|
|
163
223
|
}
|
|
164
224
|
else {
|
|
165
|
-
const text = await res.text();
|
|
166
225
|
parsed = { _raw: text, _contentType: contentType };
|
|
167
226
|
}
|
|
168
|
-
|
|
227
|
+
const retryAfter = retryAfterSeconds(res.headers.get('retry-after'));
|
|
228
|
+
return { status: res.status, body: parsed, ok: res.ok, ...(retryAfter !== undefined ? { retryAfterSeconds: retryAfter } : {}) };
|
|
169
229
|
}
|
|
170
230
|
finally {
|
|
171
231
|
clearTimeout(timeout);
|
package/dist/credentials.d.ts
CHANGED
|
@@ -16,11 +16,13 @@
|
|
|
16
16
|
* output. Server error bodies and token-command stderr are scrubbed before
|
|
17
17
|
* they are surfaced, because either can echo a token back.
|
|
18
18
|
*/
|
|
19
|
-
/** The env vars the server reads a token source from.
|
|
19
|
+
/** The env vars the server reads a token source from. */
|
|
20
20
|
export declare const OIDC_ENV: {
|
|
21
21
|
readonly TOKEN_CMD: 'AGLEDGER_OIDC_TOKEN_CMD';
|
|
22
22
|
readonly TOKEN_FILE: 'AGLEDGER_OIDC_TOKEN_FILE';
|
|
23
23
|
readonly AGENT_ID: 'AGLEDGER_OIDC_AGENT_ID';
|
|
24
|
+
/** A JWK Set file each cert exchange adds the server's public key to, for agledger_verify's agentKeys. */
|
|
25
|
+
readonly AGENT_KEYS_FILE: 'AGLEDGER_AGENT_KEYS_FILE';
|
|
24
26
|
};
|
|
25
27
|
/** Replace anything shaped like a JWT with a placeholder. */
|
|
26
28
|
export declare function redactTokens(text: string): string;
|
|
@@ -43,6 +45,36 @@ export declare class OidcTokenSourceError extends Error {
|
|
|
43
45
|
/** @param unrotated the source returned the token it returned last time, which is expected for a file between rotations */
|
|
44
46
|
constructor(message: string, unrotated?: boolean);
|
|
45
47
|
}
|
|
48
|
+
/** The agent keys file could not be read or written; nothing was signed under the new cert. */
|
|
49
|
+
export declare class AgentKeysFileError extends Error {
|
|
50
|
+
readonly path: string;
|
|
51
|
+
readonly code = "AGENT_KEYS_FILE_FAILED";
|
|
52
|
+
constructor(message: string, path: string);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Add one exchanged cert's public key to the JWK Set at `path`, creating it if
|
|
56
|
+
* needed: `{ keys: [{ publicKeyJwk, certId, agentId, issuedAt, expiresAt }] }`,
|
|
57
|
+
* the shape every AGLedger verifier's agent keys input reads. A key already
|
|
58
|
+
* listed is not added twice. Written through a temp file and a rename; a file
|
|
59
|
+
* that does not hold a `keys` list is refused, never overwritten. The read and
|
|
60
|
+
* the write happen under `<path>.lock`, the same lock the agledger CLI takes,
|
|
61
|
+
* so processes sharing one file each add their key. The same format and rules
|
|
62
|
+
* as the CLI's `--agent-keys-file`.
|
|
63
|
+
*/
|
|
64
|
+
export declare function recordAgentKey(path: string, entry: {
|
|
65
|
+
publicKeyJwk: {
|
|
66
|
+
kty: 'OKP';
|
|
67
|
+
crv: 'Ed25519';
|
|
68
|
+
x: string;
|
|
69
|
+
};
|
|
70
|
+
} & Record<string, unknown>): Promise<void>;
|
|
71
|
+
/** Bounds on the agent keys file lock. Mutable so tests can shorten them. */
|
|
72
|
+
export declare const KEYS_FILE_LOCK: {
|
|
73
|
+
/** How long to wait for another process to release the lock. */
|
|
74
|
+
waitMs: number;
|
|
75
|
+
/** A lock older than this was left by a process that died holding it. */
|
|
76
|
+
staleMs: number;
|
|
77
|
+
};
|
|
46
78
|
/** The Server refused the exchange. `body` is its error response, scrubbed. */
|
|
47
79
|
export declare class OidcExchangeError extends Error {
|
|
48
80
|
readonly status: number;
|
|
@@ -62,6 +94,8 @@ export interface TokenCommandOptions {
|
|
|
62
94
|
/** Refuse more stdout than this. Default 64 KiB; a JWT is a few KiB at most. */
|
|
63
95
|
maxStdoutBytes?: number;
|
|
64
96
|
}
|
|
97
|
+
/** Kill every token command still running. For a signal handler: the commands run detached, so they would outlive this process. */
|
|
98
|
+
export declare function killRunningTokenCommands(): void;
|
|
65
99
|
/**
|
|
66
100
|
* Runs a shell command on every call; its stdout is the token. The command
|
|
67
101
|
* runs in its own process group, which is killed on timeout, on oversized
|
|
@@ -111,6 +145,12 @@ export interface OidcCertCredentialOptions {
|
|
|
111
145
|
* CERT_AGENT_BINDING_MISMATCH rather than bind a different one.
|
|
112
146
|
*/
|
|
113
147
|
agentId?: string;
|
|
148
|
+
/**
|
|
149
|
+
* A JWK Set file the cert's public key is added to on each exchange, before
|
|
150
|
+
* the cert is used (see {@link recordAgentKey}), so the agent signatures
|
|
151
|
+
* this server seals can be re-verified offline.
|
|
152
|
+
*/
|
|
153
|
+
agentKeysFile?: string;
|
|
114
154
|
/** Re-exchange once this fraction of the cert's lifetime has passed. Default 0.5. */
|
|
115
155
|
refreshFraction?: number;
|
|
116
156
|
/** Names the token source in errors, e.g. `AGLEDGER_OIDC_TOKEN_FILE`. */
|
|
@@ -124,6 +164,7 @@ export declare class OidcCertCredential implements Credential {
|
|
|
124
164
|
readonly renewable = true;
|
|
125
165
|
private readonly getOidcToken;
|
|
126
166
|
private readonly agentId;
|
|
167
|
+
private readonly agentKeysFile;
|
|
127
168
|
private readonly refreshFraction;
|
|
128
169
|
private readonly origin;
|
|
129
170
|
private readonly onWarning;
|
|
@@ -136,6 +177,16 @@ export declare class OidcCertCredential implements Credential {
|
|
|
136
177
|
/** The last token the Server accepted. A token carrying a `jti` is exchangeable once. */
|
|
137
178
|
private lastExchangedToken;
|
|
138
179
|
constructor(options: OidcCertCredentialOptions);
|
|
180
|
+
/**
|
|
181
|
+
* The public half of this server's key pair, as sent at every exchange. The
|
|
182
|
+
* cert carries only its thumbprint; this is the key agledger_verify's
|
|
183
|
+
* agentKeys needs to re-verify what this server signed. One per process.
|
|
184
|
+
*/
|
|
185
|
+
get publicKeyJwk(): {
|
|
186
|
+
kty: 'OKP';
|
|
187
|
+
crv: 'Ed25519';
|
|
188
|
+
x: string;
|
|
189
|
+
};
|
|
139
190
|
bearer(ctx: CredentialContext): Promise<string>;
|
|
140
191
|
signBody(body: string): Record<string, string>;
|
|
141
192
|
/** Single-flight: concurrent callers share one exchange. */
|
package/dist/credentials.js
CHANGED
|
@@ -18,12 +18,16 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import { spawn } from 'node:child_process';
|
|
20
20
|
import { createHash, generateKeyPairSync, sign } from 'node:crypto';
|
|
21
|
-
import { readFile } from 'node:fs/promises';
|
|
22
|
-
|
|
21
|
+
import { link, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
22
|
+
import { dirname, join } from 'node:path';
|
|
23
|
+
import { errorMessage } from './errors.js';
|
|
24
|
+
/** The env vars the server reads a token source from. */
|
|
23
25
|
export const OIDC_ENV = {
|
|
24
26
|
TOKEN_CMD: 'AGLEDGER_OIDC_TOKEN_CMD',
|
|
25
27
|
TOKEN_FILE: 'AGLEDGER_OIDC_TOKEN_FILE',
|
|
26
28
|
AGENT_ID: 'AGLEDGER_OIDC_AGENT_ID',
|
|
29
|
+
/** A JWK Set file each cert exchange adds the server's public key to, for agledger_verify's agentKeys. */
|
|
30
|
+
AGENT_KEYS_FILE: 'AGLEDGER_AGENT_KEYS_FILE',
|
|
27
31
|
};
|
|
28
32
|
const EXCHANGE_PATH = '/v1/auth/oidc/cert';
|
|
29
33
|
const POP_CONTEXT = 'agledger.oidc.cert.v1\n';
|
|
@@ -36,7 +40,7 @@ const JWT_PATTERN = /eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g;
|
|
|
36
40
|
const REDACTED = '<redacted-token>';
|
|
37
41
|
/** Replace anything shaped like a JWT with a placeholder. */
|
|
38
42
|
export function redactTokens(text) {
|
|
39
|
-
return text.
|
|
43
|
+
return text.replaceAll(JWT_PATTERN, REDACTED);
|
|
40
44
|
}
|
|
41
45
|
/**
|
|
42
46
|
* Deep-copy a JSON value with every string passed through `redactTokens`, and
|
|
@@ -75,6 +79,139 @@ export class OidcTokenSourceError extends Error {
|
|
|
75
79
|
this.name = 'OidcTokenSourceError';
|
|
76
80
|
}
|
|
77
81
|
}
|
|
82
|
+
/** The agent keys file could not be read or written; nothing was signed under the new cert. */
|
|
83
|
+
export class AgentKeysFileError extends Error {
|
|
84
|
+
path;
|
|
85
|
+
code = 'AGENT_KEYS_FILE_FAILED';
|
|
86
|
+
constructor(message, path) {
|
|
87
|
+
super(message);
|
|
88
|
+
this.path = path;
|
|
89
|
+
this.name = 'AgentKeysFileError';
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Add one exchanged cert's public key to the JWK Set at `path`, creating it if
|
|
94
|
+
* needed: `{ keys: [{ publicKeyJwk, certId, agentId, issuedAt, expiresAt }] }`,
|
|
95
|
+
* the shape every AGLedger verifier's agent keys input reads. A key already
|
|
96
|
+
* listed is not added twice. Written through a temp file and a rename; a file
|
|
97
|
+
* that does not hold a `keys` list is refused, never overwritten. The read and
|
|
98
|
+
* the write happen under `<path>.lock`, the same lock the agledger CLI takes,
|
|
99
|
+
* so processes sharing one file each add their key. The same format and rules
|
|
100
|
+
* as the CLI's `--agent-keys-file`.
|
|
101
|
+
*/
|
|
102
|
+
export async function recordAgentKey(path, entry) {
|
|
103
|
+
await withKeysFileLock(path, () => appendAgentKey(path, entry));
|
|
104
|
+
}
|
|
105
|
+
/** Bounds on the agent keys file lock. Mutable so tests can shorten them. */
|
|
106
|
+
export const KEYS_FILE_LOCK = {
|
|
107
|
+
/** How long to wait for another process to release the lock. */
|
|
108
|
+
waitMs: 15_000,
|
|
109
|
+
/** A lock older than this was left by a process that died holding it. */
|
|
110
|
+
staleMs: 10_000,
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Run `fn` holding `<path>.lock`, an exclusively created file the holder
|
|
114
|
+
* deletes when done. A lock older than `KEYS_FILE_LOCK.staleMs` is taken over:
|
|
115
|
+
* renamed aside (atomic, so one waiter wins), and put back if what moved was a
|
|
116
|
+
* fresh lock rather than the stale one. Matches the agledger CLI's lock.
|
|
117
|
+
*/
|
|
118
|
+
async function withKeysFileLock(path, fn) {
|
|
119
|
+
const lock = `${path}.lock`;
|
|
120
|
+
const deadline = Date.now() + KEYS_FILE_LOCK.waitMs;
|
|
121
|
+
for (let delay = 5;; delay = Math.min(delay * 2, 100)) {
|
|
122
|
+
try {
|
|
123
|
+
await (await open(lock, 'wx')).close();
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
catch (err) {
|
|
127
|
+
const code = err.code;
|
|
128
|
+
if (code !== 'EEXIST') {
|
|
129
|
+
throw new AgentKeysFileError(`Cannot create the agent keys file lock ${lock} (${code ?? errorMessage(err)}).`, path);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (await breakStaleLock(lock))
|
|
133
|
+
continue;
|
|
134
|
+
if (Date.now() >= deadline) {
|
|
135
|
+
throw new AgentKeysFileError(`The agent keys file ${path} stayed locked by another process for ${KEYS_FILE_LOCK.waitMs / 1000}s. If no agledger process is running, delete ${lock}.`, path);
|
|
136
|
+
}
|
|
137
|
+
await new Promise((r) => setTimeout(r, delay + Math.random() * delay));
|
|
138
|
+
}
|
|
139
|
+
try {
|
|
140
|
+
return await fn();
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
await rm(lock, { force: true });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** Remove `lock` if it is stale. True when the caller should try to take it again. */
|
|
147
|
+
async function breakStaleLock(lock) {
|
|
148
|
+
let seen;
|
|
149
|
+
try {
|
|
150
|
+
seen = await stat(lock);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return true; // Released between our open and stat.
|
|
154
|
+
}
|
|
155
|
+
if (Date.now() - seen.mtimeMs <= KEYS_FILE_LOCK.staleMs)
|
|
156
|
+
return false;
|
|
157
|
+
const aside = `${lock}.${process.pid}.${Date.now()}.stale`;
|
|
158
|
+
try {
|
|
159
|
+
await rename(lock, aside);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return true; // Another waiter moved it first.
|
|
163
|
+
}
|
|
164
|
+
const moved = await stat(aside).catch(() => null);
|
|
165
|
+
if (moved !== null && moved.ino !== seen.ino) {
|
|
166
|
+
// A waiter replaced the stale lock between our stat and rename: put its
|
|
167
|
+
// lock back. If the path was taken again meanwhile, that holder keeps it.
|
|
168
|
+
await link(aside, lock).catch(() => { });
|
|
169
|
+
}
|
|
170
|
+
await rm(aside, { force: true });
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
async function appendAgentKey(path, entry) {
|
|
174
|
+
let doc = { keys: [] };
|
|
175
|
+
let text = null;
|
|
176
|
+
try {
|
|
177
|
+
text = await readFile(path, 'utf8');
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
if (err.code !== 'ENOENT') {
|
|
181
|
+
throw new AgentKeysFileError(`Cannot read the agent keys file ${path} (${err.code ?? errorMessage(err)}).`, path);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (text !== null && text.trim() !== '') {
|
|
185
|
+
let parsed;
|
|
186
|
+
try {
|
|
187
|
+
parsed = JSON.parse(text);
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
throw new AgentKeysFileError(`The agent keys file ${path} is not JSON; it was left as it is.`, path);
|
|
191
|
+
}
|
|
192
|
+
if (parsed === null || typeof parsed !== 'object' || !Array.isArray(parsed.keys)) {
|
|
193
|
+
throw new AgentKeysFileError(`The agent keys file ${path} does not hold a {"keys": [...]} JWK Set; it was left as it is.`, path);
|
|
194
|
+
}
|
|
195
|
+
doc = parsed;
|
|
196
|
+
}
|
|
197
|
+
const x = entry.publicKeyJwk.x;
|
|
198
|
+
const listed = doc.keys.some((k) => {
|
|
199
|
+
const jwk = k !== null && typeof k === 'object' && 'publicKeyJwk' in k ? k.publicKeyJwk : k;
|
|
200
|
+
return jwk !== null && typeof jwk === 'object' && jwk.x === x;
|
|
201
|
+
});
|
|
202
|
+
if (listed)
|
|
203
|
+
return;
|
|
204
|
+
doc.keys.push(entry);
|
|
205
|
+
const temp = join(dirname(path), `.${process.pid}.${Date.now()}.agent-keys.tmp`);
|
|
206
|
+
try {
|
|
207
|
+
await writeFile(temp, JSON.stringify(doc, null, 2) + '\n');
|
|
208
|
+
await rename(temp, path);
|
|
209
|
+
}
|
|
210
|
+
catch (err) {
|
|
211
|
+
await rm(temp, { force: true });
|
|
212
|
+
throw new AgentKeysFileError(`Cannot write the agent keys file ${path} (${err.code ?? errorMessage(err)}).`, path);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
78
215
|
/** The Server refused the exchange. `body` is its error response, scrubbed. */
|
|
79
216
|
export class OidcExchangeError extends Error {
|
|
80
217
|
status;
|
|
@@ -129,6 +266,14 @@ function killTree(pid) {
|
|
|
129
266
|
// Already gone.
|
|
130
267
|
}
|
|
131
268
|
}
|
|
269
|
+
/** Process groups of token commands that are running now, so a shutdown can end them. */
|
|
270
|
+
const runningCommands = new Set();
|
|
271
|
+
/** Kill every token command still running. For a signal handler: the commands run detached, so they would outlive this process. */
|
|
272
|
+
export function killRunningTokenCommands() {
|
|
273
|
+
for (const pid of runningCommands)
|
|
274
|
+
killTree(pid);
|
|
275
|
+
runningCommands.clear();
|
|
276
|
+
}
|
|
132
277
|
/**
|
|
133
278
|
* Runs a shell command on every call; its stdout is the token. The command
|
|
134
279
|
* runs in its own process group, which is killed on timeout, on oversized
|
|
@@ -150,9 +295,12 @@ export function oidcTokenFromCommand(command, origin = OIDC_ENV.TOKEN_CMD, optio
|
|
|
150
295
|
});
|
|
151
296
|
}
|
|
152
297
|
catch (err) {
|
|
153
|
-
reject(new OidcTokenSourceError(`${origin}: could not run the token command: ${
|
|
298
|
+
reject(new OidcTokenSourceError(`${origin}: could not run the token command: ${errorMessage(err)}`));
|
|
154
299
|
return;
|
|
155
300
|
}
|
|
301
|
+
const pid = child.pid;
|
|
302
|
+
if (pid !== undefined)
|
|
303
|
+
runningCommands.add(pid);
|
|
156
304
|
const out = [];
|
|
157
305
|
let outBytes = 0;
|
|
158
306
|
let stderr = '';
|
|
@@ -163,10 +311,12 @@ export function oidcTokenFromCommand(command, origin = OIDC_ENV.TOKEN_CMD, optio
|
|
|
163
311
|
settled = true;
|
|
164
312
|
clearTimeout(timer);
|
|
165
313
|
killTree(child.pid);
|
|
314
|
+
if (pid !== undefined)
|
|
315
|
+
runningCommands.delete(pid);
|
|
166
316
|
reject(new OidcTokenSourceError(`${origin}: ${message}`));
|
|
167
317
|
};
|
|
168
318
|
const timer = setTimeout(() => fail(`the token command did not finish within ${timeoutMs / 1000}s and was killed.`), timeoutMs);
|
|
169
|
-
child.stdout
|
|
319
|
+
child.stdout?.on('data', (d) => {
|
|
170
320
|
outBytes += d.length;
|
|
171
321
|
if (outBytes > maxStdout) {
|
|
172
322
|
fail(`the token command printed more than ${maxStdout} bytes, which is not a token; it was killed.`);
|
|
@@ -174,7 +324,7 @@ export function oidcTokenFromCommand(command, origin = OIDC_ENV.TOKEN_CMD, optio
|
|
|
174
324
|
}
|
|
175
325
|
out.push(d);
|
|
176
326
|
});
|
|
177
|
-
child.stderr
|
|
327
|
+
child.stderr?.setEncoding('utf8').on('data', (d) => {
|
|
178
328
|
if (stderr.length < STDERR_LIMIT * 2)
|
|
179
329
|
stderr += d;
|
|
180
330
|
});
|
|
@@ -186,6 +336,8 @@ export function oidcTokenFromCommand(command, origin = OIDC_ENV.TOKEN_CMD, optio
|
|
|
186
336
|
clearTimeout(timer);
|
|
187
337
|
// Anything it left running in the background goes with it.
|
|
188
338
|
killTree(child.pid);
|
|
339
|
+
if (pid !== undefined)
|
|
340
|
+
runningCommands.delete(pid);
|
|
189
341
|
if (code === 0) {
|
|
190
342
|
resolve(Buffer.concat(out).toString('utf8'));
|
|
191
343
|
return;
|
|
@@ -239,6 +391,7 @@ export class OidcCertCredential {
|
|
|
239
391
|
renewable = true;
|
|
240
392
|
getOidcToken;
|
|
241
393
|
agentId;
|
|
394
|
+
agentKeysFile;
|
|
242
395
|
refreshFraction;
|
|
243
396
|
origin;
|
|
244
397
|
onWarning;
|
|
@@ -257,6 +410,7 @@ export class OidcCertCredential {
|
|
|
257
410
|
}
|
|
258
411
|
this.getOidcToken = options.getOidcToken;
|
|
259
412
|
this.agentId = options.agentId;
|
|
413
|
+
this.agentKeysFile = options.agentKeysFile || undefined;
|
|
260
414
|
this.refreshFraction = fraction;
|
|
261
415
|
this.origin = options.origin ?? 'OIDC token source';
|
|
262
416
|
this.onWarning = options.onWarning;
|
|
@@ -268,6 +422,14 @@ export class OidcCertCredential {
|
|
|
268
422
|
throw new Error('Ed25519 public key export carried no x coordinate.');
|
|
269
423
|
this.publicX = jwk.x;
|
|
270
424
|
}
|
|
425
|
+
/**
|
|
426
|
+
* The public half of this server's key pair, as sent at every exchange. The
|
|
427
|
+
* cert carries only its thumbprint; this is the key agledger_verify's
|
|
428
|
+
* agentKeys needs to re-verify what this server signed. One per process.
|
|
429
|
+
*/
|
|
430
|
+
get publicKeyJwk() {
|
|
431
|
+
return { kty: 'OKP', crv: 'Ed25519', x: this.publicX };
|
|
432
|
+
}
|
|
271
433
|
async bearer(ctx) {
|
|
272
434
|
const current = this.cert;
|
|
273
435
|
const t = this.now();
|
|
@@ -292,7 +454,7 @@ export class OidcCertCredential {
|
|
|
292
454
|
// has not rotated yet fails the same way on every call until it does.
|
|
293
455
|
// An unrotated token file is the normal state between rotations, not a
|
|
294
456
|
// failure worth a line on stderr.
|
|
295
|
-
const message =
|
|
457
|
+
const message = errorMessage(err);
|
|
296
458
|
const expected = err instanceof OidcTokenSourceError && err.unrotated;
|
|
297
459
|
if (!expected && this.lastWarned !== message) {
|
|
298
460
|
this.lastWarned = message;
|
|
@@ -328,7 +490,7 @@ export class OidcCertCredential {
|
|
|
328
490
|
catch (err) {
|
|
329
491
|
if (err instanceof OidcTokenSourceError)
|
|
330
492
|
throw err;
|
|
331
|
-
throw new OidcTokenSourceError(`${this.origin}: ${redactTokens(
|
|
493
|
+
throw new OidcTokenSourceError(`${this.origin}: ${redactTokens(errorMessage(err))}`);
|
|
332
494
|
}
|
|
333
495
|
if (!token)
|
|
334
496
|
throw new OidcTokenSourceError(`${this.origin}: the token source returned nothing.`);
|
|
@@ -346,7 +508,7 @@ export class OidcCertCredential {
|
|
|
346
508
|
const proofOfPossession = sign(null, Buffer.from(`${POP_CONTEXT}${sub}`, 'utf8'), this.privateKey).toString('base64');
|
|
347
509
|
const body = {
|
|
348
510
|
oidcToken: token,
|
|
349
|
-
publicKeyJwk:
|
|
511
|
+
publicKeyJwk: this.publicKeyJwk,
|
|
350
512
|
proofOfPossession,
|
|
351
513
|
};
|
|
352
514
|
if (this.agentId)
|
|
@@ -356,7 +518,7 @@ export class OidcCertCredential {
|
|
|
356
518
|
res = await ctx.postAnonymous(EXCHANGE_PATH, body);
|
|
357
519
|
}
|
|
358
520
|
catch (err) {
|
|
359
|
-
throw new OidcExchangeError(`OIDC cert exchange failed: ${redactTokens(
|
|
521
|
+
throw new OidcExchangeError(`OIDC cert exchange failed: ${redactTokens(errorMessage(err))}`, 0, null);
|
|
360
522
|
}
|
|
361
523
|
if (res.status !== 201) {
|
|
362
524
|
const scrubbed = scrub(res.body, token);
|
|
@@ -370,6 +532,18 @@ export class OidcCertCredential {
|
|
|
370
532
|
if (typeof out?.certJws !== 'string' || !Number.isFinite(lifetime) || lifetime <= 0) {
|
|
371
533
|
throw new OidcExchangeError(`OIDC cert exchange failed: POST ${EXCHANGE_PATH} returned 201 without a certJws and a valid cert.issuedAt/expiresAt.`, res.status, null);
|
|
372
534
|
}
|
|
535
|
+
// Recorded before the cert is used, so nothing is signed under a key the
|
|
536
|
+
// file does not list.
|
|
537
|
+
if (this.agentKeysFile !== undefined) {
|
|
538
|
+
const certInfo = out.cert ?? {};
|
|
539
|
+
await recordAgentKey(this.agentKeysFile, {
|
|
540
|
+
publicKeyJwk: this.publicKeyJwk,
|
|
541
|
+
certId: certInfo.id,
|
|
542
|
+
agentId: certInfo.agentId,
|
|
543
|
+
issuedAt: certInfo.issuedAt,
|
|
544
|
+
expiresAt: certInfo.expiresAt,
|
|
545
|
+
});
|
|
546
|
+
}
|
|
373
547
|
this.lastExchangedToken = token;
|
|
374
548
|
this.lastWarned = undefined;
|
|
375
549
|
const receivedAt = this.now();
|
package/dist/delegation.js
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* refuses it with a 401 that names the delegation.
|
|
14
14
|
*/
|
|
15
15
|
import { jwtPayloadOf, OidcTokenSourceError, redactTokens } from './credentials.js';
|
|
16
|
+
import { errorMessage } from './errors.js';
|
|
16
17
|
export const ON_BEHALF_OF_ENV = {
|
|
17
18
|
CMD: 'AGLEDGER_ON_BEHALF_OF_CMD',
|
|
18
19
|
FILE: 'AGLEDGER_ON_BEHALF_OF_FILE',
|
|
@@ -82,7 +83,7 @@ export class DelegationSource {
|
|
|
82
83
|
}
|
|
83
84
|
catch (err) {
|
|
84
85
|
this.cached = undefined;
|
|
85
|
-
const message = redactTokens(
|
|
86
|
+
const message = redactTokens(errorMessage(err));
|
|
86
87
|
throw new DelegationSourceError(message.startsWith(this.origin) ? message : `${this.origin}: ${message}`);
|
|
87
88
|
}
|
|
88
89
|
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** An error's message, or the text of a thrown value that is not an Error. */
|
|
2
|
+
export declare function errorMessage(err: unknown): string;
|
|
3
|
+
/** An error as text. `fetch failed` says nothing on its own; the cause (ECONNREFUSED, ENOTFOUND, a certificate error) says why. */
|
|
4
|
+
export declare function describeError(err: unknown): string;
|
|
5
|
+
/** The code, else the message, of what a failed fetch was caused by. */
|
|
6
|
+
export declare function fetchCause(err: Error): string | undefined;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** An error's message, or the text of a thrown value that is not an Error. */
|
|
2
|
+
export function errorMessage(err) {
|
|
3
|
+
return err instanceof Error ? err.message : String(err);
|
|
4
|
+
}
|
|
5
|
+
/** An error as text. `fetch failed` says nothing on its own; the cause (ECONNREFUSED, ENOTFOUND, a certificate error) says why. */
|
|
6
|
+
export function describeError(err) {
|
|
7
|
+
if (!(err instanceof Error))
|
|
8
|
+
return String(err);
|
|
9
|
+
const detail = fetchCause(err);
|
|
10
|
+
return detail && !err.message.includes(detail) ? `${err.message} (${detail})` : err.message;
|
|
11
|
+
}
|
|
12
|
+
/** The code, else the message, of what a failed fetch was caused by. */
|
|
13
|
+
export function fetchCause(err) {
|
|
14
|
+
const cause = err.cause;
|
|
15
|
+
if (typeof cause?.code === 'string')
|
|
16
|
+
return cause.code;
|
|
17
|
+
return typeof cause?.message === 'string' ? cause.message : undefined;
|
|
18
|
+
}
|