# Stateless Runtime Forensics — Phase 3

**Commit:** 0cd7d41
**Date:** 2026-08-28
**Phase:** 3 — Stateless Runtime (Playbook Phase 8.1)

---

## Previous Architecture

Before Phase 3, the production runtime used **filesystem-backed rate-limit state** even when Redis was configured:

```
ContainerFactory::buildRateLimiter()
    tryConnectRedis() → null (REDIS_HOST missing) → FileRateLimiter   ← PROBLEM
    tryConnectRedis() → ok                        → RedisRateLimiter(redis, new FileRateLimiter())
                                                     └─ Redis eval fails → FileRateLimiter   ← PROBLEM
```

Additionally, `SecurityHelper::rateLimit()` was called directly in two production paths:
1. `RateLimitMiddleware::handle()` — global per-IP rate limiting
2. `AdminAuthControllerHandler::login()` — admin login brute-force protection

Both called `SecurityHelper::rateLimit()` which hardcodes `storage/cache/rate_limits/*.json` filesystem writes regardless of environment.

**Root risk:** A multi-host production deployment would lose rate-limit state on every request, since each host maintains its own filesystem, enabling bypass of login and API rate limits.

---

## Runtime-State Inventory

| Component | State Location | Pre-Phase3 Risk |
|---|---|---|
| `SecurityHelper::rateLimit()` | `storage/cache/rate_limits/*.json` | Used in 2 production paths |
| `FileRateLimiter::limit()` | `storage/cache/rate_limits/*.json` | Default fallback in production |
| `RedisRateLimiter::limit()` | Redis `anbt:rl:<hash>` keys | Only when REDIS_HOST set |
| `Cache` | Redis / no-op | No filesystem involvement |
| `$_SESSION` | Not used | Architecture test verifies |

---

## Production Fallback Risk (Pre-Phase 3)

```
REDIS_HOST missing
    ↓
ContainerFactory::buildRateLimiter()
    ↓ tryConnectRedis() → null
    ↓
return new FileRateLimiter()   ← silent production fallback (NO EXCEPTION)
```

```
REDIS_HOST set
    ↓
RedisRateLimiter($redis, new FileRateLimiter())
    ↓ Redis eval fails at runtime
    ↓
fallback->limit()   ← silent runtime fallback to filesystem (NO EXCEPTION)
```

---

## Redis Configuration

| Variable | Required in Production | Default |
|---|---|---|
| `REDIS_HOST` | **YES — startup FAILS without it** | (empty → local fallback) |
| `REDIS_PORT` | No (defaults to 6379) | 6379 |

Production behavior (Phase 3):
- `REDIS_HOST` missing → `RuntimeException` thrown during DI container resolution
- `REDIS_HOST` set, connection fails → `RuntimeException` thrown during DI container resolution
- `predis/predis` not installed → `RuntimeException` thrown during DI container resolution

Non-production behavior (Phase 3):
- `REDIS_HOST` missing → `FileRateLimiter` fallback (explicit, by environment policy)
- `REDIS_HOST` set → `RedisRateLimiter` with `FileRateLimiter` fallback on Redis errors

---

## DI Resolution

### ContainerFactory::buildRateLimiter (Phase 3)

```php
$appEnv = $app->config('app.env') ?: getenv('APP_ENV') ?: 'local';
$isProduction = $appEnv === 'production';

$redis = self::tryConnectRedis(..., $isProduction);

// Production + Redis connected:
return new RedisRateLimiter($redis, null);   // null fallback = fail-closed

// Non-production + Redis connected:
return new RedisRateLimiter($redis, new FileRateLimiter());

// Non-production + Redis missing:
return new FileRateLimiter();

// Production + Redis missing or unreachable:
throw RuntimeException;   // startup fails
```

### RedisRateLimiter::limit (Phase 3)

