Important
AI Assist Note (Knowledge Heritage): This document is part of the "Sovereign Reality" documentation.
- @docs ARCHITECTURE:Documentation
- Failure Path: Information drift, legacy terminology, or documentation mismatch.
- Telemetry Link: Search
[SECURITY]in audit logs.
Core technical resource for the Tadpole OS Sovereign infrastructure.
Traceability via parity_guard.py.
This document reflects the security controls currently implemented in the Rust engine and frontend runtime.
The engine requires an access token outside tests. Configure one of:
NEURAL_TOKEN=your-secret-token
NEURAL_ENGINE_ACCESS_TOKEN=your-secret-tokenProtected REST requests use:
Authorization: Bearer <token>The auth middleware is implemented in server-rs/src/middleware/auth.rs and uses constant-time token comparison via the subtle crate.
During active token rotation runbooks, the engine supports a phased token validation window:
NEURAL_TOKEN: Matches the primary system token (Operatorscope whenNEURAL_TOKEN_ADMINis configured; backward-compatibleAdminscope in single-token local dev).NEURAL_TOKEN_ADMIN: Optional dedicatedAdmin-scope token required for destructive host/deploy/template/script/provider/MCP/governance mutation routes (/v1/engine/deploy,/v1/engine/pre-pr,/v1/engine/kill,/v1/engine/shutdown,POST /v1/engine/templates/install,DELETE /v1/engine/templates/{id},PUT/DELETE/v1/skills/{scripts,workflows,hooks}/*,POST /v1/skills/register,POST /v1/skills/promote,POST /v1/skills/proposals/{id}/resolve,POST /v1/skills/mcp-tools/{name}/execute,POST /v1/mcp/message,POST /v1/api/pull, mutating/v1/model-manager/*includingproviders/{id}/test, mutating/v1/oversight/security/*,PUT /v1/oversight/settings, mutating/v1/governance/blueprints*, mutating/v1/continuity/*,POST /v1/agents/{id}/skills/{skill_id}/approve) when set.NEURAL_TOKEN_READONLY: OptionalReadOnly-scope token restricted strictly to safeGET/HEAD/OPTIONSobservability endpoints without WebSocket upgrades or long-lived MCP SSE streams (/v1/mcp/sse).NEURAL_TOKEN_NEW: Accepts the newly rotated token to allow phased rolling upgrades.NEURAL_TOKEN_OLD: Accepts the deprecated token within a strictly bounded window.NEURAL_TOKEN_ROTATED_AT: Unix epoch timestamp in seconds (u64) marking the exact inception of key rotation.NEURAL_TOKEN_GRACE_SECS: Number of seconds the old token remains acceptable (default: 300).- Fail-Closed Policy: If
NEURAL_TOKEN_ROTATED_ATorNEURAL_TOKEN_GRACE_SECSis unset, invalid, or the grace period has elapsed,NEURAL_TOKEN_OLDis rejected immediately (fail-closed) to prevent unbounded credential lifespan. Bearer scheme parsing conforms to RFC 7235 case-insensitivity (Bearer/bearer/BEARER). - Hardened Input & Execution Controls:
server-rs/src/utils/security.rsenforces quote-aware command tokenization (unconditionally blocking chaining/redirection metacharacters|,>,<,;,&,$(,`,${, unquoted\/^escape obfuscation, and quoted/escaped interpreter flags acrosspython/node/npmincluding short aliasesc/rm/r/un/uninstall/cargo/git/find, plus.env*/.ssh//proc//sys/.pem/.key/absolute Windows drives), validates paths fail-closed viasymlink_metadata+canonicalize, and exports the unifiedis_network_capable_mcp_toolPrivacy Shield classifier shared acrossserver-rs/src/agent/mcp/transport.rsandserver-rs/src/routes/mcp.rs;server-rs/src/agent/runner/tools/mod.rsroutes livehandle_execute_shelldirectly throughvalidate_shell_commandand never auto-approvesexecute_shellviaauto_approve_safe_skills;server-rs/src/agent/mcp/mod.rsvalidates both MCP server binaries and arguments;server-rs/src/routes/model_manager.rsblocks transmitting stored providerapi_keyvalues to modifiedbase_urlendpoints, falls back tostored_provider.base_urlwhenbase_urlis omitted for stored keys, enforcesprivacy_modevia parsed-URLis_secure_local, and restricts clusterpull_modelAdmin credential forwarding strictly to loopback peers or hosts explicitly allowlisted inSWARM_TRUSTED_PEERS(blocking unverified mDNS/LAN/external peers fail-closed);server-rs/src/routes/templates/principal.rsandserver-rs/src/routes/oversight/principal.rsenforce server-stampedAdminidentity without unauthenticated header fallbacks;server-rs/src/routes/skills.rsvalidatesPath(name)against traversal/YAML newline injection, builds typedWorkflowDefinition/HookDefinitionpayloads on promotion, and usesAND status = 'pending'OCC on proposal resolution;execution/security_scan.pyenforces zerosubprocess.{call,run,Popen,check_output,check_call}(..., shell=True)across Python scripts;src/services/base_api_service.tsdelegates directly to the consolidatedsrc/api/service/base-api-service.tsclient (enforcingis_allowed_origin,scrub_secrets, and 10MB caps across all services); andsrc/components/onboarding/FirstRun_Wizard.tsxprobes public/v1/engine/healthwithskip_auth: trueand pre-verifies tokens against/v1/agentsbefore committing to RAM-only state (INV-SEC-002).
Browser WebSocket upgrades may pass auth through:
Sec-WebSocket-Protocol: bearer.<token>Sensitive bearer credentials in Sec-WebSocket-Protocol headers are systematically redacted from logs, emitting only safe protocol classifications.
Unauthenticated public routes are strictly limited to:
GET /health(root engine health ping)GET /v1/engine/health(API v1 engine health ping)
All WebSocket connections (GET /v1/engine/ws, GET /v1/engine/live-voice) are protected and require token authentication via the Sec-WebSocket-Protocol: bearer.<token> subprotocol header. Route protection is enforced in server-rs/src/router.rs.
-
Zeroized In-Memory Key Material & File Permissions (
server-rs/src/security/audit.rs):- Staged Ed25519 audit signing key material and hex-decoded private key buffers implement
ZeroizeandSecrecy. Memory buffers are wiped automatically uponDrop, preventing cold-boot and process memory dump key extraction. - Private key files are written strictly with POSIX
0o600permissions (-rw-------), and runtime process environment modification viastd::env::set_varis prohibited.
- Staged Ed25519 audit signing key material and hex-decoded private key buffers implement
-
Deterministic Credential Preservation (
server-rs/src/agent/persistence.rs):- Agent provider credentials utilize SQL
COALESCE(excluded.api_key, agents.api_key)with explicit optional string binding, preventing destructive key nullification during periodic 30-second persistence flushes.
- Agent provider credentials utilize SQL
-
Atomic Authorization Cache Invariants (
server-rs/src/security/permissions.rs):- Permission policy reloading enforces retain-and-upsert semantics instead of clear-then-fetch, eliminating the authorization race window where incoming requests could observe an empty permission cache.
-
Fail-Closed Sovereign Security Channels (
server-rs/src/state/kernel.rs):- Security inspection actions fail closed (
PiiCheck => Ok(false)), and sovereign audit channel receivers are bounded with a strict 5.0-secondtokio::time::timeoutto prevent channel exhaustion deadlocks.
- Security inspection actions fail closed (
-
Server-Verified Operator Trust Boundaries (
server-rs/src/routes/oversight/principal.rs):-
OversightPrincipalis extracted exclusively from server-verified request extensions (OperatorIdentity/AuthenticatedOperator), preventing elevation of privilege or spoofed operator IDs from unauthenticated client headers or bodies.
-
-
A2E-01 Financial Ledger Risk Containment (
server-rs/src/routes/a2a.rs):-
24-Hour Rolling Spend Limits: Tracked in
agent_economics_metatable (default $10.00 cap / 10,000,000 micros) with automatic 24-hour resets. -
Lock-Aware Spend Projection: Before issuing a Two-Phase Commit (2PC) lock, the router calculates Total Projected Spend:
$$\text{Projected} = \text{Spent Today} + \sum \text{Pending Prepared Locks} + \text{New Amount}$$ If projected spend exceeds the daily limit, the transaction is rejected (400 Bad Request). -
Zero-Drift Micro-USDC Integer Arithmetic: Integer amounts (
u64micro-USDC: $1.00 = 1,000,000 micros) eliminate IEEE-754 floating-point rounding errors in cryptographic audit chains.
-
24-Hour Rolling Spend Limits: Tracked in
-
Asynchronous SSRF & Transport Isolation (
server-rs/src/routes/templates/security.rs):- Swarm template remote catalog downloads enforce strict scheme whitelisting (
http/https), DNS resolution verification, and rejection of loopback and RFC 1918/RFC 3927 private IP ranges (127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16, link-local169.254.0.0/16, IPv6 loopback::1), mitigating Server-Side Request Forgery (SSRF) during template catalog synchronization.
- Swarm template remote catalog downloads enforce strict scheme whitelisting (
-
Cryptographic Merkle Hash-Chain Tamper Detection (
server-rs/src/routes/missions/merkle.rs):- Mission flight recorder operations and historical logs are anchored to a cryptographic Merkle hash tree and content-addressable storage (CAS). Any discrepancy between computed state root and recorded transaction hashes triggers an immediate integrity alarm and blocks mission state promotion.
-
Fail-Closed Safe Mode & Untrusted Data Fencing (
server-rs/src/agent/runner/synthesis/mod.rs):- Prompt assembly (
server-rs/src/agent/runner/synthesis/prompt.rs) fences untrusted user inputs, dynamic tool definitions (server-rs/src/agent/runner/synthesis/tools.rs), and dynamic repository maps (server-rs/src/agent/runner/synthesis/repo_map.rs) within strict XML/delimiter boundaries. Model-invoking context collapses to fail-closed minimal prompts whenever budget thresholds or safety violations are detected (server-rs/src/agent/runner/synthesis/budget.rs).
- Prompt assembly (
The router applies these controls:
- boot readiness gate
- auth brute-force limiter
- security headers
- request ID injection
- rate-limit headers
- tracing spans
- deprecation middleware
- request timeout
- response compression
- CORS
Security headers are injected by server-rs/src/middleware/security_headers.rs:
- Content-Security-Policy
- Strict-Transport-Security
- X-Content-Type-Options
- X-Frame-Options
- Referrer-Policy
server-rs/src/middleware/cors.rs enforces an allow-list from ALLOWED_ORIGINS.
Behavior:
ALLOWED_ORIGINS=*enables wildcard troubleshooting mode and disables credentials.- A comma-separated list enables those exact origins with credentials.
- An empty value falls back to local development origins:
localhost/127.0.0.1on ports5173and3000, plustauri://localhost. - Private Network Access (PNA): Both
cors.rsandsecurity_headers.rsinjectAccess-Control-Allow-Private-Network: trueto prevent browser pre-flight blocks when web origins communicate with local development daemon loopback addresses (127.0.0.1/localhost).
Data Loss Prevention is enforced symmetrically across both the Rust backend and the frontend runtime:
-
Deterministic Regex Interceptor: Before any user prompt or command string is processed, routed to an agent, or sent to a local/cloud model, it passes through
scan_and_redact_secrets(). -
Target Patterns Scrubbed:
- OpenAI API keys:
sk-[a-zA-Z0-9_-]{20,}$\to$ [REDACTED_AI_KEY] - Anthropic API keys:
sk-ant-[a-zA-Z0-9_-]{20,}$\to$ [REDACTED_AI_KEY] - Google Gemini / Cloud keys:
AIzaSy[a-zA-Z0-9_-]{33}$\to$ [REDACTED_AI_KEY] - GitHub personal access tokens:
gh[pousr]_[a-zA-Z0-9]{36,}$\to$ [REDACTED_GITHUB_TOKEN] - Bearer tokens:
Bearer\s+[A-Za-z0-9\-_.~+/]+=*$\to$ Bearer [REDACTED_BEARER_TOKEN] - RSA / EC Private Keys:
-----BEGIN [A-Z ]*PRIVATE KEY-----$\to$ [REDACTED_PRIVATE_KEY]
- OpenAI API keys:
-
DOM Context DLP: Scraped active DOM state summarized by the Browser Sentinel (
summarize_active_dom()) is sanitized through the same DLP shield before being presented to the in-browser neural specialist, preventing inadvertent token exfiltration from rendered forms or debug panels.
Secret redaction is centralized through server-rs/src/secret_redactor.rs and used by AppState broadcast helpers before log/event publication.
Sensitive environment keys include:
NEURAL_TOKEN- cloud provider API keys
- other provider and credential-style values recognized by the redactor
Logs and telemetry should never intentionally include raw token values.
server-rs/src/security/scanner.rs implements command/script risk detection. It checks:
- known loaded secrets
- common API key formats
- raw secret export patterns
- command concatenation such as
;,&&, and|| - pipes and redirection
- command substitution
- optional aggressive checks when
AGGRESSIVE_SECURITY=true
The scanner is intentionally conservative and can flag valid complex shell commands. Risky results should be treated as requiring review rather than automatically safe execution.
For legacy and external execution tools, execution/tadpole_mcp_server.py enforces additional sandboxing boundaries to mitigate Remote Code Execution (RCE):
- Argument-Split Spawning: Spawns processes using
asyncio.create_subprocess_execandshlex.split, completely avoiding shell interpretation (shell=Falseequivalent). - Resource Boundaries: Implements Unix limits via
setrlimiton CPU runtime (30s maximum execution time) and virtual memory address space (256MB bounds), preventing resource exhaustion. - Input Schema Enforcements: Directs all inputs through strict type-safe schema checks before command assembly.
Security state is owned by SecurityHub in server-rs/src/state/hubs/sec.rs and assembled through AppState.
The security hub includes:
- Merkle audit trail
- budget guard
- shell scanner
- secret redactor
- system monitor
- permission policy
- deploy token
Oversight/security API routes are exposed under /v1/oversight/security/*.
PRIVACY_MODE=true steers runtime behavior toward local-only provider use. The privacy guard is started from startup::spawn_background_tasks.
Local insecure model-provider HTTP can be allowed with:
TADPOLE_ALLOW_LOCAL_HTTP=trueBefore deploying beyond local development:
- Set a strong
NEURAL_TOKENorNEURAL_ENGINE_ACCESS_TOKEN. - Set
ALLOWED_ORIGINSexplicitly for deployed or shared environments. - Validate that
.envis excluded from source control. - Run frontend and Rust test suites.
- Confirm protected endpoints reject missing and invalid bearer tokens.
- Confirm the dashboard stores and sends the same token configured for the engine.
- Review feature gates before enabling
vector-memoryorneural-audio.
| Area | Expected behavior | Suggested check |
|---|---|---|
| Public health | GET /v1/engine/health succeeds without auth |
call endpoint without Authorization |
| Protected API | /v1/agents rejects missing auth |
call endpoint without token and expect 401 |
| Invalid token | protected routes reject wrong bearer token | call with Authorization: Bearer wrong and expect 401 |
| Valid token | protected routes accept configured token | call with .env token and expect non-401 |
| WebSocket token | protected WS flows can use bearer.<token> subprotocol when needed |
verify browser upgrade path when route is protected |
| CORS allow-list | configured origins are allowed | set ALLOWED_ORIGINS and verify preflight |
| CORS wildcard | ALLOWED_ORIGINS=* disables credentials |
verify wildcard response has no credential support |
| Vector memory disabled | memory routes return 501 without feature |
run engine without vector-memory and call memory route |
| Vector memory enabled | memory routes become available | run engine with --features vector-memory |
The platform enforces zero-trust controls over multi-turn agent reasoning and tool execution:
-
Native Role Encapsulation (
ChatMessage::Tool):- Tool observations and execution results are dispatched strictly as native
toolrole messages, never concatenated into user or system prompt strings. - This architectural isolation neutralizes indirect prompt injection attacks where retrieved web content or file data attempts to mimic system directives or instructions.
- Tool observations and execution results are dispatched strictly as native
-
Pre-Flight Adversarial Jailbreak Detection:
- Turn-1 instructions are screened for known jailbreak tokens (
<|im_start|>,<|im_end|>,"ignore all previous instructions","you are now dan"). - Flagged prompts have their snippets redacted via
redact_secrets()and are immediately quarantined to the human-in-the-loop oversight queue with statusflagged_injection.
- Turn-1 instructions are screened for known jailbreak tokens (
-
Deterministic Artifact Verification:
- Prevents agent deception and premature task completion by verifying the physical presence of all declared files on disk prior to marking a mission as
Completed. - Missing artifacts raise
ToolExecutionError::Validation, blocking transition to terminal success state.
- Prevents agent deception and premature task completion by verifying the physical presence of all declared files on disk prior to marking a mission as
-
Financial Cap Fallback & Loop Termination:
- Pre-turn budget gate checks expenditure before each LLM invocation, falling back to a hard
$10.00safety limit (DEFAULT_BUDGET_LIMIT_USD). - Tool recursion tracker halts identical consecutive tool executions at 5 attempts via
RunnerError::RecursionBlocked.
- Pre-turn budget gate checks expenditure before each LLM invocation, falling back to a hard