Repository navigation
feat(api): add personal API keys per user #3624
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
base: develop
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,12 +5,17 @@ import type { | |
| PermissionCheckOptions, | ||
| } from '@server/lib/permissions'; | ||
| import { getSettings } from '@server/lib/settings'; | ||
| import { createHash } from 'crypto'; | ||
|
|
||
| export const hashApiKey = (apiKey: string) => | ||
| createHash('sha256').update(apiKey).digest('hex'); | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Pretty sure the CodeQL alert is a false positive. The key is 32 random bytes, not a password someone picked, so a slow hash doesn't add much here. It's also already stricter than how the main API key and Plex/Jellyfin tokens are stored, which is plaintext. That said, I'll defer to you all on how to handle it. If you'd rather satisfy the check, I can switch the key format to |
||
|
|
||
| export const checkUser: Middleware = async (req, _res, next) => { | ||
| const settings = getSettings(); | ||
| let user: User | undefined | null; | ||
| const apiKey = req.header('X-API-Key'); | ||
|
|
||
| if (req.header('X-API-Key') === settings.main.apiKey) { | ||
| if (apiKey === settings.main.apiKey) { | ||
| const userRepository = getRepository(User); | ||
|
|
||
| let userId = 1; // Work on original administrator account | ||
|
|
@@ -21,7 +26,13 @@ export const checkUser: Middleware = async (req, _res, next) => { | |
| } | ||
|
|
||
| user = await userRepository.findOne({ where: { id: userId } }); | ||
| } else if (req.session?.userId) { | ||
| } else if (apiKey) { | ||
| user = await getRepository(User).findOne({ | ||
| where: { settings: { apiKeyHash: hashApiKey(apiKey) } }, | ||
| }); | ||
| } | ||
|
|
||
| if (!user && apiKey !== settings.main.apiKey && req.session?.userId) { | ||
| const userRepository = getRepository(User); | ||
|
|
||
| user = await userRepository.findOne({ | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import type { MigrationInterface, QueryRunner } from 'typeorm'; | ||
|
|
||
| export class AddUserApiKeyHash1792348651934 implements MigrationInterface { | ||
| name = 'AddUserApiKeyHash1792348651934'; | ||
|
|
||
| public async up(queryRunner: QueryRunner): Promise<void> { | ||
| await queryRunner.query( | ||
| `ALTER TABLE "user_settings" ADD "apiKeyHash" varchar` | ||
| ); | ||
| await queryRunner.query( | ||
| `CREATE UNIQUE INDEX "IDX_fa5a2d13c60c9ec6f04637de8e" ON "user_settings" ("apiKeyHash") ` | ||
| ); | ||
| } | ||
|
|
||
| public async down(queryRunner: QueryRunner): Promise<void> { | ||
| await queryRunner.query(`DROP INDEX "IDX_fa5a2d13c60c9ec6f04637de8e"`); | ||
| await queryRunner.query( | ||
| `ALTER TABLE "user_settings" DROP COLUMN "apiKeyHash"` | ||
| ); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import type { MigrationInterface, QueryRunner } from 'typeorm'; | ||
|
|
||
| export class AddUserApiKeyHash1792348646818 implements MigrationInterface { | ||
| name = 'AddUserApiKeyHash1792348646818'; | ||
|
|
||
| public async up(queryRunner: QueryRunner): Promise<void> { | ||
| await queryRunner.query( | ||
| `ALTER TABLE "user_settings" ADD "apiKeyHash" varchar` | ||
| ); | ||
| await queryRunner.query( | ||
| `CREATE UNIQUE INDEX "IDX_fa5a2d13c60c9ec6f04637de8e" ON "user_settings" ("apiKeyHash") ` | ||
| ); | ||
| } | ||
|
|
||
| public async down(queryRunner: QueryRunner): Promise<void> { | ||
| await queryRunner.query(`DROP INDEX "IDX_fa5a2d13c60c9ec6f04637de8e"`); | ||
| await queryRunner.query( | ||
| `ALTER TABLE "user_settings" DROP COLUMN "apiKeyHash"` | ||
| ); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -13,17 +13,18 @@ import type { | |
| import { Permission } from '@server/lib/permissions'; | ||
| import { getSettings } from '@server/lib/settings'; | ||
| import logger from '@server/logger'; | ||
| import { isAuthenticated } from '@server/middleware/auth'; | ||
| import { hashApiKey, isAuthenticated } from '@server/middleware/auth'; | ||
| import { quickConnectSecret } from '@server/routes/auth'; | ||
| import { ApiError } from '@server/types/error'; | ||
| import { getHostname } from '@server/utils/getHostname'; | ||
| import { | ||
| isOwnProfile, | ||
| isOwnProfileOrAdmin, | ||
| } from '@server/utils/profileMiddleware'; | ||
| import { randomBytes } from 'crypto'; | ||
| import { Router } from 'express'; | ||
| import net from 'net'; | ||
| import { Not } from 'typeorm'; | ||
| import { IsNull, Not } from 'typeorm'; | ||
| import { canMakePermissionsChange, canModifyUser } from '.'; | ||
|
|
||
| const userSettingsRoutes = Router({ mergeParams: true }); | ||
|
|
@@ -168,6 +169,57 @@ userSettingsRoutes.post< | |
| } | ||
| }); | ||
|
|
||
| const setApiKeyHash = async (user: User, apiKeyHash: string | null) => { | ||
| user.settings ??= new UserSettings({ user }); | ||
| user.settings.apiKeyHash = apiKeyHash; | ||
| await getRepository(User).save(user); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Keep the API key write from saving the authenticated
Write only the
|
||
| }; | ||
|
|
||
| userSettingsRoutes.get<{ id: string }, { hasApiKey: boolean }>( | ||
| '/api-key', | ||
| isOwnProfile(), | ||
| async (req, res, next) => { | ||
| try { | ||
| const hasApiKey = await getRepository(UserSettings).exists({ | ||
| where: { | ||
| user: { id: Number(req.params.id) }, | ||
| apiKeyHash: Not(IsNull()), | ||
| }, | ||
| }); | ||
| return res.status(200).json({ hasApiKey }); | ||
| } catch (e) { | ||
| next({ status: 500, message: e.message }); | ||
| } | ||
| } | ||
| ); | ||
|
|
||
| userSettingsRoutes.post<{ id: string }, { apiKey: string }>( | ||
| '/api-key', | ||
| isOwnProfile(), | ||
| async (req, res, next) => { | ||
| const apiKey = randomBytes(32).toString('base64url'); | ||
| try { | ||
| await setApiKeyHash(req.user as User, hashApiKey(apiKey)); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Make the key-authenticated rotation write conditional on the key still being active. A Limit the write to the case where the stored hash still matches the hash of the key that authenticated the request. If no row is updated, return an error and do not return the new key. Keep session-authenticated generation and rotation unchanged.
|
||
| return res.status(200).json({ apiKey }); | ||
| } catch (e) { | ||
| next({ status: 500, message: e.message }); | ||
| } | ||
| } | ||
| ); | ||
|
|
||
| userSettingsRoutes.delete<{ id: string }>( | ||
| '/api-key', | ||
| isOwnProfile(), | ||
| async (req, res, next) => { | ||
| try { | ||
| await setApiKeyHash(req.user as User, null); | ||
| return res.status(204).send(); | ||
| } catch (e) { | ||
| next({ status: 500, message: e.message }); | ||
| } | ||
| } | ||
| ); | ||
|
|
||
| userSettingsRoutes.get<{ id: string }, { hasPassword: boolean }>( | ||
| '/password', | ||
| isOwnProfileOrAdmin(), | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Document the 500 response for each personal API key operation.
The
GET,POST, andDELETEoperations on/user/{userId}/settings/api-keyeach return500when their handler fails. The spec lists only success responses, so clients cannot see this failure path. Add a500response to each operation.Suggested fix for GET
properties: hasApiKey: type: boolean + '500': + description: Failed to read the API key statusSuggested fix for POST
properties: apiKey: type: string + '500': + description: Failed to generate the API keySuggested fix for DELETE
responses: '204': description: API key revoked + '500': + description: Failed to revoke the API keyCheckov (3.3.30)
[high] 1-8384: Ensure that security operations is not empty.
(CKV_OPENAPI_5)