Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions backend/src/api/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ import { AUTH0_CONFIG } from '../../conf'

import { errorHandler } from './middlewares/errorHandler'
import { oauth2Middleware } from './middlewares/oauth2Middleware'
import { staticApiKeyMiddleware } from './middlewares/staticApiKeyMiddleware'
import { v1Router } from './v1'
import { devStatsRouter } from './v1/dev-stats'

export function publicRouter(): Router {
const router = Router()

router.use('/v1/dev-stats', staticApiKeyMiddleware(), devStatsRouter())
router.use('/v1', oauth2Middleware(AUTH0_CONFIG), v1Router())
router.use(errorHandler)

Expand Down
48 changes: 48 additions & 0 deletions backend/src/api/public/middlewares/staticApiKeyMiddleware.ts
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 }
Comment thread
ulemons marked this conversation as resolved.

next()
} catch (err) {
next(err)
}
}
Comment thread
cursor[bot] marked this conversation as resolved.
}
19 changes: 19 additions & 0 deletions backend/src/api/public/v1/dev-stats/index.ts
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 backend/src/database/migrations/V1773938832__add-api-keys-tale.sql
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()
);
1 change: 1 addition & 0 deletions backend/src/security/scopes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const SCOPES = {
WRITE_WORK_EXPERIENCES: 'write:work-experiences',
READ_PROJECT_AFFILIATIONS: 'read:project-affiliations',
WRITE_PROJECT_AFFILIATIONS: 'write:project-affiliations',
READ_AFFILIATIONS: 'read:affiliations',
} as const

export type Scope = (typeof SCOPES)[keyof typeof SCOPES]
34 changes: 34 additions & 0 deletions services/libs/data-access-layer/src/apiKeys/index.ts
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 },
)
}
1 change: 1 addition & 0 deletions services/libs/data-access-layer/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './activities'
export * from './activityRelations'
export * from './apiKeys'
export * from './dashboards'
export * from './members'
export * from './organizations'
Expand Down
Loading