-
Notifications
You must be signed in to change notification settings - Fork 234
feat: add admin backend foundation (login, session, health) #641
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
Open
Ferryx349
wants to merge
5
commits into
cameri:main
Choose a base branch
from
Ferryx349:ADMIN-CONSOLE-1
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+988
−1
Open
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
84d5f93
feat(admin): add backend foundation (login, session, health)
Ferryx349 efcea03
fix(admin): handle missing SECRET and default ipWhitelist for rate li…
Ferryx349 867b788
fix(admin): rate limit request before checking if admin is enabled
Ferryx349 0c49d9d
refactor(admin): extract middleware and remove Phase 1 redundancies
Ferryx349 02d842a
Merge branch 'main' into ADMIN-CONSOLE-1
Ferryx349 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "nostream": minor | ||
| --- | ||
|
|
||
| feat: add disabled-by-default admin API with password auth, session, and health endpoints |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| import { Request, Response } from 'express' | ||
|
|
||
| export interface IAdminAuthProvider { | ||
| handleLogin(request: Request, response: Response): Promise<void> | ||
| isRequestAuthenticated(request: Request): boolean | ||
| getSessionExpiresAt(request: Request): number | undefined | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import { Request, Response } from 'express' | ||
|
|
||
| import { IAdminAuthProvider } from '../@types/admin' | ||
| import { Settings } from '../@types/settings' | ||
| import { adminLoginBodySchema } from '../schemas/admin-login-schema' | ||
| import { verifyAdminPasswordHash, verifyPlaintextPassword } from '../utils/admin-password' | ||
| import { | ||
| buildAdminSessionCookieHeader, | ||
| createAdminSessionToken, | ||
| getAdminSessionTokenFromRequest, | ||
| isValidAdminSessionToken, | ||
| parseAdminSessionToken, | ||
| resolveAdminSessionTtlSeconds, | ||
| } from '../utils/admin-session' | ||
| import { validateSchema } from '../utils/validation' | ||
|
|
||
| export class PasswordAdminAuthProvider implements IAdminAuthProvider { | ||
| public constructor(private readonly settings: () => Settings) {} | ||
|
|
||
| public async handleLogin(request: Request, response: Response): Promise<void> { | ||
| const validation = validateSchema(adminLoginBodySchema)(request.body) | ||
| if (validation.error) { | ||
| response.status(400).setHeader('content-type', 'application/json').send({ error: 'Invalid request' }) | ||
| return | ||
| } | ||
|
|
||
| if (!this.verifyPassword(validation.value.password)) { | ||
| response.status(401).setHeader('content-type', 'application/json').send({ error: 'Unauthorized' }) | ||
| return | ||
| } | ||
|
Ferryx349 marked this conversation as resolved.
|
||
|
|
||
| const currentSettings = this.settings() | ||
| const sessionTtlSeconds = resolveAdminSessionTtlSeconds(currentSettings.admin?.sessionTtlSeconds) | ||
| const expiresAt = Math.floor(Date.now() / 1000) + sessionTtlSeconds | ||
|
|
||
| try { | ||
| const token = createAdminSessionToken(expiresAt) | ||
|
|
||
| response | ||
| .status(200) | ||
| .setHeader('content-type', 'application/json') | ||
| .setHeader('Set-Cookie', buildAdminSessionCookieHeader(request, currentSettings, token, sessionTtlSeconds)) | ||
| .send({ authenticated: true, expiresAt }) | ||
| } catch { | ||
| response.status(500).setHeader('content-type', 'application/json').send({ error: 'Internal Server Error' }) | ||
| } | ||
| } | ||
|
Ferryx349 marked this conversation as resolved.
|
||
|
|
||
| public isRequestAuthenticated(request: Request): boolean { | ||
| const token = this.getToken(request) | ||
| return token ? isValidAdminSessionToken(token) : false | ||
| } | ||
|
|
||
| public getSessionExpiresAt(request: Request): number | undefined { | ||
| const token = this.getToken(request) | ||
| return token ? parseAdminSessionToken(token)?.expiresAt : undefined | ||
| } | ||
|
|
||
| private getToken(request: Request): string | undefined { | ||
| return getAdminSessionTokenFromRequest(request.headers.authorization, request.headers.cookie) | ||
| } | ||
|
|
||
| private verifyPassword(password: string): boolean { | ||
| const envPassword = process.env.ADMIN_PASSWORD | ||
| if (typeof envPassword === 'string' && envPassword.length > 0) { | ||
| return verifyPlaintextPassword(password, envPassword) | ||
| } | ||
|
|
||
| const passwordHash = this.settings().admin?.passwordHash | ||
| if (!passwordHash) { | ||
| return false | ||
| } | ||
|
|
||
| return verifyAdminPasswordHash(password, passwordHash) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| import { Request, Response } from 'express' | ||
|
|
||
| import { IController } from '../../@types/controllers' | ||
| import { collectAdminHealthSnapshot } from '../../utils/admin-health' | ||
|
|
||
| export class GetAdminHealthController implements IController { | ||
| public async handleRequest(_request: Request, response: Response): Promise<void> { | ||
| const health = await collectAdminHealthSnapshot() | ||
| response.status(200).setHeader('content-type', 'application/json').send(health) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| import { Request, Response } from 'express' | ||
|
|
||
| import { IAdminAuthProvider } from '../../@types/admin' | ||
| import { IController } from '../../@types/controllers' | ||
|
|
||
| export class GetAdminSessionController implements IController { | ||
| public constructor(private readonly authProvider: IAdminAuthProvider) {} | ||
|
|
||
| public async handleRequest(request: Request, response: Response): Promise<void> { | ||
| response.status(200).setHeader('content-type', 'application/json').send({ | ||
| authenticated: true, | ||
| expiresAt: this.authProvider.getSessionExpiresAt(request), | ||
| }) | ||
| } | ||
|
Ferryx349 marked this conversation as resolved.
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| import { Request, Response } from 'express' | ||
|
|
||
| import { IAdminAuthProvider } from '../../@types/admin' | ||
| import { IController } from '../../@types/controllers' | ||
|
|
||
| export class PostAdminLoginController implements IController { | ||
| public constructor(private readonly authProvider: IAdminAuthProvider) {} | ||
|
|
||
| public async handleRequest(request: Request, response: Response): Promise<void> { | ||
| await this.authProvider.handleLogin(request, response) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| import { PasswordAdminAuthProvider } from '../admin/password-admin-auth-provider' | ||
| import { IAdminAuthProvider } from '../@types/admin' | ||
| import { createSettings } from './settings-factory' | ||
|
|
||
| export const createAdminAuthProvider = (): IAdminAuthProvider => { | ||
| return new PasswordAdminAuthProvider(createSettings) | ||
| } |
6 changes: 6 additions & 0 deletions
6
src/factories/controllers/get-admin-health-controller-factory.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| import { GetAdminHealthController } from '../../controllers/admin/get-health-controller' | ||
| import { IController } from '../../@types/controllers' | ||
|
|
||
| export const createGetAdminHealthController = (): IController => { | ||
| return new GetAdminHealthController() | ||
| } |
7 changes: 7 additions & 0 deletions
7
src/factories/controllers/get-admin-session-controller-factory.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| import { GetAdminSessionController } from '../../controllers/admin/get-session-controller' | ||
| import { IController } from '../../@types/controllers' | ||
| import { createAdminAuthProvider } from '../admin-auth-provider-factory' | ||
|
|
||
| export const createGetAdminSessionController = (): IController => { | ||
| return new GetAdminSessionController(createAdminAuthProvider()) | ||
| } |
7 changes: 7 additions & 0 deletions
7
src/factories/controllers/post-admin-login-controller-factory.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| import { PostAdminLoginController } from '../../controllers/admin/post-login-controller' | ||
| import { IController } from '../../@types/controllers' | ||
| import { createAdminAuthProvider } from '../admin-auth-provider-factory' | ||
|
|
||
| export const createPostAdminLoginController = (): IController => { | ||
| return new PostAdminLoginController(createAdminAuthProvider()) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| import { NextFunction, Request, Response } from 'express' | ||
|
|
||
| import { createAdminAuthProvider } from '../../factories/admin-auth-provider-factory' | ||
|
|
||
| const adminAuthProvider = createAdminAuthProvider() | ||
|
|
||
| export const adminAuthMiddleware = (request: Request, response: Response, next: NextFunction) => { | ||
| try { | ||
| if (!adminAuthProvider.isRequestAuthenticated(request)) { | ||
| response.status(401).setHeader('content-type', 'application/json').send({ error: 'Unauthorized' }) | ||
| return | ||
| } | ||
| } catch { | ||
| response.status(500).setHeader('content-type', 'application/json').send({ error: 'Internal Server Error' }) | ||
| return | ||
| } | ||
|
|
||
| next() | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| import { NextFunction, Request, Response } from 'express' | ||
|
|
||
| import { createSettings } from '../../factories/settings-factory' | ||
|
|
||
| export const adminEnabledMiddleware = (_request: Request, response: Response, next: NextFunction) => { | ||
| if (!createSettings().admin?.enabled) { | ||
| response.status(404).setHeader('content-type', 'text/plain').send('Not Found') | ||
| return | ||
| } | ||
|
|
||
| next() | ||
| } |
25 changes: 25 additions & 0 deletions
25
src/handlers/request-handlers/admin-rate-limit-middleware.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import { NextFunction, Request, Response } from 'express' | ||
|
|
||
| import { createSettings } from '../../factories/settings-factory' | ||
| import { rateLimiterFactory } from '../../factories/rate-limiter-factory' | ||
| import { isAdminRateLimited } from '../../utils/admin-rate-limit' | ||
|
|
||
| type AdminRateLimitScope = 'login' | 'admin' | ||
|
|
||
| const sendTooManyRequests = (response: Response) => { | ||
| response.status(429).setHeader('content-type', 'application/json').send({ error: 'Too many requests' }) | ||
| } | ||
|
Ferryx349 marked this conversation as resolved.
|
||
|
|
||
| export const createAdminRateLimitMiddleware = (scope: AdminRateLimitScope) => { | ||
| return async (request: Request, response: Response, next: NextFunction) => { | ||
| if (await isAdminRateLimited(request, createSettings(), rateLimiterFactory, scope)) { | ||
| sendTooManyRequests(response) | ||
| return | ||
| } | ||
|
|
||
| next() | ||
| } | ||
| } | ||
|
|
||
| export const adminLoginRateLimitMiddleware = createAdminRateLimitMiddleware('login') | ||
| export const adminRateLimitMiddleware = createAdminRateLimitMiddleware('admin') | ||
13 changes: 13 additions & 0 deletions
13
src/handlers/request-handlers/with-admin-controller-request-handler.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| import { Request, Response } from 'express' | ||
|
|
||
| import { Factory } from '../../@types/base' | ||
| import { IController } from '../../@types/controllers' | ||
|
|
||
| export const withAdminController = | ||
| (controllerFactory: Factory<IController>) => async (request: Request, response: Response) => { | ||
| try { | ||
| return await controllerFactory().handleRequest(request, response) | ||
| } catch { | ||
| response.status(500).setHeader('content-type', 'application/json').send({ error: 'Internal Server Error' }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import { json, Router } from 'express' | ||
|
|
||
| import { createGetAdminHealthController } from '../../factories/controllers/get-admin-health-controller-factory' | ||
| import { createGetAdminSessionController } from '../../factories/controllers/get-admin-session-controller-factory' | ||
| import { createPostAdminLoginController } from '../../factories/controllers/post-admin-login-controller-factory' | ||
| import { adminAuthMiddleware } from '../../handlers/request-handlers/admin-auth-middleware' | ||
| import { adminEnabledMiddleware } from '../../handlers/request-handlers/admin-enabled-middleware' | ||
| import { | ||
| adminLoginRateLimitMiddleware, | ||
| adminRateLimitMiddleware, | ||
| } from '../../handlers/request-handlers/admin-rate-limit-middleware' | ||
| import { rateLimiterMiddleware } from '../../handlers/request-handlers/rate-limiter-middleware' | ||
| import { withAdminController } from '../../handlers/request-handlers/with-admin-controller-request-handler' | ||
|
|
||
| const router: Router = Router() | ||
|
|
||
| // codeql[js/missing-rate-limiting] - custom Redis-backed sliding window rate limiter | ||
| router.use(rateLimiterMiddleware) | ||
| // codeql[js/missing-rate-limiting] - feature gate only, not authentication | ||
| router.use(adminEnabledMiddleware) | ||
| router.post('/login', adminLoginRateLimitMiddleware, json(), withAdminController(createPostAdminLoginController)) | ||
| router.get('/session', adminRateLimitMiddleware, adminAuthMiddleware, withAdminController(createGetAdminSessionController)) | ||
Check failureCode scanning / CodeQL Missing rate limiting High
This route handler performs
authorization Error loading related location Loading |
||
|
|
||
| router.get('/health', adminRateLimitMiddleware, adminAuthMiddleware, withAdminController(createGetAdminHealthController)) | ||
Check failureCode scanning / CodeQL Missing rate limiting High
This route handler performs
authorization Error loading related location Loading |
||
|
|
||
|
|
||
| export default router | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| import { z } from 'zod' | ||
|
|
||
| export const adminLoginBodySchema = z | ||
| .object({ | ||
| password: z.string().min(1), | ||
| }) | ||
| .strict() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.