@impz/testing 7.5.0 → 7.6.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/README.md +36 -27
- package/dist/identity/create-test-identity-issuer.d.ts +23 -0
- package/dist/identity/index.d.ts +2 -0
- package/dist/identity.js +248 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +34800 -34299
- package/dist/types.d.ts +39 -0
- package/package.json +8 -4
package/README.md
CHANGED
|
@@ -35,20 +35,46 @@ test('it creates an imp', async () => {
|
|
|
35
35
|
optional peer dependency: add `acme-client` or the `@opentelemetry/*` exporters to your dev
|
|
36
36
|
dependencies.
|
|
37
37
|
- `onLog`: a callback for each line impd logs. impd writes nothing to stderr.
|
|
38
|
+
- `version`: the version that `system.info` and `system.features` report, so a client's
|
|
39
|
+
outdated-impd branch runs.
|
|
40
|
+
- `features`: feature flags merged into what `system.features` reports.
|
|
38
41
|
|
|
39
42
|
It returns:
|
|
40
43
|
|
|
41
|
-
| Field | What it is
|
|
42
|
-
| --------------------- |
|
|
43
|
-
| `url` |
|
|
44
|
-
| `
|
|
45
|
-
| `
|
|
46
|
-
| `
|
|
47
|
-
| `
|
|
48
|
-
| `
|
|
44
|
+
| Field | What it is |
|
|
45
|
+
| --------------------- | ----------------------------------------------------------------------------- |
|
|
46
|
+
| `url` | the fault proxy's API on a loopback port, for a client the test builds itself |
|
|
47
|
+
| `impdUrl` | impd's own API, which bypasses the proxy |
|
|
48
|
+
| `client` | an `@impz/client` client on `url` with `TEST_TOKEN`, the root token |
|
|
49
|
+
| `seedImage(name)` | adds an image of that name, which `imps.create` boots |
|
|
50
|
+
| `startGuest(impName)` | starts the stand-in guest of a created imp, for reverse forwards |
|
|
51
|
+
| `fireTicker(label)` | runs one of impd's periodic jobs now; no job runs on its own |
|
|
52
|
+
| `stop()` | stops impd and removes its data |
|
|
49
53
|
|
|
50
|
-
|
|
51
|
-
`
|
|
54
|
+
It also returns the fault hooks `fail`, `stall`, `clearFaults`, `dropConnections`, `freeze`, `thaw`,
|
|
55
|
+
`refuseExec`, `closeTunnels` and the recorded `calls`.
|
|
56
|
+
|
|
57
|
+
## Faults and identity tokens
|
|
58
|
+
|
|
59
|
+
`url` and `client` reach impd through a proxy that forwards every request and WebSocket until a test
|
|
60
|
+
sets a fault.
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
impd.fail('imps/sleep', { code: 'CONFLICT', status: 409 }, { times: 1 });
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`@impz/testing/identity` makes tokens that `verifyImpIdentity` from `@impz/client/identity` accepts,
|
|
67
|
+
with no impd:
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
import { createTestIdentityIssuer } from '@impz/testing/identity';
|
|
71
|
+
|
|
72
|
+
const issuer = await createTestIdentityIssuer({ issuer: 'host-a' });
|
|
73
|
+
const token = await issuer.signToken({ id: 'imp-1', name: 'box', audience: 'tasks.imp.internal' });
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
[Testing against impd](https://github.com/zgeoff/impz/blob/main/docs/guides/testing-impd.md) lists
|
|
77
|
+
each fault and each issuer method.
|
|
52
78
|
|
|
53
79
|
## The stand-in guest
|
|
54
80
|
|
|
@@ -58,24 +84,7 @@ forward on that guest port. It returns a Node `Duplex`: what the test writes rea
|
|
|
58
84
|
local end, and what that end sends back is what the test reads.
|
|
59
85
|
|
|
60
86
|
```ts
|
|
61
|
-
import { openReverseForward } from '@impz/client';
|
|
62
|
-
import { TEST_TOKEN } from '@impz/testing';
|
|
63
|
-
|
|
64
87
|
const guest = await impd.startGuest('box');
|
|
65
|
-
|
|
66
|
-
const forward = openReverseForward({
|
|
67
|
-
baseUrl: impd.url,
|
|
68
|
-
token: TEST_TOKEN,
|
|
69
|
-
name: 'box',
|
|
70
|
-
guest: { network: 'tcp', port: 4000 },
|
|
71
|
-
connect: (url, headers) => new WebSocket(url, { headers: { ...headers } }),
|
|
72
|
-
onConnection: (accept) => {
|
|
73
|
-
// relay to the local end, as the app under test does
|
|
74
|
-
},
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
await forward.listening;
|
|
78
|
-
|
|
79
88
|
const stream = await guest.connect(4000);
|
|
80
89
|
```
|
|
81
90
|
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { IdentityTrustDocument } from '@impz/client/identity';
|
|
2
|
+
export declare const IDENTITY_HEADER: string;
|
|
3
|
+
export interface TokenClaimsInput {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly name: string;
|
|
6
|
+
readonly audience: string;
|
|
7
|
+
readonly iat?: number;
|
|
8
|
+
readonly exp?: number;
|
|
9
|
+
readonly nowSeconds?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface TestIdentityIssuer {
|
|
12
|
+
readonly issuer: string;
|
|
13
|
+
readonly kid: string;
|
|
14
|
+
readonly document: IdentityTrustDocument;
|
|
15
|
+
readonly signToken: (claims: TokenClaimsInput) => Promise<string>;
|
|
16
|
+
readonly forge: (claims: TokenClaimsInput) => Promise<string>;
|
|
17
|
+
readonly retire: (at: number) => IdentityTrustDocument;
|
|
18
|
+
}
|
|
19
|
+
export interface TestIdentityIssuerOptions {
|
|
20
|
+
readonly issuer: string;
|
|
21
|
+
readonly kid?: string;
|
|
22
|
+
}
|
|
23
|
+
export declare function createTestIdentityIssuer(options: Readonly<TestIdentityIssuerOptions>): Promise<TestIdentityIssuer>;
|
package/dist/identity.js
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// packages/api/src/schemas/secret-schema.ts
|
|
3
|
+
import * as z3 from "zod";
|
|
4
|
+
|
|
5
|
+
// packages/api/src/schemas/exposure-schema.ts
|
|
6
|
+
import * as z2 from "zod";
|
|
7
|
+
|
|
8
|
+
// packages/api/src/schemas/name-schema.ts
|
|
9
|
+
import * as z from "zod";
|
|
10
|
+
var NameSchema = z.string().regex(/^[a-z][a-z0-9-]{0,30}$/u, "must be a lowercase letter followed by up to 30 lowercase letters, digits or hyphens");
|
|
11
|
+
|
|
12
|
+
// packages/api/src/schemas/exposure-schema.ts
|
|
13
|
+
var ExposureSchema = z2.enum(["tailnet", "public"]);
|
|
14
|
+
var PublicAuthSchema = z2.enum(["none", "token", "basic"]);
|
|
15
|
+
var BasicUserSchema = z2.string().regex(/^[!-9;-~]{1,64}$/u, "must be 1 to 64 printable characters, without a colon");
|
|
16
|
+
var ExposeInputSchema = z2.object({
|
|
17
|
+
name: NameSchema,
|
|
18
|
+
auth: PublicAuthSchema.default("token"),
|
|
19
|
+
user: BasicUserSchema.optional()
|
|
20
|
+
}).refine((input) => input.auth === "basic" || input.user === undefined, {
|
|
21
|
+
message: "only basic auth takes a user",
|
|
22
|
+
path: ["user"]
|
|
23
|
+
});
|
|
24
|
+
var ExposeResultSchema = z2.object({
|
|
25
|
+
url: z2.url(),
|
|
26
|
+
auth: PublicAuthSchema,
|
|
27
|
+
user: z2.string().nullable(),
|
|
28
|
+
credential: z2.string().nullable(),
|
|
29
|
+
warning: z2.string().optional()
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// packages/api/src/schemas/secret-schema.ts
|
|
33
|
+
var SecretNameSchema = NameSchema;
|
|
34
|
+
var PrintableSchema = z3.string().regex(/^[!-~]+$/u, "must be printable ASCII without spaces");
|
|
35
|
+
var SecretValueSchema = PrintableSchema.min(1).max(8192);
|
|
36
|
+
var BrokerHostSchema = z3.string().max(253).regex(/^(?:[a-z0-9][a-z0-9-]{0,62}\.)+[a-z][a-z0-9-]{0,62}$/u, "must be a lowercase hostname such as api.example.com");
|
|
37
|
+
var BrokerUpstreamSchema = z3.string().max(2048).transform((value, context) => {
|
|
38
|
+
const url = URL.parse(value);
|
|
39
|
+
if (url === null || url.protocol !== "http:" && url.protocol !== "https:") {
|
|
40
|
+
context.addIssue({ code: "custom", message: "must be an http or https URL" });
|
|
41
|
+
return z3.NEVER;
|
|
42
|
+
}
|
|
43
|
+
if (url.username !== "" || url.password !== "") {
|
|
44
|
+
context.addIssue({ code: "custom", message: "must not hold a user name or password" });
|
|
45
|
+
return z3.NEVER;
|
|
46
|
+
}
|
|
47
|
+
if (url.search !== "" || url.hash !== "" || value.includes("?") || value.includes("#")) {
|
|
48
|
+
context.addIssue({ code: "custom", message: "must not have a query or a fragment" });
|
|
49
|
+
return z3.NEVER;
|
|
50
|
+
}
|
|
51
|
+
if (url.pathname !== "/") {
|
|
52
|
+
context.addIssue({ code: "custom", message: "must be an origin with no path" });
|
|
53
|
+
return z3.NEVER;
|
|
54
|
+
}
|
|
55
|
+
return url.origin;
|
|
56
|
+
});
|
|
57
|
+
var METHOD_OVERRIDE_HEADERS = [
|
|
58
|
+
"x-http-method-override",
|
|
59
|
+
"x-http-method",
|
|
60
|
+
"x-method-override"
|
|
61
|
+
];
|
|
62
|
+
var IDENTITY_HEADER = "imp-identity";
|
|
63
|
+
var BrokerRuleSchema = z3.object({
|
|
64
|
+
host: BrokerHostSchema,
|
|
65
|
+
header: z3.string().regex(/^[a-z0-9-]{1,64}$/u, "must be a lowercase header name such as authorization").superRefine((header, context) => {
|
|
66
|
+
if (METHOD_OVERRIDE_HEADERS.includes(header)) {
|
|
67
|
+
context.addIssue({
|
|
68
|
+
code: "custom",
|
|
69
|
+
message: `must not be ${header}, which overrides the request's method`
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
if (header === IDENTITY_HEADER) {
|
|
73
|
+
context.addIssue({
|
|
74
|
+
code: "custom",
|
|
75
|
+
message: `must not be ${header}, which the broker sets to name the imp`
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
}),
|
|
79
|
+
scheme: z3.enum(["bearer", "basic", "raw"]),
|
|
80
|
+
user: BasicUserSchema.optional(),
|
|
81
|
+
upstream: BrokerUpstreamSchema.optional(),
|
|
82
|
+
identity: z3.literal(true).optional()
|
|
83
|
+
});
|
|
84
|
+
var SecretPresetSchema = z3.enum(["github", "anthropic", "npm"]);
|
|
85
|
+
var SecretKindSchema = z3.enum(["static", "oauth"]);
|
|
86
|
+
var OAuthConfigSchema = z3.object({
|
|
87
|
+
tokenUrl: z3.url({ protocol: /^https$/u }).max(2048),
|
|
88
|
+
clientId: PrintableSchema.min(1).max(256),
|
|
89
|
+
tokenFormat: z3.enum(["json", "form"]).default("form")
|
|
90
|
+
}, {
|
|
91
|
+
error: (issue) => issue.input === undefined ? "needs a token URL and a client id" : undefined
|
|
92
|
+
});
|
|
93
|
+
var OAuthStateSchema = OAuthConfigSchema.extend({
|
|
94
|
+
status: z3.enum(["pending", "ready", "needs_login"]),
|
|
95
|
+
expiresAt: z3.date().nullable(),
|
|
96
|
+
refreshedAt: z3.date().nullable(),
|
|
97
|
+
error: z3.string().nullable(),
|
|
98
|
+
idClaims: z3.record(z3.string(), z3.unknown()).readonly().nullable()
|
|
99
|
+
});
|
|
100
|
+
var BROKER_ENV_NAMES = [
|
|
101
|
+
"HTTPS_PROXY",
|
|
102
|
+
"https_proxy",
|
|
103
|
+
"NO_PROXY",
|
|
104
|
+
"no_proxy",
|
|
105
|
+
"NODE_USE_ENV_PROXY",
|
|
106
|
+
"SSL_CERT_FILE",
|
|
107
|
+
"NODE_EXTRA_CA_CERTS",
|
|
108
|
+
"GIT_SSL_CAINFO",
|
|
109
|
+
"REQUESTS_CA_BUNDLE",
|
|
110
|
+
"CURL_CA_BUNDLE"
|
|
111
|
+
];
|
|
112
|
+
var SecretEnvSchema = z3.array(z3.string().regex(/^[A-Z_][A-Z0-9_]{0,63}$/u, "must be an upper-case variable name").refine((name) => !BROKER_ENV_NAMES.includes(name), "must not be a variable the broker sets")).max(16).readonly();
|
|
113
|
+
var SecretSchema = z3.object({
|
|
114
|
+
name: SecretNameSchema,
|
|
115
|
+
kind: SecretKindSchema,
|
|
116
|
+
rules: z3.array(BrokerRuleSchema).readonly(),
|
|
117
|
+
env: SecretEnvSchema,
|
|
118
|
+
imps: z3.array(NameSchema).readonly(),
|
|
119
|
+
createdAt: z3.date(),
|
|
120
|
+
oauth: OAuthStateSchema.optional()
|
|
121
|
+
});
|
|
122
|
+
var SecretAddedSchema = SecretSchema.extend({
|
|
123
|
+
droppedGrants: z3.int().nonnegative().default(0)
|
|
124
|
+
});
|
|
125
|
+
var GrantMethodSchema = z3.string().regex(/^[A-Z]{1,16}$/u, "must be an uppercase method such as GET");
|
|
126
|
+
var GrantPathSchema = z3.string().max(512).regex(/^(?:\/(?:\*|[A-Za-z0-9._~!$&'()+,;=:@-]*))*(?:\/\*\*)?$/u, "must be a path such as /v1/messages, with * for one segment and a last /** for the rest").refine((path) => path.startsWith("/"), "must start with /");
|
|
127
|
+
var GrantFilterSchema = z3.object({
|
|
128
|
+
methods: z3.array(GrantMethodSchema).min(1).max(16).readonly().optional(),
|
|
129
|
+
paths: z3.array(GrantPathSchema).min(1).max(64).readonly().optional()
|
|
130
|
+
}).refine((filter) => filter.methods !== undefined || filter.paths !== undefined, "must name methods, paths or both");
|
|
131
|
+
var GrantSchema = z3.object({
|
|
132
|
+
secret: SecretNameSchema,
|
|
133
|
+
filter: GrantFilterSchema.nullable()
|
|
134
|
+
});
|
|
135
|
+
var AuditRefusalSchema = z3.enum([
|
|
136
|
+
"not-http",
|
|
137
|
+
"not-connect",
|
|
138
|
+
"bad-target",
|
|
139
|
+
"connection-limit",
|
|
140
|
+
"egress-policy",
|
|
141
|
+
"address-refused",
|
|
142
|
+
"wrong-host",
|
|
143
|
+
"websocket",
|
|
144
|
+
"no-grant",
|
|
145
|
+
"outside-filter"
|
|
146
|
+
]);
|
|
147
|
+
var AuditEntrySchema = z3.object({
|
|
148
|
+
at: z3.date(),
|
|
149
|
+
imp: NameSchema,
|
|
150
|
+
secret: SecretNameSchema,
|
|
151
|
+
method: z3.string(),
|
|
152
|
+
host: BrokerHostSchema,
|
|
153
|
+
path: z3.string(),
|
|
154
|
+
status: z3.int(),
|
|
155
|
+
requestBytes: z3.int().nonnegative(),
|
|
156
|
+
responseBytes: z3.int().nonnegative(),
|
|
157
|
+
durationMs: z3.int().nonnegative()
|
|
158
|
+
});
|
|
159
|
+
var RefusedRequestSchema = z3.object({
|
|
160
|
+
at: z3.date(),
|
|
161
|
+
imp: NameSchema,
|
|
162
|
+
method: z3.string().nullable(),
|
|
163
|
+
host: z3.string().max(253).nullable(),
|
|
164
|
+
path: z3.string().nullable(),
|
|
165
|
+
status: z3.int(),
|
|
166
|
+
durationMs: z3.int().nonnegative(),
|
|
167
|
+
reason: AuditRefusalSchema
|
|
168
|
+
});
|
|
169
|
+
// packages/api/src/schemas/identity-trust-document-schema.ts
|
|
170
|
+
import * as z4 from "zod";
|
|
171
|
+
var IdentityIssuerSchema = z4.string().regex(/^[A-Za-z0-9._-]{1,128}$/u, 'must be 1 to 128 letters, digits, ".", "_" or "-"');
|
|
172
|
+
var Base64UrlSchema = z4.string().regex(/^[A-Za-z0-9_-]+$/u);
|
|
173
|
+
var IdentityJwkSchema = z4.object({
|
|
174
|
+
kty: z4.literal("EC"),
|
|
175
|
+
crv: z4.literal("P-256"),
|
|
176
|
+
x: Base64UrlSchema,
|
|
177
|
+
y: Base64UrlSchema,
|
|
178
|
+
kid: z4.string().min(1).max(128),
|
|
179
|
+
alg: z4.literal("ES256"),
|
|
180
|
+
use: z4.literal("sig")
|
|
181
|
+
});
|
|
182
|
+
var RetireEntrySchema = z4.object({ kid: z4.string().min(1).max(128), at: z4.int().nonnegative() });
|
|
183
|
+
var IdentityTrustDocumentSchema = z4.object({
|
|
184
|
+
issuer: IdentityIssuerSchema,
|
|
185
|
+
keys: z4.array(IdentityJwkSchema).min(1).max(2).readonly(),
|
|
186
|
+
retire: z4.array(RetireEntrySchema).max(1).readonly()
|
|
187
|
+
});
|
|
188
|
+
var IdentityStageKeyInputSchema = z4.object({ at: z4.date() });
|
|
189
|
+
var IDENTITY_TOKEN_LIFE_S = 55;
|
|
190
|
+
// packages/testing/src/identity/create-test-identity-issuer.ts
|
|
191
|
+
var IDENTITY_HEADER2 = IDENTITY_HEADER;
|
|
192
|
+
var ES256 = { name: "ECDSA", namedCurve: "P-256" };
|
|
193
|
+
async function createTestIdentityIssuer(options) {
|
|
194
|
+
const issuer = options.issuer;
|
|
195
|
+
const kid = options.kid ?? `${issuer}-key-1`;
|
|
196
|
+
const pair = await crypto.subtle.generateKey(ES256, true, ["sign", "verify"]);
|
|
197
|
+
const publicJwk = await crypto.subtle.exportKey("jwk", pair.publicKey);
|
|
198
|
+
const document = {
|
|
199
|
+
issuer,
|
|
200
|
+
keys: [
|
|
201
|
+
{
|
|
202
|
+
kty: "EC",
|
|
203
|
+
crv: "P-256",
|
|
204
|
+
x: publicJwk.x ?? "",
|
|
205
|
+
y: publicJwk.y ?? "",
|
|
206
|
+
kid,
|
|
207
|
+
alg: "ES256",
|
|
208
|
+
use: "sig"
|
|
209
|
+
}
|
|
210
|
+
],
|
|
211
|
+
retire: []
|
|
212
|
+
};
|
|
213
|
+
return {
|
|
214
|
+
issuer,
|
|
215
|
+
kid,
|
|
216
|
+
document,
|
|
217
|
+
signToken: (claims) => signToken(pair.privateKey, { issuer, kid, claims }),
|
|
218
|
+
forge: async (claims) => {
|
|
219
|
+
const stranger = await crypto.subtle.generateKey(ES256, true, ["sign", "verify"]);
|
|
220
|
+
return signToken(stranger.privateKey, { issuer, kid, claims });
|
|
221
|
+
},
|
|
222
|
+
retire: (at) => ({ ...document, retire: [{ kid, at }] })
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
async function signToken(key, input) {
|
|
226
|
+
const claims = input.claims;
|
|
227
|
+
const iat = claims.iat ?? claims.nowSeconds ?? Math.floor(Date.now() / 1000);
|
|
228
|
+
const header = { alg: "ES256", typ: "JWT", kid: input.kid };
|
|
229
|
+
const payload = {
|
|
230
|
+
iss: input.issuer,
|
|
231
|
+
sub: claims.id,
|
|
232
|
+
aud: claims.audience,
|
|
233
|
+
iat,
|
|
234
|
+
exp: claims.exp ?? iat + IDENTITY_TOKEN_LIFE_S,
|
|
235
|
+
jti: Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("hex"),
|
|
236
|
+
imp_name: claims.name
|
|
237
|
+
};
|
|
238
|
+
const signingInput = `${encodeSegment(header)}.${encodeSegment(payload)}`;
|
|
239
|
+
const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, new TextEncoder().encode(signingInput));
|
|
240
|
+
return `${signingInput}.${Buffer.from(signature).toString("base64url")}`;
|
|
241
|
+
}
|
|
242
|
+
function encodeSegment(value) {
|
|
243
|
+
return Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
244
|
+
}
|
|
245
|
+
export {
|
|
246
|
+
IDENTITY_HEADER2 as IDENTITY_HEADER,
|
|
247
|
+
createTestIdentityIssuer
|
|
248
|
+
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { startTestImpd } from './start-test-impd';
|
|
2
2
|
export { TEST_TOKEN } from './test-token';
|
|
3
|
-
export type { TestGuest, TestImpd, TestImpdOptions } from './types';
|
|
3
|
+
export type { DefinedFault, ExecRefusal, FailOptions, FaultHandle, RawFault, RecordedCall, TestGuest, TestImpd, TestImpdOptions, } from './types';
|