Skip to content

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

Sign Nitro's API requests so that Cloudflare rules skip them (#5781)

Olga Bulat4756bf6ae605
diff --git a/frontend/nuxt.config.ts b/frontend/nuxt.config.ts
index 945abf71b..5fc23e71c 100644
--- a/frontend/nuxt.config.ts
+++ b/frontend/nuxt.config.ts
@@ -61,6 +61,9 @@ export default defineNuxtConfig({
// Signs the `ovSession` cookie, overridden by NUXT_HMAC_SIGNING_SECRET.
// Must be at least 32 characters long.
hmacSigningSecret: "",
+ // Signs Nitro's API requests so that the API's Cloudflare rules skip them,
+ // overridden by NUXT_API_REQUEST_SIGNING_SECRET.
+ apiRequestSigningSecret: "",
rateLimit: {
// `log` only logs the requests that would be limited, `enforce` rejects them.
mode: "log",
diff --git a/frontend/server/plugins/proxy.ts b/frontend/server/plugins/proxy.ts
index d3209fc07..3968daecc 100644
--- a/frontend/server/plugins/proxy.ts
+++ b/frontend/server/plugins/proxy.ts
@@ -42,12 +42,19 @@ export default defineNitroPlugin((nitroApp) => {
)
}
+ if (!isLocal && !config.apiRequestSigningSecret) {
+ logger.warn(
+ "The API request signing secret is not set. Proxied API requests are subject to the API's Cloudflare rules."
+ )
+ }
+
const apiUrl = config.apiUrlInternal || config.public.apiUrl
const apiClient =
hasCredentials || isLocal
? createOpenverseApiClient({
apiUrl,
credentials: hasCredentials ? { clientId, clientSecret } : undefined,
+ signingSecret: config.apiRequestSigningSecret,
})
: undefined
// Only this process knows the token, so a client can't send it to skip the
diff --git a/frontend/server/utils/api-client.ts b/frontend/server/utils/api-client.ts
index 608e5f37c..b536a624c 100644
--- a/frontend/server/utils/api-client.ts
+++ b/frontend/server/utils/api-client.ts
@@ -1,3 +1,5 @@
+import { createHmac } from "node:crypto"
+
import {
createClient,
type ClientCredentials,
@@ -8,22 +10,63 @@ import { userAgentHeader } from "#shared/constants/user-agent.mjs"
const REQUEST_TIMEOUT_MS = 30_000
+export const SIGNATURE_TIMESTAMP_HEADER = "x-ov-cf-timestamp"
+export const SIGNATURE_MAC_HEADER = "x-ov-cf-mac"
+
+/**
+ * Returns the headers that let the API's Cloudflare rules skip the request:
+ * the Unix timestamp in seconds and the HMAC-SHA256 of the path, query and
+ * timestamp, encoded as base64url. Cloudflare checks the MAC with
+ * `is_timed_hmac_valid_v0`, using the same scheme as the k6 load tests.
+ */
+export const getSignatureHeaders = (
+ url: string,
+ secret: string,
+ now = Date.now()
+) => {
+ const { pathname, search } = new URL(url)
+ const timestamp = Math.floor(now / 1000).toString()
+ const mac = createHmac("sha256", secret)
+ .update(`${pathname}${search}${timestamp}`)
+ .digest("base64url")
+ return {
+ [SIGNATURE_TIMESTAMP_HEADER]: timestamp,
+ [SIGNATURE_MAC_HEADER]: mac,
+ }
+}
+
/**
* 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.
+ * before it expires. With a signing secret, every request, including the
+ * token requests, is signed. Requests that take longer than 30 seconds are
+ * aborted.
*/
export const createOpenverseApiClient = ({
apiUrl,
credentials,
+ signingSecret,
}: {
apiUrl: string
credentials?: ClientCredentials
+ signingSecret?: string
}): OpenverseClient =>
createClient({
baseUrl: apiUrl,
credentials,
headers: userAgentHeader,
- fetch: (request) =>
- fetch(request, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }),
+ fetch: (request) => {
+ const headers = new Headers(request.headers)
+ if (signingSecret) {
+ for (const [name, value] of Object.entries(
+ getSignatureHeaders(request.url, signingSecret)
+ )) {
+ headers.set(name, value)
+ }
+ }
+ return fetch(request, {
+ headers,
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ })
+ },
})
diff --git a/frontend/test/unit/specs/server/api-client.spec.ts b/frontend/test/unit/specs/server/api-client.spec.ts
new file mode 100644
index 000000000..2dc284c01
--- /dev/null
+++ b/frontend/test/unit/specs/server/api-client.spec.ts
@@ -0,0 +1,60 @@
+import { afterEach, describe, expect, it, vi } from "vitest"
+import {
+ createOpenverseApiClient,
+ getSignatureHeaders,
+} from "~~/server/utils/api-client"
+
+const NOW = 1_763_200_000_000
+
+describe("getSignatureHeaders", () => {
+ it("signs the path, query and timestamp", () => {
+ expect(
+ getSignatureHeaders(
+ "https://api.openverse.org/v1/images/?q=cat%20dog&page=2",
+ "test-secret",
+ NOW
+ )
+ ).toEqual({
+ "x-ov-cf-timestamp": "1763200000",
+ "x-ov-cf-mac": "h4Gq657vV8M3LsN2uks62k4hBnjk5RB1qqJv0W_nTzw",
+ })
+ })
+})
+
+describe("createOpenverseApiClient", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ const getSentHeaders = async (signingSecret?: string) => {
+ const fetchMock = vi.fn(async () => Response.json({ results: [] }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ const client = createOpenverseApiClient({
+ apiUrl: "https://api.openverse.org/",
+ signingSecret,
+ })
+ await client.GET("/v1/images/", { params: { query: { q: "cat" } } })
+
+ const [, init] = fetchMock.mock.calls[0] as unknown as [
+ Request,
+ RequestInit,
+ ]
+ return new Headers(init.headers)
+ }
+
+ it("signs the requests when the secret is set", async () => {
+ const headers = await getSentHeaders("test-secret")
+
+ expect(headers.get("x-ov-cf-timestamp")).toMatch(/^\d+$/)
+ expect(headers.get("x-ov-cf-mac")).toMatch(/^[\w-]{43}$/)
+ expect(headers.get("user-agent")).toContain("Openverse")
+ })
+
+ it("does not sign the requests without the secret", async () => {
+ const headers = await getSentHeaders()
+
+ expect(headers.has("x-ov-cf-timestamp")).toBe(false)
+ expect(headers.has("x-ov-cf-mac")).toBe(false)
+ })
+})