// COMPLETE REFERENCE

Security policy (administration)

Chapter 569 11 min read English Stable reference URL

This page separates two things that are easy to confuse: what the software enforces in code, and what the operator of a deployment has to provide. Every row in the first half names the module that does the work; the second half lists the controls the product does not implement, so a security review does not credit it with them.

Detail lives in the pages each row points at. This page is the map, not a second copy of them. For the reader-facing half — what these controls mean for the person using the suite — see Security policy: what it means for you.

Table of Contents

What the platform enforces

Control Mechanism Detail
Authentication Bearer JWT verified by one function; directory (Zitadel) for SSO User Authentication
Anonymous access Declared per (method, path) in the auth allowlist, plus an anonymous entry in the RBAC table (security_setup.rs:73-76) Complete Permissions Reference
Authorization RBAC route table, first match, default deny Complete Permissions Reference
CSRF Double-submit cookie, HMAC-signed token; state-changing routes need the layer or an entry in scripts/security_directives_exemptions.toml botsecurity-auth/src/csrf/
Rate limits governor: 100 req/s (burst 200) global, 10 req/s (burst 10) per client on auth, 2 req/s (burst 5) on signup, 10 msg/s (burst 20) per socket System Limits
Security headers IMP-09 set on every response of every server (UI surfaces ship the CSP report-only) below
CORS Fail-closed allowlist; no origin configured means no Access-Control-Allow-Origin below
Outbound URLs fetch_user_url — scheme, port, address class, resolution, redirects and post-connect peer check Input Guardrails
Uploads validate_upload — size, filename, extension, MIME, magic bytes, archive bombs, malware verdict below
Error bodies log_and_sanitize — internal detail logged, never returned botsecurity-core/src/error_sanitizer/
Shell and SQL SafeCommand; sanitize_identifier / validate_table_name botsecurity-core/src/{command_guard,sql_guard}.rs
Sensitive fields encrypt_field on message history, session content, attendance content, external Drive content and personal memory below
Security decisions RBAC denials and CSRF rejections written to a hash-chained audit store below

Token signing and the single secret

Server-minted tokens are JWT HS256: the suite JwtConfig::default() selects it and cloud login (botcloud::api::handle_login) mints HS256 with the persisted saas_jwt_secret. One function turns such a token into claims — botsecurity_core::verified_jwt — which pins the algorithm to HS256, compares the HMAC in constant time, requires exp and honours nbf with a 60-second leeway (NBF_LEEWAY_SECONDS). Zitadel tokens are RS256 and take a different path: botsecurity-auth/src/zitadel_auth/jwks.rs verifies them against {issuer}/oauth/v2/keys (the kid must select a published RSA key, exp and iss are checked, 30-second skew), and verified_jwt refuses them by algorithm, so one cannot be substituted for the other.

The signing secret also has exactly one resolver, botsecurity_core::jwt_secret::resolve_saas_jwt_secret (botsecurity-core/src/jwt_secret.rs:324-363). It reads the persisted saas_jwt_secret from directory_config.json, then SAAS_JWT_SECRET, then JWT_SECRET; a sample-config placeholder counts as “not configured”. With nothing usable it generates a 48-character random secret and persists it atomically, so the minter and every verifier resolve the same value. dev-secret-key-change-in-production-minimum-32-chars is returned only by a debug build with GB_ALLOW_DEV_JWT_SECRET=1; when a production deployment (the default — only BOTSERVER_ENV=development lowers the guard) cannot persist the generated secret the resolver fails closed and the server refuses to start. scripts/check_jwt_secret.py fails CI when a second resolver, a local *saas_jwt_secret helper, a direct env/config read or a placeholder literal reappears in production code.

OAuth login flow

The authorization-code flow (botcoreoauth) treats everything travelling through the user agent as untrusted (botcoreoauth/src/state.rs, redirect.rs, cookies.rs):

  • Signed state — v1.<base64url(payload)>.<base64url(HMAC-SHA256)>, keyed by OAUTH_STATE_SECRET, else the Vault entries gbo/oauth-state → gbo/jwt, else an ephemeral per-process key that is logged as a warning. The MAC is compared in constant time before any field is read; tokens live 10 minutes and a token dated in the future (beyond 60 s of skew) is refused.
  • Browser binding — starting a flow sets gb_oauth_nonce (HttpOnly, Secure, SameSite=Lax, 10 minutes, scoped to the callback path) and registers the same nonce in botcoreoauth::nonce_store. The callback must present the cookie and the nonce must still be pending; it is removed on first use, so a replayed callback fails. SameSite=Lax rather than Strict is deliberate: the provider returns with a cross-site top-level GET.
  • Redirect allowlist — redirect_after accepts only relative paths or an absolute http(s) URL whose host[:port] is the deployment’s base_url or in OAUTH_REDIRECT_ALLOWED_HOSTS; //host, /\host, javascript:, data:, credentials in the authority, control characters and over-long values collapse to /.

