nonce-auth 0.6.3

A secure nonce-based authentication library with pluggable storage backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use crate::NonceCredential;
use crate::nonce::error::NonceError;
use crate::nonce::time_utils::current_timestamp;
use base64::Engine;
use hmac::{Hmac, Mac};
use sha2::Sha256;

type HmacSha256 = Hmac<Sha256>;

/// A function that generates unique nonce values.
pub type NonceGeneratorFn = Box<dyn Fn() -> String + Send + Sync>;

/// A function that provides timestamps.
pub type TimeProviderFn = Box<dyn Fn() -> Result<u64, NonceError> + Send + Sync>;

/// Builder for creating cryptographic credentials.
///
/// `CredentialBuilder` provides a fluent interface for configuring and creating
/// `NonceCredential` instances. It supports custom nonce generation, time providers,
/// and various signing methods.
///
/// # Example: Basic Usage
///
/// ```rust
/// use nonce_auth::CredentialBuilder;
///
/// let credential = CredentialBuilder::new(b"my_secret")
///     .sign(b"payload")?;
/// # Ok::<(), nonce_auth::NonceError>(())
/// ```
///
/// # Example: Custom Configuration
///
/// ```rust
/// use nonce_auth::CredentialBuilder;
/// use std::time::{SystemTime, UNIX_EPOCH};
///
/// # fn example() -> Result<(), nonce_auth::NonceError> {
/// let credential = CredentialBuilder::new(b"my_secret")
///     .with_nonce_generator(|| format!("custom-{}", uuid::Uuid::new_v4()))
///     .with_time_provider(|| {
///         SystemTime::now()
///             .duration_since(UNIX_EPOCH)
///             .map(|d| d.as_secs())
///             .map_err(|e| nonce_auth::NonceError::CryptoError(format!("Time error: {}", e)))
///     })
///     .sign(b"payload")?;
/// # Ok(())
/// # }
/// ```
pub struct CredentialBuilder {
    secret: Vec<u8>,
    nonce_generator: NonceGeneratorFn,
    time_provider: TimeProviderFn,
}

impl CredentialBuilder {
    /// Creates a new `CredentialBuilder` with the provided secret.
    ///
    /// The secret is required for all signing operations. Other settings
    /// can be configured using the chainable `with_*` methods.
    ///
    /// # Arguments
    ///
    /// * `secret` - The shared secret key for HMAC operations
    ///
    /// # Example
    ///
    /// ```rust
    /// use nonce_auth::CredentialBuilder;
    ///
    /// // Simple usage
    /// let credential1 = CredentialBuilder::new(b"key")
    ///     .sign(b"data")?;
    ///     
    /// // With additional configuration in any order
    /// let credential2 = CredentialBuilder::new(b"key")
    ///     .with_time_provider(|| Ok(1234567890))
    ///     .with_nonce_generator(|| "custom".to_string())
    ///     .sign(b"data")?;
    /// # Ok::<(), nonce_auth::NonceError>(())
    /// ```
    pub fn new(secret: &[u8]) -> Self {
        Self {
            secret: secret.to_vec(),
            nonce_generator: Box::new(|| uuid::Uuid::new_v4().to_string()),
            time_provider: Box::new(|| Ok(current_timestamp()? as u64)),
        }
    }

    /// Sets a custom nonce generator function.
    ///
    /// The nonce generator should produce unique values for each call.
    /// The default generator uses UUID v4.
    ///
    /// # Arguments
    ///
    /// * `generator` - A function that returns unique nonce strings
    ///
    /// # Example
    ///
    /// ```rust
    /// use nonce_auth::CredentialBuilder;
    /// use std::sync::atomic::{AtomicU64, Ordering};
    /// use std::sync::Arc;
    ///
    /// let counter = Arc::new(AtomicU64::new(0));
    /// let counter_clone = counter.clone();
    ///
    /// let credential = CredentialBuilder::new(b"key")
    ///     .with_nonce_generator(move || {
    ///         let id = counter_clone.fetch_add(1, Ordering::SeqCst);
    ///         format!("nonce-{:010}", id)
    ///     })
    ///     .sign(b"data")?;
    /// # Ok::<(), nonce_auth::NonceError>(())
    /// ```
    pub fn with_nonce_generator<F>(mut self, generator: F) -> Self
    where
        F: Fn() -> String + Send + Sync + 'static,
    {
        self.nonce_generator = Box::new(generator);
        self
    }

