SECURITY_ARCHITECTURE.md

April 28, 2026 Β· View on GitHub

Hack23 Logo

πŸ”’ European Parliament MCP Server β€” Security Architecture

Implemented Security Controls, Threat Model, and Compliance Mapping
Defense-in-depth security design for parliamentary data access

Owner Version Effective Date Review Cycle OpenSSF Best Practices

πŸ“‹ Document Owner: Hack23 | πŸ“„ Version: 1.2 | πŸ“… Last Updated: 2026-04-21 (UTC) πŸ”„ Review Cycle: Quarterly | ⏰ Next Review: 2026-07-21 🏷️ Classification: Public (Open Source MCP Server) βœ… ISMS Compliance: ISO 27001 (A.5.1, A.8.1, A.14.2), NIST CSF 2.0 (ID.AM, PR.DS), CIS Controls v8.1 (2.1, 16.1)


πŸ“‘ Table of Contents

  1. Security Documentation Map
  2. Executive Summary
  3. 4-Layer Security Architecture
  4. Security Controls Inventory
  5. Threat Mitigation Mapping (STRIDE)
  6. Authentication and Authorization
  7. Session and Action Tracking
  8. Data Integrity and Auditing
  9. Data Protection and GDPR
  10. Network Security and Perimeter Protection
  11. VPC Endpoints and Private Access
  12. High Availability and Resilience
  13. Threat Detection and Investigation
  14. Vulnerability Management
  15. Configuration and Compliance Management
  16. Security Monitoring and Analytics
  17. Automated Security Operations
  18. Application Security Controls
  19. Defense-in-Depth Strategy
  20. Security Testing Requirements
  21. Compliance Framework Mapping

πŸ—ΊοΈ Security Documentation Map

DocumentCurrentFutureDescription
ArchitectureARCHITECTURE.mdFUTURE_ARCHITECTURE.mdC4 model, containers, components, ADRs
Security ArchitectureSECURITY_ARCHITECTURE.mdFUTURE_SECURITY_ARCHITECTURE.mdSecurity controls, threat model
Data ModelDATA_MODEL.mdFUTURE_DATA_MODEL.mdEntity relationships, branded types
FlowchartFLOWCHART.mdFUTURE_FLOWCHART.mdBusiness process flows
State DiagramSTATEDIAGRAM.mdFUTURE_STATEDIAGRAM.mdSystem state transitions
Mind MapMINDMAP.mdFUTURE_MINDMAP.mdSystem concepts and relationships
SWOT AnalysisSWOT.mdFUTURE_SWOT.mdStrategic positioning
Threat ModelTHREAT_MODEL.mdFUTURE_THREAT_MODEL.mdSTRIDE, MITRE ATT&CK, attack trees
CRA AssessmentCRA-ASSESSMENT.mdβ€”EU Cyber Resilience Act conformity
E2E Test PlanE2ETestPlan.mdβ€”End-to-end test strategy and coverage matrix
Unit Test Plandocs/UnitTestPlan.mdβ€”Unit test plan and coverage targets

🎯 Executive Summary

The EP MCP Server implements a 4-layer defense-in-depth security architecture aligned with OWASP best practices, ISO 27001, NIST CSF 2.0, and GDPR requirements. Since the server operates as an MCP stdio process (not a network-exposed server), the primary security concerns are:

  1. Input validation β€” prevent malformed or malicious MCP tool arguments
  2. API abuse prevention β€” protect EP Open Data Portal from overuse
  3. Data privacy β€” GDPR-compliant handling of MEP personal data
  4. Audit trail β€” full traceability of all data access

The server does not handle authentication tokens, passwords, or payment data, significantly reducing the attack surface.


πŸ›‘οΈ 4-Layer Security Architecture

