Skip to content

Commit fab1ea5

Browse files
fix(user-management): Reject non-user access tokens in session cookies (#1753)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent fbb9a06 commit fab1ea5

4 files changed

Lines changed: 146 additions & 69 deletions

File tree

‎src/user-management/session.spec.ts‎

Lines changed: 69 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,27 @@ jest.mock('jose', () => ({
2020
jwtVerify: jest.fn(),
2121
}));
2222

23+
const verifiedUserAccessToken = {
24+
payload: {
25+
iss: 'https://api.workos.com/user_management/client_123',
26+
sub: 'user_01H5JQDV7R7ATEYZDEG0W5PRYS',
27+
sid: 'session_123',
28+
exp: 1735684500,
29+
iat: 1735683600,
30+
auth_time: 1735683600,
31+
},
32+
} as unknown as jose.JWTVerifyResult & jose.ResolvedKey;
33+
34+
function verifiedAccessToken(accessToken: string) {
35+
return {
36+
...verifiedUserAccessToken,
37+
payload: {
38+
...verifiedUserAccessToken.payload,
39+
...jose.decodeJwt(accessToken),
40+
},
41+
};
42+
}
43+
2344
describe('Session', () => {
2445
let workos: WorkOS;
2546

@@ -117,16 +138,56 @@ describe('Session', () => {
117138
});
118139
});
119140

120-
it('returns a successful response if the sessionData is valid', async () => {
121-
jest
122-
.mocked(jose.jwtVerify)
123-
.mockResolvedValue({} as jose.JWTVerifyResult & jose.ResolvedKey);
141+
it.each([
142+
[
143+
'an agent access token',
144+
{ sub: 'agent_01H5JQDV7R7ATEYZDEG0W5PRYS', sub_profile: 'ai_agent' },
145+
],
146+
['a widget session token', { sub_type: 'authkit' }],
147+
])(
148+
'returns a failed response if the accessToken is %s',
149+
async (_family, familyClaims) => {
150+
jest.mocked(jose.jwtVerify).mockResolvedValue({
151+
...verifiedUserAccessToken,
152+
payload: { ...verifiedUserAccessToken.payload, ...familyClaims },
153+
});
154+
155+
const cookiePassword = 'alongcookiesecretmadefortestingsessions';
156+
const sessionData = await sealData(
157+
{
158+
accessToken: 'abc123',
159+
refreshToken: 'def456',
160+
user: {
161+
object: 'user',
162+
id: 'user_01H5JQDV7R7ATEYZDEG0W5PRYS',
163+
email: 'test@example.com',
164+
},
165+
},
166+
{ password: cookiePassword },
167+
);
168+
169+
const session = workos.userManagement.loadSealedSession({
170+
sessionData,
171+
cookiePassword,
172+
});
173+
174+
await expect(session.authenticate()).resolves.toEqual({
175+
authenticated: false,
176+
reason: 'invalid_jwt',
177+
});
178+
},
179+
);
124180

181+
it('returns a successful response if the sessionData is valid', async () => {
125182
const cookiePassword = 'alongcookiesecretmadefortestingsessions';
126183

127184
const accessToken =
128185
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdXRoZW50aWNhdGVkIjp0cnVlLCJpbXBlcnNvbmF0b3IiOnsiZW1haWwiOiJhZG1pbkBleGFtcGxlLmNvbSIsInJlYXNvbiI6InRlc3QifSwic2lkIjoic2Vzc2lvbl8xMjMiLCJvcmdfaWQiOiJvcmdfMTIzIiwicm9sZSI6Im1lbWJlciIsInJvbGVzIjpbIm1lbWJlciIsImFkbWluIl0sInBlcm1pc3Npb25zIjpbInBvc3RzOmNyZWF0ZSIsInBvc3RzOmRlbGV0ZSJdLCJlbnRpdGxlbWVudHMiOlsiYXVkaXQtbG9ncyJdLCJmZWF0dXJlX2ZsYWdzIjpbImRhcmstbW9kZSIsImJldGEtZmVhdHVyZXMiXSwidXNlciI6eyJvYmplY3QiOiJ1c2VyIiwiaWQiOiJ1c2VyXzAxSDVKUURWN1I3QVRFWVpERUcwVzVQUllTIiwiZW1haWwiOiJ0ZXN0QGV4YW1wbGUuY29tIn19.TNUzJYn6lzLWFFsiWiKEgIshyUs-bKJQf1VxwNr1cGI';
129186

187+
jest
188+
.mocked(jose.jwtVerify)
189+
.mockResolvedValue(verifiedAccessToken(accessToken));
190+
130191
const sessionData = await sealData(
131192
{
132193
accessToken,
@@ -202,7 +263,7 @@ describe('Session', () => {
202263
jest
203264
.mocked(jose.jwtVerify)
204265
.mockReset()
205-
.mockResolvedValue({} as jose.JWTVerifyResult & jose.ResolvedKey);
266+
.mockResolvedValue(verifiedUserAccessToken);
206267
});
207268

208269
it('does not validate the issuer claim by default', async () => {
@@ -672,9 +733,7 @@ describe('Session', () => {
672733
refreshToken,
673734
});
674735

675-
jest
676-
.mocked(jose.jwtVerify)
677-
.mockResolvedValue({} as jose.JWTVerifyResult & jose.ResolvedKey);
736+
jest.mocked(jose.jwtVerify).mockResolvedValue(verifiedUserAccessToken);
678737

679738
const cookiePassword = 'alongcookiesecretmadefortestingsessions';
680739

@@ -761,9 +820,7 @@ describe('Session', () => {
761820

762821
describe('getLogoutUrl', () => {
763822
it('returns a logout URL for the user', async () => {
764-
jest
765-
.mocked(jose.jwtVerify)
766-
.mockResolvedValue({} as jose.JWTVerifyResult & jose.ResolvedKey);
823+
jest.mocked(jose.jwtVerify).mockResolvedValue(verifiedUserAccessToken);
767824

768825
const cookiePassword = 'alongcookiesecretmadefortestingsessions';
769826

@@ -806,9 +863,7 @@ describe('Session', () => {
806863

807864
describe('when a returnTo URL is provided', () => {
808865
it('returns a logout URL for the user', async () => {
809-
jest
810-
.mocked(jose.jwtVerify)
811-
.mockResolvedValue({} as jose.JWTVerifyResult & jose.ResolvedKey);
866+
jest.mocked(jose.jwtVerify).mockResolvedValue(verifiedUserAccessToken);
812867

813868
const cookiePassword = 'alongcookiesecretmadefortestingsessions';
814869

‎src/user-management/session.ts‎

Lines changed: 6 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -78,15 +78,17 @@ export class CookieSession {
7878
};
7979
}
8080

81-
if (!(await this.isValidJwt(session.accessToken))) {
81+
const claims = await this.userManagement.verifyAccessToken(
82+
session.accessToken,
83+
);
84+
85+
if (!claims) {
8286
return {
8387
authenticated: false,
8488
reason: AuthenticateWithSessionCookieFailureReason.INVALID_JWT,
8589
};
8690
}
8791

88-
const { decodeJwt } = await getJose();
89-
9092
const {
9193
sid: sessionId,
9294
org_id: organizationId,
@@ -95,7 +97,7 @@ export class CookieSession {
9597
permissions,
9698
entitlements,
9799
feature_flags: featureFlags,
98-
} = decodeJwt<UserManagementAccessToken>(session.accessToken);
100+
} = claims;
99101

100102
return {
101103
authenticated: true,
@@ -242,34 +244,6 @@ export class CookieSession {
242244
returnTo,
243245
});
244246
}
245-
246-
private async isValidJwt(accessToken: string): Promise<boolean> {
247-
const { jwtVerify } = await getJose();
248-
const jwks = await this.userManagement.getJWKS();
249-
if (!jwks) {
250-
throw new Error(
251-
'Missing client ID. Did you provide it when initializing WorkOS?',
252-
);
253-
}
254-
255-
const { issuer } = this.userManagement;
256-
try {
257-
await jwtVerify(accessToken, jwks, issuer ? { issuer } : undefined);
258-
return true;
259-
} catch (e) {
260-
// Only treat as invalid JWT if it's an actual JWT/JWS error from jose
261-
// Network errors, crypto failures, etc. should propagate
262-
if (
263-
e instanceof Error &&
264-
'code' in e &&
265-
typeof e.code === 'string' &&
266-
(e.code.startsWith('ERR_JWT_') || e.code.startsWith('ERR_JWS_'))
267-
) {
268-
return false;
269-
}
270-
throw e;
271-
}
272-
}
273247
}
274248

275249
/**

‎src/user-management/user-management.spec.ts‎

Lines changed: 67 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,27 @@ jest.mock('jose', () => ({
3636
createRemoteJWKSet: jest.fn(),
3737
}));
3838

39+
const verifiedUserAccessToken = {
40+
payload: {
41+
iss: 'https://api.workos.com/user_management/client_123',
42+
sub: 'user_01H5JQDV7R7ATEYZDEG0W5PRYS',
43+
sid: 'session_123',
44+
exp: 1735684500,
45+
iat: 1735683600,
46+
auth_time: 1735683600,
47+
},
48+
} as unknown as jose.JWTVerifyResult & jose.ResolvedKey;
49+
50+
function verifiedAccessToken(accessToken: string) {
51+
return {
52+
...verifiedUserAccessToken,
53+
payload: {
54+
...verifiedUserAccessToken.payload,
55+
...jose.decodeJwt(accessToken),
56+
},
57+
};
58+
}
59+
3960
const userId = 'user_01H5JQDV7R7ATEYZDEG0W5PRYS';
4061
const organizationMembershipId = 'om_01H5JQDV7R7ATEYZDEG0W5PRYS';
4162
const emailVerificationId = 'email_verification_01H5JQDV7R7ATEYZDEG0W5PRYS';
@@ -1614,6 +1635,43 @@ describe('UserManagement', () => {
16141635
).resolves.toEqual({ authenticated: false, reason: 'invalid_jwt' });
16151636
});
16161637

1638+
it.each([
1639+
[
1640+
'an agent access token',
1641+
{ sub: 'agent_01H5JQDV7R7ATEYZDEG0W5PRYS', sub_profile: 'ai_agent' },
1642+
],
1643+
['a widget session token', { sub_type: 'authkit' }],
1644+
])(
1645+
'returns authenticated = false when the JWT is %s',
1646+
async (_family, familyClaims) => {
1647+
jest.mocked(jose.jwtVerify).mockResolvedValue({
1648+
...verifiedUserAccessToken,
1649+
payload: { ...verifiedUserAccessToken.payload, ...familyClaims },
1650+
});
1651+
1652+
const cookiePassword = 'alongcookiesecretmadefortestingsessions';
1653+
const sessionData = await sealData(
1654+
{
1655+
accessToken: 'abc123',
1656+
refreshToken: 'def456',
1657+
user: {
1658+
object: 'user',
1659+
id: 'user_01H5JQDV7R7ATEYZDEG0W5PRYS',
1660+
email: 'test@example.com',
1661+
},
1662+
},
1663+
{ password: cookiePassword },
1664+
);
1665+
1666+
await expect(
1667+
workos.userManagement.authenticateWithSessionCookie({
1668+
sessionData,
1669+
cookiePassword,
1670+
}),
1671+
).resolves.toEqual({ authenticated: false, reason: 'invalid_jwt' });
1672+
},
1673+
);
1674+
16171675
it('rethrows non-JWT errors (e.g., network failures)', async () => {
16181676
jest.mocked(jose.jwtVerify).mockImplementationOnce(() => {
16191677
// Simulate a network error (no jose error code)
@@ -1643,14 +1701,14 @@ describe('UserManagement', () => {
16431701
});
16441702

16451703
it('returns the JWT claims when provided a valid JWT', async () => {
1646-
jest
1647-
.mocked(jose.jwtVerify)
1648-
.mockResolvedValue({} as jose.JWTVerifyResult & jose.ResolvedKey);
1649-
16501704
const cookiePassword = 'alongcookiesecretmadefortestingsessions';
16511705
const accessToken =
16521706
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdXRoZW50aWNhdGVkIjp0cnVlLCJpbXBlcnNvbmF0b3IiOnsiZW1haWwiOiJhZG1pbkBleGFtcGxlLmNvbSIsInJlYXNvbiI6InRlc3QifSwic2lkIjoic2Vzc2lvbl8xMjMiLCJvcmdfaWQiOiJvcmdfMTIzIiwicm9sZSI6Im1lbWJlciIsInBlcm1pc3Npb25zIjpbInBvc3RzOmNyZWF0ZSIsInBvc3RzOmRlbGV0ZSJdLCJlbnRpdGxlbWVudHMiOlsiYXVkaXQtbG9ncyJdLCJmZWF0dXJlX2ZsYWdzIjpbImRhcmstbW9kZSIsImJldGEtZmVhdHVyZXMiXSwidXNlciI6eyJvYmplY3QiOiJ1c2VyIiwiaWQiOiJ1c2VyXzAxSDVKUURWN1I3QVRFWVpERUcwVzVQUllTIiwiZW1haWwiOiJ0ZXN0QGV4YW1wbGUuY29tIn19.YVNjR8S2xGn2jAoLuEcBQNJ1_xY3OzjRE1-BK0zjfQE';
16531707

1708+
jest
1709+
.mocked(jose.jwtVerify)
1710+
.mockResolvedValue(verifiedAccessToken(accessToken));
1711+
16541712
const sessionData = await sealData(
16551713
{
16561714
accessToken,
@@ -1685,14 +1743,14 @@ describe('UserManagement', () => {
16851743
});
16861744

16871745
it('returns the JWT claims when provided a valid JWT with multiple roles', async () => {
1688-
jest
1689-
.mocked(jose.jwtVerify)
1690-
.mockResolvedValue({} as jose.JWTVerifyResult & jose.ResolvedKey);
1691-
16921746
const cookiePassword = 'alongcookiesecretmadefortestingsessions';
16931747
const accessToken =
16941748
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdXRoZW50aWNhdGVkIjp0cnVlLCJpbXBlcnNvbmF0b3IiOnsiZW1haWwiOiJhZG1pbkBleGFtcGxlLmNvbSIsInJlYXNvbiI6InRlc3QifSwic2lkIjoic2Vzc2lvbl8xMjMiLCJvcmdfaWQiOiJvcmdfMTIzIiwicm9sZSI6ImFkbWluIiwicm9sZXMiOlsiYWRtaW4iLCJtZW1iZXIiXSwicGVybWlzc2lvbnMiOlsicG9zdHM6Y3JlYXRlIiwicG9zdHM6ZGVsZXRlIl0sImVudGl0bGVtZW50cyI6WyJhdWRpdC1sb2dzIl0sImZlYXR1cmVfZmxhZ3MiOlsiZGFyay1tb2RlIiwiYmV0YS1mZWF0dXJlcyJdLCJ1c2VyIjp7Im9iamVjdCI6InVzZXIiLCJpZCI6InVzZXJfMDFINUpRRFY3UjdBVEVZWkRFRzBXNVBSWVMiLCJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20ifX0.hsMptIB7PmbF5pxxtgTtCdUyOAhA11ZIAP-JY5zU5fE';
16951749

1750+
jest
1751+
.mocked(jose.jwtVerify)
1752+
.mockResolvedValue(verifiedAccessToken(accessToken));
1753+
16961754
const sessionData = await sealData(
16971755
{
16981756
accessToken,
@@ -1752,7 +1810,7 @@ describe('UserManagement', () => {
17521810
jest
17531811
.mocked(jose.jwtVerify)
17541812
.mockReset()
1755-
.mockResolvedValue({} as jose.JWTVerifyResult & jose.ResolvedKey);
1813+
.mockResolvedValue(verifiedUserAccessToken);
17561814
});
17571815

17581816
it('does not validate the issuer claim by default', async () => {

‎src/user-management/user-management.ts‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -689,14 +689,6 @@ export class UserManagement {
689689
throw new Error('Cookie password is required');
690690
}
691691

692-
const jwks = await this.getJWKS();
693-
694-
if (!jwks) {
695-
throw new Error('Must provide clientId to initialize JWKS');
696-
}
697-
698-
const { decodeJwt } = await getJose();
699-
700692
if (!sessionData) {
701693
return {
702694
authenticated: false,
@@ -719,7 +711,9 @@ export class UserManagement {
719711
};
720712
}
721713

722-
if (!(await this.isValidJwt(session.accessToken))) {
714+
const claims = await this.verifyAccessToken(session.accessToken);
715+
716+
if (!claims) {
723717
return {
724718
authenticated: false,
725719
reason: AuthenticateWithSessionCookieFailureReason.INVALID_JWT,
@@ -734,7 +728,7 @@ export class UserManagement {
734728
permissions,
735729
entitlements,
736730
feature_flags: featureFlags,
737-
} = decodeJwt<UserManagementAccessToken>(session.accessToken);
731+
} = claims;
738732

739733
return {
740734
authenticated: true,
@@ -867,10 +861,6 @@ export class UserManagement {
867861
);
868862
}
869863

870-
private async isValidJwt(accessToken: string): Promise<boolean> {
871-
return (await this.verifyJwt(accessToken)) !== null;
872-
}
873-
874864
private async prepareAuthenticationResponse({
875865
authenticationResponse,
876866
session,

0 commit comments

Comments
 (0)