ocre/storage/presign.rs
1//! Presigned URLs (AWS Signature Version 4, query-string form) for R2's S3
2//! API and other S3-compatible stores, and the signed keys of direct uploads.
3//!
4//! Signing is local: two SHA-256 and five HMAC-SHA256 over a few hundred
5//! bytes (a few microseconds of CPU), no binding call and no R2 operation.
6//! The browser's `GET` (class B) or `PUT` (class A) on the URL is what R2 counts.
7
8use std::{collections::BTreeMap, fmt, fmt::Write as _};
9
10use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
11use hmac::{Hmac, Mac};
12use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14
15use super::s3::dev_url;
16use super::{Attachment, BINARY_TYPES, Disposition, Rules, StoredObject, content_disposition, essence, new_key};
17use crate::{Error, Result, Validator, helpers::civil_from_days, percent_encode, token::constant_time_eq};
18
19/// Worker variable holding the Cloudflare account ID, for presigned R2 URLs.
20///
21/// Set it in cloudflare.config.ts (`R2_ACCOUNT_ID: bindings.text("<id>"),` in
22/// `worker.env`); the ID is on the dashboard's R2 overview page. Not a secret.
23///
24/// # Examples
25///
26/// ```
27/// assert_eq!(ocre::storage::R2_ACCOUNT_ID, "R2_ACCOUNT_ID");
28/// ```
29pub const R2_ACCOUNT_ID: &str = "R2_ACCOUNT_ID";
30
31/// Worker variable holding the R2 bucket name (`<app>-storage`), for presigned R2 URLs.
32///
33/// The `STORAGE` binding knows its bucket, but R2's S3 API needs the name in
34/// the URL: set `R2_BUCKET: bindings.text("<app>-storage"),` in `worker.env`.
35///
36/// # Examples
37///
38/// ```
39/// assert_eq!(ocre::storage::R2_BUCKET, "R2_BUCKET");
40/// ```
41pub const R2_BUCKET: &str = "R2_BUCKET";
42
43/// Worker secret holding the access key ID of an R2 API token, for presigned R2 URLs.
44///
45/// Create the token in the dashboard (R2 > Manage API tokens, "Object Read &
46/// Write" on the bucket), put it in `.dev.vars` and upload it with `ocre
47/// secrets push R2_ACCESS_KEY_ID R2_SECRET_ACCESS_KEY --file .prod.vars`.
48///
49/// # Examples
50///
51/// ```
52/// assert_eq!(ocre::storage::R2_ACCESS_KEY_ID, "R2_ACCESS_KEY_ID");
53/// ```
54pub const R2_ACCESS_KEY_ID: &str = "R2_ACCESS_KEY_ID";
55
56/// Worker secret holding the secret access key of an R2 API token, for presigned R2 URLs.
57///
58/// Shown once when the token is created; set it like [`R2_ACCESS_KEY_ID`].
59/// It also signs the keys handed out by [`direct_upload`](crate::storage::direct_upload),
60/// so replacing it invalidates uploads in progress.
61///
62/// # Examples
63///
64/// ```
65/// assert_eq!(ocre::storage::R2_SECRET_ACCESS_KEY, "R2_SECRET_ACCESS_KEY");
66/// ```
67pub const R2_SECRET_ACCESS_KEY: &str = "R2_SECRET_ACCESS_KEY";
68
69/// Longest lifetime of a presigned URL, in seconds: 7 days, the SigV4 maximum.
70///
71/// # Examples
72///
73/// ```
74/// assert_eq!(ocre::storage::MAX_EXPIRES_IN, 7 * 24 * 3600);
75/// ```
76pub const MAX_EXPIRES_IN: u64 = 604_800;
77
78/// An S3-compatible bucket and the credentials to presign URLs for it.
79///
80/// [`S3Endpoint::r2`] builds the one of an R2 bucket; the runtime helpers
81/// ([`presign_get`](crate::storage::presign_get),
82/// [`direct_upload`](crate::storage::direct_upload)...) read it from the
83/// `R2_*` variables and secrets. Fill the fields yourself for another
84/// S3-compatible store (AWS S3, MinIO...). `Debug` hides the secret.
85///
86/// # Examples
87///
88/// ```
89/// use ocre::storage::S3Endpoint;
90///
91/// let r2 = S3Endpoint::r2("0123abcd", "blog-storage", "AKID", "s3cr3t");
92/// assert_eq!(r2.host, "0123abcd.r2.cloudflarestorage.com");
93/// assert_eq!(r2.region, "auto");
94/// assert!(!format!("{r2:?}").contains("s3cr3t"));
95/// ```
96#[derive(Clone, PartialEq, Eq)]
97pub struct S3Endpoint {
98 /// Host name of the S3 API, without scheme (`<account_id>.r2.cloudflarestorage.com`).
99 pub host: String,
100 /// Signing region: `auto` for R2.
101 pub region: String,
102 /// Bucket name, put first in the path (`/<bucket>/<key>`, path style); empty when the host already names the bucket.
103 pub bucket: String,
104 /// Access key ID of the credentials.
105 pub access_key_id: String,
106 /// Secret access key of the credentials.
107 pub secret_access_key: String,
108}
109
110impl fmt::Debug for S3Endpoint {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 f.debug_struct("S3Endpoint")
113 .field("host", &self.host)
114 .field("region", &self.region)
115 .field("bucket", &self.bucket)
116 .field("access_key_id", &self.access_key_id)
117 .field("secret_access_key", &"[redacted]")
118 .finish()
119 }
120}
121
122impl S3Endpoint {
123 /// The S3 endpoint of an R2 bucket: host `<account_id>.r2.cloudflarestorage.com`, region `auto`, path-style URLs.
124 ///
125 /// # Examples
126 ///
127 /// ```
128 /// let r2 = ocre::storage::S3Endpoint::r2("acc", "blog-storage", "AKID", "secret");
129 /// assert_eq!((r2.host.as_str(), r2.bucket.as_str()), ("acc.r2.cloudflarestorage.com", "blog-storage"));
130 /// ```
131 pub fn r2(account_id: &str, bucket: &str, access_key_id: &str, secret_access_key: &str) -> Self {
132 Self {
133 host: format!("{account_id}.r2.cloudflarestorage.com"),
134 region: "auto".to_owned(),
135 bucket: bucket.to_owned(),
136 access_key_id: access_key_id.to_owned(),
137 secret_access_key: secret_access_key.to_owned(),
138 }
139 }
140
141 /// Presigns a request on `key` (AWS SigV4, query-string form) and returns its `https://` URL.
142 ///
143 /// `headers` are signed too (`host` always is): the client must send
144 /// them with exactly these values, or the store refuses the request.
145 /// `query` adds parameters such as `response-content-disposition`. The
146 /// payload is not signed (`UNSIGNED-PAYLOAD`). `now` is the Unix time
147 /// of signing ([`ocre::now()`](crate::now)); the URL works for
148 /// `expires_in` seconds. Pure: no binding, a few microseconds of CPU.
149 ///
150 /// # Errors
151 ///
152 /// [`Error::Internal`] when `expires_in` is 0 or over [`MAX_EXPIRES_IN`] (7 days).
153 ///
154 /// # Examples
155 ///
156 /// ```
157 /// use ocre::storage::S3Endpoint;
158 ///
159 /// let r2 = S3Endpoint::r2("acc", "blog-storage", "AKID", "secret");
160 /// let url = r2.presign("GET", "exports/report 1.csv", &[], &[], 1_790_000_000, 300).unwrap();
161 /// assert!(url.starts_with("https://acc.r2.cloudflarestorage.com/blog-storage/exports/report%201.csv?X-Amz-Algorithm="));
162 /// assert!(url.contains("&X-Amz-Expires=300&"));
163 /// assert!(r2.presign("GET", "k", &[], &[], 1_790_000_000, 8 * 24 * 3600).is_err());
164 /// ```
165 pub fn presign(
166 &self,
167 method: &str,
168 key: &str,
169 headers: &[(&str, &str)],
170 query: &[(&str, &str)],
171 now: i64,
172 expires_in: u64,
173 ) -> Result<String> {
174 check_expires_in(expires_in)?;
175 let (date, timestamp) = amz_date(now);
176 let scope = format!("{date}/{}/s3/aws4_request", self.region);
177 let path = match (self.bucket.as_str(), key) {
178 ("", key) => format!("/{}", percent_encode(key, true)),
179 // A request on the bucket itself (ListMultipartUploads).
180 (bucket, "") => format!("/{}", percent_encode(bucket, true)),
181 (bucket, key) => format!("/{}/{}", percent_encode(bucket, true), percent_encode(key, true)),
182 };
183 let mut signed: BTreeMap<String, String> =
184 headers.iter().map(|(name, value)| (name.trim().to_ascii_lowercase(), value.trim().to_owned())).collect();
185 signed.insert("host".to_owned(), self.host.clone());
186 let signed_names = signed.keys().map(String::as_str).collect::<Vec<_>>().join(";");
187 let credential = format!("{}/{scope}", self.access_key_id);
188 let expires = expires_in.to_string();
189 let mut params: Vec<(String, String)> = [
190 ("X-Amz-Algorithm", "AWS4-HMAC-SHA256"),
191 ("X-Amz-Credential", credential.as_str()),
192 ("X-Amz-Date", timestamp.as_str()),
193 ("X-Amz-Expires", expires.as_str()),
194 ("X-Amz-SignedHeaders", signed_names.as_str()),
195 ]
196 .iter()
197 .chain(query)
198 .map(|(name, value)| (percent_encode(name, false), percent_encode(value, false)))
199 .collect();
200 params.sort();
201 let canonical_query =
202 params.iter().map(|(name, value)| format!("{name}={value}")).collect::<Vec<_>>().join("&");
203 let canonical_headers: String = signed.iter().map(|(name, value)| format!("{name}:{value}\n")).collect();
204 let method = method.to_ascii_uppercase();
205 let canonical_request =
206 format!("{method}\n{path}\n{canonical_query}\n{canonical_headers}\n{signed_names}\nUNSIGNED-PAYLOAD");
207 let string_to_sign =
208 format!("AWS4-HMAC-SHA256\n{timestamp}\n{scope}\n{}", hex(&Sha256::digest(canonical_request.as_bytes())));
209 let mut key = hmac(format!("AWS4{}", self.secret_access_key).as_bytes(), date.as_bytes());
210 for part in [self.region.as_str(), "s3", "aws4_request"] {
211 key = hmac(&key, part.as_bytes());
212 }
213 let signature = hex(&hmac(&key, string_to_sign.as_bytes()));
214 Ok(format!("https://{}{path}?{canonical_query}&X-Amz-Signature={signature}", self.host))
215 }
216}
217
218/// What the browser declares before a direct upload: the file's name, type and size.
219///
220/// The JSON body of the "start an upload" request (`{"filename": "a.png",
221/// "content_type": "image/png", "size": 1234}`), read from `File.name`,
222/// `File.type` and `File.size`. [`direct_upload`](crate::storage::direct_upload)
223/// checks it against [`Rules`] before signing anything.
224///
225/// # Examples
226///
227/// ```
228/// let request: ocre::storage::DirectUploadRequest =
229/// serde_json::from_str(r#"{"filename":"a.png","content_type":"image/png","size":1234}"#).unwrap();
230/// assert_eq!(request.size, 1234);
231/// ```
232#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
233pub struct DirectUploadRequest {
234 /// File name, as the browser gives it (cleaned up when attached).
235 pub filename: String,
236 /// Declared content type; signed into the upload URL, so R2 stores this one.
237 pub content_type: String,
238 /// Declared size in bytes; signed into the upload URL as `Content-Length`.
239 pub size: u64,
240}
241
242/// A direct upload the browser may perform: `PUT` the file to `url` with `headers`, then submit `signed_key`.
243///
244/// Returned by [`direct_upload`](crate::storage::direct_upload) and sent to
245/// the browser as JSON (Rails' `direct_upload: { url, headers }` plus
246/// `signed_id`). `signed_key` is the new object key followed by an HMAC:
247/// [`attach_direct_upload`](crate::storage::attach_direct_upload) accepts
248/// only keys this app issued, so a client cannot claim another record's file.
249///
250/// # Examples
251///
252/// ```
253/// use ocre::storage::{DirectUpload, DirectUploadRequest, Rules, S3Endpoint};
254///
255/// const PHOTO: Rules = Rules { max_bytes: 1024, content_types: &["image/png"] };
256/// let r2 = S3Endpoint::r2("acc", "blog-storage", "AKID", "secret");
257/// let request = DirectUploadRequest { filename: "a.png".into(), content_type: "image/png".into(), size: 10 };
258/// let upload = DirectUpload::sign(&r2, "uploads/photos", "image", &request, &PHOTO, 1_790_000_000, 600).unwrap();
259/// assert!(upload.signed_key.starts_with("uploads/photos/"));
260/// assert_eq!(upload.headers["Content-Type"], "image/png");
261/// let json = serde_json::to_value(&upload).unwrap();
262/// assert!(json["url"].as_str().unwrap().contains("X-Amz-SignedHeaders=content-length%3Bcontent-type%3Bhost"));
263/// ```
264#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
265pub struct DirectUpload {
266 /// The object key and its signature (`<prefix>/<22 characters>.<43 characters>`); the form submits it.
267 pub signed_key: String,
268 /// Presigned `PUT` URL on R2's S3 API.
269 pub url: String,
270 /// Headers the `PUT` must carry, exactly (`Content-Type`); the browser adds `Content-Length` itself.
271 pub headers: BTreeMap<String, String>,
272}
273
274impl DirectUpload {
275 /// Checks `request` against `rules` and presigns a `PUT` of a new key under `prefix`, valid `expires_in` seconds.
276 ///
277 /// The URL signs `Content-Type` (the declared type, normalized) and
278 /// `Content-Length` (the declared size), so R2 refuses a `PUT` of
279 /// another type or size. [`direct_upload`](crate::storage::direct_upload)
280 /// calls it with the `R2_*` settings and [`ocre::now()`](crate::now).
281 ///
282 /// # Errors
283 ///
284 /// [`Error::Invalid`] (422) on `field` when the declared size or type
285 /// breaks `rules` (the messages of [`Validator::file`]);
286 /// [`Error::Internal`] when `expires_in` is out of range.
287 ///
288 /// # Examples
289 ///
290 /// ```
291 /// use ocre::storage::{DirectUpload, DirectUploadRequest, Rules, S3Endpoint};
292 ///
293 /// const PHOTO: Rules = Rules { max_bytes: 1024, content_types: &["image/png"] };
294 /// let r2 = S3Endpoint::r2("acc", "blog-storage", "AKID", "secret");
295 /// let svg = DirectUploadRequest { filename: "a.svg".into(), content_type: "image/svg+xml".into(), size: 10 };
296 /// let err = DirectUpload::sign(&r2, "uploads", "image", &svg, &PHOTO, 1_790_000_000, 600).unwrap_err();
297 /// assert_eq!(err.to_string(), "invalid: Image has an unsupported type (allowed: image/png)");
298 /// ```
299 pub fn sign(
300 endpoint: &S3Endpoint,
301 prefix: &str,
302 field: &str,
303 request: &DirectUploadRequest,
304 rules: &Rules,
305 now: i64,
306 expires_in: u64,
307 ) -> Result<Self> {
308 Validator::new().file_size_and_type(field, request.size, &request.content_type, rules).finish()?;
309 let key = new_key(prefix);
310 let content_type = essence(&request.content_type);
311 let size = request.size.to_string();
312 let headers = [("content-type", content_type.as_str()), ("content-length", size.as_str())];
313 let url = endpoint.presign("PUT", &key, &headers, &[], now, expires_in)?;
314 let signed_key = sign_key(&endpoint.secret_access_key, &key);
315 Ok(Self { signed_key, url, headers: BTreeMap::from([("Content-Type".to_owned(), content_type)]) })
316 }
317}
318
319impl DirectUpload {
320 /// [`sign`](Self::sign) for development: the URL is the app's development
321 /// route on the local bucket, and `secret` (`upload_secret`) signs the key.
322 pub(crate) fn sign_dev(
323 base: &str,
324 secret: &str,
325 prefix: &str,
326 field: &str,
327 request: &DirectUploadRequest,
328 rules: &Rules,
329 expires_in: u64,
330 ) -> Result<Self> {
331 Validator::new().file_size_and_type(field, request.size, &request.content_type, rules).finish()?;
332 check_expires_in(expires_in)?;
333 let key = new_key(prefix);
334 let content_type = essence(&request.content_type);
335 let url = dev_url(base, &key, &[], expires_in);
336 Ok(Self {
337 signed_key: sign_key(secret, &key),
338 url,
339 headers: BTreeMap::from([("Content-Type".to_owned(), content_type)]),
340 })
341 }
342}
343
344/// A presigned URL lasts 1 second to [`MAX_EXPIRES_IN`].
345pub(crate) fn check_expires_in(expires_in: u64) -> Result<()> {
346 if expires_in == 0 || expires_in > MAX_EXPIRES_IN {
347 return Err(Error::internal(format!(
348 "a presigned URL lasts 1 to {MAX_EXPIRES_IN} seconds (7 days), not {expires_in}"
349 )));
350 }
351 Ok(())
352}
353
354/// `<key>.<HMAC-SHA256 of the key, URL-safe base64>`, with a key derived from the R2 secret.
355pub(crate) fn sign_key(secret: &str, key: &str) -> String {
356 let mac = hmac(&hmac(secret.as_bytes(), b"ocre.storage.direct_upload"), key.as_bytes());
357 format!("{key}.{}", URL_SAFE_NO_PAD.encode(mac))
358}
359
360/// The key of a `signed_key` made by [`sign_key`] with `secret`; a 422 on `field` when it was not.
361pub(crate) fn verify_key(field: &str, secret: &str, signed_key: &str) -> Result<String> {
362 let key = signed_key.rsplit_once('.').map(|(key, _)| key).unwrap_or_default();
363 let valid = constant_time_eq(sign_key(secret, key).as_bytes(), signed_key.as_bytes());
364 Validator::new().check(field, !valid, "is not a valid upload").finish()?;
365 Ok(key.to_owned())
366}
367
368/// The secret that signs upload keys: `R2_SECRET_ACCESS_KEY` (which direct
369/// uploads need anyway), else `SECRET_KEY_BASE` for uploads that go through
370/// the Worker.
371pub(crate) fn upload_secret(var: &dyn Fn(&str) -> Option<String>) -> Result<String> {
372 [R2_SECRET_ACCESS_KEY, crate::session::SECRET_KEY_BASE]
373 .iter()
374 .find_map(|name| var(name).map(|value| value.trim().to_owned()).filter(|value| !value.is_empty()))
375 .ok_or_else(|| {
376 Error::internal(
377 "uploads need R2_SECRET_ACCESS_KEY or SECRET_KEY_BASE to sign their keys (neither is set). Fix: \
378 `ocre secret` makes a SECRET_KEY_BASE for .dev.vars; `ocre deploy` sets it in production",
379 )
380 })
381}
382
383/// The endpoint of the `R2_*` variables and secrets read with `var`; the error names every missing one.
384pub(crate) fn r2_endpoint(var: &dyn Fn(&str) -> Option<String>) -> Result<S3Endpoint> {
385 let names = [R2_ACCOUNT_ID, R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY];
386 let values = names.map(|name| var(name).map(|value| value.trim().to_owned()).filter(|v| !v.is_empty()));
387 if let [Some(account), Some(bucket), Some(id), Some(secret)] = &values {
388 return Ok(S3Endpoint::r2(account, bucket, id, secret));
389 }
390 let missing: Vec<&str> = names.iter().zip(&values).filter(|(_, value)| value.is_none()).map(|(n, _)| *n).collect();
391 Err(Error::internal(format!(
392 "presigned R2 URLs need {} (not set). Fix: add `R2_ACCOUNT_ID: bindings.text(\"<account id>\"),` and \
393 `R2_BUCKET: bindings.text(\"<app>-storage\"),` to worker.env in cloudflare.config.ts; create an R2 API \
394 token (dashboard: R2 > Manage API tokens, Object Read & Write), put R2_ACCESS_KEY_ID and \
395 R2_SECRET_ACCESS_KEY in .dev.vars and run `ocre secrets push R2_ACCESS_KEY_ID R2_SECRET_ACCESS_KEY \
396 --file .prod.vars`",
397 missing.join(", ")
398 )))
399}
400
401/// Presigned `GET` of an attachment: R2 answers with a safe `Content-Type` and `Content-Disposition`.
402pub(crate) fn presign_get_url(
403 endpoint: &S3Endpoint,
404 attachment: &Attachment,
405 disposition: Disposition,
406 now: i64,
407 expires_in: u64,
408) -> Result<String> {
409 let [(a, b), (c, d)] = get_overrides(attachment, disposition);
410 endpoint.presign("GET", &attachment.key, &[], &[(a, &b), (c, &d)], now, expires_in)
411}
412
413/// [`presign_get_url`] for development: the app's route on the local bucket, with the same overrides.
414pub(crate) fn dev_get_url(
415 base: &str,
416 attachment: &Attachment,
417 disposition: Disposition,
418 expires_in: u64,
419) -> Result<String> {
420 check_expires_in(expires_in)?;
421 let [(a, b), (c, d)] = get_overrides(attachment, disposition);
422 Ok(dev_url(base, &attachment.key, &[(a, &b), (c, &d)], expires_in))
423}
424
425/// The response overrides of a presigned `GET`: a safe `Content-Type` and `Content-Disposition`.
426fn get_overrides(attachment: &Attachment, disposition: Disposition) -> [(&'static str, String); 2] {
427 let binary = BINARY_TYPES.contains(&attachment.content_type.as_str());
428 let content_type = if binary { "application/octet-stream" } else { &attachment.content_type };
429 let disposition = content_disposition(disposition, &attachment.filename, &attachment.content_type);
430 [("response-content-disposition", disposition), ("response-content-type", content_type.to_owned())]
431}
432
433/// The attachment of a direct upload found by `head`, after checking it against `rules`.
434pub(crate) fn attachment_from_head(
435 field: &str,
436 head: Option<&StoredObject>,
437 filename: &str,
438 rules: &Rules,
439) -> Result<Attachment> {
440 let mut v = Validator::new();
441 match head {
442 None => {
443 v.check(field, true, "was not uploaded");
444 }
445 Some(object) => {
446 v.file_size_and_type(field, object.size, &object.content_type, rules);
447 }
448 }
449 v.finish()?;
450 let object = head.expect("the validator refused a missing upload");
451 Ok(object.attachment(filename))
452}
453
454/// `(yyyymmdd, yyyymmddThhmmssZ)` of a Unix time, in UTC.
455fn amz_date(now: i64) -> (String, String) {
456 let (year, month, day) = civil_from_days(now.div_euclid(86_400));
457 let seconds = now.rem_euclid(86_400);
458 let date = format!("{year:04}{month:02}{day:02}");
459 let time = format!("{date}T{:02}{:02}{:02}Z", seconds / 3600, seconds % 3600 / 60, seconds % 60);
460 (date, time)
461}
462
463fn hmac(key: &[u8], data: &[u8]) -> Vec<u8> {
464 let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(key).expect("HMAC takes any key length");
465 mac.update(data);
466 mac.finalize().into_bytes().to_vec()
467}
468
469fn hex(bytes: &[u8]) -> String {
470 bytes.iter().fold(String::with_capacity(bytes.len() * 2), |mut out, byte| {
471 write!(out, "{byte:02x}").expect("writing to a String");
472 out
473 })
474}
475
476#[cfg(test)]
477#[path = "../../tests/storage/presign.rs"]
478mod tests;