flowchart TD
    MCP_IN["MCP Tool Invocation\n(args: unknown)"]

    subgraph L1["Layer 1: Input Validation"]
        ZOD["Zod Schema Validation\nStrict type checking, format enforcement"]
        ZE["ZodError β†’ MCP error response"]
    end

    subgraph L2["Layer 2: Rate Limiting"]
        RL["Token Bucket Rate Limiter\n100 tokens/minute"]
        RLE["Rate limit exceeded β†’ 429 response"]
    end

    subgraph L3["Layer 3: Audit Logging"]
        AL["Audit Logger\nTool name, params (PII-stripped), timestamp, user context"]
    end

    subgraph L4["Layer 4: GDPR Compliance"]
        GDPR["Data Minimization\nPurpose Limitation\nStorage Limitation"]
    end

    EP_API["EP Open Data Portal API v2\n(HTTPS/TLS)"]
    RESULT["Tool Result β†’ MCP Client"]

    MCP_IN --> ZOD
    ZOD -->|"invalid"| ZE
    ZOD -->|"valid"| RL
    RL -->|"exceeded"| RLE
    RL -->|"token available"| AL
    AL --> GDPR
    GDPR --> EP_API
    EP_API --> RESULT

πŸ” Security Controls Inventory

Control IDControl NameTypeImplementationStatus
SC-001Input ValidationPreventiveZod schema per tool (62 schemas) with .refine() cross-field constraints, date range validation, and format-specific ID validationβœ… Implemented
SC-002Rate LimitingPreventiveToken bucket, 100 req/minβœ… Implemented
SC-003Audit LoggingDetectiveAuditLogger singleton, all invocationsβœ… Implemented
SC-004GDPR Data MinimizationPreventiveField selection, no over-fetchingβœ… Implemented
SC-005TLS in TransitPreventiveHTTPS to EP API, Node TLS defaultsβœ… Implemented
SC-006Dependency ScanningDetectiveDependabot, npm auditβœ… Implemented
SC-007Static AnalysisPreventiveESLint, TypeScript strict modeβœ… Implemented
SC-008Secret DetectionPreventiveNo secrets in codebase; env vars onlyβœ… Implemented
SC-009Error SanitizationPreventiveInternal errors not leaked to MCP clientsβœ… Implemented
SC-010Health MonitoringDetectiveHealthService singletonβœ… Implemented
SC-011Metrics CollectionDetectiveMetricsService, rate/error trackingβœ… Implemented
SC-012Branded TypesPreventiveZod branded types for EP identifiersβœ… Implemented
SC-013Data Quality ControlsPreventiveOSINT outputs standardize confidence level and quality warnings; data availability status is included where implementedβœ… Implemented

βš”οΈ Threat Mitigation Mapping (STRIDE)

Threat CategorySpecific ThreatLikelihoodImpactMitigation
SpoofingFake MCP client identityLowLowstdio transport β€” client is the spawning process
TamperingMalicious tool argumentsMediumMediumSC-001: Zod validation rejects malformed input
RepudiationDeny data access occurredMediumMediumSC-003: Immutable audit log with timestamps
Information DisclosureMEP PII over-exposureMediumHighSC-004: Data minimization, GDPR controls
Information DisclosureInternal error details leakedLowMediumSC-009: Error sanitization
Denial of ServiceEP API floodingMediumHighSC-002: Rate limiter blocks bursts
Denial of ServiceMemory exhaustion via cacheLowMediumLRU eviction (max 500 entries)
Elevation of PrivilegeUnauthorized tool accessLowLowNo auth layer needed β€” local stdio process
Elevation of PrivilegePrototype pollution via inputLowMediumSC-001: Zod validation with strict mode
Supply ChainMalicious npm packageMediumHighSC-006: Dependabot, npm audit, lockfile
MCP ProtocolPrompt injection, tool abuse (M-1…M-7)MediumHighSee THREAT_MODEL.md Β§MCP Threats
LLM IntegrationOWASP LLM Top 10 risks (L-01…L-10)MediumHighSee THREAT_MODEL.md Β§OWASP LLM

