Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Proxy frontend API requests through Nitro with rate limits (#5694)

Olga Bulat93ee3697ee7b
diff --git a/.dockerignore b/.dockerignore
index bc1d150ee..4c7c26315 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -5,3 +5,5 @@
!.pnpmfile.cjs
!pnpm-lock.yaml
!tsconfig.base.json
+!packages/js/api-client/package.json
+!packages/js/api-client/src/**
diff --git a/api/api/migrations/0072_alter_throttledapplication_rate_limit_model.py b/api/api/migrations/0072_alter_throttledapplication_rate_limit_model.py
new file mode 100644
index 000000000..06521973b
--- /dev/null
+++ b/api/api/migrations/0072_alter_throttledapplication_rate_limit_model.py
@@ -0,0 +1,16 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('api', '0071_alter_audio_options_alter_deletedaudio_options_and_more'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name='throttledapplication',
+ name='rate_limit_model',
+ field=models.CharField(choices=[('standard', 'standard'), ('enhanced', 'enhanced'), ('exempt', 'exempt'), ('frontend', 'frontend')], default='standard', max_length=20),
+ ),
+ ]
diff --git a/api/api/models/oauth.py b/api/api/models/oauth.py
index 1a4094cf9..721a1d4cd 100644
--- a/api/api/models/oauth.py
+++ b/api/api/models/oauth.py
@@ -36,6 +36,8 @@ class ThrottledApplication(AbstractApplication):
# case-by-case basis.
("exempt", "exempt"), # Rate limits used for internal infrastructure to
# by-pass rate limiting entirely.
+ ("frontend", "frontend"), # High but finite rate limits for the
+ # openverse.org frontend, which proxies requests for all its users.
]
rate_limit_model = models.CharField(
max_length=20, choices=RATE_LIMIT_MODELS, default="standard"
diff --git a/api/api/utils/throttle.py b/api/api/utils/throttle.py
index e4de75f2c..9f6808a26 100644
--- a/api/api/utils/throttle.py
+++ b/api/api/utils/throttle.py
@@ -159,7 +159,7 @@ class AbstractOAuth2IdRateThrottle(SimpleRateThrottle, metaclass=abc.ABCMeta):
class OAuth2IdThumbnailRateThrottle(AbstractOAuth2IdRateThrottle):
- applies_to_rate_limit_model = {"standard", "enhanced"}
+ applies_to_rate_limit_model = {"standard", "enhanced", "frontend"}
scope = "oauth2_client_credentials_thumbnail"
@@ -183,6 +183,16 @@ class EnhancedOAuth2IdBurstRateThrottle(AbstractOAuth2IdRateThrottle):
scope = "enhanced_oauth2_client_credentials_burst"
+class FrontendOAuth2IdSustainedRateThrottle(AbstractOAuth2IdRateThrottle):
+ applies_to_rate_limit_model = {"frontend"}
+ scope = "frontend_oauth2_client_credentials_sustained"
+
+
+class FrontendOAuth2IdBurstRateThrottle(AbstractOAuth2IdRateThrottle):
+ applies_to_rate_limit_model = {"frontend"}
+ scope = "frontend_oauth2_client_credentials_burst"
+
+
class ExemptOAuth2IdRateThrottle(AbstractOAuth2IdRateThrottle):
applies_to_rate_limit_model = {"exempt"}
scope = "exempt_oauth2_client_credentials"
diff --git a/api/api/views/oauth2_views.py b/api/api/views/oauth2_views.py
index 38fddf5f1..d8092f9a4 100644
--- a/api/api/views/oauth2_views.py
+++ b/api/api/views/oauth2_views.py
@@ -236,6 +236,14 @@ class CheckRates(APIView):
burst_throttle_key = throttle_key.format(
scope="enhanced_oauth2_client_credentials_burst", client_id=client_id
)
+ elif throttle_type == "frontend":
+ sustained_throttle_key = throttle_key.format(
+ scope="frontend_oauth2_client_credentials_sustained",
+ client_id=client_id,
+ )
+ burst_throttle_key = throttle_key.format(
+ scope="frontend_oauth2_client_credentials_burst", client_id=client_id
+ )
elif throttle_type == "exempt":
burst_throttle_key = sustained_throttle_key = throttle_key.format(
scope="exempt_oauth2_client_credentials_burst", client_id=client_id
diff --git a/api/conf/settings/rest_framework.py b/api/conf/settings/rest_framework.py
index 28252de1b..f6a401c4b 100644
--- a/api/conf/settings/rest_framework.py
+++ b/api/conf/settings/rest_framework.py
@@ -12,6 +12,12 @@ THROTTLE_ANON_SUSTAINED = config("THROTTLE_ANON_SUSTAINED", default="100/day")
THROTTLE_ANON_THUMBS = config("THROTTLE_ANON_THUMBS", default="150/minute")
THROTTLE_OAUTH2_THUMBS = config("THROTTLE_OAUTH2_THUMBS", default="500/minute")
THROTTLE_ANON_HEALTHCHECK = config("THROTTLE_ANON_HEALTHCHECK", default="3/minute")
+# The openverse.org frontend sends the requests of all its users with one key.
+# Live environments should size these from the frontend's request rate.
+THROTTLE_FRONTEND_BURST = config("THROTTLE_FRONTEND_BURST", default="3000/min")
+THROTTLE_FRONTEND_SUSTAINED = config(
+ "THROTTLE_FRONTEND_SUSTAINED", default="2000000/day"
+)
THROTTLE_OV_REFERRER_BURST = config(
"THROTTLE_OV_REFERRER_BURST", default=THROTTLE_ANON_BURST
@@ -36,6 +42,8 @@ DEFAULT_THROTTLE_RATES = {
"oauth2_client_credentials_burst": "100/min",
"enhanced_oauth2_client_credentials_sustained": "20000/day",
"enhanced_oauth2_client_credentials_burst": "200/min",
+ "frontend_oauth2_client_credentials_sustained": THROTTLE_FRONTEND_SUSTAINED,
+ "frontend_oauth2_client_credentials_burst": THROTTLE_FRONTEND_BURST,
# ``None`` completely by-passes the rate limiting
"exempt_oauth2_client_credentials": None,
}
@@ -49,6 +57,8 @@ DEFAULT_THROTTLE_CLASSES = (
"api.utils.throttle.OAuth2IdSustainedRateThrottle",
"api.utils.throttle.EnhancedOAuth2IdBurstRateThrottle",
"api.utils.throttle.EnhancedOAuth2IdSustainedRateThrottle",
+ "api.utils.throttle.FrontendOAuth2IdBurstRateThrottle",
+ "api.utils.throttle.FrontendOAuth2IdSustainedRateThrottle",
"api.utils.throttle.ExemptOAuth2IdRateThrottle",
)
diff --git a/api/latest_migrations/api b/api/latest_migrations/api
index 0cfb4f2b5..8c47f537b 100644
--- a/api/latest_migrations/api
+++ b/api/latest_migrations/api
@@ -2,4 +2,4 @@
# If you have a merge conflict in this file, it means you need to run:
# manage.py makemigrations --merge
# in order to resolve the conflict between migrations.
-0071_alter_audio_options_alter_deletedaudio_options_and_more
+0072_alter_throttledapplication_rate_limit_model
diff --git a/api/test/unit/configuration/test_malloc_trim.py b/api/test/unit/configuration/test_malloc_trim.py
index d9e79a5fd..a552b71fa 100644
--- a/api/test/unit/configuration/test_malloc_trim.py
+++ b/api/test/unit/configuration/test_malloc_trim.py
@@ -19,11 +19,15 @@ def test_disabled_without_glibc(monkeypatch):
def test_trims_periodically(monkeypatch):
calls = []
called_twice = threading.Event()
+ never_set = threading.Event()
def fake_trim(pad):
calls.append(pad)
if len(calls) >= 2:
called_twice.set()
+ # The thread can't be stopped, so park it here; otherwise it keeps
+ # logging "Trimmed the heap" into other tests' `capture_logs`.
+ never_set.wait()
return 1
monkeypatch.setattr(malloc_trim, "_get_malloc_trim", lambda: fake_trim)
diff --git a/api/test/unit/utils/test_throttle.py b/api/test/unit/utils/test_throttle.py
index 9232b087e..5f891421e 100644
--- a/api/test/unit/utils/test_throttle.py
+++ b/api/test/unit/utils/test_throttle.py
@@ -125,6 +125,14 @@ def test_anon_frontend_referrer_used_default_throttles(api_client):
},
id="enhanced",
),
+ pytest.param(
+ "frontend",
+ {
+ throttle.FrontendOAuth2IdBurstRateThrottle.scope,
+ throttle.FrontendOAuth2IdSustainedRateThrottle.scope,
+ },
+ id="frontend",
+ ),
pytest.param(
"exempt",
# Exempted requests have _no_ throttle class applied to them
@@ -192,6 +200,11 @@ def test_anon_frontend_referrer_used_thumbnail(api_client):
{throttle.OAuth2IdThumbnailRateThrottle.scope},
id="enhanced",
),
+ pytest.param(
+ "frontend",
+ {throttle.OAuth2IdThumbnailRateThrottle.scope},
+ id="frontend",
+ ),
pytest.param(
"exempt",
# See note on test_oauth_rate_limit_used_default_throttles's
diff --git a/frontend/Dockerfile b/frontend/Dockerfile
index 9a66cc786..d323a663b 100644
--- a/frontend/Dockerfile
+++ b/frontend/Dockerfile
@@ -24,7 +24,13 @@ WORKDIR /home/node/
# Note: these files must be manually un-ignored in the root .dockerignore
# hadolint ignore=DL3022
COPY --from=repo_root --chown=node:node .npmrc .pnpmfile.cjs pnpm-lock.yaml ./
-RUN echo '{"packages":["frontend/"]}' > pnpm-workspace.yaml
+# Copy the workspace packages that the frontend depends on. The frontend uses
+# the package source through an alias, so the packages don't need to be built.
+# hadolint ignore=DL3022
+COPY --from=repo_root --chown=node:node packages/js/api-client/package.json ./packages/js/api-client/
+# hadolint ignore=DL3022
+COPY --from=repo_root --chown=node:node packages/js/api-client/src ./packages/js/api-client/src/
+RUN echo '{"packages":["frontend/","packages/js/api-client/"]}' > pnpm-workspace.yaml
# Copy the `frontend/` directory into `/home/node/frontend`, as a package in the monorepo.
COPY --chown=node:node . ./frontend/
@@ -74,6 +80,7 @@ USER node
COPY --from=builder --chown=node:node /home/node/node_modules ./node_modules/
COPY --from=builder --chown=node:node /home/node/frontend ./frontend/
+COPY --from=builder --chown=node:node /home/node/packages ./packages/
WORKDIR /home/node/frontend/
diff --git a/frontend/Dockerfile.playwright b/frontend/Dockerfile.playwright
index c419cceab..627fed91e 100644
--- a/frontend/Dockerfile.playwright
+++ b/frontend/Dockerfile.playwright
@@ -8,7 +8,11 @@ FROM mcr.microsoft.com/playwright:v${PLAYWRIGHT_VERSION}-jammy
# The image's bundled Node is too old for Nuxt 4; upgrade without changing browsers so snapshots stay stable.
RUN npm install -g n && n 22.23.4 && hash -r
-WORKDIR /frontend
+# The compose file mounts the monorepo at `/ov` and keeps the container's
+# `node_modules` in volumes. The volumes copy these folders' permissions.
+WORKDIR /ov/frontend
+RUN mkdir -p /ov/node_modules /ov/frontend/node_modules /ov/packages/js/api-client/node_modules \
+ && chmod -R 777 /ov
COPY package.json .
COPY pnpm-lock.yaml .
diff --git a/frontend/docker-compose.playwright.yml b/frontend/docker-compose.playwright.yml
index 7fa821675..2b2276243 100644
--- a/frontend/docker-compose.playwright.yml
+++ b/frontend/docker-compose.playwright.yml
@@ -6,12 +6,18 @@ services:
args:
- PLAYWRIGHT_VERSION=${PLAYWRIGHT_VERSION}
volumes:
- - .:/frontend:rw,Z
+ # Mount the whole monorepo, so that pnpm uses the root lockfile and the
+ # frontend's workspace dependencies resolve.
+ - ..:/ov:rw,Z
+ # Keep the container's dependencies out of the host's `node_modules`.
+ - root_node_modules:/ov/node_modules
+ - node_modules:/ov/frontend/node_modules
+ - api_client_node_modules:/ov/packages/js/api-client/node_modules
user: ${USER_ID}
- working_dir: /frontend
+ working_dir: /ov/frontend
entrypoint: >
/bin/sh -c '
- pnpm install;
+ pnpm install --frozen-lockfile --filter "@openverse/frontend..." &&
pnpm ${TEST_COMMAND} ${PLAYWRIGHT_ARGS:-};
'
environment:
@@ -21,3 +27,8 @@ services:
- FASTSTART=${FASTSTART:-false}
- PLAYWRIGHT_BASE_URL=${PLAYWRIGHT_BASE_URL:-}
- HMAC_SIGNING_SECRET=${HMAC_SIGNING_SECRET:-}
+
+volumes:
+ root_node_modules:
+ node_modules:
+ api_client_node_modules:
diff --git a/frontend/feat/feature-flags.json b/frontend/feat/feature-flags.json
index 296616d1d..0d0c74f22 100644
--- a/frontend/feat/feature-flags.json
+++ b/frontend/feat/feature-flags.json
@@ -39,6 +39,15 @@
"defaultState": "on",
"description": "Display the UI toggle to change the site color theme and respect system preferences.",
"storage": "cookie"
+ },
+ "proxy_requests": {
+ "status": {
+ "staging": "switchable",
+ "production": "disabled"
+ },
+ "description": "Proxy frontend requests through Nuxt server",
+ "defaultState": "off",
+ "storage": "cookie"
}
},
"groups": [
diff --git a/frontend/i18n/data/en.json5 b/frontend/i18n/data/en.json5
index 5f092e47b..37863b3da 100644
--- a/frontend/i18n/data/en.json5
+++ b/frontend/i18n/data/en.json5
@@ -725,6 +725,8 @@ _{link}_ part of "The translation for English locale is incomplete. Help us get
"noResults.alternatives": "Try a different query or use one of the external sources to expand your search.",
"serverTimeout.heading": "Whoops, it looks like that request took too long to complete. Please try again.",
"unknownError.heading": "Whoops, it looks like something went wrong. Please try again.",
+ "rateLimited.heading": "You’ve sent a lot of requests in a short time.",
+ "rateLimited.description": "Please wait a minute, then try again.",
"searchType.image": "Images",
"searchType.audio": "Audio",
"searchType.all": "All content",
diff --git a/frontend/nuxt.config.ts b/frontend/nuxt.config.ts
index dc52eb4ab..945abf71b 100644
--- a/frontend/nuxt.config.ts
+++ b/frontend/nuxt.config.ts
@@ -1,3 +1,5 @@
+import { fileURLToPath } from "node:url"
+
import { defineNuxtConfig } from "nuxt/config"
import tailwindcss from "@tailwindcss/vite"
@@ -43,9 +45,32 @@ export default defineNuxtConfig({
*
* @see {@link https://nuxt.com/docs/api/nuxt-config#runtimeconfig-1}
*/
+ alias: {
+ // Use the source of the workspace package, so that it doesn't need to be
+ // built before the frontend.
+ "@openverse/api-client": fileURLToPath(
+ new URL("../packages/js/api-client/src/index.ts", import.meta.url)
+ ),
+ },
runtimeConfig: {
apiClientId: "",
apiClientSecret: "",
+ // The API address that Nitro uses for proxied requests, overridden by
+ // NUXT_API_URL_INTERNAL. Falls back to `public.apiUrl` when empty.
+ apiUrlInternal: "",
+ // Signs the `ovSession` cookie, overridden by NUXT_HMAC_SIGNING_SECRET.
+ // Must be at least 32 characters long.
+ hmacSigningSecret: "",
+ rateLimit: {
+ // `log` only logs the requests that would be limited, `enforce` rejects them.
+ mode: "log",
+ windowSeconds: 60,
+ sessionLimit: 120,
+ noSessionLimit: 30,
+ ipLimit: 1200,
+ // The number of proxies that append to `X-Forwarded-For`.
+ trustedProxies: 1,
+ },
public: {
deploymentEnv: "local",
apiUrl: "https://api.openverse.org/",
diff --git a/frontend/package.json b/frontend/package.json
index be128c2f7..5b1d20d41 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -49,6 +49,7 @@
"doc:media-props": "node ./scripts/document-media.js"
},
"dependencies": {
+ "@openverse/api-client": "workspace:*",
"@floating-ui/dom": "^1.6.8",
"@nuxtjs/plausible": "^3.0.2",
"@nuxtjs/robots": "^5.7.1",
diff --git a/frontend/server/api/[type]/[id].get.ts b/frontend/server/api/[type]/[id].get.ts
new file mode 100644
index 000000000..4983fe4ad
--- /dev/null
+++ b/frontend/server/api/[type]/[id].get.ts
@@ -0,0 +1,6 @@
+import { defineEventHandler } from "h3"
+import { proxyApiRequest } from "~~/server/utils/proxy"
+
+export default defineEventHandler((event) =>
+ proxyApiRequest(event, "single-result")
+)
diff --git a/frontend/server/api/[type]/related/[id].get.ts b/frontend/server/api/[type]/related/[id].get.ts
new file mode 100644
index 000000000..0fd06fbae
--- /dev/null
+++ b/frontend/server/api/[type]/related/[id].get.ts
@@ -0,0 +1,4 @@
+import { defineEventHandler } from "h3"
+import { proxyApiRequest } from "~~/server/utils/proxy"
+
+export default defineEventHandler((event) => proxyApiRequest(event, "related"))
diff --git a/frontend/server/api/search/[type].get.ts b/frontend/server/api/search/[type].get.ts
new file mode 100644
index 000000000..78ee6c702
--- /dev/null
+++ b/frontend/server/api/search/[type].get.ts
@@ -0,0 +1,4 @@
+import { defineEventHandler } from "h3"
+import { proxyApiRequest } from "~~/server/utils/proxy"
+
+export default defineEventHandler((event) => proxyApiRequest(event, "search"))
diff --git a/frontend/server/middleware/rate-limit.ts b/frontend/server/middleware/rate-limit.ts
new file mode 100644
index 000000000..48834b275
--- /dev/null
+++ b/frontend/server/middleware/rate-limit.ts
@@ -0,0 +1,116 @@
+import { useRuntimeConfig } from "nitropack/runtime"
+import {
+ createError,
+ defineEventHandler,
+ getCookie,
+ getRequestURL,
+ setResponseHeader,
+ unsealSession,
+ type H3Event,
+ type SessionConfig,
+} from "h3"
+import { logger } from "~~/server/utils/logger"
+import { isInternalRequest } from "~~/server/utils/proxy"
+import {
+ getClientIp,
+ getRateLimitChecks,
+ getRateLimitedRequestKind,
+ RateLimiter,
+ type RateLimitConfig,
+} from "~~/server/utils/rate-limit"
+
+import { getSessionConfig } from "#shared/utils/session"
+
+let limiter: RateLimiter | null = null
+let nextSummaryAt = 0
+
+const readSessionId = async (event: H3Event, config: SessionConfig | null) => {
+ if (!config?.name) {
+ return null
+ }
+ const sealed = getCookie(event, config.name)
+ if (!sealed) {
+ return null
+ }
+ try {
+ const session = await unsealSession(event, config, sealed)
+ return typeof session.id === "string" && session.id ? session.id : null
+ } catch {
+ // An expired or forged session is the same as no session.
+ return null
+ }
+}
+
+const toRateLimitConfig = (
+ config: Record<string, unknown>
+): RateLimitConfig => ({
+ mode: String(config.mode),
+ windowSeconds: Number(config.windowSeconds),
+ sessionLimit: Number(config.sessionLimit),
+ noSessionLimit: Number(config.noSessionLimit),
+ ipLimit: Number(config.ipLimit),
+ trustedProxies: Number(config.trustedProxies),
+})
+
+/**
+ * Limits the proxy routes and the pages that call the API during SSR.
+ * In `log` mode, it only logs the requests that would be limited. Session
+ * values and IP addresses are never logged.
+ *
+ * In-process SSR requests to the proxy routes are not counted, because their
+ * page load is already counted.
+ */
+export default defineEventHandler(async (event) => {
+ const kind = getRateLimitedRequestKind(getRequestURL(event).pathname)
+ if (!kind || (kind === "api" && isInternalRequest(event))) {
+ return
+ }
+
+ const runtimeConfig = useRuntimeConfig(event)
+ const config = toRateLimitConfig(runtimeConfig.rateLimit)
+ limiter ??= new RateLimiter(config.windowSeconds * 1000)
+
+ const sessionId = await readSessionId(
+ event,
+ getSessionConfig(
+ runtimeConfig.hmacSigningSecret,
+ runtimeConfig.public.deploymentEnv
+ )
+ )
+ const ip = getClientIp(event, config.trustedProxies)
+ const result = limiter.hit(
+ getRateLimitChecks({ kind, sessionId, ip, config })
+ )
+
+ const now = Date.now()
+ if (now >= nextSummaryAt) {
+ nextSummaryAt = now + config.windowSeconds * 1000
+ const counts = limiter.takeLimitedCounts()
+ if (Object.values(counts).some(Boolean)) {
+ logger.info("Rate limited requests by counter", counts)
+ }
+ }
+
+ if (!result) {
+ return
+ }
+
+ const enforce = config.mode === "enforce"
+ if (result.isFirstExceeded) {
+ logger.warn("Rate limit exceeded", {
+ counter: result.counter,
+ requestKind: kind,
+ enforced: enforce,
+ })
+ }
+ if (!enforce) {
+ return
+ }
+
+ setResponseHeader(event, "Retry-After", result.retryAfterSeconds)
+ throw createError({
+ statusCode: 429,
+ statusMessage: "Too Many Requests",
+ data: { retryAfter: result.retryAfterSeconds },
+ })
+})
diff --git a/frontend/server/plugins/proxy.ts b/frontend/server/plugins/proxy.ts
new file mode 100644
index 000000000..d3209fc07
--- /dev/null
+++ b/frontend/server/plugins/proxy.ts
@@ -0,0 +1,65 @@
+import { randomUUID } from "node:crypto"
+
+import { defineNitroPlugin, useRuntimeConfig } from "nitropack/runtime"
+import { createOpenverseApiClient } from "~~/server/utils/api-client"
+import { logger } from "~~/server/utils/logger"
+
+import { LOCAL } from "#shared/constants/deploy-env"
+import { getSessionConfig } from "#shared/utils/session"
+
+/**
+ * Creates the Openverse API client for the proxy routes and adds it to the
+ * event context as `event.context.apiClient`.
+ *
+ * Outside the local environment, the proxied requests must be authenticated.
+ * Without the API credentials, the client is not created and the proxy routes
+ * return 500, but the rest of the site keeps working, for example, when the
+ * `proxy_requests` flag is off or in the Playwright tests.
+ */
+export default defineNitroPlugin((nitroApp) => {
+ const config = useRuntimeConfig()
+ const isLocal = config.public.deploymentEnv === LOCAL
+ const { apiClientId: clientId, apiClientSecret: clientSecret } = config
+
+ const hasCredentials = Boolean(clientId && clientSecret)
+ if (!hasCredentials) {
+ if (isLocal) {
+ logger.warn(
+ "API client ID and secret are not set. Proxied API requests are anonymous."
+ )
+ } else {
+ logger.error(
+ "API client ID and secret are not set. The proxy routes are disabled."
+ )
+ }
+ }
+
+ if (
+ !getSessionConfig(config.hmacSigningSecret, config.public.deploymentEnv)
+ ) {
+ logger.error(
+ "The session secret is missing or shorter than 32 characters. Rate limits count all requests by IP address."
+ )
+ }
+
+ const apiUrl = config.apiUrlInternal || config.public.apiUrl
+ const apiClient =
+ hasCredentials || isLocal
+ ? createOpenverseApiClient({
+ apiUrl,
+ credentials: hasCredentials ? { clientId, clientSecret } : undefined,
+ })
+ : undefined
+ // Only this process knows the token, so a client can't send it to skip the
+ // rate limits. See `isInternalRequest`.
+ const internalRequestToken = randomUUID()
+
+ if (apiClient) {
+ logger.info(`Initialized the Openverse API client with base URL ${apiUrl}`)
+ }
+
+ nitroApp.hooks.hook("request", (event) => {
+ event.context.apiClient = apiClient
+ event.context.internalRequestToken = internalRequestToken
+ })
+})
diff --git a/frontend/server/types/h3.d.ts b/frontend/server/types/h3.d.ts
new file mode 100644
index 000000000..accdcbeac
--- /dev/null
+++ b/frontend/server/types/h3.d.ts
@@ -0,0 +1,10 @@
+import type { OpenverseClient } from "@openverse/api-client"
+
+declare module "h3" {
+ interface H3EventContext {
+ apiClient?: OpenverseClient
+ internalRequestToken?: string
+ }
+}
+
+export {}
diff --git a/frontend/server/utils/api-client.ts b/frontend/server/utils/api-client.ts
new file mode 100644
index 000000000..608e5f37c
--- /dev/null
+++ b/frontend/server/utils/api-client.ts
@@ -0,0 +1,29 @@
+import {
+ createClient,
+ type ClientCredentials,
+ type OpenverseClient,
+} from "@openverse/api-client"
+
+import { userAgentHeader } from "#shared/constants/user-agent.mjs"
+
+const REQUEST_TIMEOUT_MS = 30_000
+
+/**
+ * Creates the client that Nitro uses to send the proxied requests to the API.
+ * With credentials, the client requests the access token and refreshes it
+ * before it expires. Requests that take longer than 30 seconds are aborted.
+ */
+export const createOpenverseApiClient = ({
+ apiUrl,
+ credentials,
+}: {
+ apiUrl: string
+ credentials?: ClientCredentials
+}): OpenverseClient =>
+ createClient({
+ baseUrl: apiUrl,
+ credentials,
+ headers: userAgentHeader,
+ fetch: (request) =>
+ fetch(request, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }),
+ })
diff --git a/frontend/server/utils/proxy.ts b/frontend/server/utils/proxy.ts
new file mode 100644
index 000000000..5ed8f7559
--- /dev/null
+++ b/frontend/server/utils/proxy.ts
@@ -0,0 +1,236 @@
+import {
+ createError,
+ getQuery,
+ getRequestHeader,
+ getRouterParam,
+ setResponseHeader,
+ type H3Event,
+} from "h3"
+
+import {
+ isSupportedMediaType,
+ type SupportedMediaType,
+} from "#shared/constants/media"
+import {
+ INTERNAL_REQUEST_HEADER,
+ RELATED_QUERY_ALLOWLIST,
+ SEARCH_QUERY_ALLOWLIST,
+} from "#shared/constants/proxy"
+import { mediaSlug, validateUUID } from "#shared/utils/query-utils"
+import type { Events } from "#shared/types/analytics"
+
+import type { OpenverseClient } from "@openverse/api-client"
+
+export type ProxyRequestKind = "search" | "single-result" | "related"
+
+export type SearchTimeEventPayload = Events["SEARCH_RESPONSE_TIME"]
+
+const QUERY_ALLOWLISTS: Record<ProxyRequestKind, readonly string[]> = {
+ search: SEARCH_QUERY_ALLOWLIST,
+ "single-result": [],
+ related: RELATED_QUERY_ALLOWLIST,
+}
+
+const notFound = () =>
+ createError({ statusCode: 404, statusMessage: "Not Found" })
+
+/**
+ * Keeps only the string values of the allowed query parameters, so that the
+ * proxy can't be used to send other parameters, such as `page_size`, with the
+ * frontend's credentials.
+ */
+export const filterQuery = (
+ query: Record<string, unknown>,
+ allowlist: readonly string[]
+): Record<string, string> => {
+ const filtered: Record<string, string> = {}
+ for (const key of allowlist) {
+ const value = query[key]
+ if (typeof value === "string") {
+ filtered[key] = value
+ }
+ }
+ return filtered
+}
+
+/**
+ * Validates the route params so that the proxy routes can only reach the
+ * search, single result and related media endpoints of the API.
+ */
+export const validateRequest = (event: H3Event, kind: ProxyRequestKind) => {
+ const mediaType = getRouterParam(event, "type")
+ if (!mediaType || !isSupportedMediaType(mediaType)) {
+ throw notFound()
+ }
+
+ let id: string | undefined
+ if (kind !== "search") {
+ id = getRouterParam(event, "id")
+ if (!validateUUID(id)) {
+ throw notFound()
+ }
+ }
+
+ return {
+ mediaType,
+ id,
+ query: filterQuery(getQuery(event), QUERY_ALLOWLISTS[kind]),
+ }
+}
+
+/**
+ * Returns the API schema path for the request, with an `{identifier}`
+ * placeholder for the media id. For example, `related` for `image` returns
+ * `/v1/images/{identifier}/related/`.
+ */
+export const generateApiPath = (
+ kind: ProxyRequestKind,
+ mediaType: SupportedMediaType
+) => {
+ const slug = mediaSlug(mediaType)
+ switch (kind) {
+ case "search": {
+ return `/v1/${slug}/`
+ }
+ case "single-result": {
+ return `/v1/${slug}/{identifier}/`
+ }
+ case "related": {
+ return `/v1/${slug}/{identifier}/related/`
+ }
+ }
+}
+
+/**
+ * `OpenverseClient.GET` is typed for each schema path, and the proxy chooses
+ * the path at runtime. The query parameters are validated by `filterQuery`.
+ */
+type ProxyGet = (
+ path: string,
+ init: {
+ params: { path?: { identifier: string }; query?: Record<string, string> }
+ }
+) => Promise<{ data?: unknown; error?: unknown; response: Response }>
+
+const getFromApi = (
+ apiClient: OpenverseClient,
+ kind: ProxyRequestKind,
+ mediaType: SupportedMediaType,
+ id: string | undefined,
+ query: Record<string, string>
+) =>
+ (apiClient.GET as unknown as ProxyGet)(generateApiPath(kind, mediaType), {
+ params: { path: id ? { identifier: id } : undefined, query },
+ })
+
+/**
+ * Builds the SEARCH_RESPONSE_TIME analytics event payload from the API
+ * response headers. Returns `undefined` if the response did not pass through
+ * Cloudflare, for example, when Nitro uses the internal API address.
+ */
+export const buildEventPayload = (
+ headers: Headers,
+ requestDatetime: Date,
+ mediaType: SupportedMediaType,
+ query: Record<string, string>
+): SearchTimeEventPayload | undefined => {
+ const date = headers.get("date")
+ const cfCacheStatus = headers.get("cf-cache-status")
+ const cfRayIATA = headers.get("cf-ray")?.split("-")[1]
+ if (!date || !cfCacheStatus || !cfRayIATA) {
+ return
+ }
+
+ const responseDatetime = new Date(date)
+ if (responseDatetime < requestDatetime) {
+ return
+ }
+
+ const search = new URLSearchParams(query).toString()
+ return {
+ cfCacheStatus,
+ cfRayIATA,
+ elapsedTime: Math.floor(
+ (responseDatetime.getTime() - requestDatetime.getTime()) / 1000
+ ),
+ queryString: search ? `?${search}` : "",
+ mediaType,
+ }
+}
+
+const isTimeoutError = (error: unknown) => {
+ const { name, cause } = error as { name?: string; cause?: { name?: string } }
+ return name === "TimeoutError" || cause?.name === "TimeoutError"
+}
+
+/**
+ * Whether the request is an in-process SSR request, whose page load has
+ * already been counted by the rate limits.
+ */
+export const isInternalRequest = (event: H3Event) => {
+ const token = event.context.internalRequestToken
+ return (
+ Boolean(token) && getRequestHeader(event, INTERNAL_REQUEST_HEADER) === token
+ )
+}
+
+/**
+ * Forwards the request to the API with the frontend's credentials. The
+ * browser's cookies and headers are not forwarded.
+ *
+ * API errors are returned with the API's status code and `detail` message.
+ * Timeouts return 504 and other failures, including a failed API token
+ * request, return 502.
+ */
+export const proxyApiRequest = async (
+ event: H3Event,
+ kind: ProxyRequestKind
+) => {
+ const { apiClient } = event.context
+ if (!apiClient) {
+ throw createError({
+ statusCode: 500,
+ statusMessage: "The Openverse API client is not initialized.",
+ })
+ }
+
+ const { mediaType, id, query } = validateRequest(event, kind)
+ const requestDatetime = new Date()
+
+ let result: Awaited<ReturnType<typeof getFromApi>>
+ try {
+ result = await getFromApi(apiClient, kind, mediaType, id, query)
+ } catch (error) {
+ const isTimeout = isTimeoutError(error)
+ throw createError({
+ statusCode: isTimeout ? 504 : 502,
+ data: { code: isTimeout ? "ECONNABORTED" : "ERR_BAD_RESPONSE" },
+ })
+ }
+
+ const { data, error, response } = result
+ if (!response.ok) {
+ const retryAfter = Number(response.headers.get("retry-after"))
+ if (retryAfter > 0) {
+ setResponseHeader(event, "Retry-After", retryAfter)
+ }
+ const detail = (error as { detail?: unknown } | undefined)?.detail
+ throw createError({
+ statusCode: response.status,
+ data: typeof detail === "string" ? { detail } : undefined,
+ })
+ }
+
+ if (kind === "search") {
+ return {
+ eventPayload: buildEventPayload(
+ response.headers,
+ requestDatetime,
+ mediaType,
+ query
+ ),
+ data,
+ }
+ }
+ return data
+}
diff --git a/frontend/server/utils/rate-limit.ts b/frontend/server/utils/rate-limit.ts
new file mode 100644
index 000000000..b7a4ac5eb
--- /dev/null
+++ b/frontend/server/utils/rate-limit.ts
@@ -0,0 +1,190 @@
+import { getRequestHeader, getRequestIP, type H3Event } from "h3"
+
+export type RateLimitCounter = "session" | "no-session" | "ip"
+export type RateLimitedRequestKind = "api" | "page"
+
+export interface RateLimitConfig {
+ mode: string
+ windowSeconds: number
+ sessionLimit: number
+ noSessionLimit: number
+ ipLimit: number
+ trustedProxies: number
+}
+
+export interface RateLimitCheck {
+ counter: RateLimitCounter
+ key: string
+ limit: number
+}
+
+export interface RateLimitResult {
+ counter: RateLimitCounter
+ retryAfterSeconds: number
+ /** Whether this is the first request over the limit in the window. */
+ isFirstExceeded: boolean
+}
+
+const PROXY_ROUTE_PATTERN =
+ /^\/api\/(?:search\/[^/]+|[^/]+\/related\/[^/]+|[^/]+\/[^/]+)\/?$/
+/**
+ * The pages that call the API during SSR, with an optional locale prefix:
+ * search, collection and single result pages.
+ */
+const API_PAGE_PATTERN =
+ /^(?:\/[a-z]{2,3}(?:-[a-z0-9]+)*)?\/(?:search(?:\/(?:image|audio))?|(?:image|audio)\/[^/]+(?:\/.*)?)\/?$/
+
+/**
+ * Returns which kind of rate-limited request this is, or `null` if the
+ * request is not rate-limited.
+ */
+export const getRateLimitedRequestKind = (
+ pathname: string
+): RateLimitedRequestKind | null => {
+ if (PROXY_ROUTE_PATTERN.test(pathname)) {
+ return "api"
+ }
+ if (API_PAGE_PATTERN.test(pathname)) {
+ return "page"
+ }
+ return null
+}
+
+/**
+ * Returns the client IP address from the `X-Forwarded-For` entry added by the
+ * closest trusted proxy, our load balancer. The earlier entries come from the
+ * client and can be faked.
+ */
+export const getClientIp = (event: H3Event, trustedProxies: number) => {
+ const forwardedFor = getRequestHeader(event, "x-forwarded-for")
+ if (forwardedFor && trustedProxies > 0) {
+ const entries = forwardedFor
+ .split(",")
+ .map((entry) => entry.trim())
+ .filter(Boolean)
+ const entry = entries[Math.max(entries.length - trustedProxies, 0)]
+ if (entry) {
+ return entry
+ }
+ }
+ return getRequestIP(event) ?? "unknown"
+}
+
+interface Window {
+ count: number
+ resetAt: number
+}
+
+/**
+ * In-memory fixed-window counters. They are per Nuxt task, so the limits are
+ * approximate. Keys are kept only until their window ends.
+ */
+export class RateLimiter {
+ private windows = new Map<string, Window>()
+ private limited: Record<RateLimitCounter, number> = {
+ session: 0,
+ "no-session": 0,
+ ip: 0,
+ }
+ private nextPruneAt = 0
+
+ constructor(
+ private windowMs: number,
+ private now: () => number = Date.now
+ ) {}
+
+ /**
+ * Counts the request in every check and returns the first exceeded limit,
+ * or `null` if the request is under all the limits.
+ */
+ hit(checks: RateLimitCheck[]): RateLimitResult | null {
+ const now = this.now()
+ this.prune(now)
+
+ let result: RateLimitResult | null = null
+ for (const { counter, key, limit } of checks) {
+ const windowKey = `${counter}:${key}`
+ let window = this.windows.get(windowKey)
+ if (!window || window.resetAt <= now) {
+ window = { count: 0, resetAt: now + this.windowMs }
+ this.windows.set(windowKey, window)
+ }
+ window.count += 1
+ if (!result && window.count > limit) {
+ this.limited[counter] += 1
+ result = {
+ counter,
+ retryAfterSeconds: Math.max(
+ Math.ceil((window.resetAt - now) / 1000),
+ 1
+ ),
+ isFirstExceeded: window.count === limit + 1,
+ }
+ }
+ }
+ return result
+ }
+
+ /**
+ * Returns the number of limited requests by counter since the last call,
+ * and resets them.
+ */
+ takeLimitedCounts() {
+ const counts = { ...this.limited }
+ this.limited = { session: 0, "no-session": 0, ip: 0 }
+ return counts
+ }
+
+ get size() {
+ return this.windows.size
+ }
+
+ private prune(now: number) {
+ if (now < this.nextPruneAt) {
+ return
+ }
+ for (const [key, window] of this.windows) {
+ if (window.resetAt <= now) {
+ this.windows.delete(key)
+ }
+ }
+ this.nextPruneAt = now + this.windowMs
+ }
+}
+
+/**
+ * Returns the counters that a request is counted by.
+ * - A request with a session counts toward its session limit.
+ * - An `/api` request without a session counts toward the low per-IP limit.
+ * - A page load without a session counts only toward the per-IP ceiling,
+ * because every new visitor arrives this way.
+ * - Every request counts toward the per-IP ceiling.
+ */
+export const getRateLimitChecks = ({
+ kind,
+ sessionId,
+ ip,
+ config,
+}: {
+ kind: RateLimitedRequestKind
+ sessionId: string | null
+ ip: string
+ config: RateLimitConfig
+}): RateLimitCheck[] => {
+ const checks: RateLimitCheck[] = []
+ if (sessionId) {
+ checks.push({
+ counter: "session",
+ key: sessionId,
+ limit: config.sessionLimit,
+ })
+ } else if (kind === "api") {
+ checks.push({
+ counter: "no-session",
+ key: ip,
+ limit: config.noSessionLimit,
+ })
+ }
+ checks.push({ counter: "ip", key: ip, limit: config.ipLimit })
+ return checks
+}
diff --git a/frontend/shared/constants/proxy.ts b/frontend/shared/constants/proxy.ts
new file mode 100644
index 000000000..76bd9eb07
--- /dev/null
+++ b/frontend/shared/constants/proxy.ts
@@ -0,0 +1,38 @@
+/**
+ * The prefix of the Nitro routes that proxy requests to the Openverse API.
+ */
+export const PROXY_ROUTE_PREFIX = "/api/"
+
+/**
+ * The header that marks the in-process SSR requests to the proxy routes.
+ * Its value is a random token that only the Nitro process knows, so a client
+ * cannot use it to skip the rate limits.
+ */
+export const INTERNAL_REQUEST_HEADER = "x-ov-internal-request"
+
+/**
+ * The query parameters that the frontend sends to the search endpoints.
+ * The proxy drops all others, including `page_size`, so that visitors don't
+ * get the larger page size that authenticated requests allow.
+ */
+export const SEARCH_QUERY_ALLOWLIST = [
+ "q",
+ "page",
+ "license",
+ "license_type",
+ "extension",
+ "size",
+ "aspect_ratio",
+ "category",
+ "source",
+ "length",
+ "peaks",
+ "unstable__include_sensitive_results",
+ "collection",
+ "unstable__collection",
+ "tag",
+ "unstable__tag",
+ "creator",
+] as const
+
+export const RELATED_QUERY_ALLOWLIST = ["peaks"] as const
diff --git a/frontend/shared/utils/session.ts b/frontend/shared/utils/session.ts
new file mode 100644
index 000000000..d3d4de2ed
--- /dev/null
+++ b/frontend/shared/utils/session.ts
@@ -0,0 +1,42 @@
+import { LOCAL, type DeployEnv } from "#shared/constants/deploy-env"
+
+import type { SessionConfig } from "h3"
+
+export const SESSION_NAME = "ovSession"
+export const SESSION_MAX_AGE_SECONDS = 60 * 60 * 24
+
+/**
+ * Used only in the local environment, so that the session works without
+ * setting up a secret. h3 requires the password to be at least 32 characters.
+ */
+const LOCAL_SESSION_SECRET = "openverse-local-development-session-secret"
+
+/**
+ * Returns the config for the anonymous session that the Nitro rate limits use
+ * to tell apart the people who share an IP address, or `null` if the session
+ * secret is not set outside the local environment.
+ *
+ * The session is read only from the cookie, so `sessionHeader` is disabled.
+ */
+export const getSessionConfig = (
+ secret: string,
+ deploymentEnv: DeployEnv | string
+): SessionConfig | null => {
+ const isLocal = deploymentEnv === LOCAL
+ const password = secret || (isLocal ? LOCAL_SESSION_SECRET : "")
+ if (password.length < 32) {
+ return null
+ }
+ return {
+ name: SESSION_NAME,
+ password,
+ maxAge: SESSION_MAX_AGE_SECONDS,
+ sessionHeader: false,
+ cookie: {
+ httpOnly: true,
+ secure: !isLocal,
+ sameSite: "lax",
+ path: "/",
+ },
+ }
+}
diff --git a/frontend/src/components/VErrorSection/VErrorSection.vue b/frontend/src/components/VErrorSection/VErrorSection.vue
index e04b9afa4..35a6857da 100644
--- a/frontend/src/components/VErrorSection/VErrorSection.vue
+++ b/frontend/src/components/VErrorSection/VErrorSection.vue
@@ -30,6 +30,8 @@ const errorCode = computed(() =>
props.fetchingError.code === NO_RESULT ? NO_RESULT : SERVER_TIMEOUT
)
+const isRateLimited = computed(() => props.fetchingError.statusCode === 429)
+
const isTimeout = computed(() =>
[SERVER_TIMEOUT, ECONNABORTED].includes(props.fetchingError.code)
)
@@ -44,6 +46,14 @@ const isTimeout = computed(() =>
</div>
<div class="grow p-4 md:p-20">
<VNoResults v-if="errorCode === NO_RESULT" :search-term="searchTerm" />
+ <div v-else-if="isRateLimited" role="alert">
+ <h1 class="text-center heading-4 font-semibold! md:heading-2">
+ {{ $t("rateLimited.heading") }}
+ </h1>
+ <p class="mt-4 text-center label-regular md:heading-6">
+ {{ $t("rateLimited.description") }}
+ </p>
+ </div>
<div v-else>
<h1 class="text-center heading-4 font-semibold! md:heading-2">
{{
diff --git a/frontend/src/components/VFourOhFour.vue b/frontend/src/components/VFourOhFour.vue
index 080acd862..ad81e2aa0 100644
--- a/frontend/src/components/VFourOhFour.vue
+++ b/frontend/src/components/VFourOhFour.vue
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { navigateTo, useHead } from "#imports"
+import { computed } from "vue"
import { ALL_MEDIA } from "#shared/constants/media"
import { skipToContentTargetId } from "#shared/constants/window"
@@ -12,7 +13,9 @@ import VSvg from "~/components/VSvg/VSvg.vue"
import type { NuxtError } from "#app"
-defineProps<{ error: NuxtError }>()
+const props = defineProps<{ error: NuxtError }>()
+
+const isRateLimited = computed(() => props.error?.statusCode === 429)
const searchStore = useSearchStore()
@@ -51,11 +54,19 @@ useHead({
tabindex="-1"
class="z-10 grow-3 space-y-4 lg:space-y-6"
>
- <h1 class="mb-6 heading-5 lg:mb-10 lg:heading-2">
+ <template v-if="isRateLimited">
+ <h1 class="mb-6 heading-5 lg:mb-10 lg:heading-2">
+ {{ $t("rateLimited.heading") }}
+ </h1>
+ <p class="label-bold lg:heading-6">
+ {{ $t("rateLimited.description") }}
+ </p>
+ </template>
+ <h1 v-else class="mb-6 heading-5 lg:mb-10 lg:heading-2">
{{ $t("404.title") }}
</h1>
<p class="sr-only">{{ error }}</p>
- <p class="label-bold lg:heading-6">
+ <p v-if="!isRateLimited" class="label-bold lg:heading-6">
<i18n-t scope="global" keypath="404.main" tag="span">
<template #link>
<VLink
diff --git a/frontend/src/composables/use-api-client.ts b/frontend/src/composables/use-api-client.ts
index 8e255cd7e..6bd27b1b0 100644
--- a/frontend/src/composables/use-api-client.ts
+++ b/frontend/src/composables/use-api-client.ts
@@ -1,15 +1,35 @@
-import { useNuxtApp } from "#imports"
+import { useNuxtApp, useRequestEvent, useRequestFetch } from "#imports"
import { createApiClient } from "~/data/api-service"
+import { createProxyClient } from "~/data/proxy-service"
import { useFeatureFlagStore } from "~/stores/feature-flag"
+import { useProviderStore } from "~/stores/provider"
+/**
+ * Returns the client for the media requests. With the `proxy_requests` flag
+ * on, the requests go through the Nuxt server routes, otherwise directly to
+ * the API.
+ */
export function useApiClient() {
- const { $openverseApiToken: accessToken } = useNuxtApp()
const featureFlagStore = useFeatureFlagStore()
const fakeSensitive =
featureFlagStore.isOn("fake_sensitive") &&
featureFlagStore.isOn("fetch_sensitive")
+ if (featureFlagStore.isOn("proxy_requests")) {
+ // During SSR, `useRequestFetch` calls the server routes in-process and
+ // forwards the request headers, including the session cookie.
+ return createProxyClient({
+ requestFetch: useRequestFetch(),
+ providerStore: useProviderStore(),
+ fakeSensitive,
+ internalRequestToken: import.meta.server
+ ? useRequestEvent()?.context.internalRequestToken
+ : undefined,
+ })
+ }
+
+ const { $openverseApiToken: accessToken } = useNuxtApp()
return createApiClient({ accessToken, fakeSensitive })
}
diff --git a/frontend/src/data/api-service.ts b/frontend/src/data/api-service.ts
index 9c60358b3..59fa331ca 100644
--- a/frontend/src/data/api-service.ts
+++ b/frontend/src/data/api-service.ts
@@ -55,7 +55,7 @@ export interface MediaResult<
* @param data - search result data
* @param fakeSensitive - whether to fake sensitive data for testing
*/
-function transformResults<T extends Media>(
+export function transformResults<T extends Media>(
mediaType: SupportedMediaType,
data: MediaResult<T[]>,
fakeSensitive: boolean,
diff --git a/frontend/src/data/proxy-service.ts b/frontend/src/data/proxy-service.ts
new file mode 100644
index 000000000..8115f8292
--- /dev/null
+++ b/frontend/src/data/proxy-service.ts
@@ -0,0 +1,86 @@
+import { AUDIO, type SupportedMediaType } from "#shared/constants/media"
+import { INTERNAL_REQUEST_HEADER } from "#shared/constants/proxy"
+import type { Media } from "#shared/types/media"
+import type {
+ PaginatedCollectionQuery,
+ PaginatedSearchQuery,
+} from "#shared/types/search"
+import {
+ type MediaResult,
+ type SearchTimeEventPayload,
+ transformResults,
+} from "~/data/api-service"
+import { decodeMediaData } from "~/utils/decode-media-data"
+import type { useProviderStore } from "~/stores/provider"
+
+type RequestFetch = typeof $fetch
+
+export interface ProxyServiceConfig {
+ requestFetch: RequestFetch
+ providerStore: ReturnType<typeof useProviderStore>
+ /** whether to use fake sensitivity data for testing */
+ fakeSensitive?: boolean
+ /**
+ * The token that marks the in-process SSR requests, so that the rate limits
+ * don't count them twice. Only set on the server.
+ */
+ internalRequestToken?: string
+}
+
+/**
+ * Creates a client with the same interface as `createApiClient` that sends
+ * the requests to the Nuxt server routes instead of the API. The server
+ * routes add the frontend's API credentials.
+ *
+ * It must not call composables, because it is called inside store actions.
+ */
+export const createProxyClient = ({
+ requestFetch,
+ providerStore,
+ fakeSensitive = false,
+ internalRequestToken,
+}: ProxyServiceConfig) => {
+ const headers: Record<string, string> = internalRequestToken
+ ? { [INTERNAL_REQUEST_HEADER]: internalRequestToken }
+ : {}
+
+ const search = async <T extends Media>(
+ mediaType: SupportedMediaType,
+ query: PaginatedSearchQuery | PaginatedCollectionQuery
+ ) => {
+ // Add the `peaks` param to all audio searches automatically
+ if (mediaType === AUDIO) {
+ query.peaks = "true"
+ }
+ const { eventPayload, data } = await requestFetch<{
+ eventPayload?: SearchTimeEventPayload
+ data: MediaResult<T[]>
+ }>(`/api/search/${mediaType}/`, { query, headers })
+
+ return {
+ eventPayload,
+ data: transformResults(mediaType, data, fakeSensitive, providerStore),
+ }
+ }
+
+ const getSingleMedia = async <T extends Media>(
+ mediaType: SupportedMediaType,
+ id: string
+ ) => {
+ const data = await requestFetch<T>(`/api/${mediaType}/${id}/`, { headers })
+ return decodeMediaData(data, mediaType, false, providerStore)
+ }
+
+ const getRelatedMedia = async (mediaType: SupportedMediaType, id: string) => {
+ const query = mediaType === AUDIO ? { peaks: "true" } : {}
+ const data = await requestFetch<{ results: Media[] }>(
+ `/api/${mediaType}/related/${id}/`,
+ { query, headers }
+ )
+ return data.results.map((media) =>
+ decodeMediaData(media, mediaType, false, providerStore)
+ )
+ }
+
+ return { search, getSingleMedia, getRelatedMedia }
+}
diff --git a/frontend/src/plugins/02.init.server.ts b/frontend/src/plugins/02.init.server.ts
index 402498f33..320b820de 100644
--- a/frontend/src/plugins/02.init.server.ts
+++ b/frontend/src/plugins/02.init.server.ts
@@ -1,5 +1,8 @@
-import { defineNuxtPlugin, useCookie } from "#imports"
+import { defineNuxtPlugin, useCookie, useRuntimeConfig } from "#imports"
+import { getSession } from "h3"
+
+import { getSessionConfig } from "#shared/utils/session"
import type { OpenverseCookieState } from "#shared/types/cookies"
import { useFeatureFlagStore } from "~/stores/feature-flag"
import { useUiStore } from "~/stores/ui"
@@ -9,7 +12,7 @@ import { useUiStore } from "~/stores/ui"
* This plugin should run before all other plugins to
* ensure that the store states are ready for other plugins.
*/
-export default defineNuxtPlugin(async () => {
+export default defineNuxtPlugin(async (nuxtApp) => {
/* Feature flag store */
// Feature flag store uses deploymentEnv variable from the runtimeContext,
// and should be the first to initialize. Otherwise, the `[nuxt]` context
@@ -27,4 +30,18 @@ export default defineNuxtPlugin(async () => {
const uiStore = useUiStore()
const uiCookies = useCookie<OpenverseCookieState["ui"]>("ui")
uiStore.initFromCookies(uiCookies.value ?? {})
+
+ /* Session */
+ // The anonymous session lets the Nitro rate limits count the requests of
+ // people who share an IP address separately. `getSession` creates the
+ // session and sets the cookie if the request doesn't have a valid one.
+ const event = nuxtApp.ssrContext?.event
+ const config = useRuntimeConfig()
+ const sessionConfig = getSessionConfig(
+ config.hmacSigningSecret,
+ config.public.deploymentEnv
+ )
+ if (event && sessionConfig) {
+ await getSession(event, sessionConfig)
+ }
})
diff --git a/frontend/src/plugins/04.errors.ts b/frontend/src/plugins/04.errors.ts
index 4183bb105..86f2e1124 100644
--- a/frontend/src/plugins/04.errors.ts
+++ b/frontend/src/plugins/04.errors.ts
@@ -9,6 +9,7 @@ import type { FetchingError, RequestKind } from "#shared/types/fetch-state"
import { debug } from "~/utils/console"
import type { NuxtApp } from "#app"
+import type { FetchError } from "ofetch"
const isValidErrorCode = (
code: string | undefined | null
@@ -23,6 +24,45 @@ function isDetailedResponseData(data: unknown): data is { detail: string } {
return !!data && typeof data === "object" && "detail" in data
}
+/**
+ * Checks the name rather than using `instanceof`, because the app and Nuxt
+ * can use different copies of `ofetch`.
+ */
+const isFetchError = (error: unknown): error is FetchError =>
+ error instanceof Error && error.name === "FetchError"
+
+/**
+ * Normalizes the errors from the Nuxt server proxy routes. The routes return
+ * h3 errors, with the API's `detail` message or an error `code` in `data`.
+ */
+function normalizeProxyFetchError(
+ error: FetchError,
+ fetchingError: FetchingError
+): FetchingError {
+ const errorData = (error.data as { data?: unknown } | undefined)?.data as
+ | { detail?: unknown; code?: unknown }
+ | undefined
+
+ if (error.statusCode) {
+ fetchingError.statusCode = error.statusCode
+ } else {
+ // The request didn't receive a response.
+ fetchingError.code = "ERR_NETWORK"
+ }
+ if (typeof errorData?.code === "string" && isValidErrorCode(errorData.code)) {
+ fetchingError.code = errorData.code
+ }
+
+ const retryAfter = error.response?.headers.get("retry-after")
+ if (retryAfter) {
+ fetchingError.details = { ...fetchingError.details, retryAfter }
+ }
+
+ fetchingError.message =
+ typeof errorData?.detail === "string" ? errorData.detail : error.message
+ return fetchingError
+}
+
/**
* Normalize any error occurring during a network call.
*
@@ -45,6 +85,10 @@ export function normalizeFetchingError(
code: ERR_UNKNOWN,
}
+ if (isFetchError(error)) {
+ return normalizeProxyFetchError(error, fetchingError)
+ }
+
if (!isAxiosError(error)) {
fetchingError.message = (error as Error).message
return fetchingError
diff --git a/frontend/test/playwright/visual-regression/pages/errors.spec.ts b/frontend/test/playwright/visual-regression/pages/errors.spec.ts
index f0d103ab2..3408dab4b 100644
--- a/frontend/test/playwright/visual-regression/pages/errors.spec.ts
+++ b/frontend/test/playwright/visual-regression/pages/errors.spec.ts
@@ -58,10 +58,16 @@ breakpoints.describeXl(({ breakpoint, expectSnapshot }) => {
// eslint-disable-next-line playwright/no-networkidle
await page.waitForLoadState("networkidle")
- await expect(getH1(page, t("404.title"))).toBeVisible()
- await expectSnapshot(page, "generic-error-ltr", page, {
- screenshotOptions: { fullPage: true },
- })
+ const isRateLimited = status === 429
+ await expect(
+ getH1(page, t(isRateLimited ? "rateLimited.heading" : "404.title"))
+ ).toBeVisible()
+ await expectSnapshot(
+ page,
+ isRateLimited ? "rate-limited-error-ltr" : "generic-error-ltr",
+ page,
+ { screenshotOptions: { fullPage: true } }
+ )
})
}
})
@@ -105,13 +111,21 @@ for (const searchType of supportedSearchTypes) {
searchType,
})
- await expect(getH1(page, t("404.title"))).toBeVisible()
- await expectSnapshot(page, "generic-error", page, {
- dir,
- screenshotOptions: {
- fullPage: true,
- },
- })
+ const isRateLimited = errorStatus === 429
+ await expect(
+ getH1(page, t(isRateLimited ? "rateLimited.heading" : "404.title"))
+ ).toBeVisible()
+ await expectSnapshot(
+ page,
+ isRateLimited ? "rate-limited-error" : "generic-error",
+ page,
+ {
+ dir,
+ screenshotOptions: {
+ fullPage: true,
+ },
+ }
+ )
})
}
diff --git a/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-ltr-sm-dark-linux.png b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-ltr-sm-dark-linux.png
new file mode 100644
index 000000000..f877eb1ca
Binary files /dev/null and b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-ltr-sm-dark-linux.png differ
diff --git a/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-ltr-sm-light-linux.png b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-ltr-sm-light-linux.png
new file mode 100644
index 000000000..059434a9a
Binary files /dev/null and b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-ltr-sm-light-linux.png differ
diff --git a/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-ltr-xl-dark-linux.png b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-ltr-xl-dark-linux.png
new file mode 100644
index 000000000..678d2f7d0
Binary files /dev/null and b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-ltr-xl-dark-linux.png differ
diff --git a/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-ltr-xl-light-linux.png b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-ltr-xl-light-linux.png
new file mode 100644
index 000000000..17264062b
Binary files /dev/null and b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-ltr-xl-light-linux.png differ
diff --git a/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-rtl-sm-dark-linux.png b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-rtl-sm-dark-linux.png
new file mode 100644
index 000000000..f877eb1ca
Binary files /dev/null and b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-rtl-sm-dark-linux.png differ
diff --git a/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-rtl-sm-light-linux.png b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-rtl-sm-light-linux.png
new file mode 100644
index 000000000..059434a9a
Binary files /dev/null and b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-rtl-sm-light-linux.png differ
diff --git a/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-rtl-xl-dark-linux.png b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-rtl-xl-dark-linux.png
new file mode 100644
index 000000000..678d2f7d0
Binary files /dev/null and b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-rtl-xl-dark-linux.png differ
diff --git a/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-rtl-xl-light-linux.png b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-rtl-xl-light-linux.png
new file mode 100644
index 000000000..17264062b
Binary files /dev/null and b/frontend/test/playwright/visual-regression/pages/errors.spec.ts-snapshots/rate-limited-error-rtl-xl-light-linux.png differ
diff --git a/frontend/test/unit/specs/data/proxy-service.spec.ts b/frontend/test/unit/specs/data/proxy-service.spec.ts
new file mode 100644
index 000000000..aefaf8691
--- /dev/null
+++ b/frontend/test/unit/specs/data/proxy-service.spec.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it, vi } from "vitest"
+import { image } from "~~/test/unit/fixtures/image"
+
+import { INTERNAL_REQUEST_HEADER } from "#shared/constants/proxy"
+import { createProxyClient } from "~/data/proxy-service"
+import { useProviderStore } from "~/stores/provider"
+
+const { id } = image
+
+const setup = (response: unknown, internalRequestToken?: string) => {
+ const requestFetch = vi.fn().mockResolvedValue(response)
+ const client = createProxyClient({
+ requestFetch: requestFetch as unknown as typeof $fetch,
+ providerStore: useProviderStore(),
+ internalRequestToken,
+ })
+ return { client, requestFetch }
+}
+
+describe("createProxyClient", () => {
+ it("sends searches to the server route and keys results by id", async () => {
+ const { client, requestFetch } = setup({
+ data: {
+ result_count: 1,
+ page_count: 1,
+ page_size: 20,
+ page: 1,
+ results: [image],
+ },
+ })
+
+ const { data } = await client.search("audio", { q: "cat" })
+
+ expect(requestFetch).toHaveBeenCalledWith("/api/search/audio/", {
+ query: { q: "cat", peaks: "true" },
+ headers: {},
+ })
+ expect(Object.keys(data.results)).toEqual([id])
+ })
+
+ it("adds the internal request header when a token is passed", async () => {
+ const { client, requestFetch } = setup({ results: [] }, "token")
+
+ await client.getRelatedMedia("image", id)
+
+ expect(requestFetch).toHaveBeenCalledWith(`/api/image/related/${id}/`, {
+ query: {},
+ headers: { [INTERNAL_REQUEST_HEADER]: "token" },
+ })
+ })
+
+ it("requests a single result", async () => {
+ const { client, requestFetch } = setup(image)
+
+ const item = await client.getSingleMedia("image", id)
+
+ expect(requestFetch).toHaveBeenCalledWith(`/api/image/${id}/`, {
+ headers: {},
+ })
+ expect(item.id).toEqual(id)
+ })
+})
diff --git a/frontend/test/unit/specs/plugins/errors.spec.ts b/frontend/test/unit/specs/plugins/errors.spec.ts
new file mode 100644
index 000000000..9b0f24f0a
--- /dev/null
+++ b/frontend/test/unit/specs/plugins/errors.spec.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vitest"
+import { FetchError } from "ofetch"
+
+import { normalizeFetchingError } from "~/plugins/04.errors"
+
+const fetchError = ({
+ statusCode,
+ data,
+ headers = {},
+}: {
+ statusCode?: number
+ data?: unknown
+ headers?: Record<string, string>
+}) => {
+ const error = new FetchError("[GET] /api/search/image/: request failed")
+ error.statusCode = statusCode
+ error.data = data
+ if (statusCode) {
+ error.response = new Response(null, {
+ status: statusCode,
+ headers,
+ }) as FetchError["response"]
+ }
+ return error
+}
+
+describe("normalizeFetchingError with proxy route errors", () => {
+ it("keeps the status code and the Retry-After header of a 429", () => {
+ const error = fetchError({
+ statusCode: 429,
+ data: { statusCode: 429, data: { retryAfter: 30 } },
+ headers: { "retry-after": "30" },
+ })
+
+ expect(normalizeFetchingError(error, "image", "search")).toMatchObject({
+ statusCode: 429,
+ code: "ERR_UNKNOWN",
+ details: { retryAfter: "30" },
+ })
+ })
+
+ it("uses the API detail message", () => {
+ const error = fetchError({
+ statusCode: 400,
+ data: { statusCode: 400, data: { detail: "Invalid license" } },
+ })
+
+ expect(normalizeFetchingError(error, "image", "search")).toMatchObject({
+ statusCode: 400,
+ message: "Invalid license",
+ })
+ })
+
+ it("uses the error code from the route", () => {
+ const error = fetchError({
+ statusCode: 504,
+ data: { statusCode: 504, data: { code: "ECONNABORTED" } },
+ })
+
+ expect(
+ normalizeFetchingError(error, "audio", "single-result")
+ ).toMatchObject({ statusCode: 504, code: "ECONNABORTED" })
+ })
+
+ it("returns a network error without a response", () => {
+ expect(
+ normalizeFetchingError(fetchError({}), "image", "related")
+ ).toMatchObject({ code: "ERR_NETWORK" })
+ })
+})
diff --git a/frontend/test/unit/specs/server/proxy.spec.ts b/frontend/test/unit/specs/server/proxy.spec.ts
new file mode 100644
index 000000000..f4ef31762
--- /dev/null
+++ b/frontend/test/unit/specs/server/proxy.spec.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from "vitest"
+import {
+ buildEventPayload,
+ filterQuery,
+ generateApiPath,
+} from "~~/server/utils/proxy"
+
+import { SEARCH_QUERY_ALLOWLIST } from "#shared/constants/proxy"
+
+describe("filterQuery", () => {
+ it("keeps only the allowed string parameters", () => {
+ expect(
+ filterQuery(
+ {
+ q: "cat",
+ page: "2",
+ page_size: "50",
+ license: ["by", "cc0"],
+ filter_dead: "false",
+ },
+ SEARCH_QUERY_ALLOWLIST
+ )
+ ).toEqual({ q: "cat", page: "2" })
+ })
+})
+
+describe("generateApiPath", () => {
+ it.each`
+ kind | mediaType | expected
+ ${"search"} | ${"image"} | ${"/v1/images/"}
+ ${"search"} | ${"audio"} | ${"/v1/audio/"}
+ ${"single-result"} | ${"image"} | ${"/v1/images/{identifier}/"}
+ ${"related"} | ${"audio"} | ${"/v1/audio/{identifier}/related/"}
+ `(
+ "returns $expected for $kind $mediaType",
+ ({ kind, mediaType, expected }) => {
+ expect(generateApiPath(kind, mediaType)).toEqual(expected)
+ }
+ )
+})
+
+describe("buildEventPayload", () => {
+ const requestDatetime = new Date("2026-11-13T10:00:00Z")
+
+ it("builds the payload from the Cloudflare headers", () => {
+ const headers = new Headers({
+ date: "Fri, 13 Nov 2026 10:00:02 GMT",
+ "cf-cache-status": "MISS",
+ "cf-ray": "8d1e2f3a4b5c6d7e-AMS",
+ })
+ expect(
+ buildEventPayload(headers, requestDatetime, "image", { q: "cat" })
+ ).toEqual({
+ cfCacheStatus: "MISS",
+ cfRayIATA: "AMS",
+ elapsedTime: 2,
+ queryString: "?q=cat",
+ mediaType: "image",
+ })
+ })
+
+ it("returns undefined without the Cloudflare headers", () => {
+ const headers = new Headers({ date: "Fri, 13 Nov 2026 10:00:02 GMT" })
+ expect(
+ buildEventPayload(headers, requestDatetime, "image", {})
+ ).toBeUndefined()
+ })
+})
diff --git a/frontend/test/unit/specs/server/rate-limit.spec.ts b/frontend/test/unit/specs/server/rate-limit.spec.ts
new file mode 100644
index 000000000..75e34a524
--- /dev/null
+++ b/frontend/test/unit/specs/server/rate-limit.spec.ts
@@ -0,0 +1,145 @@
+import { describe, expect, it } from "vitest"
+import {
+ getClientIp,
+ getRateLimitChecks,
+ getRateLimitedRequestKind,
+ RateLimiter,
+ type RateLimitConfig,
+} from "~~/server/utils/rate-limit"
+
+import type { H3Event } from "h3"
+
+const config: RateLimitConfig = {
+ mode: "log",
+ windowSeconds: 60,
+ sessionLimit: 3,
+ noSessionLimit: 1,
+ ipLimit: 5,
+ trustedProxies: 1,
+}
+
+const eventWithHeaders = (headers: Record<string, string>) =>
+ ({
+ node: { req: { headers, socket: { remoteAddress: "10.0.0.1" } } },
+ headers: new Headers(headers),
+ context: {},
+ }) as unknown as H3Event
+
+describe("getRateLimitedRequestKind", () => {
+ it.each([
+ ["/api/search/image/", "api"],
+ ["/api/search/audio", "api"],
+ ["/api/image/2a2a1c2e-6a3b-4d5c-9e8f-0a1b2c3d4e5f/", "api"],
+ ["/api/audio/related/2a2a1c2e-6a3b-4d5c-9e8f-0a1b2c3d4e5f/", "api"],
+ ["/search", "page"],
+ ["/search/image/", "page"],
+ ["/ru/search/audio", "page"],
+ ["/pt-br/image/2a2a1c2e-6a3b-4d5c-9e8f-0a1b2c3d4e5f", "page"],
+ ["/image/source/flickr/", "page"],
+ ["/api/sources", null],
+ ["/", null],
+ ["/about", null],
+ ["/_nuxt/entry.js", null],
+ ["/search/model-3d", null],
+ ])("returns the kind for %s", (path, expected) => {
+ expect(getRateLimitedRequestKind(path)).toEqual(expected)
+ })
+})
+
+describe("getClientIp", () => {
+ it("uses the entry added by the trusted proxy", () => {
+ const event = eventWithHeaders({
+ "x-forwarded-for": "1.1.1.1, 2.2.2.2, 3.3.3.3",
+ })
+ expect(getClientIp(event, 1)).toEqual("3.3.3.3")
+ expect(getClientIp(event, 2)).toEqual("2.2.2.2")
+ })
+
+ it("does not go past the first entry", () => {
+ const event = eventWithHeaders({ "x-forwarded-for": "1.1.1.1" })
+ expect(getClientIp(event, 3)).toEqual("1.1.1.1")
+ })
+
+ it("falls back to the socket address without the header", () => {
+ expect(getClientIp(eventWithHeaders({}), 1)).toEqual("10.0.0.1")
+ })
+})
+
+describe("getRateLimitChecks", () => {
+ it.each`
+ kind | sessionId | expected
+ ${"api"} | ${"s1"} | ${["session", "ip"]}
+ ${"api"} | ${null} | ${["no-session", "ip"]}
+ ${"page"} | ${"s1"} | ${["session", "ip"]}
+ ${"page"} | ${null} | ${["ip"]}
+ `(
+ "counts $kind requests with session $sessionId by $expected",
+ ({ kind, sessionId, expected }) => {
+ const checks = getRateLimitChecks({
+ kind,
+ sessionId,
+ ip: "1.1.1.1",
+ config,
+ })
+ expect(checks.map(({ counter }) => counter)).toEqual(expected)
+ }
+ )
+})
+
+describe("RateLimiter", () => {
+ const checks = getRateLimitChecks({
+ kind: "api",
+ sessionId: "s1",
+ ip: "1.1.1.1",
+ config,
+ })
+
+ it("returns the exceeded counter after the limit", () => {
+ const limiter = new RateLimiter(60_000, () => 0)
+ for (let i = 0; i < config.sessionLimit; i++) {
+ expect(limiter.hit(checks)).toBeNull()
+ }
+ expect(limiter.hit(checks)).toEqual({
+ counter: "session",
+ retryAfterSeconds: 60,
+ isFirstExceeded: true,
+ })
+ expect(limiter.hit(checks)?.isFirstExceeded).toBe(false)
+ })
+
+ it("counts sessions on one IP separately, up to the IP ceiling", () => {
+ const limiter = new RateLimiter(60_000, () => 0)
+ const hitAs = (sessionId: string) =>
+ limiter.hit(
+ getRateLimitChecks({ kind: "api", sessionId, ip: "1.1.1.1", config })
+ )
+ for (let i = 0; i < config.ipLimit; i++) {
+ expect(hitAs(`session-${i}`)).toBeNull()
+ }
+ expect(hitAs("another-session")?.counter).toEqual("ip")
+ })
+
+ it("resets the counters after the window", () => {
+ let now = 0
+ const limiter = new RateLimiter(60_000, () => now)
+ for (let i = 0; i <= config.sessionLimit; i++) {
+ limiter.hit(checks)
+ }
+ now = 60_000
+ expect(limiter.hit(checks)).toBeNull()
+ expect(limiter.size).toEqual(2)
+ })
+
+ it("reports the limited requests by counter", () => {
+ const limiter = new RateLimiter(60_000, () => 0)
+ for (let i = 0; i < config.sessionLimit + 2; i++) {
+ limiter.hit(checks)
+ }
+ expect(limiter.takeLimitedCounts()).toEqual({
+ session: 2,
+ "no-session": 0,
+ ip: 0,
+ })
+ expect(limiter.takeLimitedCounts().session).toEqual(0)
+ })
+})
diff --git a/packages/js/api-client/src/auth.ts b/packages/js/api-client/src/auth.ts
index 9fee99365..a2895dc98 100644
--- a/packages/js/api-client/src/auth.ts
+++ b/packages/js/api-client/src/auth.ts
@@ -10,6 +10,11 @@ type OAuth2Token = components["schemas"]["OAuth2Token"]
*/
const currTimestamp = (): number => Math.floor(Date.now() / 1e3)
export const EXPIRY_THRESHOLD = 5 // seconds
+/**
+ * How long to wait after a failed token request before requesting again,
+ * so that a long-running client recovers without flooding the token endpoint.
+ */
+export const FAILURE_RETRY_DELAY = 10 // seconds
type MiddlewareOnRequest = (
options: MiddlewareCallbackParams
@@ -55,6 +60,11 @@ export class OpenverseAuthMiddleware implements OpenverseMiddleware {
*/
failure = null as unknown
+ /**
+ * The UNIX timestamp of the most recent API token request failure.
+ */
+ failureTimestamp: number | null = null
+
/**
* The UNIX timestamp at which the current token will expire.
*/
@@ -104,20 +114,24 @@ export class OpenverseAuthMiddleware implements OpenverseMiddleware {
* the lack of a token altogether or due to the existing token's
* pending expiration.
*
- * Furthermore, prevent further API token requests if a previous API token
- * request failed.
- *
- * TODO: is that safe?
+ * After a failed API token request, wait `FAILURE_RETRY_DELAY` seconds
+ * before requesting again.
*
* Refer to the documentation on `mustAwaitTokenRefresh` for further details.
*
* @returns Whether the client should trigger a token refresh.
*/
private shouldTriggerTokenRefresh = () =>
- !(this.failure || this.requesting) &&
+ !this.requesting &&
+ !this.isWaitingAfterFailure() &&
(!(this.apiToken && this.tokenExpiry) ||
this.tokenExpiry - EXPIRY_THRESHOLD < currTimestamp())
+ private isWaitingAfterFailure = () =>
+ Boolean(this.failure) &&
+ this.failureTimestamp !== null &&
+ currTimestamp() - this.failureTimestamp < FAILURE_RETRY_DELAY
+
/**
* Refresh the API token used by credentialed clients.
*
@@ -154,11 +168,13 @@ export class OpenverseAuthMiddleware implements OpenverseMiddleware {
// Clear any previous failures, given this request succeeded
this.failure = null
+ this.failureTimestamp = null
resolve(true)
})
.catch((e) => {
console.error("[openverse-api-client]: Token refresh failed!", e)
this.failure = e
+ this.failureTimestamp = currTimestamp()
resolve(false)
})
})
@@ -189,7 +205,8 @@ export class OpenverseAuthMiddleware implements OpenverseMiddleware {
await this.requesting
}
- if (!this.apiToken || this.failure) {
+ // A failed eager refresh does not affect a token that is still valid.
+ if (!this.apiToken || this.mustAwaitTokenRefresh()) {
const error = new Error(
"Failed to retrieve Openverse API token for credentialed client. Check logs or `cause` for details."
)
diff --git a/packages/js/api-client/tests/client.test.ts b/packages/js/api-client/tests/client.test.ts
index 9cf13f6b7..300dbfc3c 100644
--- a/packages/js/api-client/tests/client.test.ts
+++ b/packages/js/api-client/tests/client.test.ts
@@ -2,9 +2,11 @@ import fs from "node:fs"
import path from "node:path"
import rootNock from "nock"
-import { describe, test, expect } from "vitest"
+import { afterEach, describe, test, expect, vi } from "vitest"
import { createClient, ClientCredentials } from "@openverse/api-client"
+import { FAILURE_RETRY_DELAY } from "../src/auth"
+
const mockThumbnailBuffer = fs.readFileSync(
path.resolve(__dirname, "mock-thumbnail.bin")
)
@@ -136,6 +138,86 @@ describe("OpenverseClient", () => {
expect(scope.isDone()).toBe(true)
})
+ describe("after an api token request failure", () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ test("should request a new api token after the retry delay", async () => {
+ vi.useFakeTimers({ toFake: ["Date"] })
+ vi.setSystemTime(0)
+
+ const { client, nock } = getClientAndNock({
+ clientId: "test",
+ clientSecret: "test-secret",
+ })
+
+ const scope = nock
+ .post("/v1/auth_tokens/token/", TOKEN_REQUEST_BODY)
+ .reply(500, "Server error")
+ .post("/v1/auth_tokens/token/", TOKEN_REQUEST_BODY)
+ .reply(200, {
+ access_token: "test-access-token",
+ scope: "test-scope",
+ expires_in: 3600,
+ token_type: "test-token-type",
+ })
+ .get("/v1/images/")
+ .matchHeader("Authorization", "Bearer test-access-token")
+ .reply(200, { results: [] })
+
+ await expect(client.GET("/v1/images/")).rejects.toThrow()
+
+ // Within the delay, the request fails without a new token request.
+ vi.setSystemTime((FAILURE_RETRY_DELAY - 1) * 1000)
+ await expect(client.GET("/v1/images/")).rejects.toThrow()
+ expect(scope.pendingMocks()).toHaveLength(2)
+
+ vi.setSystemTime(FAILURE_RETRY_DELAY * 1000)
+ const images = await client.GET("/v1/images/")
+
+ expect(images.error).toBeUndefined()
+ scope.done()
+ })
+
+ test("should keep using a token that is still valid", async () => {
+ vi.useFakeTimers({ toFake: ["Date"] })
+ vi.setSystemTime(0)
+
+ const { client, nock } = getClientAndNock({
+ clientId: "test",
+ clientSecret: "test-secret",
+ })
+
+ const scope = nock
+ .post("/v1/auth_tokens/token/", TOKEN_REQUEST_BODY)
+ .reply(200, {
+ access_token: "test-access-token",
+ scope: "test-scope",
+ expires_in: 10,
+ token_type: "test-token-type",
+ })
+ .post("/v1/auth_tokens/token/", TOKEN_REQUEST_BODY)
+ .reply(500, "Server error")
+ .get("/v1/images/")
+ .times(3)
+ .matchHeader("Authorization", "Bearer test-access-token")
+ .reply(200, { results: [] })
+
+ await client.GET("/v1/images/")
+
+ // Within the expiry threshold, the eager refresh fails in the background.
+ vi.setSystemTime(6 * 1000)
+ await client.GET("/v1/images/")
+ await new Promise((resolve) => setTimeout(resolve, 50))
+
+ const images = await client.GET("/v1/images/")
+
+ expect(images.error).toBeUndefined()
+ scope.done()
+ })
+ })
+
test("should send but not await token response if current token still within expiry threshold", async () => {
const { client, nock } = getClientAndNock({
clientId: "test",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9f326a93c..939e76c52 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -80,6 +80,9 @@ importers:
'@nuxtjs/sitemap':
specifier: ^7.6.2
+ '@openverse/api-client':
+ specifier: workspace:*
+ version: link:../packages/js/api-client
'@pinia/nuxt':
specifier: ^0.11.3