Skip to content

Route Handlers

Rain Zhang edited this page Nov 6, 2025 · 2 revisions

Route Handlers

Table of Contents

  1. Introduction
  2. Architecture Overview
  3. Simple Route Handlers
  4. Advanced Route Handlers
  5. General Purpose Route Handlers
  6. Shared Utilities and Helpers
  7. Cross-Origin Request Handling
  8. Performance Optimization
  9. Error Handling and Validation
  10. Security Considerations
  11. Troubleshooting Guide
  12. Best Practices

Introduction

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.

Architecture Overview

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
Loading

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

Simple Route Handlers

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.

Registration Flow

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
Loading

Diagram sources

  • server/server/routes/simple.py
  • server/server/routes/simple.py

Registration Begin Endpoint

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"
}

Registration Complete Endpoint

The /api/register/complete endpoint validates and stores the completed registration:

Processing Steps:

  1. Extract and validate attestation data
  2. Verify client data JSON integrity
  3. Perform cryptographic attestation checks
  4. Store credential metadata and public key material
  5. Generate audit trail and logging

Section sources

  • server/server/routes/simple.py
  • server/server/routes/simple.py

Authentication Flow

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]
Loading

Diagram sources

  • server/server/routes/simple.py
  • server/server/routes/simple.py

Authentication Begin Endpoint

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

Authentication Complete Endpoint

The /api/authenticate/complete endpoint validates authentication assertions:

Validation Process:

  1. Session state verification
  2. Challenge validation
  3. Signature verification against stored public key
  4. Sign count update and validation
  5. User identity confirmation

Section sources

  • server/server/routes/simple.py

Advanced Route Handlers

The advanced route handlers provide comprehensive WebAuthn customization through JSON editor interfaces. These endpoints support complex authenticator configurations and CTAP2 extensions.

Advanced Registration Flow

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]
Loading

Diagram sources

  • server/server/routes/advanced.py

Advanced Registration Begin Endpoint

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

Advanced Registration Complete Endpoint

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

Advanced Authentication Flow

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]
Loading

Diagram sources

  • server/server/routes/advanced.py

Section sources

  • server/server/routes/advanced.py

General Purpose Route Handlers

The general purpose handlers provide administrative and utility functions essential for platform operation.

Metadata Management Endpoints

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

Codec and Decoder Endpoints

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

Utility Endpoints

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

Shared Utilities and Helpers

The route handlers rely on a comprehensive set of shared utilities for common operations.

Binary Data Processing

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]
Loading

Diagram sources

  • server/server/routes/simple.py
  • server/server/routes/advanced.py

Algorithm Management

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

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

Cross-Origin Request Handling

The platform implements comprehensive CORS support for secure cross-origin operations.

Origin Validation

Origin validation ensures requests come from trusted sources:

Validation Process:

  1. Extract origin from request headers
  2. Compare against configured allowed origins
  3. Validate against RP ID hash
  4. Apply fallback origin determination

Section sources

  • server/server/routes/simple.py

Security Headers

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=()

Performance Optimization

The route handlers implement several performance optimization strategies for high-throughput scenarios.

Caching Strategies

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

Connection Pooling

Storage Backend Optimization:

  • Cloud storage connections pooled
  • Local filesystem operations optimized
  • Batch operations for bulk credential updates

Memory Management

Efficient Data Structures:

  • Lazy loading of credential data
  • Streaming responses for large payloads
  • Garbage collection optimization for temporary objects

Error Handling and Validation

The route handlers implement comprehensive error handling and validation mechanisms.

Input Validation

Request Validation Pipeline:

  1. JSON parsing with error recovery
  2. Parameter type checking
  3. Range and format validation
  4. 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 Standardization

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

Logging and Monitoring

Structured Logging:

  • Request/response logging with correlation IDs
  • Performance metrics collection
  • Security event logging
  • Error tracking and alerting

Security Considerations

The route handlers implement multiple security layers to protect against various attack vectors.

Authentication Security

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

Data Integrity

Cryptographic Validation:

  • Digital signature verification
  • Attestation chain validation
  • Hash verification for data integrity

Section sources

  • server/server/attestation.py

Troubleshooting Guide

Common issues and their resolutions for route handler operations.

Registration Issues

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

Authentication Issues

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

Performance Issues

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

Best Practices

Development Guidelines

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

Deployment Considerations

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

Post-Quantum WebAuthn Platform

Getting Started

Architectural Foundations

Cryptography & Security

Authentication Platform

Core Protocol

Flows & Interfaces

Authenticator Capabilities

Server Platform

Frontend Platform

Architecture

Interaction & Utilities

Metadata Service (MDS)

Storage & Data Management

Data Models & Encoding

API Reference

Cross-Platform & HID

Operations & Troubleshooting

Glossary & References

Clone this wiki locally