Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Security Architecture

This document describes the threat model, authentication tiers, and security mechanisms in the 4got metasearch engine.

Threat model

4got faces several threat categories:

  1. Abuse (bots, scraping, DoS): Automated clients attempting to use the instance as a free search API proxy, or overwhelming it with requests.
  2. Privacy leakage: Search queries, user IPs, or browsing patterns leaking to upstream engines, result sites, or third parties.
  3. Server-Side Request Forgery (SSRF): Attackers using the image proxy, service proxy, or AI research agent to access internal network resources.
  4. Cross-Site Request Forgery (CSRF): Malicious sites submitting forms to the instance on behalf of authenticated users.
  5. Plugin/extension code execution: Lua plugins or AI research agents executing arbitrary code within the server process.
  6. Federation trust abuse: Malicious or compromised peer instances exploiting the cache sharing or service proxy mechanisms.

Non-threats (by design)

  • User account compromise: No user accounts exist. All personalization is cookie-based with no passwords.
  • Data theft from database: The SQLite database contains only search logs, engine stats, and anonymized trending data. No PII is stored.

Network-level access control

For private instances shared with friends, 4got recommends mTLS client certificates at the reverse proxy layer (Caddy/nginx). This keeps authentication entirely outside 4got’s scope — unauthorized users are rejected at the TLS handshake before any HTTP traffic is exchanged. See Friend Access (mTLS) for setup instructions.

Authentication tiers

4got uses a tiered authentication model defined in groups.kdl:

TierHow acquiredCapabilities
UnauthenticatedNo cookieRedirected to PoW or captcha challenge
Session (cookie)Solve PoW or captchaSearch access, settings, history
API keyIssued by ownerProgrammatic search access via X-API-Key header
DeluxeGroup membershipAccess to browser-backed engines, banner uploads, AI features
OwnerBearer token matching owner-secret in configFull admin: search logs, user management, engine health, force-unsuspend

Group membership is determined by the group-members section in config.kdl, which maps cookie hashes to groups. Groups inherit permissions from their definition in groups.kdl.

Session lifecycle

  1. New visitor hits any search endpoint.
  2. Server checks for a valid 4got_session cookie.
  3. If absent, redirects to PoW challenge (or captcha for JavaScript-disabled clients and Tor users).
  4. PoW solution or captcha answer is verified server-side.
  5. On success, a session cookie is set with a configurable TTL (captcha-bypass-hours).
  6. The 4got_seen cookie marks a browser that passed the captcha, so later visits go straight to PoW (from a Tor exit, past it). It is signed by the server (an HMAC keyed from the identity key) and expires after captcha-bypass-hours; a cookie the server did not sign, or an expired one, counts as absent.

CSRF implementation

All state-mutating POST endpoints are protected by double-submit CSRF tokens:

  1. EnsureCSRFToken() reads or generates a 32-hex-character token (16 random bytes from crypto/rand).
  2. The token is stored in a csrf_token cookie (HttpOnly is not set because JavaScript needs to read it for AJAX requests).
  3. Every form includes a hidden <input name="_csrf"> field with the token value.
  4. On POST, ValidateCSRF() compares the form field (or X-CSRF-Token header for JSON endpoints) against the cookie using crypto/subtle.ConstantTimeCompare.
  5. Mismatches return 403.

Protected endpoints include: settings update, feedback submission, captcha/PoW verification, banner upload/delete, bookmark operations, and admin actions.

SSRF protection

Multiple subsystems make outbound HTTP requests. Each enforces SSRF protections:

Image proxy (/proxy/image)

  • Fetches through a guarded client (safe_fetch.go): the dialer resolves the name and connects only to an address publicIP() accepts — not private, loopback, link-local, CGNAT (100.64.0.0/10), IPv6 ULA, multicast or reserved. The check is made on every connection, redirects included, so neither DNS rebinding nor a redirect to an inside address gets through.
  • Only fetches image content types; rejects non-image responses.
  • Size limit prevents memory exhaustion from large responses.

