chain-rdeveloper portal
build

API Security

Overview

The Chainr platform implements comprehensive API security measures to protect against common web vulnerabilities and ensure secure communication between services.

Authentication & Authorization

JWT Token Security

  • RS256 signing algorithm

  • Token expiration and refresh

  • Secure token storage (HttpOnly cookies)

  • Token revocation capabilities

API Key Management

  • Service-to-service authentication

  • API key rotation

  • Rate limiting per key

  • Key scope limitations

Internal Trust Boundary

  • Edge authentication is enforced by Nginx + svc-auth for app traffic.

  • svc-bff acts as the internal caller to svc-core and svc-ai.

  • Downstream services validate a signed, audience-bound internal token (X-Internal-Token, HS256, short-lived) on every call — they do not trust forwarded user headers alone. svc-core derives identity from the verified sub; svc-ai rejects untokened requests. Enabled via INTERNAL_JWT_SECRET (required in staging/production).

  • Internal services publish no host ports and sit on an internal Docker network; only nginx (:8000) is exposed. Local dev re-opens ports via docker-compose.override.yml.

  • See security/auth-flow.md for the full auth boundary contract.

MCP Servers — Off in Every Environment

MCP servers, and the toolkits that bundle them, are withdrawn for the MVP (October 2026). As built, they were a hole in the boundary above:

  • stdio servers ran inside svc-ai — the container holding the provider keys, on ai-network with postgres-ai, qdrant, minio and neo4j. The launcher allowlist included python, so any signed-in user could save a server whose command was python -c "<code>" and run it with Probe. The allowlist was never a sandbox: npx and uvx fetch and execute any package.

  • http/sse URLs were checked only for their scheme, so a server could name an internal service (http://qdrant:6333) and svc-ai would call it.

  • Connection credentials (tokens, connection strings) were stored as plaintext JSON and returned on the server's read response.

Each service now holds its own constant, MCP_AVAILABLE = False, and neither trusts the other to be off. It is a constant rather than a setting, so no dotenv file or environment variable can turn it on:

  • svc-ai (app/mcp/__init__.py) — tool loading and probing return before a descriptor is parsed, so no client is built and no subprocess spawned whatever svc-core forwards. Toolkit generation answers 403. Stdio is off by default and no interpreter is on the launcher allowlist, for when MCP returns.

  • svc-core (app/services/mcp.py) — every write that would configure a server or put one in an agent's reach answers 403 (creating or editing a server or toolkit, probing, templates, toolkit membership and grants, a skill node or worker naming a server, toolkits in generative agent setup). The resolvers forward no descriptors, so stored credentials never leave svc-core. Reads, history and deletes still work.

  • fe-core (src/util/mcp.ts) — no MCP or toolkit page, route, picker or request. The Inference tab and an agent's Tools tab say "coming soon".

tests/mcp/test_unavailable.py (svc-ai), tests/test_mcp_unavailable.py (svc-core) and src/util/mcp.test.ts (fe-core) pin all three off. svc-core's test also walks the route table, so a new MCP or toolkit write route that arrives ungated fails it. Before turning MCP back on: run stdio servers in an isolated sidecar, refuse http/sse URLs that resolve to private, loopback, link-local or reserved addresses (as svc-core's feed fetcher does), and keep connection credentials in the secrets vault (roadmap Phase 4).

Knowledge Source Credentials — Readers Get the Reader's View

A database source's source_config holds its connection string, password included, and an API source's its auth header's value. Until October 2026 every listing returned the whole config to anyone who could read the workspace (GET /app/knowledge sent raw rows, as did a repository's member list and the generation proposals), and the Sources page printed a database's connection string on its card.

