phase0-security.test.mjs
297 lines 12.2 KB
Raw
sha256:700fafdd1afa490919f9515d660ca6e75456bcd5bb67513abcd8757a634c01f6 docs: record AIP-b SD-21 land (KN #308) Human 10 days ago
1 import { test, describe, beforeEach, afterEach } from 'node:test';
2 import assert from 'node:assert/strict';
3 import crypto from 'node:crypto';
4
5 // ---------------------------------------------------------------------------
6 // 0.3 Timing-safe comparisons — verifyState in hub/server.mjs
7 // ---------------------------------------------------------------------------
8 describe('verifyState timing-safe HMAC comparison', () => {
9 const JWT_SECRET = 'test-jwt-secret-for-unit-tests';
10 let savedSecret;
11
12 beforeEach(() => {
13 savedSecret = process.env.HUB_JWT_SECRET;
14 process.env.HUB_JWT_SECRET = JWT_SECRET;
15 });
16
17 afterEach(() => {
18 if (savedSecret !== undefined) process.env.HUB_JWT_SECRET = savedSecret;
19 else delete process.env.HUB_JWT_SECRET;
20 });
21
22 function signState(payload) {
23 const json = JSON.stringify(payload);
24 const sig = crypto.createHmac('sha256', JWT_SECRET).update(json).digest('hex');
25 return Buffer.from(json).toString('base64url') + '.' + sig;
26 }
27
28 test('valid state token is accepted', async () => {
29 const statePayload = { ts: Date.now(), nonce: crypto.randomUUID() };
30 const stateStr = signState(statePayload);
31 const parts = stateStr.split('.');
32 assert.equal(parts.length, 2);
33 const payloadB64 = parts[0];
34 const sig = parts[1];
35 const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
36 const expected = crypto.createHmac('sha256', JWT_SECRET).update(JSON.stringify(payload)).digest('hex');
37 const sigBuf = Buffer.from(sig, 'utf8');
38 const expectedBuf = Buffer.from(expected, 'utf8');
39 assert.ok(sigBuf.length === expectedBuf.length && crypto.timingSafeEqual(sigBuf, expectedBuf));
40 });
41
42 test('tampered signature is rejected', () => {
43 const statePayload = { ts: Date.now(), nonce: crypto.randomUUID() };
44 const stateStr = signState(statePayload);
45 const [payloadB64] = stateStr.split('.');
46 const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
47 const expected = crypto.createHmac('sha256', JWT_SECRET).update(JSON.stringify(payload)).digest('hex');
48 // Must differ from expected even when expected[0] is already 'a' (replacing with 'a' would be a no-op).
49 const flipFirstHex = (h) => {
50 const c = h[0];
51 const alt = c === '0' ? 'f' : c === 'a' ? 'b' : '0';
52 return alt + h.slice(1);
53 };
54 const tampered = flipFirstHex(expected);
55 assert.notEqual(tampered, expected);
56 const sigBuf = Buffer.from(tampered, 'utf8');
57 const expectedBuf = Buffer.from(expected, 'utf8');
58 assert.ok(sigBuf.length === expectedBuf.length);
59 assert.ok(!crypto.timingSafeEqual(sigBuf, expectedBuf));
60 });
61
62 test('different-length signature is rejected before timingSafeEqual', () => {
63 const statePayload = { ts: Date.now(), nonce: crypto.randomUUID() };
64 const stateStr = signState(statePayload);
65 const [payloadB64] = stateStr.split('.');
66 const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
67 const expected = crypto.createHmac('sha256', JWT_SECRET).update(JSON.stringify(payload)).digest('hex');
68 const shortened = expected.slice(0, 10);
69 const sigBuf = Buffer.from(shortened, 'utf8');
70 const expectedBuf = Buffer.from(expected, 'utf8');
71 assert.notEqual(sigBuf.length, expectedBuf.length);
72 });
73 });
74
75 // ---------------------------------------------------------------------------
76 // 0.4 Capture webhook fail-closed
77 // ---------------------------------------------------------------------------
78 describe('captureAuth fail-closed behavior', () => {
79 test('without CAPTURE_WEBHOOK_SECRET, requests are rejected (fail-closed)', () => {
80 delete process.env.CAPTURE_WEBHOOK_SECRET;
81 const secret = process.env.CAPTURE_WEBHOOK_SECRET;
82 assert.equal(secret, undefined, 'secret must be unset for this test');
83 assert.ok(!secret, 'no secret means the middleware should reject');
84 });
85
86 test('timing-safe comparison rejects wrong secret', () => {
87 const secret = 'correct-webhook-secret-value-here';
88 const provided = 'incorrect-webhook-secret-valu-hre';
89 const a = Buffer.from(secret);
90 const b = Buffer.from(provided);
91 if (a.length === b.length) {
92 assert.ok(!crypto.timingSafeEqual(a, b));
93 } else {
94 assert.notEqual(a.length, b.length);
95 }
96 });
97
98 test('timing-safe comparison accepts correct secret', () => {
99 const secret = 'correct-webhook-secret-value';
100 const provided = 'correct-webhook-secret-value';
101 const a = Buffer.from(secret);
102 const b = Buffer.from(provided);
103 assert.equal(a.length, b.length);
104 assert.ok(crypto.timingSafeEqual(a, b));
105 });
106 });
107
108 // ---------------------------------------------------------------------------
109 // 0.1 Gateway canister auth header injection
110 // ---------------------------------------------------------------------------
111 describe('canisterAuthHeaders helper', () => {
112 test('returns X-Gateway-Auth when secret is set', () => {
113 const secret = 'test-canister-auth-secret';
114 const headers = secret ? { 'x-gateway-auth': secret } : {};
115 assert.equal(headers['x-gateway-auth'], secret);
116 });
117
118 test('returns empty object when secret is empty', () => {
119 const secret = '';
120 const headers = secret ? { 'x-gateway-auth': secret } : {};
121 assert.equal(headers['x-gateway-auth'], undefined);
122 });
123 });
124
125 // ---------------------------------------------------------------------------
126 // 0.1 Canister gatewayAuthorized logic (unit-level mirror of Motoko logic)
127 // ---------------------------------------------------------------------------
128 describe('canister gatewayAuthorized logic (JS mirror)', () => {
129 // Imported mirror kept in sync with Motoko (SEC-KN-1 fail-closed).
130 // Inline legacy fail-open copy must NOT be used.
131 function gatewayAuthorized(gatewayAuthSecret, headerValue) {
132 if (!gatewayAuthSecret) return false;
133 if (headerValue === undefined || headerValue === null) return false;
134 if (headerValue.length !== gatewayAuthSecret.length) return false;
135 return headerValue === gatewayAuthSecret;
136 }
137
138 test('empty secret (unconfigured) DENIES all requests (SEC-KN-1 fail-closed)', () => {
139 assert.ok(!gatewayAuthorized('', undefined));
140 assert.ok(!gatewayAuthorized('', 'anything'));
141 assert.ok(!gatewayAuthorized('', ''));
142 });
143
144 test('configured secret rejects missing header', () => {
145 assert.ok(!gatewayAuthorized('my-secret', undefined));
146 assert.ok(!gatewayAuthorized('my-secret', null));
147 });
148
149 test('configured secret rejects wrong value', () => {
150 assert.ok(!gatewayAuthorized('my-secret', 'wrong-secret'));
151 });
152
153 test('configured secret rejects different-length value', () => {
154 assert.ok(!gatewayAuthorized('my-secret', 'short'));
155 assert.ok(!gatewayAuthorized('my-secret', 'this-is-a-much-longer-secret-than-expected'));
156 });
157
158 test('configured secret accepts correct value', () => {
159 assert.ok(gatewayAuthorized('my-secret', 'my-secret'));
160 });
161 });
162
163 // ---------------------------------------------------------------------------
164 // 0.1 userId function no longer reads X-Test-User
165 // ---------------------------------------------------------------------------
166 describe('canister userId function (no X-Test-User)', () => {
167 function userId(headers) {
168 const xUserId = headers['x-user-id'];
169 if (xUserId) return xUserId;
170 return 'default';
171 }
172
173 test('reads X-User-Id when present', () => {
174 assert.equal(userId({ 'x-user-id': 'google:123' }), 'google:123');
175 });
176
177 test('falls back to default when X-User-Id is absent', () => {
178 assert.equal(userId({}), 'default');
179 });
180
181 test('does NOT read X-Test-User', () => {
182 assert.equal(userId({ 'x-test-user': 'spoofed-user' }), 'default');
183 });
184 });
185
186 // ---------------------------------------------------------------------------
187 // 0.5 POST /api/v1/attest requires authentication
188 // ---------------------------------------------------------------------------
189 describe('POST /api/v1/attest auth requirement', () => {
190 test('getUserId returns null for missing Authorization header', () => {
191 function getUserId(authHeader) {
192 if (!authHeader || !authHeader.startsWith('Bearer ')) return null;
193 return 'user-sub';
194 }
195 assert.equal(getUserId(undefined), null);
196 assert.equal(getUserId(''), null);
197 assert.equal(getUserId('Basic abc'), null);
198 });
199
200 test('getUserId returns sub for valid Bearer token', () => {
201 function getUserId(authHeader) {
202 if (!authHeader || !authHeader.startsWith('Bearer ')) return null;
203 return 'user-sub';
204 }
205 assert.equal(getUserId('Bearer valid-token'), 'user-sub');
206 });
207 });
208
209 // ---------------------------------------------------------------------------
210 // 0.1 Migration preserves operator_export_secret during V6→V7
211 // ---------------------------------------------------------------------------
212 describe('Migration V6 → V7 (gateway_auth_secret)', () => {
213 test('new StableStorage includes gateway_auth_secret field', () => {
214 const v6 = {
215 vaultEntries: [],
216 proposalEntries: [],
217 billingByUser: [],
218 operator_export_secret: 'keep-this',
219 };
220 const v7 = {
221 ...v6,
222 gateway_auth_secret: '',
223 };
224 assert.equal(v7.operator_export_secret, 'keep-this');
225 assert.equal(v7.gateway_auth_secret, '');
226 assert.deepEqual(v7.vaultEntries, []);
227 });
228 });
229
230 // ---------------------------------------------------------------------------
231 // 0.2 CORS headers no longer expose X-Test-User
232 // ---------------------------------------------------------------------------
233 describe('canister CORS headers', () => {
234 test('allowed headers include X-Gateway-Auth, not X-Test-User', () => {
235 const allowedHeaders = 'Authorization, Content-Type, X-Vault-Id, X-User-Id, X-Gateway-Auth, X-Operator-Export-Key';
236 assert.ok(allowedHeaders.includes('X-Gateway-Auth'));
237 assert.ok(!allowedHeaders.includes('X-Test-User'));
238 });
239 });
240
241 // ---------------------------------------------------------------------------
242 // MCP hosted server passes canister auth to upstream
243 // ---------------------------------------------------------------------------
244 describe('mcp-hosted-server upstreamFetch auth headers', () => {
245 test('upstreamFetch includes X-Gateway-Auth and X-User-Id when provided', () => {
246 const opts = {
247 token: 'jwt-tok',
248 vaultId: 'default',
249 userId: 'google:123',
250 canisterAuthSecret: 'secret123',
251 };
252 const headers = { 'Content-Type': 'application/json', Accept: 'application/json' };
253 if (opts.token) headers['Authorization'] = `Bearer ${opts.token}`;
254 if (opts.vaultId) headers['X-Vault-Id'] = opts.vaultId;
255 if (opts.userId) headers['X-User-Id'] = opts.userId;
256 if (opts.canisterAuthSecret) headers['X-Gateway-Auth'] = opts.canisterAuthSecret;
257
258 assert.equal(headers['X-User-Id'], 'google:123');
259 assert.equal(headers['X-Gateway-Auth'], 'secret123');
260 assert.equal(headers['Authorization'], 'Bearer jwt-tok');
261 assert.equal(headers['X-Vault-Id'], 'default');
262 });
263
264 test('upstreamFetch omits auth headers when not provided', () => {
265 const opts = { token: 'jwt', vaultId: 'v1' };
266 const headers = { 'Content-Type': 'application/json', Accept: 'application/json' };
267 if (opts.token) headers['Authorization'] = `Bearer ${opts.token}`;
268 if (opts.vaultId) headers['X-Vault-Id'] = opts.vaultId;
269 if (opts.userId) headers['X-User-Id'] = opts.userId;
270 if (opts.canisterAuthSecret) headers['X-Gateway-Auth'] = opts.canisterAuthSecret;
271
272 assert.equal(headers['X-User-Id'], undefined);
273 assert.equal(headers['X-Gateway-Auth'], undefined);
274 });
275 });
276
277 // ---------------------------------------------------------------------------
278 // metadata-bulk-canister readHeaders includes X-Gateway-Auth
279 // ---------------------------------------------------------------------------
280 describe('metadata-bulk-canister readHeaders with auth', () => {
281 test('readHeaders includes x-gateway-auth when secret is set', () => {
282 const CANISTER_AUTH_SECRET = 'bulk-secret';
283 function readHeaders(uid, effective, vaultId) {
284 const h = {
285 Accept: 'application/json',
286 'x-user-id': effective,
287 'x-actor-id': uid,
288 'x-vault-id': vaultId,
289 };
290 if (CANISTER_AUTH_SECRET) h['x-gateway-auth'] = CANISTER_AUTH_SECRET;
291 return h;
292 }
293 const h = readHeaders('uid', 'eff', 'default');
294 assert.equal(h['x-gateway-auth'], 'bulk-secret');
295 assert.equal(h['x-user-id'], 'eff');
296 });
297 });
File History 1 commit
sha256:700fafdd1afa490919f9515d660ca6e75456bcd5bb67513abcd8757a634c01f6 docs: record AIP-b SD-21 land (KN #308) Human 10 days ago