-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathbroker-register.test.mjs
More file actions
291 lines (253 loc) 路 10.1 KB
/
Copy pathbroker-register.test.mjs
File metadata and controls
291 lines (253 loc) 路 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createServer } from "node:http";
import { pathToFileURL } from "node:url";
import {
parseArgs,
normalizeBrokerUrl,
validateWorkspaceId,
mapRegisterError,
registerWithBroker,
upsertEnvContent,
runRegistration,
isMainModule,
} from "./broker-register.mjs";
const FIXTURE_SERVER_KEYS = {
server_pubkey: Buffer.alloc(32, 1).toString("base64"),
server_private_key: Buffer.alloc(32, 2).toString("base64"),
server_signing_pubkey: Buffer.alloc(32, 3).toString("base64"),
server_signing_private_key: Buffer.alloc(32, 4).toString("base64"),
};
function jsonResponse(data, status = 200) {
return new Response(JSON.stringify(data), {
status,
headers: { "Content-Type": "application/json" },
});
}
test("parseArgs parses long-form options", () => {
const parsed = parseArgs([
"--broker-url",
"https://broker.example.com/",
"--workspace-id",
"T123ABC",
"--registration-token",
"token-xyz",
]);
assert.deepEqual(parsed, {
brokerUrl: "https://broker.example.com/",
workspaceId: "T123ABC",
registrationToken: "token-xyz",
verbose: false,
help: false,
});
});
test("parseArgs sets verbose=true for -v and --verbose", () => {
const short = parseArgs(["-v"]);
assert.equal(short.verbose, true);
const long = parseArgs(["--verbose"]);
assert.equal(long.verbose, true);
});
test("isMainModule handles symlink argv path", () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "broker-register-main-"));
const realFile = path.join(tempDir, "real.mjs");
const symlinkFile = path.join(tempDir, "link.mjs");
try {
fs.writeFileSync(realFile, "export default 1;\n", "utf8");
fs.symlinkSync(realFile, symlinkFile);
const moduleUrl = pathToFileURL(fs.realpathSync(realFile)).href;
assert.equal(isMainModule(moduleUrl, symlinkFile), true);
} finally {
try { fs.unlinkSync(symlinkFile); } catch {}
try { fs.unlinkSync(realFile); } catch {}
try { fs.rmdirSync(tempDir); } catch {}
}
});
test("parseArgs accepts registration token", () => {
const parsed = parseArgs(["--registration-token", "token-123"]);
assert.equal(parsed.registrationToken, "token-123");
});
test("parseArgs rejects unknown arguments", () => {
assert.throws(() => parseArgs(["--wat"]), /unknown argument/);
});
test("parseArgs rejects legacy auth-code argument", () => {
assert.throws(() => parseArgs(["--auth-code", "legacy"]), /unknown argument/);
});
test("validation helpers normalize and enforce broker/workspace formats", () => {
assert.equal(normalizeBrokerUrl("https://broker.example.com/"), "https://broker.example.com");
assert.equal(validateWorkspaceId("T0ABC123"), true);
assert.equal(validateWorkspaceId("workspace-123"), false);
assert.throws(() => normalizeBrokerUrl("ftp://broker.example.com"), /http:\/\/ or https:\/\//);
});
test("mapRegisterError returns actionable messages", () => {
assert.match(mapRegisterError(400, "missing registration proof"), /registration token is required/);
assert.match(mapRegisterError(403, "invalid registration token"), /invalid registration token/);
assert.match(mapRegisterError(409, "workspace already active"), /already active/);
assert.match(mapRegisterError(500, "oops"), /broker server error/);
});
test("registerWithBroker fetches pubkeys then posts registration payload", async () => {
const calls = [];
const fetchImpl = async (url, init = {}) => {
calls.push({ url: String(url), init });
if (String(url).endsWith("/api/broker-pubkey")) {
return jsonResponse({
ok: true,
broker_pubkey: Buffer.alloc(32, 9).toString("base64"),
broker_signing_pubkey: Buffer.alloc(32, 8).toString("base64"),
});
}
if (String(url).endsWith("/api/register")) {
const payload = JSON.parse(init.body);
assert.equal(payload.workspace_id, "TTEST123");
assert.equal(payload.server_pubkey, FIXTURE_SERVER_KEYS.server_pubkey);
assert.equal(payload.server_signing_pubkey, FIXTURE_SERVER_KEYS.server_signing_pubkey);
assert.equal(payload.registration_token, "token-abc");
assert.equal(payload.auth_code, undefined);
assert.equal(payload.server_callback_url, undefined);
return jsonResponse({
ok: true,
broker_pubkey: Buffer.alloc(32, 9).toString("base64"),
broker_signing_pubkey: Buffer.alloc(32, 8).toString("base64"),
broker_access_token: "tok-abc",
broker_access_token_expires_at: "2026-02-22T22:00:00.000Z",
broker_access_token_scopes: ["slack.send", "inbox.pull"],
});
}
return jsonResponse({ ok: false, error: "unexpected endpoint" }, 404);
};
const result = await registerWithBroker({
brokerUrl: "https://broker.example.com",
workspaceId: "TTEST123",
registrationToken: "token-abc",
serverKeys: FIXTURE_SERVER_KEYS,
fetchImpl,
});
assert.equal(calls.length, 2);
assert.match(calls[0].url, /\/api\/broker-pubkey$/);
assert.match(calls[1].url, /\/api\/register$/);
assert.equal(result.broker_pubkey, Buffer.alloc(32, 9).toString("base64"));
assert.equal(result.broker_signing_pubkey, Buffer.alloc(32, 8).toString("base64"));
assert.equal(result.broker_access_token, "tok-abc");
assert.equal(result.broker_access_token_expires_at, "2026-02-22T22:00:00.000Z");
assert.deepEqual(result.broker_access_token_scopes, ["slack.send", "inbox.pull"]);
});
test("registerWithBroker sends registration_token when provided", async () => {
const fetchImpl = async (url, init = {}) => {
if (String(url).endsWith("/api/broker-pubkey")) {
return jsonResponse({
ok: true,
broker_pubkey: Buffer.alloc(32, 9).toString("base64"),
broker_signing_pubkey: Buffer.alloc(32, 8).toString("base64"),
});
}
if (String(url).endsWith("/api/register")) {
const payload = JSON.parse(init.body);
assert.equal(payload.registration_token, "token-abc");
assert.equal(payload.auth_code, undefined);
return jsonResponse({
ok: true,
broker_pubkey: Buffer.alloc(32, 9).toString("base64"),
broker_signing_pubkey: Buffer.alloc(32, 8).toString("base64"),
});
}
return jsonResponse({ ok: false, error: "unexpected endpoint" }, 404);
};
await registerWithBroker({
brokerUrl: "https://broker.example.com",
workspaceId: "TTEST123",
registrationToken: "token-abc",
serverKeys: FIXTURE_SERVER_KEYS,
fetchImpl,
});
});
test("runRegistration integration path succeeds against live local HTTP server", async (t) => {
const brokerPubkey = Buffer.alloc(32, 5).toString("base64");
const brokerSigningPubkey = Buffer.alloc(32, 6).toString("base64");
let receivedRegisterPayload = null;
const server = createServer(async (req, res) => {
if (req.method === "GET" && req.url === "/api/broker-pubkey") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, broker_pubkey: brokerPubkey, broker_signing_pubkey: brokerSigningPubkey }));
return;
}
if (req.method === "POST" && req.url === "/api/register") {
let raw = "";
for await (const chunk of req) raw += chunk;
receivedRegisterPayload = JSON.parse(raw);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({
ok: true,
broker_pubkey: brokerPubkey,
broker_signing_pubkey: brokerSigningPubkey,
broker_access_token: "tok-live",
broker_access_token_expires_at: "2026-02-22T22:00:00.000Z",
broker_access_token_scopes: ["slack.send"],
}));
return;
}
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: false, error: "not found" }));
});
try {
await new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
} catch (error) {
if (error && typeof error === "object" && "code" in error) {
const code = String(error.code || "");
if (code === "EPERM" || code === "EACCES") {
t.skip("Localhost bind is not permitted in this environment");
return;
}
}
throw error;
}
const address = server.address();
const brokerUrl = `http://127.0.0.1:${address.port}`;
try {
const result = await runRegistration({
brokerUrl,
workspaceId: "TABC12345",
registrationToken: "token-from-dashboard",
});
assert.ok(receivedRegisterPayload);
assert.equal(receivedRegisterPayload.workspace_id, "TABC12345");
assert.equal(receivedRegisterPayload.registration_token, "token-from-dashboard");
assert.equal(receivedRegisterPayload.server_callback_url, undefined);
assert.ok(result.updates.SLACK_BROKER_SERVER_PRIVATE_KEY);
assert.ok(result.updates.SLACK_BROKER_SERVER_SIGNING_PRIVATE_KEY);
assert.equal(result.updates.SLACK_BROKER_PUBLIC_KEY, brokerPubkey);
assert.equal(result.updates.SLACK_BROKER_SIGNING_PUBLIC_KEY, brokerSigningPubkey);
assert.equal(result.updates.SLACK_BROKER_ACCESS_TOKEN, "tok-live");
assert.equal(result.updates.SLACK_BROKER_ACCESS_TOKEN_EXPIRES_AT, "2026-02-22T22:00:00.000Z");
assert.equal(result.updates.SLACK_BROKER_ACCESS_TOKEN_SCOPES, "slack.send");
} finally {
await new Promise((resolve, reject) => server.close((err) => (err ? reject(err) : resolve())));
}
});
test("runRegistration requires registration token", async () => {
await assert.rejects(
runRegistration({
brokerUrl: "https://broker.example.com",
workspaceId: "TABC12345",
}),
/registration token is required/,
);
});
test("upsertEnvContent updates existing values and appends new ones", () => {
const existing = [
"SLACK_BOT_TOKEN=xoxb-old",
"SLACK_ALLOWED_USERS=U1,U2",
"",
].join("\n");
const next = upsertEnvContent(existing, {
SLACK_ALLOWED_USERS: "U3,U4",
SLACK_BROKER_URL: "https://broker.example.com",
});
assert.match(next, /SLACK_ALLOWED_USERS=U3,U4/);
assert.match(next, /SLACK_BROKER_URL=https:\/\/broker\.example\.com/);
assert.match(next, /SLACK_BOT_TOKEN=xoxb-old/);
});