How OmniRoute Implements Security Measures for API Keys and Tokens
OmniRoute employs a defense-in-depth strategy that encrypts API keys at rest using environment-derived secrets, validates every request through multi-layered policy enforcement, and monitors usage via granular rate limits, budget controls, and audit logging.
The open-source OmniRoute project (diegosouzapw/OmniRoute) treats every API credential as a highly sensitive asset requiring protection across its entire lifecycle. Understanding how OmniRoute implements security measures for API keys and tokens reveals a comprehensive architecture covering encryption, validation, rotation, and fine-grained access controls.
Encryption at Rest and Environment Secrets
OmniRoute ensures that API keys are never stored in plain text. When a key is persisted to the SQLite database, the system encrypts the value using a secret derived from the mandatory environment variable API_KEY_SECRET.
Database Encryption with API_KEY_SECRET
In src/lib/localDb/apiKeys.ts, the database helpers handle encryption during insertion and decryption during retrieval. The encryption key is derived from API_KEY_SECRET, which is also used by the apiKeyRotator service to decrypt keys on-the-fly during rotation cycles. This ensures that even if the database files are compromised, the credentials remain inaccessible without the environment secret.
Mandatory Environment Validation
The application enforces strict startup validation. If API_KEY_SECRET is missing, OmniRoute aborts initialization to prevent accidental exposure of keys. This behavior is verified in the test suite, specifically in files like tests/unit/web-runtime-env.test.ts, where tests deliberately omit the variable to confirm the application fails safely.
Request Validation and Policy Enforcement
Every incoming request undergoes rigorous validation before reaching business logic. The system extracts the key, validates its format and status, then enforces a comprehensive policy matrix.
Key Extraction and Validation
The extractApiKey function in src/sse/services/auth.ts pulls credentials from Authorization headers or query strings. Immediately after extraction, validateApiKey (located in src/lib/localDb/apiKeys.ts) verifies the key's existence, format, and active status, ensuring banned or revoked keys are rejected at the edge.
Granular Policy Controls
After validation, enforceApiKeyPolicy in src/shared/utils/apiKeyPolicy.ts applies fine-grained controls:
- Model whitelist/blacklist (
allowedModels) - Connection whitelist (
allowedConnections) - Combo whitelist (
allowedCombos) - Quota whitelist (
allowedQuotas) - Budget enforcement (
budgetandusedBudgettracking) - Custom rate limits (
RateLimitRulearrays) - Time-based access windows (scheduling)
- Scope-based feature gating (
scopes) - Endpoint restrictions (
allowedEndpoints)
This centralized policy engine ensures that even valid keys can only access explicitly permitted resources.
Rate Limiting and Temporal Controls
OmniRoute implements sophisticated traffic management to prevent abuse and ensure fair usage across tenant boundaries.
Per-Key Rate Limiting
Each API key can define custom multi-window rate limits (daily, hourly, etc.). The buildDefaultRateLimits function parses DEFAULT_RATE_LIMIT_PER_DAY from environment variables into RateLimitRule[] structures. At runtime, the checkRateLimit function in src/sse/utils/rateLimiter.ts enforces these limits and optionally applies throttling delays via throttleDelayMs.
The following TypeScript demonstrates how rate limits are structured in the database:
// Settings payload sent by the UI
{
"apiKeyId": "ck_3f7b9a2e",
"rateLimits": [
{ "limit": 5000, "window": 86400 }, // 5k requests per day
{ "limit": 200, "window": 3600 } // 200 requests per hour
]
}
Time-Based Access Scheduling
Keys may be restricted to specific hours and days using the isWithinSchedule function in src/shared/utils/apiKeyPolicy.ts. This utility evaluates configured timezones, supports overnight windows (e.g., 22:00 to 06:00), and falls back to allow-open behavior on invalid timezone configurations, preventing accidental lockouts while maintaining strict enforcement when properly configured.
Budget Management and Scope Controls
Beyond rate limiting, OmniRoute implements financial and permission-based guardrails.
Budget Caps and Usage Tracking
The checkBudget routine in src/domain/costRules.ts monitors budget and usedBudget columns for each key. If a request would exceed the configured monetary limit, the system blocks the operation before incurring costs. This prevents runaway spending from compromised or misconfigured keys.
Scope-Based Permissions
Scopes (stored in the scopes column) enable feature gating. For example, hasProviderQuotaBypassScope grants specific keys the ability to bypass standard quota checks. The request pipeline consults these scopes via helper functions in src/shared/utils/apiKeyPolicy.ts to determine whether special tooling or elevated permissions are permitted.
Key Rotation and Token Hierarchy
OmniRoute provides mechanisms for credential lifecycle management and fallback strategies for different service tiers.
Automated Key Rotation
The apiKeyRotator service (located in @omniroute/open-sse/services/apiKeyRotator.ts) manages key health through syncHealthFromDB and KeyHealth interfaces. This service periodically refreshes long-living keys, updates database rows with newly encrypted values, and clears stale error states. All rotation events are logged with request IDs for auditability.
The following snippet illustrates the rotation workflow:
import { getApiKeyById, updateProviderConnection } from "@/lib/localDb";
import { syncHealthFromDB } from "@/sse/services/auth";
async function rotateKey(keyId: string) {
const key = await getApiKeyById(keyId);
// Decrypt, rotate with external provider, re‑encrypt
const newPlain = await providerRotate(key.plaintext);
await updateProviderConnection(key.connectionId, {
apiKey: encrypt(newPlain, process.env.API_KEY_SECRET!),
});
// Update health status so the rest of the system knows the key is fresh
await syncHealthFromDB(key.connectionId, { healthy: true });
}
Hierarchical Token Resolution
For services like Vision Bridge that require image or video processing tokens, OmniRoute implements a fallback hierarchy. The system first checks VISION_BRIDGE_API_KEY, then falls back to provider-specific variables (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.). This hierarchy is exercised in tests/unit/vision-bridge-env-override.test.ts, ensuring graceful degradation while maintaining security boundaries.
Audit Logging and Security Monitoring
Comprehensive logging ensures that security events are traceable without exposing sensitive data.
Secure Log Masking
Before any key identifier appears in logs, sensitive segments are redacted using the maskSegment helper in src/shared/utils/formatting.ts. Every policy decision—whether "budget exceeded", "model not allowed", or rate limit violations—logs the masked key ID and reason via the logger in src/sse/utils/logger.ts, providing audit trails without compromising credential security.
Summary
OmniRoute implements security measures for API keys and tokens through a defense-in-depth architecture:
- Encryption at rest using
API_KEY_SECRETto protect database-stored credentials insrc/lib/localDb/apiKeys.ts - Mandatory environment validation that prevents startup without proper secrets
- Request validation via
validateApiKeyandextractApiKeyin the authentication layer - Policy enforcement covering models, connections, budgets, and scopes through
enforceApiKeyPolicy - Rate limiting with customizable windows and throttling via
checkRateLimit - Temporal controls restricting access to specific hours and days using
isWithinSchedule - Budget enforcement preventing overspend through
checkBudgetin the cost rules domain - Key rotation managed by the
apiKeyRotatorservice with health synchronization - Secure logging using
maskSegmentto redact sensitive identifiers before persistence
Frequently Asked Questions
How does OmniRoute encrypt API keys at rest?
OmniRoute encrypts API keys using a secret derived from the API_KEY_SECRET environment variable before storing them in the SQLite database. The encryption and decryption logic resides in src/lib/localDb/apiKeys.ts, ensuring that database files never contain plaintext credentials. The same secret is used by the rotation service to decrypt keys temporarily during refresh cycles.
What happens if the API_KEY_SECRET environment variable is missing?
The application performs mandatory validation during startup and aborts initialization if API_KEY_SECRET is undefined or empty. This fail-safe mechanism, verified in unit tests like tests/unit/web-runtime-env.test.ts, prevents the system from running in an insecure state where keys would be stored or transmitted without encryption.
How does OmniRoute handle API key rotation?
Key rotation is managed by the apiKeyRotator service (@omniroute/open-sse/services/apiKeyRotator.ts) which uses syncHealthFromDB to refresh long-living keys. The service decrypts existing keys, rotates them with external providers, re-encrypts the new values using API_KEY_SECRET, and updates the database while maintaining health status. This process ensures continuous service without exposing keys during the transition.
Can I restrict API key usage to specific time windows?
Yes, OmniRoute supports time-based access controls through the isWithinSchedule function in src/shared/utils/apiKeyPolicy.ts. Administrators can configure specific hours and weekdays for each key, with support for overnight windows and timezone-aware validation. Invalid timezone configurations gracefully fall back to allow-open behavior to prevent accidental service disruption.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →