Add Cloudflare API controls
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
import type { Env } from "./bindings.js";
|
||||
import { jsonResponse } from "./responses.js";
|
||||
|
||||
const RATE_LIMIT_WINDOW_SECONDS = 60;
|
||||
|
||||
export type ApiHandler = () => Promise<Response>;
|
||||
|
||||
export async function withPublicApiControls(
|
||||
request: Request,
|
||||
env: Env,
|
||||
route: string,
|
||||
allowedMethods: readonly string[],
|
||||
handler: ApiHandler,
|
||||
): Promise<Response> {
|
||||
if (!allowedMethods.includes(request.method)) {
|
||||
const response = jsonResponse({ error: "method_not_allowed" }, 405, {
|
||||
Allow: allowedMethods.join(", "),
|
||||
});
|
||||
recordApiAuditEvent(request, env, route, response, "method_not_allowed");
|
||||
return response;
|
||||
}
|
||||
|
||||
const limit = await env.ELY_RATE_LIMITER.limit({
|
||||
key: rateLimitKey(env.ELY_ENVIRONMENT, route),
|
||||
});
|
||||
if (!limit.success) {
|
||||
const response = jsonResponse({ error: "rate_limited" }, 429, {
|
||||
"Cache-Control": "no-store",
|
||||
"Retry-After": RATE_LIMIT_WINDOW_SECONDS.toString(),
|
||||
});
|
||||
recordApiAuditEvent(request, env, route, response, "rate_limited");
|
||||
return response;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await handler();
|
||||
recordApiAuditEvent(request, env, route, response, "handled");
|
||||
return response;
|
||||
} catch (error) {
|
||||
recordApiAuditEvent(request, env, route, internalErrorResponse(), "exception");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function rateLimitKey(environment: string, route: string): string {
|
||||
return `${environment}:${route}`;
|
||||
}
|
||||
|
||||
function recordApiAuditEvent(
|
||||
request: Request,
|
||||
env: Env,
|
||||
route: string,
|
||||
response: Response,
|
||||
outcome: string,
|
||||
): void {
|
||||
const url = new URL(request.url);
|
||||
env.ELY_API_AUDIT.writeDataPoint({
|
||||
indexes: [env.ELY_ENVIRONMENT],
|
||||
blobs: [
|
||||
route,
|
||||
request.method,
|
||||
url.pathname,
|
||||
outcome,
|
||||
request.headers.get("cf-ray") ?? "",
|
||||
request.headers.get("user-agent") ?? "",
|
||||
],
|
||||
doubles: [response.status, Date.now()],
|
||||
});
|
||||
}
|
||||
|
||||
function internalErrorResponse(): Response {
|
||||
return jsonResponse({ error: "internal_error" }, 500, { "Cache-Control": "no-store" });
|
||||
}
|
||||
@@ -2,7 +2,23 @@ export interface ElyKvNamespace {
|
||||
get(key: string): Promise<string | null>;
|
||||
}
|
||||
|
||||
export interface ElyRateLimit {
|
||||
limit(options: { key: string }): Promise<{ success: boolean }>;
|
||||
}
|
||||
|
||||
export interface ElyAnalyticsDataPoint {
|
||||
indexes?: (ArrayBuffer | string | null)[];
|
||||
doubles?: number[];
|
||||
blobs?: (ArrayBuffer | string | null)[];
|
||||
}
|
||||
|
||||
export interface ElyAnalyticsDataset {
|
||||
writeDataPoint(event?: ElyAnalyticsDataPoint): void;
|
||||
}
|
||||
|
||||
export interface Env {
|
||||
ELY_KV: ElyKvNamespace;
|
||||
ELY_RATE_LIMITER: ElyRateLimit;
|
||||
ELY_API_AUDIT: ElyAnalyticsDataset;
|
||||
ELY_ENVIRONMENT: string;
|
||||
}
|
||||
|
||||
+22
-45
@@ -1,4 +1,5 @@
|
||||
import type { Env } from "./bindings.js";
|
||||
import { withPublicApiControls } from "./api_controls.js";
|
||||
import {
|
||||
PluginRegistrySchemaError,
|
||||
parsePluginRegistryDocument,
|
||||
@@ -21,6 +22,7 @@ import {
|
||||
parsePublicSigningKeysDocument,
|
||||
publicSigningKeysKvKey,
|
||||
} from "./signing_keys.js";
|
||||
import { jsonResponse } from "./responses.js";
|
||||
|
||||
export default {
|
||||
fetch(request: Request, env: Env): Promise<Response> {
|
||||
@@ -31,32 +33,36 @@ export default {
|
||||
export async function handleRequest(request: Request, env: Env): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
if (url.pathname === "/api/plugins/signing-keys") {
|
||||
return handlePublicSigningKeys(request, env);
|
||||
return withPublicApiControls(request, env, "plugins.signing_keys", ["GET"], () =>
|
||||
handlePublicSigningKeys(env),
|
||||
);
|
||||
}
|
||||
const pluginRoute = parsePluginRoute(url.pathname);
|
||||
if (pluginRoute !== null) {
|
||||
return handlePluginRoute(request, env, pluginRoute);
|
||||
return withPublicApiControls(request, env, pluginRoute.auditRoute, ["GET"], () =>
|
||||
handlePluginRoute(env, pluginRoute),
|
||||
);
|
||||
}
|
||||
if (url.pathname === "/api/releases/manifest") {
|
||||
return handleReleaseManifest(request, env);
|
||||
return withPublicApiControls(request, env, "releases.manifest", ["GET"], () =>
|
||||
handleReleaseManifest(env),
|
||||
);
|
||||
}
|
||||
if (url.pathname === "/api/releases/signature") {
|
||||
return handleReleaseSignature(request, env, url);
|
||||
return withPublicApiControls(request, env, "releases.signature", ["GET"], () =>
|
||||
handleReleaseSignature(env, url),
|
||||
);
|
||||
}
|
||||
|
||||
return jsonResponse({ error: "not_found" }, 404);
|
||||
}
|
||||
|
||||
type PluginRoute =
|
||||
| { kind: "catalog" }
|
||||
| { kind: "details"; pluginId: string }
|
||||
| { kind: "package"; pluginId: string };
|
||||
|
||||
async function handlePublicSigningKeys(request: Request, env: Env): Promise<Response> {
|
||||
if (request.method !== "GET") {
|
||||
return jsonResponse({ error: "method_not_allowed" }, 405, { Allow: "GET" });
|
||||
}
|
||||
| { kind: "catalog"; auditRoute: "plugins.catalog" }
|
||||
| { kind: "details"; auditRoute: "plugins.details"; pluginId: string }
|
||||
| { kind: "package"; auditRoute: "plugins.package"; pluginId: string };
|
||||
|
||||
async function handlePublicSigningKeys(env: Env): Promise<Response> {
|
||||
const kvKey = publicSigningKeysKvKey(env.ELY_ENVIRONMENT);
|
||||
const value = await env.ELY_KV.get(kvKey);
|
||||
if (value === null) {
|
||||
@@ -77,14 +83,9 @@ async function handlePublicSigningKeys(request: Request, env: Env): Promise<Resp
|
||||
}
|
||||
|
||||
async function handlePluginRoute(
|
||||
request: Request,
|
||||
env: Env,
|
||||
route: PluginRoute,
|
||||
): Promise<Response> {
|
||||
if (request.method !== "GET") {
|
||||
return jsonResponse({ error: "method_not_allowed" }, 405, { Allow: "GET" });
|
||||
}
|
||||
|
||||
const kvKey = pluginRegistryKvKey(env.ELY_ENVIRONMENT);
|
||||
const value = await env.ELY_KV.get(kvKey);
|
||||
if (value === null) {
|
||||
@@ -118,11 +119,7 @@ async function handlePluginRoute(
|
||||
}
|
||||
}
|
||||
|
||||
async function handleReleaseManifest(request: Request, env: Env): Promise<Response> {
|
||||
if (request.method !== "GET") {
|
||||
return jsonResponse({ error: "method_not_allowed" }, 405, { Allow: "GET" });
|
||||
}
|
||||
|
||||
async function handleReleaseManifest(env: Env): Promise<Response> {
|
||||
const kvKey = releaseManifestKvKey(env.ELY_ENVIRONMENT);
|
||||
const value = await env.ELY_KV.get(kvKey);
|
||||
if (value === null) {
|
||||
@@ -143,14 +140,9 @@ async function handleReleaseManifest(request: Request, env: Env): Promise<Respon
|
||||
}
|
||||
|
||||
async function handleReleaseSignature(
|
||||
request: Request,
|
||||
env: Env,
|
||||
url: URL,
|
||||
): Promise<Response> {
|
||||
if (request.method !== "GET") {
|
||||
return jsonResponse({ error: "method_not_allowed" }, 405, { Allow: "GET" });
|
||||
}
|
||||
|
||||
let query;
|
||||
try {
|
||||
query = parseReleaseSignatureQuery(url.searchParams);
|
||||
@@ -186,7 +178,7 @@ async function handleReleaseSignature(
|
||||
|
||||
function parsePluginRoute(pathname: string): PluginRoute | null {
|
||||
if (pathname === "/api/plugins") {
|
||||
return { kind: "catalog" };
|
||||
return { kind: "catalog", auditRoute: "plugins.catalog" };
|
||||
}
|
||||
|
||||
if (!pathname.startsWith("/api/plugins/")) {
|
||||
@@ -199,14 +191,14 @@ function parsePluginRoute(pathname: string): PluginRoute | null {
|
||||
if (pluginId === null) {
|
||||
return null;
|
||||
}
|
||||
return { kind: "details", pluginId };
|
||||
return { kind: "details", auditRoute: "plugins.details", pluginId };
|
||||
}
|
||||
if (segments.length === 5 && segments[4] === "package") {
|
||||
const pluginId = pluginRouteId(segments[3]);
|
||||
if (pluginId === null) {
|
||||
return null;
|
||||
}
|
||||
return { kind: "package", pluginId };
|
||||
return { kind: "package", auditRoute: "plugins.package", pluginId };
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -229,18 +221,3 @@ function pluginRouteId(segment: string | undefined): string | null {
|
||||
function publicPluginCacheHeaders(): Record<string, string> {
|
||||
return { "Cache-Control": "public, max-age=300, stale-while-revalidate=60" };
|
||||
}
|
||||
|
||||
function jsonResponse(
|
||||
body: unknown,
|
||||
status: number,
|
||||
headers: Record<string, string> = {},
|
||||
): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
...headers,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
export function jsonResponse(
|
||||
body: unknown,
|
||||
status: number,
|
||||
headers: Record<string, string> = {},
|
||||
): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
...headers,
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user