Skip to main content

navree_http/
signed.rs

1//! Signed URLs: [`UrlSigner`] and the [`ValidSignature`] guard.
2
3use std::fmt;
4use std::sync::Arc;
5
6use chrono::{DateTime, Utc};
7use hmac::{Hmac, KeyInit, Mac};
8use http::Uri;
9use http::request::Parts;
10use navree_contracts::Clock;
11use navree_kernel::{AppContext, BoxFuture};
12use sha2::Sha256;
13
14use crate::{AppError, Guard};
15
16/// Signs URLs with HMAC-SHA256 so links (email verification, downloads) can
17/// be trusted without a session. The signature covers the path, the query
18/// and an `expires` timestamp.
19///
20/// ```
21/// use chrono::{Duration, Utc};
22/// use navree_http::UrlSigner;
23///
24/// let signer = UrlSigner::new(b"a long random key");
25/// let now = Utc::now();
26/// let url = signer.sign("/verify-email/42?hash=abc", now + Duration::minutes(60));
27/// assert!(signer.verify(&url.parse().unwrap(), now));
28/// assert!(!signer.verify(&url.parse().unwrap(), now + Duration::minutes(61)));
29/// ```
30///
31/// The app's signer is a provider of `HttpModule`, keyed by
32/// `http.signing_key`, or else by a key derived from the app key (`app.key`
33/// or `APP_KEY`), or else by a random per-process key (links then stop
34/// working after a restart).
35#[derive(Clone)]
36pub struct UrlSigner {
37    key: Vec<u8>,
38}
39
40impl UrlSigner {
41    /// A signer using `key`.
42    pub fn new(key: &[u8]) -> Self {
43        Self { key: key.to_vec() }
44    }
45
46    /// `path_and_query` plus `expires=<unix seconds>&signature=<hex>`.
47    pub fn sign(&self, path_and_query: &str, expires_at: DateTime<Utc>) -> String {
48        let separator = if path_and_query.contains('?') {
49            '&'
50        } else {
51            '?'
52        };
53        let unsigned = format!(
54            "{path_and_query}{separator}expires={}",
55            expires_at.timestamp()
56        );
57        let signature = hex::encode(self.mac(&unsigned).finalize().into_bytes());
58        format!("{unsigned}&signature={signature}")
59    }
60
61    /// Whether `uri` carries a valid signature that has not expired at `now`.
62    pub fn verify(&self, uri: &Uri, now: DateTime<Utc>) -> bool {
63        let Some(query) = uri.query() else {
64            return false;
65        };
66        let mut signature = None;
67        let mut expires = None;
68        let mut rest = Vec::new();
69        for pair in query.split('&') {
70            match pair.split_once('=') {
71                Some(("signature", value)) => {
72                    if signature.replace(value).is_some() {
73                        return false;
74                    }
75                }
76                Some(("expires", value)) => {
77                    expires = value.parse::<i64>().ok();
78                    rest.push(pair);
79                }
80                _ => rest.push(pair),
81            }
82        }
83        let (Some(signature), Some(expires)) = (signature, expires) else {
84            return false;
85        };
86        if now.timestamp() >= expires {
87            return false;
88        }
89        let Ok(signature) = hex::decode(signature) else {
90            return false;
91        };
92        let unsigned = format!("{}?{}", uri.path(), rest.join("&"));
93        self.mac(&unsigned).verify_slice(&signature).is_ok()
94    }
95
96    /// A signer keyed by a subkey of the app key (`APP_KEY`): an
97    /// HMAC-SHA256 of a fixed purpose string, so the raw app key never signs
98    /// anything.
99    pub(crate) fn derived_from_app_key(app_key: &str) -> Self {
100        let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(app_key.as_bytes())
101            .expect("HMAC accepts keys of any length");
102        mac.update(b"navree-http/url-signing/v1");
103        Self::new(&mac.finalize().into_bytes())
104    }
105
106    fn mac(&self, message: &str) -> Hmac<Sha256> {
107        let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(&self.key)
108            .expect("HMAC accepts keys of any length");
109        mac.update(message.as_bytes());
110        mac
111    }
112}
113
114impl fmt::Debug for UrlSigner {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        f.debug_struct("UrlSigner")
117            .field("key", &"[redacted]")
118            .finish()
119    }
120}
121
122/// A [`Guard`] that rejects requests without a valid, unexpired URL
123/// signature (401). Uses the app's [`UrlSigner`] and `dyn Clock` when one is
124/// registered.
125#[derive(Clone, Copy, Debug, Default)]
126pub struct ValidSignature;
127
128impl ValidSignature {
129    /// The guard as a route guard (`route.guard(ValidSignature::guard())`).
130    pub fn guard() -> Arc<dyn Guard> {
131        Arc::new(Self)
132    }
133}
134
135impl Guard for ValidSignature {
136    fn check<'a>(&'a self, parts: &'a mut Parts) -> BoxFuture<'a, Result<(), AppError>> {
137        Box::pin(async move {
138            let ctx = parts
139                .extensions
140                .get::<AppContext>()
141                .cloned()
142                .ok_or_else(|| {
143                    AppError::internal("ValidSignature runs outside the navree pipeline")
144                })?;
145            let signer = ctx.get::<UrlSigner>().await?;
146            let now = match ctx.try_get::<dyn Clock>().await {
147                Some(clock) => clock.now(),
148                None => Utc::now(),
149            };
150            if signer.verify(&parts.uri, now) {
151                Ok(())
152            } else {
153                Err(AppError::new(
154                    http::StatusCode::UNAUTHORIZED,
155                    crate::codes::INVALID_SIGNATURE,
156                    "Invalid signature.",
157                ))
158            }
159        })
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use chrono::Duration;
166
167    use super::*;
168
169    fn uri(s: &str) -> Uri {
170        s.parse().unwrap()
171    }
172
173    #[test]
174    fn signed_url_roundtrip_and_expiry() {
175        let signer = UrlSigner::new(b"key-1");
176        let now = Utc::now();
177        let url = signer.sign("/verify/1?hash=abc", now + Duration::seconds(60));
178        assert!(url.starts_with("/verify/1?hash=abc&expires="));
179        assert!(signer.verify(&uri(&url), now));
180        assert!(signer.verify(&uri(&url), now + Duration::seconds(59)));
181        assert!(
182            !signer.verify(&uri(&url), now + Duration::seconds(60)),
183            "expired"
184        );
185
186        let no_query = signer.sign("/download", now + Duration::seconds(60));
187        assert!(no_query.starts_with("/download?expires="));
188        assert!(signer.verify(&uri(&no_query), now));
189    }
190
191    #[test]
192    fn tampering_or_another_key_fails() {
193        let signer = UrlSigner::new(b"key-1");
194        let now = Utc::now();
195        let url = signer.sign("/verify/1?hash=abc", now + Duration::seconds(60));
196
197        assert!(!signer.verify(&uri(&url.replace("/verify/1", "/verify/2")), now));
198        assert!(!signer.verify(&uri(&url.replace("hash=abc", "hash=abd")), now));
199        let later = (now + Duration::days(1)).timestamp().to_string();
200        let expires = url
201            .split("expires=")
202            .nth(1)
203            .unwrap()
204            .split('&')
205            .next()
206            .unwrap();
207        assert!(!signer.verify(&uri(&url.replace(expires, &later)), now));
208        assert!(!UrlSigner::new(b"key-2").verify(&uri(&url), now));
209        assert!(!signer.verify(&uri("/verify/1?hash=abc"), now), "unsigned");
210        assert!(
211            !signer.verify(&uri(&format!("{url}&signature=00")), now),
212            "two signatures"
213        );
214        assert!(!signer.verify(&uri(&url.replace("signature=", "signature=zz")), now));
215    }
216
217    #[test]
218    fn debug_hides_the_key() {
219        assert!(!format!("{:?}", UrlSigner::new(b"hunter2")).contains("hunter2"));
220    }
221}