Now a reader is served app/util/knowledge_config.reader_config: per source type, the keys a reader may see (a website's config whole, since it holds no secrets and is in the edit history; a graph's counts; nothing of a database's but where it is), with every address served as scheme://host[:port]/path — no userinfo, query or fragment, and a connection string in any other form withheld whole. Schema.Knowledge.Read applies it on validation, so every schema-built response is safe by default. Only GET /app/knowledge/{id} serves the whole config, and only to a caller who may change the source here (can_change), because the edit form reads it there. The form cannot show a stored secret back, so an edit that leaves an API's auth value blank keeps the stored one (kept_secrets) — an edit used to drop it. tests/test_knowledge_config.py pins it.

The credentials are still plaintext JSON at rest; the secrets vault (roadmap Phase 4) is where they belong.

Input Validation & Sanitization

Request Validation

from pydantic import BaseModel, validator
from fastapi import HTTPException

class CreateProjectRequest(BaseModel):
    name: str
    description: Optional[str] = None

    @validator('name')
    def name_must_be_valid(cls, v):
        if not v or len(v.strip()) < 3:
            raise ValueError('Project name must be at least 3 characters')
        if len(v) > 100:
            raise ValueError('Project name must be less than 100 characters')
        return v.strip()

    @validator('description')
    def description_must_be_valid(cls, v):
        if v and len(v) > 1000:
            raise ValueError('Description must be less than 1000 characters')
        return v

SQL Injection Prevention

  • Parameterized queries only

  • ORM usage (SQLAlchemy)

  • Input sanitization

  • Prepared statements

XSS Protection

  • HTML escaping in responses

  • Content Security Policy (CSP)

  • Input sanitization

  • Safe HTML rendering

Rate Limiting

Implementation

from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.middleware import SlowAPIMiddleware

limiter = Limiter(key_func=get_remote_address)

app.state.limiter = limiter
app.add_exception_handler(RateLimited, _rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)

Rate Limits

  • Authentication endpoints: 5 requests/minute per IP

  • API endpoints: 100 requests/minute per user

  • File uploads: 10 uploads/hour per user

  • Search endpoints: 30 requests/minute per user

CORS Configuration

Security Headers

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://chainr.com", "https://app.chainr.com"],
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
    max_age=86400,  # 24 hours
)

CORS Policy

  • Explicit origin allowlist

  • Credential support for authenticated requests

  • Preflight request caching

  • Secure header handling

Data Encryption

In Transit

  • Browser → Cloudflare: TLS, ending at the Cloudflare edge, with Cloudflare Access in front of every hostname.

  • Cloudflare → host: an outbound-only Cloudflare Tunnel, encrypted between Cloudflare and cloudflared on the host. The host accepts no inbound connections: no published ports, no inbound security-group rules (see Cloudflare Tunnel).

  • Inside the host: plain HTTP between containers on private Docker networks, with internal service JWTs proving each hop's caller (see auth-flow.md).

Caching

svc-bff answers every response it does not otherwise label with Cache-Control: private, no-store (modules/svc-bff/app/cache_control.py). Cloudflare caches by URL extension — *.pdf included, which document downloads end in — and keys on the URL alone, so a cached copy would be served to the next requester without the session check. A route that states its own policy keeps it.

At Rest

  • Database encryption

  • File storage encryption

  • Sensitive data masking

  • Key management

Security Headers

Response Headers

X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000; includeSubDomains
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'
X-Permitted-Cross-Domain-Policies: none
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: geolocation=(), microphone=(), camera=()

File Upload Security

Upload Validation

  • File type verification (magic bytes)

  • File size limits

  • Filename sanitization

  • Virus scanning (future)

  • Content analysis

Secure Storage

  • Random filename generation

  • Access control on storage

  • CDN integration with signed URLs

  • Automatic cleanup of temp files

Error Handling

Secure Error Responses

@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    # Don't leak internal details
    if exc.status_code >= 500:
        return JSONResponse(
            status_code=500,
            content={"detail": "Internal server error"}
        )
    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": exc.detail}
    )

Logging Security

  • Sensitive data filtering in logs

  • Error tracking without PII

  • Security event logging

  • Audit trail maintenance

API Versioning

Version Strategy

  • URL path versioning: /api/v1/projects

  • Header-based versioning: Accept: application/vnd.chainr.v1+json

  • Backward compatibility maintenance

  • Deprecation notices

Monitoring & Alerting

Security Monitoring

  • Failed authentication attempts

  • Rate limit violations

  • Suspicious request patterns

  • API abuse detection

Automated Responses

  • IP blocking for brute force

  • Account lockout

  • Alert notifications

  • Incident response triggers

Penetration Testing

Regular Testing

  • Automated security scans

  • Manual penetration testing

  • Dependency vulnerability checks

  • Configuration reviews

Security Checklist

  • [ ] Input validation on all endpoints

  • [ ] Authentication required for sensitive operations

  • [ ] Authorization checks implemented

  • [ ] Rate limiting configured

  • [ ] HTTPS enforced

  • [ ] Security headers present

  • [ ] CORS properly configured

  • [ ] Error messages don't leak information

  • [ ] File uploads validated

  • [ ] API keys secured

  • [ ] Logs sanitized