πŸ”‘ Authentication and Authorization

Current Model (v1.1)

The EP MCP Server operates as a local stdio process spawned by the MCP client (e.g., Claude Desktop). The security model relies on OS-level process isolation:

  • No network authentication β€” the server is not network-exposed
  • No user credentials β€” the server does not handle user tokens
  • Process isolation β€” only the spawning MCP client can communicate via stdio
  • EP API access β€” public open data, no authentication required by EP

Trust Boundaries

flowchart LR
    subgraph TrustHigh["High Trust Zone"]
        OS["Operating System"]
        User["Local User Account"]
    end

    subgraph TrustMedium["Medium Trust Zone"]
        MCP["MCP Client Process\n(Claude Desktop / Cursor)"]
        Server["EP MCP Server Process"]
    end

    subgraph TrustLow["Low Trust Zone"]
        Input["Tool Arguments\n(from AI-generated content)"]
    end

    subgraph External["Untrusted External"]
        EPAPI["EP Open Data Portal\n(public internet)"]
    end

    OS --> MCP
    MCP --> Server
    Server --> Input
    Input -->|"Zod validation"| Server
    Server -->|"HTTPS"| EPAPI

Key principle: Tool arguments are treated as untrusted input regardless of their origin, since AI models may generate unexpected parameter values.


πŸ“Š Session and Action Tracking

All user interactions with the MCP server are tracked through the integrated audit and metrics systems:

Session Tracking Model

flowchart LR
    subgraph SessionContext["Session Context"]
        STDIO["stdio Connection\n(1 session per process)"]
        TC["Tool Call Counter"]
        TS["Session Start Time"]
    end

    subgraph ActionTracking["Action Tracking"]
        AL["AuditLogger\n(every tool invocation)"]
        MS["MetricsService\n(aggregated counters)"]
        HS["HealthService\n(process health)"]
    end

    STDIO --> AL
    STDIO --> MS
    AL --> TC
    MS --> TS
    HS --> TC

Tracked Actions

Action TypeTracked FieldsStoragePurpose
Tool invocationTool name, sanitized params, timestamp, durationstderr audit logFull traceability
API requestURL, status, duration, cache hit/missMetricsServicePerformance monitoring
Rate limit eventToken count, refill status, rejectionstderr audit logAbuse detection
Error occurrenceError type (no stack trace), tool contextstderr audit logIncident response
Cache operationKey, hit/miss, evictionMetricsServiceEfficiency tracking

Action Tracking Implementation

  • No persistent session storage β€” session state is in-memory only (process-scoped)
  • PII stripping β€” all logged parameters have personal data fields removed before logging
  • Structured logging β€” JSON format on stderr for machine-parseable audit trail
  • Per-tool metrics β€” invocation count, error count, average duration per tool

πŸ“œ Data Integrity and Auditing

Data Integrity Controls

ControlImplementationVerification
Source integrityAll data sourced from official EP API over HTTPS/TLSTLS certificate validation
Transport integrityHTTPS with TLS 1.2+ for all API callsNode.js default TLS verification
Cache integrityIn-memory LRU cache (no persistent storage) β€” no disk tampering riskProcess isolation
Cache key integrityDeterministic cache key generation via sorted parameter keysPrevents cache misses from property insertion order
Schema validationZod schemas validate all API responses before processingTypeScript strict mode + runtime validation
Data quality integrityOSINT outputs include DataAvailability and dataQualityWarnings (SC-013)Consumers distinguish "zero" from "unavailable"
Audit immutabilityAudit logs written to stderr (append-only within process)No log modification API exposed
Package integritynpm lockfile with exact versions, SLSA Level 3 provenanceProvenance attestations, Sigstore signing

Audit Trail Architecture

flowchart TD
    ToolCall["Tool Invocation"] --> AuditLog["AuditLogger.logToolCall()"]
    AuditLog --> PIIStrip["PII Stripping\n(remove personal data fields)"]
    PIIStrip --> Format["JSON Structured Format"]
    Format --> Stderr["stderr Output\n(append-only)"]
    Stderr --> External["External Log Collection\n(host-managed)"]

