@oxyhq/core 20.1.0 → 21.0.1
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/boot/sessionColdBoot.js +107 -8
- package/dist/cjs/i18n/locales/en-US.json +26 -4
- package/dist/cjs/i18n/locales/es-ES.json +26 -4
- package/dist/cjs/i18n/locales/locales/en-US.json +26 -4
- package/dist/cjs/i18n/locales/locales/es-ES.json +26 -4
- package/dist/cjs/index.js +57 -16
- package/dist/cjs/inference/OxyInferenceClient.js +330 -0
- package/dist/cjs/mixins/OxyServices.accounts.js +5 -72
- package/dist/cjs/mixins/OxyServices.auth.js +27 -3
- 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/index.js +5 -1
- package/dist/cjs/session/SessionClient.js +361 -1
- package/dist/cjs/session/accountDialogController.js +121 -147
- package/dist/cjs/session/accountSwitchTargets.js +75 -0
- package/dist/cjs/session/deviceDirectory.js +143 -0
- package/dist/cjs/session/deviceSwitcherRows.js +76 -0
- package/dist/cjs/session/projectSessionState.js +8 -1
- package/dist/cjs/session/sharedDeviceCredential.js +247 -0
- package/dist/esm/.tsbuildinfo +1 -1
- package/dist/esm/HttpService.js +47 -8
- package/dist/esm/boot/sessionColdBoot.js +107 -8
- package/dist/esm/i18n/locales/en-US.json +26 -4
- package/dist/esm/i18n/locales/es-ES.json +26 -4
- package/dist/esm/i18n/locales/locales/en-US.json +26 -4
- package/dist/esm/i18n/locales/locales/es-ES.json +26 -4
- package/dist/esm/index.js +36 -10
- package/dist/esm/inference/OxyInferenceClient.js +325 -0
- package/dist/esm/mixins/OxyServices.accounts.js +5 -72
- package/dist/esm/mixins/OxyServices.auth.js +27 -3
- 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/index.js +1 -1
- package/dist/esm/session/SessionClient.js +362 -2
- package/dist/esm/session/accountDialogController.js +121 -147
- package/dist/esm/session/accountSwitchTargets.js +71 -0
- package/dist/esm/session/deviceDirectory.js +135 -0
- package/dist/esm/session/deviceSwitcherRows.js +72 -0
- package/dist/esm/session/projectSessionState.js +8 -2
- package/dist/esm/session/sharedDeviceCredential.js +239 -0
- package/dist/types/.tsbuildinfo +1 -1
- package/dist/types/HttpService.d.ts +39 -1
- package/dist/types/boot/sessionColdBoot.d.ts +24 -4
- package/dist/types/index.d.ts +11 -4
- package/dist/types/inference/OxyInferenceClient.d.ts +324 -0
- package/dist/types/mixins/OxyServices.accounts.d.ts +73 -95
- package/dist/types/mixins/OxyServices.auth.d.ts +75 -3
- 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/models/session.d.ts +11 -0
- package/dist/types/server/auth.d.ts +80 -0
- package/dist/types/server/index.d.ts +2 -2
- package/dist/types/session/SessionClient.d.ts +202 -1
- package/dist/types/session/accountDialogController.d.ts +76 -64
- package/dist/types/session/accountSwitchTargets.d.ts +64 -0
- package/dist/types/session/deviceDirectory.d.ts +182 -0
- package/dist/types/session/deviceSwitcherRows.d.ts +92 -0
- package/dist/types/session/projectSessionState.d.ts +29 -0
- package/dist/types/session/sharedDeviceCredential.d.ts +202 -0
- package/package.json +3 -3
- package/src/HttpService.ts +50 -10
- package/src/__tests__/httpServiceUnwrapEnvelope.test.ts +115 -0
- package/src/boot/__tests__/sessionColdBoot.sharedDevice.test.ts +325 -0
- package/src/boot/sessionColdBoot.ts +133 -9
- package/src/i18n/locales/en-US.json +26 -4
- package/src/i18n/locales/es-ES.json +26 -4
- package/src/index.ts +94 -25
- 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.auth.ts +67 -5
- 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__/preSessionSkipAuth.test.ts +54 -1
- package/src/mixins/__tests__/serviceAuth.test.ts +2 -0
- package/src/mixins/index.ts +8 -0
- package/src/models/session.ts +11 -0
- package/src/server/__tests__/serviceTokenAttribution.test.ts +396 -0
- package/src/server/auth.ts +118 -0
- package/src/server/index.ts +6 -0
- package/src/session/SessionClient.ts +386 -1
- package/src/session/__tests__/SessionClient.directory.test.ts +688 -0
- package/src/session/__tests__/accountDialogController.test.ts +411 -278
- package/src/session/__tests__/accountDialogShape.test.ts +118 -0
- package/src/session/__tests__/accountSwitchTargets.test.ts +132 -0
- package/src/session/__tests__/deviceDirectory.test.ts +422 -0
- package/src/session/__tests__/deviceSwitcherRows.test.ts +223 -0
- package/src/session/__tests__/projectSessionState.test.ts +17 -0
- package/src/session/__tests__/sharedDeviceCredential.test.ts +300 -0
- package/src/session/accountDialogController.ts +141 -179
- package/src/session/accountSwitchTargets.ts +87 -0
- package/src/session/deviceDirectory.ts +269 -0
- package/src/session/deviceSwitcherRows.ts +145 -0
- package/src/session/projectSessionState.ts +9 -3
- package/src/session/sharedDeviceCredential.ts +349 -0
- package/dist/cjs/session/accountProjection.js +0 -213
- package/dist/esm/session/accountProjection.js +0 -207
- package/dist/types/session/accountProjection.d.ts +0 -198
- package/src/session/__tests__/accountProjection.test.ts +0 -447
- package/src/session/accountProjection.ts +0 -354
|
@@ -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/index.ts
CHANGED
|
@@ -18,7 +18,11 @@
|
|
|
18
18
|
export {
|
|
19
19
|
createOptionalOxyAuth,
|
|
20
20
|
createOxyAuthMiddleware,
|
|
21
|
+
getOxyBillingPrincipal,
|
|
22
|
+
getOxyDelegatedUserId,
|
|
23
|
+
getOxyRequestAttribution,
|
|
21
24
|
getOxyUserId,
|
|
25
|
+
getRequiredOxyBillingPrincipal,
|
|
22
26
|
getRequiredOxyUserId,
|
|
23
27
|
isOxyAuthenticated,
|
|
24
28
|
requireOxyAuth,
|
|
@@ -28,6 +32,8 @@ export type {
|
|
|
28
32
|
OxyAuthenticatedRequest,
|
|
29
33
|
OxyAuthMiddlewareOptions,
|
|
30
34
|
OxyAuthRequest,
|
|
35
|
+
OxyBillingPrincipal,
|
|
36
|
+
OxyRequestAttribution,
|
|
31
37
|
OxyRequestUser,
|
|
32
38
|
OxyServiceActingAsContext,
|
|
33
39
|
OxyServiceAppContext,
|