AI research agent

  • URL fetch and POST tool calls, and child URLs discovered during page scraping, go through the same guarded client.
  • The Lua sandbox (see below) only exposes http_get/http_post when lua-network is enabled in the AI config.

Favicon proxy (/proxy/favicon)

  • Proxies through DuckDuckGo’s favicon service, not direct connections to arbitrary hosts.

Service proxy (/api/v1/proxy)

  • Only proxies to pre-configured service endpoints (translation backends, Wolfram Alpha, etc.).
  • Only for a friend: the X-Peer-Secret header, this server’s peer-secret.
  • Service names are whitelisted: translation, deepl, lingva, nllb, wolfram, autocomplete.

Lua sandbox boundaries

Plugins (data/plugins/*.lua) and the AI research agent run in sandboxed Lua states with restricted capabilities:

What is allowed

  • Safe standard libraries: base (minus dangerous functions), string, table, math
  • Safe os functions: os.time(), os.clock() only
  • JSON: json_decode(), json_encode()
  • Network (when enabled): http_get(), http_post() with SSRF protection
  • Logging: log() (writes to server log), print() (writes to response stream for AI)
  • Events: emit_event() for plugin hooks

What is blocked

  • Filesystem access: dofile, loadfile, require, io, os.execute, os.remove, os.rename – all removed or never loaded
  • Code loading: load, loadstring – removed
  • Raw table access: rawget, rawset, rawequal, rawlen, getmetatable, setmetatable – removed
  • Full os library: Only time() and clock() are injected; the os library is never opened
  • Debug library: Never loaded
  • Package/module system: Never loaded

Execution limits

  • Per-execution timeout (configurable, default 180s for AI research, shorter for plugins).
  • The Lua state is created fresh per execution – no persistent state between calls.
  • Plugin states persist across calls but are isolated from each other.

Federation trust model

4got instances can form friend networks for cache sharing and service proxying. The trust model is:

Authentication

  • Peer secret: A shared secret (peer-secret in config.kdl) used as a Bearer token for inter-instance API calls.
  • Mutual configuration: Both instances must list each other in their peers.kdl configuration.

Cache sharing

  • Friend instances share search result caches via /api/v1/cache GET/POST.
  • Cache entries are keyed by query hash – friends cannot enumerate what was searched.

Service proxying

  • Instances can proxy service calls (translation, Wolfram Alpha, autocomplete) through friends.
  • allow-proxy in config whitelists which services can be proxied.
  • prefer-friend directives route specific services through preferred friends, only for the owner and groups with friend_proxy; anyone else’s text never reaches the friend.
  • Each proxied request carries the peer secret for authentication.

Trust boundaries

  • Friends see query hashes (SHA-256) but not the original queries in cache keys.
  • No IP addresses or user identifiers are shared between instances.
  • A compromised friend can inject bad cache entries (low-quality results) but cannot:
    • Access the local instance’s search logs or user data
    • Execute code on the local instance
    • Access internal network resources (SSRF protection applies to all outbound requests)
  • Friend connection failures are handled gracefully with the same exponential backoff as engine failures.

Additional security measures

Rate limiting

  • Per-IP and per-cookie-hash rate limiting on search endpoints.
  • Adaptive PoW difficulty increases under load (+1 bit at >100 RPM, +2 bits at >500 RPM).
  • Engine-level rate limiting prevents upstream abuse.

Content Security

  • All user-generated content is HTML-escaped via html.EscapeString().
  • Result URLs use rel="noreferrer nofollow" to prevent referrer leakage.
  • The image proxy strips EXIF data and re-encodes images to JXL where possible.
  • robots meta tag is set to noindex,nofollow on all pages.
  • Session cookies use SameSite=Lax to prevent cross-site attachment.
  • Settings are stored as plaintext key=value cookies with no sensitive data.
  • Cookie hashes (SHA-256 of the session cookie) are used for internal tracking – the raw cookie value is never logged.

No tracking

  • No IP logging in search results or history views.
  • No browser fingerprinting.
  • No third-party analytics or tracking scripts.
  • The /static/assets/beacon.js link is a honeypot for ad blockers, not a real tracker.