@sealant/api-contracts-next 0.40.0-next.933 → 0.40.0-next.935

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.
@@ -0,0 +1,292 @@
1
+ /**
2
+ * A workspace's network policy and its brokered secrets (workspace isolation architecture §7,
3
+ * §8.4): the ONE definition of their shape and of the rules a value must meet, shared by the SDK
4
+ * (client-side refusal with the server's wording), the control-plane validators (every parse:
5
+ * create, worker, restart, policy update) and the runtime that hands them to the workspace's
6
+ * egress proxy (`<name>-proxy`).
7
+ *
8
+ * The rules mirror what the proxy itself refuses (`sealant-egress-proxy` `policy.rs`), so a
9
+ * policy sealant accepts is one the proxy loads: exact host names (never a wildcard), one HTTP
10
+ * header name per secret that neither frames nor routes a request, and bind hosts that are names,
11
+ * not addresses or URLs.
12
+ *
13
+ * Deliberately dependency-free, like `workspace-environment.ts`: data plus pure functions.
14
+ */
15
+ import { findWorkspaceSecretEnvReservedRule } from "./workspace-environment.js";
16
+ /** The lease the proxy holds traffic open for without hearing from sealant (§7.3). */
17
+ export const EGRESS_PROXY_LEASE_TTL_SECONDS = 120;
18
+ /** Synthetic addresses worktree resources are answered from. */
19
+ export const SYNTHETIC_RESOURCE_CIDR = "10.201.0.0/16";
20
+ export const NETWORK_POLICY_MAX_ALLOW_HOSTS = 256;
21
+ export const NETWORK_POLICY_MAX_RESOURCES = 64;
22
+ export const BROKERED_SECRETS_MAX = 64;
23
+ /** A brokered secret's value is one header value: bounded like one. */
24
+ export const BROKERED_SECRET_VALUE_MAX_LENGTH = 16 * 1024;
25
+ /**
26
+ * Header names that frame, route or authenticate the request to the proxy itself. A secret in
27
+ * one could change where the request goes or how it is read, so none may carry one. The same list
28
+ * as the proxy's `FORBIDDEN_SECRET_HEADERS`.
29
+ */
30
+ export const FORBIDDEN_BROKERED_HEADER_NAMES = [
31
+ "host",
32
+ "content-length",
33
+ "transfer-encoding",
34
+ "connection",
35
+ "upgrade",
36
+ "te",
37
+ "trailer",
38
+ "keep-alive",
39
+ "proxy-authorization",
40
+ "proxy-connection",
41
+ ];
42
+ const HEADER_TOKEN = /^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/;
43
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
44
+ const LABEL = /^[a-z0-9_-]{1,63}$/;
45
+ /** One IPv4 octet as Rust's `Ipv4Addr` reads it: 0-255, no sign and no leading zero. */
46
+ const OCTET = /^(0|[1-9]\d{0,2})$/;
47
+ /** The four octets of a strict dotted-quad IPv4 address, or `undefined`. */
48
+ const ipv4Octets = (value) => {
49
+ const parts = value.split(".");
50
+ if (parts.length !== 4 || !parts.every((part) => OCTET.test(part)))
51
+ return undefined;
52
+ const octets = parts.map(Number);
53
+ return octets.every((octet) => octet <= 255) ? octets : undefined;
54
+ };
55
+ const HEX_GROUP = /^[0-9a-fA-F]{1,4}$/;
56
+ /**
57
+ * Whether `value` is an IPv6 address as Rust's `Ipv6Addr` reads it: eight hex groups of one to
58
+ * four digits, at most one `::` standing for one or more zero groups, and an IPv4 dotted quad as
59
+ * the last 32 bits. No zone, no port, no brackets.
60
+ */
61
+ const isIpv6 = (value) => {
62
+ if (value.length === 0 || value.includes(":::"))
63
+ return false;
64
+ const halves = value.split("::");
65
+ if (halves.length > 2)
66
+ return false;
67
+ const head = (halves[0] ?? "").length === 0 ? [] : (halves[0] ?? "").split(":");
68
+ const tail = halves.length === 2 && (halves[1] ?? "").length > 0 ? (halves[1] ?? "").split(":") : [];
69
+ const groups = [...head, ...tail];
70
+ // The dotted quad is the address's last 32 bits: the final group, after any `::` (so never in a
71
+ // head that `::` ends, as in `1.2.3.4::`).
72
+ const quadAllowed = halves.length === 1 || tail.length > 0;
73
+ let width = 0;
74
+ for (const [index, group] of groups.entries()) {
75
+ const last = index === groups.length - 1;
76
+ if (quadAllowed && last && group.includes(".")) {
77
+ if (ipv4Octets(group) === undefined)
78
+ return false;
79
+ width += 2;
80
+ }
81
+ else if (HEX_GROUP.test(group)) {
82
+ width += 1;
83
+ }
84
+ else {
85
+ return false;
86
+ }
87
+ }
88
+ return halves.length === 2 ? width < 8 : width === 8;
89
+ };
90
+ /**
91
+ * Whether `value` is an IP literal a policy may name: a strict IPv4 or IPv6 address, an IPv6 one
92
+ * in brackets too. `db:5432` and `10.0.0.5:8080` are not: a port is never part of a host.
93
+ */
94
+ const isIpLiteral = (value) => {
95
+ const unbracketed = value.startsWith("[") && value.endsWith("]") ? value.slice(1, -1) : value;
96
+ return unbracketed === value
97
+ ? ipv4Octets(value) !== undefined || isIpv6(value)
98
+ : isIpv6(unbracketed);
99
+ };
100
+ /** Whether `name` is one HTTP header name (an RFC 9110 token). */
101
+ export const isHttpHeaderName = (name) => HEADER_TOKEN.test(name);
102
+ /** Whether a secret in header `name` is refused: not one name, or one that frames or routes. */
103
+ export const brokeredHeaderNameProblem = (name) => {
104
+ if (name.trim().length === 0)
105
+ return "headerName is required";
106
+ if (!isHttpHeaderName(name))
107
+ return `headerName \`${name}\` must be one HTTP header name`;
108
+ if (FORBIDDEN_BROKERED_HEADER_NAMES.includes(name.toLowerCase())) {
109
+ return `headerName \`${name}\` frames or routes the request and cannot carry a secret`;
110
+ }
111
+ return undefined;
112
+ };
113
+ /**
114
+ * Why `host` is not an exact policy host name, or `undefined` when it is one: lowercase DNS labels
115
+ * (letters, digits, `-`, `_`), or an IP literal when `allowIp`. Never a wildcard, a port, a path or
116
+ * a query: a policy names hosts, not URLs.
117
+ */
118
+ export const policyHostProblem = (host, options) => {
119
+ if (host.includes("*"))
120
+ return `\`${host}\` is a wildcard; name exact hosts`;
121
+ if (/[/?#@:\s]/.test(host) && !(options.allowIp && isIpLiteral(host))) {
122
+ return `\`${host}\` is not a host name (no scheme, port, path or query)`;
123
+ }
124
+ if (isIpLiteral(host)) {
125
+ return options.allowIp ? undefined : `\`${host}\` is an IP address; name a host`;
126
+ }
127
+ if (host !== host.toLowerCase())
128
+ return `\`${host}\` must be lowercase`;
129
+ const name = host.endsWith(".") ? host.slice(0, -1) : host;
130
+ if (name.length === 0 || name.length > 253 || !name.split(".").every((l) => LABEL.test(l))) {
131
+ return `\`${host}\` is not a host name`;
132
+ }
133
+ return undefined;
134
+ };
135
+ const portProblem = (port) => Number.isInteger(port) && port >= 1 && port <= 65_535
136
+ ? undefined
137
+ : `port ${String(port)} must be 1-65535`;
138
+ const methodsProblems = (field, methods) => (methods ?? []).flatMap((method) => isHttpHeaderName(method) && method === method.toUpperCase()
139
+ ? []
140
+ : [`${field}: \`${method}\` is not an uppercase HTTP method`]);
141
+ const pathPrefixProblems = (field, prefixes) => (prefixes ?? []).flatMap((prefix) => prefix.startsWith("/") && !prefix.includes("?") && !prefix.includes("#")
142
+ ? []
143
+ : [`${field}: path prefix \`${prefix}\` must start with \`/\` and hold no query`]);
144
+ const repeated = (values) => values.find((value, index) => values.indexOf(value) !== index);
145
+ /** Every rule `policy` breaks, in the words a create's refusal uses; empty when it breaks none. */
146
+ export const networkPolicyProblems = (policy) => {
147
+ const problems = [];
148
+ if (policy.policyHash.trim().length === 0)
149
+ problems.push("networkPolicy.policyHash is required");
150
+ if (policy.sourcePolicyRevision !== undefined &&
151
+ (!Number.isInteger(policy.sourcePolicyRevision) || policy.sourcePolicyRevision < 0)) {
152
+ problems.push("networkPolicy.sourcePolicyRevision must be a non-negative integer");
153
+ }
154
+ const hosts = policy.allowHosts ?? [];
155
+ if (hosts.length > NETWORK_POLICY_MAX_ALLOW_HOSTS) {
156
+ problems.push(`networkPolicy.allowHosts holds at most ${NETWORK_POLICY_MAX_ALLOW_HOSTS} hosts`);
157
+ }
158
+ for (const entry of hosts) {
159
+ const field = `networkPolicy.allowHosts \`${entry.host}\``;
160
+ const host = policyHostProblem(entry.host, { allowIp: true });
161
+ if (host !== undefined)
162
+ problems.push(`networkPolicy.allowHosts: ${host}`);
163
+ if (entry.ports !== undefined && entry.ports.length === 0) {
164
+ problems.push(`${field}: ports, when given, must name at least one port`);
165
+ }
166
+ for (const port of entry.ports ?? []) {
167
+ const problem = portProblem(port);
168
+ if (problem !== undefined)
169
+ problems.push(`${field}: ${problem}`);
170
+ }
171
+ problems.push(...methodsProblems(field, entry.methods));
172
+ problems.push(...pathPrefixProblems(field, entry.pathPrefixes));
173
+ }
174
+ for (const mirror of policy.allowMirrors ?? []) {
175
+ const host = policyHostProblem(mirror.host, { allowIp: false });
176
+ if (host !== undefined)
177
+ problems.push(`networkPolicy.allowMirrors: ${host}`);
178
+ const port = portProblem(mirror.port);
179
+ if (port !== undefined)
180
+ problems.push(`networkPolicy.allowMirrors \`${mirror.host}\`: ${port}`);
181
+ }
182
+ const resources = policy.allowResources ?? [];
183
+ if (resources.length > NETWORK_POLICY_MAX_RESOURCES) {
184
+ problems.push(`networkPolicy.allowResources holds at most ${NETWORK_POLICY_MAX_RESOURCES} resources`);
185
+ }
186
+ for (const resource of resources) {
187
+ const field = `networkPolicy.allowResources \`${resource.name}\``;
188
+ const name = policyHostProblem(resource.name, { allowIp: false });
189
+ if (name !== undefined)
190
+ problems.push(`networkPolicy.allowResources: ${name}`);
191
+ const host = policyHostProblem(resource.host, { allowIp: false });
192
+ if (host !== undefined)
193
+ problems.push(`${field}: ${host}`);
194
+ const port = portProblem(resource.port);
195
+ if (port !== undefined)
196
+ problems.push(`${field}: ${port}`);
197
+ const octets = ipv4Octets(resource.guestIp);
198
+ if (octets === undefined || octets[0] !== 10 || octets[1] !== 201) {
199
+ problems.push(`${field}: guestIp ${resource.guestIp} is outside ${SYNTHETIC_RESOURCE_CIDR}`);
200
+ }
201
+ }
202
+ const slot = repeated(resources.map((resource) => `${resource.guestIp}:${resource.port}`));
203
+ if (slot !== undefined)
204
+ problems.push(`networkPolicy.allowResources: ${slot} is assigned twice`);
205
+ return problems;
206
+ };
207
+ /** Every rule `secrets` break; empty when they break none. Values are never read here. */
208
+ export const brokeredSecretsProblems = (secrets) => {
209
+ const problems = [];
210
+ if (secrets.length > BROKERED_SECRETS_MAX) {
211
+ problems.push(`brokeredSecrets holds at most ${BROKERED_SECRETS_MAX} secrets`);
212
+ }
213
+ for (const secret of secrets) {
214
+ const field = `brokeredSecrets \`${secret.secretId}\``;
215
+ if (secret.secretId.trim().length === 0)
216
+ problems.push("brokeredSecrets: secretId is required");
217
+ if (!ENV_NAME.test(secret.name)) {
218
+ problems.push(`${field}: name must match [A-Za-z_][A-Za-z0-9_]*`);
219
+ }
220
+ else if (findWorkspaceSecretEnvReservedRule(secret.name) !== undefined) {
221
+ problems.push(`${field}: name ${secret.name} is reserved for the platform or an account`);
222
+ }
223
+ if (secret.placeholder.length < 8 || !/^[\x21-\x7e]+$/.test(secret.placeholder)) {
224
+ problems.push(`${field}: placeholder must be at least 8 visible ASCII characters`);
225
+ }
226
+ if (secret.secretRef.trim().length === 0)
227
+ problems.push(`${field}: secretRef is required`);
228
+ const header = brokeredHeaderNameProblem(secret.headerName);
229
+ if (header !== undefined)
230
+ problems.push(`${field}: ${header}`);
231
+ if (secret.bindHosts.length === 0) {
232
+ problems.push(`${field}: bindHosts must name at least one host`);
233
+ }
234
+ for (const bindHost of secret.bindHosts) {
235
+ const host = policyHostProblem(bindHost, { allowIp: false });
236
+ if (host !== undefined)
237
+ problems.push(`${field}: bindHosts ${host}`);
238
+ }
239
+ problems.push(...methodsProblems(field, secret.methods));
240
+ problems.push(...pathPrefixProblems(field, secret.pathPrefixes));
241
+ }
242
+ for (const [key, label] of [
243
+ ["secretId", "secretId"],
244
+ ["name", "name"],
245
+ ["placeholder", "placeholder"],
246
+ ]) {
247
+ const twice = repeated(secrets.map((secret) => secret[key]));
248
+ if (twice !== undefined)
249
+ problems.push(`brokeredSecrets: ${label} \`${twice}\` appears twice`);
250
+ }
251
+ return problems;
252
+ };
253
+ /**
254
+ * The problems with the values a request sends for its brokered secrets: each `secretRef` needs a
255
+ * value, each value is one non-empty header value (no line breaks or control characters), and no
256
+ * value goes unused. Never echoes a value.
257
+ */
258
+ export const brokeredSecretValuesProblems = (secrets, values) => {
259
+ const problems = [];
260
+ const refs = new Set(secrets.map((secret) => secret.secretRef));
261
+ for (const ref of refs) {
262
+ const value = values[ref];
263
+ if (value === undefined) {
264
+ problems.push(`brokeredSecretValues has no value for secretRef \`${ref}\``);
265
+ continue;
266
+ }
267
+ if (value.length === 0 ||
268
+ value.length > BROKERED_SECRET_VALUE_MAX_LENGTH ||
269
+ // oxlint-disable-next-line no-control-regex -- a header value must hold no control character
270
+ /[\u0000-\u0008\u000a-\u001f\u007f]/.test(value)) {
271
+ problems.push(`brokeredSecretValues \`${ref}\` must be one non-empty header value of at most ${BROKERED_SECRET_VALUE_MAX_LENGTH} characters`);
272
+ }
273
+ }
274
+ for (const ref of Object.keys(values)) {
275
+ if (!refs.has(ref))
276
+ problems.push(`brokeredSecretValues \`${ref}\` names no brokered secret`);
277
+ }
278
+ return problems;
279
+ };
280
+ /** Whether a workspace with this policy and these secrets runs behind its own egress proxy. */
281
+ export const needsEgressProxy = (input) => input.networkPolicy?.mode === "restricted" ||
282
+ (input.brokeredSecrets ?? []).length > 0 ||
283
+ (input.revokedHosts ?? []).length > 0;
284
+ /**
285
+ * A host as a revocation stores it: lowercase, no trailing dot, so a tombstone matches the host the
286
+ * proxy compares it with. `undefined` when it is not a host a policy could name.
287
+ */
288
+ export const canonicalRevocationHost = (host) => {
289
+ const trimmed = host.trim().toLowerCase();
290
+ const canonical = trimmed.endsWith(".") ? trimmed.slice(0, -1) : trimmed;
291
+ return policyHostProblem(canonical, { allowIp: true }) === undefined ? canonical : undefined;
292
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sealant/api-contracts-next",
3
- "version": "0.40.0-next.933",
3
+ "version": "0.40.0-next.935",
4
4
  "description": "Contract-first HTTP API definitions for Sealant services",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -25,6 +25,10 @@
25
25
  "./connected-account-selector": {
26
26
  "types": "./dist/connected-account-selector.d.ts",
27
27
  "import": "./dist/connected-account-selector.js"
28
+ },
29
+ "./network-policy": {
30
+ "types": "./dist/network-policy.d.ts",
31
+ "import": "./dist/network-policy.js"
28
32
  }
29
33
  },
30
34
  "files": [
@@ -36,7 +40,7 @@
36
40
  "peerDependencies": {
37
41
  "effect": "^4.0.5"
38
42
  },
39
- "gitHead": "7dd7c9a1a706b222fd5474284406879b31afa882",
43
+ "gitHead": "692011a24d7f4de9d273d9db025f6c29edb79bc2",
40
44
  "publishConfig": {
41
45
  "access": "public"
42
46
  }