Skip to content

Security: DDS-Solutions/Autonomous-Agentic-Tadpole

Security

docs/SECURITY.md

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.

AI Assist Note

Core technical resource for the Tadpole OS Sovereign infrastructure.

🔍 Debugging & Observability

Traceability via parity_guard.py.

Tadpole OS Security Policy

This document reflects the security controls currently implemented in the Rust engine and frontend runtime.

Authentication Boundary

The engine requires an access token outside tests. Configure one of:

NEURAL_TOKEN=your-secret-token
NEURAL_ENGINE_ACCESS_TOKEN=your-secret-token

Protected 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.

Token Rotation Grace Window

During active token rotation runbooks, the engine supports a phased token validation window:

  • NEURAL_TOKEN: Matches the primary system token (Operator scope when NEURAL_TOKEN_ADMIN is configured; backward-compatible Admin scope in single-token local dev).
  • NEURAL_TOKEN_ADMIN: Optional dedicated Admin-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/* including providers/{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: Optional ReadOnly-scope token restricted strictly to safe GET/HEAD/OPTIONS observability 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_AT or NEURAL_TOKEN_GRACE_SECS is unset, invalid, or the grace period has elapsed, NEURAL_TOKEN_OLD is 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.rs enforces quote-aware command tokenization (unconditionally blocking chaining/redirection metacharacters |, >, <, ;, &, $(, `, ${, unquoted \/^ escape obfuscation, and quoted/escaped interpreter flags across python/node/npm including short aliases c/rm/r/un/uninstall/cargo/git/find, plus .env*/.ssh//proc//sys/.pem/.key/absolute Windows drives), validates paths fail-closed via symlink_metadata + canonicalize, and exports the unified is_network_capable_mcp_tool Privacy Shield classifier shared across server-rs/src/agent/mcp/transport.rs and server-rs/src/routes/mcp.rs; server-rs/src/agent/runner/tools/mod.rs routes live handle_execute_shell directly through validate_shell_command and never auto-approves execute_shell via auto_approve_safe_skills; server-rs/src/agent/mcp/mod.rs validates both MCP server binaries and arguments; server-rs/src/routes/model_manager.rs blocks transmitting stored provider api_key values to modified base_url endpoints, falls back to stored_provider.base_url when base_url is omitted for stored keys, enforces privacy_mode via parsed-URL is_secure_local, and restricts cluster pull_model Admin credential forwarding strictly to loopback peers or hosts explicitly allowlisted in SWARM_TRUSTED_PEERS (blocking unverified mDNS/LAN/external peers fail-closed); server-rs/src/routes/templates/principal.rs and server-rs/src/routes/oversight/principal.rs enforce server-stamped Admin identity without unauthenticated header fallbacks; server-rs/src/routes/skills.rs validates Path(name) against traversal/YAML newline injection, builds typed WorkflowDefinition/HookDefinition payloads on promotion, and uses AND status = 'pending' OCC on proposal resolution; execution/security_scan.py enforces zero subprocess.{call,run,Popen,check_output,check_call}(..., shell=True) across Python scripts; src/services/base_api_service.ts delegates directly to the consolidated src/api/service/base-api-service.ts client (enforcing is_allowed_origin, scrub_secrets, and 10MB caps across all services); and src/components/onboarding/FirstRun_Wizard.tsx probes public /v1/engine/health with skip_auth: true and pre-verifies tokens against /v1/agents before 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.

Cryptographic & Financial Security Controls

  1. 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 Zeroize and Secrecy. Memory buffers are wiped automatically upon Drop, preventing cold-boot and process memory dump key extraction.
    • Private key files are written strictly with POSIX 0o600 permissions (-rw-------), and runtime process environment modification via std::env::set_var is prohibited.
  2. 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.
  3. 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.
  4. 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-second tokio::time::timeout to prevent channel exhaustion deadlocks.
  5. Server-Verified Operator Trust Boundaries (server-rs/src/routes/oversight/principal.rs):

    • OversightPrincipal is extracted exclusively from server-verified request extensions (OperatorIdentity / AuthenticatedOperator), preventing elevation of privilege or spoofed operator IDs from unauthenticated client headers or bodies.
  6. A2E-01 Financial Ledger Risk Containment (server-rs/src/routes/a2a.rs):

    • 24-Hour Rolling Spend Limits: Tracked in agent_economics_meta table (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 (u64 micro-USDC: $1.00 = 1,000,000 micros) eliminate IEEE-754 floating-point rounding errors in cryptographic audit chains.
  7. 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-local 169.254.0.0/16, IPv6 loopback ::1), mitigating Server-Side Request Forgery (SSRF) during template catalog synchronization.
  8. 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.
  9. 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).

Middleware Controls

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

CORS Status

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.1 on ports 5173 and 3000, plus tauri://localhost.
  • Private Network Access (PNA): Both cors.rs and security_headers.rs inject Access-Control-Allow-Private-Network: true to prevent browser pre-flight blocks when web origins communicate with local development daemon loopback addresses (127.0.0.1 / localhost).

Secret Redaction & Client-Side Pre-Flight DLP Shield

Data Loss Prevention is enforced symmetrically across both the Rust backend and the frontend runtime:

1. Client-Side Pre-Flight DLP Shield (src/utils/security_utils.ts, src/logic/command_processor.ts)

  • 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]
  • 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.

2. Backend Secret Redactor (server-rs/src/secret_redactor.rs)

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.

Shell Scanner & MCP Sandboxing

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.

MCP Subprocess Sandbox Boundary

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_exec and shlex.split, completely avoiding shell interpretation (shell=False equivalent).
  • Resource Boundaries: Implements Unix limits via setrlimit on 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.

Audit, Budget, And Permissions

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

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=true

Deployment Notes

Before deploying beyond local development:

  1. Set a strong NEURAL_TOKEN or NEURAL_ENGINE_ACCESS_TOKEN.
  2. Set ALLOWED_ORIGINS explicitly for deployed or shared environments.
  3. Validate that .env is excluded from source control.
  4. Run frontend and Rust test suites.
  5. Confirm protected endpoints reject missing and invalid bearer tokens.
  6. Confirm the dashboard stores and sends the same token configured for the engine.
  7. Review feature gates before enabling vector-memory or neural-audio.

Security Test Matrix

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

Prompt Injection & Autonomous Reasoning Boundaries

The platform enforces zero-trust controls over multi-turn agent reasoning and tool execution:

  1. Native Role Encapsulation (ChatMessage::Tool):

    • Tool observations and execution results are dispatched strictly as native tool role 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.
  2. 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 status flagged_injection.
  3. 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.
  4. Financial Cap Fallback & Loop Termination:

    • Pre-turn budget gate checks expenditure before each LLM invocation, falling back to a hard $10.00 safety limit (DEFAULT_BUDGET_LIMIT_USD).
    • Tool recursion tracker halts identical consecutive tool executions at 5 attempts via RunnerError::RecursionBlocked.

There aren't any published security advisories