Audit Log Fields

FieldTypeDescription
timestampISO 8601Event occurrence time
toolNamestringMCP tool identifier
parametersobjectSanitized input parameters (PII removed)
resultStatusenumsuccess, error, rate_limited
durationMsnumberExecution duration
errorTypestring?Error category (no stack traces)
cacheHitboolean?Whether result came from cache

πŸ›‘οΈ Data Protection and GDPR

Personal Data Inventory

Data CategoryEP API EndpointGDPR BasisRetention in CacheMinimization Applied
MEP Names/meps/{id}Public role (Art. 6.1.e)15 min TTLName, group only
MEP Contact/meps/{id}Legitimate interest15 min TTLOfficial EP address only
MEP Votes/votesPublic interest15 min TTLVote record, no commentary
MEP Attendance/plenary-sessionsPublic interest15 min TTLSession data only
MEP Declarations/meps/{id}/declarationsPublic role15 min TTLOfficial declarations only

GDPR Principles Implementation

PrincipleImplementation
LawfulnessProcessing public parliamentary records per Art. 6.1.e (public interest)
Purpose LimitationData used solely for parliamentary intelligence queries
Data MinimizationField selection queries β€” only request needed attributes
AccuracyData sourced directly from official EP API
Storage LimitationLRU cache with 15-min TTL; no persistent storage
Integrity and ConfidentialityHTTPS transport, no local file system writes
AccountabilityAudit logging of all data access requests

🌐 Network Security and Perimeter Protection

Outbound Connections

DestinationProtocolPortTLSPurpose
data.europarl.europa.euHTTPS443TLS 1.2+EP Open Data Portal API v2
EP Vocabulary endpointsHTTPS443TLS 1.2+AT4EU taxonomy lookups

Security Headers (Outbound Requests)

// Applied to all EP API requests
headers: {
  'Accept': 'application/json',
  'User-Agent': 'European-Parliament-MCP-Server/1.1',
  'Accept-Encoding': 'gzip, deflate, br'
}

No Inbound Network Exposure

  • Server operates exclusively via stdio (no listening sockets)
  • No HTTP server, no WebSocket server in current v1.1
  • No ports bound, no firewall rules required

πŸ“Š Audit and Monitoring

Audit Log Schema

interface AuditLogEntry {
  timestamp: string;        // ISO 8601
  toolName: string;         // e.g., "get_mep_details"
  parameters: Record<string, unknown>;  // PII-stripped
  resultStatus: 'success' | 'error' | 'rate_limited';
  durationMs: number;
  errorType?: string;       // Error category (no stack traces)
}

Metrics Collected

MetricTypePurpose
tool.invocations.totalCounterUsage tracking per tool
tool.invocations.errorsCounterError rate monitoring
cache.hitsCounterCache efficiency
cache.missesCounterCache efficiency
ratelimit.tokens.usedGaugeRate limit consumption
api.request.duration_msHistogramEP API latency
api.request.errorsCounterEP API error rates

Health Checks

The HealthService singleton monitors:

  • EP API reachability (periodic ping)
  • Cache memory utilization
  • Rate limiter token availability
  • Error rate thresholds

πŸ”Œ VPC Endpoints and Private Access

Current Architecture (stdio-based)

The EP MCP Server operates as a local process using stdio transport, which means:

  • No VPC deployment β€” the server runs on the local machine as a child process of the MCP client
  • No cloud networking β€” no VPC, subnets, or security groups required
  • Direct internet access β€” outbound HTTPS to EP API via the host's network stack
  • Process-level isolation β€” OS process boundaries provide access control

Network Access Pattern