Multi-factor authentication

MFA is a directory feature. Separately, botsecurity-auth/src/mfa/ verifies TOTP codes in one wire format fixed by tests: unpadded uppercase RFC 4648 base32 secret, SHA1/6 digits/30 s in the otpauth:// URI, ±1 period window, legacy 40-character hex rows converted on read. See User Authentication.

Security headers

botsecurity_core::headers::with_security_headers is the single applier, and it is layered outermost so fallbacks, ServeDir responses and the 401/403/404/ 429/500 rendered by inner layers all carry the headers (botserver/crates/botsecurity-core/src/headers/strict.rs:4-42; main_module/server/server_layers.rs:120-126). SecurityHeadersConfig::default() emits Content-Security-Policy, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, Strict-Transport-Security, Referrer-Policy, Permissions-Policy and Cache-Control, plus X-Powered-By. All four surfaces apply it: the API (8080), suite (3000), cloud (4000) and login (5000) (botui/src/ui_server/mod.rs:53-64); the sandbox listener and the ChatGPT OAuth loopback listener apply the same layer.

Two differences on the browser-facing surfaces, both deliberate (botui/src/ui_server/security_headers.rs:1-16):

  • The suite, cloud and login pages deliver CSP as Content-Security-Policy-Report-Only, because roughly a thousand inline on*= handlers still exist there (tracked by scripts/check_inline_handlers.py). Enforcing script-src 'self' today would blank the app.
  • BotUI emits HSTS only when the request arrived over TLS (directly or via X-Forwarded-Proto: https), since it listens on plain HTTP behind a TLS-terminating proxy.

Handler-scoped policies win where they exist: CSP and X-Frame-Options use insert-if-absent, so a sandboxed preview keeps its own stricter value. Permissions-Policy delegates microphone and camera to self because the chat composer records voice notes and takes camera shots from the same origin.

Plain-HTTP local development sets GB_SECURITY_HSTS=off (0, false, no also accepted); that drops HSTS only, and production never sets it (headers/mod.rs:11-50).

CORS

