@udibo/oauth2 0.55.3 → 0.57.0
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/cli/idp/config.d.ts +27 -0
- package/dist/cli/idp/config.js +68 -0
- package/dist/cli/idp/pages.js +2 -1
- package/dist/cli/idp/server.d.ts +2 -1
- package/dist/cli/idp/server.js +101 -25
- package/dist/testing/contract/tenant.d.ts +8 -0
- package/dist/testing/contract/tenant.js +111 -0
- package/dist/testing/tenant.d.ts +11 -1
- package/dist/testing/tenant.js +29 -5
- package/package.json +1 -1
- package/skills/udibo-oauth2/SKILL.md +8 -8
package/dist/cli/idp/config.d.ts
CHANGED
|
@@ -38,6 +38,12 @@ export interface DevIdpClientConfig {
|
|
|
38
38
|
* on `127.0.0.1` or `[::1]` also matches the same URI on any port.
|
|
39
39
|
*/
|
|
40
40
|
redirectUris: string[];
|
|
41
|
+
/**
|
|
42
|
+
* Where the end-session endpoint may send the browser after a logout this
|
|
43
|
+
* client starts, matched as exact strings. Every entry of `redirectUris` is
|
|
44
|
+
* accepted as well, so list only the extra ones (a "signed out" page).
|
|
45
|
+
*/
|
|
46
|
+
postLogoutRedirectUris?: string[];
|
|
41
47
|
/** Grant types this client may use. */
|
|
42
48
|
grants: string[];
|
|
43
49
|
/**
|
|
@@ -70,6 +76,20 @@ export type DevIdpAccessTokenFormat = "opaque" | "jwt";
|
|
|
70
76
|
* `audience` it sets.
|
|
71
77
|
*/
|
|
72
78
|
export declare function jwtAudienceOf(client: DevIdpClientConfig): string | undefined;
|
|
79
|
+
/**
|
|
80
|
+
* Every URI the end-session endpoint accepts as this client's
|
|
81
|
+
* `post_logout_redirect_uri`: its `postLogoutRedirectUris`, then its
|
|
82
|
+
* `redirectUris`.
|
|
83
|
+
*/
|
|
84
|
+
export declare function postLogoutRedirectUrisOf(client: DevIdpClientConfig): string[];
|
|
85
|
+
/**
|
|
86
|
+
* The browser origins the provider answers CORS for: the `http(s)` origin of
|
|
87
|
+
* every client redirect URI and post-logout redirect URI, plus each
|
|
88
|
+
* `corsOrigins` entry that is itself a bare `http(s)` origin. Compare a
|
|
89
|
+
* request's `Origin` header to these as exact strings; `null` and `*` are
|
|
90
|
+
* never members.
|
|
91
|
+
*/
|
|
92
|
+
export declare function corsOriginsOf(config: DevIdpConfig): Set<string>;
|
|
73
93
|
/**
|
|
74
94
|
* A fully resolved configuration. Every field the server needs is present:
|
|
75
95
|
* {@link parseDevIdpConfig} fills the defaults so nothing downstream has to.
|
|
@@ -105,6 +125,13 @@ export interface DevIdpConfig {
|
|
|
105
125
|
users: DevIdpUserConfig[];
|
|
106
126
|
/** Clients to register. */
|
|
107
127
|
clients: DevIdpClientConfig[];
|
|
128
|
+
/**
|
|
129
|
+
* Browser origins allowed to call the discovery, token, revocation, UserInfo
|
|
130
|
+
* and JWKS endpoints cross-origin, beyond the origins of the clients'
|
|
131
|
+
* redirect URIs, which are always allowed. Each is a bare `http(s)` origin
|
|
132
|
+
* such as `http://localhost:4200`; the config parser refuses anything else.
|
|
133
|
+
*/
|
|
134
|
+
corsOrigins?: string[];
|
|
108
135
|
}
|
|
109
136
|
/**
|
|
110
137
|
* The configuration used when `idp dev` runs without `--config`: one
|
package/dist/cli/idp/config.js
CHANGED
|
@@ -16,6 +16,56 @@ export function jwtAudienceOf(client) {
|
|
|
16
16
|
return undefined;
|
|
17
17
|
return client.audience ?? client.id;
|
|
18
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* Every URI the end-session endpoint accepts as this client's
|
|
21
|
+
* `post_logout_redirect_uri`: its `postLogoutRedirectUris`, then its
|
|
22
|
+
* `redirectUris`.
|
|
23
|
+
*/
|
|
24
|
+
export function postLogoutRedirectUrisOf(client) {
|
|
25
|
+
return [
|
|
26
|
+
...new Set([
|
|
27
|
+
...(client.postLogoutRedirectUris ?? []),
|
|
28
|
+
...client.redirectUris,
|
|
29
|
+
]),
|
|
30
|
+
];
|
|
31
|
+
}
|
|
32
|
+
function webOriginOf(uri) {
|
|
33
|
+
let url;
|
|
34
|
+
try {
|
|
35
|
+
url = new URL(uri);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
return url.protocol === "http:" || url.protocol === "https:"
|
|
41
|
+
? url.origin
|
|
42
|
+
: undefined;
|
|
43
|
+
}
|
|
44
|
+
function isExactWebOrigin(entry) {
|
|
45
|
+
return !entry.includes("*") && webOriginOf(entry) === entry;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The browser origins the provider answers CORS for: the `http(s)` origin of
|
|
49
|
+
* every client redirect URI and post-logout redirect URI, plus each
|
|
50
|
+
* `corsOrigins` entry that is itself a bare `http(s)` origin. Compare a
|
|
51
|
+
* request's `Origin` header to these as exact strings; `null` and `*` are
|
|
52
|
+
* never members.
|
|
53
|
+
*/
|
|
54
|
+
export function corsOriginsOf(config) {
|
|
55
|
+
const origins = new Set();
|
|
56
|
+
for (const client of config.clients) {
|
|
57
|
+
for (const uri of postLogoutRedirectUrisOf(client)) {
|
|
58
|
+
const origin = webOriginOf(uri);
|
|
59
|
+
if (origin !== undefined)
|
|
60
|
+
origins.add(origin);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
for (const entry of config.corsOrigins ?? []) {
|
|
64
|
+
if (isExactWebOrigin(entry))
|
|
65
|
+
origins.add(entry);
|
|
66
|
+
}
|
|
67
|
+
return origins;
|
|
68
|
+
}
|
|
19
69
|
const DEFAULT_PORT = 9000;
|
|
20
70
|
const DEFAULT_HOSTNAME = "127.0.0.1";
|
|
21
71
|
const DEFAULT_ACCESS_TOKEN_LIFETIME = 3600;
|
|
@@ -43,12 +93,14 @@ const CONFIG_FIELDS = [
|
|
|
43
93
|
"signingKey",
|
|
44
94
|
"users",
|
|
45
95
|
"clients",
|
|
96
|
+
"corsOrigins",
|
|
46
97
|
];
|
|
47
98
|
const USER_FIELDS = ["id", "username", "password", "claims"];
|
|
48
99
|
const CLIENT_FIELDS = [
|
|
49
100
|
"id",
|
|
50
101
|
"secret",
|
|
51
102
|
"redirectUris",
|
|
103
|
+
"postLogoutRedirectUris",
|
|
52
104
|
"grants",
|
|
53
105
|
"ownerUserId",
|
|
54
106
|
"accessTokenFormat",
|
|
@@ -191,6 +243,11 @@ function parseClient(value, path) {
|
|
|
191
243
|
id,
|
|
192
244
|
secret: optionalString(source.secret, `${path}.secret`),
|
|
193
245
|
redirectUris,
|
|
246
|
+
...(source.postLogoutRedirectUris === undefined
|
|
247
|
+
? {}
|
|
248
|
+
: {
|
|
249
|
+
postLogoutRedirectUris: stringArray(source.postLogoutRedirectUris, `${path}.postLogoutRedirectUris`),
|
|
250
|
+
}),
|
|
194
251
|
grants,
|
|
195
252
|
ownerUserId: optionalString(source.ownerUserId, `${path}.ownerUserId`),
|
|
196
253
|
accessTokenFormat,
|
|
@@ -203,6 +260,14 @@ function parseAccessTokenFormat(value, path) {
|
|
|
203
260
|
}
|
|
204
261
|
return value;
|
|
205
262
|
}
|
|
263
|
+
function parseCorsOrigins(value, path) {
|
|
264
|
+
return stringArray(value, path).map((entry, index) => {
|
|
265
|
+
if (!isExactWebOrigin(entry)) {
|
|
266
|
+
fail(`${path}[${index}]`, 'must be an http(s) origin with no path or wildcard, such as "http://localhost:3000"');
|
|
267
|
+
}
|
|
268
|
+
return entry;
|
|
269
|
+
});
|
|
270
|
+
}
|
|
206
271
|
function parseConsent(value, path) {
|
|
207
272
|
const consent = string(value, path);
|
|
208
273
|
if (consent !== "auto" && consent !== "prompt") {
|
|
@@ -273,6 +338,9 @@ export function parseDevIdpConfig(value) {
|
|
|
273
338
|
: parseSigningKey(source.signingKey, "config.signingKey"),
|
|
274
339
|
users,
|
|
275
340
|
clients,
|
|
341
|
+
corsOrigins: source.corsOrigins === undefined
|
|
342
|
+
? []
|
|
343
|
+
: parseCorsOrigins(source.corsOrigins, "config.corsOrigins"),
|
|
276
344
|
};
|
|
277
345
|
}
|
|
278
346
|
/**
|
package/dist/cli/idp/pages.js
CHANGED
|
@@ -157,7 +157,8 @@ export function statusPage(options) {
|
|
|
157
157
|
<span class="mono">/revoke</span>,
|
|
158
158
|
<span class="mono">/introspect</span></li>
|
|
159
159
|
<li><span class="mono">/login</span>,
|
|
160
|
-
<span class="mono">/
|
|
160
|
+
<span class="mono">/end_session</span>
|
|
161
|
+
(also served at <span class="mono">/logout</span>)</li>
|
|
161
162
|
</ul>
|
|
162
163
|
<h2>Users</h2>
|
|
163
164
|
<ul>
|
package/dist/cli/idp/server.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The development identity provider itself: a real {@link AuthorizationServer}
|
|
3
3
|
* over the in-memory services, served on a socket with a sign-in page, an
|
|
4
|
-
* optional consent screen,
|
|
4
|
+
* optional consent screen, RP-initiated logout, CORS for the configured
|
|
5
|
+
* clients' origins, and a test-control surface under `/__admin/`.
|
|
5
6
|
*
|
|
6
7
|
* Everything here is packaging — the protocol behavior is the same code an
|
|
7
8
|
* application runs in production. What makes it a development tool is the
|
package/dist/cli/idp/server.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The development identity provider itself: a real {@link AuthorizationServer}
|
|
3
3
|
* over the in-memory services, served on a socket with a sign-in page, an
|
|
4
|
-
* optional consent screen,
|
|
4
|
+
* optional consent screen, RP-initiated logout, CORS for the configured
|
|
5
|
+
* clients' origins, and a test-control surface under `/__admin/`.
|
|
5
6
|
*
|
|
6
7
|
* Everything here is packaging — the protocol behavior is the same code an
|
|
7
8
|
* application runs in production. What makes it a development tool is the
|
|
@@ -22,13 +23,13 @@ import { ClientCredentialsGrant } from "../../server/grants/client-credentials.j
|
|
|
22
23
|
import { PasswordGrant } from "../../server/grants/password.js";
|
|
23
24
|
import { RefreshTokenGrant } from "../../server/grants/refresh-token.js";
|
|
24
25
|
import { satisfiesAuthenticationRequest } from "../../server/authentication-request.js";
|
|
25
|
-
import { createJwtAccessTokenGenerator, StaticSigningKeyProvider, } from "../../server/signing-keys.js";
|
|
26
|
+
import { createJwtAccessTokenGenerator, StaticSigningKeyProvider, verifyJwt, } from "../../server/signing-keys.js";
|
|
26
27
|
import { generateCodeChallenge, generateCodeVerifier, generateState, } from "../../utils/pkce.js";
|
|
27
28
|
import { DEFAULT_MAX_BODY_BYTES, readBoundedBody } from "../../utils/_body.js";
|
|
28
29
|
import { timingSafeEqualString } from "../../utils/crypto.js";
|
|
29
30
|
import { safeReturnTo } from "../../utils/url.js";
|
|
30
31
|
import { MemoryAuthorizationCodeService, MemoryClientService, MemoryTokenService, MemoryUserService, } from "../../testing/services.js";
|
|
31
|
-
import { jwtAudienceOf } from "./config.js";
|
|
32
|
+
import { corsOriginsOf, jwtAudienceOf, postLogoutRedirectUrisOf, } from "./config.js";
|
|
32
33
|
import { consentPage, htmlResponse, loginPage, messagePage, statusPage, } from "./pages.js";
|
|
33
34
|
const SESSION_COOKIE = "dev_idp_session";
|
|
34
35
|
const CONSENT_COOKIE = "dev_idp_consent";
|
|
@@ -90,6 +91,7 @@ async function createState(config, signingKey, issuer) {
|
|
|
90
91
|
const clientService = new MemoryClientService(userService);
|
|
91
92
|
const authorizationCodeService = new MemoryAuthorizationCodeService({ clientService, userService });
|
|
92
93
|
const signingKeys = new StaticSigningKeyProvider(signingKey);
|
|
94
|
+
const sessions = new Map();
|
|
93
95
|
const tokenService = new DevIdpTokenService({
|
|
94
96
|
clientService,
|
|
95
97
|
userService,
|
|
@@ -134,6 +136,14 @@ async function createState(config, signingKey, issuer) {
|
|
|
134
136
|
preferred_username: user.username,
|
|
135
137
|
...user.claims,
|
|
136
138
|
}),
|
|
139
|
+
endSession: ({ request }) => {
|
|
140
|
+
const sessionId = readCookie(request, SESSION_COOKIE);
|
|
141
|
+
if (sessionId)
|
|
142
|
+
sessions.delete(sessionId);
|
|
143
|
+
return {
|
|
144
|
+
headers: { "set-cookie": cookie(SESSION_COOKIE, "", { maxAge: 0 }) },
|
|
145
|
+
};
|
|
146
|
+
},
|
|
137
147
|
});
|
|
138
148
|
const secrets = new Map();
|
|
139
149
|
for (const user of config.users) {
|
|
@@ -148,6 +158,7 @@ async function createState(config, signingKey, issuer) {
|
|
|
148
158
|
id: client.id,
|
|
149
159
|
grants: client.grants,
|
|
150
160
|
redirectUris: client.redirectUris,
|
|
161
|
+
postLogoutRedirectUris: postLogoutRedirectUrisOf(client),
|
|
151
162
|
}, client.secret, client.ownerUserId);
|
|
152
163
|
if (client.secret)
|
|
153
164
|
secrets.set(client.id, client.secret);
|
|
@@ -156,7 +167,7 @@ async function createState(config, signingKey, issuer) {
|
|
|
156
167
|
server,
|
|
157
168
|
userService,
|
|
158
169
|
clientService,
|
|
159
|
-
sessions
|
|
170
|
+
sessions,
|
|
160
171
|
consents: new Map(),
|
|
161
172
|
secrets,
|
|
162
173
|
};
|
|
@@ -217,6 +228,32 @@ function rejectUnauthorizedAdmin(request, adminToken) {
|
|
|
217
228
|
}
|
|
218
229
|
return undefined;
|
|
219
230
|
}
|
|
231
|
+
const CORS_PATHS = new Set([
|
|
232
|
+
"/.well-known/openid-configuration",
|
|
233
|
+
"/.well-known/oauth-authorization-server",
|
|
234
|
+
"/token",
|
|
235
|
+
"/revoke",
|
|
236
|
+
"/userinfo",
|
|
237
|
+
"/jwks",
|
|
238
|
+
]);
|
|
239
|
+
const CORS_PREFLIGHT_MAX_AGE = 600;
|
|
240
|
+
function varyOnOrigin(headers) {
|
|
241
|
+
headers.append("vary", "Origin");
|
|
242
|
+
}
|
|
243
|
+
function answerPreflight(origin, allowed) {
|
|
244
|
+
const headers = new Headers({ "cache-control": "no-store" });
|
|
245
|
+
varyOnOrigin(headers);
|
|
246
|
+
if (!allowed) {
|
|
247
|
+
return Response.json({
|
|
248
|
+
error: `origin ${origin} is not allowed; register a redirect URI on it or list it in "corsOrigins"`,
|
|
249
|
+
}, { status: 403, headers });
|
|
250
|
+
}
|
|
251
|
+
headers.set("access-control-allow-origin", origin);
|
|
252
|
+
headers.set("access-control-allow-methods", "GET, POST");
|
|
253
|
+
headers.set("access-control-allow-headers", "authorization, content-type");
|
|
254
|
+
headers.set("access-control-max-age", String(CORS_PREFLIGHT_MAX_AGE));
|
|
255
|
+
return new Response(null, { status: 204, headers });
|
|
256
|
+
}
|
|
220
257
|
function pathAndQuery(request) {
|
|
221
258
|
const { pathname, search } = new URL(request.url);
|
|
222
259
|
return `${pathname}${search}`;
|
|
@@ -342,27 +379,47 @@ async function handleConsentSubmission(state, request) {
|
|
|
342
379
|
}),
|
|
343
380
|
});
|
|
344
381
|
}
|
|
345
|
-
function
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
if (
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
return new Response(messagePage("Signed out", "The session was dropped."), {
|
|
359
|
-
status: 200,
|
|
360
|
-
headers: {
|
|
361
|
-
"content-type": "text/html; charset=utf-8",
|
|
362
|
-
"cache-control": "no-store",
|
|
363
|
-
"set-cookie": expired,
|
|
364
|
-
},
|
|
382
|
+
async function endSessionParameters(request) {
|
|
383
|
+
if (request.method !== "POST")
|
|
384
|
+
return new URL(request.url).searchParams;
|
|
385
|
+
return new URLSearchParams(new TextDecoder().decode(await readBody(request)));
|
|
386
|
+
}
|
|
387
|
+
async function namesClient(params, signingKey) {
|
|
388
|
+
if (params.get("client_id"))
|
|
389
|
+
return true;
|
|
390
|
+
const hint = params.get("id_token_hint");
|
|
391
|
+
if (!hint)
|
|
392
|
+
return false;
|
|
393
|
+
const claims = await verifyJwt(hint, signingKey.publicJwk, {
|
|
394
|
+
ignoreExpiration: true,
|
|
365
395
|
});
|
|
396
|
+
return claims !== undefined;
|
|
397
|
+
}
|
|
398
|
+
async function handleEndSession(state, config, signingKey, request) {
|
|
399
|
+
const params = await endSessionParameters(request);
|
|
400
|
+
const requested = params.get("post_logout_redirect_uri");
|
|
401
|
+
if (requested && !(await namesClient(params, signingKey))) {
|
|
402
|
+
const registrant = config.clients.find((client) => postLogoutRedirectUrisOf(client).includes(requested));
|
|
403
|
+
if (registrant)
|
|
404
|
+
params.set("client_id", registrant.id);
|
|
405
|
+
}
|
|
406
|
+
const url = new URL(request.url);
|
|
407
|
+
url.search = params.toString();
|
|
408
|
+
const response = await state.server.handleEndSessionRequest(new Request(url, { headers: request.headers }));
|
|
409
|
+
if (response.status === 302) {
|
|
410
|
+
return new Response(null, { status: 303, headers: response.headers });
|
|
411
|
+
}
|
|
412
|
+
if (response.status !== 204)
|
|
413
|
+
return response;
|
|
414
|
+
const headers = new Headers(response.headers);
|
|
415
|
+
headers.set("content-type", "text/html; charset=utf-8");
|
|
416
|
+
headers.set("cache-control", "no-store");
|
|
417
|
+
return requested
|
|
418
|
+
? new Response(messagePage("Invalid logout request", "The session was dropped, but post_logout_redirect_uri must exactly match a redirect URI or post-logout redirect URI registered by the client the request names, or by any configured client when it names none."), { status: 400, headers })
|
|
419
|
+
: new Response(messagePage("Signed out", "The session was dropped."), {
|
|
420
|
+
status: 200,
|
|
421
|
+
headers,
|
|
422
|
+
});
|
|
366
423
|
}
|
|
367
424
|
async function readJsonBody(request) {
|
|
368
425
|
const text = new TextDecoder().decode(await readBody(request));
|
|
@@ -527,8 +584,26 @@ export async function startDevIdentityProvider(options) {
|
|
|
527
584
|
const adminToken = options.adminToken ?? crypto.randomUUID();
|
|
528
585
|
const issuer = { value: config.issuer ?? "" };
|
|
529
586
|
let state = await createState(config, signingKey, issuer);
|
|
587
|
+
const corsOrigins = corsOriginsOf(config);
|
|
530
588
|
const handler = async (request) => {
|
|
531
589
|
const { pathname } = new URL(request.url);
|
|
590
|
+
if (!CORS_PATHS.has(pathname))
|
|
591
|
+
return await route(request, pathname);
|
|
592
|
+
const origin = request.headers.get("origin");
|
|
593
|
+
const allowed = origin !== null && corsOrigins.has(origin);
|
|
594
|
+
if (origin !== null &&
|
|
595
|
+
request.method === "OPTIONS" &&
|
|
596
|
+
request.headers.has("access-control-request-method")) {
|
|
597
|
+
return answerPreflight(origin, allowed);
|
|
598
|
+
}
|
|
599
|
+
const routed = await route(request, pathname);
|
|
600
|
+
const response = new Response(routed.body, routed);
|
|
601
|
+
varyOnOrigin(response.headers);
|
|
602
|
+
if (allowed)
|
|
603
|
+
response.headers.set("access-control-allow-origin", origin);
|
|
604
|
+
return response;
|
|
605
|
+
};
|
|
606
|
+
const route = async (request, pathname) => {
|
|
532
607
|
const { method } = request;
|
|
533
608
|
if (pathname.startsWith("/__admin/")) {
|
|
534
609
|
const rejected = rejectUnauthorizedAdmin(request, adminToken);
|
|
@@ -573,8 +648,9 @@ export async function startDevIdentityProvider(options) {
|
|
|
573
648
|
if (method !== "POST")
|
|
574
649
|
return jsonError(405, "method must be POST");
|
|
575
650
|
return await handleConsentSubmission(state, request);
|
|
651
|
+
case "/end_session":
|
|
576
652
|
case "/logout":
|
|
577
|
-
return
|
|
653
|
+
return await handleEndSession(state, config, signingKey, request);
|
|
578
654
|
case "/__admin/reset":
|
|
579
655
|
if (method !== "POST")
|
|
580
656
|
return jsonError(405, "method must be POST");
|
|
@@ -80,6 +80,14 @@ export interface TenantContractFixture {
|
|
|
80
80
|
* returns its id.
|
|
81
81
|
*/
|
|
82
82
|
addRole(permissions: string[]): Promise<string>;
|
|
83
|
+
/**
|
|
84
|
+
* Removes a permission key from the tenant's registry, as an administrator
|
|
85
|
+
* deleting it does: every role keeps carrying the key, but no role confers
|
|
86
|
+
* it or is listed for it any more. The suite deregisters only keys it
|
|
87
|
+
* named for this purpose. Leave it out and the checks that need it are
|
|
88
|
+
* skipped.
|
|
89
|
+
*/
|
|
90
|
+
deregisterPermission?(key: string): Promise<void>;
|
|
83
91
|
/**
|
|
84
92
|
* Grants `permissions` on one instance of a resource type to a person, or
|
|
85
93
|
* to every member of an organization. Registers the type if it is new.
|
|
@@ -680,6 +680,117 @@ export function runTenantContractTests(options) {
|
|
|
680
680
|
const reply = await call(null, "GET", "/api/organizations");
|
|
681
681
|
expect(reply.status).toStrictEqual(401);
|
|
682
682
|
});
|
|
683
|
+
describe("member-roles narrowed to a product's permission keys", () => {
|
|
684
|
+
const run = crypto.randomUUID().slice(0, 8);
|
|
685
|
+
const projectsRead = `contract-projects-${run}:read`;
|
|
686
|
+
const projectsWrite = `contract-projects-${run}:write`;
|
|
687
|
+
const reportsEdit = `contract-reports-${run}:edit`;
|
|
688
|
+
const archiveRead = `contract-archive-${run}:read`;
|
|
689
|
+
const archiveWrite = `contract-archive-${run}:write`;
|
|
690
|
+
const roles = {
|
|
691
|
+
projectLead: "",
|
|
692
|
+
reportEditor: "",
|
|
693
|
+
portalOwner: "",
|
|
694
|
+
archivist: "",
|
|
695
|
+
};
|
|
696
|
+
beforeAll(async () => {
|
|
697
|
+
roles.projectLead = await tenant.addRole([
|
|
698
|
+
projectsRead,
|
|
699
|
+
projectsWrite,
|
|
700
|
+
]);
|
|
701
|
+
roles.reportEditor = await tenant.addRole([reportsEdit]);
|
|
702
|
+
roles.portalOwner = await tenant.addRole([projectsRead, reportsEdit]);
|
|
703
|
+
roles.archivist = await tenant.addRole([archiveRead, archiveWrite]);
|
|
704
|
+
});
|
|
705
|
+
function memberRoles(query, accessToken = seats.admin.token) {
|
|
706
|
+
return call(accessToken, "GET", `/api/organizations/${organization.id}/member-roles${query}`);
|
|
707
|
+
}
|
|
708
|
+
const naming = (keys) => `?${new URLSearchParams(keys.map((key) => ["permission", key]))}`;
|
|
709
|
+
async function offered(query) {
|
|
710
|
+
const reply = await memberRoles(query);
|
|
711
|
+
expect(reply.status, JSON.stringify(reply.body)).toStrictEqual(200);
|
|
712
|
+
for (const slug of ["owner", "admin", "member"]) {
|
|
713
|
+
const tier = reply.body.find((entry) => entry.slug === slug);
|
|
714
|
+
assert(tier, `the built-in ${slug} tier is listed for ${query}`);
|
|
715
|
+
expect("id" in tier).toBeFalsy();
|
|
716
|
+
}
|
|
717
|
+
const ours = new Set(Object.values(roles));
|
|
718
|
+
return reply.body
|
|
719
|
+
.flatMap((entry) => (entry.id === undefined ? [] : [entry.id]))
|
|
720
|
+
.filter((id) => ours.has(id))
|
|
721
|
+
.sort();
|
|
722
|
+
}
|
|
723
|
+
const sorted = (...ids) => [...ids].sort();
|
|
724
|
+
const emptyKeyRefusal = {
|
|
725
|
+
permission: "Name a permission key in every permission parameter",
|
|
726
|
+
};
|
|
727
|
+
const tooManyKeysRefusal = {
|
|
728
|
+
permission: "Name at most 500 permission keys, as many as a tenant may register",
|
|
729
|
+
};
|
|
730
|
+
function refusal(reply) {
|
|
731
|
+
expect(reply.status, JSON.stringify(reply.body)).toStrictEqual(400);
|
|
732
|
+
const { fieldErrors } = reply.body;
|
|
733
|
+
return fieldErrors ?? {};
|
|
734
|
+
}
|
|
735
|
+
it("lists every tenant-wide role when no permission key is named", async () => {
|
|
736
|
+
expect(await offered("")).toStrictEqual(sorted(...Object.values(roles)));
|
|
737
|
+
});
|
|
738
|
+
it("offers each product on a shared tenant only the roles conferring one of its keys, and a mixed role to both", async () => {
|
|
739
|
+
expect(await offered(naming([projectsRead, projectsWrite]))).toStrictEqual(sorted(roles.projectLead, roles.portalOwner));
|
|
740
|
+
expect(await offered(naming([projectsWrite]))).toStrictEqual([
|
|
741
|
+
roles.projectLead,
|
|
742
|
+
]);
|
|
743
|
+
expect(await offered(naming([reportsEdit]))).toStrictEqual(sorted(roles.reportEditor, roles.portalOwner));
|
|
744
|
+
});
|
|
745
|
+
it("matches nothing for a key nobody registered or a comma-joined value, without refusing the read", async () => {
|
|
746
|
+
expect(await offered(naming([`contract-unknown-${run}:read`]))).toStrictEqual([]);
|
|
747
|
+
expect(await offered(naming([`${projectsRead},${reportsEdit}`]))).toStrictEqual([]);
|
|
748
|
+
});
|
|
749
|
+
it("stops matching a role on a key the tenant deregistered, while its live keys still match it", async ({ skip, }) => {
|
|
750
|
+
if (!tenant.deregisterPermission) {
|
|
751
|
+
skip("the fixture cannot deregister a permission key");
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
expect(await offered(naming([archiveRead]))).toStrictEqual([
|
|
755
|
+
roles.archivist,
|
|
756
|
+
]);
|
|
757
|
+
await tenant.deregisterPermission(archiveRead);
|
|
758
|
+
expect(await offered(naming([archiveRead]))).toStrictEqual([]);
|
|
759
|
+
expect(await offered(naming([archiveWrite]))).toStrictEqual([
|
|
760
|
+
roles.archivist,
|
|
761
|
+
]);
|
|
762
|
+
expect(await offered(""), "the unfiltered list still names the role").toContain(roles.archivist);
|
|
763
|
+
});
|
|
764
|
+
it("refuses an empty key, bare or beside a named one, rather than reading it as no filter", async () => {
|
|
765
|
+
for (const query of [
|
|
766
|
+
"?permission=",
|
|
767
|
+
"?permission",
|
|
768
|
+
`?permission=${encodeURIComponent(projectsRead)}&permission=`,
|
|
769
|
+
]) {
|
|
770
|
+
expect(refusal(await memberRoles(query)), query).toStrictEqual(emptyKeyRefusal);
|
|
771
|
+
}
|
|
772
|
+
});
|
|
773
|
+
it("refuses more keys than a tenant may register, and accepts exactly that many", async () => {
|
|
774
|
+
const keys = Array.from({ length: 501 }, (_, index) => `k${index}`);
|
|
775
|
+
expect(refusal(await memberRoles(naming(keys)))).toStrictEqual(tooManyKeysRefusal);
|
|
776
|
+
expect(refusal(await memberRoles(naming(["", ...keys.slice(1)]))), "the key count is checked before an empty key").toStrictEqual(tooManyKeysRefusal);
|
|
777
|
+
expect(await offered(naming(keys.slice(0, 500)))).toStrictEqual([]);
|
|
778
|
+
});
|
|
779
|
+
it("refuses a plain member with the same 404 before looking at the keys", async () => {
|
|
780
|
+
const unfiltered = await memberRoles("", seats.member.token);
|
|
781
|
+
expect(unfiltered.status).toStrictEqual(404);
|
|
782
|
+
const tooMany = Array.from({ length: 501 }, (_, index) => `k${index}`);
|
|
783
|
+
for (const query of [
|
|
784
|
+
naming([projectsRead]),
|
|
785
|
+
"?permission=",
|
|
786
|
+
naming(tooMany),
|
|
787
|
+
]) {
|
|
788
|
+
const refused = await memberRoles(query, seats.member.token);
|
|
789
|
+
expect(refused.status, query).toStrictEqual(404);
|
|
790
|
+
expect(refused.body, query).toStrictEqual(unfiltered.body);
|
|
791
|
+
}
|
|
792
|
+
});
|
|
793
|
+
});
|
|
683
794
|
describe("application roles a manager grants a member", () => {
|
|
684
795
|
const APP_PERMISSION = "contract:app";
|
|
685
796
|
let roleId;
|
package/dist/testing/tenant.d.ts
CHANGED
|
@@ -266,9 +266,19 @@ export interface FakeTenant {
|
|
|
266
266
|
* offer it, `member-roles` lists it, and an organization's manager may grant
|
|
267
267
|
* it to a member. Returns its id. Defining a slug again changes its name
|
|
268
268
|
* and permissions and keeps its id. Throws on a built-in slug, on an id
|
|
269
|
-
* another role holds,
|
|
269
|
+
* another role holds, on a new id for a slug already defined, and on a key
|
|
270
|
+
* {@linkcode deregisterPermission} removed.
|
|
270
271
|
*/
|
|
271
272
|
defineOrganizationRole(role: FakeTenantOrganizationRole): string;
|
|
273
|
+
/**
|
|
274
|
+
* Removes a permission key from the tenant's registry, as an administrator
|
|
275
|
+
* deleting it does. Every role, person, membership and grant naming the key
|
|
276
|
+
* keeps it but confers it no more, and `member-roles` no longer lists a role
|
|
277
|
+
* for it under `?permission=`. The other keys a role carries still count.
|
|
278
|
+
* Re-registering a key is not modelled: the removal lasts for the fake's
|
|
279
|
+
* life, so name a key you deregister nowhere afterwards.
|
|
280
|
+
*/
|
|
281
|
+
deregisterPermission(key: string): void;
|
|
272
282
|
/** Registers a resource type, so `/api/check` accepts it. */
|
|
273
283
|
registerResourceType(type: string): void;
|
|
274
284
|
/**
|
package/dist/testing/tenant.js
CHANGED
|
@@ -16,6 +16,7 @@ const PATHS = {
|
|
|
16
16
|
jwks: "/api/oauth2/jwks",
|
|
17
17
|
};
|
|
18
18
|
const MAX_PERMISSIONS = 50;
|
|
19
|
+
const MAX_REGISTERED_PERMISSIONS = 500;
|
|
19
20
|
const MAX_BATCH_IDS = 100;
|
|
20
21
|
const DEFAULT_PAGE_SIZE = 20;
|
|
21
22
|
const MAX_PAGE_SIZE = 100;
|
|
@@ -302,6 +303,7 @@ export async function createFakeTenant(options) {
|
|
|
302
303
|
const userMetadata = new Map();
|
|
303
304
|
const organizations = new Map();
|
|
304
305
|
const definedRoles = new Map();
|
|
306
|
+
const deregisteredPermissions = new Set();
|
|
305
307
|
const appRoles = [];
|
|
306
308
|
const invitations = new Map();
|
|
307
309
|
const resourceTypes = new Set();
|
|
@@ -325,6 +327,7 @@ export async function createFakeTenant(options) {
|
|
|
325
327
|
const definedRoleById = (roleId) => [...definedRoles.values()].find((role) => role.id === roleId);
|
|
326
328
|
const appRolesHeld = (organizationId, userId) => appRoles.filter((assignment) => assignment.organizationId === organizationId &&
|
|
327
329
|
assignment.userId === userId);
|
|
330
|
+
const registered = (key) => !deregisteredPermissions.has(key);
|
|
328
331
|
const appRolePermissions = (organizationId, userId) => appRolesHeld(organizationId, userId).flatMap((assignment) => definedRoleById(assignment.roleId)?.permissions ?? []);
|
|
329
332
|
const permissionsIn = (userId, organizationId) => new Set([
|
|
330
333
|
...(users.get(userId)?.permissions ?? []),
|
|
@@ -335,7 +338,7 @@ export async function createFakeTenant(options) {
|
|
|
335
338
|
...appRolePermissions(organizationId, userId),
|
|
336
339
|
]
|
|
337
340
|
: []),
|
|
338
|
-
]);
|
|
341
|
+
].filter(registered));
|
|
339
342
|
const organizationClaims = (userId, organizationId) => {
|
|
340
343
|
if (!organizationId || !isMember(organizationId, userId))
|
|
341
344
|
return {};
|
|
@@ -465,7 +468,7 @@ export async function createFakeTenant(options) {
|
|
|
465
468
|
? grant.subject.id === userId
|
|
466
469
|
: isMember(grant.subject.id, userId);
|
|
467
470
|
if (admits)
|
|
468
|
-
grant.permissions.forEach((p) => held.add(p));
|
|
471
|
+
grant.permissions.filter(registered).forEach((p) => held.add(p));
|
|
469
472
|
}
|
|
470
473
|
return held;
|
|
471
474
|
};
|
|
@@ -999,11 +1002,25 @@ export async function createFakeTenant(options) {
|
|
|
999
1002
|
};
|
|
1000
1003
|
}), request));
|
|
1001
1004
|
});
|
|
1002
|
-
const listMemberRoles = organizationApi((caller,
|
|
1005
|
+
const listMemberRoles = organizationApi((caller, request, [id]) => {
|
|
1003
1006
|
const organization = managedOrganization(caller, id);
|
|
1004
1007
|
if (organization instanceof Response)
|
|
1005
1008
|
return organization;
|
|
1006
|
-
|
|
1009
|
+
const query = new URL(request.url).searchParams;
|
|
1010
|
+
if (!query.has("permission"))
|
|
1011
|
+
return Response.json(roleVocabulary());
|
|
1012
|
+
const keys = query.getAll("permission");
|
|
1013
|
+
if (keys.length > MAX_REGISTERED_PERMISSIONS) {
|
|
1014
|
+
return invalid("permission", `Name at most ${MAX_REGISTERED_PERMISSIONS} permission keys, as many as a tenant may register`);
|
|
1015
|
+
}
|
|
1016
|
+
if (keys.includes("")) {
|
|
1017
|
+
return invalid("permission", "Name a permission key in every permission parameter");
|
|
1018
|
+
}
|
|
1019
|
+
const named = new Set(keys.filter(registered));
|
|
1020
|
+
const matching = new Set([...definedRoles.values()]
|
|
1021
|
+
.filter((role) => role.permissions.some((key) => named.has(key)))
|
|
1022
|
+
.map((role) => role.id));
|
|
1023
|
+
return Response.json(roleVocabulary().filter((role) => role.id === undefined || matching.has(role.id)));
|
|
1007
1024
|
});
|
|
1008
1025
|
const revokeMembership = organizationApi((caller, _request, [id, userId, role]) => {
|
|
1009
1026
|
const organization = managedOrganization(caller, id);
|
|
@@ -1033,7 +1050,7 @@ export async function createFakeTenant(options) {
|
|
|
1033
1050
|
organizationId: null,
|
|
1034
1051
|
slug: role.slug,
|
|
1035
1052
|
name: role.name,
|
|
1036
|
-
permissions:
|
|
1053
|
+
permissions: role.permissions.filter(registered),
|
|
1037
1054
|
});
|
|
1038
1055
|
const listMemberAppRoles = organizationApi((caller, _request, [id, userId]) => {
|
|
1039
1056
|
const organization = managedOrganization(caller, id);
|
|
@@ -1640,6 +1657,10 @@ export async function createFakeTenant(options) {
|
|
|
1640
1657
|
if (holder && holder.slug !== slug) {
|
|
1641
1658
|
throw new Error(`Role id "${roleId}" belongs to "${holder.slug}"`);
|
|
1642
1659
|
}
|
|
1660
|
+
const unregistered = permissions?.find((key) => !registered(key));
|
|
1661
|
+
if (unregistered !== undefined) {
|
|
1662
|
+
throw new Error(`Permission "${unregistered}" is not registered`);
|
|
1663
|
+
}
|
|
1643
1664
|
definedRoles.set(slug, {
|
|
1644
1665
|
id: roleId,
|
|
1645
1666
|
slug,
|
|
@@ -1648,6 +1669,9 @@ export async function createFakeTenant(options) {
|
|
|
1648
1669
|
});
|
|
1649
1670
|
return roleId;
|
|
1650
1671
|
},
|
|
1672
|
+
deregisterPermission: (key) => {
|
|
1673
|
+
deregisteredPermissions.add(key);
|
|
1674
|
+
},
|
|
1651
1675
|
registerResourceType: (type) => {
|
|
1652
1676
|
resourceTypes.add(type);
|
|
1653
1677
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@udibo/oauth2",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.57.0",
|
|
4
4
|
"description": "A flexible OAuth2 toolkit: framework-agnostic authorization & resource servers, a typed client, Hono adapters (including a backend-for-frontend), Express adapters, and React bindings.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"authorization-server",
|
|
@@ -4,8 +4,8 @@ description: Build an OAuth2 authorization server for a Node application with @u
|
|
|
4
4
|
license: MIT
|
|
5
5
|
compatibility: Node.js 22.18 or later for the TypeScript quickstart.
|
|
6
6
|
metadata:
|
|
7
|
-
version: "0.
|
|
8
|
-
targets: "@udibo/oauth2@0.
|
|
7
|
+
version: "0.57.0"
|
|
8
|
+
targets: "@udibo/oauth2@0.57.0"
|
|
9
9
|
---
|
|
10
10
|
|
|
11
11
|
# Build authorization with @udibo/oauth2
|
|
@@ -63,12 +63,12 @@ the person's local secret storage and out of the conversation.
|
|
|
63
63
|
|
|
64
64
|
## Your own authorization server
|
|
65
65
|
|
|
66
|
-
For a local sign-in, follow the complete app in the [versioned quickstart](https://github.com/udibo/oauth2/blob/0.
|
|
66
|
+
For a local sign-in, follow the complete app in the [versioned quickstart](https://github.com/udibo/oauth2/blob/0.57.0/docs/quickstart.md).
|
|
67
67
|
In an existing project, keep its lockfile and package manager. Pin the package
|
|
68
68
|
to the version this skill targets. For an npm project:
|
|
69
69
|
|
|
70
70
|
```sh
|
|
71
|
-
npm install --save-exact @udibo/oauth2@0.
|
|
71
|
+
npm install --save-exact @udibo/oauth2@0.57.0
|
|
72
72
|
```
|
|
73
73
|
|
|
74
74
|
For a local provider, create the quickstart's development configuration with
|
|
@@ -105,7 +105,7 @@ rotation atomic. Wire the authorization-code grant with PKCE and the refresh
|
|
|
105
105
|
grant the application needs. Configure the issuer and registered redirects
|
|
106
106
|
from the deployment settings. Run the package's store contract tests and
|
|
107
107
|
exercise sign-in, refresh and revocation before switching application traffic.
|
|
108
|
-
[Authorization server guide](https://github.com/udibo/oauth2/blob/0.
|
|
108
|
+
[Authorization server guide](https://github.com/udibo/oauth2/blob/0.57.0/docs/guides/become-an-oauth-provider.md) · [Production deployment](https://github.com/udibo/oauth2/blob/0.57.0/docs/guides/production-deployment.md)
|
|
109
109
|
|
|
110
110
|
## Connect a client and protect an API
|
|
111
111
|
|
|
@@ -119,7 +119,7 @@ For an API, mount the bearer middleware from
|
|
|
119
119
|
scope required by the route. Check the verified subject's application
|
|
120
120
|
permissions before returning a private record. Exercise a permitted request,
|
|
121
121
|
a request without a token and a request whose token lacks the route's scope.
|
|
122
|
-
[Protect an API](https://github.com/udibo/oauth2/blob/0.
|
|
122
|
+
[Protect an API](https://github.com/udibo/oauth2/blob/0.57.0/docs/guides/protect-an-api.md)
|
|
123
123
|
|
|
124
124
|
## Hosted path: connect a tenant
|
|
125
125
|
|
|
@@ -128,7 +128,7 @@ application in their tenant and register the callback.
|
|
|
128
128
|
Ask for its public issuer and client ID, and the name of the environment
|
|
129
129
|
variable holding the secret. Use those settings on the server and repeat the
|
|
130
130
|
client sign-in and protected API checks.
|
|
131
|
-
[Hosted integration guide](https://github.com/udibo/oauth2/blob/0.
|
|
131
|
+
[Hosted integration guide](https://github.com/udibo/oauth2/blob/0.57.0/docs/guides/use-udibo.md)
|
|
132
132
|
|
|
133
133
|
## Migrating between authorization servers
|
|
134
134
|
|
|
@@ -136,4 +136,4 @@ First adopt the package against the existing issuer. Verify sign-in, sign-out,
|
|
|
136
136
|
session continuity and one protected request on that issuer. Before switching
|
|
137
137
|
issuers or moving users, present a separate plan covering account identifiers,
|
|
138
138
|
credentials, registrations, cutover and rollback. Wait for approval.
|
|
139
|
-
[Migration guide](https://github.com/udibo/oauth2/blob/0.
|
|
139
|
+
[Migration guide](https://github.com/udibo/oauth2/blob/0.57.0/docs/guides/migrate-from-another-provider.md)
|