flowchart LR
    subgraph LocalMachine["Local Machine"]
        MCPClient["MCP Client\n(Claude/Cursor)"]
        MCPServer["EP MCP Server\n(child process)"]
    end

    subgraph Internet["Public Internet"]
        EPAPI["EP Open Data Portal\n(data.europarl.europa.eu)"]
    end

    MCPClient -->|"stdio pipe"| MCPServer
    MCPServer -->|"HTTPS/TLS 1.2+"| EPAPI

Future Cloud Deployment Considerations

When deployed as a hosted service (v2.0+), VPC architecture will include:

  • Private subnets for MCP server instances
  • NAT Gateway for outbound EP API access
  • VPC endpoints for AWS services (CloudWatch, KMS)
  • Security groups restricting inbound to MCP protocol only

See FUTURE_SECURITY_ARCHITECTURE.md for planned VPC architecture.


πŸ—οΈ High Availability and Resilience

Current Resilience Model

AspectImplementationRecovery
Process crashMCP client auto-restarts server processInstant restart, cold cache
EP API unavailableGraceful error responses to MCP clientCached data served if available
Rate limit exceededToken bucket rejects requests with clear errorAuto-recovery after window reset
Memory exhaustionLRU cache eviction (max 500 entries)Automatic eviction of oldest entries
Network timeoutConfigurable timeout (default 30s) per requestRetry with exponential backoff

Fault Tolerance Architecture

flowchart TD
    subgraph Resilience["Resilience Controls"]
        RC["Rate Limiter\n(100 req/min)"]
        CA["LRU Cache\n(500 entries, 15-min TTL)"]
        TO["Request Timeout\n(30s default)"]
        EH["Error Handler\n(graceful degradation)"]
    end

    subgraph Recovery["Recovery Mechanisms"]
        AR["Auto-restart\n(MCP client managed)"]
        CE["Cache eviction\n(LRU policy)"]
        TR["Token refill\n(1-minute window)"]
    end

    RC --> TR
    CA --> CE
    TO --> EH
    EH --> AR

Data Durability

  • No persistent state β€” all state is in-memory (cache, metrics, rate limiter tokens)
  • Stateless design β€” server can be restarted at any time without data loss
  • Cache warm-up β€” first requests after restart may be slower (cold cache)
  • npm package integrity β€” SLSA Level 3 provenance ensures package authenticity

⚑ Threat Detection and Investigation

Detection Capabilities

Detection MethodImplementationThreats Detected
Rate limit monitoringToken bucket algorithm logs rejection eventsAPI abuse, DoS attempts
Error rate trackingMetricsService tracks per-tool error ratesInjection attempts, API anomalies
Input validation loggingZod validation failures logged with sanitized inputMalformed input, fuzzing attempts
Health check alertsHealthService monitors EP API reachabilityNetwork issues, EP API outages
Dependency scanningDependabot + npm audit in CI/CDSupply chain vulnerabilities
Static analysisCodeQL + ESLint in GitHub ActionsCode-level security issues

Investigation Workflow

flowchart TD
    Alert["Security Alert\n(error spike, validation failure)"] --> Triage["Triage\n(review audit logs)"]
    Triage --> Analyze["Analyze\n(correlate metrics + logs)"]
    Analyze --> Classify{"Classify"}
    Classify -->|"False Positive"| Document["Document & Close"]
    Classify -->|"True Positive"| Respond["Incident Response"]
    Respond --> Contain["Contain\n(rate limit, block input)"]
    Contain --> Remediate["Remediate\n(patch, update schema)"]
    Remediate --> Verify["Verify Fix"]
    Verify --> Document

πŸ” Vulnerability Management

Vulnerability Scanning Pipeline

ScannerScopeFrequencyIntegration
Dependabotnpm dependenciesContinuousGitHub automatic PRs
npm auditDirect + transitive depsEvery CI runBuild gate
CodeQLSource code (TypeScript)Every PR + scheduledGitHub code scanning
ESLint security rulesCode patternsEvery commitPre-commit + CI
License complianceDependency licensesEvery CI runtest:licenses script
SLSA provenancePackage supply chainEvery releaseSigstore attestation

