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:
- Abuse (bots, scraping, DoS): Automated clients attempting to use the instance as a free search API proxy, or overwhelming it with requests.
- Privacy leakage: Search queries, user IPs, or browsing patterns leaking to upstream engines, result sites, or third parties.
- Server-Side Request Forgery (SSRF): Attackers using the image proxy, service proxy, or AI research agent to access internal network resources.
- Cross-Site Request Forgery (CSRF): Malicious sites submitting forms to the instance on behalf of authenticated users.
- Plugin/extension code execution: Lua plugins or AI research agents executing arbitrary code within the server process.
- 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:
| Tier | How acquired | Capabilities |
|---|---|---|
| Unauthenticated | No cookie | Redirected to PoW or captcha challenge |
| Session (cookie) | Solve PoW or captcha | Search access, settings, history |
| API key | Issued by owner | Programmatic search access via X-API-Key header |
| Deluxe | Group membership | Access to browser-backed engines, banner uploads, AI features |
| Owner | Bearer token matching owner-secret in config | Full 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
- New visitor hits any search endpoint.
- Server checks for a valid
4got_sessioncookie. - If absent, redirects to PoW challenge (or captcha for JavaScript-disabled clients and Tor users).
- PoW solution or captcha answer is verified server-side.
- On success, a session cookie is set with a configurable TTL (
captcha-bypass-hours). - The
4got_seencookie 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 aftercaptcha-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:
EnsureCSRFToken()reads or generates a 32-hex-character token (16 random bytes fromcrypto/rand).- The token is stored in a
csrf_tokencookie (HttpOnly is not set because JavaScript needs to read it for AJAX requests). - Every form includes a hidden
<input name="_csrf">field with the token value. - On POST,
ValidateCSRF()compares the form field (orX-CSRF-Tokenheader for JSON endpoints) against the cookie usingcrypto/subtle.ConstantTimeCompare. - 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 addresspublicIP()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_postwhenlua-networkis 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-Secretheader, this server’speer-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()andclock()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-secretinconfig.kdl) used as aBearertoken for inter-instance API calls. - Mutual configuration: Both instances must list each other in their
peers.kdlconfiguration.
Cache sharing
- Friend instances share search result caches via
/api/v1/cacheGET/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-proxyin config whitelists which services can be proxied.prefer-frienddirectives route specific services through preferred friends, only for the owner and groups withfriend_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.
robotsmeta tag is set tonoindex,nofollowon all pages.
Cookie security
- Session cookies use
SameSite=Laxto 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.jslink is a honeypot for ad blockers, not a real tracker.