```
Redis eval OK    → use Redis result
Redis eval fails:
    fallback != null  → use FileRateLimiter (local/testing only)
    fallback == null  → fail-closed: allowed=false, remaining=0  (production)
```

---

## Environment Matrix

| Environment | REDIS_HOST | Result | Test |
|---|---|---|---|
| `production` | missing | startup FAIL (RuntimeException) | `testProductionFailsFastWhenRedisHostIsMissing` |
| `production` | configured | `RedisRateLimiter` (fail-closed) | `testProductionResolvesRedisRateLimiterWhenRedisHostIsConfigured` |
| `testing` | missing | `FileRateLimiter` fallback | `testTestingEnvironmentAllowsFileFallbackWhenRedisIsMissing` |
| `local` | missing | `FileRateLimiter` fallback | Same code path as testing |

---

## Tests Added

| Test Class | Method | Proves |
|---|---|---|
| `StatelessRuntimeArchitectureTest` | `testProductionFailsFastWhenRedisHostIsMissing` | Production startup fails with REDIS_HOST missing |
| `StatelessRuntimeArchitectureTest` | `testTestingEnvironmentAllowsFileFallbackWhenRedisIsMissing` | Testing fallback preserved |
| `StatelessRuntimeArchitectureTest` | `testProductionResolvesRedisRateLimiterWhenRedisHostIsConfigured` | Production resolves RedisRateLimiter |
| `Phase8ScaleTest` | `testLegacyFileRateLimiterIsOnlySelectedByContainerFactory` | No code outside ContainerFactory/RedisRateLimiter creates FileRateLimiter |
| `Phase8ScaleTest` | `testProductionRateLimitingCannotUseLegacySecurityHelper` | SecurityHelper::rateLimit not called in production code |

---

## Failure Semantics

**Policy:** Fail-closed in production.

When Redis is unavailable at runtime (after startup):
- `RedisRateLimiter::limit()` returns `allowed=false, remaining=0`
- No traffic passes the rate limiter

Rationale: Failing open (allowing all requests when Redis is down) would enable brute-force bypass during Redis outages. Failing closed is the safer default for a security control.

This policy is explicit, not invented: the `$fallback = null` in production makes the closed behavior observable at code review.

---

## Files Changed

| File | Change |
|---|---|
| `src/Core/Container/ContainerFactory.php` | Fail-fast for production; env-based policy selection |
| `src/Common/Service/RedisRateLimiter.php` | Support null fallback (fail-closed); nullable `$fallback` property |
| `src/Core/Middleware/RateLimitMiddleware.php` | Inject `RateLimiterInterface` via DI; remove `SecurityHelper::rateLimit` |
| `src/Admin/AdminAuthControllerHandler.php` | Inject `RateLimiterInterface` via DI; remove `SecurityHelper::rateLimit` |
| `tests/Architecture/StatelessRuntimeArchitectureTest.php` | NEW — 3 environment-matrix tests |
| `.env.example` | Document REDIS_HOST production requirement |
| `docs/arch/PROGRESS.md` | Phase 3 marked IN PROGRESS → DONE |

---

## Acceptance Gate Result

- [x] Production runtime state does not use filesystem
- [x] Production RateLimiterInterface resolves to Redis implementation
- [x] Missing REDIS_HOST causes production startup failure
- [x] No silent production fallback
- [x] Local fallback behavior preserved where allowed
- [x] Testing fallback behavior preserved where allowed
- [x] FileRateLimiter not reachable from production DI
- [x] Rate-limit semantics unchanged
- [x] Security semantics unchanged (fail-closed)
- [x] Architecture tests PASS (33 / 593 assertions)
- [x] Full PHPUnit PASS (200 tests / 1233 assertions / 0 failures)
- [x] PHPStan PASS (Level 6, 0 errors)
- [x] OpenAPI check PASS (183/183 operations)
- [x] Migration checks PASS (pre-existing known duplicates only)
- [x] Schema drift = 0
- [x] No secrets introduced
