Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved session token validation #22353

Merged
merged 8 commits into from
May 2, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/late-lions-pump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---

Check warning on line 1 in .changeset/late-lions-pump.md

View workflow job for this annotation

GitHub Actions / Lint

File ignored by default.
"@directus/api": patch
---

Improved session token validation
5 changes: 5 additions & 0 deletions api/src/utils/get-accountability-for-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { InvalidCredentialsError } from '@directus/errors';
import type { Accountability } from '@directus/types';
import getDatabase from '../database/index.js';
import isDirectusJWT from './is-directus-jwt.js';
import { verifySessionJWT } from './verify-session-jwt.js';
import { verifyAccessJWT } from './jwt.js';

export async function getAccountabilityForToken(
Expand All @@ -24,6 +25,10 @@ export async function getAccountabilityForToken(
if (isDirectusJWT(token)) {
const payload = verifyAccessJWT(token, env['SECRET'] as string);

if ('session' in payload) {
await verifySessionJWT(payload);
}

accountability.role = payload.role;
accountability.admin = payload.admin_access === true || payload.admin_access == 1;
accountability.app = payload.app_access === true || payload.app_access == 1;
Expand Down
21 changes: 21 additions & 0 deletions api/src/utils/verify-session-jwt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import getDatabase from '../database/index.js';
import { InvalidTokenError } from '@directus/errors';
import type { DirectusTokenPayload } from '../types/index.js';

export async function verifySessionJWT(payload: DirectusTokenPayload) {
br41nslug marked this conversation as resolved.
Show resolved Hide resolved
const database = getDatabase();

const session = await database
.select('token', 'user', 'expires', 'ip')
br41nslug marked this conversation as resolved.
Show resolved Hide resolved
.from('directus_sessions')
.where({
token: payload['session'],
user: payload['id'],
})
.andWhere('expires', '>=', new Date())
.first();

if (!session) {
throw new InvalidTokenError();
}
}