Remediation SLAs

SeverityCVSS ScoreRemediation TimelineEscalation
Critical9.0–10.024 hoursImmediate patch release
High7.0–8.97 daysNext patch release
Medium4.0–6.930 daysNext minor release
Low0.1–3.990 daysScheduled maintenance

Dependency Update Strategy

  • Automated PRs via Dependabot for all dependency updates
  • Lockfile pinning β€” exact versions in package-lock.json
  • Minimal dependencies β€” only 4 runtime dependencies (SDK, LRU cache, undici, zod)
  • Provenance verification β€” SLSA Level 3 for published npm package

βš™οΈ Configuration and Compliance Management

Configuration Management

ConfigurationSourceValidationDefault
Rate limitEP_RATE_LIMIT env varNumeric > 0100 req/min
Cache sizeHardcodedN/A500 entries
Cache TTLEP_CACHE_TTL env varNumeric (ms)900,000 ms (15 min)
EP API base URLEP_API_URL env varURL formathttps://data.europarl.europa.eu/api/v2/
Request timeoutEP_REQUEST_TIMEOUT_MS env varNumeric (ms)10,000 ms

Infrastructure as Code

  • TypeScript strict mode β€” all configuration types are compile-time checked
  • Zod runtime validation β€” environment variables validated at startup
  • No secrets in code β€” all sensitive values via environment variables
  • Reproducible builds β€” npm ci with lockfile for deterministic installs

Compliance Drift Detection

CheckToolFrequencyAction on Drift
Dependency versionsDependabotContinuousAuto-PR
Code qualityESLint + TypeScriptEvery commitBuild failure
Security findingsCodeQLEvery PRPR blocked
License compliancelicense-complianceEvery CIBuild failure
Unused codeKnipEvery CIBuild warning
Package integritySLSA provenanceEvery releaseRelease blocked

πŸ“ˆ Security Monitoring and Analytics

Metrics Dashboard

Metric CategoryMetricsCollection Method
Tool usageInvocations per tool, error rate per toolMetricsService counters
API performanceRequest duration, response status codesMetricsService histograms
Rate limitingTokens used, rejections, peak usageToken bucket state
Cache efficiencyHit rate, miss rate, eviction countLRU cache stats
Error analysisError types, error frequency, error trendsAuditLogger + MetricsService

Security Alerting Thresholds

AlertThresholdAction
Error rate spike> 10% of requests in 5-min windowLog warning, investigate
Rate limit saturation> 90% token usageLog warning, potential abuse
EP API connectivity loss3 consecutive failuresHealth check degraded
Validation failure spike> 5 failures in 1 minutePotential injection attempt

Analytics for Threat Intelligence

  • Tool usage patterns β€” detect anomalous tool call sequences
  • Parameter analysis β€” identify suspicious parameter patterns (logged after PII stripping)
  • Error correlation β€” correlate error spikes with external events
  • Rate limit patterns β€” identify API abuse patterns

πŸ€– Automated Security Operations

CI/CD Security Automation

flowchart LR
    subgraph CI["GitHub Actions CI/CD"]
        Lint["ESLint\n+ TypeScript"]
        Test["Vitest\n(1130+ unit + 71 E2E tests)"]
        Scan["CodeQL\n+ npm audit"]
        License["License\nCompliance"]
        Build["TypeScript\nBuild"]
        Publish["npm Publish\n+ SLSA Provenance"]
    end

    Commit["Git Commit"] --> Lint --> Test --> Scan --> License --> Build --> Publish

Automated Security Controls

AutomationTriggerActionOutcome
Dependabot PRsNew vulnerabilityAuto-create update PRDependency patched
CodeQL scanningEvery PR/pushStatic analysisVulnerabilities flagged
npm auditEvery CI runDependency auditBuild gate enforced
License checkEvery CI runLicense validationNon-compliant deps blocked
KnipEvery CI runUnused code detectionDead code flagged
SLSA provenancenpm publishProvenance attestationSupply chain verified
Branch protectionPR mergeRequired reviews + checksQuality gate enforced

