Commit 95e0eb9679
Unsigned
Layout: unified · split
.github/workflows/ci-api.yml −1
| @@ -5,7 +5,6 @@ on: | |||
| 5 | pull_request: | 5 | pull_request: |
| 6 | paths: | 6 | paths: |
| 7 | - 'api/**' | 7 | - 'api/**' |
| 8 | - 'awesome-privacy.yml' | ||
| 9 | - '.github/workflows/ci-api.yml' | 8 | - '.github/workflows/ci-api.yml' |
| 10 | workflow_dispatch: | 9 | workflow_dispatch: |
| 11 | 10 | ||
.github/zizmor.yml added +5
| @@ -0,0 +1,5 @@ | |||
| 1 | rules: | ||
| 2 | unpinned-uses: | ||
| 3 | config: | ||
| 4 | policies: | ||
| 5 | '*': ref-pin | ||
api/src/app.ts +23 −13
| @@ -3,8 +3,8 @@ import { cors } from 'hono/cors' | |||
| 3 | import { Scalar } from '@scalar/hono-api-reference' | 3 | import { Scalar } from '@scalar/hono-api-reference' |
| 4 | 4 | ||
| 5 | import { createStorage } from '@/lib/cache' | 5 | import { createStorage } from '@/lib/cache' |
| 6 | import { errorHandler, notFound } from '@/lib/errors' | 6 | import { ApiError, errorHandler, notFound } from '@/lib/errors' |
| 7 | import { requireBearer } from '@/lib/auth' | 7 | import { hasValidToken, authRequired } from '@/lib/auth' |
| 8 | import { rateLimit } from '@/lib/ratelimit' | 8 | import { rateLimit } from '@/lib/ratelimit' |
| 9 | import { newApp } from '@/lib/openapi' | 9 | import { newApp } from '@/lib/openapi' |
| 10 | import type { AppEnv } from '@/types' | 10 | import type { AppEnv } from '@/types' |
| @@ -37,9 +37,8 @@ const buildPublic = () => { | |||
| 37 | } | 37 | } |
| 38 | 38 | ||
| 39 | const buildPrivate = () => { | 39 | const buildPrivate = () => { |
| 40 | // Private enrichment routes, bearer auth on every /enrich/* path | 40 | // Enrichment routes, public but rate-limited (see rate-limit wiring below) |
| 41 | const priv = newApp() | 41 | const priv = newApp() |
| 42 | priv.use('/enrich/*', requireBearer()) | ||
| 43 | priv.route('/', privacy) | 42 | priv.route('/', privacy) |
| 44 | priv.route('/', github) | 43 | priv.route('/', github) |
| 45 | priv.route('/', ios) | 44 | priv.route('/', ios) |
| @@ -64,13 +63,21 @@ export const buildApp = () => { | |||
| 64 | await next() | 63 | await next() |
| 65 | }) | 64 | }) |
| 66 | 65 | ||
| 67 | // CORS everywhere; rate limiting and edge caching are for public routes only, | 66 | // CORS everywhere. Public browse routes get the standard limit; enrich routes |
| 68 | // authenticated /enrich/* requests are exempt from both | 67 | // are public too, but anonymous callers hit a stricter limit while a valid |
| 68 | // bearer token bypasses it. Edge caching stays off for enrich (below). | ||
| 69 | app.use('*', cors({ origin: '*' })) | 69 | app.use('*', cors({ origin: '*' })) |
| 70 | const limiter = rateLimit() | 70 | const publicLimiter = rateLimit() |
| 71 | app.use('/v1/*', (c, next) => | 71 | const enrichLimiter = rateLimit((env) => env.ENRICH_RATE_LIMIT ?? env.RATE_LIMIT) |
| 72 | c.req.path.startsWith('/v1/enrich') ? next() : limiter(c, next), | 72 | app.use('/v1/*', (c, next) => { |
| 73 | ) | 73 | if (!c.req.path.startsWith('/v1/enrich')) return publicLimiter(c, next) |
| 74 | const authed = hasValidToken(c.env.API_TOKEN, c.req.header('authorization')) | ||
| 75 | if (authRequired(c.env.REQUIRE_AUTH) && !authed) { | ||
| 76 | throw new ApiError('UNAUTHORIZED', 'Invalid or missing bearer token', 401) | ||
| 77 | } | ||
| 78 | if (authed) return next() | ||
| 79 | return enrichLimiter(c, next) | ||
| 80 | }) | ||
| 74 | app.use('/v1/*', async (c, next) => { | 81 | app.use('/v1/*', async (c, next) => { |
| 75 | if (c.req.path.startsWith('/v1/enrich')) return next() | 82 | if (c.req.path.startsWith('/v1/enrich')) return next() |
| 76 | await next() | 83 | await next() |
| @@ -100,9 +107,12 @@ export const buildApp = () => { | |||
| 100 | <details> | 107 | <details> |
| 101 | <summary>Authenticating</summary> | 108 | <summary>Authenticating</summary> |
| 102 | 109 | ||
| 103 | By default, no auth is needed. | 110 | The enrichment endpoints are public, but anonymous requests are rate-limited. |
| 104 | If you're self-hosting, you can enable auth by setting the \`API_TOKEN\` env var. | 111 | On the hosted instance, sending a valid \`Authorization: Bearer <token>\` header |
| 105 | Then, add the \`Authorization: Bearer <your-token>\` header when accessing the enrichment endpoints. | 112 | exempts the request from rate limiting. Self-hosters can set the \`API_TOKEN\` |
| 113 | env var to enable the same bypass for their own token. | ||
| 114 | To lock the endpoints down entirely, set \`REQUIRE_AUTH\` (alongside \`API_TOKEN\`): | ||
| 115 | requests without a valid token are then rejected with a 401. | ||
| 106 | </details> | 116 | </details> |
| 107 | 117 | ||
| 108 | <details> | 118 | <details> |
api/src/lib/auth.ts +19 −19
| @@ -1,15 +1,12 @@ | |||
| 1 | /** | 1 | /** |
| 2 | * Middleware to add basic bearer token auth to /enrich/* routes | 2 | * Bearer token check for /enrich/* routes. |
| 3 | * To prevent abuse of endpoints which make third-party requests | 3 | * The endpoints are public by default, but a request carrying the correct |
| 4 | * It's off-by-default, and can be enabled by setting API_TOKEN | 4 | * "Authorization: Bearer $API_TOKEN" header is exempt from rate limiting. |
| 5 | * Works by checking the "Authorization: Bearer $API_TOKEN" header | 5 | * When API_TOKEN is unset (e.g. self-hosted), no request is privileged. |
| 6 | * Setting REQUIRE_AUTH turns the token into a hard gate (see authRequired). | ||
| 6 | */ | 7 | */ |
| 7 | 8 | ||
| 8 | import type { MiddlewareHandler } from 'hono' | 9 | // Compare two strings in constant time |
| 9 | import { ApiError } from '@/lib/errors' | ||
| 10 | import type { HonoEnv } from '@/types' | ||
| 11 | |||
| 12 | // Compare specified token against expected, using constant time | ||
| 13 | const constantTimeEqual = (left: string, right: string) => { | 10 | const constantTimeEqual = (left: string, right: string) => { |
| 14 | if (left.length !== right.length) return false | 11 | if (left.length !== right.length) return false |
| 15 | let diff = 0 | 12 | let diff = 0 |
| @@ -19,14 +16,17 @@ const constantTimeEqual = (left: string, right: string) => { | |||
| 19 | return diff === 0 | 16 | return diff === 0 |
| 20 | } | 17 | } |
| 21 | 18 | ||
| 22 | // If auth enabled, check specified header matches env var, otherwise respond 401 | 19 | // True when a valid bearer token is present (auth must be configured) |
| 23 | export const requireBearer = (): MiddlewareHandler<HonoEnv> => async (c, next) => { | 20 | export const hasValidToken = ( |
| 24 | const expected = c.env.API_TOKEN | 21 | expected: string | undefined, |
| 25 | if (!expected) return next() | 22 | header: string | undefined, |
| 26 | const header = c.req.header('authorization') ?? '' | 23 | ): boolean => { |
| 27 | const match = /^Bearer\s+(\S+)$/i.exec(header) | 24 | if (!expected) return false |
| 28 | if (!match || !constantTimeEqual(match[1], expected)) { | 25 | const match = /^Bearer\s+(\S+)$/i.exec(header ?? '') |
| 29 | throw new ApiError('UNAUTHORIZED', 'Invalid or missing bearer token', 401) | 26 | return !!match && constantTimeEqual(match[1], expected) |
| 30 | } | ||
| 31 | await next() | ||
| 32 | } | 27 | } |
| 28 | |||
| 29 | // True when REQUIRE_AUTH is enabled, hard-gating enrich behind a valid token. | ||
| 30 | // Off by default; needs API_TOKEN set too, else every request fails closed. | ||
| 31 | export const authRequired = (value: string | undefined): boolean => | ||
| 32 | /^(1|true|yes|on)$/i.test(value ?? '') | ||
api/src/lib/env.ts +2
| @@ -10,6 +10,7 @@ export const readEnv = (workersEnv?: Partial<AppEnv>): AppEnv => { | |||
| 10 | const env = proc as Record<string, string | undefined> | 10 | const env = proc as Record<string, string | undefined> |
| 11 | return { | 11 | return { |
| 12 | API_TOKEN: workersEnv?.API_TOKEN ?? env.API_TOKEN, | 12 | API_TOKEN: workersEnv?.API_TOKEN ?? env.API_TOKEN, |
| 13 | REQUIRE_AUTH: workersEnv?.REQUIRE_AUTH ?? env.REQUIRE_AUTH, | ||
| 13 | DISCORD_BOT_TOKEN: workersEnv?.DISCORD_BOT_TOKEN ?? env.DISCORD_BOT_TOKEN, | 14 | DISCORD_BOT_TOKEN: workersEnv?.DISCORD_BOT_TOKEN ?? env.DISCORD_BOT_TOKEN, |
| 14 | APIVOID_API_KEY: workersEnv?.APIVOID_API_KEY ?? env.APIVOID_API_KEY, | 15 | APIVOID_API_KEY: workersEnv?.APIVOID_API_KEY ?? env.APIVOID_API_KEY, |
| 15 | EXODUS_TOKEN: workersEnv?.EXODUS_TOKEN ?? env.EXODUS_TOKEN, | 16 | EXODUS_TOKEN: workersEnv?.EXODUS_TOKEN ?? env.EXODUS_TOKEN, |
| @@ -17,6 +18,7 @@ export const readEnv = (workersEnv?: Partial<AppEnv>): AppEnv => { | |||
| 17 | DOCKERHUB_TOKEN: workersEnv?.DOCKERHUB_TOKEN ?? env.DOCKERHUB_TOKEN, | 18 | DOCKERHUB_TOKEN: workersEnv?.DOCKERHUB_TOKEN ?? env.DOCKERHUB_TOKEN, |
| 18 | CACHE: workersEnv?.CACHE, | 19 | CACHE: workersEnv?.CACHE, |
| 19 | RATE_LIMIT: workersEnv?.RATE_LIMIT, | 20 | RATE_LIMIT: workersEnv?.RATE_LIMIT, |
| 21 | ENRICH_RATE_LIMIT: workersEnv?.ENRICH_RATE_LIMIT, | ||
| 20 | API_BASE: workersEnv?.API_BASE ?? env.API_BASE, | 22 | API_BASE: workersEnv?.API_BASE ?? env.API_BASE, |
| 21 | } | 23 | } |
| 22 | } | 24 | } |
api/src/lib/ratelimit/index.ts +15 −11
| @@ -2,19 +2,23 @@ | |||
| 2 | * Rate limit middleware factory | 2 | * Rate limit middleware factory |
| 3 | * Basic measure to prevent obvious abuse for public routes | 3 | * Basic measure to prevent obvious abuse for public routes |
| 4 | * Uses CF's native rate-limiting API, configurable in wrangler.toml | 4 | * Uses CF's native rate-limiting API, configurable in wrangler.toml |
| 5 | * Only applies to unauthenticated requests on the public instance | 5 | * The binding is selectable, so different routes can use different limits |
| 6 | * By default, there's no rate-limiting on self-hosted/Bun versions | 6 | * By default, there's no rate-limiting on self-hosted/Bun versions |
| 7 | */ | 7 | */ |
| 8 | import type { MiddlewareHandler } from 'hono' | 8 | import type { MiddlewareHandler } from 'hono' |
| 9 | import { ApiError } from '@/lib/errors' | 9 | import { ApiError } from '@/lib/errors' |
| 10 | import type { HonoEnv } from '@/types' | 10 | import type { AppEnv, HonoEnv, RateLimiter } from '@/types' |
| 11 | 11 | ||
| 12 | export const rateLimit = (): MiddlewareHandler<HonoEnv> => async (c, next) => { | 12 | export const rateLimit = |
| 13 | const limiter = c.env.RATE_LIMIT | 13 | ( |
| 14 | if (!limiter) return next() | 14 | pick: (env: AppEnv) => RateLimiter | undefined = (env) => env.RATE_LIMIT, |
| 15 | const key = | 15 | ): MiddlewareHandler<HonoEnv> => |
| 16 | c.req.header('cf-connecting-ip') ?? c.req.header('x-forwarded-for') ?? 'anon' | 16 | async (c, next) => { |
| 17 | const { success } = await limiter.limit({ key }) | 17 | const limiter = pick(c.env) |
| 18 | if (!success) throw new ApiError('RATE_LIMITED', 'Too many requests', 429) | 18 | if (!limiter) return next() |
| 19 | return next() | 19 | const key = |
| 20 | } | 20 | c.req.header('cf-connecting-ip') ?? c.req.header('x-forwarded-for') ?? 'anon' |
| 21 | const { success } = await limiter.limit({ key }) | ||
| 22 | if (!success) throw new ApiError('RATE_LIMITED', 'Too many requests', 429) | ||
| 23 | return next() | ||
| 24 | } | ||
api/src/types.ts +3
| @@ -56,6 +56,8 @@ export interface RateLimiter { | |||
| 56 | // Unified environment seen by both Workers + Node | 56 | // Unified environment seen by both Workers + Node |
| 57 | export interface AppEnv { | 57 | export interface AppEnv { |
| 58 | API_TOKEN?: string | 58 | API_TOKEN?: string |
| 59 | // When truthy, /enrich/* requires a valid bearer token (off by default) | ||
| 60 | REQUIRE_AUTH?: string | ||
| 59 | DISCORD_BOT_TOKEN?: string | 61 | DISCORD_BOT_TOKEN?: string |
| 60 | APIVOID_API_KEY?: string | 62 | APIVOID_API_KEY?: string |
| 61 | EXODUS_TOKEN?: string | 63 | EXODUS_TOKEN?: string |
| @@ -63,6 +65,7 @@ export interface AppEnv { | |||
| 63 | DOCKERHUB_TOKEN?: string | 65 | DOCKERHUB_TOKEN?: string |
| 64 | CACHE?: KVNamespace | 66 | CACHE?: KVNamespace |
| 65 | RATE_LIMIT?: RateLimiter | 67 | RATE_LIMIT?: RateLimiter |
| 68 | ENRICH_RATE_LIMIT?: RateLimiter | ||
| 66 | API_BASE?: string | 69 | API_BASE?: string |
| 67 | } | 70 | } |
| 68 | 71 | ||
api/tests/app.test.ts +76 −15
| @@ -55,27 +55,80 @@ describe('public routes', () => { | |||
| 55 | }) | 55 | }) |
| 56 | }) | 56 | }) |
| 57 | 57 | ||
| 58 | describe('auth', () => { | 58 | describe('enrich rate limiting', () => { |
| 59 | it('private route rejects missing token', async () => { | 59 | // A limiter that always denies, recording how many times it was consulted |
| 60 | const res = await hit('/v1/enrich/privacy/1') | 60 | const denyLimiter = () => { |
| 61 | expect(res.status).toBe(401) | 61 | const calls = { n: 0 } |
| 62 | const limiter = { | ||
| 63 | limit: async () => { | ||
| 64 | calls.n++ | ||
| 65 | return { success: false } | ||
| 66 | }, | ||
| 67 | } | ||
| 68 | return { limiter, calls } | ||
| 69 | } | ||
| 70 | // A KV cache pre-seeded so handlers serve cached data without any upstream call | ||
| 71 | const seededCache = (value: unknown) => ({ | ||
| 72 | get: async () => ({ value, cachedAt: Date.now() }), | ||
| 73 | put: async () => {}, | ||
| 62 | }) | 74 | }) |
| 63 | 75 | ||
| 64 | it('private route rejects wrong token', async () => { | 76 | it('anonymous enrich request is rate-limited', async () => { |
| 65 | const res = await hit('/v1/enrich/privacy/1', { | 77 | const { limiter, calls } = denyLimiter() |
| 66 | headers: { authorization: 'Bearer wrong' }, | 78 | const res = await app.fetch(new Request('http://localhost/v1/enrich/privacy/1'), { |
| 79 | API_TOKEN: 'test', | ||
| 80 | ENRICH_RATE_LIMIT: limiter, | ||
| 67 | }) | 81 | }) |
| 68 | expect(res.status).toBe(401) | 82 | expect(res.status).toBe(429) |
| 83 | expect(calls.n).toBe(1) | ||
| 69 | }) | 84 | }) |
| 70 | 85 | ||
| 71 | it('security enrich route requires auth', async () => { | 86 | it('valid bearer token bypasses the enrich rate limit', async () => { |
| 72 | const res = await hit('/v1/enrich/security/jquery/jquery') | 87 | const { limiter, calls } = denyLimiter() |
| 73 | expect(res.status).toBe(401) | 88 | const res = await app.fetch( |
| 89 | new Request('http://localhost/v1/enrich/privacy/1', { | ||
| 90 | headers: { authorization: 'Bearer test' }, | ||
| 91 | }), | ||
| 92 | { API_TOKEN: 'test', ENRICH_RATE_LIMIT: limiter, CACHE: seededCache({ id: 1 }) }, | ||
| 93 | ) | ||
| 94 | expect(res.status).toBe(200) | ||
| 95 | expect(calls.n).toBe(0) | ||
| 96 | }) | ||
| 97 | |||
| 98 | it('wrong token does not bypass the enrich rate limit', async () => { | ||
| 99 | const { limiter, calls } = denyLimiter() | ||
| 100 | const res = await app.fetch( | ||
| 101 | new Request('http://localhost/v1/enrich/privacy/1', { | ||
| 102 | headers: { authorization: 'Bearer wrong' }, | ||
| 103 | }), | ||
| 104 | { API_TOKEN: 'test', ENRICH_RATE_LIMIT: limiter }, | ||
| 105 | ) | ||
| 106 | expect(res.status).toBe(429) | ||
| 107 | expect(calls.n).toBe(1) | ||
| 74 | }) | 108 | }) |
| 75 | 109 | ||
| 76 | it('docker enrich route requires auth', async () => { | 110 | it('REQUIRE_AUTH rejects missing/invalid token with 401', async () => { |
| 77 | const res = await hit('/v1/enrich/docker/pihole') | 111 | const env = { API_TOKEN: 'test', REQUIRE_AUTH: 'true' } |
| 78 | expect(res.status).toBe(401) | 112 | expect( |
| 113 | (await app.fetch(new Request('http://localhost/v1/enrich/privacy/1'), env)).status, | ||
| 114 | ).toBe(401) | ||
| 115 | const wrong = await app.fetch( | ||
| 116 | new Request('http://localhost/v1/enrich/privacy/1', { | ||
| 117 | headers: { authorization: 'Bearer wrong' }, | ||
| 118 | }), | ||
| 119 | env, | ||
| 120 | ) | ||
| 121 | expect(wrong.status).toBe(401) | ||
| 122 | }) | ||
| 123 | |||
| 124 | it('REQUIRE_AUTH still admits a valid token', async () => { | ||
| 125 | const res = await app.fetch( | ||
| 126 | new Request('http://localhost/v1/enrich/privacy/1', { | ||
| 127 | headers: { authorization: 'Bearer test' }, | ||
| 128 | }), | ||
| 129 | { API_TOKEN: 'test', REQUIRE_AUTH: 'true', CACHE: seededCache({ id: 1 }) }, | ||
| 130 | ) | ||
| 131 | expect(res.status).toBe(200) | ||
| 79 | }) | 132 | }) |
| 80 | }) | 133 | }) |
| 81 | 134 | ||
| @@ -86,7 +139,15 @@ describe('middleware scoping', () => { | |||
| 86 | }) | 139 | }) |
| 87 | 140 | ||
| 88 | it('enrich routes are not advertised as public cacheable', async () => { | 141 | it('enrich routes are not advertised as public cacheable', async () => { |
| 89 | const res = await hit('/v1/enrich/privacy/1') | 142 | // Seed the cache so the handler serves without an upstream call |
| 143 | const cache = { | ||
| 144 | get: async () => ({ value: { id: 1 }, cachedAt: Date.now() }), | ||
| 145 | put: async () => {}, | ||
| 146 | } | ||
| 147 | const res = await app.fetch(new Request('http://localhost/v1/enrich/privacy/1'), { | ||
| 148 | API_TOKEN: 'test', | ||
| 149 | CACHE: cache, | ||
| 150 | }) | ||
| 90 | expect(res.headers.get('cache-control') ?? '').not.toContain('public') | 151 | expect(res.headers.get('cache-control') ?? '').not.toContain('public') |
| 91 | }) | 152 | }) |
| 92 | }) | 153 | }) |
api/wrangler.toml +7
| @@ -26,6 +26,13 @@ type = "ratelimit" | |||
| 26 | namespace_id = "1001" | 26 | namespace_id = "1001" |
| 27 | simple = { limit = 60, period = 60 } | 27 | simple = { limit = 60, period = 60 } |
| 28 | 28 | ||
| 29 | # Stricter limit for anonymous /enrich/* requests; a valid API_TOKEN bypasses it | ||
| 30 | [[unsafe.bindings]] | ||
| 31 | name = "ENRICH_RATE_LIMIT" | ||
| 32 | type = "ratelimit" | ||
| 33 | namespace_id = "1002" | ||
| 34 | simple = { limit = 10, period = 60 } | ||
| 35 | |||
| 29 | # Scheduled cache warmer | 36 | # Scheduled cache warmer |
| 30 | [triggers] | 37 | [triggers] |
| 31 | crons = ["*/15 * * * *"] | 38 | crons = ["*/15 * * * *"] |
lib/checks/check-project.py +8 −6
| @@ -22,6 +22,8 @@ FINDINGS_PATH = "/tmp/findings-project.json" | |||
| 22 | 22 | ||
| 23 | TIMEOUT = 10 | 23 | TIMEOUT = 10 |
| 24 | USER_AGENT = "awesome-privacy-ci/1.0" | 24 | USER_AGENT = "awesome-privacy-ci/1.0" |
| 25 | # Reachable but blocking automated probes (bot-block/rate-limit), not a missing page. | ||
| 26 | SOFT_HTTP = {401, 403, 405, 406, 429} | ||
| 25 | MIN_STARS = 100 | 27 | MIN_STARS = 100 |
| 26 | INACTIVE_DAYS = 90 | 28 | INACTIVE_DAYS = 90 |
| 27 | MIN_AGE_DAYS = 120 | 29 | MIN_AGE_DAYS = 120 |
| @@ -106,13 +108,13 @@ def load_diff(path): | |||
| 106 | 108 | ||
| 107 | 109 | ||
| 108 | def check_url(url): | 110 | def check_url(url): |
| 109 | """Return True if the URL is reachable. Transport errors are treated as reachable.""" | 111 | """Return True if reachable. Transport errors and bot-block/rate-limit statuses |
| 112 | (SOFT_HTTP) count as reachable; only a real bad status (404, 5xx, ...) fails.""" | ||
| 110 | ok, status = utils.check_url(url, SESSION, TIMEOUT) | 113 | ok, status = utils.check_url(url, SESSION, TIMEOUT) |
| 111 | if not ok: | 114 | if ok or status is None or status in SOFT_HTTP: |
| 112 | logger.warning("URL check failed for %s (HTTP %d)", url, status) | 115 | return True |
| 113 | elif status is None: | 116 | logger.warning("URL check failed for %s (HTTP %d)", url, status) |
| 114 | logger.warning("URL check error for %s (unreachable)", url) | 117 | return False |
| 115 | return ok | ||
| 116 | 118 | ||
| 117 | 119 | ||
| 118 | def _gh_get(path, token, params=None, label=""): | 120 | def _gh_get(path, token, params=None, label=""): |