@o3co/create-auth-provider 0.14.0 → 0.16.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/README.ja.md +93 -47
- package/README.md +92 -46
- package/package.json +1 -1
- package/templates/standalone/.env.example +34 -0
- package/templates/standalone/Dockerfile +1 -1
- package/templates/standalone/README.ja.md +565 -130
- package/templates/standalone/README.md +356 -92
- package/templates/standalone/config/application.conf +77 -2
- package/templates/standalone/docker-compose.production.yml +7 -0
- package/templates/standalone/docker-compose.yml +7 -0
- package/templates/standalone/gitignore +3 -2
- package/templates/standalone/package.json +3 -2
- package/templates/standalone/src/__tests__/access-token-lifetime-alias.test.mts +49 -15
- package/templates/standalone/src/__tests__/all-modules-composition.fixture.mts +1103 -0
- package/templates/standalone/src/__tests__/all-modules-composition.multi.test.mts +241 -0
- package/templates/standalone/src/__tests__/all-modules-composition.test.mts +1100 -0
- package/templates/standalone/src/__tests__/documented-env-overrides.test.mts +40 -5
- package/templates/standalone/src/__tests__/federation-grants-composition.test.mts +445 -0
- package/templates/standalone/src/__tests__/federation-grants-survive-logout.test.mts +446 -0
- package/templates/standalone/src/__tests__/federation-token-refresh-outage.test.mts +133 -0
- package/templates/standalone/src/__tests__/google-federation-config-module.test.mts +85 -0
- package/templates/standalone/src/__tests__/google-session.fixture.mts +304 -0
- package/templates/standalone/src/__tests__/host-routes.test.mts +141 -0
- package/templates/standalone/src/__tests__/listen.test.mts +128 -0
- package/templates/standalone/src/__tests__/logger-projection.test.mts +77 -0
- package/templates/standalone/src/__tests__/metrics.test.mts +20 -5
- package/templates/standalone/src/__tests__/post-logout-redirect.test.mts +187 -0
- package/templates/standalone/src/__tests__/redis-connection-error-log.test.mts +139 -0
- package/templates/standalone/src/__tests__/replica-safety.test.mts +13 -3
- package/templates/standalone/src/__tests__/router-error-answers.test.mts +149 -0
- package/templates/standalone/src/__tests__/scaffold-assets.test.mts +14 -0
- package/templates/standalone/src/__tests__/shutdown.test.mts +253 -22
- package/templates/standalone/src/__tests__/smoke.test.mts +39 -20
- package/templates/standalone/src/__tests__/store-credential.test.mts +276 -0
- package/templates/standalone/src/app.mts +30 -51
- package/templates/standalone/src/buildModules.mts +94 -12
- package/templates/standalone/src/listen.mts +66 -0
- package/templates/standalone/src/logger.mts +7 -4
- package/templates/standalone/src/modules.mts +118 -12
- package/templates/standalone/src/routes.mts +95 -0
- package/templates/standalone/src/shutdown.mts +90 -18
- package/templates/standalone/vitest.supertest-loopback.mts +22 -3
- package/templates/versions.json +15 -14
- package/templates/standalone/src/__tests__/terminal-error.test.mts +0 -96
- package/templates/standalone/src/terminalError.mts +0 -60
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright 2026 1o1 Co. Ltd.
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* #593 acceptance criterion 8, at the two HTTP logout endpoints (D14).
|
|
19
|
+
*
|
|
20
|
+
* A federation grant outlives the session it was agreed through. The proof of
|
|
21
|
+
* that used to be a direct call to `cascadeLogout()` — which is the cascade
|
|
22
|
+
* `/oauth/logout` runs, and not what `/session/logout` runs: that endpoint has
|
|
23
|
+
* its own record hygiene (`invalidateSessionRecords`) and reaches the grant
|
|
24
|
+
* store on no path, by construction. A proof of the helper is not a proof of
|
|
25
|
+
* the endpoints. So this drives both, on the standalone, as a deployment
|
|
26
|
+
* composes them: a grant seeded beside a live browser session, the session's
|
|
27
|
+
* records gone afterwards, the grant and its credential exactly as they were,
|
|
28
|
+
* and `/token` still disclosing.
|
|
29
|
+
*
|
|
30
|
+
* The seeded grant's access token is fresh, so the disclosure is the cached
|
|
31
|
+
* one and no upstream is asked — the OIDC federation the connection names is
|
|
32
|
+
* configured with `discovery = false` and hand-typed endpoints so that the
|
|
33
|
+
* deployment boots without a network.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import { createHmac } from "node:crypto";
|
|
37
|
+
import { fileURLToPath } from "node:url";
|
|
38
|
+
import {
|
|
39
|
+
type AppConfig,
|
|
40
|
+
AppConfigSchema,
|
|
41
|
+
createApp,
|
|
42
|
+
createKeyStoreFactory,
|
|
43
|
+
defineModule,
|
|
44
|
+
type FederationTokenStore,
|
|
45
|
+
federationGrantAuthorizationRevision,
|
|
46
|
+
federationGrantIdentityRevision,
|
|
47
|
+
InMemoryClientRepository,
|
|
48
|
+
InMemoryUserRepository,
|
|
49
|
+
type MemoryFederationGrantStore,
|
|
50
|
+
memoryRefreshTokenFamilyStoreModule,
|
|
51
|
+
registerBuiltinKeyStores,
|
|
52
|
+
type UserSessionStore,
|
|
53
|
+
} from "@o3co/auth-provider-core";
|
|
54
|
+
import { parseFile } from "@o3co/ts.hocon";
|
|
55
|
+
import { validate } from "@o3co/ts.hocon/zod";
|
|
56
|
+
import express from "express";
|
|
57
|
+
import request from "supertest";
|
|
58
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
59
|
+
import { buildModules } from "../buildModules.mjs";
|
|
60
|
+
import { resolveConfigPaths, resolveLibraryReferenceConfPath } from "../configPath.mjs";
|
|
61
|
+
|
|
62
|
+
const DAY = 86_400_000;
|
|
63
|
+
const configDir = fileURLToPath(new URL("../../config", import.meta.url));
|
|
64
|
+
|
|
65
|
+
const ISSUER = "https://auth.test";
|
|
66
|
+
const JWT_SECRET = "federation-grants-survive-logout.at-least-32-bytes.ok";
|
|
67
|
+
const UPSTREAM = "https://issuer.example";
|
|
68
|
+
const UPSTREAM_CLIENT_ID = "provider-client";
|
|
69
|
+
const ENCRYPTION_KEY = Buffer.alloc(32, 9).toString("base64");
|
|
70
|
+
|
|
71
|
+
const CLIENT_ID = "worker";
|
|
72
|
+
const CLIENT_SECRET = "worker-secret-value";
|
|
73
|
+
const BASIC = `Basic ${Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`;
|
|
74
|
+
const USERNAME = "alice";
|
|
75
|
+
const PASSWORD = "correct-horse-battery-staple";
|
|
76
|
+
const SUB = "u-alice";
|
|
77
|
+
|
|
78
|
+
const CONNECTION = "calendar";
|
|
79
|
+
const SCOPES: readonly string[] = ["openid", "offline_access", "calendar.read"];
|
|
80
|
+
const BOUNDARY = "production";
|
|
81
|
+
const GRANT_ID = "g-1";
|
|
82
|
+
const REFRESH_TOKEN = "SENTINEL-refresh-token";
|
|
83
|
+
const ACCESS_TOKEN = "upstream-access-token";
|
|
84
|
+
|
|
85
|
+
const ENV: Readonly<Record<string, string>> = {
|
|
86
|
+
OAUTH_JWT_ALGORITHM: "HS256",
|
|
87
|
+
OAUTH_JWT_SECRET: JWT_SECRET,
|
|
88
|
+
OAUTH_JWT_ISSUER: ISSUER,
|
|
89
|
+
SESSION_SECRET: "federation-grants-survive-logout-session.at-least-32-bytes.ok",
|
|
90
|
+
SESSION_SECURE: "false",
|
|
91
|
+
SESSION_NAME: "auth.session",
|
|
92
|
+
SESSION_STORAGE_TYPE: "memory",
|
|
93
|
+
CLIENT_USER_TYPE: "yaml",
|
|
94
|
+
REFRESH_TOKEN_FAMILY_STORE_REDIS_URL: "redis://redis.test:6379",
|
|
95
|
+
USER_SESSION_STORES_ADAPTER: "memory",
|
|
96
|
+
RATE_LIMITER_ADAPTER: "memory",
|
|
97
|
+
OAUTH_CODE_ADAPTER: "memory",
|
|
98
|
+
ACCESS_TOKEN_DENYLIST_ADAPTER: "memory",
|
|
99
|
+
REPLAY_SEEN_SET_ADAPTER: "memory",
|
|
100
|
+
FEDERATION_TOKEN_STORE_TYPE: "memory",
|
|
101
|
+
CONSENT_STORE_ADAPTER: "none",
|
|
102
|
+
FEDERATION_GRANT_STORE_ADAPTER: "memory",
|
|
103
|
+
FEDERATION_GRANT_INTENT_STORE_ADAPTER: "memory",
|
|
104
|
+
FEDERATION_GRANTS_ENABLED: "true",
|
|
105
|
+
FEDERATION_GRANTS_CONSENT_URL: "/consent/grants",
|
|
106
|
+
// The connect flow is not driven here, and the bundled repository has no
|
|
107
|
+
// identity lookup; "unsupported" is the declaration a deployment without one
|
|
108
|
+
// makes (#613), and what lets a connection be configured at all.
|
|
109
|
+
FEDERATION_GRANTS_IDENTITY_LOOKUP: "unsupported",
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The shipped configuration under the environment above, with the two lists
|
|
114
|
+
* that have no environment form (comment 9 on #593) written over it: the
|
|
115
|
+
* upstream federation the connection names, and the connection.
|
|
116
|
+
*/
|
|
117
|
+
function resolveConfig(): AppConfig {
|
|
118
|
+
const { applicationConfPath, envConfPath } = resolveConfigPaths(configDir, "production");
|
|
119
|
+
const config = validate(
|
|
120
|
+
parseFile(envConfPath, { env: ENV })
|
|
121
|
+
.withFallback(parseFile(applicationConfPath, { env: ENV }))
|
|
122
|
+
.withFallback(parseFile(resolveLibraryReferenceConfPath(), { env: ENV })),
|
|
123
|
+
AppConfigSchema,
|
|
124
|
+
);
|
|
125
|
+
return {
|
|
126
|
+
...config,
|
|
127
|
+
federations: {
|
|
128
|
+
...config.federations,
|
|
129
|
+
upstream: {
|
|
130
|
+
enabled: true,
|
|
131
|
+
type: "oidc",
|
|
132
|
+
issuer: UPSTREAM,
|
|
133
|
+
clientId: UPSTREAM_CLIENT_ID,
|
|
134
|
+
clientSecret: "provider-secret",
|
|
135
|
+
callbackURL: `${ISSUER}/session/oauth/federation/upstream/callback`,
|
|
136
|
+
scopes: [...SCOPES],
|
|
137
|
+
discovery: false,
|
|
138
|
+
endpoints: {
|
|
139
|
+
authorizationEndpoint: `${UPSTREAM}/authorize`,
|
|
140
|
+
tokenEndpoint: `${UPSTREAM}/token`,
|
|
141
|
+
jwksUri: `${UPSTREAM}/jwks`,
|
|
142
|
+
},
|
|
143
|
+
redirectAllowlist: [],
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
federationGrants: {
|
|
147
|
+
...config.federationGrants,
|
|
148
|
+
encryptionKeys: [{ id: "k-test", key: ENCRYPTION_KEY }],
|
|
149
|
+
connections: {
|
|
150
|
+
[CONNECTION]: {
|
|
151
|
+
federation: "upstream",
|
|
152
|
+
scopes: [...SCOPES],
|
|
153
|
+
boundary: BOUNDARY,
|
|
154
|
+
maxAccessTokenLifetime: 3600,
|
|
155
|
+
callbackURL: `${ISSUER}/session/federation-grants/callback/${CONNECTION}`,
|
|
156
|
+
},
|
|
157
|
+
},
|
|
158
|
+
},
|
|
159
|
+
} as AppConfig;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const testRepositoriesModule = defineModule({
|
|
163
|
+
name: "test:repositories",
|
|
164
|
+
provides: {
|
|
165
|
+
clientRepository: () =>
|
|
166
|
+
new InMemoryClientRepository(
|
|
167
|
+
new Map([
|
|
168
|
+
[
|
|
169
|
+
CLIENT_ID,
|
|
170
|
+
{
|
|
171
|
+
tokenEndpointAuthMethod: "client_secret_basic",
|
|
172
|
+
clientSecret: CLIENT_SECRET,
|
|
173
|
+
allowedRedirectUris: [],
|
|
174
|
+
allowedScopes: ["openid", "profile"],
|
|
175
|
+
allowedAudiences: [],
|
|
176
|
+
allowedGrantTypes: ["session"],
|
|
177
|
+
backchannelLogoutSessionRequired: true,
|
|
178
|
+
frontchannelLogoutSessionRequired: true,
|
|
179
|
+
allowedAzpForFederationToken: false,
|
|
180
|
+
allowedFederationGrantConnections: [CONNECTION],
|
|
181
|
+
},
|
|
182
|
+
],
|
|
183
|
+
]),
|
|
184
|
+
),
|
|
185
|
+
userRepository: () =>
|
|
186
|
+
new InMemoryUserRepository(
|
|
187
|
+
new Map([[USERNAME, { id: SUB, password: PASSWORD, email: "alice@example.com" }]]),
|
|
188
|
+
),
|
|
189
|
+
} as never,
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
const testKeyStoreModule = defineModule({
|
|
193
|
+
name: "test:key-store",
|
|
194
|
+
requires: ["config"] as const,
|
|
195
|
+
provides: {
|
|
196
|
+
keyStore: async ({ config: c }) => {
|
|
197
|
+
const factory = createKeyStoreFactory();
|
|
198
|
+
registerBuiltinKeyStores(factory);
|
|
199
|
+
return factory.create({
|
|
200
|
+
type: "local",
|
|
201
|
+
...((c as AppConfig).oauth.jwt.signingKey.local ?? {}),
|
|
202
|
+
});
|
|
203
|
+
},
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
/** The grant as the connect flow would have left it, a fresh upstream token in hand. */
|
|
208
|
+
async function seedGrant(store: MemoryFederationGrantStore): Promise<void> {
|
|
209
|
+
const at = new Date();
|
|
210
|
+
// The revisions as `connections.mts` resolves them from the configuration
|
|
211
|
+
// above: the federation's issuer and client, the connection's scopes and
|
|
212
|
+
// boundary, no resource, no authorization parameters.
|
|
213
|
+
const resolved = {
|
|
214
|
+
upstreamIssuer: UPSTREAM,
|
|
215
|
+
upstreamClientId: UPSTREAM_CLIENT_ID,
|
|
216
|
+
scopes: SCOPES,
|
|
217
|
+
boundary: BOUNDARY,
|
|
218
|
+
authorizationParams: {},
|
|
219
|
+
};
|
|
220
|
+
await store.createPending({
|
|
221
|
+
id: GRANT_ID,
|
|
222
|
+
subject: SUB,
|
|
223
|
+
clientId: CLIENT_ID,
|
|
224
|
+
connection: CONNECTION,
|
|
225
|
+
intent: { handle: "h", expiresAt: new Date(at.getTime() + 600_000) },
|
|
226
|
+
now: at,
|
|
227
|
+
});
|
|
228
|
+
const written = await store.activate({
|
|
229
|
+
grantId: GRANT_ID,
|
|
230
|
+
intentHandle: "h",
|
|
231
|
+
authorization: {
|
|
232
|
+
identityRevision: federationGrantIdentityRevision(resolved),
|
|
233
|
+
authorizationRevision: federationGrantAuthorizationRevision(resolved),
|
|
234
|
+
upstream: { issuer: UPSTREAM, subject: "upstream-alice" },
|
|
235
|
+
scopes: [...SCOPES],
|
|
236
|
+
consent: { at, sid: "sid-consent", scopes: [...SCOPES] },
|
|
237
|
+
authorizedAt: at,
|
|
238
|
+
expiresAt: new Date(at.getTime() + 30 * DAY),
|
|
239
|
+
resource: undefined,
|
|
240
|
+
},
|
|
241
|
+
credentials: {
|
|
242
|
+
refreshToken: REFRESH_TOKEN,
|
|
243
|
+
accessToken: {
|
|
244
|
+
value: ACCESS_TOKEN,
|
|
245
|
+
tokenType: "Bearer",
|
|
246
|
+
obtainedAt: at,
|
|
247
|
+
issuedLifetime: 3600,
|
|
248
|
+
scopes: [...SCOPES],
|
|
249
|
+
},
|
|
250
|
+
},
|
|
251
|
+
now: at,
|
|
252
|
+
});
|
|
253
|
+
if (!written.ok) throw new Error("fixture: the grant was not activated");
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const base64url = (value: unknown): string =>
|
|
257
|
+
Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* An id_token for the session, signed with the deployment's own HS256 key, as
|
|
261
|
+
* the RP would present it: `/oauth/logout` reads `sid` from the hint and from
|
|
262
|
+
* nothing else.
|
|
263
|
+
*/
|
|
264
|
+
function idTokenHint(sid: string): string {
|
|
265
|
+
const header = base64url({ alg: "HS256", kid: "v0", typ: "JWT" });
|
|
266
|
+
const now = Math.floor(Date.now() / 1000);
|
|
267
|
+
const payload = base64url({
|
|
268
|
+
iss: ISSUER,
|
|
269
|
+
sub: SUB,
|
|
270
|
+
aud: CLIENT_ID,
|
|
271
|
+
sid,
|
|
272
|
+
iat: now,
|
|
273
|
+
exp: now + 3600,
|
|
274
|
+
});
|
|
275
|
+
const signature = createHmac("sha256", JWT_SECRET)
|
|
276
|
+
.update(`${header}.${payload}`)
|
|
277
|
+
.digest("base64url");
|
|
278
|
+
return `${header}.${payload}.${signature}`;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const claimsOf = (jwt: string): Record<string, unknown> =>
|
|
282
|
+
JSON.parse(Buffer.from(jwt.split(".")[1] ?? "", "base64url").toString("utf8")) as Record<
|
|
283
|
+
string,
|
|
284
|
+
unknown
|
|
285
|
+
>;
|
|
286
|
+
|
|
287
|
+
describe("#593 AC8: a grant outlives the browser session at both logout endpoints (D14)", () => {
|
|
288
|
+
let handleRef: Awaited<ReturnType<typeof createApp>> | undefined;
|
|
289
|
+
|
|
290
|
+
afterEach(async () => {
|
|
291
|
+
await handleRef?.dispose();
|
|
292
|
+
handleRef = undefined;
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
async function boot() {
|
|
296
|
+
const config = resolveConfig();
|
|
297
|
+
const handle = await createApp({
|
|
298
|
+
modules: buildModules(config, {
|
|
299
|
+
keyStoreModule: testKeyStoreModule,
|
|
300
|
+
repositoriesModule: testRepositoriesModule,
|
|
301
|
+
refreshTokenFamilyModules: [memoryRefreshTokenFamilyStoreModule],
|
|
302
|
+
}),
|
|
303
|
+
bootstrapComponents: { config, pathResolver: (s) => s },
|
|
304
|
+
});
|
|
305
|
+
handleRef = handle;
|
|
306
|
+
const components = handle.components as {
|
|
307
|
+
federationGrantStore: MemoryFederationGrantStore;
|
|
308
|
+
userSessionStore: UserSessionStore;
|
|
309
|
+
federationTokenStore: FederationTokenStore;
|
|
310
|
+
};
|
|
311
|
+
await seedGrant(components.federationGrantStore);
|
|
312
|
+
const app = express();
|
|
313
|
+
app.use(handle.router);
|
|
314
|
+
return { app, config, ...components };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** The real browser half: a CSRF pair, a login, and the cookies plus the token the login reissued. */
|
|
318
|
+
async function login(app: express.Express, config: AppConfig) {
|
|
319
|
+
const csrfRes = await request(app).get("/session/csrf");
|
|
320
|
+
expect(csrfRes.status).toBe(200);
|
|
321
|
+
const csrfToken = csrfRes.body.csrf_token as string;
|
|
322
|
+
const headerName = csrfRes.body.header_name as string;
|
|
323
|
+
const csrfCookies = csrfRes.headers["set-cookie"] as unknown as string[];
|
|
324
|
+
|
|
325
|
+
const loginRes = await request(app)
|
|
326
|
+
.post("/session/login")
|
|
327
|
+
.set("Cookie", csrfCookies)
|
|
328
|
+
.set(headerName, csrfToken)
|
|
329
|
+
.type("form")
|
|
330
|
+
.send({ username: USERNAME, password: PASSWORD });
|
|
331
|
+
expect(loginRes.status).toBe(200);
|
|
332
|
+
|
|
333
|
+
const cookies = loginRes.headers["set-cookie"] as unknown as string[];
|
|
334
|
+
const csrfCookiePrefix = `${config.session.name}.csrf=`;
|
|
335
|
+
const reissued = cookies
|
|
336
|
+
.find((c) => c.startsWith(csrfCookiePrefix))
|
|
337
|
+
?.slice(csrfCookiePrefix.length)
|
|
338
|
+
.split(";")[0];
|
|
339
|
+
expect(reissued).toBeDefined();
|
|
340
|
+
return { cookies, csrfToken: decodeURIComponent(reissued as string), headerName };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** The session's `sid`, read off the access token the session grant mints for it. */
|
|
344
|
+
async function sidOf(app: express.Express, cookies: string[]): Promise<string> {
|
|
345
|
+
const res = await request(app)
|
|
346
|
+
.post("/oauth/token")
|
|
347
|
+
.set("Authorization", BASIC)
|
|
348
|
+
.set("Cookie", cookies)
|
|
349
|
+
.type("form")
|
|
350
|
+
.send({ grant_type: "session" });
|
|
351
|
+
expect(res.status).toBe(200);
|
|
352
|
+
const sid = claimsOf(res.body.access_token as string).sid;
|
|
353
|
+
expect(typeof sid).toBe("string");
|
|
354
|
+
return sid as string;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const disclose = (app: express.Express) =>
|
|
358
|
+
request(app)
|
|
359
|
+
.post(`/oauth/federation-grants/${GRANT_ID}/token`)
|
|
360
|
+
.set("Authorization", BASIC)
|
|
361
|
+
.send({ sub: SUB });
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* What a logout has to leave: the record, its credential — the values, not
|
|
365
|
+
* only a readable state, since a rotated or dropped refresh token beside an
|
|
366
|
+
* untouched access token would still read `"ok"` — and a disclosure that
|
|
367
|
+
* still answers.
|
|
368
|
+
*/
|
|
369
|
+
async function expectGrantUntouched(app: express.Express, store: MemoryFederationGrantStore) {
|
|
370
|
+
expect((await store.find(GRANT_ID, new Date()))?.status).toBe("active");
|
|
371
|
+
const opened = await store.open(GRANT_ID, new Date());
|
|
372
|
+
if (opened?.credentials.state !== "ok")
|
|
373
|
+
throw new Error("the grant's credential is not readable");
|
|
374
|
+
expect(opened.credentials.value).toMatchObject({
|
|
375
|
+
refreshToken: REFRESH_TOKEN,
|
|
376
|
+
accessToken: { value: ACCESS_TOKEN },
|
|
377
|
+
});
|
|
378
|
+
const response = await disclose(app);
|
|
379
|
+
expect(response.status).toBe(200);
|
|
380
|
+
expect(response.body.access_token).toBe(ACCESS_TOKEN);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
it("POST /session/logout ends the session's own records and leaves the grant spendable", async () => {
|
|
384
|
+
const { app, config, federationGrantStore, userSessionStore, federationTokenStore } =
|
|
385
|
+
await boot();
|
|
386
|
+
const { cookies, csrfToken, headerName } = await login(app, config);
|
|
387
|
+
const sid = await sidOf(app, cookies);
|
|
388
|
+
// A session-bound upstream token beside the grant: the record #276's
|
|
389
|
+
// guarantee is about, keyed by this session.
|
|
390
|
+
await federationTokenStore.attach(sid, "upstream", {
|
|
391
|
+
accessToken: "session-bound-upstream-token",
|
|
392
|
+
expiresAt: null,
|
|
393
|
+
// Every field is a required key since the #645 follow-up; this
|
|
394
|
+
// record carries only the access token.
|
|
395
|
+
refreshToken: undefined,
|
|
396
|
+
idToken: undefined,
|
|
397
|
+
tokenType: undefined,
|
|
398
|
+
scope: undefined,
|
|
399
|
+
grantedScope: undefined,
|
|
400
|
+
});
|
|
401
|
+
expect(await userSessionStore.get(sid)).not.toBeNull();
|
|
402
|
+
await expectGrantUntouched(app, federationGrantStore);
|
|
403
|
+
|
|
404
|
+
const logout = await request(app)
|
|
405
|
+
.post("/session/logout")
|
|
406
|
+
.set("Cookie", cookies)
|
|
407
|
+
.set(headerName, csrfToken);
|
|
408
|
+
expect([200, 204]).toContain(logout.status);
|
|
409
|
+
|
|
410
|
+
// The session-bound records are gone (#276 holds) ...
|
|
411
|
+
expect(await userSessionStore.get(sid)).toBeNull();
|
|
412
|
+
expect(await federationTokenStore.get(sid, "upstream")).toBeNull();
|
|
413
|
+
// ... and the grant is not among them.
|
|
414
|
+
await expectGrantUntouched(app, federationGrantStore);
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
it("POST /oauth/logout runs the cascade and leaves the grant spendable", async () => {
|
|
418
|
+
const { app, config, federationGrantStore, userSessionStore, federationTokenStore } =
|
|
419
|
+
await boot();
|
|
420
|
+
const { cookies } = await login(app, config);
|
|
421
|
+
const sid = await sidOf(app, cookies);
|
|
422
|
+
await federationTokenStore.attach(sid, "upstream", {
|
|
423
|
+
accessToken: "session-bound-upstream-token",
|
|
424
|
+
expiresAt: null,
|
|
425
|
+
// Every field is a required key since the #645 follow-up; this
|
|
426
|
+
// record carries only the access token.
|
|
427
|
+
refreshToken: undefined,
|
|
428
|
+
idToken: undefined,
|
|
429
|
+
tokenType: undefined,
|
|
430
|
+
scope: undefined,
|
|
431
|
+
grantedScope: undefined,
|
|
432
|
+
});
|
|
433
|
+
expect(await userSessionStore.get(sid)).not.toBeNull();
|
|
434
|
+
await expectGrantUntouched(app, federationGrantStore);
|
|
435
|
+
|
|
436
|
+
const logout = await request(app)
|
|
437
|
+
.post("/oauth/logout")
|
|
438
|
+
.type("form")
|
|
439
|
+
.send({ id_token_hint: idTokenHint(sid) });
|
|
440
|
+
expect(logout.status).toBe(200);
|
|
441
|
+
|
|
442
|
+
expect(await userSessionStore.get(sid)).toBeNull();
|
|
443
|
+
expect(await federationTokenStore.get(sid, "upstream")).toBeNull();
|
|
444
|
+
await expectGrantUntouched(app, federationGrantStore);
|
|
445
|
+
});
|
|
446
|
+
});
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright 2026 1o1 Co. Ltd.
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* `POST /oauth/federation/:name/token` ends a session's upstream tokens only
|
|
19
|
+
* on the upstream's own verdict that the refresh token is bad — a structured
|
|
20
|
+
* `invalid_grant` under a 4xx — and never while the upstream is down, whatever
|
|
21
|
+
* the body of its 5xx says. An outage is `503`, and the tokens are kept for
|
|
22
|
+
* the retry.
|
|
23
|
+
*
|
|
24
|
+
* Driven through the real Google adapter and its library (openid-client)
|
|
25
|
+
* against a fake Google (`createFakeIdp`), so the errors the route classifies
|
|
26
|
+
* are the ones the library raises: a 4xx whose body names a code is a
|
|
27
|
+
* `ResponseBodyError` carrying `error` and `status`; a 5xx is an
|
|
28
|
+
* `OperationProcessingError` raised over the `Response`, whose body the
|
|
29
|
+
* library does not read — and which the route used to answer `500
|
|
30
|
+
* refresh_failed`, as if the upstream had said something it could not place.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import { createFakeIdp, type FakeIdp } from "@o3co/auth-provider-core/testing";
|
|
34
|
+
import request from "supertest";
|
|
35
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
36
|
+
import {
|
|
37
|
+
accessTokenWithFamily,
|
|
38
|
+
GOOGLE_CLIENT_ID,
|
|
39
|
+
type GoogleSession,
|
|
40
|
+
signInLinkedToGoogle,
|
|
41
|
+
} from "./google-session.fixture.mjs";
|
|
42
|
+
|
|
43
|
+
const GOOGLE = {
|
|
44
|
+
issuer: "https://accounts.google.com",
|
|
45
|
+
authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
|
|
46
|
+
tokenEndpoint: "https://oauth2.googleapis.com/token",
|
|
47
|
+
jwksUri: "https://www.googleapis.com/oauth2/v3/certs",
|
|
48
|
+
userinfoEndpoint: "https://www.googleapis.com/oauth2/v3/userinfo",
|
|
49
|
+
};
|
|
50
|
+
const STORED_REFRESH_TOKEN = "stored-refresh-token";
|
|
51
|
+
|
|
52
|
+
describe("POST /oauth/federation/google/token: an upstream outage never ends the session's Google tokens", () => {
|
|
53
|
+
let session: GoogleSession | undefined;
|
|
54
|
+
|
|
55
|
+
afterEach(async () => {
|
|
56
|
+
await session?.dispose();
|
|
57
|
+
session = undefined;
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Alice's session with Google linked, its access token expired so the
|
|
62
|
+
* route refreshes, and the fake Google answering the refresh with `status`
|
|
63
|
+
* and `body`.
|
|
64
|
+
*/
|
|
65
|
+
async function refreshAnswered(status: number, body: Record<string, unknown>) {
|
|
66
|
+
const idp: FakeIdp = await createFakeIdp({ ...GOOGLE, clientId: GOOGLE_CLIENT_ID });
|
|
67
|
+
idp.tokenStatus = status;
|
|
68
|
+
idp.refusal = body;
|
|
69
|
+
session = await signInLinkedToGoogle({
|
|
70
|
+
google: { fetch: idp.fetch },
|
|
71
|
+
tokens: {
|
|
72
|
+
accessToken: "expired-upstream-access-token",
|
|
73
|
+
expiresAt: new Date(Date.now() - 60_000),
|
|
74
|
+
refreshToken: STORED_REFRESH_TOKEN,
|
|
75
|
+
idToken: undefined,
|
|
76
|
+
tokenType: "Bearer",
|
|
77
|
+
scope: "openid profile email",
|
|
78
|
+
grantedScope: "openid profile email",
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
const res = await request(session.app)
|
|
82
|
+
.post("/oauth/federation/google/token")
|
|
83
|
+
.set("Authorization", `Bearer ${accessTokenWithFamily(session.sid)}`)
|
|
84
|
+
.send();
|
|
85
|
+
// The library did ask Google: what follows is its reading of the answer.
|
|
86
|
+
expect(
|
|
87
|
+
idp.requests.filter(
|
|
88
|
+
(r) =>
|
|
89
|
+
`${r.url.origin}${r.url.pathname}` === GOOGLE.tokenEndpoint &&
|
|
90
|
+
r.body?.get("grant_type") === "refresh_token",
|
|
91
|
+
),
|
|
92
|
+
).toHaveLength(1);
|
|
93
|
+
return { res, ...session };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
it("keeps them and answers 503 when Google answers 503 with a body naming invalid_grant", async () => {
|
|
97
|
+
const { res, sid, federationTokenStore, sessionFederationIndex } = await refreshAnswered(503, {
|
|
98
|
+
error: "invalid_grant",
|
|
99
|
+
error_description: "Backend unavailable",
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
expect(res.status).toBe(503);
|
|
103
|
+
expect(res.body).toEqual({
|
|
104
|
+
error: "temporarily_unavailable",
|
|
105
|
+
error_description: "upstream federation provider temporarily unavailable",
|
|
106
|
+
});
|
|
107
|
+
expect((await federationTokenStore.get(sid, "google"))?.refreshToken).toBe(
|
|
108
|
+
STORED_REFRESH_TOKEN,
|
|
109
|
+
);
|
|
110
|
+
expect(await sessionFederationIndex.listFederations(sid)).toContain("google");
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("keeps them and answers 503 when Google answers 502 with no OAuth body at all", async () => {
|
|
114
|
+
const { res, sid, federationTokenStore } = await refreshAnswered(502, {});
|
|
115
|
+
|
|
116
|
+
expect(res.status).toBe(503);
|
|
117
|
+
expect((await federationTokenStore.get(sid, "google"))?.refreshToken).toBe(
|
|
118
|
+
STORED_REFRESH_TOKEN,
|
|
119
|
+
);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it("ends them on Google's structured 400 invalid_grant", async () => {
|
|
123
|
+
const { res, sid, federationTokenStore, sessionFederationIndex } = await refreshAnswered(400, {
|
|
124
|
+
error: "invalid_grant",
|
|
125
|
+
error_description: "Token has been expired or revoked.",
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
expect(res.status).toBe(410);
|
|
129
|
+
expect(res.body.error).toBe("re_authentication_required");
|
|
130
|
+
expect(await federationTokenStore.get(sid, "google")).toBeNull();
|
|
131
|
+
expect(await sessionFederationIndex.listFederations(sid)).not.toContain("google");
|
|
132
|
+
});
|
|
133
|
+
});
|
|
@@ -112,3 +112,88 @@ describe("googleFederationConfigModule — redirect-policy plumbing (#278)", ()
|
|
|
112
112
|
expect(out.redirectAllowlist).toEqual(["https://app.example.com/dashboard"]);
|
|
113
113
|
});
|
|
114
114
|
});
|
|
115
|
+
|
|
116
|
+
describe("googleFederationConfigModule — requireAuthorizationResponseIss (#597)", () => {
|
|
117
|
+
it("is absent by default, so the provider's own default (required) applies", () => {
|
|
118
|
+
expect("requireAuthorizationResponseIss" in buildConfig(credentials)).toBe(false);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("forwards the operator's escape hatch", () => {
|
|
122
|
+
expect(
|
|
123
|
+
buildConfig({ ...credentials, requireAuthorizationResponseIss: false })
|
|
124
|
+
.requireAuthorizationResponseIss,
|
|
125
|
+
).toBe(false);
|
|
126
|
+
expect(
|
|
127
|
+
buildConfig({ ...credentials, requireAuthorizationResponseIss: true })
|
|
128
|
+
.requireAuthorizationResponseIss,
|
|
129
|
+
).toBe(true);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it("reads the strings an environment override produces", () => {
|
|
133
|
+
expect(
|
|
134
|
+
buildConfig({ ...credentials, requireAuthorizationResponseIss: "false" })
|
|
135
|
+
.requireAuthorizationResponseIss,
|
|
136
|
+
).toBe(false);
|
|
137
|
+
expect(
|
|
138
|
+
buildConfig({ ...credentials, requireAuthorizationResponseIss: "true" })
|
|
139
|
+
.requireAuthorizationResponseIss,
|
|
140
|
+
).toBe(true);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("reads the spellings every other env-overridable boolean accepts", () => {
|
|
144
|
+
for (const [raw, expected] of [
|
|
145
|
+
["False", false],
|
|
146
|
+
[" false ", false],
|
|
147
|
+
["0", false],
|
|
148
|
+
["TRUE", true],
|
|
149
|
+
["1", true],
|
|
150
|
+
] as const) {
|
|
151
|
+
expect(
|
|
152
|
+
buildConfig({ ...credentials, requireAuthorizationResponseIss: raw })
|
|
153
|
+
.requireAuthorizationResponseIss,
|
|
154
|
+
).toBe(expected);
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it("refuses an empty value, which elsewhere reads as false: exported-but-empty must not switch this check off", () => {
|
|
159
|
+
expect(() => buildConfig({ ...credentials, requireAuthorizationResponseIss: "" })).toThrow(
|
|
160
|
+
/federations\.google\.requireAuthorizationResponseIss/,
|
|
161
|
+
);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it("refuses anything else: a typo must not silently switch the check off, or leave it on", () => {
|
|
165
|
+
for (const bad of ["no", "off", 0, 1, []]) {
|
|
166
|
+
expect(() => buildConfig({ ...credentials, requireAuthorizationResponseIss: bad })).toThrow(
|
|
167
|
+
/federations\.google\.requireAuthorizationResponseIss/,
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
describe("googleFederationConfigModule — accessType", () => {
|
|
174
|
+
// federation-google asks every sign-in for consent with offline access, so
|
|
175
|
+
// every session gets a refresh token; "online" is the operator's way to
|
|
176
|
+
// keep Google's consent screen to the first sign-in, at the price of no
|
|
177
|
+
// refresh token at all. A bridge that drops the field leaves the operator
|
|
178
|
+
// without that choice.
|
|
179
|
+
it("is absent by default, so the provider's own default (offline) applies", () => {
|
|
180
|
+
expect("accessType" in buildConfig(credentials)).toBe(false);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it("leaves a null accessType absent, never forwarded as null, which the provider refuses", () => {
|
|
184
|
+
expect("accessType" in buildConfig({ ...credentials, accessType: null })).toBe(false);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
it("forwards offline and online", () => {
|
|
188
|
+
expect(buildConfig({ ...credentials, accessType: "online" }).accessType).toBe("online");
|
|
189
|
+
expect(buildConfig({ ...credentials, accessType: "offline" }).accessType).toBe("offline");
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it("refuses anything else at boot, naming the key", () => {
|
|
193
|
+
for (const bad of ["", "offine", "Online", "true", false, 1]) {
|
|
194
|
+
expect(() => buildConfig({ ...credentials, accessType: bad })).toThrow(
|
|
195
|
+
/federations\.google\.accessType/,
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
});
|