Nonce Auth
A Rust-based secure nonce authentication library that provides one-time token (nonce) generation, signing, and verification functionality to effectively prevent replay attacks.
Features
- 🔐 HMAC-SHA256 Signing - Cryptographic signing of requests using shared secrets
- ⏰ Timestamp Window Validation - Prevents replay attacks from expired requests
- 🔑 One-time Nonce - Ensures each nonce can only be used once
- 💾 SQLite Persistence - Automatic nonce storage and cleanup management
- 🎯 Context Isolation - Support for nonce isolation across different business scenarios
- 🚀 Async Support - Fully asynchronous API design
- 🛡️ Security Protection - Constant-time comparison to prevent timing attacks
- 📦 Client-Server Separation - Clean separation of client and server responsibilities
- 🔧 Flexible Signature Algorithm - Customizable signature data construction
Architecture
Client-Server Separation Design
The library provides two independent managers for clear separation of responsibilities:
NonceClient - Client-side Manager
- Responsible for generating signed authentication data
- No database dependencies required
- Lightweight design suitable for client-side use
- Flexible signature algorithm through closures
NonceServer - Server-side Manager
- Responsible for verifying signed authentication data
- Manages nonce storage and cleanup
- Includes timestamp validation and replay attack prevention
- Supports context isolation for different business scenarios
Parameter Explanation
default_ttl: Nonce time-to-live, representing the duration from generation to expiration, defaults to 5 minutestime_window: Timestamp validation window, defaults to 1 minute
Both work together to prevent replay attacks.
Important Notes
- The server uses local SQLite for nonce persistence, please consider using with connection sticky policies
- Signature algorithms are fully customizable through closures for maximum flexibility
Quick Start
Add Dependencies
[]
= "0.2.0"
= { = "1", = ["full"] }
= { = "1.0", = ["derive"] }
= "1.0"
= "0.3"
= "0.12"
Simple Usage Example
use Mac;
use ;
use Duration;
async
Complete Web Application Example
JavaScript Client
// client.js
// Usage example
Rust Server
// server.rs
use Mac;
use NonceServer;
use ;
use HashMap;
use Arc;
use Duration;
use Filter;
// Store PSKs for each session
type PskStore = ;
async
async
Example Authentication Flow Sequence Diagram
sequenceDiagram
participant Browser as Web Browser
participant RustServer as Rust Server
participant DB as SQLite Database
Note over Browser, DB: Session-based Authentication Flow
Browser->>RustServer: 1. GET / (page request)
RustServer->>RustServer: 2. Generate random PSK and session ID
RustServer->>RustServer: 3. Store PSK with session ID
RustServer->>Browser: 4. HTML with embedded PSK and session ID
Browser->>Browser: 5. User enters payload
Browser->>Browser: 6. Generate UUID nonce
Browser->>Browser: 7. Create timestamp
Browser->>Browser: 8. Sign (timestamp + nonce + payload) with HMAC-SHA256
Browser->>RustServer: 9. POST /api/protected<br/>{payload, session_id, auth: {timestamp, nonce, signature}}
RustServer->>RustServer: 10. Lookup PSK by session_id
alt Invalid session ID
RustServer-->>Browser: 401 Invalid session ID
end
RustServer->>RustServer: 11. Create NonceServer with PSK
RustServer->>RustServer: 12. Verify timestamp within window
alt Timestamp out of window
RustServer-->>Browser: 401 Timestamp expired
end
RustServer->>RustServer: 13. Verify HMAC signature
alt Invalid signature
RustServer-->>Browser: 401 Invalid signature
end
RustServer->>DB: 14. Check if nonce exists
alt Nonce already used
RustServer-->>Browser: 401 Duplicate nonce
end
RustServer->>DB: 15. Store nonce
RustServer->>RustServer: 16. Process business logic
RustServer-->>Browser: 200 Success response
Note over RustServer, DB: Background cleanup
RustServer->>DB: Cleanup expired nonces as needed
API Documentation
NonceClient
Constructor
secret: Secret key used for signing
Methods
Create Authentication Data
Generates authentication data with custom signature algorithm. The closure receives the MAC instance, timestamp string, and nonce string.
Generate Signature
Generates HMAC-SHA256 signature with custom data builder.
NonceServer
Constructor
secret: Secret key used for verificationdefault_ttl: Default nonce expiration time (default: 5 minutes)time_window: Allowed time window for timestamp validation (default: 1 minute)
Methods
Verify Authentication Data
pub async
Verifies authentication data with custom signature algorithm. The closure should match the one used on the client side.
Initialize Database
pub async
Creates necessary database tables and indexes.
AuthData
Error Types
Typical Use Cases
1. API Authentication
- Client generates authentication data for each request
- Server verifies each request independently
- Each authentication data can only be used once
2. Form Submission Protection
- Generate authentication data when rendering form
- Verify authentication data when submitting
- Prevents duplicate form submissions
3. Microservice Authentication
- Service A generates authentication data for requests
- Service B verifies requests from Service A
- Ensures request uniqueness and authenticity
4. Session-based Authentication
- Server generates random PSK per session
- Client uses session PSK for all requests
- Provides stateless authentication with session isolation
Security Features
Replay Attack Prevention
- Time Window Limitation: Only accepts requests within specified time window
- One-time Nonce: Each nonce is deleted after verification, ensuring no reuse
- Context Isolation: Nonces from different business scenarios are isolated
Timing Attack Prevention
- Uses constant-time comparison algorithms for signature verification
Cryptographic Strength
- Uses HMAC-SHA256 algorithm to ensure signature integrity and authenticity
- Supports custom secret key lengths
- Flexible signature algorithms through closures
Performance Optimization
- Automatic background cleanup of expired nonce records
- Database index optimization for query performance
- Asynchronous design supports high-concurrency scenarios
Dependencies
hmac- HMAC signingsha2- SHA256 hashingturbosql- SQLite ORMuuid- UUID generationserde- Serialization supporttokio- Async runtimethiserror- Error handling
License
MIT OR Apache-2.0
Contributing
Issues and Pull Requests are welcome!