raz / registry / worker.ts

148 lines · 7.3 KiB · raw · history · last change 4c98ab55

1// The upstream implements the Docker registry protocol and R2 storage.
2// This adapter exposes anonymous pulls for raz alone. All uploads still
3// pass through upstream authentication; its public identity has only pull.
4import registry, { type Env as RegistryEnv } from "r2-registry";
5import { UserAuthenticator } from "r2-registry/src/user";
6
7interface Env {
8 REGISTRY: R2Bucket;
9 REGISTRY_USERNAME: string;
10 REGISTRY_PASSWORD?: string;
11}
12
13const anonymousUser = "__anonymous_pull__";
14const anonymousPassword = "public-read-only";
15const publicPath = /^\/v2\/raz\/(?:manifests\/[^/]+|blobs\/[^/]+|tags\/list|referrers\/[^/]+)$/;
16const uploadPath = /^\/v2\/raz\/blobs\/uploads\/(?:[^/]+)?$/;
17
18const encoder = new TextEncoder();
19const tokenLifetime = 300;
20const encode = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
21const decode = (text: string) => Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
22
23// One secret serves as publisher password and token signing key. Rotation
24// revokes both. Without a configured password, only public pulls can work.
25async function tokenKey(env: Env) {
26 return crypto.subtle.importKey("raw", encoder.encode(env.REGISTRY_PASSWORD || anonymousPassword),
27 { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
28}
29
30function challenge(request: Request): Response {
31 const url = new URL(request.url);
32 const scope = url.pathname === "/v2/" ? "" : ',scope="repository:raz:pull,push"';
33 return new Response(JSON.stringify({ errors: [{ code: "UNAUTHORIZED", message: "authentication required" }] }), {
34 status: 401,
35 headers: {
36 "Content-Type": "application/json",
37 "Docker-Distribution-Api-Version": "registry/2.0",
38 "WWW-Authenticate": `Bearer realm="${url.origin}/token",service="${url.host}"${scope}`,
39 },
40 });
41}
42
43async function issueToken(request: Request, env: Env): Promise<Response> {
44 if (request.method !== "GET") return new Response(null, { status: 405, headers: { Allow: "GET" } });
45 const url = new URL(request.url);
46 if (url.searchParams.has("service") && url.searchParams.get("service") !== url.host) {
47 return new Response("Unknown service\n", { status: 400 });
48 }
49 const scopes = url.searchParams.getAll("scope");
50 if (scopes.length > 1 || (scopes.length && !/^repository:raz:(pull|push)(,(pull|push))*$/.test(scopes[0]))) {
51 return new Response("Unknown scope\n", { status: 400 });
52 }
53 let publisher = false;
54 if (request.headers.has("Authorization")) {
55 const credentials = env.REGISTRY_PASSWORD ? [{
56 username: env.REGISTRY_USERNAME, password: env.REGISTRY_PASSWORD, capabilities: ["pull", "push"] as ("pull" | "push")[],
57 }] : [];
58 publisher = (await new UserAuthenticator(credentials).checkCredentials(request)).verified;
59 if (!publisher) return challenge(request);
60 }
61 const requested = scopes.length ? scopes[0].split(":")[2].split(",") : ["pull", "push"];
62 const actions = requested.filter((action) => action === "pull" || publisher);
63 const now = Math.floor(Date.now() / 1000);
64 const header = encode(encoder.encode(JSON.stringify({ alg: "HS256", typ: "JWT" })));
65 const payload = encode(encoder.encode(JSON.stringify({
66 iss: "raz-registry", aud: url.host, iat: now, exp: now + tokenLifetime,
67 access: [{ type: "repository", name: "raz", actions }],
68 })));
69 const message = `${header}.${payload}`;
70 const signature = encode(new Uint8Array(await crypto.subtle.sign("HMAC", await tokenKey(env), encoder.encode(message))));
71 return Response.json({ token: `${message}.${signature}`, expires_in: tokenLifetime, issued_at: new Date().toISOString() }, {
72 headers: { "Cache-Control": "no-store" },
73 });
74}
75
76async function bearerActions(request: Request, env: Env): Promise<string[] | null> {
77 try {
78 const token = request.headers.get("Authorization")!.slice(7).split(".");
79 if (token.length !== 3) return null;
80 const valid = await crypto.subtle.verify("HMAC", await tokenKey(env), decode(token[2]), encoder.encode(`${token[0]}.${token[1]}`));
81 if (!valid) return null;
82 const header = JSON.parse(new TextDecoder().decode(decode(token[0])));
83 const payload = JSON.parse(new TextDecoder().decode(decode(token[1])));
84 if (header.alg !== "HS256" || payload.iss !== "raz-registry" || payload.aud !== new URL(request.url).host
85 || !Number.isFinite(payload.exp) || payload.exp <= Date.now() / 1000) return null;
86 const access = payload.access?.find((entry: { type: string; name: string }) => entry.type === "repository" && entry.name === "raz");
87 return Array.isArray(access?.actions) ? access.actions : null;
88 } catch {
89 return null;
90 }
91}
92
93export default {
94 async fetch(request: Request, env: Env, context: ExecutionContext): Promise<Response> {
95 const path = new URL(request.url).pathname;
96 if (path === "/token") return issueToken(request, env);
97 const ping = path === "/v2/";
98 const pull = request.method === "GET" || request.method === "HEAD";
99 if (!ping && !publicPath.test(path) && !uploadPath.test(path)) {
100 return new Response("Not found\n", { status: 404 });
101 }
102
103 const headers = new Headers(request.headers);
104 const authorization = headers.get("Authorization");
105 if (authorization?.startsWith("Bearer ")) {
106 const actions = await bearerActions(request, env);
107 const permitted = actions && (ping || request.method === "HEAD"
108 ? actions.includes("pull") || actions.includes("push")
109 : actions.includes(pull ? "pull" : "push"));
110 if (!permitted) return challenge(request);
111 const publisher = !pull && env.REGISTRY_PASSWORD && actions!.includes("push");
112 if (!pull && !publisher) return challenge(request);
113 const user = publisher ? env.REGISTRY_USERNAME : anonymousUser;
114 const password = publisher ? env.REGISTRY_PASSWORD! : anonymousPassword;
115 headers.set("Authorization", `Basic ${btoa(`${user}:${password}`)}`);
116 } else if (ping && !authorization) {
117 // Docker discovers authentication at the initial ping. Returning 200
118 // here makes it omit credentials on subsequent uploads.
119 return challenge(request);
120 } else if (pull && publicPath.test(path) && !authorization) {
121 headers.set("Authorization", `Basic ${btoa(`${anonymousUser}:${anonymousPassword}`)}`);
122 }
123 const forwarded = new Request(request, {
124 headers,
125 method: ping && request.method === "HEAD" ? "GET" : request.method,
126 });
127 // REGISTRY_CLIENT is initialized by the upstream fetch handler. Do not
128 // pass fallback registries or other credentials into this public service.
129 const registryEnv = {
130 REGISTRY: env.REGISTRY,
131 ENVIRONMENT: "production",
132 USERNAME: env.REGISTRY_USERNAME,
133 PASSWORD: env.REGISTRY_PASSWORD,
134 READONLY_USERNAME: anonymousUser,
135 READONLY_PASSWORD: anonymousPassword,
136 PUSH_COMPATIBILITY_MODE: "full",
137 } as RegistryEnv;
138 const response = await registry.fetch(forwarded, registryEnv, context);
139 if (response.status === 401) return challenge(request);
140 const responseHeaders = new Headers(response.headers);
141 responseHeaders.set("Docker-Distribution-Api-Version", "registry/2.0");
142 return new Response(request.method === "HEAD" ? null : response.body, {
143 status: response.status,
144 statusText: response.statusText,
145 headers: responseHeaders,
146 });
147 },
148} satisfies ExportedHandler<Env>;