@oxyhq/core 21.0.0 → 21.0.2
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/dist/cjs/.tsbuildinfo +1 -1
- package/dist/cjs/HttpService.js +47 -8
- package/dist/cjs/i18n/locales/en-US.json +7 -2
- package/dist/cjs/i18n/locales/es-ES.json +7 -2
- package/dist/cjs/i18n/locales/locales/en-US.json +7 -2
- package/dist/cjs/i18n/locales/locales/es-ES.json +7 -2
- package/dist/cjs/index.js +8 -1
- package/dist/cjs/inference/OxyInferenceClient.js +330 -0
- package/dist/cjs/mixins/OxyServices.accounts.js +5 -72
- package/dist/cjs/mixins/OxyServices.inference.js +59 -0
- package/dist/cjs/mixins/OxyServices.utility.js +18 -6
- package/dist/cjs/mixins/index.js +6 -0
- package/dist/cjs/server/auth.js +76 -0
- package/dist/cjs/server/cors.js +84 -15
- package/dist/cjs/server/index.js +5 -1
- package/dist/esm/.tsbuildinfo +1 -1
- package/dist/esm/HttpService.js +47 -8
- package/dist/esm/i18n/locales/en-US.json +7 -2
- package/dist/esm/i18n/locales/es-ES.json +7 -2
- package/dist/esm/i18n/locales/locales/en-US.json +7 -2
- package/dist/esm/i18n/locales/locales/es-ES.json +7 -2
- package/dist/esm/index.js +4 -0
- package/dist/esm/inference/OxyInferenceClient.js +325 -0
- package/dist/esm/mixins/OxyServices.accounts.js +5 -72
- package/dist/esm/mixins/OxyServices.inference.js +56 -0
- package/dist/esm/mixins/OxyServices.utility.js +18 -6
- package/dist/esm/mixins/index.js +6 -0
- package/dist/esm/server/auth.js +72 -0
- package/dist/esm/server/cors.js +82 -15
- package/dist/esm/server/index.js +1 -1
- package/dist/types/.tsbuildinfo +1 -1
- package/dist/types/HttpService.d.ts +39 -1
- package/dist/types/index.d.ts +3 -1
- package/dist/types/inference/OxyInferenceClient.d.ts +324 -0
- package/dist/types/mixins/OxyServices.accounts.d.ts +73 -95
- package/dist/types/mixins/OxyServices.inference.d.ts +95 -0
- package/dist/types/mixins/OxyServices.utility.d.ts +44 -13
- package/dist/types/mixins/index.d.ts +2 -1
- package/dist/types/server/auth.d.ts +80 -0
- package/dist/types/server/cors.d.ts +41 -0
- package/dist/types/server/index.d.ts +2 -2
- package/package.json +2 -2
- package/src/HttpService.ts +50 -10
- package/src/__tests__/httpServiceUnwrapEnvelope.test.ts +115 -0
- package/src/i18n/locales/en-US.json +7 -2
- package/src/i18n/locales/es-ES.json +7 -2
- package/src/index.ts +19 -7
- package/src/inference/OxyInferenceClient.ts +590 -0
- package/src/inference/__tests__/OxyInferenceClient.test.ts +383 -0
- package/src/mixins/OxyServices.accounts.ts +75 -176
- package/src/mixins/OxyServices.inference.ts +57 -0
- package/src/mixins/OxyServices.utility.ts +58 -14
- package/src/mixins/__tests__/accounts.test.ts +57 -102
- package/src/mixins/__tests__/inferenceFactory.test.ts +58 -0
- package/src/mixins/__tests__/serviceAuth.test.ts +2 -0
- package/src/mixins/index.ts +8 -0
- package/src/server/__tests__/cors.socket.test.ts +225 -0
- package/src/server/__tests__/serviceTokenAttribution.test.ts +396 -0
- package/src/server/auth.ts +118 -0
- package/src/server/cors.ts +87 -12
- package/src/server/index.ts +6 -0
- package/src/session/__tests__/accountDialogShape.test.ts +118 -0
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical request attribution for service tokens (ADR 0007, issue #972 §2.2).
|
|
3
|
+
*
|
|
4
|
+
* Two claims are under test, and they are different claims:
|
|
5
|
+
*
|
|
6
|
+
* 1. A VERIFIED service token names the whole attribution tuple locally —
|
|
7
|
+
* application, credential, owning account, environment and effective
|
|
8
|
+
* scopes — so a verifier with no database can say who is responsible.
|
|
9
|
+
* 2. A delegated `X-Oxy-User-Id` can never become that responsible party. It
|
|
10
|
+
* is visible exactly where delegation is meant to be visible
|
|
11
|
+
* (`req.userId`, `getOxyDelegatedUserId`) and nowhere else.
|
|
12
|
+
*
|
|
13
|
+
* Everything runs through the REAL `oxy.auth()` middleware with a real HMAC
|
|
14
|
+
* signature, so the assertions are about the shipped lane rather than a
|
|
15
|
+
* hand-built request object. The one exception is deliberate and marked: the
|
|
16
|
+
* tampering cases plant fields on an already-authenticated request to prove the
|
|
17
|
+
* billing resolver does not read them.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import crypto from 'node:crypto';
|
|
21
|
+
import { OxyServices } from '../../OxyServices';
|
|
22
|
+
import {
|
|
23
|
+
getOxyBillingPrincipal,
|
|
24
|
+
getOxyDelegatedUserId,
|
|
25
|
+
getOxyRequestAttribution,
|
|
26
|
+
getRequiredOxyBillingPrincipal,
|
|
27
|
+
getRequiredOxyUserId,
|
|
28
|
+
} from '../auth';
|
|
29
|
+
import type { Request } from 'express';
|
|
30
|
+
|
|
31
|
+
const SERVICE_SECRET = 'attribution-suite-secret-not-production';
|
|
32
|
+
const OWNER_ACCOUNT = 'account-owning-the-application';
|
|
33
|
+
const DELEGATED_USER = 'end-user-the-service-acts-for';
|
|
34
|
+
|
|
35
|
+
interface Claims {
|
|
36
|
+
[key: string]: unknown;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const b64url = (input: Buffer | string): string =>
|
|
40
|
+
(typeof input === 'string' ? Buffer.from(input, 'utf8') : input)
|
|
41
|
+
.toString('base64')
|
|
42
|
+
.replace(/\+/g, '-')
|
|
43
|
+
.replace(/\//g, '_')
|
|
44
|
+
.replace(/=+$/, '');
|
|
45
|
+
|
|
46
|
+
/** Sign an HS256 JWT byte-identically to `POST /auth/service-token`. */
|
|
47
|
+
function signServiceToken(claims: Claims = {}, secret = SERVICE_SECRET): string {
|
|
48
|
+
const now = Math.floor(Date.now() / 1000);
|
|
49
|
+
const payload: Claims = {
|
|
50
|
+
iat: now,
|
|
51
|
+
exp: now + 3600,
|
|
52
|
+
type: 'service',
|
|
53
|
+
aud: 'oxy-api',
|
|
54
|
+
iss: 'oxy-auth',
|
|
55
|
+
appId: 'app-1',
|
|
56
|
+
appName: 'relay',
|
|
57
|
+
credentialId: 'cred-1',
|
|
58
|
+
ownerAccountId: OWNER_ACCOUNT,
|
|
59
|
+
environment: 'production',
|
|
60
|
+
scopes: ['inference:invoke'],
|
|
61
|
+
...claims,
|
|
62
|
+
};
|
|
63
|
+
const headerB64 = b64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
|
|
64
|
+
const payloadB64 = b64url(JSON.stringify(payload));
|
|
65
|
+
const signature = crypto
|
|
66
|
+
.createHmac('sha256', secret)
|
|
67
|
+
.update(`${headerB64}.${payloadB64}`)
|
|
68
|
+
.digest('base64')
|
|
69
|
+
.replace(/\+/g, '-')
|
|
70
|
+
.replace(/\//g, '_')
|
|
71
|
+
.replace(/=+$/, '');
|
|
72
|
+
return `${headerB64}.${payloadB64}.${signature}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface MockReq {
|
|
76
|
+
method: string;
|
|
77
|
+
path: string;
|
|
78
|
+
headers: Record<string, string>;
|
|
79
|
+
query: Record<string, string>;
|
|
80
|
+
userId?: string | null;
|
|
81
|
+
user?: unknown;
|
|
82
|
+
serviceApp?: unknown;
|
|
83
|
+
serviceActingAs?: unknown;
|
|
84
|
+
accessToken?: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
interface MockRes {
|
|
88
|
+
statusCode: number;
|
|
89
|
+
body: unknown;
|
|
90
|
+
headersSent: boolean;
|
|
91
|
+
status(code: number): MockRes;
|
|
92
|
+
json(body: unknown): MockRes;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const makeReq = (headers: Record<string, string> = {}): MockReq => ({
|
|
96
|
+
method: 'POST',
|
|
97
|
+
path: '/v1/responses',
|
|
98
|
+
headers,
|
|
99
|
+
query: {},
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
const makeRes = (): MockRes => ({
|
|
103
|
+
statusCode: 0,
|
|
104
|
+
body: undefined,
|
|
105
|
+
headersSent: false,
|
|
106
|
+
status(code: number) {
|
|
107
|
+
this.statusCode = code;
|
|
108
|
+
return this;
|
|
109
|
+
},
|
|
110
|
+
json(body: unknown) {
|
|
111
|
+
this.body = body;
|
|
112
|
+
this.headersSent = true;
|
|
113
|
+
return this;
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
/** Run `oxy.auth()` over a request and report what the middleware decided. */
|
|
118
|
+
async function authenticate(
|
|
119
|
+
oxy: OxyServices,
|
|
120
|
+
headers: Record<string, string>,
|
|
121
|
+
options: Parameters<OxyServices['auth']>[0] = { jwtSecret: SERVICE_SECRET },
|
|
122
|
+
): Promise<{ req: MockReq; res: MockRes; nextCalled: boolean }> {
|
|
123
|
+
const req = makeReq(headers);
|
|
124
|
+
const res = makeRes();
|
|
125
|
+
const next = jest.fn();
|
|
126
|
+
const middleware = oxy.auth(options);
|
|
127
|
+
await middleware(req as unknown as never, res as unknown as never, next as unknown as never);
|
|
128
|
+
return { req, res, nextCalled: next.mock.calls.length > 0 };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** `MockReq` is the structural subset the resolvers read; Express's own shape is irrelevant here. */
|
|
132
|
+
const asRequest = (req: MockReq): Request => req as unknown as Request;
|
|
133
|
+
|
|
134
|
+
let oxy: OxyServices;
|
|
135
|
+
|
|
136
|
+
beforeEach(() => {
|
|
137
|
+
oxy = new OxyServices({ baseURL: 'http://test.invalid' });
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
describe('a verified service token resolves the whole attribution tuple locally', () => {
|
|
141
|
+
it('names application, credential, owning account, environment and effective scopes', async () => {
|
|
142
|
+
const { req, nextCalled } = await authenticate(oxy, {
|
|
143
|
+
authorization: `Bearer ${signServiceToken()}`,
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
expect(nextCalled).toBe(true);
|
|
147
|
+
expect(getOxyBillingPrincipal(asRequest(req))).toEqual({
|
|
148
|
+
accountId: OWNER_ACCOUNT,
|
|
149
|
+
applicationId: 'app-1',
|
|
150
|
+
credentialId: 'cred-1',
|
|
151
|
+
environment: 'production',
|
|
152
|
+
scopes: ['inference:invoke'],
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('reports the effective scopes verbatim — nothing re-intersects them here', async () => {
|
|
157
|
+
// The mint already intersected credential ∩ application via the API's
|
|
158
|
+
// `intersectScopes`. If this side narrowed again it would be a second
|
|
159
|
+
// authority, and the two could disagree.
|
|
160
|
+
const token = signServiceToken({ scopes: ['inference:invoke', 'inference:models:read'] });
|
|
161
|
+
const { req } = await authenticate(oxy, { authorization: `Bearer ${token}` });
|
|
162
|
+
|
|
163
|
+
expect(getRequiredOxyBillingPrincipal(asRequest(req)).scopes).toEqual([
|
|
164
|
+
'inference:invoke',
|
|
165
|
+
'inference:models:read',
|
|
166
|
+
]);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it('has no principal at all for an unauthenticated request', () => {
|
|
170
|
+
expect(getOxyBillingPrincipal(asRequest(makeReq()))).toBeNull();
|
|
171
|
+
expect(() => getRequiredOxyBillingPrincipal(asRequest(makeReq()))).toThrow(
|
|
172
|
+
'no verified Oxy service principal',
|
|
173
|
+
);
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
describe('a delegated X-Oxy-User-Id is attribution, never the payer', () => {
|
|
178
|
+
it('leaves the billing account untouched while the delegated user stays visible', async () => {
|
|
179
|
+
jest
|
|
180
|
+
.spyOn(oxy, 'verifyServiceActingAs')
|
|
181
|
+
.mockResolvedValue({ authorized: true, scopes: ['user:read'] });
|
|
182
|
+
|
|
183
|
+
const { req, nextCalled } = await authenticate(oxy, {
|
|
184
|
+
authorization: `Bearer ${signServiceToken()}`,
|
|
185
|
+
'x-oxy-user-id': DELEGATED_USER,
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
expect(nextCalled).toBe(true);
|
|
189
|
+
|
|
190
|
+
// The assertion that matters: who pays does not move.
|
|
191
|
+
const principal = getRequiredOxyBillingPrincipal(asRequest(req));
|
|
192
|
+
expect(principal.accountId).toBe(OWNER_ACCOUNT);
|
|
193
|
+
expect(principal.accountId).not.toBe(DELEGATED_USER);
|
|
194
|
+
|
|
195
|
+
// The POSITIVE CONTROL. Without it, a resolver that simply returned a
|
|
196
|
+
// constant would pass the line above. The delegated id must be visible
|
|
197
|
+
// exactly where delegation is supposed to be visible.
|
|
198
|
+
expect(getOxyDelegatedUserId(asRequest(req))).toBe(DELEGATED_USER);
|
|
199
|
+
expect(getRequiredOxyUserId(asRequest(req))).toBe(DELEGATED_USER);
|
|
200
|
+
expect(getOxyRequestAttribution(asRequest(req))).toEqual({
|
|
201
|
+
accountId: OWNER_ACCOUNT,
|
|
202
|
+
applicationId: 'app-1',
|
|
203
|
+
credentialId: 'cred-1',
|
|
204
|
+
environment: 'production',
|
|
205
|
+
scopes: ['inference:invoke'],
|
|
206
|
+
delegatedUserId: DELEGATED_USER,
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
it('resolves the SAME billing account with and without delegation', async () => {
|
|
211
|
+
jest
|
|
212
|
+
.spyOn(oxy, 'verifyServiceActingAs')
|
|
213
|
+
.mockResolvedValue({ authorized: true, scopes: ['user:read'] });
|
|
214
|
+
|
|
215
|
+
const withDelegation = await authenticate(oxy, {
|
|
216
|
+
authorization: `Bearer ${signServiceToken()}`,
|
|
217
|
+
'x-oxy-user-id': DELEGATED_USER,
|
|
218
|
+
});
|
|
219
|
+
const withoutDelegation = await authenticate(oxy, {
|
|
220
|
+
authorization: `Bearer ${signServiceToken()}`,
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
// Restated as ADR 0007 states it: removing `userId` from a request must not
|
|
224
|
+
// change what any account is charged.
|
|
225
|
+
expect(getRequiredOxyBillingPrincipal(asRequest(withDelegation.req))).toEqual(
|
|
226
|
+
getRequiredOxyBillingPrincipal(asRequest(withoutDelegation.req)),
|
|
227
|
+
);
|
|
228
|
+
expect(getOxyDelegatedUserId(asRequest(withoutDelegation.req))).toBeNull();
|
|
229
|
+
expect(withoutDelegation.req.userId).toBeNull();
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
it('ignores a userId planted on an already-authenticated request', async () => {
|
|
233
|
+
const { req } = await authenticate(oxy, {
|
|
234
|
+
authorization: `Bearer ${signServiceToken()}`,
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
// Deliberate tampering AFTER authentication: this is the shape a downstream
|
|
238
|
+
// middleware bug takes. `getOxyBillingPrincipal` must read `serviceApp` and
|
|
239
|
+
// nothing else, so none of these can move the answer.
|
|
240
|
+
req.userId = DELEGATED_USER;
|
|
241
|
+
req.user = { id: DELEGATED_USER };
|
|
242
|
+
req.serviceActingAs = { userId: DELEGATED_USER, scopes: [] };
|
|
243
|
+
|
|
244
|
+
expect(getRequiredOxyBillingPrincipal(asRequest(req)).accountId).toBe(OWNER_ACCOUNT);
|
|
245
|
+
// Control: the planted fields ARE readable through the user-identity
|
|
246
|
+
// accessor, so the assertion above is about the resolver's inputs and not
|
|
247
|
+
// about the fields being unset.
|
|
248
|
+
expect(getRequiredOxyUserId(asRequest(req))).toBe(DELEGATED_USER);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('does not put the delegated user anywhere on the service principal', async () => {
|
|
252
|
+
jest
|
|
253
|
+
.spyOn(oxy, 'verifyServiceActingAs')
|
|
254
|
+
.mockResolvedValue({ authorized: true, scopes: ['user:read'] });
|
|
255
|
+
|
|
256
|
+
const { req } = await authenticate(oxy, {
|
|
257
|
+
authorization: `Bearer ${signServiceToken()}`,
|
|
258
|
+
'x-oxy-user-id': DELEGATED_USER,
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
// A field-name-agnostic sweep: no value of `req.serviceApp`, at any depth
|
|
262
|
+
// this object has, may equal the delegated id. A future field called
|
|
263
|
+
// `userId`/`subject`/`onBehalfOf` would fail here without anyone having to
|
|
264
|
+
// remember to extend the list above.
|
|
265
|
+
expect(JSON.stringify(req.serviceApp)).not.toContain(DELEGATED_USER);
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
describe('signature verification is mandatory before any claim is trusted', () => {
|
|
270
|
+
it('refuses a token signed with a different secret (401, no principal)', async () => {
|
|
271
|
+
const forged = signServiceToken({}, 'a-secret-the-issuer-never-used');
|
|
272
|
+
const { req, res, nextCalled } = await authenticate(oxy, {
|
|
273
|
+
authorization: `Bearer ${forged}`,
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
expect(nextCalled).toBe(false);
|
|
277
|
+
expect(res.statusCode).toBe(401);
|
|
278
|
+
expect(res.body).toMatchObject({ code: 'INVALID_SERVICE_TOKEN' });
|
|
279
|
+
expect(req.serviceApp).toBeUndefined();
|
|
280
|
+
expect(getOxyBillingPrincipal(asRequest(req))).toBeNull();
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
it('refuses a token whose payload was edited after signing', async () => {
|
|
284
|
+
// The attack the claim set invites: take a real token and rewrite
|
|
285
|
+
// `ownerAccountId` to somebody else's account. The signature covers the
|
|
286
|
+
// payload, so the edit must not survive.
|
|
287
|
+
const token = signServiceToken();
|
|
288
|
+
const [headerB64, , signatureB64] = token.split('.');
|
|
289
|
+
const tamperedPayload = b64url(
|
|
290
|
+
JSON.stringify({
|
|
291
|
+
iat: Math.floor(Date.now() / 1000),
|
|
292
|
+
exp: Math.floor(Date.now() / 1000) + 3600,
|
|
293
|
+
type: 'service',
|
|
294
|
+
aud: 'oxy-api',
|
|
295
|
+
iss: 'oxy-auth',
|
|
296
|
+
appId: 'app-1',
|
|
297
|
+
appName: 'relay',
|
|
298
|
+
credentialId: 'cred-1',
|
|
299
|
+
ownerAccountId: 'somebody-elses-account',
|
|
300
|
+
environment: 'production',
|
|
301
|
+
scopes: ['inference:invoke'],
|
|
302
|
+
}),
|
|
303
|
+
);
|
|
304
|
+
const { req, res, nextCalled } = await authenticate(oxy, {
|
|
305
|
+
authorization: `Bearer ${headerB64}.${tamperedPayload}.${signatureB64}`,
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
expect(nextCalled).toBe(false);
|
|
309
|
+
expect(res.statusCode).toBe(401);
|
|
310
|
+
expect(req.serviceApp).toBeUndefined();
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
it('refuses an UNSIGNED token (alg: none, empty signature segment)', async () => {
|
|
314
|
+
const headerB64 = b64url(JSON.stringify({ alg: 'none', typ: 'JWT' }));
|
|
315
|
+
const payloadB64 = b64url(
|
|
316
|
+
JSON.stringify({
|
|
317
|
+
type: 'service',
|
|
318
|
+
appId: 'app-1',
|
|
319
|
+
appName: 'relay',
|
|
320
|
+
credentialId: 'cred-1',
|
|
321
|
+
ownerAccountId: OWNER_ACCOUNT,
|
|
322
|
+
environment: 'production',
|
|
323
|
+
exp: Math.floor(Date.now() / 1000) + 3600,
|
|
324
|
+
aud: 'oxy-api',
|
|
325
|
+
iss: 'oxy-auth',
|
|
326
|
+
}),
|
|
327
|
+
);
|
|
328
|
+
const { req, res, nextCalled } = await authenticate(oxy, {
|
|
329
|
+
authorization: `Bearer ${headerB64}.${payloadB64}.`,
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
expect(nextCalled).toBe(false);
|
|
333
|
+
expect(res.statusCode).toBe(401);
|
|
334
|
+
expect(req.serviceApp).toBeUndefined();
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
it('refuses every service token when no verification secret is configured', async () => {
|
|
338
|
+
// The secure default: without a secret the middleware CANNOT verify, so it
|
|
339
|
+
// must not fall back to reading the decoded claims.
|
|
340
|
+
const { req, res, nextCalled } = await authenticate(
|
|
341
|
+
oxy,
|
|
342
|
+
{ authorization: `Bearer ${signServiceToken()}` },
|
|
343
|
+
{},
|
|
344
|
+
);
|
|
345
|
+
|
|
346
|
+
expect(nextCalled).toBe(false);
|
|
347
|
+
expect(res.statusCode).toBe(403);
|
|
348
|
+
expect(res.body).toMatchObject({ code: 'SERVICE_TOKEN_NOT_CONFIGURED' });
|
|
349
|
+
expect(req.serviceApp).toBeUndefined();
|
|
350
|
+
expect(getOxyBillingPrincipal(asRequest(req))).toBeNull();
|
|
351
|
+
});
|
|
352
|
+
|
|
353
|
+
it('attaches no principal on the OPTIONAL lane either', async () => {
|
|
354
|
+
// `optional: true` degrades to anonymous rather than 401 — the thing that
|
|
355
|
+
// must not happen is degrading to an UNVERIFIED principal.
|
|
356
|
+
const forged = signServiceToken({}, 'wrong-secret');
|
|
357
|
+
const { req, nextCalled } = await authenticate(
|
|
358
|
+
oxy,
|
|
359
|
+
{ authorization: `Bearer ${forged}` },
|
|
360
|
+
{ jwtSecret: SERVICE_SECRET, optional: true },
|
|
361
|
+
);
|
|
362
|
+
|
|
363
|
+
expect(nextCalled).toBe(true);
|
|
364
|
+
expect(req.serviceApp).toBeUndefined();
|
|
365
|
+
expect(req.userId).toBeNull();
|
|
366
|
+
expect(getOxyBillingPrincipal(asRequest(req))).toBeNull();
|
|
367
|
+
});
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
describe('the owning account is a required claim', () => {
|
|
371
|
+
it.each([
|
|
372
|
+
['absent', undefined],
|
|
373
|
+
['empty', ''],
|
|
374
|
+
['a number', 42],
|
|
375
|
+
['null', null],
|
|
376
|
+
])('refuses a signature-valid token whose ownerAccountId is %s', async (_label, value) => {
|
|
377
|
+
const token = signServiceToken({ ownerAccountId: value });
|
|
378
|
+
const { req, res, nextCalled } = await authenticate(oxy, {
|
|
379
|
+
authorization: `Bearer ${token}`,
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
expect(nextCalled).toBe(false);
|
|
383
|
+
expect(res.statusCode).toBe(401);
|
|
384
|
+
expect(res.body).toMatchObject({ code: 'INVALID_SERVICE_TOKEN' });
|
|
385
|
+
expect(getOxyBillingPrincipal(asRequest(req))).toBeNull();
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
it('accepts the same token once the claim is present — the control', async () => {
|
|
389
|
+
const { res, nextCalled } = await authenticate(oxy, {
|
|
390
|
+
authorization: `Bearer ${signServiceToken()}`,
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
expect(nextCalled).toBe(true);
|
|
394
|
+
expect(res.statusCode).toBe(0);
|
|
395
|
+
});
|
|
396
|
+
});
|
package/src/server/auth.ts
CHANGED
|
@@ -19,6 +19,12 @@ export interface OxyServiceAppContext {
|
|
|
19
19
|
appName: string;
|
|
20
20
|
scopes: string[];
|
|
21
21
|
credentialId: string;
|
|
22
|
+
/**
|
|
23
|
+
* The Oxy account that owns `appId` and is financially responsible for it.
|
|
24
|
+
* Read off the VERIFIED service-token claim set — never a user id, and never
|
|
25
|
+
* the delegated `X-Oxy-User-Id` (ADR 0007).
|
|
26
|
+
*/
|
|
27
|
+
ownerAccountId: string;
|
|
22
28
|
environment: OxyServiceEnvironment;
|
|
23
29
|
}
|
|
24
30
|
|
|
@@ -84,6 +90,118 @@ export function isOxyAuthenticated(req: Request): req is OxyAuthenticatedRequest
|
|
|
84
90
|
return getOxyUserId(req) !== null;
|
|
85
91
|
}
|
|
86
92
|
|
|
93
|
+
/**
|
|
94
|
+
* The principal a request is CHARGED to, and the identifiers a receipt needs.
|
|
95
|
+
*
|
|
96
|
+
* Every field is read from the verified service-token claim set. It is an
|
|
97
|
+
* OBJECT, not a string, and that is the point: `getOxyUserId` returns a
|
|
98
|
+
* `string | null`, so a delegated end-user id cannot be passed anywhere an
|
|
99
|
+
* `OxyBillingPrincipal` is expected. The confusion ADR 0007 forbids —
|
|
100
|
+
* attributing spend to the person a service is acting for rather than to the
|
|
101
|
+
* service's own account — stops being a code-review question and becomes a
|
|
102
|
+
* compile error.
|
|
103
|
+
*
|
|
104
|
+
* `scopes` are the effective scopes minted into the token (credential ∩
|
|
105
|
+
* application). Nothing re-intersects them here.
|
|
106
|
+
*/
|
|
107
|
+
export interface OxyBillingPrincipal {
|
|
108
|
+
/** `applications.owner_account_id` — the financially responsible account. */
|
|
109
|
+
readonly accountId: string;
|
|
110
|
+
readonly applicationId: string;
|
|
111
|
+
readonly credentialId: string;
|
|
112
|
+
readonly environment: OxyServiceEnvironment;
|
|
113
|
+
readonly scopes: readonly string[];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The full canonical attribution of ADR 0007 for a request: the billing
|
|
118
|
+
* principal PLUS the optional delegated end user.
|
|
119
|
+
*
|
|
120
|
+
* `delegatedUserId` is named for what it is. It answers "on whose behalf" and
|
|
121
|
+
* is absent for a machine credential acting for itself — its absence is normal,
|
|
122
|
+
* and nothing may synthesize one. If removing it would change what any account
|
|
123
|
+
* is charged, the code reading it is wrong.
|
|
124
|
+
*/
|
|
125
|
+
export interface OxyRequestAttribution extends OxyBillingPrincipal {
|
|
126
|
+
readonly delegatedUserId: string | null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The billing principal of a request, or `null` when the request carries no
|
|
131
|
+
* verified service principal (an ordinary user session is not a billable
|
|
132
|
+
* machine principal — its account is resolved from the account graph, not from
|
|
133
|
+
* a token claim).
|
|
134
|
+
*
|
|
135
|
+
* Reads `req.serviceApp` and NOTHING else: not `req.userId`, not `req.user`,
|
|
136
|
+
* not `req.serviceActingAs`. That exclusivity is the invariant this function
|
|
137
|
+
* exists to hold, and `serviceTokenAttribution.test.ts` mutation-tests it.
|
|
138
|
+
*
|
|
139
|
+
* **It answers for the SERVICE-TOKEN lane only.** The API's machine-credential
|
|
140
|
+
* lane (`oxy_sk_*`, issue #972 §2.3) resolves the same five facts into its own
|
|
141
|
+
* `req.machineCredential`, deliberately never `req.serviceApp` — populating the
|
|
142
|
+
* latter would hand a self-serve third-party credential the lane that only
|
|
143
|
+
* platform-trusted applications may enter. So a machine-credential request has
|
|
144
|
+
* no billing principal HERE and resolves `null`, which fails closed: the caller
|
|
145
|
+
* must handle it, and `getRequiredOxyBillingPrincipal` throws rather than
|
|
146
|
+
* charging anyone. One accessor answering for both lanes belongs to the public
|
|
147
|
+
* inference edge that has to admit both, and it needs the machine principal's
|
|
148
|
+
* shape to move into this package first.
|
|
149
|
+
*/
|
|
150
|
+
export function getOxyBillingPrincipal(req: Request): OxyBillingPrincipal | null {
|
|
151
|
+
const serviceApp = (req as OxyAuthRequest).serviceApp;
|
|
152
|
+
if (!serviceApp) {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
const accountId = normalizeId(serviceApp.ownerAccountId);
|
|
156
|
+
const applicationId = normalizeId(serviceApp.appId);
|
|
157
|
+
const credentialId = normalizeId(serviceApp.credentialId);
|
|
158
|
+
if (!accountId || !applicationId || !credentialId) {
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
accountId,
|
|
163
|
+
applicationId,
|
|
164
|
+
credentialId,
|
|
165
|
+
environment: serviceApp.environment,
|
|
166
|
+
scopes: serviceApp.scopes,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* {@link getOxyBillingPrincipal}, throwing when the request has none. Use on
|
|
172
|
+
* routes that have already required a service token.
|
|
173
|
+
*/
|
|
174
|
+
export function getRequiredOxyBillingPrincipal(req: Request): OxyBillingPrincipal {
|
|
175
|
+
const principal = getOxyBillingPrincipal(req);
|
|
176
|
+
if (!principal) {
|
|
177
|
+
throw new Error('Request has no verified Oxy service principal');
|
|
178
|
+
}
|
|
179
|
+
return principal;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The delegated end user of a service request, or `null`.
|
|
184
|
+
*
|
|
185
|
+
* Deliberately reads `req.serviceActingAs` — the grant-verified delegation —
|
|
186
|
+
* and not `req.userId`, which on a non-service request is the caller's own
|
|
187
|
+
* session identity and is not a delegation at all.
|
|
188
|
+
*/
|
|
189
|
+
export function getOxyDelegatedUserId(req: Request): string | null {
|
|
190
|
+
return normalizeId((req as OxyAuthRequest).serviceActingAs?.userId);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* The whole attribution tuple for a service request: who pays, which
|
|
195
|
+
* application and credential, and optionally on whose behalf.
|
|
196
|
+
*/
|
|
197
|
+
export function getOxyRequestAttribution(req: Request): OxyRequestAttribution | null {
|
|
198
|
+
const principal = getOxyBillingPrincipal(req);
|
|
199
|
+
if (!principal) {
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
return { ...principal, delegatedUserId: getOxyDelegatedUserId(req) };
|
|
203
|
+
}
|
|
204
|
+
|
|
87
205
|
export function getRequiredOxyUserId(req: Request): string {
|
|
88
206
|
const userId = getOxyUserId(req);
|
|
89
207
|
if (!userId) {
|
package/src/server/cors.ts
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* one-label subdomains such as `auth.oxy.so`, `api.oxy.so`,
|
|
16
16
|
* `accounts.oxy.so`, `console.oxy.so`, and `inbox.oxy.so`,
|
|
17
17
|
* - allows the caller's explicit `appOrigins`,
|
|
18
|
+
* - REFUSES the opaque origin on both sides (see `OPAQUE_ORIGIN`),
|
|
18
19
|
* - DENIES everything else (no reflection, never a wildcard with credentials),
|
|
19
20
|
* - echoes back the EXACT matched origin (so credentialed requests work) and
|
|
20
21
|
* sets `Vary: Origin` for correct caching,
|
|
@@ -24,8 +25,11 @@
|
|
|
24
25
|
*/
|
|
25
26
|
|
|
26
27
|
import type { NextFunction, Request, RequestHandler, Response } from 'express';
|
|
28
|
+
import { createLogger } from '../logger';
|
|
27
29
|
import { CENTRAL_IDP_APEX } from '../utils/authWebUrl';
|
|
28
30
|
|
|
31
|
+
const log = createLogger('OxyCors');
|
|
32
|
+
|
|
29
33
|
/** Default HTTP methods allowed across origins. */
|
|
30
34
|
const DEFAULT_ALLOWED_METHODS = ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'];
|
|
31
35
|
|
|
@@ -52,6 +56,11 @@ export interface OxyCorsOptions {
|
|
|
52
56
|
* `https://app.example.com`, `http://localhost:3000`). These are allowed IN
|
|
53
57
|
* ADDITION TO the built-in HTTPS Oxy apex origin family. Each is normalized
|
|
54
58
|
* via `new URL().origin`.
|
|
59
|
+
*
|
|
60
|
+
* An entry that is not a URL, or whose origin is the opaque origin
|
|
61
|
+
* (`exp://…`, `capacitor://…`, `chrome-extension://…`, `file:`, `data:`), is
|
|
62
|
+
* DROPPED with an error log rather than admitted — see `OPAQUE_ORIGIN` for
|
|
63
|
+
* why one such entry would otherwise admit every other one.
|
|
55
64
|
*/
|
|
56
65
|
appOrigins?: string[];
|
|
57
66
|
/**
|
|
@@ -94,6 +103,30 @@ function isOxyFamilyOrigin(candidate: string): boolean {
|
|
|
94
103
|
}
|
|
95
104
|
}
|
|
96
105
|
|
|
106
|
+
/**
|
|
107
|
+
* The URL standard's serialization of an OPAQUE origin: the literal string
|
|
108
|
+
* `"null"`, which `new URL(x).origin` returns for every scheme that has no
|
|
109
|
+
* origin to speak of — `exp:`, `capacitor:`, `chrome-extension:`,
|
|
110
|
+
* `vscode-webview:`, and also `file:`, `data:` and `about:`.
|
|
111
|
+
*
|
|
112
|
+
* This value is why an allowlist may never store it. Every such scheme
|
|
113
|
+
* normalizes to the SAME `"null"`, so a set built by normalization cannot tell
|
|
114
|
+
* them apart: ONE opaque entry admits ALL of them. With credentials on and the
|
|
115
|
+
* raw header echoed back, a single `myapp://` in `appOrigins` turned this
|
|
116
|
+
* helper into "allow any custom-scheme browsing context" — measured live, an
|
|
117
|
+
* `exp://localhost:8150` entry answered `Origin: vscode-webview://…` with
|
|
118
|
+
* `access-control-allow-origin: vscode-webview://…` and
|
|
119
|
+
* `access-control-allow-credentials: true`.
|
|
120
|
+
*
|
|
121
|
+
* There is deliberately no escape hatch that matches such an origin by raw
|
|
122
|
+
* string instead. Admitting a custom-scheme browsing context to a CREDENTIALED
|
|
123
|
+
* allowlist is a distinct decision with its own threat model, and it must not
|
|
124
|
+
* arrive as a side effect of someone adding one line to `appOrigins`. Note
|
|
125
|
+
* also that a native client is not subject to CORS at all — React Native sends
|
|
126
|
+
* no `Origin` header — so a mobile app never needs an entry here.
|
|
127
|
+
*/
|
|
128
|
+
const OPAQUE_ORIGIN = 'null';
|
|
129
|
+
|
|
97
130
|
/** Normalize a raw origin string to its canonical `scheme://host[:port]` form. */
|
|
98
131
|
function normalizeOrigin(raw: string): string | null {
|
|
99
132
|
try {
|
|
@@ -104,21 +137,63 @@ function normalizeOrigin(raw: string): string | null {
|
|
|
104
137
|
}
|
|
105
138
|
|
|
106
139
|
/**
|
|
107
|
-
*
|
|
108
|
-
*
|
|
140
|
+
* Normalize the configured `appOrigins` into the exact-match set — the
|
|
141
|
+
* CONFIGURE-SIDE half of the opaque-origin guard.
|
|
142
|
+
*
|
|
143
|
+
* An entry that is not a URL, or whose origin is opaque, is dropped and named
|
|
144
|
+
* in an error log. Dropped rather than thrown on because `appOrigins` is
|
|
145
|
+
* deployment configuration — at least one Oxy backend reads it from the
|
|
146
|
+
* environment — and a typo there must cost that one origin its CORS headers,
|
|
147
|
+
* never the whole service its boot. Both failure modes are equally SAFE (the
|
|
148
|
+
* entry is absent from the set either way), so the choice is purely about
|
|
149
|
+
* blast radius, and dropping keeps it to one origin whose requests then fail
|
|
150
|
+
* visibly in the browser.
|
|
151
|
+
*
|
|
152
|
+
* Exported for `__tests__/cors.socket.test.ts` and NOT re-exported from
|
|
153
|
+
* `server/index.ts`, so it is not part of the package's public surface. The
|
|
154
|
+
* two halves of the guard are separately exported because they are separately
|
|
155
|
+
* testable only that way: with this half in place the match-side half is
|
|
156
|
+
* unreachable through `createOxyCors`, so a test driving the public API alone
|
|
157
|
+
* would measure this function twice and the other one never.
|
|
109
158
|
*/
|
|
110
|
-
function
|
|
159
|
+
export function normalizeAppOrigins(appOrigins: string[]): Set<string> {
|
|
111
160
|
const explicit = new Set<string>();
|
|
112
161
|
for (const raw of appOrigins) {
|
|
113
162
|
const normalized = normalizeOrigin(raw);
|
|
114
|
-
if (normalized)
|
|
163
|
+
if (normalized === null) {
|
|
164
|
+
log.error('CORS allowlist entry ignored: it is not a URL', undefined, { entry: raw });
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
if (normalized === OPAQUE_ORIGIN) {
|
|
168
|
+
log.error('CORS allowlist entry ignored: it has no origin to match against', undefined, {
|
|
169
|
+
entry: raw,
|
|
170
|
+
});
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
explicit.add(normalized);
|
|
115
174
|
}
|
|
116
|
-
return
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
175
|
+
return explicit;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Whether `origin` may be echoed back: it is in the built-in HTTPS Oxy apex
|
|
180
|
+
* family, or it exactly matches one of the configured app origins.
|
|
181
|
+
*
|
|
182
|
+
* The opaque-origin refusal here is the MATCH-SIDE half of the guard, and it
|
|
183
|
+
* is what makes the property hold regardless of how `explicit` was built — a
|
|
184
|
+
* set that somehow contains `"null"` still matches nothing, because no
|
|
185
|
+
* incoming origin ever normalizes past this line. `normalizeAppOrigins` is
|
|
186
|
+
* what stops such a set existing today; this is what stops it mattering.
|
|
187
|
+
*
|
|
188
|
+
* Exported for the same reason as `normalizeAppOrigins`, and likewise absent
|
|
189
|
+
* from `server/index.ts`.
|
|
190
|
+
*/
|
|
191
|
+
export function matchesAllowedOrigin(explicit: ReadonlySet<string>, origin: string): boolean {
|
|
192
|
+
const normalized = normalizeOrigin(origin);
|
|
193
|
+
if (normalized === null) return false;
|
|
194
|
+
if (normalized === OPAQUE_ORIGIN) return false;
|
|
195
|
+
if (explicit.has(normalized)) return true;
|
|
196
|
+
return isOxyFamilyOrigin(normalized);
|
|
122
197
|
}
|
|
123
198
|
|
|
124
199
|
/**
|
|
@@ -139,7 +214,7 @@ export function createOxyCors(options: OxyCorsOptions = {}): RequestHandler {
|
|
|
139
214
|
maxAgeSeconds = DEFAULT_MAX_AGE_SECONDS,
|
|
140
215
|
} = options;
|
|
141
216
|
|
|
142
|
-
const
|
|
217
|
+
const explicitOrigins = normalizeAppOrigins(appOrigins);
|
|
143
218
|
const methodsHeader = methods.join(', ');
|
|
144
219
|
const allowedHeadersHeader = allowedHeaders.join(', ');
|
|
145
220
|
const exposedHeadersHeader = exposedHeaders.join(', ');
|
|
@@ -161,7 +236,7 @@ export function createOxyCors(options: OxyCorsOptions = {}): RequestHandler {
|
|
|
161
236
|
// Origin is present. Caching correctness: this response varies by Origin.
|
|
162
237
|
res.setHeader('Vary', 'Origin');
|
|
163
238
|
|
|
164
|
-
if (!
|
|
239
|
+
if (!matchesAllowedOrigin(explicitOrigins, origin)) {
|
|
165
240
|
// DENY: do NOT reflect the origin, do NOT emit a wildcard. The browser
|
|
166
241
|
// will block the cross-origin read. Preflights for denied origins get a
|
|
167
242
|
// 204 with no CORS headers (the actual request then fails CORS).
|