Skip to main content

haystack_core/
auth.rs

1//! SCRAM SHA-256 authentication primitives for the Haystack auth protocol.
2//!
3//! This module implements the cryptographic operations needed for SCRAM
4//! (Salted Challenge Response Authentication Mechanism) with SHA-256 as
5//! specified by the [Project Haystack auth spec](https://project-haystack.org/doc/docHaystack/Auth).
6//!
7//! It provides functions shared by both server and client implementations
8//! for the three-phase handshake: HELLO, SCRAM challenge/response, and
9//! BEARER token issuance.
10
11use base64::Engine;
12use base64::engine::general_purpose::STANDARD as BASE64;
13use hmac::{Hmac, Mac};
14use pbkdf2::pbkdf2_hmac;
15use rand::Rng;
16use sha2::{Digest, Sha256};
17use subtle::ConstantTimeEq;
18
19type HmacSha256 = Hmac<Sha256>;
20
21/// Default PBKDF2 iteration count for SCRAM SHA-256.
22pub const DEFAULT_ITERATIONS: u32 = 100_000;
23
24// ---------------------------------------------------------------------------
25// Error type
26// ---------------------------------------------------------------------------
27
28/// Errors that can occur during SCRAM authentication.
29#[derive(Debug, thiserror::Error)]
30pub enum AuthError {
31    #[error("invalid credentials")]
32    InvalidCredentials,
33    #[error("invalid auth header: {0}")]
34    InvalidHeader(String),
35    #[error("handshake failed: {0}")]
36    HandshakeFailed(String),
37    #[error("base64 decode error: {0}")]
38    Base64Error(String),
39}
40
41// ---------------------------------------------------------------------------
42// Types
43// ---------------------------------------------------------------------------
44
45/// Pre-computed SCRAM credentials for a user (stored server-side).
46#[derive(Debug, Clone)]
47pub struct ScramCredentials {
48    pub salt: Vec<u8>,
49    pub iterations: u32,
50    pub stored_key: Vec<u8>,
51    pub server_key: Vec<u8>,
52}
53
54/// In-flight SCRAM handshake state held by the server between the
55/// server-first-message and client-final-message exchanges.
56#[derive(Debug, Clone)]
57pub struct ScramHandshake {
58    pub username: String,
59    pub client_nonce: String,
60    pub server_nonce: String,
61    pub salt: Vec<u8>,
62    pub iterations: u32,
63    pub auth_message: String,
64    pub server_signature: Vec<u8>,
65    /// Stored key from credentials, needed to verify the client proof.
66    stored_key: Vec<u8>,
67}
68
69/// Parsed Haystack `Authorization` header.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub enum AuthHeader {
72    Hello {
73        username: String,
74        /// Base64-encoded client-first-message (contains the client nonce).
75        data: Option<String>,
76    },
77    Scram {
78        handshake_token: String,
79        data: String,
80    },
81    Bearer {
82        auth_token: String,
83    },
84}
85
86// ---------------------------------------------------------------------------
87// Internal helpers
88// ---------------------------------------------------------------------------
89
90/// Compute HMAC-SHA-256(key, msg).
91fn hmac_sha256(key: &[u8], msg: &[u8]) -> Vec<u8> {
92    let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts keys of any size");
93    mac.update(msg);
94    mac.finalize().into_bytes().to_vec()
95}
96
97/// Compute SHA-256(data).
98fn sha256(data: &[u8]) -> Vec<u8> {
99    let mut hasher = Sha256::new();
100    hasher.update(data);
101    hasher.finalize().to_vec()
102}
103
104/// XOR two equal-length byte slices.
105fn xor_bytes(a: &[u8], b: &[u8]) -> Vec<u8> {
106    assert_eq!(a.len(), b.len(), "XOR operands must be the same length");
107    a.iter().zip(b.iter()).map(|(x, y)| x ^ y).collect()
108}
109
110/// PBKDF2-HMAC-SHA-256 key derivation, producing a 32-byte salted password.
111fn pbkdf2_sha256(password: &[u8], salt: &[u8], iterations: u32) -> Vec<u8> {
112    let mut salted_password = vec![0u8; 32];
113    pbkdf2_hmac::<Sha256>(password, salt, iterations, &mut salted_password);
114    salted_password
115}
116
117/// Derive (ClientKey, StoredKey, ServerKey) from a salted password.
118fn derive_keys(salted_password: &[u8]) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
119    let client_key = hmac_sha256(salted_password, b"Client Key");
120    let stored_key = sha256(&client_key);
121    let server_key = hmac_sha256(salted_password, b"Server Key");
122    (client_key, stored_key, server_key)
123}
124
125/// Parse a `key=value` parameter from a SCRAM message segment.
126fn parse_scram_param<'a>(segment: &'a str, prefix: &str) -> Result<&'a str, AuthError> {
127    let trimmed = segment.trim();
128    trimmed.strip_prefix(prefix).ok_or_else(|| {
129        AuthError::HandshakeFailed(format!(
130            "expected prefix '{}' but got '{}'",
131            prefix, trimmed
132        ))
133    })
134}
135
136/// Build the client-first-message-bare: `n=<username>,r=<client_nonce>`.
137fn make_client_first_bare(username: &str, client_nonce: &str) -> String {
138    format!("n={},r={}", username, client_nonce)
139}
140
141// ---------------------------------------------------------------------------
142// Public API
143// ---------------------------------------------------------------------------
144
145/// Derive SCRAM credentials from a password (for user creation/storage).
146///
147/// Uses PBKDF2-HMAC-SHA-256 with the given salt and iteration count.
148pub fn derive_credentials(password: &str, salt: &[u8], iterations: u32) -> ScramCredentials {
149    let salted_password = pbkdf2_sha256(password.as_bytes(), salt, iterations);
150    let (_client_key, stored_key, server_key) = derive_keys(&salted_password);
151    ScramCredentials {
152        salt: salt.to_vec(),
153        iterations,
154        stored_key,
155        server_key,
156    }
157}
158
159/// Generate a random nonce string (base64-encoded 18 random bytes).
160pub fn generate_nonce() -> String {
161    let mut bytes = [0u8; 18];
162    rand::rng().fill(&mut bytes);
163    BASE64.encode(bytes)
164}
165
166/// Client-side: Create the client-first-message data (base64-encoded).
167///
168/// Returns `(client_nonce, client_first_data_base64)`.
169///
170/// The client-first-message-bare is `n=<username>,r=<client_nonce>`.
171/// The full message prepends the GS2 header `n,,` (no channel binding).
172pub fn client_first_message(username: &str) -> (String, String) {
173    let client_nonce = generate_nonce();
174    let bare = make_client_first_bare(username, &client_nonce);
175    let full = format!("n,,{}", bare);
176    let encoded = BASE64.encode(full.as_bytes());
177    (client_nonce, encoded)
178}
179
180/// Server-side: Create the server-first-message data and handshake state.
181///
182/// `username` is taken from the HELLO phase. `client_nonce_b64` is the raw
183/// client nonce (as returned by [`client_first_message`]). `credentials` are
184/// the pre-computed SCRAM credentials for this user.
185///
186/// Returns `(handshake_state, server_first_data_base64)`.
187pub fn server_first_message(
188    username: &str,
189    client_nonce_b64: &str,
190    credentials: &ScramCredentials,
191) -> (ScramHandshake, String) {
192    let server_nonce = generate_nonce();
193    let combined_nonce = format!("{}{}", client_nonce_b64, server_nonce);
194    let salt_b64 = BASE64.encode(&credentials.salt);
195
196    // server-first-message: r=<combined>,s=<salt_b64>,i=<iterations>
197    let server_first_msg = format!(
198        "r={},s={},i={}",
199        combined_nonce, salt_b64, credentials.iterations
200    );
201
202    // client-first-message-bare (includes username per SCRAM spec)
203    let cfmb = make_client_first_bare(username, client_nonce_b64);
204
205    // client-final-message-without-proof (anticipated)
206    let client_final_without_proof = format!("c=biws,r={}", combined_nonce);
207
208    // AuthMessage = client-first-bare "," server-first-msg "," client-final-without-proof
209    let auth_message = format!(
210        "{},{},{}",
211        cfmb, server_first_msg, client_final_without_proof
212    );
213
214    // Pre-compute server signature
215    let server_signature = hmac_sha256(&credentials.server_key, auth_message.as_bytes());
216
217    let server_first_b64 = BASE64.encode(server_first_msg.as_bytes());
218
219    let handshake = ScramHandshake {
220        username: username.to_string(),
221        client_nonce: client_nonce_b64.to_string(),
222        server_nonce,
223        salt: credentials.salt.clone(),
224        iterations: credentials.iterations,
225        auth_message,
226        server_signature,
227        stored_key: credentials.stored_key.clone(),
228    };
229
230    (handshake, server_first_b64)
231}
232
233/// Client-side: Process server-first-message, produce client-final-message.
234///
235/// `username` is the same value originally passed to [`client_first_message`].
236/// `password` is the user's plaintext password. `client_nonce` is the nonce
237/// returned by [`client_first_message`]. `server_first_b64` is the base64
238/// server-first-message data received from the server.
239///
240/// Returns `(client_final_data_base64, expected_server_signature)`.
241pub fn client_final_message(
242    password: &str,
243    client_nonce: &str,
244    server_first_b64: &str,
245    username: &str,
246) -> Result<(String, Vec<u8>), AuthError> {
247    // Decode and parse server-first-message
248    let server_first_bytes = BASE64
249        .decode(server_first_b64)
250        .map_err(|e| AuthError::Base64Error(e.to_string()))?;
251    let server_first_msg = String::from_utf8(server_first_bytes)
252        .map_err(|e| AuthError::HandshakeFailed(e.to_string()))?;
253
254    // Expected format: r=<combined_nonce>,s=<salt_b64>,i=<iterations>
255    let parts: Vec<&str> = server_first_msg.splitn(3, ',').collect();
256    if parts.len() != 3 {
257        return Err(AuthError::HandshakeFailed(
258            "invalid server-first-message format".to_string(),
259        ));
260    }
261
262    let combined_nonce = parse_scram_param(parts[0], "r=")?;
263    let salt_b64 = parse_scram_param(parts[1], "s=")?;
264    let iterations_str = parse_scram_param(parts[2], "i=")?;
265
266    // The combined nonce must start with our client nonce
267    if !combined_nonce.starts_with(client_nonce) {
268        return Err(AuthError::HandshakeFailed(
269            "combined nonce does not start with client nonce".to_string(),
270        ));
271    }
272
273    let salt = BASE64
274        .decode(salt_b64)
275        .map_err(|e| AuthError::Base64Error(e.to_string()))?;
276    let iterations: u32 = iterations_str
277        .parse()
278        .map_err(|e: std::num::ParseIntError| AuthError::HandshakeFailed(e.to_string()))?;
279
280    // Key derivation
281    let salted_password = pbkdf2_sha256(password.as_bytes(), &salt, iterations);
282    let (client_key, stored_key, server_key) = derive_keys(&salted_password);
283
284    // Build AuthMessage
285    let cfmb = make_client_first_bare(username, client_nonce);
286    let client_final_without_proof = format!("c=biws,r={}", combined_nonce);
287    let auth_message = format!(
288        "{},{},{}",
289        cfmb, server_first_msg, client_final_without_proof
290    );
291
292    // ClientSignature = HMAC(StoredKey, AuthMessage)
293    let client_signature = hmac_sha256(&stored_key, auth_message.as_bytes());
294    // ClientProof = ClientKey XOR ClientSignature
295    let client_proof = xor_bytes(&client_key, &client_signature);
296    // ServerSignature = HMAC(ServerKey, AuthMessage)
297    let server_signature = hmac_sha256(&server_key, auth_message.as_bytes());
298
299    // client-final-message: c=biws,r=<combined>,p=<proof_b64>
300    let proof_b64 = BASE64.encode(&client_proof);
301    let client_final_msg = format!("{},p={}", client_final_without_proof, proof_b64);
302    let client_final_b64 = BASE64.encode(client_final_msg.as_bytes());
303
304    Ok((client_final_b64, server_signature))
305}
306
307/// Server-side: Verify client-final-message and produce server signature.
308///
309/// Decodes the client-final-message, verifies the client proof against the
310/// stored key in the handshake state, and returns the server signature for
311/// the client to verify (sent as the `v=` field in server-final-message).
312pub fn server_verify_final(
313    handshake: &ScramHandshake,
314    client_final_b64: &str,
315) -> Result<Vec<u8>, AuthError> {
316    // Decode client-final-message
317    let client_final_bytes = BASE64
318        .decode(client_final_b64)
319        .map_err(|e| AuthError::Base64Error(e.to_string()))?;
320    let client_final_msg = String::from_utf8(client_final_bytes)
321        .map_err(|e| AuthError::HandshakeFailed(e.to_string()))?;
322
323    // Expected format: c=biws,r=<combined_nonce>,p=<proof_b64>
324    let parts: Vec<&str> = client_final_msg.splitn(3, ',').collect();
325    if parts.len() != 3 {
326        return Err(AuthError::HandshakeFailed(
327            "invalid client-final-message format".to_string(),
328        ));
329    }
330
331    // Validate channel binding
332    let channel_binding = parse_scram_param(parts[0], "c=")?;
333    if channel_binding != "biws" {
334        return Err(AuthError::HandshakeFailed(
335            "unexpected channel binding".to_string(),
336        ));
337    }
338
339    // Validate combined nonce
340    let combined_nonce = parse_scram_param(parts[1], "r=")?;
341    let expected_combined = format!("{}{}", handshake.client_nonce, handshake.server_nonce);
342    if combined_nonce != expected_combined {
343        return Err(AuthError::HandshakeFailed("nonce mismatch".to_string()));
344    }
345
346    // Extract and decode client proof
347    let proof_b64 = parse_scram_param(parts[2], "p=")?;
348    let client_proof = BASE64
349        .decode(proof_b64)
350        .map_err(|e| AuthError::Base64Error(e.to_string()))?;
351
352    // Verify the proof per RFC 5802:
353    //   ClientSignature = HMAC(StoredKey, AuthMessage)
354    //   RecoveredClientKey = ClientProof XOR ClientSignature
355    //   Check: SHA-256(RecoveredClientKey) == StoredKey
356    let client_signature = hmac_sha256(&handshake.stored_key, handshake.auth_message.as_bytes());
357    let recovered_client_key = xor_bytes(&client_proof, &client_signature);
358    let recovered_stored_key = sha256(&recovered_client_key);
359
360    if recovered_stored_key
361        .ct_eq(&handshake.stored_key)
362        .unwrap_u8()
363        == 0
364    {
365        return Err(AuthError::InvalidCredentials);
366    }
367
368    // Proof verified -- return server signature for the client to verify
369    Ok(handshake.server_signature.clone())
370}
371
372/// Extract the client nonce from a base64-encoded client-first-message.
373///
374/// The client-first-message format is `n,,n=<username>,r=<client_nonce>`.
375/// Returns the raw nonce string.
376pub fn extract_client_nonce(client_first_b64: &str) -> Result<String, AuthError> {
377    let bytes = BASE64
378        .decode(client_first_b64)
379        .map_err(|e| AuthError::Base64Error(e.to_string()))?;
380    let msg = String::from_utf8(bytes)
381        .map_err(|e| AuthError::HandshakeFailed(e.to_string()))?;
382    // Strip GS2 header "n,," prefix
383    let bare = msg
384        .strip_prefix("n,,")
385        .ok_or_else(|| AuthError::HandshakeFailed("missing GS2 header in client-first".into()))?;
386    // Parse n=<user>,r=<nonce>
387    for part in bare.split(',') {
388        if let Some(nonce) = part.strip_prefix("r=") {
389            return Ok(nonce.to_string());
390        }
391    }
392    Err(AuthError::HandshakeFailed(
393        "missing r= nonce in client-first-message".into(),
394    ))
395}
396
397/// Parse a Haystack `Authorization` header value.
398///
399/// Supported formats:
400/// - `HELLO username=<base64(username)>`
401/// - `SCRAM handshakeToken=<token>, data=<data>`
402/// - `BEARER authToken=<token>`
403pub fn parse_auth_header(header: &str) -> Result<AuthHeader, AuthError> {
404    let header = header.trim();
405
406    if let Some(rest) = header.strip_prefix("HELLO ") {
407        let mut username_b64_val = None;
408        let mut data_val = None;
409        for part in rest.split(',') {
410            let part = part.trim();
411            if let Some(val) = part.strip_prefix("username=") {
412                username_b64_val = Some(val.trim().to_string());
413            } else if let Some(val) = part.strip_prefix("data=") {
414                data_val = Some(val.trim().to_string());
415            }
416        }
417        let username_b64 = username_b64_val
418            .ok_or_else(|| AuthError::InvalidHeader("missing username= in HELLO".into()))?;
419        let username_bytes = BASE64
420            .decode(&username_b64)
421            .map_err(|e| AuthError::Base64Error(e.to_string()))?;
422        let username = String::from_utf8(username_bytes)
423            .map_err(|e| AuthError::InvalidHeader(e.to_string()))?;
424        Ok(AuthHeader::Hello { username, data: data_val })
425    } else if let Some(rest) = header.strip_prefix("SCRAM ") {
426        let mut handshake_token = None;
427        let mut data = None;
428        for part in rest.split(',') {
429            let part = part.trim();
430            if let Some(val) = part.strip_prefix("handshakeToken=") {
431                handshake_token = Some(val.trim().to_string());
432            } else if let Some(val) = part.strip_prefix("data=") {
433                data = Some(val.trim().to_string());
434            }
435        }
436        let handshake_token = handshake_token
437            .ok_or_else(|| AuthError::InvalidHeader("missing handshakeToken= in SCRAM".into()))?;
438        let data = data.ok_or_else(|| AuthError::InvalidHeader("missing data= in SCRAM".into()))?;
439        Ok(AuthHeader::Scram {
440            handshake_token,
441            data,
442        })
443    } else if let Some(rest) = header.strip_prefix("BEARER ") {
444        let token = rest
445            .trim()
446            .strip_prefix("authToken=")
447            .ok_or_else(|| AuthError::InvalidHeader("missing authToken= in BEARER".into()))?;
448        Ok(AuthHeader::Bearer {
449            auth_token: token.trim().to_string(),
450        })
451    } else {
452        Err(AuthError::InvalidHeader(format!(
453            "unrecognized auth scheme: {}",
454            header
455        )))
456    }
457}
458
459/// Format a Haystack `WWW-Authenticate` header for a SCRAM challenge.
460///
461/// Produces: `SCRAM handshakeToken=<token>, hash=<hash>, data=<data_b64>`
462pub fn format_www_authenticate(handshake_token: &str, hash: &str, data_b64: &str) -> String {
463    format!(
464        "SCRAM handshakeToken={}, hash={}, data={}",
465        handshake_token, hash, data_b64
466    )
467}
468
469/// Format a Haystack `Authentication-Info` header with the auth token.
470///
471/// Produces: `authToken=<token>, data=<data_b64>`
472pub fn format_auth_info(auth_token: &str, data_b64: &str) -> String {
473    format!("authToken={}, data={}", auth_token, data_b64)
474}
475
476// ---------------------------------------------------------------------------
477// Tests
478// ---------------------------------------------------------------------------
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483
484    #[test]
485    fn test_derive_credentials() {
486        let password = "pencil";
487        let salt = b"random-salt-value";
488        let iterations = 4096;
489
490        let creds = derive_credentials(password, salt, iterations);
491
492        // Fields are populated correctly
493        assert_eq!(creds.salt, salt.to_vec());
494        assert_eq!(creds.iterations, iterations);
495        assert_eq!(creds.stored_key.len(), 32); // SHA-256 output length
496        assert_eq!(creds.server_key.len(), 32);
497
498        // Deterministic: same inputs produce same outputs
499        let creds2 = derive_credentials(password, salt, iterations);
500        assert_eq!(creds.stored_key, creds2.stored_key);
501        assert_eq!(creds.server_key, creds2.server_key);
502
503        // Different password yields different credentials
504        let creds3 = derive_credentials("other", salt, iterations);
505        assert_ne!(creds.stored_key, creds3.stored_key);
506        assert_ne!(creds.server_key, creds3.server_key);
507    }
508
509    #[test]
510    fn test_generate_nonce() {
511        let n1 = generate_nonce();
512        let n2 = generate_nonce();
513
514        // Each call produces a unique nonce
515        assert_ne!(n1, n2);
516
517        // Valid base64 encoding of 18 bytes
518        let decoded1 = BASE64.decode(&n1).expect("nonce must be valid base64");
519        assert_eq!(decoded1.len(), 18);
520
521        let decoded2 = BASE64.decode(&n2).expect("nonce must be valid base64");
522        assert_eq!(decoded2.len(), 18);
523    }
524
525    #[test]
526    fn test_parse_auth_header_hello() {
527        let username = "user";
528        let username_b64 = BASE64.encode(username.as_bytes());
529        let header = format!("HELLO username={}", username_b64);
530
531        let parsed = parse_auth_header(&header).unwrap();
532        assert_eq!(
533            parsed,
534            AuthHeader::Hello {
535                username: "user".to_string(),
536                data: None,
537            }
538        );
539    }
540
541    #[test]
542    fn test_parse_auth_header_scram() {
543        let header = "SCRAM handshakeToken=abc123, data=c29tZWRhdGE=";
544        let parsed = parse_auth_header(header).unwrap();
545        assert_eq!(
546            parsed,
547            AuthHeader::Scram {
548                handshake_token: "abc123".to_string(),
549                data: "c29tZWRhdGE=".to_string(),
550            }
551        );
552    }
553
554    #[test]
555    fn test_parse_auth_header_bearer() {
556        let header = "BEARER authToken=mytoken123";
557        let parsed = parse_auth_header(header).unwrap();
558        assert_eq!(
559            parsed,
560            AuthHeader::Bearer {
561                auth_token: "mytoken123".to_string(),
562            }
563        );
564    }
565
566    #[test]
567    fn test_parse_auth_header_invalid() {
568        // Unknown scheme
569        assert!(parse_auth_header("UNKNOWN foo=bar").is_err());
570        // HELLO missing username=
571        assert!(parse_auth_header("HELLO foo=bar").is_err());
572        // SCRAM missing data=
573        assert!(parse_auth_header("SCRAM handshakeToken=abc").is_err());
574        // BEARER missing authToken=
575        assert!(parse_auth_header("BEARER token=abc").is_err());
576        // Empty
577        assert!(parse_auth_header("").is_err());
578    }
579
580    #[test]
581    fn test_full_handshake() {
582        // Simulate the complete HELLO -> SCRAM -> BEARER flow.
583        let username = "testuser";
584        let password = "s3cret";
585        let salt = b"test-salt-12345";
586        let iterations = 4096;
587
588        // --- Server: pre-compute credentials (user registration) ---
589        let credentials = derive_credentials(password, salt, iterations);
590
591        // --- Client: HELLO phase ---
592        let username_b64 = BASE64.encode(username.as_bytes());
593        let hello_header = format!("HELLO username={}", username_b64);
594        let parsed = parse_auth_header(&hello_header).unwrap();
595        match &parsed {
596            AuthHeader::Hello { username: u, .. } => assert_eq!(u, username),
597            _ => panic!("expected Hello variant"),
598        }
599
600        // --- Client: generate client-first-message ---
601        let (client_nonce, _client_first_b64) = client_first_message(username);
602
603        // --- Server: generate server-first-message ---
604        let (handshake, server_first_b64) =
605            server_first_message(username, &client_nonce, &credentials);
606
607        // --- Server: format WWW-Authenticate header ---
608        let www_auth = format_www_authenticate("handshake-token-xyz", "SHA-256", &server_first_b64);
609        assert!(www_auth.contains("SCRAM"));
610        assert!(www_auth.contains("SHA-256"));
611        assert!(www_auth.contains("handshake-token-xyz"));
612
613        // --- Client: process server-first, produce client-final ---
614        let (client_final_b64, expected_server_sig) =
615            client_final_message(password, &client_nonce, &server_first_b64, username).unwrap();
616
617        // --- Server: verify client-final ---
618        let server_sig = server_verify_final(&handshake, &client_final_b64).unwrap();
619
620        // Server signature should match what the client expects
621        assert_eq!(server_sig, expected_server_sig);
622
623        // --- Server: format Authentication-Info header ---
624        let server_final_msg = format!("v={}", BASE64.encode(&server_sig));
625        let server_final_b64 = BASE64.encode(server_final_msg.as_bytes());
626        let auth_info = format_auth_info("auth-token-abc", &server_final_b64);
627        assert!(auth_info.contains("authToken=auth-token-abc"));
628
629        // --- Client: verify server signature from server-final ---
630        let server_final_decoded = BASE64.decode(&server_final_b64).unwrap();
631        let server_final_str = String::from_utf8(server_final_decoded).unwrap();
632        let sig_b64 = server_final_str.strip_prefix("v=").unwrap();
633        let received_server_sig = BASE64.decode(sig_b64).unwrap();
634        assert_eq!(received_server_sig, expected_server_sig);
635    }
636
637    #[test]
638    fn test_client_server_roundtrip() {
639        // Full roundtrip using the public API functions.
640        let username = "admin";
641        let password = "correcthorsebatterystaple";
642        let salt = b"unique-salt-value";
643        let iterations = DEFAULT_ITERATIONS;
644
645        // 1. Server: create credentials during user registration
646        let credentials = derive_credentials(password, salt, iterations);
647
648        // 2. Client: create client-first-message
649        let (client_nonce, client_first_b64) = client_first_message(username);
650
651        // Verify client-first is valid base64 and well-formed
652        let client_first_decoded = BASE64.decode(&client_first_b64).unwrap();
653        let client_first_str = String::from_utf8(client_first_decoded).unwrap();
654        assert!(client_first_str.starts_with("n,,"));
655        assert!(client_first_str.contains(&format!("r={}", client_nonce)));
656
657        // 3. Server: create server-first-message
658        let (handshake, server_first_b64) =
659            server_first_message(username, &client_nonce, &credentials);
660
661        // Verify server-first contains expected SCRAM fields
662        let server_first_decoded = BASE64.decode(&server_first_b64).unwrap();
663        let server_first_str = String::from_utf8(server_first_decoded).unwrap();
664        assert!(server_first_str.starts_with("r="));
665        assert!(server_first_str.contains(",s="));
666        assert!(server_first_str.contains(",i="));
667        assert!(server_first_str.contains(&client_nonce));
668
669        // 4. Client: create client-final-message
670        let (client_final_b64, expected_server_sig) =
671            client_final_message(password, &client_nonce, &server_first_b64, username).unwrap();
672
673        // Verify client-final structure
674        let client_final_decoded = BASE64.decode(&client_final_b64).unwrap();
675        let client_final_str = String::from_utf8(client_final_decoded).unwrap();
676        assert!(client_final_str.starts_with("c=biws,"));
677        assert!(client_final_str.contains(",p="));
678
679        // 5. Server: verify and get server signature
680        let server_sig = server_verify_final(&handshake, &client_final_b64).unwrap();
681        assert_eq!(server_sig, expected_server_sig);
682
683        // 6. Wrong password: server rejects the proof
684        let (wrong_final_b64, _) =
685            client_final_message("wrongpassword", &client_nonce, &server_first_b64, username)
686                .unwrap();
687        let result = server_verify_final(&handshake, &wrong_final_b64);
688        assert!(result.is_err());
689        match result {
690            Err(AuthError::InvalidCredentials) => {} // expected
691            other => panic!("expected InvalidCredentials, got {:?}", other),
692        }
693    }
694
695    #[test]
696    fn test_format_www_authenticate() {
697        let result = format_www_authenticate("tok123", "SHA-256", "c29tZQ==");
698        assert_eq!(
699            result,
700            "SCRAM handshakeToken=tok123, hash=SHA-256, data=c29tZQ=="
701        );
702    }
703
704    #[test]
705    fn test_format_auth_info() {
706        let result = format_auth_info("auth-tok", "ZGF0YQ==");
707        assert_eq!(result, "authToken=auth-tok, data=ZGF0YQ==");
708    }
709}