Documentation menu

Security

Security

This page lists what Taphra protects by default, what each default does, and what you still set up yourself, then ends with a checklist for production. Logging users in, tokens and policies are in Authentication.

Every PHP example below marked as runnable runs as written, in order.

Contents

#

Environments and error pages

#

The mode comes from the APP_ENV environment variable, read in app/bootstrap.php:

APP_ENV Mode
dev, development, local development
stg, stage, staging staging
anything else, or unset production

IS_PRODUCTION=1 forces production whatever APP_ENV says. A server that forgets to set APP_ENV therefore runs in production mode. php taphra serve sets APP_ENV=dev for the development server it starts.

The debug error page (Whoops, with the stack trace, request data and queries) is registered in development only. In staging and production an uncaught exception is logged and answered with the right status (403, 404, 405, 500) and the app's error404.tpl.php or error500.tpl.php view, or a JSON body without details for clients that ask for JSON (see REST APIs). display_errors comes from app.yml (0 in the skeleton's prod section).

PHP
foreach (['dev', 'local', 'staging', 'production', 'test', ''] as $env) {
    echo str_pad("'$env'", 13), modeFromEnvironment($env, false), "\n";
}
// 'dev'        dev
// 'local'      dev
// 'staging'    stg
// 'production' prod
// 'test'       prod
// ''           prod

CSRF

#

The skeleton's AppController, the base of its HTML controllers, sets protected $autoVerifyCsrf = true;. Every request that is not GET, HEAD or OPTIONS must then carry the session's CSRF token, in the _csrf_token form field or the X-CSRF-Token header; otherwise the action does not run and the request ends with 403 Forbidden.

Put the token in every form:

PHP
<form method="post" action="/notes">
  <?= $this->csrf() ?>
  ...
</form>

$html->formOpen('/notes') from the HTML helper adds it too. For JavaScript requests (fetch, HTMX), print the token once in the layout, for example in a <meta name="csrf-token"> tag filled from Taphra\Security::generateCsrfToken(), and send it as the X-CSRF-Token header. The token is 64 hex characters, one per session, compared in constant time.

app/Config/routes.yml
POST:
  /notes: note/store
PHP
// app/Controllers/NoteController.php
namespace App\Controllers;

class NoteController extends AppController
{
    public function store(): string
    {
        return 'saved';
    }
}
PHP
use Taphra\Security;

$token = Security::generateCsrfToken();   // what $this->csrf() put in the form

echo docs_request('POST', '/notes')->getStatusCode(), "\n";                                    // 403
echo docs_request('POST', '/notes', ['_csrf_token' => 'forged'])->getStatusCode(), "\n";       // 403
echo docs_request('POST', '/notes', ['_csrf_token' => $token])->getBody(), "\n";               // saved

The X-CSRF-Token header works the same way.

Bind each state-changing action to POST, PUT, PATCH or DELETE in routes.yml (see Routing); a GET to it then gets 405, so a link or an image cannot trigger it.

Controllers that extend RestController directly do not check the token: an API that authenticates every request with an Authorization header is not exposed to CSRF, because browsers do not add that header on their own. An API that relies on the session cookie must check a token, either by setting protected $autoVerifyCsrf = true; on its controllers or with the double-submit cookie for single-page apps:

PHP
use Taphra\Security;

// When the page loads: a random token in a cookie that JavaScript can read
// (XSRF-TOKEN, SameSite=Strict, not HttpOnly).
Security::setCsrfCookie();

// On each state-changing request: the client copies the cookie into the X-XSRF-Token header.
if (!Security::validateCsrfHeader()) {
    return $this->apiError(403, 'CSRF token mismatch.');
}

For a form with its own token, pass the same id to both sides: $this->csrf('delete-account') in the view and $this->verifyCsrf('delete-account') in the action (the automatic check uses the default id).

Sessions and cookies

#

Sessions start on demand (a login, a CSRF token, flash data), with these settings:

Setting Value
HttpOnly on: scripts cannot read the session cookie
SameSite Lax: the cookie is not sent on cross-site POSTs
Secure on when the request is HTTPS, including HTTPS ended at a trusted proxy
session.use_strict_mode on: a session ID the server did not issue is replaced
session.use_only_cookies on: no session IDs in URLs
lifetime app.session.timeout seconds, else PHP's session.cookie_lifetime, then session.gc_maxlifetime

Auth::login() and Auth::logout() give the session a new ID, so an ID seen before login is useless after it. Override the cookie values under app.session.cookie (lifetime, path, domain, secure, httponly, samesite) in app.yml. The remember-me cookie is described in Authentication.

