-
Notifications
You must be signed in to change notification settings - Fork 0
Route Handlers
- Introduction
- Architecture Overview
- Simple Route Handlers
- Advanced Route Handlers
- General Purpose Route Handlers
- Shared Utilities and Helpers
- Cross-Origin Request Handling
- Performance Optimization
- Error Handling and Validation
- Security Considerations
- Troubleshooting Guide
- Best Practices
The WebAuthn platform implements a comprehensive set of route handlers that manage the complete WebAuthn authentication and registration lifecycle. The system provides three distinct routing layers: simple handlers for basic WebAuthn flows, advanced handlers for JSON editor-based customization, and general purpose handlers for administrative and utility functions.
The route handlers are built on Flask and leverage the FIDO2 library to provide robust WebAuthn support with post-quantum cryptographic algorithm compatibility. The architecture separates concerns between presentation, business logic, and data persistence while maintaining security best practices throughout the authentication pipeline.
The route handler architecture follows a layered approach with clear separation of responsibilities:
graph TB
subgraph "Client Layer"
A[Browser Frontend]
B[JavaScript Clients]
end
subgraph "Route Handlers"
C[Simple Routes<br/>/api/register/*, /api/authenticate/*]
D[Advanced Routes<br/>/api/advanced/*]
E[General Routes<br/>/api/mds/*, /api/codec/*]
end
subgraph "Business Logic"
F[FIDO2 Server]
G[Attestation Verification]
H[Credential Management]
end
subgraph "Data Layer"
I[Storage Backend]
J[Cloud Storage]
K[Local Filesystem]
end
A --> B
B --> C
B --> D
B --> E
C --> F
D --> F
E --> G
F --> H
H --> I
I --> J
I --> K
Diagram sources
- server/server/routes/simple.py
- server/server/routes/advanced.py
- server/server/routes/general.py
The architecture implements several key design patterns:
- Handler Pattern: Each route endpoint is implemented as a dedicated handler function
- Factory Pattern: FIDO2 server instances are created dynamically based on request context
- Strategy Pattern: Different attestation verification strategies based on authenticator type
- Template Method: Common validation and processing logic shared across handlers
Section sources
- server/server/app.py
- server/server/routes/simple.py
The simple route handlers provide streamlined WebAuthn functionality for basic registration and authentication scenarios. These endpoints are designed for straightforward user experiences with minimal configuration requirements.
The registration process follows the standard WebAuthn ceremony with enhanced post-quantum cryptographic support:
sequenceDiagram
participant Client as Browser Client
participant Simple as Simple Handler
participant FIDO2 as FIDO2 Server
participant Storage as Storage Backend
Client->>Simple : POST /api/register/begin
Simple->>Simple : Parse request parameters
Simple->>FIDO2 : register_begin()
FIDO2-->>Simple : RegistrationOptions
Simple-->>Client : Challenge + Options
Client->>Client : Authenticator interaction
Client->>Simple : POST /api/register/complete
Simple->>Simple : Extract attestation details
Simple->>Simple : Perform attestation checks
Simple->>Storage : Store credential data
Simple-->>Client : Registration result
Diagram sources
- server/server/routes/simple.py
- server/server/routes/simple.py
The /api/register/begin endpoint initiates the registration process:
Key Features:
- Supports post-quantum algorithms (ML-DSA variants)
- Automatic algorithm filtering based on client capabilities
- Cross-platform authenticator attachment preference
- Session state management for CSRF protection
Request Schema:
{
"credentials": [
{
"credentialId": "base64url_encoded_id",
"publicKey": "base64url_encoded_public_key",
"aaguid": "base64url_encoded_aaguid",
"signCount": 0,
"algorithm": -50
}
]
}Response Schema:
{
"publicKey": {
"challenge": "base64url_challenge",
"rp": {"id": "example.com", "name": "Example"},
"user": {
"id": "base64url_user_id",
"name": "username",
"displayName": "User Display Name"
},
"pubKeyCredParams": [
{"type": "public-key", "alg": -50},
{"type": "public-key", "alg": -49},
{"type": "public-key", "alg": -7}
],
"timeout": 90000,
"attestation": "none",
"authenticatorSelection": {
"authenticatorAttachment": "cross-platform",
"userVerification": "discouraged"
}
},
"__session_state": "session_state_data"
}The /api/register/complete endpoint validates and stores the completed registration:
Processing Steps:
- Extract and validate attestation data
- Verify client data JSON integrity
- Perform cryptographic attestation checks
- Store credential metadata and public key material
- Generate audit trail and logging
Section sources
- server/server/routes/simple.py
- server/server/routes/simple.py
The authentication process enables secure user verification using previously registered credentials:
flowchart TD
A[Begin Authentication] --> B{Credentials Found?}
B --> |No| C[Return 404 Not Found]
B --> |Yes| D[Generate Challenge]
D --> E[Send Options to Client]
E --> F[Client Authenticates]
F --> G[Receive Assertion]
G --> H[Verify Signature]
H --> I[Update Sign Count]
I --> J[Return Success]
H --> |Invalid| K[Return Error]
I --> |Error| L[Log Failure]
Diagram sources
- server/server/routes/simple.py
- server/server/routes/simple.py
The /api/authenticate/begin endpoint prepares authentication options:
Features:
- Credential filtering based on stored data
- Challenge generation for replay protection
- Session state preservation
- Cross-origin request support
Section sources
- server/server/routes/simple.py
The /api/authenticate/complete endpoint validates authentication assertions:
Validation Process:
- Session state verification
- Challenge validation
- Signature verification against stored public key
- Sign count update and validation
- User identity confirmation
Section sources
- server/server/routes/simple.py
The advanced route handlers provide comprehensive WebAuthn customization through JSON editor interfaces. These endpoints support complex authenticator configurations and CTAP2 extensions.
The advanced registration process supports extensive customization options:
graph LR
A[JSON Editor Input] --> B[Parse Configuration]
B --> C[Validate Parameters]
C --> D[Apply Algorithm Filtering]
D --> E[Configure Extensions]
E --> F[Set Authenticator Selection]
F --> G[Generate Options]
G --> H[Store Session State]
H --> I[Return Configuration]
Diagram sources
- server/server/routes/advanced.py
The /api/advanced/register/begin endpoint accepts fully customizable registration options:
Supported Configurations:
- Custom Relying Party entities
- Multi-algorithm credential creation
- Authenticator attachment preferences
- User verification requirements
- Resident key policies
- CTAP2 extensions (largeBlob, PRF, credProtect)
Advanced Request Schema:
{
"publicKey": {
"rp": {
"id": "example.com",
"name": "Example Corporation"
},
"user": {
"id": "base64url_user_id",
"name": "username",
"displayName": "User Display Name"
},
"challenge": "base64url_challenge",
"pubKeyCredParams": [
{"type": "public-key", "alg": -50},
{"type": "public-key", "alg": -49},
{"type": "public-key", "alg": -7},
{"type": "public-key", "alg": -257}
],
"timeout": 90000,
"attestation": "direct",
"authenticatorSelection": {
"authenticatorAttachment": "cross-platform",
"userVerification": "required",
"residentKey": "required",
"requireResidentKey": true
},
"extensions": {
"credProps": true,
"minPinLength": true,
"largeBlob": {"support": "true"},
"prf": {"eval": {"first": "base64_data", "second": "base64_data"}},
"credentialProtectionPolicy": "userVerificationRequired",
"enforceCredentialProtectionPolicy": true
}
}
}Section sources
- server/server/routes/advanced.py
The /api/advanced/register/complete endpoint handles complex attestation scenarios:
Enhanced Features:
- Extensive extension result processing
- Authenticator attachment enforcement
- Large blob capability detection
- Post-quantum algorithm availability checking
- Comprehensive error reporting
Section sources
- server/server/routes/advanced.py
The advanced authentication flow supports sophisticated credential selection and assertion processing:
flowchart TD
A[Parse Advanced Options] --> B[Validate Credentials]
B --> C[Apply Attachment Filters]
C --> D[Select Suitable Authenticators]
D --> E[Generate Authentication Options]
E --> F[Process Extensions]
F --> G[Send to Client]
G --> H[Receive Assertion]
H --> I[Validate Results]
I --> J[Update Metadata]
Diagram sources
- server/server/routes/advanced.py
Section sources
- server/server/routes/advanced.py
The general purpose handlers provide administrative and utility functions essential for platform operation.
The metadata service endpoints handle FIDO Alliance metadata synchronization:
| Endpoint | Method | Purpose | Response |
|---|---|---|---|
/api/mds/metadata/base |
GET | Retrieve verified metadata snapshot | JSON metadata |
/api/mds/metadata/custom |
GET | List custom uploaded metadata | Metadata entries |
/api/mds/metadata/upload |
POST | Upload custom metadata files | Upload results |
/api/mds/metadata/custom/<filename> |
DELETE | Remove custom metadata | Deletion status |
Section sources
- server/server/routes/general.py
The codec endpoints provide payload conversion utilities:
| Endpoint | Method | Purpose | Input Format | Output Format |
|---|---|---|---|---|
/api/codec |
POST | Universal codec for various formats | JSON with payload and mode | Converted payload |
/api/decode |
POST | Base64/Hex decoding | JSON with payload | Decoded data |
/api/mds/decode-certificate |
POST | X.509 certificate decoding | JSON with certificate | Certificate details |
Section sources
- server/server/routes/general.py
Additional utility endpoints support platform maintenance:
- Health Check: Basic server status monitoring
- Feature Detection: Browser capability assessment
- Credential Download: Export stored credentials
- Public Key Deletion: Remove stored public keys
Section sources
- server/server/routes/general.py
The route handlers rely on a comprehensive set of shared utilities for common operations.
The system implements robust binary data handling for WebAuthn payloads:
flowchart TD
A[Raw Input] --> B{Input Type?}
B --> |String| C[Normalize Encoding]
B --> |Bytes| D[Direct Processing]
B --> |Iterable| E[Convert to Bytes]
C --> F{Encoding Type?}
F --> |Base64| G[Base64 Decode]
F --> |Base64URL| H[Base64URL Decode]
F --> |Hex| I[Hex Decode]
G --> J[Validate Result]
H --> J
I --> J
D --> J
E --> J
J --> K{Valid?}
K --> |Yes| L[Return Bytes]
K --> |No| M[Return Empty]
Diagram sources
- server/server/routes/simple.py
- server/server/routes/advanced.py
The system supports extensive algorithm management for cryptographic operations:
Supported Algorithms:
- Post-Quantum: ML-DSA-87 (-50), ML-DSA-65 (-49), ML-DSA-44 (-48)
- Classical ECDSA: ES256 (-7), ES384 (-35), ES512 (-36)
- Classical RSA: RS256 (-257), RS384 (-258), RS512 (-259)
- EdDSA: EDDSA (-8), ED25519 (-19), ED448 (-53)
Section sources
- server/server/routes/simple.py
- server/server/routes/advanced.py
Session state management ensures security and prevents replay attacks:
State Components:
- Challenge values for replay protection
- Session identifiers for user context
- State tokens for CSRF protection
- Temporary credential data storage
Section sources
- server/server/routes/simple.py
- server/server/routes/advanced.py
The platform implements comprehensive CORS support for secure cross-origin operations.
Origin validation ensures requests come from trusted sources:
Validation Process:
- Extract origin from request headers
- Compare against configured allowed origins
- Validate against RP ID hash
- Apply fallback origin determination
Section sources
- server/server/routes/simple.py
The system applies appropriate security headers for WebAuthn operations:
Headers Applied:
- Content-Security-Policy: webauthn directives
- Cross-Origin-Embedder-Policy: require-corp
- Cross-Origin-Opener-Policy: same-origin
- Permissions-Policy: webauthn=()
The route handlers implement several performance optimization strategies for high-throughput scenarios.
Static Response Caching:
- Metadata snapshots cached in memory
- Algorithm lists cached during registration
- Extension configurations cached per session
Dynamic Data Caching:
- Credential data cached temporarily
- Attestation results cached for validation
- Authenticator capabilities cached
Storage Backend Optimization:
- Cloud storage connections pooled
- Local filesystem operations optimized
- Batch operations for bulk credential updates
Efficient Data Structures:
- Lazy loading of credential data
- Streaming responses for large payloads
- Garbage collection optimization for temporary objects
The route handlers implement comprehensive error handling and validation mechanisms.
Request Validation Pipeline:
- JSON parsing with error recovery
- Parameter type checking
- Range and format validation
- Business logic constraint checking
Common Validation Errors:
- Malformed JSON payloads
- Invalid base64 encoding
- Missing required parameters
- Out-of-range values
- Unsupported algorithm identifiers
Error Response Format:
{
"error": "Error description",
"code": "ERROR_CODE",
"details": "Additional context information"
}Error Categories:
- Client errors (4xx): Invalid requests, missing parameters
- Server errors (5xx): Internal failures, storage issues
- Authentication errors: Invalid signatures, expired challenges
- Authorization errors: Insufficient permissions
Section sources
- server/server/routes/simple.py
- server/server/routes/advanced.py
Structured Logging:
- Request/response logging with correlation IDs
- Performance metrics collection
- Security event logging
- Error tracking and alerting
The route handlers implement multiple security layers to protect against various attack vectors.
CSRF Protection:
- Session state validation for all mutations
- Challenge-based replay protection
- Origin validation for cross-origin requests
Credential Security:
- Encrypted storage of sensitive data
- Secure deletion of temporary data
- Audit logging for all credential operations
Cryptographic Validation:
- Digital signature verification
- Attestation chain validation
- Hash verification for data integrity
Section sources
- server/server/attestation.py
Common issues and their resolutions for route handler operations.
Problem: Registration fails with "Algorithm not supported"
- Cause: Client requested unsupported algorithm
- Solution: Verify algorithm support in client configuration
- Prevention: Use automatic algorithm filtering
Problem: Attestation verification fails
- Cause: Authenticator certificate chain validation failure
- Solution: Check metadata synchronization and certificate validity
- Prevention: Regular metadata updates
Problem: Authentication returns "Invalid signature"
- Cause: Stored public key mismatch or tampered data
- Solution: Re-register credential or verify data integrity
- Prevention: Implement proper data backup and recovery
Problem: Challenge validation fails
- Cause: Expired challenge or session state corruption
- Solution: Clear browser cookies and retry operation
- Prevention: Implement proper session management
Problem: Slow registration response times
- Cause: Metadata synchronization delays or storage backend issues
- Solution: Optimize metadata caching and storage configuration
- Prevention: Monitor performance metrics and implement caching
Section sources
- tests/test_server.py
Code Organization:
- Keep route handlers focused on request/response processing
- Move complex business logic to service layers
- Use consistent error handling patterns
Testing Strategy:
- Implement unit tests for individual handlers
- Create integration tests for complete flows
- Test edge cases and error conditions
Documentation Standards:
- Document all public endpoints with OpenAPI/Swagger
- Provide clear examples for complex scenarios
- Maintain inline code comments for complex logic
Environment Configuration:
- Separate configuration for development, staging, and production
- Environment-specific logging levels and monitoring
- Proper SSL/TLS configuration for all endpoints
Monitoring and Alerting:
- Track endpoint response times and error rates
- Monitor storage backend performance
- Implement alerting for security events
Section sources
- server/server/app.py