Authentication & Security
Relevant source files
The following files were used as context for generating this wiki page:
The Authentication and Security system within SecondLayer is designed as a multi-layered defense architecture to protect legal data and AI services. It employs a "Dual-Auth" strategy, supporting both standard web-based user sessions via JWT/OAuth and programmatic API access via Bearer tokens. This system ensures that all interactions with the Model Context Protocol (MCP) tools, document analysis services, and financial transactions are authenticated, authorized, and rate-limited.
The scope of this system covers the primary HTTP server, Server-Sent Events (SSE) streaming, and the unified gateway that aggregates tools from multiple MCP servers. It integrates closely with the billing and cost-tracking modules to prevent unauthorized resource consumption and ensure budget-aware tool execution.
Multi-Layered Authentication Architecture
SecondLayer implements several authentication strategies depending on the client type and the endpoint being accessed. The core logic is centralized in the http-server.ts and managed through various middleware components.
Dual-Auth Strategy
The system utilizes a "Dual-Auth" middleware that can process different types of credentials within a single request context. This is particularly important for the Unified Gateway which handles requests from web users, CLI tools, and automated bots.
- JWT Authentication: Primarily used for web users. The system validates 128-character random hex secrets to verify signatures.
- API Key Authentication: Used for programmatic access. Valid keys are stored in the
SECONDARY_LAYER_KEYSenvironment variable. - OAuth 2.0: Specifically implemented for integration with external platforms like ChatGPT/OpenAI, supporting authorization codes and bearer tokens.
Sources: mcp_backend/src/http-server.ts:212-230, mcp_backend/JWT_AUTH_SETUP.md:73-85, CLAUDE.md:213-220
Authentication Flow
The following sequence diagram illustrates how the system handles a request across different authentication providers:
Security Components and Features
1. Rate Limiting
To protect against DoS attacks and resource exhaustion, specific rate limits are applied to various categories of endpoints.
| Rate Limit Policy | Target Endpoints | Purpose |
|---|---|---|
mcpDiscoveryRateLimit | GET /mcp | Limits tool and capability discovery requests. |
healthCheckRateLimit | /health, /health/ready | Protects monitoring endpoints from spam. |
webhookRateLimit | /webhooks/stripe, /webhooks/fondy | Prevents high-frequency payment notification floods. |
chatRateLimit | /api/chat | Controls expensive AI agentic loop executions. |
Sources: mcp_backend/src/http-server.ts:25-30, mcp_backend/src/middleware/rate-limit.ts
2. JWT Configuration
JWT tokens are used for long-term programmatic access and web session persistence. The implementation uses jsonwebtoken and follows strict expiration and signing rules.
- Algorithm: HS256.
- Payload: Includes
sub(Client ID),iat(Issued at),exp(Expires at), andiss(Issuer). - Default Expiration: 365 days, with options for
7d,30d,90d, ornever. - Storage: Secrets are stored in
.env.productionand must never be committed to version control.
Sources: mcp_backend/JWT_AUTH_SETUP.md:92-110, mcp_backend/JWT_AUTH_SETUP.md:144-155
3. Server-Sent Events (SSE) Security
The SSE implementation requires specific handling because connections remain open for long periods.
- Public Access: The
/healthand/sse(GET/OPTIONS) endpoints allow anonymous access for compatibility with platform discovery (e.g., ChatGPT/OpenAI discovery). - Protected Access: Standard MCP tool execution over SSE (
POST /v1/sseor/api/tools/:name/stream) requires valid Bearer authentication. - Context Injection: The system extracts
userIdorclientKeyand injects it into therequestContextto ensure costs are tracked correctly even in asynchronous streams.
Sources: mcp_backend/src/http-server.ts:390-420, mcp_backend/src/api/tests/sse/sse-authentication.test.ts:70-100
Credential Management
Secure credential initialization is automated during deployment to prevent common authentication failures.
Key Environment Variables
| Variable | Description | Security Requirement |
|---|---|---|
JWT_SECRET | Secret for signing JSON Web Tokens. | 128-character random hex string. |
SECONDARY_LAYER_KEYS | Comma-separated list of valid API keys. | Generated via openssl rand -hex 32. |
ZAKONONLINE_API_TOKEN | Token for external legal database access. | Must be protected to prevent budget drain. |
POSTGRES_SUPERUSER_PASSWORD | Database administrative password. | Used only during initial volume setup. |
Sources: mcp_backend/DEPLOYMENT.md:25-40, mcp_backend/JWT_AUTH_SETUP.md:73-80, deployment/CREDENTIALS_SETUP.md:110-125
Authentication Testing and Verification
The system includes a dedicated test suite for verifying security flows, particularly for SSE and tool execution.
- Handshake Verification: Tests verify that
POST /v1/ssewithout a token returns401 Unauthorized. - Content Negotiation: The system ensures that requests with
Accept: text/event-streamare handled as authenticated streams. - Anonymous Fallback: Tests confirm that the system gracefully handles invalid JWTs by falling back to anonymous mode only for discovery endpoints, while enforcing strict rejection for tool execution.
Sources: mcp_backend/src/api/tests/sse/sse-authentication.test.ts:110-140, mcp_backend/src/api/tests/sse/sse-authentication.test.ts:215-235
Conclusion
The Authentication & Security system provides a robust framework for securing a complex legal AI platform. By combining Dual-Auth strategies, rigid rate limiting, and automated credential validation, the project ensures that both user-facing web applications and programmatic MCP clients operate within a secure, audited environment. This architecture is central to maintaining the integrity of legal analysis and protecting the platform's operational resources.
Sources: CLAUDE.md:213-220, mcp_backend/src/http-server.ts:440-460