    /// Sets a custom time provider function.
    ///
    /// The time provider should return the current Unix timestamp.
    /// The default provider uses system time.
    ///
    /// # Arguments
    ///
    /// * `provider` - A function that returns the current timestamp
    ///
    /// # Example
    ///
    /// ```rust
    /// use nonce_auth::CredentialBuilder;
    ///
    /// let credential = CredentialBuilder::new(b"key")
    ///     .with_time_provider(|| {
    ///         // Custom time source (e.g., NTP-synchronized)
    ///         Ok(1234567890)
    ///     })
    ///     .sign(b"data")?;
    /// # Ok::<(), nonce_auth::NonceError>(())
    /// ```
    pub fn with_time_provider<F>(mut self, provider: F) -> Self
    where
        F: Fn() -> Result<u64, NonceError> + Send + Sync + 'static,
    {
        self.time_provider = Box::new(provider);
        self
    }

    /// Signs a payload and creates a `NonceCredential`.
    ///
    /// This method generates a nonce, gets the current timestamp, and creates
    /// an HMAC signature over the timestamp, nonce, and payload.
    ///
    /// # Arguments
    ///
    /// * `payload` - The data to be signed
    ///
    /// # Returns
    ///
    /// A `NonceCredential` containing the timestamp, nonce, and signature.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Time provider fails
    /// - Signature generation fails
    ///
    /// # Example
    ///
    /// ```rust
    /// use nonce_auth::CredentialBuilder;
    ///
    /// let credential = CredentialBuilder::new(b"secret")
    ///     .sign(b"important_data")?;
    /// # Ok::<(), nonce_auth::NonceError>(())
    /// ```
    pub fn sign(self, payload: &[u8]) -> Result<NonceCredential, NonceError> {
        let timestamp = (self.time_provider)()?;
        let nonce = (self.nonce_generator)();

        let signature = self.create_signature(&self.secret, timestamp, &nonce, payload)?;

        Ok(NonceCredential {
            timestamp,
            nonce,
            signature,
        })
    }

    /// Signs multiple data components as a structured payload.
    ///
    /// This method concatenates all components in order and signs them as a single payload.
    /// The order of components is significant for verification.
    ///
    /// # Arguments
    ///
    /// * `components` - Array of data components to sign in order
    ///
    /// # Returns
    ///
    /// A `NonceCredential` containing the timestamp, nonce, and signature.
    ///
    /// # Example
    ///
    /// ```rust
    /// use nonce_auth::CredentialBuilder;
    ///
    /// let credential = CredentialBuilder::new(b"secret")
    ///     .sign_structured(&[b"user123", b"action", b"data"])?;
    /// # Ok::<(), nonce_auth::NonceError>(())
    /// ```
    pub fn sign_structured(self, components: &[&[u8]]) -> Result<NonceCredential, NonceError> {
        let timestamp = (self.time_provider)()?;
        let nonce = (self.nonce_generator)();

        let signature =
            self.create_structured_signature(&self.secret, timestamp, &nonce, components)?;

        Ok(NonceCredential {
            timestamp,
            nonce,
            signature,
        })
    }

    /// Signs using a custom MAC construction function.
    ///
    /// This method provides maximum flexibility by allowing custom MAC construction.
    /// The provided function receives a MAC instance and the generated timestamp and nonce.
    ///
    /// # Arguments
    ///
    /// * `mac_fn` - Function that constructs the MAC using timestamp, nonce, and custom data
    ///
    /// # Returns
    ///
    /// A `NonceCredential` containing the timestamp, nonce, and signature.
    ///
    /// # Example
    ///
    /// ```rust
    /// use nonce_auth::CredentialBuilder;
    /// use hmac::Mac;
    ///
    /// # fn example() -> Result<(), nonce_auth::NonceError> {
    /// let credential = CredentialBuilder::new(b"secret")
    ///     .sign_with(|mac, timestamp, nonce| {
    ///         mac.update(b"prefix:");
    ///         mac.update(timestamp.as_bytes());
    ///         mac.update(b":nonce:");
    ///         mac.update(nonce.as_bytes());
    ///         mac.update(b":custom_data");
    ///     })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn sign_with<F>(self, mac_fn: F) -> Result<NonceCredential, NonceError>
    where
        F: FnOnce(&mut HmacSha256, &str, &str),
    {
        let timestamp = (self.time_provider)()?;
        let nonce = (self.nonce_generator)();

        let signature = self.create_custom_signature(&self.secret, timestamp, &nonce, mac_fn)?;

        Ok(NonceCredential {
            timestamp,
            nonce,
            signature,
        })
    }

    /// Creates a standard HMAC signature for timestamp, nonce, and payload.
    fn create_signature(
        &self,
        secret: &[u8],
        timestamp: u64,
        nonce: &str,
        payload: &[u8],
    ) -> Result<String, NonceError> {
        let mut mac = HmacSha256::new_from_slice(secret)
            .map_err(|e| NonceError::CryptoError(format!("Invalid secret key: {e}")))?;

        mac.update(timestamp.to_string().as_bytes());
        mac.update(nonce.as_bytes());
        mac.update(payload);

        let result = mac.finalize();
        Ok(base64::engine::general_purpose::STANDARD.encode(result.into_bytes()))
    }

    /// Creates a structured signature for multiple data components.
    fn create_structured_signature(
        &self,
        secret: &[u8],
        timestamp: u64,
        nonce: &str,
        components: &[&[u8]],
    ) -> Result<String, NonceError> {
        let mut mac = HmacSha256::new_from_slice(secret)
            .map_err(|e| NonceError::CryptoError(format!("Invalid secret key: {e}")))?;

        mac.update(timestamp.to_string().as_bytes());
        mac.update(nonce.as_bytes());
        for component in components {
            mac.update(component);
        }

        let result = mac.finalize();
        Ok(base64::engine::general_purpose::STANDARD.encode(result.into_bytes()))
    }