Self-Healing Capabilities

  • Automatic cache eviction β€” LRU policy prevents memory exhaustion
  • Rate limit recovery β€” token bucket auto-refills after window expiry
  • Graceful degradation β€” tools return structured errors when EP API is unavailable
  • Process restart β€” MCP client automatically restarts crashed server processes

πŸ›‘οΈ Application Security Controls

Input Validation Architecture

flowchart TD
    Input["Raw MCP Input\n(unknown type)"] --> ZodParse["Zod Schema.parse()"]
    ZodParse -->|"Valid"| TypeSafe["Type-Safe Parameters"]
    ZodParse -->|"Invalid"| ZodError["ZodError\n(structured rejection)"]
    TypeSafe --> BrandedTypes["Branded Type Enforcement\n(MEPId, ProcedureId, etc.)"]
    BrandedTypes --> Handler["Tool Handler\n(type-safe execution)"]
    ZodError --> ErrorResponse["MCP Error Response\n(no internal details)"]

Validation Controls per Layer

LayerControlImplementation
Input parsingZod schema validationEvery tool has a dedicated schema
Type enforcementBranded types via ZodMEPId, ProcedureId, SessionId prevent type confusion
Cross-field validation.refine() constraintsDate range ordering, mutual exclusivity, conditional requirements
String sanitizationMax length limits, pattern matchingZod .max(), .regex() constraints
Numeric boundsRange validation.min(), .max(), .int() constraints
Enum restrictionAllowed value sets.enum() for country codes, group names
Output encodingJSON serializationJSON.stringify() prevents injection in responses
Data qualityOSINT output validationdataQualityWarnings, confidenceLevel, DataAvailability fields (SC-013)

Error Handling Security

All tool errors are reported via the ToolError class which carries toolName, operation, isRetryable, and optional cause β€” ensuring structured error reporting without leaking internal implementation details. Success responses use buildToolResponse() for consistent JSON formatting.

Error TypeResponse to ClientLogged Internally
Zod validation errorStructured field errorsFull error details
EP API error (4xx)Generic "API error" messageStatus code, URL, response body
EP API error (5xx)Generic "service unavailable"Full error details
Network timeout"Request timeout"URL, timeout duration
Rate limit exceeded"Rate limit exceeded"Token state, request details
Unexpected error"Internal error"Full stack trace (internal only)

πŸ† Defense-in-Depth Strategy

Security Layer Architecture

flowchart TD
    subgraph Layer1["Layer 1: Process Isolation"]
        OS["OS Process Boundaries"]
        STDIO["stdio Transport\n(no network exposure)"]
    end

    subgraph Layer2["Layer 2: Input Validation"]
        ZOD["Zod Schema Validation\n(62 tool schemas)"]
        BT["Branded Types\n(type-safe identifiers)"]
    end

    subgraph Layer3["Layer 3: Rate Limiting & Caching"]
        RL["Token Bucket Rate Limiter"]
        LRU["LRU Cache\n(bounded memory)"]
    end

    subgraph Layer4["Layer 4: Transport Security"]
        TLS["HTTPS/TLS 1.2+\n(to EP API)"]
        CERT["Certificate Validation\n(Node.js defaults)"]
    end

    subgraph Layer5["Layer 5: Audit & Monitoring"]
        AUDIT["Audit Logger\n(PII-stripped)"]
        METRICS["MetricsService\n(performance + errors)"]
        HEALTH["HealthService\n(availability)"]
    end

    subgraph Layer6["Layer 6: Supply Chain Security"]
        SLSA["SLSA Level 3 Provenance"]
        DEPS["Minimal Dependencies (4)"]
        LOCK["Lockfile Pinning"]
        SCAN["Dependabot + CodeQL"]
    end

    Layer1 --> Layer2 --> Layer3 --> Layer4 --> Layer5 --> Layer6

