passcontrol 0.6.0 → 0.6.1
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/bin/passcontrol.mjs +35 -5
- package/cli/config.mjs +29 -1
- package/cli/proxy-policy.mjs +276 -0
- package/cli/sidecar.mjs +181 -8
- package/package.json +1 -1
package/bin/passcontrol.mjs
CHANGED
|
@@ -25,6 +25,7 @@ import {
|
|
|
25
25
|
redact,
|
|
26
26
|
requireControlApiKey,
|
|
27
27
|
requireControlGateway,
|
|
28
|
+
operatorEnv,
|
|
28
29
|
requirePassportGateway,
|
|
29
30
|
requirePassport,
|
|
30
31
|
step,
|
|
@@ -145,7 +146,8 @@ ${heading("Operate")}
|
|
|
145
146
|
show active config and instance state
|
|
146
147
|
${cmd} doctor [--deep] [--fix] diagnose setup and repair a stopped dashboard
|
|
147
148
|
${cmd} call "hi" mint a visa and make a governed model call
|
|
148
|
-
${cmd} sidecar [--port 8788]
|
|
149
|
+
${cmd} sidecar [--port 8788] [--allow-connect host[,host]]
|
|
150
|
+
start the local agent bridge
|
|
149
151
|
|
|
150
152
|
${heading("Manage")}
|
|
151
153
|
${cmd} agent list [--json] list agents
|
|
@@ -430,13 +432,26 @@ function checkDockerDaemon() {
|
|
|
430
432
|
try {
|
|
431
433
|
// Docker Desktop can leave its CLI socket present while the engine is
|
|
432
434
|
// wedged. A diagnostic command must report that state, not hang every
|
|
433
|
-
// onboarding/release check indefinitely.
|
|
434
|
-
|
|
435
|
+
// onboarding/release check indefinitely — hence a bound.
|
|
436
|
+
//
|
|
437
|
+
// The bound is generous because the failure it must not cause is worse than
|
|
438
|
+
// the one it prevents. At 2s this reported "not running" about a daemon that
|
|
439
|
+
// was merely COLD: it failed the public repo's local-smoke CI job on a runner
|
|
440
|
+
// where Docker was available throughout, and it would tell a first-time user
|
|
441
|
+
// on a slow laptop to go start something already running. A wedged engine
|
|
442
|
+
// still gets caught; it just takes fifteen seconds to say so.
|
|
443
|
+
execFileSync("docker", ["info"], { stdio: "ignore", timeout: 15_000 });
|
|
435
444
|
return { ok: true, message: "Docker daemon: running." };
|
|
436
|
-
} catch {
|
|
445
|
+
} catch (error) {
|
|
446
|
+
// A timeout and a stopped daemon need different things from the reader, so
|
|
447
|
+
// they must not share a sentence. `execFileSync` surfaces the timeout kill as
|
|
448
|
+
// ETIMEDOUT, or as the signal it used when the platform reports no code.
|
|
449
|
+
const timedOut = error?.code === "ETIMEDOUT" || error?.signal === "SIGTERM";
|
|
437
450
|
return {
|
|
438
451
|
ok: false,
|
|
439
|
-
message:
|
|
452
|
+
message: timedOut
|
|
453
|
+
? "Docker daemon: did not respond within 15s. The engine may still be starting — wait and re-run. If it persists, Docker is wedged: restart Docker Desktop."
|
|
454
|
+
: "Docker daemon: not running. Fix: start Docker Desktop and wait for the engine to become ready.",
|
|
440
455
|
};
|
|
441
456
|
}
|
|
442
457
|
}
|
|
@@ -1549,6 +1564,21 @@ async function sidecarCommand(rest, opts) {
|
|
|
1549
1564
|
passportSecret,
|
|
1550
1565
|
port: sidecarPort(opts),
|
|
1551
1566
|
host: String(opts.host ?? process.env.SIDECAR_HOST ?? "127.0.0.1"),
|
|
1567
|
+
// Named on the command line, never inferred. A sidecar reachable off-host
|
|
1568
|
+
// mints visas for whoever connects, so widening the bind is a decision the
|
|
1569
|
+
// operator states rather than one a config value makes quietly.
|
|
1570
|
+
allowNonLoopback: Boolean(opts.allowNonLoopback),
|
|
1571
|
+
// Hosts the agent may CONNECT-tunnel to, beyond the gateway itself. Provider
|
|
1572
|
+
// hosts are never eligible — see cli/proxy-policy.mjs.
|
|
1573
|
+
//
|
|
1574
|
+
// `operatorEnv`, not `process.env`, for the same reason `allowNonLoopback`
|
|
1575
|
+
// above takes no environment fallback at all: this is an egress control. A
|
|
1576
|
+
// `.passcontrol` that travels with a cloned repository was able to add tunnel
|
|
1577
|
+
// destinations to a sidecar started with no flags, and say nothing about it.
|
|
1578
|
+
allowConnectHosts: String(opts.allowConnect ?? operatorEnv("SIDECAR_ALLOW_CONNECT") ?? "")
|
|
1579
|
+
.split(",")
|
|
1580
|
+
.map((entry) => entry.trim())
|
|
1581
|
+
.filter(Boolean),
|
|
1552
1582
|
refreshSkewSeconds: Number(opts.refreshSkewSeconds ?? process.env.REFRESH_SKEW_SECONDS ?? 30),
|
|
1553
1583
|
});
|
|
1554
1584
|
|
package/cli/config.mjs
CHANGED
|
@@ -134,16 +134,44 @@ export function loadConfigSources({ cwd = process.cwd(), env = process.env } = {
|
|
|
134
134
|
return sources;
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
/**
|
|
138
|
+
* Keys that arrived from a `.passcontrol` FILE rather than the operator's shell.
|
|
139
|
+
*
|
|
140
|
+
* A config file is checked in and travels with a repository, so for anything
|
|
141
|
+
* security-relevant "the environment says so" and "the operator said so" are not
|
|
142
|
+
* the same statement. Recorded at injection time rather than derived afterwards:
|
|
143
|
+
* a key present in BOTH the shell and a file keeps its shell value below, and
|
|
144
|
+
* that value is the operator's — so asking the file later would wrongly disown it.
|
|
145
|
+
*/
|
|
146
|
+
export const configInjectedKeys = new Set();
|
|
147
|
+
|
|
137
148
|
export function applyConfigSourcesToEnv({ cwd = process.cwd(), env = process.env } = {}) {
|
|
138
149
|
const sources = loadConfigSources({ cwd, env });
|
|
139
150
|
const merged = {};
|
|
140
151
|
for (const source of sources) Object.assign(merged, source.values);
|
|
141
152
|
for (const [key, value] of Object.entries(merged)) {
|
|
142
|
-
if (env[key] === undefined)
|
|
153
|
+
if (env[key] === undefined) {
|
|
154
|
+
env[key] = value;
|
|
155
|
+
configInjectedKeys.add(key);
|
|
156
|
+
}
|
|
143
157
|
}
|
|
144
158
|
return sources;
|
|
145
159
|
}
|
|
146
160
|
|
|
161
|
+
/**
|
|
162
|
+
* Read an environment variable ONLY if the operator set it.
|
|
163
|
+
*
|
|
164
|
+
* For an egress or credential control, a value a cloned repository's
|
|
165
|
+
* `.passcontrol` dropped into the environment must not stand in for a decision
|
|
166
|
+
* the operator made. Everything else — `MODEL`, `SIDECAR_PORT`, `PROMPT` — is
|
|
167
|
+
* still perfectly good to configure from a file and goes on reading `process.env`
|
|
168
|
+
* directly; this is deliberately opt-in per key rather than a blanket filter,
|
|
169
|
+
* because narrowing what a config file may set would break ordinary use.
|
|
170
|
+
*/
|
|
171
|
+
export function operatorEnv(key, { env = process.env, injected = configInjectedKeys } = {}) {
|
|
172
|
+
return injected.has(key) ? undefined : env[key];
|
|
173
|
+
}
|
|
174
|
+
|
|
147
175
|
export let configLoadError = null;
|
|
148
176
|
export let configSources = [];
|
|
149
177
|
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// Destination policy for the sidecar's forward-proxy front door.
|
|
2
|
+
//
|
|
3
|
+
// Everything else in the sidecar routes to a destination WE configured. This
|
|
4
|
+
// module is the one place that judges a destination the CLIENT chose, which is
|
|
5
|
+
// what `HTTPS_PROXY=http://127.0.0.1:8788` turns every agent request into. Two
|
|
6
|
+
// failures are possible and both are bad:
|
|
7
|
+
//
|
|
8
|
+
// * tunnel a provider host → an ungoverned provider call carried by the
|
|
9
|
+
// component whose entire job is governing it, with the operator believing
|
|
10
|
+
// scope and budget applied;
|
|
11
|
+
// * tunnel anything asked → an open proxy on a developer laptop.
|
|
12
|
+
//
|
|
13
|
+
// So the rule is deny-by-default with two narrow exits: the gateway we already
|
|
14
|
+
// send visas to, and hosts the operator named on the command line.
|
|
15
|
+
//
|
|
16
|
+
// Why a provider CONNECT is refused rather than governed: injecting the key
|
|
17
|
+
// would mean terminating the TLS, which means a locally trusted CA that can
|
|
18
|
+
// impersonate any host to any process trusting it. PassControl exists to get a
|
|
19
|
+
// secret with a one-provider blast radius off the agent's machine; installing a
|
|
20
|
+
// broader one to save an environment variable is the wrong trade, and every
|
|
21
|
+
// mainstream provider SDK already honours a base-URL variable that needs no CA.
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The provider upstreams, as host + base path.
|
|
25
|
+
*
|
|
26
|
+
* A second copy of `lib/providers.ts`'s `upstreamBaseUrl`, for the same reason
|
|
27
|
+
* `bareGatewayOrigin` exists twice: `cli/` is plain .mjs run straight from the
|
|
28
|
+
* checkout and published as-is, so it cannot import TypeScript that only exists
|
|
29
|
+
* after `tsc`. `tests/cli-provider-hosts.test.ts` runs both through one table and
|
|
30
|
+
* fails the moment they disagree — a provider added there and missed here is a
|
|
31
|
+
* provider this file would let through.
|
|
32
|
+
*/
|
|
33
|
+
export const PROVIDER_UPSTREAMS = {
|
|
34
|
+
openai: { hostname: "api.openai.com", basePath: "" },
|
|
35
|
+
anthropic: { hostname: "api.anthropic.com", basePath: "" },
|
|
36
|
+
groq: { hostname: "api.groq.com", basePath: "/openai" },
|
|
37
|
+
mistral: { hostname: "api.mistral.ai", basePath: "" },
|
|
38
|
+
together: { hostname: "api.together.ai", basePath: "" },
|
|
39
|
+
deepseek: { hostname: "api.deepseek.com", basePath: "" },
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const HOST_BY_NAME = new Map(
|
|
43
|
+
Object.entries(PROVIDER_UPSTREAMS).map(([provider, entry]) => [entry.hostname, { provider, ...entry }])
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
// A hostname carrying any of these is not a hostname. Checked rather than
|
|
47
|
+
// assumed because the value arrives on a request line from whatever the client
|
|
48
|
+
// felt like sending.
|
|
49
|
+
const NOT_IN_A_HOSTNAME = /[\s/\\@?#]/;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Lower-case, unbracket, and drop the fully-qualified trailing dot.
|
|
53
|
+
*
|
|
54
|
+
* `api.anthropic.com.` resolves to exactly the same address as
|
|
55
|
+
* `api.anthropic.com`, so a string comparison that treats them as different
|
|
56
|
+
* hosts is a one-character bypass of the provider refusal below.
|
|
57
|
+
*/
|
|
58
|
+
function normalizeHostname(value) {
|
|
59
|
+
let host = String(value ?? "").trim().toLowerCase();
|
|
60
|
+
if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1);
|
|
61
|
+
if (host.endsWith(".")) host = host.slice(0, -1);
|
|
62
|
+
return host;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Exact match only — `evil-api.anthropic.com` is somebody else's hostname. */
|
|
66
|
+
export function providerForHost(hostname) {
|
|
67
|
+
return HOST_BY_NAME.get(normalizeHostname(hostname)) ?? null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function parsePort(value) {
|
|
71
|
+
if (!/^\d{1,5}$/.test(String(value))) return null;
|
|
72
|
+
const port = Number(value);
|
|
73
|
+
return port >= 1 && port <= 65535 ? port : null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Split a CONNECT authority-form target (`host:port`) as RFC 9110 defines it.
|
|
78
|
+
*
|
|
79
|
+
* The port is mandatory: a bare host is not a valid CONNECT target, and guessing
|
|
80
|
+
* 443 for it would mean inventing a destination the client never named.
|
|
81
|
+
*/
|
|
82
|
+
export function parseConnectTarget(raw) {
|
|
83
|
+
const value = String(raw ?? "").trim();
|
|
84
|
+
if (!value) return null;
|
|
85
|
+
|
|
86
|
+
let hostPart;
|
|
87
|
+
let portPart;
|
|
88
|
+
if (value.startsWith("[")) {
|
|
89
|
+
const close = value.indexOf("]");
|
|
90
|
+
if (close === -1 || value[close + 1] !== ":") return null;
|
|
91
|
+
hostPart = value.slice(0, close + 1);
|
|
92
|
+
portPart = value.slice(close + 2);
|
|
93
|
+
} else {
|
|
94
|
+
const colon = value.indexOf(":");
|
|
95
|
+
// Exactly one colon outside brackets. `a:1:2` is malformed, not an address.
|
|
96
|
+
if (colon === -1 || value.indexOf(":", colon + 1) !== -1) return null;
|
|
97
|
+
hostPart = value.slice(0, colon);
|
|
98
|
+
portPart = value.slice(colon + 1);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const hostname = normalizeHostname(hostPart);
|
|
102
|
+
const port = parsePort(portPart);
|
|
103
|
+
if (!hostname || port === null || NOT_IN_A_HOSTNAME.test(hostname)) return null;
|
|
104
|
+
return { hostname, port };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The gateway's own host and effective port, which CONNECT is allowed to reach. */
|
|
108
|
+
function gatewayTarget(gatewayOrigin) {
|
|
109
|
+
let url;
|
|
110
|
+
try {
|
|
111
|
+
url = new URL(String(gatewayOrigin ?? ""));
|
|
112
|
+
} catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
const port = url.port ? parsePort(url.port) : url.protocol === "https:" ? 443 : 80;
|
|
116
|
+
if (port === null) return null;
|
|
117
|
+
return { hostname: normalizeHostname(url.hostname), port };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** `host` (any port) or `host:port` (that port only). */
|
|
121
|
+
function parseAllowEntry(entry) {
|
|
122
|
+
const value = String(entry ?? "").trim();
|
|
123
|
+
if (!value) return null;
|
|
124
|
+
const withPort = parseConnectTarget(value);
|
|
125
|
+
if (withPort) return withPort;
|
|
126
|
+
|
|
127
|
+
const hostname = normalizeHostname(value);
|
|
128
|
+
if (!hostname || NOT_IN_A_HOSTNAME.test(hostname) || hostname.includes(":")) return null;
|
|
129
|
+
return { hostname, port: null };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function parseAllowHosts(entries) {
|
|
133
|
+
const list = Array.isArray(entries)
|
|
134
|
+
? entries
|
|
135
|
+
: String(entries ?? "")
|
|
136
|
+
.split(",")
|
|
137
|
+
.filter(Boolean);
|
|
138
|
+
return list.map(parseAllowEntry).filter(Boolean);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function refuse(status, code, message, help) {
|
|
142
|
+
return { allow: false, status, code, message, help };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function governedPathHelp(provider, localBaseUrl) {
|
|
146
|
+
const base = localBaseUrl ? String(localBaseUrl).replace(/\/+$/, "") : "";
|
|
147
|
+
return `${base}/api/v1/${provider}`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Decide what to do with `CONNECT host:port`.
|
|
152
|
+
*
|
|
153
|
+
* Order matters: the provider check runs FIRST, before the operator allowlist.
|
|
154
|
+
* An allowlist that could name a provider would stop being an egress control and
|
|
155
|
+
* become an off-switch for governance.
|
|
156
|
+
*/
|
|
157
|
+
export function classifyConnect({ target, gatewayOrigin, allowHosts = [], localBaseUrl = "" } = {}) {
|
|
158
|
+
const parsed = parseConnectTarget(target);
|
|
159
|
+
if (!parsed) {
|
|
160
|
+
return refuse(
|
|
161
|
+
400,
|
|
162
|
+
"bad_connect_target",
|
|
163
|
+
"CONNECT needs an authority-form target, for example api.example.com:443.",
|
|
164
|
+
"Check the proxy setting; PassControl received a target it could not parse."
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const provider = providerForHost(parsed.hostname);
|
|
169
|
+
if (provider) {
|
|
170
|
+
return refuse(
|
|
171
|
+
403,
|
|
172
|
+
"provider_tunnel_not_governed",
|
|
173
|
+
`PassControl will not tunnel TLS to ${parsed.hostname}. It cannot see inside that connection, so it could ` +
|
|
174
|
+
"neither inject the provider key nor apply scope, budget or the kill switch — the call would leave " +
|
|
175
|
+
"ungoverned while appearing to be governed.",
|
|
176
|
+
`Point the client's base URL at ${governedPathHelp(provider.provider, localBaseUrl)} instead. ` +
|
|
177
|
+
"PassControl does not install a TLS-intercepting CA."
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const gateway = gatewayTarget(gatewayOrigin);
|
|
182
|
+
if (gateway && parsed.hostname === gateway.hostname && parsed.port === gateway.port) {
|
|
183
|
+
return { allow: true, ...parsed, reason: "gateway" };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const allowed = parseAllowHosts(allowHosts).some(
|
|
187
|
+
(entry) => entry.hostname === parsed.hostname && (entry.port === null || entry.port === parsed.port)
|
|
188
|
+
);
|
|
189
|
+
if (allowed) return { allow: true, ...parsed, reason: "allowlist" };
|
|
190
|
+
|
|
191
|
+
return refuse(
|
|
192
|
+
403,
|
|
193
|
+
"host_not_allowed",
|
|
194
|
+
`PassControl is not an open proxy and will not tunnel to ${parsed.hostname}.`,
|
|
195
|
+
`Allow it explicitly with \`passcontrol sidecar --allow-connect ${parsed.hostname}\` if the agent needs it.`
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Decide what to do with a request line.
|
|
201
|
+
*
|
|
202
|
+
* Origin-form (`/api/v1/…`) is the sidecar's original mode and passes through.
|
|
203
|
+
* Absolute-form (`http://api.anthropic.com/v1/messages`) is what a proxy client
|
|
204
|
+
* sends for a plain-HTTP URL; it used to be concatenated onto the gateway origin
|
|
205
|
+
* verbatim, producing `https://gateway/http://api.anthropic.com/v1/messages`.
|
|
206
|
+
*/
|
|
207
|
+
export function classifyProxyRequest({ url, gatewayOrigin, localBaseUrl = "" } = {}) {
|
|
208
|
+
const target = String(url ?? "");
|
|
209
|
+
if (target.startsWith("/")) return { allow: true, path: target, reason: "origin-form" };
|
|
210
|
+
|
|
211
|
+
if (!/^https?:\/\//i.test(target)) {
|
|
212
|
+
return refuse(
|
|
213
|
+
400,
|
|
214
|
+
"bad_request_target",
|
|
215
|
+
"PassControl received a request target that is neither a path nor an absolute URL.",
|
|
216
|
+
"Point the client at the sidecar's base URL, or set HTTP_PROXY/HTTPS_PROXY to it."
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
let parsed;
|
|
221
|
+
try {
|
|
222
|
+
parsed = new URL(target);
|
|
223
|
+
} catch {
|
|
224
|
+
return refuse(400, "bad_request_target", "PassControl could not parse that request target.", "Check the client's base URL.");
|
|
225
|
+
}
|
|
226
|
+
// Never echoed anywhere below, and refused outright: a URL carrying userinfo
|
|
227
|
+
// is a credential in a request line, and the same rule already governs
|
|
228
|
+
// PASSCONTROL_GATEWAY in `bareGatewayOrigin`.
|
|
229
|
+
if (parsed.username || parsed.password) {
|
|
230
|
+
return refuse(
|
|
231
|
+
400,
|
|
232
|
+
"bad_request_target",
|
|
233
|
+
"PassControl refuses a request target with embedded credentials.",
|
|
234
|
+
"Remove the user:password@ prefix from the client's base URL."
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const hostname = normalizeHostname(parsed.hostname);
|
|
239
|
+
const provider = providerForHost(hostname);
|
|
240
|
+
if (provider) {
|
|
241
|
+
// The gateway re-adds the provider's base path from `upstreamBaseUrl`, so
|
|
242
|
+
// forwarding groq's `/openai` prefix as well would double it.
|
|
243
|
+
let rest = parsed.pathname;
|
|
244
|
+
if (provider.basePath && (rest === provider.basePath || rest.startsWith(`${provider.basePath}/`))) {
|
|
245
|
+
rest = rest.slice(provider.basePath.length);
|
|
246
|
+
}
|
|
247
|
+
if (!rest.startsWith("/")) rest = `/${rest}`;
|
|
248
|
+
return { allow: true, path: `/api/v1/${provider.provider}${rest}${parsed.search}`, reason: "provider" };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const gateway = gatewayTarget(gatewayOrigin);
|
|
252
|
+
const port = parsed.port ? parsePort(parsed.port) : parsed.protocol === "https:" ? 443 : 80;
|
|
253
|
+
if (gateway && hostname === gateway.hostname && port === gateway.port) {
|
|
254
|
+
return { allow: true, path: `${parsed.pathname}${parsed.search}`, reason: "gateway" };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return refuse(
|
|
258
|
+
403,
|
|
259
|
+
"host_not_allowed",
|
|
260
|
+
`PassControl is not an open proxy and will not forward to ${hostname}.`,
|
|
261
|
+
"Only the configured gateway and the supported providers are routed."
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Loopback bind addresses.
|
|
267
|
+
*
|
|
268
|
+
* The sidecar holds the passport and mints visas on demand, so a listener
|
|
269
|
+
* reachable off-host is a credential-issuing endpoint for anyone who can route
|
|
270
|
+
* to it. `127.0.0.0/8` in full, because `127.0.0.2` is as loopback as `127.0.0.1`.
|
|
271
|
+
*/
|
|
272
|
+
export function isLoopbackBindHost(host) {
|
|
273
|
+
const value = normalizeHostname(host);
|
|
274
|
+
if (!value) return false;
|
|
275
|
+
return value === "localhost" || value === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(value);
|
|
276
|
+
}
|
package/cli/sidecar.mjs
CHANGED
|
@@ -1,9 +1,28 @@
|
|
|
1
1
|
import http from "node:http";
|
|
2
|
+
import net from "node:net";
|
|
2
3
|
import { Readable } from "node:stream";
|
|
3
|
-
import { bareGatewayOrigin, fail, ok, step } from "./config.mjs";
|
|
4
|
+
import { bareGatewayOrigin, fail, ok, step, warn } from "./config.mjs";
|
|
5
|
+
import { classifyConnect, classifyProxyRequest, isLoopbackBindHost } from "./proxy-policy.mjs";
|
|
4
6
|
import { createVisaClient } from "./visa-client.mjs";
|
|
5
7
|
|
|
6
|
-
|
|
8
|
+
// Hop-by-hop headers plus the ones the sidecar rebuilds itself. `proxy-connection`
|
|
9
|
+
// and friends only appear once something is used as a FORWARD proxy, which is
|
|
10
|
+
// what HTTP_PROXY/HTTPS_PROXY make this: they are addressed to the proxy and
|
|
11
|
+
// have no meaning upstream.
|
|
12
|
+
const STRIP_REQ = new Set([
|
|
13
|
+
"authorization",
|
|
14
|
+
"x-api-key",
|
|
15
|
+
"host",
|
|
16
|
+
"content-length",
|
|
17
|
+
"accept-encoding",
|
|
18
|
+
"connection",
|
|
19
|
+
"proxy-connection",
|
|
20
|
+
"keep-alive",
|
|
21
|
+
"te",
|
|
22
|
+
"trailer",
|
|
23
|
+
"upgrade",
|
|
24
|
+
"proxy-authenticate",
|
|
25
|
+
]);
|
|
7
26
|
|
|
8
27
|
// The set above is a denylist over header NAMES, and a denylist over names loses
|
|
9
28
|
// to spelling. A client that was previously configured with a raw provider key
|
|
@@ -21,7 +40,72 @@ function isStripped(name) {
|
|
|
21
40
|
}
|
|
22
41
|
const STRIP_RES = new Set(["content-encoding", "content-length", "transfer-encoding", "connection"]);
|
|
23
42
|
|
|
24
|
-
|
|
43
|
+
const STATUS_TEXT = { 400: "Bad Request", 403: "Forbidden", 502: "Bad Gateway" };
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* A header value is a single line of printable ASCII, always.
|
|
47
|
+
*
|
|
48
|
+
* The refusal text below interpolates a hostname the CLIENT chose. `proxy-policy`
|
|
49
|
+
* already refuses a hostname containing whitespace or a delimiter, so this is the
|
|
50
|
+
* second of two gates rather than the only one — but a header writer that can be
|
|
51
|
+
* handed a newline is a response-splitting bug, and one that can be handed a
|
|
52
|
+
* non-latin1 byte is a crash, so neither is left to the caller's good behaviour.
|
|
53
|
+
*/
|
|
54
|
+
function headerSafe(value) {
|
|
55
|
+
return String(value ?? "").replace(/[^\x20-\x7e]/g, " ").slice(0, 512);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function refusalBody(verdict) {
|
|
59
|
+
return JSON.stringify({ error: verdict.code, message: verdict.message, help: verdict.help });
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Refusals travel on five channels because clients surface wildly different
|
|
64
|
+
* subsets of them: a status code, a machine-readable code header, a one-line fix
|
|
65
|
+
* header, a JSON body for `curl -v`, and a line on the sidecar's own console.
|
|
66
|
+
* A CONNECT client typically shows only the status, so the console line is the
|
|
67
|
+
* one an operator can always read.
|
|
68
|
+
*/
|
|
69
|
+
function refusalHeaders(verdict) {
|
|
70
|
+
return {
|
|
71
|
+
"content-type": "application/json",
|
|
72
|
+
"x-passcontrol-refusal": headerSafe(verdict.code),
|
|
73
|
+
"x-passcontrol-help": headerSafe(verdict.help),
|
|
74
|
+
connection: "close",
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function writeRefusal(res, verdict) {
|
|
79
|
+
const body = refusalBody(verdict);
|
|
80
|
+
res.writeHead(verdict.status, { ...refusalHeaders(verdict), "content-length": Buffer.byteLength(body) });
|
|
81
|
+
res.end(body);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The same refusal, hand-rolled: a CONNECT is answered on the raw socket. */
|
|
85
|
+
function writeConnectRefusal(socket, verdict) {
|
|
86
|
+
if (socket.destroyed) return;
|
|
87
|
+
const body = refusalBody(verdict);
|
|
88
|
+
const head = [
|
|
89
|
+
`HTTP/1.1 ${verdict.status} ${STATUS_TEXT[verdict.status] ?? "Error"}`,
|
|
90
|
+
...Object.entries({ ...refusalHeaders(verdict), "content-length": Buffer.byteLength(body) }).map(
|
|
91
|
+
([k, v]) => `${k}: ${v}`
|
|
92
|
+
),
|
|
93
|
+
"",
|
|
94
|
+
"",
|
|
95
|
+
].join("\r\n");
|
|
96
|
+
socket.end(head + body);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function createSidecar({
|
|
100
|
+
gateway,
|
|
101
|
+
passportId,
|
|
102
|
+
passportSecret,
|
|
103
|
+
port = 8788,
|
|
104
|
+
host = "127.0.0.1",
|
|
105
|
+
refreshSkewSeconds = 30,
|
|
106
|
+
allowConnectHosts = [],
|
|
107
|
+
onRefusal = (verdict) => warn(`${verdict.code}: ${verdict.message} → ${verdict.help}`),
|
|
108
|
+
}) {
|
|
25
109
|
// The upstream URL below is built from this, not from the argument: the
|
|
26
110
|
// sidecar forwards a bearer visa on every proxied request, so its destination
|
|
27
111
|
// is part of the credential's security rather than a formatting detail.
|
|
@@ -34,6 +118,13 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
|
|
|
34
118
|
missingVisaMessage: "challenge returned no visa",
|
|
35
119
|
});
|
|
36
120
|
|
|
121
|
+
// Used only to print the governed base URL back in a refusal. Read from the
|
|
122
|
+
// live listener when there is one so the advice names the port actually bound.
|
|
123
|
+
const localBaseUrl = () => {
|
|
124
|
+
const address = server?.listening ? server.address() : null;
|
|
125
|
+
return `http://${host}:${address?.port ?? port}`;
|
|
126
|
+
};
|
|
127
|
+
|
|
37
128
|
function readBody(req) {
|
|
38
129
|
return new Promise((resolve, reject) => {
|
|
39
130
|
const chunks = [];
|
|
@@ -43,14 +134,14 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
|
|
|
43
134
|
});
|
|
44
135
|
}
|
|
45
136
|
|
|
46
|
-
async function fetchUpstream(req, body, visa) {
|
|
137
|
+
async function fetchUpstream(req, path, body, visa) {
|
|
47
138
|
const headers = {};
|
|
48
139
|
for (const [k, v] of Object.entries(req.headers)) {
|
|
49
140
|
if (!isStripped(k) && typeof v === "string") headers[k] = v;
|
|
50
141
|
}
|
|
51
142
|
headers["authorization"] = `Bearer ${visa}`;
|
|
52
143
|
headers["accept-encoding"] = "identity";
|
|
53
|
-
return fetch(`${origin}${
|
|
144
|
+
return fetch(`${origin}${path}`, { method: req.method, headers, body: body ?? undefined });
|
|
54
145
|
}
|
|
55
146
|
|
|
56
147
|
function writeResponse(res, upstream) {
|
|
@@ -64,9 +155,19 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
|
|
|
64
155
|
}
|
|
65
156
|
|
|
66
157
|
const server = http.createServer(async (req, res) => {
|
|
158
|
+
// Judge the destination before reading the body: a refused host should not
|
|
159
|
+
// get to make the sidecar buffer megabytes on its way to a 403.
|
|
160
|
+
const verdict = classifyProxyRequest({ url: req.url, gatewayOrigin: origin, localBaseUrl: localBaseUrl() });
|
|
161
|
+
if (!verdict.allow) {
|
|
162
|
+
req.resume();
|
|
163
|
+
onRefusal(verdict);
|
|
164
|
+
writeRefusal(res, verdict);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
|
|
67
168
|
try {
|
|
68
169
|
const body = await readBody(req);
|
|
69
|
-
const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, body, visa));
|
|
170
|
+
const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, verdict.path, body, visa));
|
|
70
171
|
writeResponse(res, upstream);
|
|
71
172
|
} catch (e) {
|
|
72
173
|
if (!res.headersSent) {
|
|
@@ -78,17 +179,89 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
|
|
|
78
179
|
}
|
|
79
180
|
});
|
|
80
181
|
|
|
182
|
+
// `CONNECT host:port` — what every client with HTTPS_PROXY set sends first.
|
|
183
|
+
// PassControl cannot govern what it cannot read, and it deliberately does not
|
|
184
|
+
// terminate TLS to make it readable, so a provider target is refused here
|
|
185
|
+
// rather than tunnelled into a call that is ungoverned while looking governed.
|
|
186
|
+
server.on("connect", (req, clientSocket, head) => {
|
|
187
|
+
clientSocket.on("error", () => {});
|
|
188
|
+
|
|
189
|
+
const verdict = classifyConnect({
|
|
190
|
+
target: req.url,
|
|
191
|
+
gatewayOrigin: origin,
|
|
192
|
+
allowHosts: allowConnectHosts,
|
|
193
|
+
localBaseUrl: localBaseUrl(),
|
|
194
|
+
});
|
|
195
|
+
if (!verdict.allow) {
|
|
196
|
+
onRefusal(verdict);
|
|
197
|
+
writeConnectRefusal(clientSocket, verdict);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
let established = false;
|
|
202
|
+
const upstream = net.connect(verdict.port, verdict.hostname, () => {
|
|
203
|
+
established = true;
|
|
204
|
+
clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
|
|
205
|
+
if (head?.length) upstream.write(head);
|
|
206
|
+
upstream.pipe(clientSocket);
|
|
207
|
+
clientSocket.pipe(upstream);
|
|
208
|
+
});
|
|
209
|
+
upstream.on("error", () => {
|
|
210
|
+
if (established) {
|
|
211
|
+
clientSocket.destroy();
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
writeConnectRefusal(clientSocket, {
|
|
215
|
+
status: 502,
|
|
216
|
+
code: "tunnel_unreachable",
|
|
217
|
+
message: `PassControl could not open a tunnel to ${verdict.hostname}.`,
|
|
218
|
+
help: "Check that the host is reachable from this machine.",
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
clientSocket.on("close", () => upstream.destroy());
|
|
222
|
+
});
|
|
223
|
+
|
|
81
224
|
return { server, getVisa: visas.getVisa };
|
|
82
225
|
}
|
|
83
226
|
|
|
227
|
+
/**
|
|
228
|
+
* Bind guard.
|
|
229
|
+
*
|
|
230
|
+
* The sidecar holds the passport and mints a visa for whoever connects, so a
|
|
231
|
+
* listener reachable off-host hands the agent's scope and budget to anyone who
|
|
232
|
+
* can route to it. Loopback is the default and a non-loopback bind is an
|
|
233
|
+
* explicit, named opt-in rather than a config value that quietly widens it.
|
|
234
|
+
*/
|
|
235
|
+
export function assertBindHost(host, allowNonLoopback = false) {
|
|
236
|
+
if (isLoopbackBindHost(host) || allowNonLoopback) return host;
|
|
237
|
+
throw new Error(
|
|
238
|
+
`Refusing to bind the sidecar to ${host}: it is not a loopback address. The sidecar mints work-visas for ` +
|
|
239
|
+
"anything that connects to it, so a non-loopback bind exposes your agent's scope and budget to the " +
|
|
240
|
+
"network. Pass allowNonLoopback only if the listener is protected by something else."
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
|
|
84
244
|
export function startSidecar(opts) {
|
|
85
|
-
const { gateway, port = 8788, host = "127.0.0.1" } = opts;
|
|
245
|
+
const { gateway, port = 8788, host = "127.0.0.1", allowNonLoopback = false, allowConnectHosts = [] } = opts;
|
|
246
|
+
assertBindHost(host, allowNonLoopback);
|
|
86
247
|
const { server, getVisa } = createSidecar(opts);
|
|
87
248
|
server.listen(port, host, () => {
|
|
88
249
|
step(`PassControl visa sidecar forwarding to ${gateway}`);
|
|
89
250
|
step(`Listening on http://${host}:${port}`);
|
|
90
251
|
step(`Point your agent at: http://${host}:${port}/api/v1/anthropic (or /api/v1/openai)`);
|
|
91
|
-
step("API key = anything (ignored). Visa is minted + refreshed automatically
|
|
252
|
+
step("API key = anything (ignored). Visa is minted + refreshed automatically.");
|
|
253
|
+
// Said at startup rather than only in a refusal, because the whole point of
|
|
254
|
+
// HTTPS_PROXY is that nobody reads the docs first.
|
|
255
|
+
step("HTTPS_PROXY: CONNECT to a provider is refused, not tunnelled — PassControl cannot");
|
|
256
|
+
step("govern TLS it does not terminate, and does not install an intercepting CA.");
|
|
257
|
+
// Always printed, including when empty. An egress exception the operator
|
|
258
|
+
// cannot see is one they cannot audit, and this list is exactly the thing a
|
|
259
|
+
// checked-in config file used to be able to extend without saying so.
|
|
260
|
+
step(
|
|
261
|
+
allowConnectHosts.length
|
|
262
|
+
? `CONNECT allowlist: ${allowConnectHosts.join(", ")} (provider hosts are never eligible).\n`
|
|
263
|
+
: "CONNECT allowlist: none — only the gateway.\n"
|
|
264
|
+
);
|
|
92
265
|
getVisa()
|
|
93
266
|
.then(() => ok("visa warmed"))
|
|
94
267
|
.catch((e) => fail(`could not mint initial visa: ${e.message}`));
|
package/package.json
CHANGED