    /// Creates a custom signature using a user-provided MAC construction function.
    fn create_custom_signature<F>(
        &self,
        secret: &[u8],
        timestamp: u64,
        nonce: &str,
        mac_fn: F,
    ) -> Result<String, NonceError>
    where
        F: FnOnce(&mut HmacSha256, &str, &str),
    {
        let mut mac = HmacSha256::new_from_slice(secret)
            .map_err(|e| NonceError::CryptoError(format!("Invalid secret key: {e}")))?;

        mac_fn(&mut mac, &timestamp.to_string(), nonce);

        let result = mac.finalize();
        Ok(base64::engine::general_purpose::STANDARD.encode(result.into_bytes()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU64, Ordering};

    #[test]
    fn test_credential_builder_new() {
        let builder = CredentialBuilder::new(b"test_secret");
        assert_eq!(builder.secret, b"test_secret".to_vec());
    }

    #[test]
    fn test_basic_signing() {
        let credential = CredentialBuilder::new(b"secret").sign(b"payload").unwrap();

        assert!(!credential.nonce.is_empty());
        assert!(credential.timestamp > 0);
        assert!(!credential.signature.is_empty());
    }

    #[test]
    fn test_structured_signing() {
        let credential = CredentialBuilder::new(b"secret")
            .sign_structured(&[b"part1", b"part2", b"part3"])
            .unwrap();

        assert!(!credential.nonce.is_empty());
        assert!(credential.timestamp > 0);
        assert!(!credential.signature.is_empty());
    }

    #[test]
    fn test_custom_nonce_generator() {
        let counter = Arc::new(AtomicU64::new(0));
        let counter_clone = counter.clone();

        let credential = CredentialBuilder::new(b"secret")
            .with_nonce_generator(move || {
                let id = counter_clone.fetch_add(1, Ordering::SeqCst);
                format!("custom-{id:010}")
            })
            .sign(b"payload")
            .unwrap();

        assert_eq!(credential.nonce, "custom-0000000000");
    }

    #[test]
    fn test_custom_time_provider() {
        let fixed_time = 1234567890u64;
        let credential = CredentialBuilder::new(b"secret")
            .with_time_provider(move || Ok(fixed_time))
            .sign(b"payload")
            .unwrap();

        assert_eq!(credential.timestamp, fixed_time);
    }

    #[test]
    fn test_time_provider_error() {
        let result = CredentialBuilder::new(b"secret")
            .with_time_provider(|| Err(NonceError::CryptoError("Time error".to_string())))
            .sign(b"payload");

        assert!(matches!(result, Err(NonceError::CryptoError(_))));
    }

    #[test]
    fn test_sign_with_custom_mac() {
        let credential = CredentialBuilder::new(b"secret")
            .sign_with(|mac, timestamp, nonce| {
                mac.update(b"prefix:");
                mac.update(timestamp.as_bytes());
                mac.update(b":nonce:");
                mac.update(nonce.as_bytes());
                mac.update(b":custom");
            })
            .unwrap();

        assert!(!credential.nonce.is_empty());
        assert!(credential.timestamp > 0);
        assert!(!credential.signature.is_empty());
    }

    #[test]
    fn test_multiple_credentials_different_nonces() {
        let builder = || CredentialBuilder::new(b"secret");

        let cred1 = builder().sign(b"payload").unwrap();
        let cred2 = builder().sign(b"payload").unwrap();

        // Different nonces should be generated
        assert_ne!(cred1.nonce, cred2.nonce);

        // But signatures should be different due to different nonces
        assert_ne!(cred1.signature, cred2.signature);
    }

    #[test]
    fn test_structured_vs_regular_signing() {
        let secret = b"secret";

        // Sign components individually
        let mut combined = Vec::new();
        combined.extend_from_slice(b"part1");
        combined.extend_from_slice(b"part2");

        let cred1 = CredentialBuilder::new(secret)
            .with_nonce_generator(|| "fixed_nonce".to_string())
            .with_time_provider(|| Ok(1234567890))
            .sign(&combined)
            .unwrap();

        // Sign as structured components
        let cred2 = CredentialBuilder::new(secret)
            .with_nonce_generator(|| "fixed_nonce".to_string())
            .with_time_provider(|| Ok(1234567890))
            .sign_structured(&[b"part1", b"part2"])
            .unwrap();

        // Should produce the same result
        assert_eq!(cred1.signature, cred2.signature);
    }

    #[test]
    fn test_builder_method_chaining() {
        let secret = b"test_secret";
        let payload = b"test_payload";

        // Test different building orders produce same result
        let cred1 = CredentialBuilder::new(secret)
            .with_nonce_generator(|| "custom".to_string())
            .with_time_provider(|| Ok(1234567890))
            .sign(payload)
            .unwrap();

        let cred2 = CredentialBuilder::new(secret)
            .with_time_provider(|| Ok(1234567890))
            .with_nonce_generator(|| "custom".to_string())
            .sign(payload)
            .unwrap();

        assert_eq!(cred1.nonce, "custom");
        assert_eq!(cred1.timestamp, 1234567890);
        assert_eq!(cred1.signature, cred2.signature);
    }
}