Skip to main content

objectstore_types/
presign.rs

1//! Utilities for signing and verifying pre-signed URLs.
2//!
3//! A pre-signed URL lets a client that owns an Ed25519 keypair hand out a
4//! time-limited URL that authorizes a specific request.
5//!
6//! Example:
7//!
8//! ```text
9//! GET /v1/objects/<usecase>/<scopes>/<key>
10//!     ?os_timestamp=2026-04-20T13:37:00.00Z
11//!     &os_duration=3600
12//!     &os_kid=relay
13//!     &os_sig=<signature>
14//! ```
15//!
16//! The signature covers a canonical form of the request.
17//!
18//! # Canonical form
19//!
20//! The canonical form is comprised of three newline-separated components:
21//!
22//! ```text
23//! <normalized method>\n
24//! <path>\n
25//! <canonical query string>
26//! ```
27//!
28//! - normalized method: the uppercase HTTP method, with `HEAD` mapped to `GET`;
29//! - path: the request path, included verbatim as transmitted/received on the wire;
30//! - canonical query string: every query parameter except `os_sig`, with keys
31//!   lowercased, sorted lexicographically by name and value, joined with `&`.
32
33use base64::Engine as _;
34use base64::engine::general_purpose::URL_SAFE_NO_PAD;
35use ed25519_dalek::{Signature, Signer};
36use http::Method;
37
38pub use ed25519_dalek::{SigningKey as DalekSigningKey, VerifyingKey as DalekVerifyingKey};
39
40/// Query parameter carrying the time at which the request was signed.
41pub const PARAM_TIMESTAMP: &str = "os_timestamp";
42
43/// Query parameter carrying the validity duration, in seconds.
44pub const PARAM_DURATION: &str = "os_duration";
45
46/// Query parameter naming the key ID used to sign the request.
47pub const PARAM_KID: &str = "os_kid";
48
49/// Query parameter carrying the base64url-encoded signature.
50pub const PARAM_SIG: &str = "os_sig";
51
52/// Errors returned when verifying a pre-signed request signature.
53#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
54pub enum Error {
55    /// The user supplied a sequence of bytes that's not a valid Ed25519 key.
56    #[error("invalid key")]
57    InvalidKey,
58    /// The signature is not valid base64url or doesn't decode to a 64-byte
59    /// Ed25519 signature.
60    #[error("invalid signature encoding")]
61    InvalidSignatureEncoding,
62    /// The signature did not match the canonical request for the given key.
63    #[error("signature verification failed")]
64    VerificationFailed,
65}
66
67/// The canonical form of a request to be signed or verified.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct CanonicalRequest(String);
70
71/// An Ed25519 signing key.
72pub type SigningKey = [u8; 32];
73
74/// An Ed25519 verifying key.
75pub type VerifyingKey = [u8; 32];
76
77impl CanonicalRequest {
78    /// Builds the canonical form of a request.
79    ///
80    /// `path` and `query` MUST be the raw request path and query string as transmitted/received
81    /// on the wire, which means that servers should pass the raw contents of these components, and
82    /// clients should ensure that the encoding used to compute the signature matches exactly the
83    /// encoding used by their HTTP client.
84    ///
85    /// This is important to avoid any signature verification failures due to different
86    /// encoding/decoding implementations between the client and server, and is based on the
87    /// assumption that any intermediate proxies will never re-encode the URL, but always pass it
88    /// through with the original encoding.
89    pub fn new(method: &Method, path: &str, query: Option<&str>) -> Self {
90        let normalized_method = if *method == Method::HEAD {
91            String::from("GET")
92        } else {
93            method.as_str().to_uppercase()
94        };
95
96        let mut pairs: Vec<String> = query
97            .unwrap_or_default()
98            .split('&')
99            .filter(|pair| !pair.is_empty())
100            .filter_map(|pair| {
101                if let Some((key, value)) = pair.split_once('=') {
102                    let key = key.to_ascii_lowercase();
103                    (key != PARAM_SIG).then(|| format!("{key}={value}"))
104                } else {
105                    let key = pair.to_ascii_lowercase();
106                    (key != PARAM_SIG).then_some(key)
107                }
108            })
109            .collect();
110        pairs.sort_unstable();
111        let canonical_query = pairs.join("&");
112
113        Self(format!("{normalized_method}\n{path}\n{canonical_query}"))
114    }
115
116    /// Signs this canonical form with Ed25519.
117    ///
118    /// Returns the base64url-encoded signature, suitable as the value of the
119    /// [`PARAM_SIG`] query parameter.
120    pub fn sign(&self, key: &SigningKey) -> String {
121        let key = DalekSigningKey::from_bytes(key);
122        let signature = key.sign(self.0.as_bytes());
123        URL_SAFE_NO_PAD.encode(signature.to_bytes())
124    }
125
126    /// Verifies a base64url-encoded Ed25519 signature against this canonical form.
127    ///
128    /// # Errors
129    ///
130    /// Returns [`Error::InvalidKey`] if `key` is not a valid Ed25519 verifying key,
131    /// [`Error::InvalidSignatureEncoding`] if `signature_b64` is not valid base64url
132    /// or not a 64-byte signature, and [`Error::VerificationFailed`] if the signature
133    /// does not match.
134    pub fn verify(&self, key: &VerifyingKey, signature_b64: &str) -> Result<(), Error> {
135        let key = DalekVerifyingKey::from_bytes(key).map_err(|_| Error::InvalidKey)?;
136        let bytes = URL_SAFE_NO_PAD
137            .decode(signature_b64)
138            .map_err(|_| Error::InvalidSignatureEncoding)?;
139        let signature =
140            Signature::from_slice(&bytes).map_err(|_| Error::InvalidSignatureEncoding)?;
141        key.verify_strict(self.0.as_bytes(), &signature)
142            .map_err(|_| Error::VerificationFailed)
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    fn test_signing_key() -> DalekSigningKey {
151        DalekSigningKey::from_bytes(&[0x42; 32])
152    }
153
154    /// Raw query string as it would appear on the wire (unsorted, includes the
155    /// os_sig that must be excluded).
156    fn sample_query() -> &'static str {
157        "os_timestamp=1985-04-12T23:20:50.52Z\
158         &os_kid=relay\
159         &os_duration=3600\
160         &os_sig=should-be-excluded"
161    }
162
163    #[test]
164    fn canonical_form_is_stable() {
165        // Base case: full query. Pins path encoding (slashes too), os_sig
166        // exclusion, key lowercasing, and query sort order.
167        let canonical = CanonicalRequest::new(
168            &Method::GET,
169            "/v1/objects/testing/org=17;project=42/foo/bar",
170            Some(sample_query()),
171        );
172        assert_eq!(
173            canonical.0,
174            "GET\n\
175             /v1/objects/testing/org=17;project=42/foo/bar\n\
176             os_duration=3600&\
177             os_kid=relay&\
178             os_timestamp=1985-04-12T23:20:50.52Z"
179        );
180
181        // Empty query: the canonical query component is empty.
182        let canonical = CanonicalRequest::new(&Method::GET, "/v1/objects/testing/_/key", None);
183        assert_eq!(canonical.0, "GET\n/v1/objects/testing/_/key\n");
184
185        // Duplicate query keys are preserved (not deduplicated) and ordered by
186        // (key, value).
187        let canonical = CanonicalRequest::new(
188            &Method::GET,
189            "/v1/objects/testing/_/key",
190            Some("dup=b&dup=a&x=1"),
191        );
192        assert_eq!(
193            canonical.0,
194            "GET\n/v1/objects/testing/_/key\ndup=a&dup=b&x=1"
195        );
196
197        let canonical = CanonicalRequest::new(
198            &Method::GET,
199            "/v1/objects/testing/_/key",
200            Some(sample_query()),
201        );
202        assert_eq!(
203            canonical.0,
204            "GET\n\
205             /v1/objects/testing/_/key\n\
206             os_duration=3600&\
207             os_kid=relay&\
208             os_timestamp=1985-04-12T23:20:50.52Z"
209        );
210    }
211
212    #[test]
213    fn head_is_normalized_to_get() {
214        let path = "/v1/objects/testing/_/key";
215        assert_eq!(
216            CanonicalRequest::new(&Method::HEAD, path, Some(sample_query()),),
217            CanonicalRequest::new(&Method::GET, path, Some(sample_query()),),
218        );
219    }
220
221    #[test]
222    fn sign_and_verify_roundtrip() {
223        let sk = test_signing_key();
224        let vk = sk.verifying_key();
225
226        let canonical = CanonicalRequest::new(
227            &Method::GET,
228            "/v1/objects/testing/_/key",
229            Some(sample_query()),
230        );
231        let signature = canonical.sign(sk.as_bytes());
232
233        assert_eq!(canonical.verify(vk.as_bytes(), &signature), Ok(()));
234    }
235
236    #[test]
237    fn verify_rejects_tampered_canonical() {
238        let sk = test_signing_key();
239        let vk = sk.verifying_key();
240
241        let canonical = CanonicalRequest::new(
242            &Method::GET,
243            "/v1/objects/testing/_/key",
244            Some(sample_query()),
245        );
246        let signature = canonical.sign(sk.as_bytes());
247
248        let tampered = CanonicalRequest::new(
249            &Method::GET,
250            "/v1/objects/testing/_/other",
251            Some(sample_query()),
252        );
253        assert_eq!(
254            tampered.verify(vk.as_bytes(), &signature),
255            Err(Error::VerificationFailed)
256        );
257    }
258
259    #[test]
260    fn verify_rejects_wrong_key() {
261        let sk = test_signing_key();
262        let other_vk = DalekSigningKey::from_bytes(&[0x01; 32]).verifying_key();
263
264        let canonical = CanonicalRequest::new(
265            &Method::GET,
266            "/v1/objects/testing/_/key",
267            Some(sample_query()),
268        );
269        let signature = canonical.sign(sk.as_bytes());
270
271        assert_eq!(
272            canonical.verify(other_vk.as_bytes(), &signature),
273            Err(Error::VerificationFailed)
274        );
275    }
276
277    #[test]
278    fn verify_rejects_bad_signature_encoding() {
279        let vk = test_signing_key().verifying_key();
280        let canonical = CanonicalRequest::new(
281            &Method::GET,
282            "/v1/objects/testing/_/key",
283            Some(sample_query()),
284        );
285
286        // Not valid base64url.
287        assert_eq!(
288            canonical.verify(vk.as_bytes(), "not valid base64!!"),
289            Err(Error::InvalidSignatureEncoding)
290        );
291        // Valid base64url but not a 64-byte signature.
292        assert_eq!(
293            canonical.verify(vk.as_bytes(), &URL_SAFE_NO_PAD.encode([0u8; 10])),
294            Err(Error::InvalidSignatureEncoding)
295        );
296    }
297}