From fab43ac4ab99b635e88155dda7ed5f6f54d69480 Mon Sep 17 00:00:00 2001 From: Thodoris Greasidis Date: Thu, 30 May 2024 13:53:27 +0300 Subject: [PATCH] Require a freshly authenticated JWT when creating an api_key Change-type: major --- src/features/auth/hooks/index.ts | 1 + .../auth/hooks/restrict-api-key-creation.ts | 15 +++++++++++++++ 2 files changed, 16 insertions(+) create mode 100644 src/features/auth/hooks/restrict-api-key-creation.ts diff --git a/src/features/auth/hooks/index.ts b/src/features/auth/hooks/index.ts index 4af5c512f..bf644f49b 100644 --- a/src/features/auth/hooks/index.ts +++ b/src/features/auth/hooks/index.ts @@ -3,6 +3,7 @@ import './create-application-actor.js'; import './create-device-actor.js'; import './create-user-actor.js'; import './fetch-api-key.js'; +import './restrict-api-key-creation.js'; import './restrict-user-deletion.js'; import './update-jwt-secret.js'; import './validate-username-email.js'; diff --git a/src/features/auth/hooks/restrict-api-key-creation.ts b/src/features/auth/hooks/restrict-api-key-creation.ts new file mode 100644 index 000000000..8d54af63f --- /dev/null +++ b/src/features/auth/hooks/restrict-api-key-creation.ts @@ -0,0 +1,15 @@ +import { hooks, errors } from '@balena/pinejs'; + +import { getUser } from '../../../infra/auth/auth.js'; +import { checkSudoValidity } from '../../../infra/auth/jwt.js'; + +const { UnauthorizedError } = errors; + +hooks.addPureHook('POST', 'resin', 'api_key', { + PRERUN: async ({ req, tx }) => { + const user = await getUser(req, tx); + if (!(await checkSudoValidity(user))) { + throw new UnauthorizedError('Fresh authentication token required'); + } + }, +});