Skip to main content

hyprstream_core/services/oauth/
challenge.rs

1//! Shared Ed25519 challenge-response verification for OAuth endpoints.
2//!
3//! Used by both the device flow (`device.rs`) and the authorization code
4//! flow (`authorize.rs`) to verify that a user possesses the private key
5//! corresponding to the public key registered in their UserStore entry.
6
7use base64::engine::general_purpose::STANDARD;
8use base64::Engine;
9
10use crate::auth::user_store::UserStore;
11
12/// Error types for Ed25519 challenge-response verification.
13#[derive(Debug)]
14#[allow(dead_code)]
15pub(super) enum ChallengeError {
16    /// Username contains ':', which would make the challenge string ambiguous.
17    InvalidUsername,
18    /// Fingerprint string is malformed (empty, contains ':' delimiter conflict, etc.).
19    InvalidFingerprint,
20    /// Presented public key is not a canonical supported Ed25519 encoding.
21    InvalidPublicKey,
22    /// Signature is not valid base64.
23    InvalidSignatureEncoding,
24    /// Signature is not exactly 64 bytes (88 base64 chars).
25    InvalidSignatureLength,
26    /// No UserStore entry for this username.
27    UserNotFound,
28    /// User has no pubkeys registered.
29    NoPubkeys,
30    /// No user is registered with the supplied key fingerprint.
31    UnknownFingerprint,
32    /// UserStore returned an error.
33    UserStoreError(#[allow(dead_code)] anyhow::Error),
34    /// Signature is syntactically valid but does not verify against any registered key.
35    SignatureInvalid,
36}
37
38impl ChallengeError {
39    /// Human-readable error message for display in HTML forms.
40    pub(super) fn message(&self) -> &'static str {
41        match self {
42            ChallengeError::InvalidUsername => "Username must not contain ':'",
43            ChallengeError::InvalidFingerprint =>
44                "Invalid key fingerprint format. Expected `SHA256:...` from `hyprstream sign-challenge`.",
45            ChallengeError::InvalidPublicKey =>
46                "Invalid account public key (expected base64 Ed25519 key bytes).",
47            ChallengeError::InvalidSignatureEncoding =>
48                "Invalid signature encoding (expected base64).",
49            ChallengeError::InvalidSignatureLength =>
50                "Invalid signature length (expected 64 bytes / 88 base64 chars).",
51            ChallengeError::UserNotFound =>
52                "Unknown user. Please contact your administrator.",
53            ChallengeError::NoPubkeys =>
54                "No public keys registered for this user.",
55            ChallengeError::UnknownFingerprint =>
56                "Key fingerprint not registered to any user. Run `hyprstream wizard` or have an admin register your key.",
57            ChallengeError::UserStoreError(_) =>
58                "Internal error looking up user credentials.",
59            ChallengeError::SignatureInvalid =>
60                "Invalid signature. Ensure you signed the correct challenge string.",
61        }
62    }
63}
64
65/// Verify proof-of-possession for a not-yet-registered vault key.
66///
67/// Unlike normal authorize, signup cannot resolve the key from a reverse
68/// index. The caller presents the public key; this function derives its
69/// canonical fingerprint, requires the submitted fingerprint to match, and
70/// verifies the domain-separated signup challenge before any account mutation.
71pub(super) fn verify_unregistered_ed25519_response(
72    public_key_b64: &str,
73    fingerprint: &str,
74    challenge: &[u8],
75    sig_b64: &str,
76) -> Result<ed25519_dalek::VerifyingKey, ChallengeError> {
77    let verifying_key = crate::auth::decode_pubkey_base64(public_key_b64)
78        .map_err(|_| ChallengeError::InvalidPublicKey)?;
79    if crate::auth::pubkey_fingerprint(&verifying_key) != fingerprint {
80        return Err(ChallengeError::InvalidFingerprint);
81    }
82    let sig_bytes = STANDARD
83        .decode(sig_b64)
84        .map_err(|_| ChallengeError::InvalidSignatureEncoding)?;
85    let sig_array: [u8; 64] = sig_bytes
86        .try_into()
87        .map_err(|_| ChallengeError::InvalidSignatureLength)?;
88    let signature = ed25519_dalek::Signature::from_bytes(&sig_array);
89    verifying_key
90        .verify_strict(challenge, &signature)
91        .map_err(|_| ChallengeError::SignatureInvalid)?;
92    Ok(verifying_key)
93}
94
95/// Verify an Ed25519 challenge-response.
96///
97/// The `challenge` parameter is the fully-constructed challenge string
98/// (caller is responsible for constructing it correctly for the flow):
99/// - Device flow:    `"{username}:{user_code_normalized}:{nonce}"`
100/// - Auth code flow: `"{username}:{nonce}:{code_challenge}"`
101///
102/// `sig_b64` is the standard (non-URL-safe) base64-encoded 64-byte signature.
103///
104/// Returns the verified `VerifyingKey` on success — the key confirmed to have
105/// signed the challenge. Tries all registered pubkeys for the user until one matches.
106pub(super) async fn verify_ed25519_response(
107    user_store: &dyn UserStore,
108    username: &str,
109    challenge: &str,
110    sig_b64: &str,
111) -> Result<ed25519_dalek::VerifyingKey, ChallengeError> {
112    if username.contains(':') {
113        return Err(ChallengeError::InvalidUsername);
114    }
115
116    let sig_bytes = STANDARD
117        .decode(sig_b64)
118        .map_err(|_| ChallengeError::InvalidSignatureEncoding)?;
119
120    let sig_array: [u8; 64] = sig_bytes
121        .try_into()
122        .map_err(|_| ChallengeError::InvalidSignatureLength)?;
123
124    let signature = ed25519_dalek::Signature::from_bytes(&sig_array);
125
126    // Get all pubkeys for the user and try each one
127    let pubkeys = user_store
128        .list_pubkeys(username)
129        .await
130        .map_err(ChallengeError::UserStoreError)?;
131
132    if pubkeys.is_empty() {
133        return Err(ChallengeError::NoPubkeys);
134    }
135
136    // Try to verify against each registered pubkey
137    for entry in &pubkeys {
138        if entry
139            .pubkey
140            .verify_strict(challenge.as_bytes(), &signature)
141            .is_ok()
142        {
143            // Optionally touch the pubkey to update last_used_at
144            let _ = user_store.touch_pubkey(username, &entry.fingerprint).await;
145            return Ok(entry.pubkey);
146        }
147    }
148
149    Err(ChallengeError::SignatureInvalid)
150}
151
152/// Verify an Ed25519 challenge-response identified by the signer's key
153/// fingerprint rather than a client-declared username.
154///
155/// Resolves the user via the `pubkey:{fingerprint} → username` reverse index
156/// the UserStore already maintains. Builds the challenge string as
157/// `"{fingerprint}:{nonce}:{code_challenge}"` so the client and server agree
158/// on the binding without the client ever asserting an identity.
159///
160/// Returns `(username, VerifyingKey)` on success: the resolved username (for
161/// the JWT `sub` claim) and the key that verified the signature.
162pub(super) async fn verify_ed25519_response_by_fingerprint(
163    user_store: &dyn UserStore,
164    fingerprint: &str,
165    challenge: &str,
166    sig_b64: &str,
167) -> Result<(String, ed25519_dalek::VerifyingKey), ChallengeError> {
168    // Accept only the canonical `SHA256:...` form. The client and server
169    // build the challenge with the exact same string, so additional ':' inside
170    // the fingerprint don't cause delimiter ambiguity — but rejecting other
171    // shapes early gives a better error than "unknown fingerprint".
172    if !fingerprint.starts_with("SHA256:") {
173        return Err(ChallengeError::InvalidFingerprint);
174    }
175
176    let sig_bytes = STANDARD
177        .decode(sig_b64)
178        .map_err(|_| ChallengeError::InvalidSignatureEncoding)?;
179    let sig_array: [u8; 64] = sig_bytes
180        .try_into()
181        .map_err(|_| ChallengeError::InvalidSignatureLength)?;
182    let signature = ed25519_dalek::Signature::from_bytes(&sig_array);
183
184    let Some(username) = user_store
185        .get_pubkey_user(fingerprint)
186        .await
187        .map_err(ChallengeError::UserStoreError)?
188    else {
189        return Err(ChallengeError::UnknownFingerprint);
190    };
191
192    let pubkeys = user_store
193        .list_pubkeys(&username)
194        .await
195        .map_err(ChallengeError::UserStoreError)?;
196    let Some(entry) = pubkeys.into_iter().find(|e| e.fingerprint == fingerprint) else {
197        // Reverse index pointed at this user but the key is gone — treat as unknown.
198        return Err(ChallengeError::UnknownFingerprint);
199    };
200
201    if entry
202        .pubkey
203        .verify_strict(challenge.as_bytes(), &signature)
204        .is_err()
205    {
206        return Err(ChallengeError::SignatureInvalid);
207    }
208
209    let _ = user_store.touch_pubkey(&username, &entry.fingerprint).await;
210    Ok((username, entry.pubkey))
211}
212
213/// HTML-escape a string for safe embedding in HTML attributes and text.
214pub(crate) fn html_escape(s: &str) -> String {
215    s.replace('&', "&amp;")
216        .replace('<', "&lt;")
217        .replace('>', "&gt;")
218        .replace('"', "&quot;")
219        .replace('\'', "&#x27;")
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225    use ed25519_dalek::Signer as _;
226
227    #[test]
228    fn unregistered_key_proof_requires_matching_key_fingerprint_and_signature() {
229        let key = ed25519_dalek::SigningKey::from_bytes(&[0x31; 32]);
230        let public_key = STANDARD.encode(key.verifying_key().as_bytes());
231        let fingerprint = crate::auth::pubkey_fingerprint(&key.verifying_key());
232        let challenge = b"hyprstream-cold-signup-v1\0alice\0fingerprint\0nonce\0pkce\0";
233        let signature = STANDARD.encode(key.sign(challenge).to_bytes());
234
235        let Ok(verified) =
236            verify_unregistered_ed25519_response(&public_key, &fingerprint, challenge, &signature)
237        else {
238            panic!("valid signup proof must verify");
239        };
240        assert_eq!(verified, key.verifying_key());
241        assert!(matches!(
242            verify_unregistered_ed25519_response(
243                &public_key,
244                "SHA256:not-the-presented-key",
245                challenge,
246                &signature,
247            ),
248            Err(ChallengeError::InvalidFingerprint)
249        ));
250        assert!(matches!(
251            verify_unregistered_ed25519_response(
252                &public_key,
253                &fingerprint,
254                b"tampered",
255                &signature,
256            ),
257            Err(ChallengeError::SignatureInvalid)
258        ));
259    }
260}