Skip to content

Commit 8c4923b

Browse files
authored
Add OIDC token preference for determining session expiry (#1337)
* Add OIDC token preference for determining session expiry Site admins can now choose whether the GitBook session token expiry is derived from the ID token or the access token returned by the authentication provider. - ID token (default): the `exp` claim, as before, so existing installations are unaffected. - Access token: the `expires_in` of the token response, counted from the moment the token is exchanged, falling back to the minimum session duration when the provider omits it. Session lifetimes are clamped between 1 hour and 7 days regardless of the source, so a long-lived upstream token can no longer mint a GitBook session that outlives a revoked visitor's access by weeks. `OIDCTokenResponseData` is updated to match RFC 6749 section 5.1 and OIDC Core section 3.1.3.3: `id_token`, `access_token` and `token_type` are required, `expires_in`, `refresh_token` and `scope` optional. The runtime guards stay, since the response is untrusted input. The expiry logic moves to `src/session-expiry.ts` so it can be unit tested without pulling in the integration entrypoint. Ref: RND-13568 * Keep the Cloudflare worker types alongside the bun test types `compilerOptions.types` replaces the list inherited from @gitbook/tsconfig/integration.json rather than extending it, so adding `bun` for `bun:test` dropped `@cloudflare/workers-types` and with it the `Response.json<T>()` generic the token exchange relies on.
1 parent c99e9d4 commit 8c4923b

6 files changed

Lines changed: 332 additions & 11 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@gitbook/integration-oidc": minor
3+
---
4+
5+
Add a "Session Expiry" option to choose whether the GitBook session expiry is derived from the ID token's `exp` claim (default) or the access token's `expires_in`, and cap sessions at 7 days

‎integrations/oidc/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
},
1616
"scripts": {
1717
"typecheck": "tsc --noEmit",
18+
"test": "bun test",
1819
"publish-integrations-staging": "gitbook publish .",
1920
"check": "gitbook check",
2021
"publish-integrations": "gitbook publish ."

‎integrations/oidc/src/index.tsx‎

Lines changed: 60 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ import {
3131
getPKCECodeVerifierFromCookie,
3232
serializePKCECookie,
3333
} from './pkce';
34+
import {
35+
computeSessionExpiry,
36+
DEFAULT_SESSION_EXPIRY_SOURCE,
37+
type OIDCSessionExpirySource,
38+
} from './session-expiry';
3439

3540
const logger = Logger('oidc.visitor-auth');
3641

@@ -48,6 +53,7 @@ type OIDCSiteInstallationConfiguration = {
4853
logout_endpoint?: string;
4954
redirect_to_site_on_logout?: boolean;
5055
send_id_token_hint?: boolean;
56+
session_expiry_source?: OIDCSessionExpirySource;
5157
};
5258

5359
type OIDCState = OIDCSiteInstallationConfiguration;
@@ -63,12 +69,28 @@ type OIDCProps = {
6369

6470
export type OIDCAction = { action: 'save.config' };
6571

72+
/**
73+
* Successful response of the token endpoint.
74+
*
75+
* Spec: https://datatracker.ietf.org/doc/html/rfc6749#section-5.1 and
76+
* https://openid.net/specs/openid-connect-core-1_0.html#TokenResponse
77+
*
78+
* The response comes from the authentication provider, so even the fields the specs
79+
* mark as required are validated at runtime before being used.
80+
*/
6681
type OIDCTokenResponseData = {
67-
access_token?: string;
68-
id_token?: string;
82+
/** REQUIRED by OIDC Core section 3.1.3.3. */
83+
id_token: string;
84+
/** REQUIRED by RFC 6749 section 4.1.4. */
85+
access_token: string;
86+
/** REQUIRED by RFC 6749 section 4.1.4. Case-insensitive, in practice `Bearer`. */
87+
token_type: string;
88+
/** RECOMMENDED by RFC 6749 section 4.1.4: lifetime of the access token, in seconds. */
89+
expires_in?: number;
90+
/** OPTIONAL by RFC 6749 section 4.1.4. */
6991
refresh_token?: string;
70-
token_type: 'Bearer';
71-
expires_in: number;
92+
/** OPTIONAL by RFC 6749 section 4.1.4, REQUIRED when the granted scope differs from the requested one. */
93+
scope?: string;
7294
};
7395

7496
const getDomainWithHttps = (url: string): string => {
@@ -99,6 +121,9 @@ const configBlock = createComponent<OIDCProps, OIDCState, OIDCAction, OIDCRuntim
99121
redirect_to_site_on_logout:
100122
siteInstallation.configuration?.redirect_to_site_on_logout ?? false,
101123
send_id_token_hint: siteInstallation.configuration?.send_id_token_hint ?? false,
124+
session_expiry_source:
125+
siteInstallation.configuration?.session_expiry_source ??
126+
DEFAULT_SESSION_EXPIRY_SOURCE,
102127
};
103128
},
104129
action: async (element, action, context) => {
@@ -125,6 +150,8 @@ const configBlock = createComponent<OIDCProps, OIDCState, OIDCAction, OIDCRuntim
125150
: undefined,
126151
redirect_to_site_on_logout: element.state.redirect_to_site_on_logout ?? false,
127152
send_id_token_hint: element.state.send_id_token_hint ?? false,
153+
session_expiry_source:
154+
element.state.session_expiry_source ?? DEFAULT_SESSION_EXPIRY_SOURCE,
128155
};
129156
await api.integrations.updateIntegrationSiteInstallation(
130157
siteInstallation.integration,
@@ -266,6 +293,28 @@ const configBlock = createComponent<OIDCProps, OIDCState, OIDCAction, OIDCRuntim
266293
element={<switch state="use_pkce" />}
267294
/>
268295

296+
<input
297+
label="Session Expiry"
298+
hint={
299+
<text>
300+
The token whose expiry determines how long a visitor stays signed in to
301+
your site. The ID token uses its <text style="bold">exp</text> claim,
302+
the access token uses the <text style="bold">expires_in</text> of the
303+
token response. Sessions last at least 1 hour and never more than 7
304+
days.
305+
</text>
306+
}
307+
element={
308+
<select
309+
state="session_expiry_source"
310+
options={[
311+
{ id: 'id_token', label: 'ID token (default)' },
312+
{ id: 'access_token', label: 'Access token' },
313+
]}
314+
/>
315+
}
316+
/>
317+
269318
<input
270319
label="End Session Endpoint"
271320
hint={
@@ -687,12 +736,13 @@ const handleFetchEvent: FetchEventCallback<OIDCRuntimeContext> = async (request,
687736
});
688737
}
689738

690-
const minimumExp = Math.floor(Date.now() / 1000) + 60 * 60;
691-
const upstreamTokenExp =
692-
typeof decodedIdToken?.payload?.exp === 'number'
693-
? decodedIdToken.payload.exp
694-
: undefined;
695-
const sessionExp = Math.max(minimumExp, upstreamTokenExp ?? 0);
739+
const sessionExp = computeSessionExpiry({
740+
source:
741+
siteInstallation.configuration.session_expiry_source ??
742+
DEFAULT_SESSION_EXPIRY_SOURCE,
743+
idTokenExp: decodedIdToken?.payload?.exp,
744+
accessTokenExpiresIn: tokenRespData.expires_in,
745+
});
696746

697747
let jwtToken: string | undefined;
698748
try {
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import { Logger } from '@gitbook/runtime';
2+
3+
/**
4+
* Derivation of the GitBook session token expiry from the tokens returned by the
5+
* upstream authentication provider.
6+
*/
7+
8+
const logger = Logger('oidc.session-expiry');
9+
10+
/**
11+
* Which of the tokens returned by the authentication provider drives the expiry of
12+
* the GitBook session. Defaults to the ID token, matching the behaviour of the
13+
* integration before this option existed.
14+
*/
15+
export type OIDCSessionExpirySource = 'id_token' | 'access_token';
16+
17+
export const DEFAULT_SESSION_EXPIRY_SOURCE: OIDCSessionExpirySource = 'id_token';
18+
19+
/** Floor of the GitBook session lifetime, however short-lived the upstream token is. */
20+
export const MINIMUM_SESSION_DURATION_SECONDS = 60 * 60;
21+
22+
/**
23+
* Ceiling of the GitBook session lifetime. Visitors are re-checked against the
24+
* authentication provider at least once a week, whichever lifetime it hands out.
25+
*/
26+
export const MAXIMUM_SESSION_DURATION_SECONDS = 7 * 24 * 60 * 60;
27+
28+
/**
29+
* Derive the expiry of the GitBook session token from the upstream token the site
30+
* admin picked as the source of truth:
31+
*
32+
* - `id_token` (default): the `exp` claim of the ID token.
33+
* - `access_token`: the `expires_in` of the token response, counted from now.
34+
*
35+
* Either one can be missing or unusable, in which case the session falls back to the
36+
* minimum lifetime. The result is always clamped between the minimum and maximum
37+
* session durations.
38+
*/
39+
export function computeSessionExpiry(params: {
40+
source: OIDCSessionExpirySource;
41+
idTokenExp: unknown;
42+
accessTokenExpiresIn: unknown;
43+
}): number {
44+
const now = Math.floor(Date.now() / 1000);
45+
const minimumExp = now + MINIMUM_SESSION_DURATION_SECONDS;
46+
const maximumExp = now + MAXIMUM_SESSION_DURATION_SECONDS;
47+
48+
let upstreamExp: number | undefined;
49+
if (params.source === 'access_token') {
50+
const expiresIn = toPositiveNumber(params.accessTokenExpiresIn);
51+
upstreamExp = expiresIn !== undefined ? now + expiresIn : undefined;
52+
if (upstreamExp === undefined) {
53+
logger.info(
54+
'token response has no usable expires_in, falling back to the minimum session duration',
55+
);
56+
}
57+
} else {
58+
upstreamExp = toPositiveNumber(params.idTokenExp);
59+
}
60+
61+
return Math.min(maximumExp, Math.max(minimumExp, upstreamExp ?? 0));
62+
}
63+
64+
/**
65+
* Coerce a value coming from the authentication provider into a positive number.
66+
* Providers are known to send numeric fields as strings, so those are accepted too.
67+
*/
68+
export function toPositiveNumber(value: unknown): number | undefined {
69+
const parsed = typeof value === 'string' ? Number(value) : value;
70+
if (typeof parsed !== 'number' || !Number.isFinite(parsed) || parsed <= 0) {
71+
return undefined;
72+
}
73+
74+
return parsed;
75+
}
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
import { describe, expect, it } from 'bun:test';
2+
3+
import {
4+
computeSessionExpiry,
5+
MAXIMUM_SESSION_DURATION_SECONDS,
6+
MINIMUM_SESSION_DURATION_SECONDS,
7+
toPositiveNumber,
8+
} from '../src/session-expiry';
9+
10+
const now = () => Math.floor(Date.now() / 1000);
11+
12+
/** The expiry is computed against a clock read inside the function, so allow a little drift. */
13+
const expectCloseTo = (actual: number, expected: number) => {
14+
expect(Math.abs(actual - expected)).toBeLessThanOrEqual(2);
15+
};
16+
17+
describe('computeSessionExpiry', () => {
18+
describe('with the ID token as the source', () => {
19+
it('uses the exp claim of the ID token', () => {
20+
const idTokenExp = now() + 3 * 60 * 60;
21+
expectCloseTo(
22+
computeSessionExpiry({
23+
source: 'id_token',
24+
idTokenExp,
25+
accessTokenExpiresIn: 60,
26+
}),
27+
idTokenExp,
28+
);
29+
});
30+
31+
it('ignores the expires_in of the token response', () => {
32+
const idTokenExp = now() + 3 * 60 * 60;
33+
expectCloseTo(
34+
computeSessionExpiry({
35+
source: 'id_token',
36+
idTokenExp,
37+
accessTokenExpiresIn: MAXIMUM_SESSION_DURATION_SECONDS,
38+
}),
39+
idTokenExp,
40+
);
41+
});
42+
43+
it('falls back to the minimum duration when the exp claim is missing', () => {
44+
expectCloseTo(
45+
computeSessionExpiry({
46+
source: 'id_token',
47+
idTokenExp: undefined,
48+
accessTokenExpiresIn: undefined,
49+
}),
50+
now() + MINIMUM_SESSION_DURATION_SECONDS,
51+
);
52+
});
53+
54+
it('raises a short-lived ID token up to the minimum duration', () => {
55+
expectCloseTo(
56+
computeSessionExpiry({
57+
source: 'id_token',
58+
idTokenExp: now() + 60,
59+
accessTokenExpiresIn: undefined,
60+
}),
61+
now() + MINIMUM_SESSION_DURATION_SECONDS,
62+
);
63+
});
64+
65+
it('caps a long-lived ID token at the maximum duration', () => {
66+
expectCloseTo(
67+
computeSessionExpiry({
68+
source: 'id_token',
69+
idTokenExp: now() + 365 * 24 * 60 * 60,
70+
accessTokenExpiresIn: undefined,
71+
}),
72+
now() + MAXIMUM_SESSION_DURATION_SECONDS,
73+
);
74+
});
75+
});
76+
77+
describe('with the access token as the source', () => {
78+
it('counts expires_in from now', () => {
79+
const expiresIn = 3 * 60 * 60;
80+
expectCloseTo(
81+
computeSessionExpiry({
82+
source: 'access_token',
83+
idTokenExp: undefined,
84+
accessTokenExpiresIn: expiresIn,
85+
}),
86+
now() + expiresIn,
87+
);
88+
});
89+
90+
it('ignores the exp claim of the ID token', () => {
91+
const expiresIn = 3 * 60 * 60;
92+
expectCloseTo(
93+
computeSessionExpiry({
94+
source: 'access_token',
95+
idTokenExp: now() + MAXIMUM_SESSION_DURATION_SECONDS,
96+
accessTokenExpiresIn: expiresIn,
97+
}),
98+
now() + expiresIn,
99+
);
100+
});
101+
102+
it('accepts expires_in sent as a string', () => {
103+
expectCloseTo(
104+
computeSessionExpiry({
105+
source: 'access_token',
106+
idTokenExp: undefined,
107+
accessTokenExpiresIn: '7200',
108+
}),
109+
now() + 7200,
110+
);
111+
});
112+
113+
it('falls back to the minimum duration when expires_in is absent', () => {
114+
expectCloseTo(
115+
computeSessionExpiry({
116+
source: 'access_token',
117+
idTokenExp: now() + 3 * 60 * 60,
118+
accessTokenExpiresIn: undefined,
119+
}),
120+
now() + MINIMUM_SESSION_DURATION_SECONDS,
121+
);
122+
});
123+
124+
it('falls back to the minimum duration when expires_in is not a usable number', () => {
125+
for (const expiresIn of [0, -60, 'soon', Number.NaN, null, {}]) {
126+
expectCloseTo(
127+
computeSessionExpiry({
128+
source: 'access_token',
129+
idTokenExp: undefined,
130+
accessTokenExpiresIn: expiresIn,
131+
}),
132+
now() + MINIMUM_SESSION_DURATION_SECONDS,
133+
);
134+
}
135+
});
136+
137+
it('raises a short-lived access token up to the minimum duration', () => {
138+
expectCloseTo(
139+
computeSessionExpiry({
140+
source: 'access_token',
141+
idTokenExp: undefined,
142+
accessTokenExpiresIn: 300,
143+
}),
144+
now() + MINIMUM_SESSION_DURATION_SECONDS,
145+
);
146+
});
147+
148+
it('caps a long-lived access token at the maximum duration', () => {
149+
expectCloseTo(
150+
computeSessionExpiry({
151+
source: 'access_token',
152+
idTokenExp: undefined,
153+
accessTokenExpiresIn: 30 * 24 * 60 * 60,
154+
}),
155+
now() + MAXIMUM_SESSION_DURATION_SECONDS,
156+
);
157+
});
158+
});
159+
});
160+
161+
describe('toPositiveNumber', () => {
162+
it('accepts positive numbers and numeric strings', () => {
163+
expect(toPositiveNumber(3600)).toBe(3600);
164+
expect(toPositiveNumber('3600')).toBe(3600);
165+
expect(toPositiveNumber(0.5)).toBe(0.5);
166+
});
167+
168+
it('rejects anything that is not a usable positive number', () => {
169+
for (const value of [
170+
0,
171+
'0',
172+
-1,
173+
'-1',
174+
'',
175+
' ',
176+
'abc',
177+
Number.NaN,
178+
Number.POSITIVE_INFINITY,
179+
null,
180+
undefined,
181+
{},
182+
[],
183+
]) {
184+
expect(toPositiveNumber(value)).toBeUndefined();
185+
}
186+
});
187+
});

0 commit comments

Comments
 (0)