Taphra\Cookie::set($name, $value, $expiry = 0, ...) sets your own cookies HttpOnly and SameSite=Lax by default, but not Secure: call Cookie::configSecure(true) once in app/bootstrap.php for an HTTPS site, or pass $secure per cookie.

Security headers

#

Every response of the web front controller carries:

Header Value
X-Content-Type-Options nosniff
X-Frame-Options SAMEORIGIN
Referrer-Policy strict-origin-when-cross-origin
X-XSS-Protection 0 (turns off the old browser filter, which caused leaks)
Strict-Transport-Security max-age=31536000, on HTTPS requests only

No Content-Security-Policy is sent by default, because it would block the inline styles and scripts many existing pages use. Add one, change a value, or remove a header with ~ under security_headers in app.yml:

YAML
prod:
  security_headers:
    Content-Security-Policy: "default-src 'self'"
    X-Frame-Options: DENY
    X-XSS-Protection: ~

For inline scripts under a CSP, Taphra\Security::nonce() returns one random nonce per request, for both the header (script-src 'nonce-...') and the <script nonce="..."> tags. In a PSR-15 pipeline, Taphra\Http\SecurityHeadersMiddleware sends the same headers plus Content-Security-Policy: default-src 'self'; its constructor takes the same overrides (null removes a header).

Proxies, client IPs and URLs

#

Behind a load balancer or reverse proxy, the connection comes from the proxy. Taphra reads X-Forwarded-For and X-Forwarded-Proto only from the addresses listed in app.trusted_proxies (single addresses or CIDR ranges):

YAML
prod:
  trusted_proxies: [10.0.0.0/8]

Without that list, Request::clientIP() is REMOTE_ADDR and HTTPS is detected from the server variables alone, so a client cannot fake its address or the scheme with a header. With it, the client IP is the last address in X-Forwarded-For that is not itself a trusted proxy, and X-Forwarded-Proto: https from a proxy counts as HTTPS (for the Secure cookie flag and HSTS).

url() builds absolute links (for emails, redirects to other hosts, feeds). In production it uses app.base_url and throws a ConfigurationException when that is not set, because the alternative, the Host header, is chosen by the client: a forged one would end up in password-reset links. Set it in the prod section:

YAML
prod:
  base_url: https://example.com

Escaping output

#
  • e($value) escapes for HTML (htmlspecialchars with ENT_QUOTES; arrays and objects are JSON-encoded first).
  • In views, top-level string variables are escaped once before the template runs, and e() leaves those as they are, so <?= e($title) ?> is never escaped twice. Strings inside arrays and objects are not escaped in advance: print them with e().
  • The HTML helpers escape attribute values, option labels and anchor text.
  • new Taphra\SafeString($html) marks HTML you trust (your own markup, or sanitised rich text) so none of these escape it.
  • Taphra\HtmlSanitizer::clean($html) keeps a safe subset of user-written HTML: an allow-list of tags and attributes, http, https and mailto links only, and no scripts, styles, frames, forms or event handlers. It needs ext-dom.
PHP
use Taphra\HtmlSanitizer;
use Taphra\SafeString;

echo e('<b>"Tom" & Jerry</b>'), "\n";
// &lt;b&gt;&quot;Tom&quot; &amp; Jerry&lt;/b&gt;
echo e(new SafeString('<em>ok</em>')), "\n";  // <em>ok</em>

echo HtmlSanitizer::clean('<p onclick="steal()">Hi <a href="javascript:alert(1)">there</a><script>x()</script></p>'), "\n";
// <p>Hi <a>there</a></p>

Views and helpers has the details.

SQL

#