Defense-in-Depth Summary

LayerControlsThreats Mitigated
Process Isolationstdio transport, no network listenerRemote access, network attacks
Input ValidationZod schemas, branded types, strict TypeScriptInjection, type confusion, malformed input
Rate LimitingToken bucket (100/min), cache bounds (500)DoS, API abuse, memory exhaustion
Transport SecurityHTTPS/TLS 1.2+, certificate validationMITM, data interception
Audit & MonitoringStructured logging, metrics, health checksRepudiation, undetected abuse
Supply ChainSLSA L3, Dependabot, lockfile, minimal depsDependency hijacking, package tampering

πŸ§ͺ Security Testing Requirements

Coverage Requirements

ComponentMinimum CoverageFocus Areas
Zod validators95%Edge cases, injection attempts
Rate limiter90%Boundary conditions, token exhaustion
Audit logger90%PII stripping, log format
EP API clients80%Error handling, timeout behavior
Tool handlers80%Happy path + error paths

Security Test Categories

  1. Input Validation Tests

    • Oversized strings (> 10,000 chars)
    • Special characters in identifiers
    • Prototype pollution attempts: {"__proto__": {...}}
    • Type confusion: passing objects where strings expected
    • Boundary values: negative IDs, zero values, MAX_SAFE_INTEGER
  2. Rate Limiting Tests

    • Burst requests (> 100 in 60s window)
    • Token recovery after window reset
    • Concurrent request handling
  3. Data Privacy Tests

    • Verify PII fields are stripped from audit logs
    • Verify data minimization (no extra fields returned)
    • Verify 15-min cache TTL enforcement
  4. Error Handling Tests

    • EP API 429 (rate limited) β€” graceful handling
    • EP API 500 β€” error message sanitization
    • Network timeout β€” no credential leakage
    • ZodError β€” structured error response

πŸ“‹ Compliance Framework Mapping

ControlStandardClauseImplementation
Information Security PoliciesISO 27001A.5.1SECURITY.md, SECURITY_ARCHITECTURE.md, THREAT_MODEL.md
Asset ManagementISO 27001A.8.162 tools + 9 resources inventoried
Access ControlISO 27001A.9.1stdio isolation, no network exposure
CryptographyISO 27001A.10.1TLS 1.2+ for all EP API calls
Secure DevelopmentISO 27001A.14.2TypeScript strict, Zod validation, ESLint
Vulnerability ManagementISO 27001A.12.6Dependabot, npm audit, CodeQL
Audit LoggingISO 27001A.12.4AuditLogger, all invocations logged
Change ManagementISO 27001A.12.1Git-based change tracking, PR reviews
Privacy by DesignGDPRArt. 25Data minimization, purpose limitation
Data ProtectionGDPRArt. 32TLS transport, no persistent PII storage
Identify: AssetsNIST CSF 2.0ID.AMFull tool and component inventory
Protect: Data SecurityNIST CSF 2.0PR.DSTLS, cache TTL, data minimization
Detect: AnomaliesNIST CSF 2.0DE.AEMetricsService, error rate monitoring
Respond: PlanningNIST CSF 2.0RS.RPIncident response via GitHub Security Advisories
Recover: PlanningNIST CSF 2.0RC.RPStateless design enables instant recovery
Software InventoryCIS Controls v8.12.1package.json with locked versions, SBOM
Secure ConfigurationCIS Controls v8.14.1TypeScript strict, no dangerous defaults
Audit Log ManagementCIS Controls v8.18.2AuditLogger singleton
Application SecurityCIS Controls v8.116.1Zod validation, branded types, CodeQL
Penetration TestingCIS Controls v8.118.1Security test categories in CI

See FUTURE_SECURITY_ARCHITECTURE.md for the planned security evolution including OAuth 2.0, RBAC, and zero-trust architecture.