The allowlist comes from the cors-allowed-origins configuration value (comma-separated exact origins, read in security_setup.rs:29-52). With no origin configured the response carries no Access-Control-Allow-Origin, so browsers treat the API as same-origin only; a configured origin is echoed exactly, and Access-Control-Allow-Credentials: true is announced only for an origin on the list. * is ignored. CORS_ALLOW_ANY_ORIGIN=1 is a development switch that is off unless explicitly set and is never honoured in production (the default; only BOTSERVER_ENV=development opts out, #2615).

Uploads and malware scanning

Every handler that persists an upload calls botsecurity_core::upload_policy::validate_upload before writing (the scripts/check_upload_validation.py gate enumerates them): per-endpoint size cap, filename sanitization, extension allowlist (the last extension decides), declared MIME against extension, magic bytes, archive-bomb limits, and the hostile-file gate (upload_policy.rs:1-46). Rejections answer 400/413 with a stable error-file-* code. Drive calls it on all three write paths (botdrive/src/drive_handlers/{upload_binary,transfer}.rs, botdrive/src/external/routes_upload.rs).

A malware scanner is installed once at boot: with clamscan on the machine the ClamAV scanner is registered, and a failed registration aborts startup instead of serving unscanned uploads (main_module/server/run_axum_server_malware_scanner.rs:49-74). The exception is the gblite edition on a machine without clamscan, which logs that uploads are accepted without a scan.

Field-level encryption

encrypt_field (AES-256-GCM, botsecurity-crypto/src/encryption/) is applied to a narrow set of values, not to everything:

Data Call site
message_history.content_encrypted botcoresession/src/session_manager/with_key.rs:278-292, main_module/migration/store.rs:215
Session content botcoresession/src/session_manager/with_key.rs
Attendance content botattendance/src/routes.rs:170
External Drive content botdrive/src/external/crypto.rs:26
Personal memory botsettings/src/memory_store.rs:46

Uploaded files, the database files and backups are not encrypted by the application; that control belongs to the storage layer.

Audit trail of security decisions

botsecurity_core::audit::security_decision bridges enforcement outcomes to the hash-chained AuditStore (audit/security_decision.rs:1-16,120-140). Callers are the RBAC middleware (denials), the CSRF middleware (rejections) and the pipeline executor. The actor is always server-derived, action and reason_code are static strings, and only a SHA-256 fingerprint of the payload is retained. Successes are skipped unless they are authentication, role/group or admin changes, so a busy server does not flood the chain.

Retention that exists

Only a few subsystems have a retention window today, and each is defined next to its job (main_module/background.rs:125-131):

Data Window Source
Drive trash rows 30 days (expires_at, then purged) drive_handlers::spawn_trash_purge
Terminal audit records 90 days computer_use_routes::spawn_terminal_audit_purge
Run events configured window core/bot/runs/store.rs:119-133

There is no per-data-type retention schedule for conversations or files: no configuration key sets one, and nothing purges message_history by age.

What the platform does not do

Area Reality Who provides it
Encryption at rest for Drive objects, database files, backups Not implemented in the application; only the fields listed above are encrypted Storage/database layer, disk encryption
Row-level security in PostgreSQL No ROW LEVEL SECURITY policy in any migration; isolation is application-level (branch_id, bucket per tenant) Application code; verify with the tenant suite
TLS termination The server listens on plain HTTP; TLS is terminated by the proxy (Caddy) Deployment
Mutual TLS between services Opt-in for containerized installs with provisioned certificates (init_tls.rs, #2590); plain loopback otherwise Deployment
Certificate pinning Implemented and enforced at the TLS handshake, but opt-in per deployment (GB_CERT_PINNING_CONFIG) Deployment
MFA enforcement The TOTP verifier exists; nothing forces enrolment Directory policy
Password policy Argon2id where the platform stores a password itself; SSO deployments delegate policy to the directory Directory policy
Malware scanning on gblite without clamscan Explicitly skipped, with a log line Install clamscan
Backups and restore drills Host scripts (scripts/restore_drill.sh), not an application feature Operator
Intrusion detection, antivirus on the host Optional install, not part of the server (Security Protection Tools) Operator
SIEM / log shipping Logs go to the process output; no shipper is built in Operator

Policies the product cannot decide for you

The following are organisational decisions with no representation in the configuration: information classification, retention periods beyond the table above, access-review cadence, acceptable-use rules, security training, vendor assessment, and breach-notification timelines. Write them in your own policy and point them at the controls above; this book does not state numbers it cannot source.

Two obligations are concrete and already documented elsewhere:

  • Incident handling and disclosure — intake, triage, publication authority and escalation to CERT.br / CTIR Gov are defined in Incident Response and Publication Authority.
  • Vulnerability reporting — generalbots.org/.well-known/security.txt (RFC 9116), SECURITY.md and the advisory pages under this chapter. Reports go to security@generalbots.org; acknowledgement is within 3 business days (incident-response.md:130).

Mechanical gates in CI

Structural rules a reviewer would otherwise have to remember are enforced by scripts. Each fails the build with file:line, and each allowlist is shrink-only: an entry that no longer suppresses a violation is itself reported.

Gate Command Fails on
JWT hardening (#2125) python3 scripts/check_jwt_hardening.py --check jsonwebtoken::dangerous / insecure_decode; a file that decodes a JWT payload and reads sub/user_id/email without the shared verifier
Single JWT secret (#2140) python3 scripts/check_jwt_secret.py --check a second resolver or local *saas_jwt_secret helper; a direct SAAS_JWT_SECRET/JWT_SECRET/config read outside the canonical module; a placeholder secret in production code
Container runtime (#2126) python3 scripts/check_container_runtime.py --check spawning lxc/lxd/lxc-execute, or incus through a raw Command::new instead of SafeCommand
Security directives (IMP-07/IMP-08) python3 scripts/check_security_directives.py a state-changing handler without the CSRF layer and without an entry in scripts/security_directives_exemptions.toml; a missing general/auth/API rate limiter or WebSocket message limiter
Security headers (IMP-09) python3 scripts/check_security_headers.py --check an axum::serve without the header layer, a configure_*_router factory that stopped applying it, an API stack not layered outermost, a missing header
SSRF fetch sites (#2131) python3 scripts/check_ssrf.py --check a client.get(variable_url) / reqwest::get(variable_url) whose enclosing function does not call fetch_user_url/fetch_internal_service_url and is not in scripts/ssrf_allowlist.txt
Upload validation (#2132) python3 scripts/check_upload_validation.py --check an upload handler that does not call validate_upload

Each gate carries a --self-test that proves its rules fire. The ones wired into .github/workflows/ci.yml run in the guard job. scripts/prod_readiness.py aggregates the readiness checks registered in scripts/prod_readiness_gates.py and prints one row per check; SKIP is never a pass. The scoreboard is generated into Production Readiness Gate — regenerate it instead of editing it.

Verification

python3 scripts/check_security_headers.py --check
python3 scripts/check_ssrf.py --check
python3 scripts/check_upload_validation.py --check
python3 scripts/check_jwt_secret.py --check
python3 scripts/prod_readiness.py

See also

// SEARCH ESC
Pagefind · 236 pages · 4 books Enter to open ↑ ↓ to move