Values are always bound as parameters, column names and operators are checked, and SQL text goes in only through the methods that say so (whereRaw() and the other *Raw() methods, string conditions, the connection's query()). $fillable and $guarded limit mass assignment. See Database: input safety.

Encryption

#

Taphra\Crypt encrypts with libsodium (XSalsa20-Poly1305, a fresh random salt and nonce per message). The key must be at least 32 bytes; a shorter one throws InvalidArgumentException. decrypt() returns false for a wrong key or changed data, never partial plaintext.

PHP
use Taphra\Crypt;

$key = bin2hex(random_bytes(32));   // in an app: from the environment

$token = Crypt::encrypt('JBSWY3DPEHPK3PXP', $key);
echo Crypt::decrypt($token, $key), "\n";                       // JBSWY3DPEHPK3PXP
var_dump(Crypt::decrypt($token, bin2hex(random_bytes(32))));   // bool(false)

try {
    Crypt::encrypt('x', 'short key');
} catch (InvalidArgumentException $e) {
    echo "refused: key too short\n";
}

// For a secret a person types, the passphrase API derives the key with Argon2id:
$sealed = Crypt::encryptWithPassphrase('notes', 'correct horse battery staple');
echo Crypt::decryptWithPassphrase($sealed, 'correct horse battery staple'), "\n";   // notes

The two pairs do not read each other's output. php taphra key:generate writes a random APP_SECRET_KEY to .env. Taphra loads .env at boot, and a variable already set in the process environment wins; in production, set the variables in the server's environment (PHP-FPM pool, systemd unit, container) rather than shipping a .env file. The package README, packages/crypt/README.md, lists the exact format.

Rate limiting

#

Taphra\RateLimiter counts hits per key in a fixed window: the first hit opens a window of $decaySeconds, and the count starts again when it has passed. It stores the counts in the application cache (Redis when configured, else files).

PHP
use Taphra\RateLimiter;

$limiter = RateLimiter::make('docs-api', 3, 60);   // 3 hits per 60 seconds
$key = '203.0.113.7';                             // in an app: Request::clientIP() or a user id

// attempt() counts the hit and checks the limit in one step, so parallel
// requests cannot all pass before one of them is counted.
for ($i = 1; $i <= 4; $i++) {
    if (!$limiter->attempt($key)) {
        echo "hit $i: refused, retry in ", $limiter->availableIn($key) > 0 ? 'under a minute' : 'now', "\n";
        continue;
    }
    echo "hit $i: allowed, ", $limiter->remaining($key), " left\n";
}
// hit 1: allowed, 2 left
// hit 2: allowed, 1 left
// hit 3: allowed, 0 left
// hit 4: refused, retry in under a minute

$limiter->clear($key);

Taphra\Http\RateLimitMiddleware(RateLimiter::cacher(), $maxRequests, $windowSeconds) applies one limit to every request through a PSR-15 pipeline and answers 429 with a Retry-After header. It counts per Request::clientIP(): behind a proxy listed in trusted_proxies each client gets its own limit; without the list every client shares the proxy's address.

Queues, MCP and the AI builder

#
  • Queue workers run only jobs whose payload names a class implementing Taphra\Queue\JobInterface and one of its static methods; a payload naming any other class or function is refused. See Queues.
  • MCP over HTTP refuses every request (401) until you set a token of at least 32 bytes (the TAPHRA_MCP_TOKEN environment variable or mcp.token in ai.yml) or override authorizeMcp(); it refuses browser origins other than loopback and mcp.allowed_origins (403) and requires JSON. See MCP server.
  • The AI builder (ai:build, ai:fix) asks before every file write (including the files make:* generators create) and before every command outside a fixed allow-list, never runs a shell, and keeps a receipt so ai:rollback can undo a session. See AI builder.

Logs

#

Outside development, only notices, warnings and errors are written (app.logging.level changes the threshold); logging.method: null discards logs. The opt-in request log for php taphra debug:request (logging.log_requests) is never written in production, and it writes cookies, Authorization, session ids, token, secret, key, password, one-time code, PIN and CSRF headers and fields, bodies it cannot parse and token-like path segments as [redacted]. Logs can still hold user input and exception messages: keep app/tmp/ out of the web root (the document root is app/Static/) and readable by the application user only.

Production checklist

#
  • APP_ENV=prod (or simply not set to a development value) on every web server, worker and cron job.
  • display_errors: 0 in the prod section of app.yml (the skeleton sets it).
  • base_url set in prod, so url() never uses the Host header.
  • trusted_proxies set when a load balancer or proxy is in front, and only then.
  • HTTPS everywhere; HSTS and the Secure cookie flag follow automatically. Call Cookie::configSecure(true) if you set your own cookies.
  • A Content-Security-Policy under security_headers, once your pages work with it.
  • Secrets (database password, JWT_SECRET of at least 32 bytes, APP_SECRET_KEY, AI and payment keys) come from the environment, not from files in the repository.
  • Every HTML controller extends AppController (CSRF on); every form prints $this->csrf(); every state-changing route is bound to POST, PUT, PATCH or DELETE.
  • APIs authenticate with a token (AuthMiddleware or a JWT middleware in a route group), or check CSRF when they use the session cookie.
  • Login, password reset and verification endpoints are rate limited; two-factor secrets are encrypted at rest.
  • DataStores declare $fillable (or $guarded); raw SQL methods never receive request data as SQL.
  • A shared cache (Redis) when several servers share sessions, rate limits, TOTP replay protection or JWT revocation.
  • The web server's document root is app/Static/; app/tmp/ is writable by PHP and not served.
  • MCP over HTTP has a token; queue workers run as an unprivileged user.
  • After changing YAML configuration on a production server, run php taphra cache:clear (production keeps the parsed configuration cached), then php taphra optimize if you use it. See Deployment.