-
Notifications
You must be signed in to change notification settings - Fork 732
feat: add static api key middleware for dev stats (CM-1055) #3933
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
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
621d4c9
feat: add static api key middleware for dev stats
ulemons 5181255
fix: lint
ulemons b4d3f7d
fix: remove local secret
ulemons 1905574
feat: add rate limiter
ulemons ee99ceb
feat: add fallback unauthorized
ulemons 020d3fe
fix: use db oriented api keys
ulemons 33cd00e
fix: add scopes
ulemons 98f8cfa
fix: remove useless env var
ulemons 0f47c11
fix: lint
ulemons 80f6b61
fix: review
ulemons 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
48 changes: 48 additions & 0 deletions
48
backend/src/api/public/middlewares/staticApiKeyMiddleware.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,48 @@ | ||
| import crypto from 'crypto' | ||
| import type { NextFunction, Request, RequestHandler, Response } from 'express' | ||
|
|
||
| import { UnauthorizedError } from '@crowd/common' | ||
| import { findApiKeyByHash, optionsQx, touchApiKeyLastUsed } from '@crowd/data-access-layer' | ||
|
|
||
| export function staticApiKeyMiddleware(): RequestHandler { | ||
| return async (req: Request, _res: Response, next: NextFunction): Promise<void> => { | ||
| try { | ||
| const authHeader = req.headers.authorization | ||
|
|
||
| if (!authHeader || !authHeader.startsWith('Bearer ')) { | ||
| next(new UnauthorizedError('Missing or invalid Authorization header')) | ||
| return | ||
| } | ||
|
|
||
| const providedKey = authHeader.slice('Bearer '.length) | ||
| const keyHash = crypto.createHash('sha256').update(providedKey).digest('hex') | ||
|
|
||
| const qx = optionsQx(req) | ||
| const apiKey = await findApiKeyByHash(qx, keyHash) | ||
|
|
||
| if (!apiKey) { | ||
| next(new UnauthorizedError('Invalid API key')) | ||
| return | ||
| } | ||
|
|
||
| if (apiKey.revokedAt) { | ||
| next(new UnauthorizedError('API key has been revoked')) | ||
| return | ||
| } | ||
|
|
||
| if (apiKey.expiresAt && apiKey.expiresAt < new Date()) { | ||
| next(new UnauthorizedError('API key has expired')) | ||
| return | ||
| } | ||
|
|
||
| // fire and forget — don't block the request | ||
| touchApiKeyLastUsed(qx, apiKey.id).catch(() => {}) | ||
|
|
||
| req.actor = { id: apiKey.name, type: 'service', scopes: apiKey.scopes } | ||
|
|
||
| next() | ||
| } catch (err) { | ||
| next(err) | ||
| } | ||
| } | ||
|
cursor[bot] 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,19 @@ | ||
| import { Router } from 'express' | ||
|
|
||
| import { createRateLimiter } from '@/api/apiRateLimiter' | ||
| import { requireScopes } from '@/api/public/middlewares/requireScopes' | ||
| import { SCOPES } from '@/security/scopes' | ||
|
|
||
| const rateLimiter = createRateLimiter({ max: 60, windowMs: 60 * 1000 }) | ||
|
|
||
| export function devStatsRouter(): Router { | ||
| const router = Router() | ||
|
|
||
| router.use(rateLimiter) | ||
|
|
||
| router.post('/affiliations', requireScopes([SCOPES.READ_AFFILIATIONS]), (_req, res) => { | ||
| res.json({ status: 'ok' }) | ||
| }) | ||
|
|
||
| return router | ||
| } |
Empty file.
13 changes: 13 additions & 0 deletions
13
backend/src/database/migrations/V1773938832__add-api-keys-tale.sql
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 @@ | ||
| CREATE TABLE "apiKeys" ( | ||
| "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(), | ||
| "name" TEXT NOT NULL, | ||
| "keyHash" TEXT NOT NULL UNIQUE, | ||
| "keyPrefix" TEXT NOT NULL, | ||
| "scopes" TEXT[] NOT NULL DEFAULT '{}', | ||
| "expiresAt" TIMESTAMPTZ, | ||
| "lastUsedAt" TIMESTAMPTZ, | ||
| "createdById" TEXT, | ||
| "revokedAt" TIMESTAMPTZ, | ||
| "createdAt" TIMESTAMPTZ NOT NULL DEFAULT now(), | ||
| "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT now() | ||
| ); |
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,34 @@ | ||
| import { QueryExecutor } from '../queryExecutor' | ||
|
|
||
| export interface IApiKey { | ||
| id: string | ||
| name: string | ||
| scopes: string[] | ||
| expiresAt: Date | null | ||
| revokedAt: Date | null | ||
| } | ||
|
|
||
| export async function findApiKeyByHash( | ||
| qx: QueryExecutor, | ||
| keyHash: string, | ||
| ): Promise<IApiKey | null> { | ||
| return qx.selectOneOrNone( | ||
| ` | ||
| SELECT id, name, scopes, "expiresAt", "revokedAt" | ||
| FROM "apiKeys" | ||
| WHERE "keyHash" = $(keyHash) | ||
| `, | ||
| { keyHash }, | ||
| ) | ||
| } | ||
|
|
||
| export async function touchApiKeyLastUsed(qx: QueryExecutor, id: string): Promise<void> { | ||
| await qx.result( | ||
| ` | ||
| UPDATE "apiKeys" | ||
| SET "lastUsedAt" = now(), "updatedAt" = now() | ||
| WHERE id = $(id) | ||
| `, | ||
| { id }, | ||
| ) | ||
| } |
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
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.