phase0-security.test.mjs
sha256:65ccb454656ea5acdea0a10e559b78bcde1eb6ff753ecc2911bc99d1c3d7cadd
feat(calendar): enforce agent context tiers in retrieval AP…
Human
minor
⚠ breaking
2 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 | function gatewayAuthorized(gatewayAuthSecret, headerValue) { |
| 130 | if (!gatewayAuthSecret) return true; |
| 131 | if (headerValue === undefined || headerValue === null) return false; |
| 132 | if (headerValue.length !== gatewayAuthSecret.length) return false; |
| 133 | return headerValue === gatewayAuthSecret; |
| 134 | } |
| 135 | |
| 136 | test('empty secret (unconfigured) allows all requests (backward compat)', () => { |
| 137 | assert.ok(gatewayAuthorized('', undefined)); |
| 138 | assert.ok(gatewayAuthorized('', 'anything')); |
| 139 | }); |
| 140 | |
| 141 | test('configured secret rejects missing header', () => { |
| 142 | assert.ok(!gatewayAuthorized('my-secret', undefined)); |
| 143 | assert.ok(!gatewayAuthorized('my-secret', null)); |
| 144 | }); |
| 145 | |
| 146 | test('configured secret rejects wrong value', () => { |
| 147 | assert.ok(!gatewayAuthorized('my-secret', 'wrong-secret')); |
| 148 | }); |
| 149 | |
| 150 | test('configured secret rejects different-length value', () => { |
| 151 | assert.ok(!gatewayAuthorized('my-secret', 'short')); |
| 152 | assert.ok(!gatewayAuthorized('my-secret', 'this-is-a-much-longer-secret-than-expected')); |
| 153 | }); |
| 154 | |
| 155 | test('configured secret accepts correct value', () => { |
| 156 | assert.ok(gatewayAuthorized('my-secret', 'my-secret')); |
| 157 | }); |
| 158 | }); |
| 159 | |
| 160 | // --------------------------------------------------------------------------- |
| 161 | // 0.1 userId function no longer reads X-Test-User |
| 162 | // --------------------------------------------------------------------------- |
| 163 | describe('canister userId function (no X-Test-User)', () => { |
| 164 | function userId(headers) { |
| 165 | const xUserId = headers['x-user-id']; |
| 166 | if (xUserId) return xUserId; |
| 167 | return 'default'; |
| 168 | } |
| 169 | |
| 170 | test('reads X-User-Id when present', () => { |
| 171 | assert.equal(userId({ 'x-user-id': 'google:123' }), 'google:123'); |
| 172 | }); |
| 173 | |
| 174 | test('falls back to default when X-User-Id is absent', () => { |
| 175 | assert.equal(userId({}), 'default'); |
| 176 | }); |
| 177 | |
| 178 | test('does NOT read X-Test-User', () => { |
| 179 | assert.equal(userId({ 'x-test-user': 'spoofed-user' }), 'default'); |
| 180 | }); |
| 181 | }); |
| 182 | |
| 183 | // --------------------------------------------------------------------------- |
| 184 | // 0.5 POST /api/v1/attest requires authentication |
| 185 | // --------------------------------------------------------------------------- |
| 186 | describe('POST /api/v1/attest auth requirement', () => { |
| 187 | test('getUserId returns null for missing Authorization header', () => { |
| 188 | function getUserId(authHeader) { |
| 189 | if (!authHeader || !authHeader.startsWith('Bearer ')) return null; |
| 190 | return 'user-sub'; |
| 191 | } |
| 192 | assert.equal(getUserId(undefined), null); |
| 193 | assert.equal(getUserId(''), null); |
| 194 | assert.equal(getUserId('Basic abc'), null); |
| 195 | }); |
| 196 | |
| 197 | test('getUserId returns sub for valid Bearer token', () => { |
| 198 | function getUserId(authHeader) { |
| 199 | if (!authHeader || !authHeader.startsWith('Bearer ')) return null; |
| 200 | return 'user-sub'; |
| 201 | } |
| 202 | assert.equal(getUserId('Bearer valid-token'), 'user-sub'); |
| 203 | }); |
| 204 | }); |
| 205 | |
| 206 | // --------------------------------------------------------------------------- |
| 207 | // 0.1 Migration preserves operator_export_secret during V6→V7 |
| 208 | // --------------------------------------------------------------------------- |
| 209 | describe('Migration V6 → V7 (gateway_auth_secret)', () => { |
| 210 | test('new StableStorage includes gateway_auth_secret field', () => { |
| 211 | const v6 = { |
| 212 | vaultEntries: [], |
| 213 | proposalEntries: [], |
| 214 | billingByUser: [], |
| 215 | operator_export_secret: 'keep-this', |
| 216 | }; |
| 217 | const v7 = { |
| 218 | ...v6, |
| 219 | gateway_auth_secret: '', |
| 220 | }; |
| 221 | assert.equal(v7.operator_export_secret, 'keep-this'); |
| 222 | assert.equal(v7.gateway_auth_secret, ''); |
| 223 | assert.deepEqual(v7.vaultEntries, []); |
| 224 | }); |
| 225 | }); |
| 226 | |
| 227 | // --------------------------------------------------------------------------- |
| 228 | // 0.2 CORS headers no longer expose X-Test-User |
| 229 | // --------------------------------------------------------------------------- |
| 230 | describe('canister CORS headers', () => { |
| 231 | test('allowed headers include X-Gateway-Auth, not X-Test-User', () => { |
| 232 | const allowedHeaders = 'Authorization, Content-Type, X-Vault-Id, X-User-Id, X-Gateway-Auth, X-Operator-Export-Key'; |
| 233 | assert.ok(allowedHeaders.includes('X-Gateway-Auth')); |
| 234 | assert.ok(!allowedHeaders.includes('X-Test-User')); |
| 235 | }); |
| 236 | }); |
| 237 | |
| 238 | // --------------------------------------------------------------------------- |
| 239 | // MCP hosted server passes canister auth to upstream |
| 240 | // --------------------------------------------------------------------------- |
| 241 | describe('mcp-hosted-server upstreamFetch auth headers', () => { |
| 242 | test('upstreamFetch includes X-Gateway-Auth and X-User-Id when provided', () => { |
| 243 | const opts = { |
| 244 | token: 'jwt-tok', |
| 245 | vaultId: 'default', |
| 246 | userId: 'google:123', |
| 247 | canisterAuthSecret: 'secret123', |
| 248 | }; |
| 249 | const headers = { 'Content-Type': 'application/json', Accept: 'application/json' }; |
| 250 | if (opts.token) headers['Authorization'] = `Bearer ${opts.token}`; |
| 251 | if (opts.vaultId) headers['X-Vault-Id'] = opts.vaultId; |
| 252 | if (opts.userId) headers['X-User-Id'] = opts.userId; |
| 253 | if (opts.canisterAuthSecret) headers['X-Gateway-Auth'] = opts.canisterAuthSecret; |
| 254 | |
| 255 | assert.equal(headers['X-User-Id'], 'google:123'); |
| 256 | assert.equal(headers['X-Gateway-Auth'], 'secret123'); |
| 257 | assert.equal(headers['Authorization'], 'Bearer jwt-tok'); |
| 258 | assert.equal(headers['X-Vault-Id'], 'default'); |
| 259 | }); |
| 260 | |
| 261 | test('upstreamFetch omits auth headers when not provided', () => { |
| 262 | const opts = { token: 'jwt', vaultId: 'v1' }; |
| 263 | const headers = { 'Content-Type': 'application/json', Accept: 'application/json' }; |
| 264 | if (opts.token) headers['Authorization'] = `Bearer ${opts.token}`; |
| 265 | if (opts.vaultId) headers['X-Vault-Id'] = opts.vaultId; |
| 266 | if (opts.userId) headers['X-User-Id'] = opts.userId; |
| 267 | if (opts.canisterAuthSecret) headers['X-Gateway-Auth'] = opts.canisterAuthSecret; |
| 268 | |
| 269 | assert.equal(headers['X-User-Id'], undefined); |
| 270 | assert.equal(headers['X-Gateway-Auth'], undefined); |
| 271 | }); |
| 272 | }); |
| 273 | |
| 274 | // --------------------------------------------------------------------------- |
| 275 | // metadata-bulk-canister readHeaders includes X-Gateway-Auth |
| 276 | // --------------------------------------------------------------------------- |
| 277 | describe('metadata-bulk-canister readHeaders with auth', () => { |
| 278 | test('readHeaders includes x-gateway-auth when secret is set', () => { |
| 279 | const CANISTER_AUTH_SECRET = 'bulk-secret'; |
| 280 | function readHeaders(uid, effective, vaultId) { |
| 281 | const h = { |
| 282 | Accept: 'application/json', |
| 283 | 'x-user-id': effective, |
| 284 | 'x-actor-id': uid, |
| 285 | 'x-vault-id': vaultId, |
| 286 | }; |
| 287 | if (CANISTER_AUTH_SECRET) h['x-gateway-auth'] = CANISTER_AUTH_SECRET; |
| 288 | return h; |
| 289 | } |
| 290 | const h = readHeaders('uid', 'eff', 'default'); |
| 291 | assert.equal(h['x-gateway-auth'], 'bulk-secret'); |
| 292 | assert.equal(h['x-user-id'], 'eff'); |
| 293 | }); |
| 294 | }); |
File History
2 commits
sha256:65ccb454656ea5acdea0a10e559b78bcde1eb6ff753ecc2911bc99d1c3d7cadd
feat(calendar): enforce agent context tiers in retrieval AP…
Human
minor
⚠
2 days ago
sha256:9103f98c89257ed2b01c237cea895dabb3e85ea337dccb1161c175e4422355b6
docs: accept Calendar Events v0 spec with Phase 0 security …
Human
2 days ago