71 Commits
Author SHA1 Message Date
andrew 1335c31d4e Merge pull request 'feat: passkey (WebAuthn) authentication on the auth subdomain' (#20) from feat/passkey-auth-subdomain into main
Sync GitHub / sync (push) Successful in 8s
PHP Test / test (push) Successful in 1m10s
Tests / test (push) Successful in 1m10s
Docker Publish / docker (push) Successful in 1m47s
Push Develop / docker (push) Successful in 1m47s
Reviewed-on: #20
Reviewed-by: Andrew <andrew@digitaladapt.com>
2026-09-27 09:43:13 -04:00
lyra 9523accd23 Close the coverage gaps in the passkey code, fixing what they exposed
PHP Test / test (pull_request) Successful in 51s
Tests / test (pull_request) Successful in 51s
The project's own bar is full coverage, and the new code had drifted from it —
notably every error path, which is exactly where a browser is least likely to
go on purpose and an attacker is most likely to.

Two real bugs surfaced, both of the same shape: a cache failure escaping as a
500 on the login page.

- `credentials->find()` was called outside the try block in `finishLogin()`, so
  a store failure threw instead of reporting a failed ceremony.
- `credentials->save()` was likewise unguarded in `finishRegistration()`, and
  there the consequence was worse: reporting success for a credential that was
  never stored, so the user would believe their passkey was registered and
  discover otherwise only at the next login.

Both now degrade to a failed ceremony, matching the rule the rest of the class
follows: a failure the user cannot act on must never look like a server fault.

Coverage is now at 98.7% of lines; the remainder is pre-existing defensive
catches in AcceptListener/AllowListener plus a couple of unreachable guards.
2026-09-27 11:40:01 +00:00
lyra 6bbfd44e7d Document passkey authentication
Covers the README (prerequisites, the two hard requirements, every new env var,
how registration and login work, and the counter caveat), SECURITY.md (the
ceremony model, single-use challenges, origin handling, the shared rate-limit
budget, and the attestation rationale with the conditions that would reverse
it), CHANGELOG (Added/Security/Changed), ROADMAP (Phase 2c complete, with the
deviations from the original sketch) and DESIGN_CONSIDERATIONS (the four
decisions whose reasoning is not visible in the code).

The docs lead with the two prerequisites because both are enforced rather than
advisory: enabling passkeys without central auth, or on a host that cannot
serve HTTPS, fails at container start. Neither is a runtime surprise, and a
reader needs to know that before they turn the feature on.

The plan document is updated to record that it is complete, and to note the two
places where implementation deviated from it — the listener/extraction order,
and register-begin not being a listener operation. The second was a design
error in the plan, not just an ordering change, so it is called out explicitly.
2026-09-27 11:37:02 +00:00
lyra ffe6870231 Add end-to-end functional tests with real cryptography
The whole flow through the real HTTP kernel, with nothing about the ceremony
stubbed: registration builds a genuine CBOR attestation object signed by a real
P-256 key, and login signs a real assertion. Only the browser's plumbing is
simulated — the fetch() calls become requests, which is the seam worth testing.

Covered: a real registration grants a session; a real passkey login grants a
session and reports the right Remote-User; a bad TOTP starts no ceremony; a
spent nonce starts no ceremony; a replayed ceremony fails; an assertion for
another challenge fails; an unknown credential fails with the same generic
message a wrong code gets; both login paths set an identical cookie; ceremony
responses are not cacheable and do not leak their marker; the ceremony is inert
when disabled; the page offers passkeys only when enabled; and the CSP permits
the two WebAuthn directives.

Writing these found a real bug. The registration checkbox originally submitted
a plain form POST, which returns HTML — and, more importantly, loses the fresh
nonce the failure response issues. The user's next attempt would then fail
against a nonce that had already been spent, with no visible reason why. It now
goes through the same X-Preauth AJAX path as an ordinary login, so failures come
back as JSON with a usable nonce; a non-JSON submission is treated as an
ordinary login, and LoginManager returns null for it rather than starting a
ceremony that nothing could finish.

Three test failures were also correct behaviour rather than bugs: once a session
cookie exists, AcceptListener (priority 99) answers before any ceremony listener
runs, so tests exercising a second ceremony need a visitor without that cookie.
That is the intended ordering, now documented in the tests.
2026-09-27 11:35:54 +00:00
lyra 11903bf746 Add the passkey UI and fix issues it exposed
The login page gains a sign-in button and, where the form actually POSTs, a
"register this device" checkbox. Both are rendered only when the policy says
passkeys are available for that request, so an unavailable configuration stays
byte-identical to before — a test asserts exactly that, rather than trusting the
conditional is in the right place.

The registration checkbox is omitted on hosts the form does not POST from,
because a registration ceremony is authorised by the TOTP code carried in that
submission. The button is still offered there; only the checkbox is not.

Writing the tests surfaced three real problems, all fixed here:

- ConfigBag had no passkeyButtonName()/passkeyRegisterName() accessors, so the
  template referenced configuration that was never exposed.
- ListenerTestHelper's anonymous rate-limiter classes were missing #[Override],
  and the baseline pinned them by line number — so adding two array keys broke
  it. Fixed at the source instead: the attributes are now present, which also
  let 36 line-pinned baseline entries be deleted.
- Those classes threw ReserveNotSupportedException with no arguments, which the
  Symfony signature forbids. The baseline had been hiding this behind
  path-specific ignores; phpstan reports it correctly now.

The net baseline change is 216 deletions and no additions: every entry removed
was one whose underlying issue is now genuinely fixed.
2026-09-27 11:32:16 +00:00
lyra 69ee5e99aa Route passkey registration through the TOTP check, not the listener
Corrects a design error in the previous commit. I had exposed register-begin as
a listener operation and gated it on a session cookie, but the approved flow has
no session at that point: the whole point is that a valid TOTP code is what
authorises registration, and the session is only issued once the new credential
has been verified.

Two consequences, both bad:

- There is no session cookie to check, so the gate could never have worked. It
  would have been dead code that looked like a security control.
- More seriously, a listener-side register-begin would hand out a challenge
  without proving anything. Anyone could obtain ceremony options and attempt
  registration. The cookie check was not a weak control; the operation itself
  was the hole.

Registration is now started by LoginManager, after it has verified both the code
and the nonce, and its options are returned with the login response. That is the
flow in the plan, and it keeps nonce validation in the one place that already
enforces it. The capability for register-finish is the single-use ceremonyId,
which is server-issued and bound to the identity that passed the check.

The listener now serves three operations, and a test pins that register-begin is
not one of them.

Also adds Payload::$register so the checkbox intent survives from the form to
LoginManager, and moves the ceremony marker constant to AppConstants since both
LoginManager and the listener now produce marked responses.
2026-09-27 11:29:17 +00:00
lyra ffb824c652 Add the passkey listener at priority 70
Priority 70 sits after RejectListener (77) and before LoginListener (66), and
both bounds are load-bearing:

- After 77 so a rate-limited IP never reaches a ceremony. Passkeys cannot be
  used to sidestep a lockout (D3), which is the point of the reviewer's third
  clarification.
- Before 66 because LoginListener treats any POST to the auth subdomain as a
  login attempt. A ceremony finish body has no username/totp, so Payload::load()
  returns null and the request would be scored as a failed login, burning a
  rate-limit token for every legitimate passkey login.

Verified in the live container rather than assumed: debug:event-dispatcher
confirms 77 -> 70 -> 66.

Other properties asserted by tests: every header-bearing request gets a JSON
response so fetch() callers never receive HTML; registration identity comes from
the live session, never the request body; a failed ceremony is indistinguishable
from a wrong TOTP code and spends the same shared budget; and begin is bounded
by a separate resource guard that deliberately does not consume failure budget.

The listener also marks its responses so SecurityHeadersListener can apply
no-store: these are the only browser-facing 2xx this application produces, since
the auth subdomain has no forward_auth in front of it. CSP gains
publickey-credentials-get/-create only when passkeys are available, so the
unavailable case stays byte-identical to before.
2026-09-27 10:50:09 +00:00
lyra fed7b1b48c Extract session issuing so both login paths share it
SessionIssuer now owns 'grant access after authenticating', which LoginManager
previously did internally. The passkey ceremony needs the same behaviour, and
two implementations would inevitably drift — most likely in cookie attributes,
where a difference stays invisible until it breaks in a browser.

LoginManager keeps what is specific to code-based login: verifying the TOTP or
backup code and enforcing the single-use nonce. Its 18 existing tests pass
unchanged, which is the evidence that this is behaviour-preserving rather than a
rewrite.

Also folds the redundant early-return into a single guard in checkToken so the
success path reads straight through.
2026-09-27 10:45:58 +00:00
lyra 436450cdc2 Add passkey ceremony store and manager
Builds both WebAuthn ceremonies on top of the library, with real cryptography
proven in tests rather than stubbed:

- PasskeyCeremonyStore: server-authoritative, single-use challenge state in the
  nonceCache pool. The client's challenge copy is never trusted, and consume()
  deletes before verifying so a replay cannot retry the same challenge.
- PasskeyManager: registration and login ceremonies. Library types are confined
  to this class and PasskeyCeremonyFactory. Failures return null rather than
  distinguishing unknown-credential from bad-signature, so the endpoint is not
  an enumeration oracle.
- PasskeyTestHelper: builds genuinely valid ceremonies (real P-256 keypair,
  COSE key, signed authenticatorData, CBOR attestation object).
- PasskeyRealCryptoSpikeTest: proves registration and assertion verify, that
  http:// origins are refused (D4), that challenges and rpIdHash are bound, and
  that a synchronised passkey with a constant zero counter can log in repeatedly.
2026-09-27 10:42:59 +00:00
lyra 69609db8af Use a lenient signature-counter check for passkeys
The library default (ThrowExceptionIfInvalid) requires the reported counter to
be strictly greater than the stored one. Synchronised passkeys report a
constant 0 forever, so the default rejects a brand-new credential on its first
login — and only on real hardware, never in a unit test that increments the
counter.

The replacement still rejects a counter that moves backwards, which is the only
signal the counter can carry. Clone detection remains explicitly not a property
this feature claims; see SECURITY.md.
2026-09-27 10:38:02 +00:00
lyra c84cf8c308 Add passkey credential store
Persistence for registered passkeys, backed by sessionCache so credentials
survive a container restart the way sessions do.

The pool is wrapped in MonitorCacheKeys, matching LoginManager and
BackupCodeManager. Without that wrapper the credentials would live only in the
APCu-side pool and vanish on the next restart, because PersistCache::persist()
only flushes keys a monitor recorded. A test asserts visibility to the
persistent pool rather than trusting the wrapper.

Two storage hazards found while building this and covered by tests:

  - makeCacheKey() is not injective for base64url. It collapses the whole
    punctuation alphabet to "_", so "abc-def" and "abc_def" would share one
    cache slot and one credential would silently overwrite the other.
    Credential ids are therefore hashed, and a test uses precisely that pair.
  - A record's own credential id is authoritative. An index entry pointing at
    a record that disagrees with its key is rejected rather than trusted.

Unreadable or wrong-shaped entries degrade to "credential unavailable" so a
corrupt value cannot 500 the login page.

PasskeyCeremonyFactory is the single seam onto webauthn-lib: it builds the
serializer and pins attestation to `none` only, so a future version that moves
or renames library types touches one file.

Suite: 353 tests / 831 assertions, 100% coverage on all new files.
phpstan level 6 clean, php-cs-fixer clean, conformance 35/35.
2026-09-27 02:40:31 +00:00
lyra 108e9623e6 Add passkey configuration and availability policy (inert)
Groundwork for passkey authentication, with the feature switched off by
default and no behaviour change when it is off.

Decision D1: passkeys require central authentication. A passkey is scoped to
a relying party spanning the base domain, which only exists when
SUBDOMAIN_REDIRECT is on and AUTH_SUBDOMAIN resolves to a base domain. The
RP ID is therefore always that base domain, never the request host.

Decision D4: HTTPS is required and is not exemptible. The allowed origin is
built as https://{authSubdomain} from configuration and never from the
request, so an http:// origin cannot be accepted, and isAvailableFor()
additionally refuses to offer the UI on a non-secure connection. The
deprecated setSecuredRelyingPartyId() escape hatch is not used and there is
deliberately no override that could reintroduce one.

Enabling PASSKEY_ENABLED without a usable configuration is a hard error via
a non-optional cache warmer, because entrypoint.sh runs cache:warmup on every
production boot: a misconfigured deployment fails to start instead of
offering a button that cannot work.

Also drops 12 obsolete phpstan-baseline entries for TotpTestHelper: adding
#[\Override] to its anonymous clock removed the rule violation at its source
rather than suppressing it.

Suite: 333 tests / 770 assertions (was 313 / 738), 100% coverage on new
files. phpstan level 6 clean, php-cs-fixer clean, conformance 35/35.
2026-09-27 02:37:07 +00:00
lyra 0458d9b8d2 minor text formatting change
Sync GitHub / sync (push) Successful in 7s
Docker Publish / docker (push) Successful in 20s
Push Develop / docker (push) Successful in 20s
PHP Test / test (push) Successful in 50s
Tests / test (push) Successful in 50s
2026-09-25 19:22:33 -04:00
andrew 8cd06838d3 trailing comma for code standards
Sync GitHub / sync (push) Successful in 7s
PHP Test / test (push) Successful in 54s
Tests / test (push) Successful in 55s
Docker Publish / docker (push) Successful in 56s
Push Develop / docker (push) Successful in 56s
Docker Publish / docker (push) Successful in 23s
Push Docker / docker (push) Successful in 23s
2026-09-25 12:42:25 -04:00
andrew 54990dafc6 Using cache pool by variable name is deprecated,
Sync GitHub / sync (push) Successful in 7s
PHP Test / test (push) Failing after 54s
Tests / test (push) Failing after 54s
Docker Publish / docker (push) Successful in 58s
Push Develop / docker (push) Successful in 58s
so we've added target attributes.
2026-09-25 12:32:43 -04:00
andrew 06e2ca8b19 Merge pull request 'chore(ci): re-vendor conformance.sh so the audit/validate checks see the shared-workflow pin' (#19) from fix/conformance-revendor into main
Sync GitHub / sync (push) Successful in 7s
Docker Publish / docker (push) Successful in 21s
Push Develop / docker (push) Successful in 21s
PHP Test / test (push) Successful in 51s
Tests / test (push) Successful in 51s
Reviewed-on: #19
Reviewed-by: Andrew <andrew@digitaladapt.com>
2026-09-25 11:53:23 -04:00
lyra 4d5afa20e9 chore(ci): re-vendor conformance.sh (follow the shared-workflow pin)
PHP Test / test (pull_request) Successful in 54s
Tests / test (pull_request) Successful in 54s
private/ci gained the fix that makes ci-composer-audit / ci-composer-validate
follow a project's shared-workflow pin (`uses: private/ci/.../php-test.yaml@v1`)
instead of grepping for inline workflow text that an adopted repo no longer
contains.

That file is VENDORED into this repo at .ci/ (by design — §8.2, so CI never
fetches from the LAN-only private/ci at run time), so moving the v1 tag
updated the workflow but not this copy. Re-vendored with sync-configs.sh.

Before: 2 of 34 checks failed (the two false positives).
After:  All 35 runnable checks passed.

Also brings .ci/validate-bake.py, which the new checker's bake-target-exists
check needs; without it that check correctly reports SKIPPED rather than
silently passing.
2026-09-25 15:27:18 +00:00
andrew 74902c0fc7 adding intl
Sync GitHub / sync (push) Successful in 9s
PHP Test / test (push) Successful in 1m11s
Tests / test (push) Successful in 1m11s
Docker Publish / docker (push) Successful in 17m19s
Push Develop / docker (push) Successful in 17m19s
2026-09-25 10:22:08 -04:00
andrew bd2f5cbac3 removed problematic opcache line from dockerfile
Sync GitHub / sync (push) Successful in 7s
Docker Publish / docker (push) Successful in 7m6s
Push Develop / docker (push) Successful in 7m6s
PHP Test / test (push) Successful in 1m5s
Tests / test (push) Successful in 1m5s
2026-09-25 09:49:46 -04:00
andrew 51e921f54f now syncing github via shared workflow
Sync GitHub / sync (push) Successful in 7s
Docker Publish / docker (push) Failing after 49s
Push Develop / docker (push) Failing after 49s
PHP Test / test (push) Successful in 1m10s
Tests / test (push) Successful in 1m10s
2026-09-25 09:03:42 -04:00
andrew ba8924a244 Merge pull request 'docker to be more inline with other projects and best practices' (#18) from feat/refactoring into main
Sync GitHub / sync (push) Successful in 8s
Docker Publish / docker (push) Failing after 54s
Push Develop / docker (push) Failing after 54s
PHP Test / test (push) Successful in 57s
Tests / test (push) Successful in 57s
Reviewed-on: #18
2026-09-25 08:50:24 -04:00
lyra 538bd74100 docker to be more inline with other projects and best practices
PHP Test / test (pull_request) Successful in 52s
Tests / test (pull_request) Successful in 52s
2026-09-25 08:25:55 -04:00
andrew db0cf77049 normalizing workflow and build files
Sync GitHub / sync (push) Successful in 6s
Docker Publish / docker (push) Successful in 18s
Push Develop / docker (push) Successful in 18s
PHP Test / test (push) Successful in 1m5s
Tests / test (push) Successful in 1m5s
2026-09-24 16:41:42 -04:00
lyra ef924472a3 normalizing workflow content
Sync GitHub / sync (push) Successful in 7s
Docker Publish / docker (push) Successful in 22s
Push Develop / docker (push) Successful in 23s
Tests / test (push) Successful in 1m19s
2026-09-24 09:05:07 -04:00
lyra 539385c438 finish moving to central CI.
Sync GitHub / sync (push) Successful in 7s
Tests / test (push) Successful in 1m12s
Docker Publish / docker (push) Successful in 21s
Push Develop / docker (push) Successful in 22s
2026-09-23 17:37:49 -04:00
lyra eed6b4dbff moment of truth, trying to use central CI for docker image build, starting with just develop.
Sync GitHub / sync (push) Successful in 7s
Tests / test (push) Successful in 1m12s
Docker Publish / docker (push) Successful in 5m1s
Push Develop / docker (push) Successful in 5m1s
2026-09-23 17:34:15 -04:00
andrew 2b61a43f60 Merge pull request 'build: define the Docker build in docker-bake.hcl' (#17) from chore/docker-bake into main
Sync GitHub / sync (push) Successful in 7s
Tests / test (push) Successful in 1m19s
Push Develop / docker (push) Successful in 4m41s
Reviewed-on: #17
Reviewed-by: Andrew <andrew@digitaladapt.com>
2026-09-23 17:30:04 -04:00
lyra abe94c6238 build: define the Docker build in docker-bake.hcl
Tests / test (pull_request) Successful in 1m15s
The build was described in two places kept in step by hand: the Dockerfile, and
the `with:` block of each docker workflow file. This moves the parts CI actually
decides — Dockerfile target, platforms, tags, build args — into docker-bake.hcl,
so the build is version-controlled with the code and reviewable in a diff.

Tags are byte-identical to the current workflows, verified with
`buildx bake --print`:

  main push   -> digitaladapt/preauth:develop
  tag v1.2.0  -> digitaladapt/preauth:latest AND digitaladapt/preauth:1.2.0

Dockerfile: the final stage gains `AS app` so bake can target it. Naming the
last stage is a no-op for a plain `docker build` — it is still the default
target — so `docker build .` behaves exactly as before.

THREE THINGS FOUND WHILE DOING THIS
-----------------------------------

1. `buildx bake --print` does NOT read the Dockerfile, so it accepts a `target`
   naming no stage. preauth's final stage was unnamed, so `target = "app"` would
   have failed at build time in CI *after the push*, with --print reporting
   success. Fixed by naming the stage.

2. The `bake` backend in docker-publish.yaml sets no layer cache, while the
   `action` backend it replaces sets cache-from/cache-to: type=gha. Neither
   existing bake user in the portfolio sets one either, so every bake build in
   the portfolio runs cold. preauth compiles APCu from source (pecl) in both
   stages, so this would have been a real regression. The bake file now sets the
   gha cache, with the override for local builds documented.

3. `ARG MAX_REQUESTS` has been documented in the Dockerfile since the Symfony
   8.1 upgrade, but no workflow ever passed it, so CI silently built with the
   500 default. It is now an explicit named variable, overridable per build.

The workflow callers that select the bake backend are NOT in this commit:
.gitea/workflows/ is protected by a pre-receive hook and only changes via a
trusted ref. They are staged in the working tree.

Verified: Dockerfile stage/target contract holds; bake file parses and resolves
under buildx 0.37; 313 tests pass; conformance 31/34 with callers staged.
2026-09-23 21:01:53 +00:00
andrew 1e186c9354 Merge pull request 'chore: adopt shared Guiding Light configs, fix conformance gaps (18/34 → 30/34)' (#16) from chore/adopt-guiding-light into main
Sync GitHub / sync (push) Successful in 8s
Tests / test (push) Successful in 1m8s
Push Develop / docker (push) Successful in 6m53s
Reviewed-on: #16
Reviewed-by: Andrew <andrew@digitaladapt.com>
2026-09-23 16:40:51 -04:00
lyra 2064153cd3 chore: adopt shared Guiding Light configs and fix conformance gaps
Tests / test (pull_request) Successful in 1m10s
Brings preauth from 18/34 to 30/34 conformance (auth-gateway profile). The
remaining four checks all depend on files this branch cannot change (see below).

PHP toolchain (§1)
  - require.php  >=8.4 -> ^8.5, and pin config.platform to 8.5.0. The old
    constraint also permitted PHP 9, which is not a promise we can keep.
    composer.lock regenerated with --lock: content-hash + platform-overrides
    only, zero dependency version movement.
  - friendsofphp/php-cs-fixer  * -> ^3.95. A wildcard meant CI was not
    reproducible.

PHPStan (§2.2)
  - vendor the shared phpstan.neon.dist (level 6) + a generated baseline.
    187 errors are captured rather than fixed; the baseline should only shrink
    from here.
  - add phpstan/phpstan:^2.1 to require-dev.

Code style (§8.2)
  - vendor the shared .php-cs-fixer.dist.php (@Symfony + @Symfony:risky +
    declare_strict_types) and apply it: 59 of 67 files reformatted.
  - Verified this is a formatting change, not a behaviour change: all 313 tests
    pass after the reformat, all in_array() calls already passed strict=true,
    and the remaining edits are @Symfony:risky idiom (yoda conditions, \count(),
    self:: over the class name).

Repository layout (§4.4)
  - docs/{Caddyfile,compose.yaml,example.env} -> docs/examples/, with
    example.env becoming the conventional .env.example. This is the layout
    GUIDING-LIGHT already cites preauth as doing correctly — it just needed
    renaming.
  - update the four readme.md references and a stale compose.yaml comment.
  - docs/v1.1-plan.md references are left alone deliberately: it is a historical
    plan recording what was done at the time, not live documentation.

Licence and security policy (§7)
  - add LICENSE (uniform MIT, matching composer.json).
  - add SECURITY.md describing the actual threat model: per-request
    allow/intercept, no caching of the login flow, app-set security headers,
    TOTP, and the fact that REMOTE_USER is trusted input.

Mobile accessibility (§3.3a)
  - templates/base.html.twig: drop maximum-scale=1 and add viewport-fit=cover.
    preauth was the one app already past the font-size precondition (controls
    render at 21.6px = 0.9em x 24px), so removing the lock is safe here and
    restores pinch-zoom for Android users.

Conformance tooling (§8.2)
  - vendor .ci/conformance.sh and .ci/css-control-size.py so the check runs
    from a checkout rather than fetching from the LAN-only private/ci.
  - .editorconfig synced from the version that keeps the Caddyfile tab rule.

Not included (blocked by the .gitea/workflows pre-receive hook):
  - ci-composer-audit, ci-composer-validate, ci-reusable-workflows.
    Workflow files may only change via a trusted ref, so the caller files are
    staged but not committed.

Also not included: dockerfile-nonroot (§6.4). Adding USER to an image with
VOLUME [/config, /data] changes volume ownership and needs an actual container
build/run to verify, so it goes in its own change.
2026-09-23 20:13:45 +00:00
andrew 054b8ef48f Merge pull request 'fix: never cache the login flow (stale pre-auth responses in Safari)' (#12) from fix/login-flow-cache-control into main
Sync GitHub / sync (push) Successful in 10s
Tests / test (push) Successful in 1m35s
Push Develop / docker (push) Successful in 6m3s
Push Docker / docker (push) Successful in 8m45s
Reviewed-on: #12
Reviewed-by: Andrew <andrew@digitaladapt.com>
2026-09-14 21:56:59 -04:00
lyra 5258e175a1 fix: never cache the login flow (stale pre-auth responses in Safari)
Tests / test (pull_request) Successful in 1m8s
The login page, failed logins, redirects, and rate-limit/error pages could
be stored by the browser (Symfony's default 'no-cache, private' still
permits storage — it only requires revalidation). Older Safari builds may
then replay a stale pre-auth response on refresh, appearing to log the
user back out, or show a previous session after logging in again.

- SecurityHeadersListener: send strict anti-caching headers on non-2xx
  responses only (no-store/no-cache/must-revalidate/proxy-revalidate,
  max-age=0, s-maxage=0 + Pragma, Expires, Surrogate-Control, Vary: *).
  2xx grants (already-authenticated / public access) are consumed by
  Caddy's forward_auth check and never reach the browser, and protected
  services' own cache headers must stay untouched.
- templates/_script.html.twig: fetch() with cache: 'no-store'; follow
  redirects with location.replace() to keep the login page out of history
  and the back-forward cache.
- docs/Caddyfile: reusable (preauth_no_store) snippet imported into every
  forward_auth block, using header_down so the guarantee holds at the edge
  (verified: replaces conflicting upstream values, leaves service
  responses alone).
- tests: unit coverage for the listener and functional coverage for the
  full HTTP kernel (login/failure/redirect/rate-limit not cacheable;
  200 grants untouched); asserts the rendered page carries the JS changes.
- readme/CHANGELOG updates.
2026-09-14 19:31:44 -04:00
andrew 2f7ae31ba1 Merge pull request 'feat: upgrade Symfony 7.4 → 8.1, drop runtime/frankenphp-symfony' (#11) from feat/symfony-8.1-upgrade-plan into main
Sync GitHub / sync (push) Successful in 8s
Tests / test (push) Successful in 1m21s
Push Develop / docker (push) Successful in 4m49s
Reviewed-on: #11
Reviewed-by: Andrew <andrew@digitaladapt.com>
2026-09-12 16:51:29 -04:00
lyra baf976a8e6 feat: restore worker recycle limit via Caddyfile max_requests (default 500)
Tests / test (pull_request) Successful in 1m4s
The removed runtime/frankenphp-symfony package force-restarted the
worker after FRANKENPHP_LOOP_MAX requests (default 500) - memory-leak
paranoia the built-in 8.1 runner intentionally doesn't reimplement.

Restore the behavior natively so the upgrade is a no-op operationally:
- Caddyfile: global frankenphp block with max_requests {$MAX_REQUESTS}
  - per-thread graceful restarts, other threads keep serving
- Dockerfile: ARG/ENV MAX_REQUESTS=500 bakes the same default the old
  package had, overridable at docker build or runtime (-e, 0 disables)
- Stock FRANKENPHP_CONFIG env var remains the full-config escape hatch
- Documented in readme env table, docs/example.env, CHANGELOG, and the
  upgrade plan (phase-4 staging note now checks thread recycling)
2026-09-08 06:15:20 -04:00
lyra af4d2a4ac7 docs: record Symfony 8.1 upgrade results, update stack references
Tests / test (pull_request) Successful in 1m7s
- Plan doc: mark Phases 0-3 + worker-mode state audit complete with
  verified results; resolve open questions (all src/ services are final
  readonly - no ResetInterface needed under kernel-reusing runner)
- CHANGELOG: Unreleased entries for the 8.1 bump and the
  runtime/frankenphp-symfony removal (incl. FRANKENPHP_LOOP_MAX note)
- ROADMAP: current stack now Symfony 8.1; webauthn research note updated
- bin/dev.sh: correct stale PHP requirement comment
2026-09-07 22:46:22 -04:00
lyra c743a1baac feat: upgrade Symfony 7.4 -> 8.1, drop runtime/frankenphp-symfony
- All symfony/* constraints bumped 7.4.* -> 8.1.* (resolved to 8.1.2-8.1.6)
- Removed runtime/frankenphp-symfony: symfony/runtime 8.1 handles
  FrankenPHP worker mode natively via FrankenPhpWorkerRunner; deleted
  the extra.runtime class override so GenericRuntime auto-detects it
- phpunit 13.3.2, twig 3.28, otphp 11.5 ride along
- Deprecation sweep on 7.4 was clean (failOnDeprecation suite, zero hits)
- Verified: bin/console about boots on 8.1.6; 295 tests / 612 assertions
  green after the bump
2026-09-07 22:40:17 -04:00
lyra 3f1778cd6b docs: add Symfony 7.4 -> 8.1 upgrade plan
Covers deprecation sweep gate, composer.json constraint bumps to 8.1.*,
and removal of runtime/frankenphp-symfony (FrankenPHP worker mode is
handled natively by symfony/runtime in 8.x). Includes config recipe
re-sync, Docker/CI notes, phased rollout with rollback, and open
questions (kernel-reset audit for worker mode).
2026-09-07 22:26:00 -04:00
andrew 33181f11d8 testing branch is safe now that git hook protections have been setup
Sync GitHub / sync (push) Successful in 10s
Tests / test (push) Successful in 1m10s
Push Develop / docker (push) Successful in 4m44s
Push Docker / docker (push) Successful in 4m53s
2026-08-30 22:24:50 -04:00
andrew bb2cc3ce49 only test and push select branches
Sync GitHub / sync (push) Successful in 8s
Tests / test (push) Successful in 1m9s
Push Develop / docker (push) Successful in 4m48s
2026-08-27 21:55:07 -04:00
andrew e4f54769e6 use main branch workflow
Sync GitHub / sync (push) Successful in 7s
Tests / test (push) Successful in 1m1s
Push Develop / docker (push) Successful in 4m45s
Push Docker / docker (push) Successful in 10m28s
2026-08-25 20:22:12 -04:00
andrew b75a16a781 Merge remote-tracking branch 'origin/fix/ci-github-rate-limit' into develop
Sync GitHub / sync (push) Successful in 8s
Push Develop / docker (push) Successful in 4m55s
Tests / test (push) Successful in 59s
Push Docker / docker (push) Successful in 4m42s
2026-08-21 16:11:31 -04:00
andrew 9111958bcf Merge branch 'main' into develop 2026-08-21 16:10:30 -04:00
andrew 95dc6bf0ce Merge branch 'main' into fix/ci-github-rate-limit
Sync GitHub / sync (push) Successful in 6s
2026-08-20 16:27:52 -04:00
lyra 472abfdf89 fix(ci): cache composer deps and authenticate to GitHub
Tests / test (pull_request) Successful in 1m21s
Tests / test (push) Successful in 1m30s
Push Develop / docker (push) Successful in 5m12s
Sync GitHub / sync (push) Successful in 9s
The test workflow was hitting GitHub's unauthenticated API rate
limit (60 req/hour) when downloading 95 packages via composer
install --prefer-dist, causing 429 Too Many Requests errors.

Two fixes applied:
1. Cache Composer's download cache (~/.composer/cache) keyed on
   composer.lock hash, so repeated CI runs don't re-download
   packages at all.
2. Configure GitHub OAuth token via SYNC_GITHUB_TOKEN secret to
   raise the rate limit to 5,000 req/hour for cache misses.
2026-08-17 12:03:14 -04:00
lyra e2780ca5f6 fix: allow same-origin fetch in CSP when inline login script is used
Tests / test (pull_request) Successful in 49s
Sync GitHub / sync (push) Successful in 9s
Tests / test (push) Successful in 1m1s
Push Develop / docker (push) Successful in 4m47s
Push Docker / docker (push) Successful in 7m35s
When subdomain redirection is off, the login form is served inline on
the protected host and submission happens via a same-origin fetch() call
in _script.html.twig. The CSP default-src 'none' was blocking that
fetch (connect-src falls back to default-src).

Add connect-src 'self' to the CSP only when the request is not on the
auth subdomain (i.e. when the inline script is present). On the auth
subdomain the form POSTs normally with no inline script, so the stricter
policy still applies there.

This is the least-privilege relaxation: only same-origin connections,
only on pages that need them.
2026-08-17 11:27:46 -04:00
andrew 7a68c933ce Merge pull request 'fix: handle host-prefixed root path in PublicPathMatcher' (#8) from fix/public-path-host-root into main
Push Develop / docker (push) Successful in 4m44s
Sync GitHub / sync (push) Successful in 7s
Tests / test (push) Successful in 45s
Push Docker / docker (push) Successful in 4m43s
Reviewed-on: #8
Reviewed-by: Andrew <andrew@digitaladapt.com>
2026-08-13 16:28:05 -04:00
andrew 55f8e9e84c Merge branch 'main' into fix/public-path-host-root
Sync GitHub / sync (push) Successful in 9s
Tests / test (pull_request) Successful in 1m16s
2026-08-13 15:43:54 -04:00
lyra e3cd8c6739 fix: handle host-prefixed root path in PublicPathMatcher
Sync GitHub / sync (push) Successful in 6s
Tests / test (pull_request) Successful in 1m3s
The host-prefix regex required at least one character after the slash
(/\+.+/), so a pattern like 'code.example.com/' was silently dropped
instead of matching the root path '/'. Changed \+.+ to \+.* so the
trailing slash alone is accepted as the path '/'.

Added tests covering the exact bug scenario from PUBLIC_PATHS
config: 'code.digitaladapt.com/,code.digitaladapt.com/public/**'
2026-08-13 14:30:52 -04:00
lyra 235a7866b3 fix: remove incorrect CSS escaping on color values
Tests / test (pull_request) Successful in 1m5s
Push Develop / docker (push) Successful in 6m43s
Sync GitHub / sync (push) Successful in 8s
Tests / test (push) Successful in 54s
The Twig |e('css') filter was escaping '#' (0x23) to '\23 ' in hex
color values (bg_color, fg_color, error_color), causing browsers to
not recognize them as valid CSS colors. These are admin-configured
environment variables, not user input, so CSS escaping is unnecessary.
2026-08-13 12:07:20 -04:00
lyra c7585e720a feat: add self-bootstrapping dev server script (bin/dev.sh)
Tests / test (pull_request) Successful in 50s
Push Develop / docker (push) Successful in 8m39s
Sync GitHub / sync (push) Successful in 7s
Tests / test (push) Successful in 57s
Manages a local PHP dev server for end-to-end development and testing.
Binds to 0.0.0.0:8773, accessible via Caddy at
https://preauth.lyra-dev.devgnome.com.

Features:
- Self-bootstrapping: installs PHP 8.4 + extensions (including APCu,
  which is critical for nonce cache, rate limiter, and session storage),
  Composer, and project dependencies if missing. Survives terminal
  resets/reboots.
- Enables apc.enable_cli=1 for console commands (matches Dockerfile)
- Subcommands: start, stop, status, restart
- Sets APP_SHARE_DIR to var/share for filesystem session persistence
- Clears dev cache on start

No database needed — preauth uses APCu + filesystem cache exclusively.

Port assignment: P-R-E = 7-7-3 → 8773
2026-08-13 11:56:55 -04:00
andrew 66b960ccea Merge pull request 'feat: v1.1 — public rate-limited access' (#5) from feat/v1.1-public-access into main
Push Develop / docker (push) Successful in 4m47s
Sync GitHub / sync (push) Successful in 7s
Tests / test (push) Successful in 55s
Push Docker / docker (push) Successful in 4m46s
Reviewed-on: #5
Reviewed-by: Andrew <andrew@digitaladapt.com>
2026-08-13 01:30:13 -04:00
andrew 17c2d525ff Merge branch 'main' into feat/v1.1-public-access
Sync GitHub / sync (push) Successful in 13s
Tests / test (pull_request) Successful in 54s
2026-08-13 01:19:08 -04:00
andrew 72c41fec77 Merge pull request 'fix: v1.0 release — security hardening, code quality, and documentation' (#4) from fix/v1.0-must-fix into main
Push Develop / docker (push) Successful in 4m47s
Sync GitHub / sync (push) Successful in 8s
Tests / test (push) Successful in 57s
Push Docker / docker (push) Successful in 4m48s
Reviewed-on: #4
Reviewed-by: Andrew <andrew@digitaladapt.com>
2026-08-12 22:31:59 -04:00
lyra 29e471c536 Merge branch 'fix/v1.0-must-fix' into feat/v1.1-public-access
Push Develop / docker (push) Successful in 6m1s
Sync GitHub / sync (push) Successful in 7s
Tests / test (push) Successful in 1m3s
2026-08-12 11:21:42 -04:00
lyra 44e4c60f80 fix: restore develop branch trigger support for CI workflows
Tests / test (pull_request) Successful in 1m1s
Push Develop / docker (push) Successful in 6m29s
Sync GitHub / sync (push) Successful in 10s
Tests / test (push) Successful in 1m0s
Re-adds 'develop' to push triggers in develop.yaml and tests.yaml
so the :develop Docker image can be built from the develop branch,
enabling dev testing without requiring a merge to main.
2026-08-12 11:21:37 -04:00
lyra 5563999525 feat: public rate-limited access for v1.1
Sync GitHub / sync (push) Successful in 8s
Add PublicAccessListener (priority 84) that allows rate-limited
unauthenticated access to configured public paths. Authenticated users
bypass this listener entirely via AcceptListener/AllowListener.

New components:
- PublicPathMatcher service with wildcard path matching (* and **)
  and optional host-prefix scoping
- PublicAccessListener applying per-IP rate limiting to public paths
- Separate public_limiter compound rate limiter (burst + sustained)
- publicRateLimitCache pool (APCu in prod, array in tests)

New env vars:
- PUBLIC_PATHS (comma-separated path patterns, empty = disabled)
- PUBLIC_BURST_COUNT/PUBLIC_BURST_TIME (default 100/60s)
- PUBLIC_UPPER_COUNT/PUBLIC_UPPER_TIME (default 500/3600s)

Tests: 52 new tests (29 unit for PublicPathMatcher, 12 unit for
PublicAccessListener, 11 functional for PublicAccessFlowTest).
Total: 293 tests, 605 assertions, all passing.
PHP CS Fixer: 0 of 63 files need fixing.

Documentation: README, CHANGELOG, ROADMAP, Caddyfile, example.env
all updated with public access configuration and examples.
2026-08-12 09:26:50 -04:00
lyra 9ad54f8e2a feat: configurable Remote-User header (design consideration 1.2)
Sync GitHub / sync (push) Successful in 7s
Tests / test (pull_request) Successful in 58s
Add REMOTE_USER env var with four modes:
- session (default): sends session id, backward-compatible
- static: sends a fixed string (REMOTE_USER_STATIC)
- mapped: looks up session id in REMOTE_USER_MAP
- none: omits the header entirely

New RemoteUserMode enum, ConfigBag parsing/validation, and
StringTrait::authSuccessResponse resolves the header value based
on the configured mode. AcceptListener now receives ConfigBag as
a constructor dependency.

Addresses design consideration 1.2 (Remote-User header value is
user-controlled) from DESIGN_CONSIDERATIONS.md.

241 tests pass, 0 cs-fixer violations.
2026-08-11 22:48:52 -04:00
lyra 2258839bd6 docs: update DESIGN_CONSIDERATIONS.md to reflect addressed items
Sync GitHub / sync (push) Successful in 8s
- Mark all resolved items with ✅ and describe the fix applied
- Mark remaining open items with ⬜ and keep recommendations
- Add new sections for items discovered during the fix work:
  - 1.7 CSS injection in style template
  - 1.8 ->json null safety
  - 1.9 validReturn() parse_url false check
  - 1.10 Incomplete TLD list
  - 2.8 Duplicated response construction
  - 2.9 Duplicated constants
  - 5.3 Kernel::terminate() try/finally
  - 9. CI & Workflows (tag format, stale branches, publish.yaml)
- Update 'What's Done Well' to reflect new improvements
- Add summary noting this is a living document tracking the
  fix/v1.0-must-fix branch state
2026-08-11 17:02:27 -04:00
lyra 408d75dda1 chore: nice-to-have improvements for v1.0
Sync GitHub / sync (push) Successful in 8s
Code quality:
- Create AppConstants class with shared constants:
  - FAR_FUTURE_DATE (replaces duplicated '2999-12-31' strings)
  - MAX_INPUT_LENGTH (replaces duplicated 128 in Payload and StringTrait)
- Extract duplicated 'hi $id' response body into StringTrait::authSuccessResponse()
  method, used by AcceptListener, AllowListener, and LoginManager
- Add missing @throws InvalidArgumentException annotations to
  MonitorCacheKeys (getItem, hasItem, deleteItem, deleteItems, commit)

Configuration:
- Add proper env var type casting in services.yaml:
  - COOKIE_TTL → env(int:)
  - SUBDOMAIN_REDIRECT → env(bool:)
  - IP_TTL → env(int:)
  - TEAPOT → env(bool:)

Documentation:
- Create CONTRIBUTING.md with development setup, code style,
  testing guidelines, and PR process
2026-08-11 16:37:23 -04:00
lyra b89070e985 fix: should-fix items for v1.0 release
Documentation:
- Create CHANGELOG.md with full version history (v0.0.1 through unreleased)
- Rewrite README with comprehensive setup guide, configuration reference,
  architecture overview, security model, and feature list
- Update ROADMAP.md: fix branch status table, mark completed security
  review items, update TOTP leeway description
- Fix 'centeral' typo in docs/Caddyfile
- Remove TODO comment from docs/compose.yaml
- Add DESIGN_CONSIDERATIONS.md (design review document)

Code quality:
- Extract duplicated cookie name/domain logic into CookieNameTrait
  methods: sessionCookieName() and sessionCookieDomain()
- Update AcceptListener, AllowListener, InterceptListener, and
  LoginManager to use the shared methods
- Remove fragile cross-file coupling comment between LoginManager
  and InterceptListener

Error handling:
- Wrap cache operations in AcceptListener and AllowListener with
  try/catch to fail closed (don't authenticate on cache errors)
- Log cache errors at error level instead of propagating as 500s
- Early return pattern in AcceptListener and AllowListener for
  cleaner control flow
2026-08-11 16:35:27 -04:00
lyra d2eb914637 fix: must-fix items for v1.0 release
Security:
- Add SecurityHeadersListener (X-Content-Type-Options, X-Frame-Options,
  CSP, Referrer-Policy, HSTS)
- Replace document.write() with document.documentElement.innerHTML
  in login JS to avoid CSP violations
- Add CSS escaping (|e('css')) to env color values in _style.html.twig
- Document CSRF protection model: nonce serves as CSRF token for POST
  form path (single-use, server-generated, 120s TTL)
- Reduce TOTP verification window from 10 periods (±5 min) to 1 (±30s)
- Remove hardcoded APP_SECRET from bin/franken.sh (now uses env or
  generates random)
- Remove backup code values from debug log output
- Add .env to .gitignore

Bug fixes:
- Fix ->json access on possibly-null  in LoginListener
  (uses null-safe operator ?->)
- Fix validReturn() not checking false from parse_url (could cause
  TypeError on malformed URLs)
- Add isHit() race condition check in AcceptListener and AllowListener
- Add try/finally in Kernel::terminate() so parent::terminate() always
  runs even if persist() throws
- Add input validation to GenerateBackupCodesCommand (reject count < 1)
- Use Response::HTTP_INTERNAL_SERVER_ERROR constant in GetTotpTrait
  instead of literal 500

Docker/CI:
- Explicitly install curl in Docker final image (needed for healthcheck)
- Update workflow tag pattern to v*.*.* (standardize on v-prefix)
- Extract version without v-prefix for Docker image tag
- Remove stale develop branch from CI triggers
- Fix publish.yaml git remote add to use set-url on re-runs

Code quality:
- Add declare(strict_types=1) to all interface files
- Add #[AsCommand] attribute to GenerateBackupCodesCommand
- Fix BackupCodeInterface default count to match implementation (10)
- Lowercase host before TLD lookup in DomainManager
- Expand TLD list with many missing multi-part TLDs (.com.au, .co.jp,
  .com.br, .co.kr, .com.tw, .co.za, etc.) to prevent open redirect
  vulnerabilities
- Disable unused Symfony sessions in framework.yaml

Tests:
- Update DomainManagerTest for corrected TLD parsing (.com.au, .co.jp,
  .com.br now correctly recognized as multi-part)
- Update GetTotpTraitTest for corrected error message
- Update GenerateBackupCodesCommandTest: zero count now throws exception
2026-08-11 16:33:00 -04:00
andrew c0bda8aeec Merge pull request 'chore: add php-cs-fixer with PSR-12 config and CI check' (#3) from chore/add-php-cs-fixer into main
Push Develop / docker (push) Successful in 4m48s
Sync GitHub / sync (push) Successful in 8s
Tests / test (push) Successful in 1m14s
Push Docker / docker (push) Successful in 4m44s
Reviewed-on: #3
2026-08-11 09:58:51 -04:00
lyra cb378e20bc chore: add php-cs-fixer with PSR-12 config and CI check
Sync GitHub / sync (push) Failing after 5s
Tests / test (pull_request) Successful in 49s
- Add friendsofphp/php-cs-fixer to require-dev
- Create .php-cs-fixer.dist.php configured for @PSR12 ruleset
- Add php-cs-fixer dry-run step to CI pipeline
- Auto-fix existing PSR-12 violations
- Document code style tooling in readme.md
2026-08-11 08:30:05 -04:00
lyra 6b5a711fa9 Fix docs, add .dockerignore, fix base64url padding, fix typo
Sync GitHub / sync (push) Successful in 7s
Tests / test (pull_request) Successful in 42s
- Add .dockerignore to exclude .git, vendor, var, tests, docs, .env
  and other non-build files from Docker context
- Fix broken base64url padding in src/Data/Payload.php: str_pad was
  a no-op because the length argument was always < string length.
  Replaced with correct str_repeat approach
- Fix typo in bin/franken.sh: digtialadapt → digitaladapt
- Add comment to bin/franken.sh noting it's a dev utility
- Remove config/reference.php from git tracking (auto-generated file)
  and add to .gitignore
- Fix readme.md: env.example → example.env (matches actual filename)
2026-08-10 18:55:19 -04:00
andrew 95ab77db2a added roadmap for where we are aiming to take this project
Push Develop / docker (push) Successful in 4m43s
Sync GitHub / sync (push) Successful in 6s
Tests / test (push) Successful in 47s
2026-08-07 09:25:56 -04:00
andrew d6bcbf661e Merge pull request 'Add PHPUnit test suite — 222 tests, 100% code coverage' (#1) from Lyra into main
Push Develop / docker (push) Successful in 7m5s
Sync GitHub / sync (push) Successful in 8s
Tests / test (push) Successful in 46s
Push Docker / docker (push) Successful in 4m44s
First AI contribution to main branch, a full suite of tests, thank you GLM-5.2.
2026-08-07 09:13:16 -04:00
lyra de2a382cbf Add Gitea workflow to run test suite on push and PR
Sync GitHub / sync (push) Successful in 7s
Tests / test (pull_request) Successful in 1m58s
2026-08-07 09:06:32 -04:00
lyra 12ba6cde7b Add unit tests for untested edge cases and code paths
Sync GitHub / sync (push) Successful in 9s
PayloadTest:
- decode() with invalid JSON, JSON array, null, boolean, number
- load() with all fields present but empty strings
- create() with invalid scope string (falls back to cookie)
- create() with missing json property (defaults to true)

DomainManagerTest:
- TLD table coverage: com.au, co.jp, com.br, co.nz, com.mx, co.in, br.com
- Single-label host matching behavior
- Empty string host
- validReturn with URL containing port, without path, different domain with port

MakeNonceTraitTest:
- Retry-then-succeed path (first attempt collides, second succeeds)
- Zero retries throws immediately on collision

StringTraitTest:
- Only invalid characters collapses to single underscore
- Exactly 128 characters boundary
- Multibyte characters (é, ö) replaced with underscore
- Emoji replaced with underscore

GetTotpTraitTest:
- HOTP URI triggers HttpException(500) via instanceof check

LoginManagerTest:
- ULID collision throws HttpException(500)
- Central auth cookie sets domain on matching host (uses auth cookie name)
- Central auth cookie uses null domain on non-matching host
- Empty return parameter falls back to request path

BackupCodeManagerTest:
- Empty string code returns false
- Code with value false (consumed) verified via cache state
- Generated codes are unique (50 codes)
- Code length equals TOTP digits + 2

MonitorCacheKeysTest:
- saveDeferred on __key_list and __chg_list throws OutOfBoundsException
- getKeys returns empty when key list is lost
- deleteItem/deleteItems return true assertions

PersistCacheTest:
- Mixed updates and removals in same persist cycle
- Multiple boot-modify-persist cycles with interleaved modifications
2026-08-06 06:10:31 -04:00
lyra 6c5a7c98e8 Fix failing functional tests and add test infrastructure
- Add TestKernel that removes the kernel.reset tag from nonceCache,
  rateLimitCache, sessionCache and sessionStorage pools so in-memory
  state survives across requests within a single test (mirroring APCu
  persistence in production)
- Add config/packages/test/ with array cache adapters and test session
  config
- Set fixed TOTP secret (JBSWY3DPEHPK3PXP) and high rate limits in
  phpunit.dist.xml and .env.test so functional tests can compute valid
  codes and are not rate-limited
- Make Kernel non-final so TestKernel can extend it
- Fix testFailedLoginWithSpentNonceIsRejected and
  testConsumedBackupCodeCannotBeReused: clear the CookieJar between
  sub-requests so a session cookie set by a prior successful login does
  not auto-authenticate the next request via AcceptListener before the
  nonce/backup-code path is exercised
2026-08-06 06:07:14 -04:00
lyra 4d314bcb28 Add unit tests for all listeners, the backup-codes command, and test support helpers
- Add ListenerTestHelper providing a real Twig Environment pointed at the
  project templates and configurable RateLimiterFactoryInterface doubles
  (fixed-remaining and counting variants)
- Add AcceptListenerTest: valid cookie session (host & auth-subdomain cookie
  names), missing/empty cookie, no session
- Add AllowListenerTest: valid IP session, missing session, IP access disabled
- Add RejectListenerTest: blocked -> teapot / too-many-requests, unblocked,
  error template content
- Add InterceptListenerTest: central-auth redirect, login page rendering,
  post form on auth subdomain, invalid-cookie pruning (host & auth cookies)
- Add LoginListenerTest: no-login early return, successful login via header
  and via POST to auth subdomain, failed login (json/html), rate-limited
  (teapot/too-many), invalid payload handling
- Add GenerateBackupCodesCommandTest: default/specific count, default argument
  is 10, boot+persist invocation, zero codes, name & description configuration
- Fix MakeNonceTraitTest nonce cache lookups to use makeCacheKey() (was flaky
  when random nonce contained '-')
2026-08-05 16:55:28 -04:00
lyra 890cc225ef Add PHPUnit test suite and supporting infrastructure
- Add phpunit/phpunit ^13.2, symfony/browser-kit and symfony/css-selector
  to require-dev, plus the autoload-dev mapping for App\Tests- Add phpunit.dist.xml (strict deprecation/notice/warning failures,
  APP_ENV=test forced) and .env.test / bin/phpunit / tests/bootstrap.php
  from the PHPUnit recipe
- Add tests/Support/TotpTestHelper providing a deterministic TOTP
  fixture, frozen clock and ConfigBag/cache-pool helpers
- Add 121 unit tests covering Clock, ConfigBag, Data/Payload, Enum/Scope,
  MonitorCacheKeys, PersistCache, Utilities, all five Traits and the
  three Service managers (BackupCode, Domain, Login)
- Fix LoginManagerTest nonce lookups to use makeCacheKey() so the cache
  key matches the one the manager actually reads/writes
- Gitignore bin/.phpunit.result.cache
2026-08-05 16:52:44 -04:00
150 changed files with 24007 additions and 2100 deletions
+554
View File
@@ -0,0 +1,554 @@
#!/usr/bin/env bash
#
# conformance.sh — checks a Symfony project against the shared standard.
#
# Usage:
# conformance.sh --profile=web-app|auth-gateway|api-gateway [--json] [path]
#
# Design rules (GUIDING-LIGHT §8.2):
# 1. It only CHECKS. It never fixes anything. No remediation logic to maintain.
# 2. Checks are ADDED, never removed. The script can only get stricter. If a
# check is wrong, fix the check — don't delete it from a repo.
# 3. Every check names the document section it comes from, so a failure tells
# you WHY the rule exists, not just that you broke it.
#
# Exit codes: 0 = all passed, 1 = at least one failure.
#
# DEPENDENCIES: bash + coreutils + grep for everything except one check.
# `controls-16px-min-css` shells out to css-control-size.py because resolving
# rem/em/font-shorthand units correctly is not something grep can do — and
# getting it wrong silently misses the single most important regression in
# this codebase (vital-pulse's 0.95rem inputs). python3 is present on every
# GitHub/Gitea runner and in the setup-php images, so this is a safe
# dependency; if it is ever missing, that one check is SKIPPED with a warning
# rather than failed, so the rest of the suite still runs.
set -uo pipefail
PROFILE=""
OUTPUT_JSON=false
TARGET=""
# Directory this script lives in, so helper tools can be located regardless of
# the CWD the caller is in (CI runs it from the project root).
CONFORMANCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export CONFORMANCE_DIR
for arg in "$@"; do
case "$arg" in
--profile=*) PROFILE="${arg#*=}" ;;
--json) OUTPUT_JSON=true ;;
-h|--help)
sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
exit 0
;;
-*) echo "Unknown flag: $arg" >&2; exit 2 ;;
*) TARGET="$arg" ;;
esac
done
PROFILE="${PROFILE:-web-app}"
TARGET="${TARGET:-.}"
cd "$TARGET" || { echo "Cannot cd to $TARGET" >&2; exit 2; }
case "$PROFILE" in
web-app|auth-gateway|api-gateway) ;;
*) echo "Invalid --profile: $PROFILE (expected web-app, auth-gateway, or api-gateway)" >&2; exit 2 ;;
esac
PASS=0
FAIL=0
SKIP=0
declare -a FAILURES=()
declare -a SKIPPED=()
# check <id> <description> <doc-section> <test-command...>
# The test command must exit 0 to pass.
check() {
local id="$1" desc="$2" section="$3"
shift 3
if "$@" >/dev/null 2>&1; then
PASS=$((PASS + 1))
$OUTPUT_JSON || printf ' \033[32m✓\033[0m %s\n' "$id"
else
FAIL=$((FAIL + 1))
FAILURES+=("$id|$desc|$section")
$OUTPUT_JSON || printf ' \033[31m✗\033[0m %s — %s [%s]\n' "$id" "$desc" "$section"
fi
}
# check_opt <id> <desc> <section> <prereq-cmd> <real-cmd...>
#
# For checks that depend on optional tooling. If the prerequisite is missing
# the check is reported as SKIPPED — its own state, never a green tick.
# A silently-passing check is the most dangerous outcome here: it makes a repo
# look compliant while the check never actually ran.
check_opt() {
local id="$1" desc="$2" section="$3" prereq="$4"
shift 4
# `prereq` is a SHELL EXPRESSION STRING, evaluated with eval.
#
# It must not be a multi-word command: `$prereq` is a single variable, so
# passing `bash -c '...'` would bind only `bash` and run it bare — and a
# bare `bash` reads stdin and BLOCKS FOREVER. That turns a broken check into
# a hung CI job (which only surfaces when the job timeout kills it).
if ! eval "$prereq" >/dev/null 2>&1; then
SKIP=$((SKIP + 1))
SKIPPED+=("$id|$desc|$section")
$OUTPUT_JSON || printf ' \033[33m–\033[0m %s — SKIPPED (prerequisite unavailable) [%s]\n' "$id" "$section"
return
fi
check "$id" "$desc" "$section" "$@"
}
# has_file <path>
has_file() { [ -f "$1" ]; }
# not_has_file <path>
not_has_file() { [ ! -f "$1" ]; }
# file_contains <path> <pattern> (silently false if path missing)
file_contains() { [ -f "$1" ] && grep -qE "$2" "$1"; }
# any_file_contains <pattern> <path...>
#
# NOTE: matches anywhere in the file, INCLUDING comments. That is correct for
# rules about the mere presence of a string, and WRONG for rules about a
# directive. When checking a directive ("CI calls X"), anchor the pattern to
# the line form that the directive actually takes — see ci-reusable-workflows
# below for why that matters.
any_file_contains() {
local pat="$1"; shift
grep -rlE "$pat" "$@" >/dev/null 2>&1
}
# caller_disables <knob> <value>
#
# True when one of the repo's own *php-test pins* sets a shared-workflow input
# to <value> — `run-composer-audit: 'false'`, `coverage: 'none'`. Accepts the
# bare YAML boolean spelling and both quote styles, ignores indentation and
# trailing comments, and only reads files that pin php-test.yaml (a
# docker-publish caller's knobs are unrelated).
#
# "Any pin disables it" is deliberate: one workflow that switches the step off
# is enough to make the check un-satisfied. Refusing to accept an opt-out
# would turn this fix into a false green, which is the one outcome worse than
# the false red it replaces.
caller_disables() {
local knob="$1" value="$2" got
local pins=()
mapfile -t pins < <(grep -rlE '^[[:space:]]*uses:[[:space:]]*private/ci/\.gitea/workflows/php-test\.yaml@' .gitea/workflows 2>/dev/null)
[ "${#pins[@]}" -eq 0 ] && return 1
got=$(grep -hE "^[[:space:]]*${knob}:" "${pins[@]}" 2>/dev/null \
| sed 's/#.*//' | sed 's/^[^:]*://' | tr -d "[:space:]\042\047" \
| tr '[:upper:]' '[:lower:]' || true)
printf '%s\n' "$got" | grep -qx "$value"
}
# ci_runs <inline-pattern> [<knob> <disabled-value>]
#
# "CI runs X" checks have TWO legitimate shapes, and only one existed when
# they were written — before the move to shared workflows (§8.2(1)):
#
# 1. INLINE — this repo's own workflow contains the command. Grep it.
# 2. DELEGATED — this repo pins private/ci's php-test.yaml, and the command
# runs there. The text is deliberately NOT in this repo any more; the
# caller is a ~15-line pin by design.
#
# Only shape 1 used to be accepted, which turned every adopted repo's audit
# and validate checks red while the steps genuinely ran — a false positive
# that reported a violation where there was none.
#
# For shape 2 the only local evidence is the knobs the caller passes, so that
# is what gets checked: an explicit opt-out (`run-composer-audit: 'false'`,
# `coverage: 'none'`) means the step does NOT run there, and the check must
# keep failing. A check that accepts a switched-off step is a false green.
#
# Deliberately NOT verified here: that the shared pipeline still contains the
# step. This script is vendored and stays offline (see the header), and
# private/ci is LAN-only, so fetching it at run time would reintroduce exactly
# the silent-no-op dependency that vendoring removed. That half of the
# contract is guarded where the file lives: validate-workflows.py fails
# private/ci's own CI if php-test.yaml loses a step the projects' checks take
# on faith, or if a gate's default flips to disabled.
ci_runs() {
local pattern="$1" knob="${2:-}" disabled="${3:-}"
if grep -rqE '^[[:space:]]*uses:[[:space:]]*private/ci/\.gitea/workflows/php-test\.yaml@' .gitea/workflows 2>/dev/null; then
# Delegated: the caller's knobs are the only local source of truth.
[ -n "$knob" ] && caller_disables "$knob" "$disabled" && return 1
return 0
fi
any_file_contains "$pattern" .gitea/workflows
}
# no_file_contains <ext-glob> <pattern> — searches source trees only
no_match_in_sources() {
local pattern="$1"; shift
grep -rEl "$pattern" "$@" >/dev/null 2>&1 && return 1 || return 0
}
# dir_exists
dir_exists() { [ -d "$1" ]; }
$OUTPUT_JSON || {
echo ""
echo "Conformance check — profile: $PROFILE — $(pwd)"
echo "Standard: GUIDING-LIGHT.md"
echo ""
}
# ─────────────────────────────────────────────────────────────────────────────
# UNIVERSAL — every repo, every archetype
# ─────────────────────────────────────────────────────────────────────────────
$OUTPUT_JSON || echo "PHP & framework baseline"
check "php-85" \
"composer.json requires PHP 8.5 (use ^8.5, not >=8.4)" \
"§1.1" \
file_contains composer.json '"php"[[:space:]]*:[[:space:]]*"\^8\.5'
check "php-not-open-ended" \
"PHP constraint is not open-ended (>=8.4 allows PHP 9)" \
"§1.1" \
bash -c '! grep -qE "\"php\"[[:space:]]*:[[:space:]]*\">=" composer.json'
check "platform-pinned" \
"config.platform is set in composer.json (prevents silent version drift)" \
"§1.2" \
file_contains composer.json '"platform"'
check "symfony-81" \
"Symfony pinned to 8.1" \
"§1" \
file_contains composer.json 'symfony/framework-bundle":[[:space:]]*"8\.1\.'
$OUTPUT_JSON || echo ""
$OUTPUT_JSON || echo "Toolchain"
check "phpstan-config" \
"phpstan.neon.dist present" \
"§2.2" \
has_file phpstan.neon.dist
check "phpstan-level" \
"PHPStan level >= 6 declared" \
"§2.2" \
bash -c 'grep -qE "level:[[:space:]]*[6-9]|level:[[:space:]]*max" phpstan.neon.dist 2>/dev/null'
check "cs-fixer-config" \
".php-cs-fixer.dist.php present" \
"§2.5" \
has_file .php-cs-fixer.dist.php
check "cs-fixer-pinned" \
"friendsofphp/php-cs-fixer pinned to ^3.95 (not \"*\")" \
"§2.5" \
bash -c '! grep -qE "php-cs-fixer\"[[:space:]]*:[[:space:]]*\"\*\"" composer.json'
check "phpunit-config-name" \
"PHPUnit config named phpunit.dist.xml" \
"§2.4" \
has_file phpunit.dist.xml
check "editorconfig" \
".editorconfig present" \
"§8.10" \
has_file .editorconfig
$OUTPUT_JSON || echo ""
$OUTPUT_JSON || echo "CI & supply chain"
# These three accept the command either inline or via the shared pipeline —
# see ci_runs above for why, and for what is still required of a delegating
# caller (the opt-out knobs must not be set).
check "ci-composer-audit" \
"CI runs 'composer audit'" \
"§8.1" \
ci_runs 'composer audit' run-composer-audit false
check "ci-coverage" \
"CI measures test coverage" \
"§2.3" \
ci_runs 'coverage' coverage none
check "ci-composer-validate" \
"CI runs 'composer validate --strict'" \
"§8.3" \
ci_runs 'composer validate'
# Anchored to a REAL `uses:` line, not the string anywhere in the file.
#
# The previous form matched the string anywhere, which gave it a false-positive
# mode that made it worse than useless: a repo that INLINED the shared workflow
# still carries a header comment saying it was "inlined from
# private/ci/.gitea/workflows/...", so the check went green in exactly the repos
# that had drifted. It reported compliance precisely where compliance was absent.
#
# `uses:` is what the description always claimed to test.
check "ci-reusable-workflows" \
"CI calls shared workflows from private/ci (not five drift surfaces)" \
"§8.2" \
any_file_contains '^[[:space:]]*uses:[[:space:]]*private/ci/\.gitea/workflows' .gitea/workflows
# A bake file describes WHICH Dockerfile stage to build. buildx does not check
# that the stage exists until build time, and `bake --print` — the obvious way
# to validate one — happily resolves a target that names no stage, because it
# never reads the Dockerfile. So a typo there reaches CI and fails after the
# push. This is the check that buildx is missing.
#
# SKIPPED when there is no bake file: most repos use the `action` backend and
# have none, and absence is not a violation.
#
# The helper belongs in the PREREQUISITE, not only in the command. It used to
# be `[ -f ... ] || exit 0` INSIDE the command, which is a different thing: a
# repo that has a bake file but no vendored helper reported a green tick for a
# check that never ran. That is the one outcome this script's header singles
# out as most dangerous, and it was live — preauth adopted a bake file before
# the `validate-bake.py` half of the re-vendor landed, so its next sync would
# have shown a green `bake-target-exists` no matter what the bake file said.
#
# With the helper in the prerequisite the same state reports SKIPPED — its own
# yellow state, explicitly not a pass. (`css-control-size.py`, the other
# helper, has been wired this way since it was added; see below.)
check_opt "bake-target-exists" \
"docker-bake.hcl targets a stage that exists in the Dockerfile" \
"§6.2" \
'command -v python3 >/dev/null 2>&1 && [ -f docker-bake.hcl ] && [ -f "$CONFORMANCE_DIR/validate-bake.py" ]' \
bash -c 'exec "$CONFORMANCE_DIR/validate-bake.py" docker-bake.hcl Dockerfile'
$OUTPUT_JSON || echo ""
$OUTPUT_JSON || echo "Hygiene & layout"
check "dockerignore-env" \
".env is excluded in .dockerignore (prevents secrets in images)" \
"§6.1" \
file_contains .dockerignore '^/?\.env$'
check "dockerignore-present" \
".dockerignore present" \
"§6" \
has_file .dockerignore
check "gitignore-var" \
"/var/ excluded in .gitignore" \
"§5.2" \
file_contains .gitignore '^/?var/?$'
check "dockerfile-nonroot" \
"Dockerfile drops privileges with USER" \
"§6.4" \
file_contains Dockerfile '^USER '
check "dockerfile-pinned-base" \
"Dockerfile base image is not :latest" \
"§6.4" \
bash -c '! grep -qE "^FROM[^ ]*:latest" Dockerfile'
check "docs-examples" \
"docs/examples/ present" \
"§4.4" \
dir_exists docs/examples
check "boilerplate-security" \
"SECURITY.md present" \
"§7.1" \
has_file SECURITY.md
check "license-file" \
"LICENSE file present" \
"§7.2" \
has_file LICENSE
check "license-mit" \
"LICENSE is MIT (uniform MIT decided §7.2)" \
"§7.2" \
bash -c 'head -1 LICENSE 2>/dev/null | grep -qi "^MIT License"'
# A composer.json license that contradicts the shipped LICENSE file is worse
# than declaring none: tooling trusts the metadata, humans read the file.
# task-weaver declared "proprietary" while shipping no file at all.
check "license-declared-matches" \
"composer.json declares MIT, matching the LICENSE file" \
"§7.2" \
file_contains composer.json '"license"[[:space:]]*:[[:space:]]*"MIT"'
check "no-cdn-references" \
"No CDN script/link references (zero-CDN goal)" \
"§3.5" \
bash -c '! grep -rElE "(cdn\.jsdelivr|cdnjs\.cloudflare|unpkg\.com|cdn\.tailwindcss)" templates public assets config 2>/dev/null | head -1 | grep -q .'
# ─────────────────────────────────────────────────────────────────────────────
# NOT API-GATEWAY — anything that renders HTML
# ─────────────────────────────────────────────────────────────────────────────
if [ "$PROFILE" != "api-gateway" ]; then
$OUTPUT_JSON || echo ""
$OUTPUT_JSON || echo "Accessibility (§3.3a) — the iOS zoom root cause"
check "viewport-not-zoom-locked" \
"Viewport does not disable pinch-zoom (WCAG 1.4.4)" \
"§3.3a" \
bash -c '! grep -rElE "(user-scalable=no|maximum-scale=1)" templates public 2>/dev/null | head -1 | grep -q .'
check "viewport-fit-cover" \
"Viewport declares viewport-fit=cover (safe areas)" \
"§3.3a" \
bash -c 'grep -rElE "viewport-fit=cover" templates public 2>/dev/null | head -1 | grep -q .'
# Two checks, because there are two ways to get this wrong and one grep
# cannot see both:
# (a) raw CSS with a small font-size — needs unit resolution (rem/em/shorthand)
# (b) Tailwind-style utility classes on the control — not CSS at all
# Requires python3 AND the vendored helper. If either is absent this is
# SKIPPED (reported as its own state), never a green tick.
check_opt "controls-16px-min-css" \
"No form control renders below 16px (root cause of iOS auto-zoom)" \
"§3.3a" \
'command -v python3 >/dev/null 2>&1 && [ -f "$CONFORMANCE_DIR/css-control-size.py" ]' \
bash -c '
mapfile -t files < <(find templates assets public -type f \( -name "*.css" -o -name "*.twig" -o -name "*.html" \) 2>/dev/null)
[ "${#files[@]}" -eq 0 ] && exit 0
exec "$CONFORMANCE_DIR/css-control-size.py" 16 "${files[@]}"
'
check "controls-16px-min-utility" \
"No small text utility class on a form control (Tailwind text-xs/text-sm)" \
"§3.3a" \
bash -c '
! grep -rPzoE "<(input|select|textarea)[^>]*class=\"[^\"]*(text-xs|text-sm)[^\"]*\"" templates 2>/dev/null | head -c1 | grep -q .
'
check "security-headers" \
"Security headers configured (Symfony listener or Caddy)" \
"§8.9" \
bash -c 'grep -rElE "X-Content-Type-Options" src config docker Caddyfile 2>/dev/null | head -1 | grep -q .'
check "no-deprecated-xss-header" \
"X-XSS-Protection not used (deprecated)" \
"§8.9" \
bash -c '! grep -rElE "X-XSS-Protection" src config docker Caddyfile 2>/dev/null | head -1 | grep -q .'
fi
# ─────────────────────────────────────────────────────────────────────────────
# WEB-APP ONLY — installable PWA surface
# ─────────────────────────────────────────────────────────────────────────────
if [ "$PROFILE" = "web-app" ]; then
$OUTPUT_JSON || echo ""
$OUTPUT_JSON || echo "PWA (§3.3b)"
check "webmanifest" \
"Web app manifest present" \
"§3.3b" \
bash -c 'ls public/*.webmanifest public/manifest.json 2>/dev/null | head -1 | grep -q .'
check "manifest-display-standalone" \
"Manifest declares display: standalone" \
"§3.3b" \
bash -c 'grep -qE "\"display\"[[:space:]]*:[[:space:]]*\"standalone\"" public/*.webmanifest public/manifest.json 2>/dev/null'
check "manifest-start-url" \
"Manifest declares start_url" \
"§3.3b" \
bash -c 'grep -qE "\"start_url\"" public/*.webmanifest public/manifest.json 2>/dev/null'
check "service-worker" \
"Service worker present (required for installability)" \
"§3.3b" \
bash -c 'ls public/sw.js public/service-worker.js 2>/dev/null | head -1 | grep -q .'
check "theme-color" \
"theme-color meta present (status bar theming)" \
"§3.3a" \
bash -c 'grep -rElE "theme-color" templates public 2>/dev/null | head -1 | grep -q .'
check "touch-action" \
"touch-action: manipulation used (removes 300ms tap delay)" \
"§3.3a" \
bash -c 'grep -rElE "touch-action" templates assets public 2>/dev/null | head -1 | grep -q .'
fi
# ─────────────────────────────────────────────────────────────────────────────
# AUTH-GATEWAY ONLY — preauth-specific security invariants
# ─────────────────────────────────────────────────────────────────────────────
if [ "$PROFILE" = "auth-gateway" ]; then
$OUTPUT_JSON || echo ""
$OUTPUT_JSON || echo "Auth gateway security (§3.3d)"
check "no-service-worker" \
"Auth gateway has NO service worker (must never replay a cached session)" \
"§3.3d" \
bash -c '! ls public/sw.js public/service-worker.js 2>/dev/null | head -1 | grep -q .'
check "no-store-present" \
"no-store cache directive present somewhere (login flow anti-cache guard)" \
"§3.3d" \
bash -c 'grep -rEli "no-store" src config 2>/dev/null | head -1 | grep -q .'
check "rate-limiter" \
"symfony/rate-limiter required" \
"§8.11" \
file_contains composer.json 'rate-limiter'
fi
# ─────────────────────────────────────────────────────────────────────────────
# REPORT
# ─────────────────────────────────────────────────────────────────────────────
TOTAL=$((PASS + FAIL + SKIP))
# JSON strings must be escaped. Without this, a description containing a double
# quote (e.g. 'pinned to ^3.95 (not "*")') produces invalid JSON and silently
# breaks every consumer of --json.
json_escape() {
local s="$1"
s="${s//\\/\\\\}" # backslash first
s="${s//\"/\\\"}" # then double quote
s="${s//$'\n'/\\n}"
s="${s//$'\t'/\\t}"
s="${s//$'\r'/}"
printf '%s' "$s"
}
if $OUTPUT_JSON; then
printf '{"profile":"%s","passed":%d,"failed":%d,"skipped":%d,"total":%d,"failures":[' \
"$(json_escape "$PROFILE")" "$PASS" "$FAIL" "$SKIP" "$TOTAL"
first=true
for f in "${FAILURES[@]:-}"; do
[ -z "$f" ] && continue
IFS='|' read -r fid fdesc fsec <<< "$f"
$first || printf ','
printf '{"id":"%s","description":"%s","section":"%s"}' \
"$(json_escape "$fid")" "$(json_escape "$fdesc")" "$(json_escape "$fsec")"
first=false
done
printf '],"skipped_checks":['
first=true
for f in "${SKIPPED[@]:-}"; do
[ -z "$f" ] && continue
IFS='|' read -r fid fdesc fsec <<< "$f"
$first || printf ','
printf '{"id":"%s","description":"%s","section":"%s"}' \
"$(json_escape "$fid")" "$(json_escape "$fdesc")" "$(json_escape "$fsec")"
first=false
done
printf ']}\n'
else
echo ""
echo "─────────────────────────────────────────────"
if [ "$SKIP" -gt 0 ]; then
printf ' \033[33m%d of %d checks SKIPPED\033[0m (missing prerequisites — NOT a pass):\n' "$SKIP" "$TOTAL"
for f in "${SKIPPED[@]}"; do
IFS='|' read -r fid fdesc fsec <<< "$f"
printf ' · [%s] %s\n' "$fsec" "$fid"
done
echo ""
fi
if [ "$FAIL" -eq 0 ]; then
printf ' \033[32mAll %d runnable checks passed.\033[0m\n' "$((TOTAL - SKIP))"
else
printf ' \033[31m%d of %d checks failed.\033[0m\n\n' "$FAIL" "$TOTAL"
echo " Guidance:"
for f in "${FAILURES[@]}"; do
IFS='|' read -r fid fdesc fsec <<< "$f"
printf ' • [%s] %s\n %s\n' "$fsec" "$fdesc" "$fid"
done
fi
echo "─────────────────────────────────────────────"
echo ""
fi
[ "$FAIL" -eq 0 ] && exit 0 || exit 1
+228
View File
@@ -0,0 +1,228 @@
#!/usr/bin/env python3
"""
css-control-size.py — finds form controls whose rendered font-size is below 16px.
This is the precise version of the check. A naive `grep font-size` on the source
produces both false negatives and false positives:
FALSE NEGATIVE: vital-pulse declares `font-size: 0.95rem` on its inputs.
0.95rem x 16px = 15.2px — under the iOS auto-zoom threshold
— but it never appears as a `px` literal.
FALSE POSITIVE: task-weaver has many `font-size: 11px` rules for table
headers and labels. Those are fine. It's *form controls*
that matter, so only rules whose selector targets a control
should be judged.
FALSE POSITIVE: preauth declares `button, input { font-size: 0.9em }`, which
looks small as an `em` value — but its root is
`html { font-size: 1.5em }` = 24px, so the real rendered
size is 21.6px. `em` must be resolved against the parsed root.
So this walks CSS rules, keeps only control-targeting selectors, resolves
px / rem / em to a pixel value, and reports anything under the threshold.
Usage: css-control-size.py <threshold-px> <file> [file...]
Output: one line per violation: "<file>:<line-ish>\t<selector>\t<raw>\t<computed-px>"
Exit: 0 = clean, 1 = violations found
"""
from __future__ import annotations
import re
import sys
# Selectors that style an actual interactive form control.
CONTROL_RE = re.compile(
r"""(?ix)
(?:^|[\s,>+~\[.(#]) # boundary
(?:
input | select | textarea | button
| \.input\b | \.form-control\b | \.btn\b
| \[type= | \.tag-input\b | \.schedule-number\b
)
""",
)
# font-size: 14px | font-size: 0.95rem | font-size: 0.9em
FONT_SIZE_RE = re.compile(
r"font-size\s*:\s*(?P<val>[0-9]*\.?[0-9]+)\s*(?P<unit>px|rem|em|pt)\b",
re.IGNORECASE,
)
# font: 14px/1.5 ... (shorthand — sets font-size implicitly)
FONT_SHORTHAND_RE = re.compile(
r"font\s*:\s*(?:[^;{}]*?\s)?(?P<val>[0-9]*\.?[0-9]+)\s*(?P<unit>px|rem|em|pt)\b",
re.IGNORECASE,
)
# html { font-size: 1.5em } — establishes the em base.
ROOT_SELECTOR_RE = re.compile(r"(?i)^\s*(?:html|:root)\s*$")
DEFAULT_ROOT_PX = 16.0
PT_TO_PX = 4.0 / 3.0
def strip_comments(css: str) -> str:
return re.sub(r"/\*.*?\*/", " ", css, flags=re.DOTALL)
def parse_rules(css: str):
"""Yield (selector, body, index) for every rule, including nested ones."""
css = strip_comments(css)
stack: list[str] = []
acc = ""
for i, ch in enumerate(css):
if ch == "{":
stack.append(acc.strip())
acc = ""
elif ch == "}":
selector = stack.pop() if stack else ""
if selector:
# Body is what accumulated inside this rule; recover it from
# the source between the opening brace and here.
yield selector, "", i
acc = ""
else:
acc += ch
def parse_rules_with_bodies(css: str):
"""Yield (selector, body). Handles nesting (@media) by tracking depth."""
css = strip_comments(css)
stack: list[str] = []
out: list[tuple[str, str]] = []
acc = ""
body_start: list[int] = []
for i, ch in enumerate(css):
if ch == "{":
stack.append(acc.strip())
body_start.append(i + 1)
acc = ""
elif ch == "}":
if stack:
selector = stack.pop()
start = body_start.pop() if body_start else 0
out.append((selector, css[start:i]))
acc = ""
else:
acc += ch
return out
def resolve_px(value: float, unit: str, root_px: float) -> float:
unit = unit.lower()
if unit == "px":
return value
if unit == "rem":
return value * DEFAULT_ROOT_PX
if unit == "em":
# Resolved against the root that we parsed. This is an approximation
# (true `em` is parent-relative) but it is correct for the real case
# that matters: a page-level `html { font-size: N }` scaling controls.
return value * root_px
if unit == "pt":
return value * PT_TO_PX
return value
def find_root_px(rules) -> float:
"""Find an explicit html/:root font-size to use as the em base."""
for selector, body in rules:
sel = selector.split(",")[0].strip()
if ROOT_SELECTOR_RE.match(sel):
m = FONT_SIZE_RE.search(body)
if m:
val = float(m.group("val"))
unit = m.group("unit")
# Root em is relative to the 16px default.
return resolve_px(val, unit, DEFAULT_ROOT_PX)
return DEFAULT_ROOT_PX
def check_file(path: str, threshold: float) -> list[tuple[str, str, str, float]]:
violations: list[tuple[str, str, str, float]] = []
try:
with open(path, "r", encoding="utf-8", errors="replace") as fh:
css = fh.read()
except OSError:
return violations
# Only look at things that plausibly contain CSS.
if "{" not in css:
return violations
rules = parse_rules_with_bodies(css)
root_px = find_root_px(rules)
for selector, body in rules:
# Skip at-rule wrappers; their inner rules are yielded separately.
head = selector.strip()
if head.startswith("@"):
continue
# A rule may have several comma-separated selectors; judge each.
for one in head.split(","):
one = one.strip()
if not one:
continue
is_inherited_base = bool(re.match(r"(?i)^(?:html|body)$", one))
targets_control = bool(CONTROL_RE.search(one))
if not targets_control and not is_inherited_base:
continue
# Ignore rules that only set colours etc. — we want font-size.
m = FONT_SIZE_RE.search(body)
if m:
val = float(m.group("val"))
unit = m.group("unit")
raw = f"{m.group('val')}{unit}"
elif is_inherited_base:
# `body { font: 14px/1.5 }` sets the base every unstyled control
# inherits. Only the shorthand carries a size here.
m2 = FONT_SHORTHAND_RE.search(body)
if not m2:
continue
val = float(m2.group("val"))
unit = m2.group("unit")
raw = f"font-shorthand {m2.group('val')}{unit}"
else:
# A control-targeting rule with no size of its own inherits
# whatever body provides, which is reported separately.
continue
computed = resolve_px(val, unit, root_px)
if computed < threshold:
violations.append((path, one, raw, computed))
return violations
def main() -> int:
if len(sys.argv) < 3:
print(__doc__, file=sys.stderr)
return 2
try:
threshold = float(sys.argv[1])
except ValueError:
print(f"threshold must be a number, got {sys.argv[1]!r}", file=sys.stderr)
return 2
total = 0
for path in sys.argv[2:]:
for vpath, selector, raw, computed in check_file(path, threshold):
print(f"{vpath}\t{selector}\t{raw}\t{computed:.1f}px")
total += 1
if total:
print(
f"\n{total} control style(s) render below {threshold:.0f}px. "
"iOS Safari auto-zooms any focused control under 16px — this is the "
"trigger that `user-scalable=no` was masking (GUIDING-LIGHT §3.3a).",
file=sys.stderr,
)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""
validate-bake.py — check a docker-bake.hcl against its Dockerfile.
WHY THIS EXISTS
---------------
`docker buildx bake --print` resolves the bake file but does NOT read the
Dockerfile, so it happily accepts `target = "app"` when no stage is named
`app`. The failure only surfaces at build time, in CI, after the push:
ERROR: failed to solve: target stage "app" could not be found
That is exactly the failure preauth had: its final stage was unnamed
(`FROM dunglas/frankenphp:php8.5-trixie`), so `target = "app"` could never
have resolved. --print reported success.
This script checks the cross-file contract that buildx does not:
1. every `target = "..."` matches a named Dockerfile stage
2. the named stage is the LAST one, so a plain `docker build` still works
3. every variable the file references is declared
4. the `default` group only names targets that exist
Works without a Docker daemon, so it is usable in CI and on the workstation.
Usage: validate-bake.py [bake-file] [dockerfile]
Exit: 0 = clean, 1 = problems found
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
FROM_RE = re.compile(r"^\s*FROM\s+(\S+)(?:\s+AS\s+(\S+))?\s*$", re.I)
TARGET_RE = re.compile(r'^\s*target\s*=\s*"([^"]+)"', re.M)
DECL_RE = re.compile(r'^\s*target\s+"([^"]+)"\s*\{', re.M)
VAR_DECL_RE = re.compile(r'^\s*variable\s+"([^"]+)"\s*\{', re.M)
VAR_USE_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
GROUP_RE = re.compile(r'^\s*group\s+"([^"]+)"\s*\{', re.M)
TARGETS_LIST_RE = re.compile(r"targets\s*=\s*\[([^\]]*)\]")
def stages(dockerfile: Path) -> list[tuple[int, str, str]]:
"""Return (line_no, image, stage_name_or_empty) for each FROM."""
out = []
for i, line in enumerate(dockerfile.read_text().splitlines(), 1):
if m := FROM_RE.match(line):
out.append((i, m.group(1), m.group(2) or ""))
return out
def main() -> int:
bake = Path(sys.argv[1] if len(sys.argv) > 1 else "docker-bake.hcl")
dockerfile = Path(sys.argv[2] if len(sys.argv) > 2 else "Dockerfile")
for f in (bake, dockerfile):
if not f.is_file():
print(f" ✗ missing file: {f}", file=sys.stderr)
return 1
text = bake.read_text()
found_stages = stages(dockerfile)
named = [(ln, n) for ln, _, n in found_stages if n]
names = [n for _, n in named]
problems: list[str] = []
notes: list[str] = []
# 1 + 2: target/stage contract
for t in TARGET_RE.findall(text):
if t not in names:
problems.append(
f"bake target '{t}' matches no named Dockerfile stage. "
f"Named stages: {names or '(none)'}. "
f"buildx --print does NOT catch this; the build fails."
)
if names:
# A plain `docker build` builds the LAST stage. If no bake target
# points at it, the two build paths produce different images — worth
# knowing, but legitimate for repos that publish one variant per
# target (task-weaver builds controller + worker and never uses the
# bare `docker build` path). So: note, not error.
bake_targets = TARGET_RE.findall(text)
last_name = named[-1][1]
if bake_targets and last_name not in bake_targets:
notes.append(
f"no bake target selects the LAST Dockerfile stage "
f"('{last_name}'), so a plain `docker build` and `bake` "
f"produce different images."
)
else:
problems.append("Dockerfile has no named stages; bake needs one.")
# 3: declared vs used variables
declared = set(VAR_DECL_RE.findall(text))
used = set(VAR_USE_RE.findall(text))
for u in sorted(used - declared):
problems.append(
f"${{{u}}} is used but never declared as a `variable` block; "
f"bake would error at load time."
)
for d in sorted(declared - used):
notes.append(f"variable '{d}' is declared but never referenced.")
# 4: default group names real targets
declared_targets = set(DECL_RE.findall(text))
for gname in GROUP_RE.findall(text):
block = text.split(f'group "{gname}"', 1)[1][:400]
if m := TARGETS_LIST_RE.search(block):
for t in re.findall(r'"([^"]+)"', m.group(1)):
if t not in declared_targets:
problems.append(
f"group '{gname}' references target '{t}', "
f"which is not declared."
)
name = bake.name
if problems:
print(f" FAIL {name}")
for p in problems:
print(f" ✗ {p}")
else:
print(f" OK {name} (targets: {sorted(declared_targets)} / "
f"stages: {names})")
for n in notes:
print(f" · {n}")
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main())
+84
View File
@@ -0,0 +1,84 @@
# .dockerignore — defines the build context used by `COPY . .`.
#
# Ignoring a path keeps EVERYTHING under it out of the context, which is what
# makes "copy the tree instead of listing files" safe: the allowlist that used
# to live in eight `COPY ./x /app/x` lines is now simply the absence of a
# pattern here. The failure mode is inverted — a missed entry fails the build
# loudly ("not found in build context") instead of silently baking a file in.
#
# Rules that matter (Guiding Light §6.3): `config/`, `bin/`, `public/` and the
# composer manifests are never ignored, and /Caddyfile is the inverse case —
# it is ignored, because the final stage copies it from `docker/Caddyfile`.
# ── VCS & CI ────────────────────────────────────────────────────────────────
.git
.gitignore
.editorconfig
.gitea
.ci
# ── Secrets: never bake these into a layer (§6.1, §8.12) ────────────────────
# Bare `.env` included deliberately: it is exactly the file a developer has
# locally and must not land in an image layer.
.env
.env.local
.env.local.php
.env.*.local
.env.dev
.env.test
host.env
config/secrets/prod/prod.decrypt.private.php
# ── Local runtime state (§5.2) ──────────────────────────────────────────────
# var/ holds the dev cache and logs; the prod cache is warmed inside the image.
var/
*.sqlite
*.sqlite3
*.db
# ── Rebuilt inside the image from composer.lock ─────────────────────────────
vendor/
# ── Dev / test artefacts not needed at runtime ──────────────────────────────
tests/
.phpunit.cache/
.phpunit.result.cache
phpunit.xml
phpunit.dist.xml
.php-cs-fixer.cache
.php-cs-fixer.dist.php
.php-cs-fixer.php
phpstan.neon.dist
phpstan-baseline.neon
# ── Build inputs that aren't payload ────────────────────────────────────────
Dockerfile
.dockerignore
docker-bake.hcl
compose*.yaml
docker-compose*.yaml
# ── Docs, examples and host-side tooling ────────────────────────────────────
# The root Caddyfile is the host-side example (docs/examples/ has a longer
# one); the image's config is docker/Caddyfile, copied explicitly below.
docs/
*.md
license.txt
Caddyfile
Domainfile
run.sh
deploy.sh
bin/composer
bin/dev.sh
bin/franken.sh
bin/phpunit
composer.phar
# ── Generated config reference (regenerate with config:dump) ────────────────
config/reference.php
# ── Editor / OS noise ───────────────────────────────────────────────────────
.idea
.vscode
*.swp
.DS_Store
+41 -5
View File
@@ -1,20 +1,56 @@
# editorconfig.org # editorconfig.org
#
# Canonical shared .editorconfig. Copy verbatim into a project root.
# LEAF file: sync = overwrite, never merge (GUIDING-LIGHT §8.2).
#
# context-loom was missing this entirely in the 2026-09 audit; the other four
# had three subtly different versions.
root = true root = true
[*] [*]
charset = utf-8 charset = utf-8
end_of_line = lf end_of_line = lf
indent_size = 4
indent_style = space indent_style = space
indent_size = 4
insert_final_newline = true insert_final_newline = true
trim_trailing_whitespace = true trim_trailing_whitespace = true
# YAML is indentation-significant and the rest of the ecosystem uses 2 spaces.
[*.{yaml,yml}]
indent_size = 2
# Docker/compose files follow the same convention.
[{Dockerfile,*.dockerfile}]
indent_size = 4
[{compose.yaml,compose.*.yaml,compose.yml}]
indent_size = 2
[*.json]
indent_size = 2
# Markdown: trailing whitespace is a hard line break in some renderers, so
# stripping it silently changes formatting.
[*.md]
trim_trailing_whitespace = false
# Generated / vendored content: never touch, even accidentally on save.
[{vendor/**,var/**,node_modules/**,public/bundles/**}]
insert_final_newline = false
trim_trailing_whitespace = false
# Caddy's own formatter (caddy fmt) indents with tabs, and every Caddyfile in
# the portfolio already uses them — at the root (preauth, penny-track,
# vital-pulse), under docker/ (the FrankenPHP app config), and under
# docs/examples/ (the edge-proxy reference copied from). Without this rule the
# `[*]` block above silently tells editors to use spaces, so every save
# reindents the file and caddy fmt immediately undoes it.
[Caddyfile] [Caddyfile]
indent_style = tab indent_style = tab
[{compose.yaml,compose.*.yaml}] [Makefile]
indent_size = 2 indent_style = tab
[*.md] [*.{sh,bash}]
trim_trailing_whitespace = false indent_size = 4
+40
View File
@@ -0,0 +1,40 @@
APP_ENV=test
APP_DEBUG=0
APP_SECRET=test_secret_key_change_me
# fixed TOTP secret (JBSWY3DPEHPK3PXP) so functional tests can compute valid codes
TOTP_URI='otpauth://totp/Test-TOTP?secret=JBSWY3DPEHPK3PXP'
COOKIE_TTL=2592000
SUBDOMAIN_REDIRECT=0
AUTH_SUBDOMAIN=''
IP_TTL=0
TEAPOT=1
BURST_COUNT=10
BURST_TIME=30
UPPER_COUNT=100
UPPER_TIME=3600
PASSKEY_ENABLED=0
PASSKEY_RP_NAME=''
PASSKEY_USER_VERIFICATION='required'
PASSKEY_TIMEOUT=60000
PASSKEY_BUTTON_NAME='Sign in with a passkey'
PASSKEY_REGISTER_NAME='Register this device as a passkey'
PASSKEY_BEGIN_BURST_COUNT=30
PASSKEY_BEGIN_BURST_TIME=60
PUBLIC_PATHS=''
PUBLIC_BURST_COUNT=100
PUBLIC_BURST_TIME=60
PUBLIC_UPPER_COUNT=500
PUBLIC_UPPER_TIME=3600
TITLE='Pre-Authentication System'
BG_COLOR='#029386'
FG_COLOR='#ffffff'
ERROR_COLOR='#ffb16d'
ID_NAME='Session ID'
TOKEN_NAME='Authentication Token'
SUBMIT_NAME='Submit'
ERROR_MESSAGE='Unsuccessful login attempt'
TEAPOT_TITLE="I'm a teapot"
TEAPOT_MESSAGE='I refuse to brew coffee'
TOO_MANY_TITLE='Too many requests'
TOO_MANY_MESSAGE='Try again later'
SHELL_VERBOSITY=0
+14 -22
View File
@@ -1,34 +1,26 @@
# Push Develop - update the "develop" rolling docker image tag, via the shared workflow
#
# The build is defined in docker-bake.hcl.
name: Push Develop name: Push Develop
on: on:
push: push:
branches: branches:
- 'main' - 'main'
- 'develop'
jobs: jobs:
docker: docker:
runs-on: ubuntu-latest uses: private/ci/.gitea/workflows/docker-publish.yaml@v1
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
uses: docker/login-action@v3
with: with:
username: ${{ secrets.DOCKERHUB_USERNAME }} mode: develop
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build image # Passed explicitly from repo vars
uses: docker/build-push-action@v5 image-target: ${{ vars.DOCKERHUB_TARGET }}
with:
context: .
push: true
platforms: linux/amd64,linux/arm64
tags: |
${{ vars.DOCKERHUB_TARGET }}:develop
# docker-bake.hcl controls building
build-backend: 'bake'
secrets:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
+15 -23
View File
@@ -1,34 +1,26 @@
# Push Docker - release new version to docker and update the "latest" rolling docker image tag, via the shared workflow
#
# The build is defined in docker-bake.hcl.
name: Push Docker name: Push Docker
on: on:
push: push:
tags: tags:
- '*.*.*' - 'v*.*.*'
jobs: jobs:
docker: docker:
runs-on: ubuntu-latest uses: private/ci/.gitea/workflows/docker-publish.yaml@v1
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
uses: docker/login-action@v3
with: with:
username: ${{ secrets.DOCKERHUB_USERNAME }} mode: release
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build image # Passed explicitly from repo vars
uses: docker/build-push-action@v5 image-target: ${{ vars.DOCKERHUB_TARGET }}
with:
context: .
push: true
platforms: linux/amd64,linux/arm64
tags: |
${{ vars.DOCKERHUB_TARGET }}:latest
${{ vars.DOCKERHUB_TARGET }}:${{ github.ref_name }}
# docker-bake.hcl controls building
build-backend: 'bake'
secrets:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
+13 -26
View File
@@ -1,37 +1,24 @@
# Sync GitHub - upload branch change to github, via the shared workflow
name: Sync GitHub name: Sync GitHub
on: on:
push: push:
branches: branches:
- '**' - 'main'
- 'feat*'
- 'fix*'
- 'cleanup*'
- 'chore*'
jobs: jobs:
sync: sync:
runs-on: ubuntu-latest uses: private/ci/.gitea/workflows/sync-github.yaml@v1
steps:
- name: Checkout
uses: actions/checkout@v4
with: with:
fetch-depth: 0 sync-target: ${{ vars.SYNC_GITHUB_TARGET }}
- name: Configure Git # by default we do not alter existing github tags, but that can be changed here.
run: | # force-tags: true
git config --global user.name "Andrew Sync"
git config --global user.email "sync@digitaladapt.com"
- name: Add GitHub Remote
env:
SYNC_TOKEN: ${{ secrets.SYNC_GITHUB_TOKEN }}
SYNC_TARGET: ${{ vars.SYNC_GITHUB_TARGET }}
run: |
git remote add github "https://digitaladapt:${SYNC_TOKEN}@github.com/$SYNC_TARGET"
- name: Push Current Branch
run: |
git push github HEAD:${GITHUB_REF_NAME}
- name: Push Tags
run: |
git push github --tags
secrets:
SYNC_GITHUB_TOKEN: ${{ secrets.SYNC_GITHUB_TOKEN }}
+43
View File
@@ -0,0 +1,43 @@
# Tests - ensure code quality, via the shared workflow.
#
# Checks include: PHPStan, PHPUnit, and PHP-CS-Fixer.
name: Tests
on:
push:
branches:
- 'main'
- 'feat*'
- 'fix*'
- 'cleanup*'
- 'chore*'
pull_request:
branches:
- 'main'
jobs:
test:
uses: private/ci/.gitea/workflows/php-test.yaml@v1
with:
php-version: '8.5'
# profiles defines what to test:
# * web-app: full test suite (default)
# * auth-gateway: skip template check
# * api-gateway: skip interface checks
profile: auth-gateway
# coverage defines how to check test-coverage:
# * pcov: recommended (default)
# * xdebug
coverage: 'pcov'
# 0-100 percentage of test-coverage required
coverage-min: '75'
# does failing our "conformance" check make the test suite fail
conformance-blocking: false
secrets:
# github token so composer can download dependencies
SYNC_GITHUB_TOKEN: ${{ secrets.SYNC_GITHUB_TOKEN }}
+16
View File
@@ -6,3 +6,19 @@
/vendor/ /vendor/
###< symfony/framework-bundle ### ###< symfony/framework-bundle ###
###> phpunit/phpunit ###
/phpunit.xml
/.phpunit.cache/
/bin/.phpunit.result.cache
###< phpunit/phpunit ###
###> project-specific ###
/config/reference.php
###< project-specific ###
###> friendsofphp/php-cs-fixer ###
/.php-cs-fixer.php
/.php-cs-fixer.cache
###< friendsofphp/php-cs-fixer ###
.env
+73
View File
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
/**
* .php-cs-fixer.dist.php — canonical shared config.
*
* Copy verbatim into a project root. LEAF file: sync = overwrite, never merge.
* Change it here and re-sync; do not hand-edit per repo (GUIDING-LIGHT §8.2).
*
* This replaces three divergent versions found in the 2026-09 audit:
* context-loom — had @Symfony + risky + declare_strict_types
* penny-track / preauth / vital-pulse — a second variant
* task-weaver — a third variant
*
* Pin friendsofphp/php-cs-fixer to ^3.95 in composer.json. preauth was on
* "*", which means its CI was not reproducible.
*/
$config = new PhpCsFixer\Config();
return $config
->setRiskyAllowed(true)
->setRules([
'@Symfony' => true,
'@Symfony:risky' => true,
// Unambiguous wins.
'declare_strict_types' => true,
'no_unused_imports' => true,
'ordered_imports' => [
'sort_algorithm' => 'alpha',
'imports_order' => ['class', 'function', 'const'],
],
'php_unit_method_casing' => ['case' => 'snake_case'],
// Trailing commas in multiline constructs keep diffs to one line when
// a parameter is appended — reviewable, and no reformat noise.
'trailing_comma_in_multiline' => [
'elements' => ['arrays', 'arguments', 'parameters', 'match'],
],
// `array()` → `[]`, consistent with everything else in these repos.
'array_syntax' => ['syntax' => 'short'],
// Group imports so a file's dependency surface is scannable.
'global_namespace_import' => [
'import_classes' => true,
'import_constants' => false,
'import_functions' => false,
],
// Keep `#[Attribute]`-style attributes on their own line for long ones.
'attribute_empty_parentheses' => true,
])
->setFinder(
(new PhpCsFixer\Finder())
->in(__DIR__)
->exclude('vendor')
->exclude('var')
->exclude('node_modules')
// Migration classes are generated and version-stamped upstream;
// reformatting them makes diffs against the generator noisy.
->notPath('src/Migrations')
// Symfony's config reference is regenerated by `cache:clear`, which
// composer runs on every install — so it is present in CI even
// though it is gitignored. Formatting it makes the fixer report a
// file the author cannot commit, and a fresh `cache:clear`
// immediately undoes the fix, so CI can never go green.
->notPath('config/reference.php')
->ignoreDotFiles(true)
->ignoreVCS(true)
);
+297
View File
@@ -0,0 +1,297 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased] — v1.1
### Added
- **Passkey authentication (WebAuthn)** — Registered passkeys can replace the
TOTP code for everyday logins. Registration itself still requires a valid
code, so a passkey can never be created without already holding the secret.
- New dependency: `web-auth/webauthn-lib` `^5.3` (resolved to 5.3.9);
`composer audit` reports no advisories.
- **Requires central auth** (`SUBDOMAIN_REDIRECT` + `AUTH_SUBDOMAIN`) so
there is one relying party for the whole domain, and **requires HTTPS in
every environment, development included**. Enabling it in a configuration
that cannot work fails at container start rather than in a browser.
- Registration is a checkbox on the login form; login is a button. Passive
keys and OS pickers work normally, with the code as a fallback.
- New `PasskeyListener` (priority 70) — after the rate-limit gate so a
blocked IP never reaches a ceremony, and before `LoginListener` so a
ceremony request is not misfiled as a failed login.
- New env vars: `PASSKEY_ENABLED`, `PASSKEY_RP_NAME`,
`PASSKEY_USER_VERIFICATION`, `PASSKEY_TIMEOUT`, `PASSKEY_BUTTON_NAME`,
`PASSKEY_REGISTER_NAME`, `PASSKEY_BEGIN_BURST_COUNT`,
`PASSKEY_BEGIN_BURST_TIME`.
- New `docs/examples/Caddyfile` section describing local development over
real TLS, because there is deliberately no `http://` exemption.
- **Public rate-limited access** — Select paths can now be made publicly
accessible without TOTP authentication, with separate per-IP rate limiting.
This is useful for exposing public content (e.g., public Gitea repositories)
while protecting server resources from bot traffic.
- New `PUBLIC_PATHS` env var: comma-separated path patterns with `*` (single
segment) and `**` (cross-segment) wildcard support. Optional host prefix
(e.g., `code.example.com/public/**`). When empty (default), the feature
is fully disabled.
- New `PUBLIC_BURST_COUNT` / `PUBLIC_BURST_TIME` env vars for burst rate
limiting (default: 100 requests per 60 seconds).
- New `PUBLIC_UPPER_COUNT` / `PUBLIC_UPPER_TIME` env vars for sustained
rate limiting (default: 500 requests per 3600 seconds).
- Authenticated users bypass the public rate limiter entirely.
- Over-limit responses include a `Retry-After` header.
- New `PublicPathMatcher` service for path pattern matching.
- New `PublicAccessListener` (priority 84) in the request pipeline.
### Security
- **Passkey ceremonies** — The challenge is issued and stored server-side and
the client's copy is never trusted; it is single-use, deleted before
verification so a failed or replayed attempt cannot be retried against the
same challenge. Only the derived `https://{AUTH_SUBDOMAIN}` origin is ever
accepted, and an unknown credential produces the same response as a wrong
code so the endpoint cannot be used for enumeration.
### Changed
- **Session issuing extracted into `SessionIssuer`** — `LoginManager`
previously built the session cookie itself. Both login paths now share one
implementation, so a passkey login and a code login set an identical cookie;
two copies would have drifted, most likely in cookie attributes, where the
difference is invisible until it breaks in a browser.
- **Upgraded Symfony 7.4 → 8.1** — All `symfony/*` components bumped to
`8.1.*` (resolved to 8.1.2–8.1.6). The 7.4 deprecation sweep was clean
(test suite runs with `failOnDeprecation`), so the major-version jump
required no application code changes. See
`docs/symfony-8.1-upgrade-plan.md`.
### Removed
- **`runtime/frankenphp-symfony`** — No longer needed: `symfony/runtime`
8.1 handles FrankenPHP worker mode natively via its built-in
`FrankenPhpWorkerRunner`. The `extra.runtime` override in
`composer.json` was removed so the runtime auto-detects FrankenPHP.
The old package's `FRANKENPHP_LOOP_MAX` env var is no longer read;
an equivalent recycle limit is restored via the new `MAX_REQUESTS`
setting below.
### Added
- **`MAX_REQUESTS` worker-thread recycle limit** — The `Caddyfile` now
sets FrankenPHP's native `max_requests` from the `MAX_REQUESTS`
environment variable: each PHP worker thread is gracefully restarted
after N requests while others keep serving, containing slow memory
growth across long uptime. The image default is **500** (matching the
previous `runtime/frankenphp-symfony` default), baked in as a Docker
build arg and overridable at runtime (`MAX_REQUESTS=0` disables
restarts). Arbitrary `frankenphp`-block configuration is still
possible via the stock `FRANKENPHP_CONFIG` env var.
### Fixed
- **Login flow responses are no longer cacheable** — the login page,
failed logins, redirects, and rate-limit/error pages now send strict
anti-caching headers (`Cache-Control: no-store, no-cache,
must-revalidate, proxy-revalidate, max-age=0, s-maxage=0` plus
`Pragma`, `Expires`, `Surrogate-Control`, and `Vary: *`), the login
form's `fetch()` bypasses the HTTP cache, and the example Caddyfile
guards every `forward_auth` block with matching `header_down` rules.
This prevents browsers — notably older Safari — from replaying a stale
pre-auth response on refresh (previously: log in successfully, refresh,
and land back on the login page). Successful (2xx) responses are
deliberately excluded: they are consumed by the proxy's `forward_auth`
check and never reach the browser.
### Changed
- **Dockerfile rebuild — same layout as the rest of the portfolio** (Guiding
Light §6.4). The build now copies the tree (`COPY . .`) and lets
`.dockerignore` decide what reaches the context, instead of maintaining a
hand-written `COPY ./x /app/x` allowlist that had to be kept in step with
the project layout. `var/` — which the old file list never copied — now
simply stays out via the ignore file.
- **The image runs as a non-root `app` user** (uid/gid 1000, the same
convention as task-loom/context-shuttle). `/data` (cache pools) and
`/config` are created and owned by it. This resolves the last failing
conformance check (§6.4 `dockerfile-nonroot`).
- **`.dockerignore` rebuilt on the Guiding Light §6.2 baseline** — in
particular `.env` is now excluded explicitly (§6.1), so a developer's
local environment file can never be baked into a layer.
- **`docker/php.ini` and `docker/Caddyfile` added.** The PHP overrides
(`expose_php=Off`, error/log settings, OPcache timestamps off, APCu for
CLI) and the FrankenPHP app config now live in the repository instead of
being three heredocs inside the Dockerfile, so what the image runs is
reviewable in a diff.
- **Runtime base image pinned to `dunglas/frankenphp:1-php8.5-trixie` and
APCu installed via the base image's `install-php-extensions`** — the
versioned tag replaces the floating one, and the build no longer drags a
compiler toolchain into the runtime layer to build one extension.
- **`/app` is now the whole project.** The old image only shipped
`bin/console`, `config`, `public`, `src`, `templates` and the composer
manifests; `config/reference.php` and other loose files are now present.
No application path changes: `public/index.php` and `bin/console` resolve
through the same relative paths.
- `bin/franken.sh` mounts the share dir at its new default
(`/app/var/share`) instead of the old `/app/var/share` bind that no longer
matched the image.
### Fixed
- **`composer dump-env prod --empty` removed.** preauth does not depend on
`symfony/dotenv` (it is not in `composer.lock`), so nothing reads a `.env`
file in the container — the command only produced a dead
`.env.local.php` in the build stage. The Dockerfile comment that claimed
otherwise is gone with it.
- **`composer install` no longer ships a classmap missing `App\`.** The old
build ran `install --optimize-autoloader` before `src/` was copied, and the
final `--classmap-authoritative` dump happened before any `COPY . .`; the
classmap is now rebuilt after the application is in place.
- **The HEALTHCHECK can actually pass.** It probed `curl -f http://localhost/`,
and preauth answers every unauthenticated request to `/` with the login page
and a `401` — so the probe failed 100% of the time and the container was
permanently marked unhealthy. It now probes Caddy's loopback admin endpoint
(the base image's own default probe, restated explicitly), which is why the
Caddyfile deliberately does not disable the admin API.
- **`expose_php` is now genuinely off in the runtime image.** The base image
ships the `php.ini-production` *template* but no active `php.ini`, so the
previous `cp` of the template was the only thing setting it — and the
`docker/php.ini` overrides are loaded after it, so stating it here makes the
intent explicit; verified against a real boot that no `X-Powered-By` header
is emitted.
- `bin/franken.sh` no longer passes `DEFAULT_URI`, which the application does
not read (`config/packages/routing.yaml` sets the router's `default_uri`).
## [1.0.0] — v1.0 Release
### Security
- Made `Remote-User` header value configurable via `REMOTE_USER` environment
variable with four modes: `session` (default), `static`, `mapped`, and `none`.
This allows deployments to prevent user-controlled header values from reaching
backend services.
- Added `SecurityHeadersListener` to set `X-Content-Type-Options`, `X-Frame-Options`,
`Content-Security-Policy`, `Referrer-Policy`, and `Strict-Transport-Security`
headers on all responses.
- Replaced `document.write()` with `document.documentElement.innerHTML` in login
page JavaScript to avoid CSP violations.
- Added CSS escaping (`|e('css')`) to environment-configured color values in
the login page template to prevent CSS injection.
- Documented CSRF protection model: the nonce system provides CSRF protection
for POST form logins (server-generated, single-use, 120s TTL).
- Reduced TOTP verification window from 10 periods (±5 minutes) to 1 period
(±30 seconds) to reduce brute-force attack surface.
- Removed hardcoded `APP_SECRET` from `bin/franken.sh` (now uses environment
variable or generates a random secret).
- Removed backup code values from debug log output.
- Added `.env` to `.gitignore`.
- Expanded TLD list in `DomainManager` with many missing multi-part TLDs
(`.com.au`, `.co.jp`, `.com.br`, `.co.kr`, `.com.tw`, `.co.za`, etc.)
to prevent open redirect vulnerabilities from incorrect domain matching.
- Lowercased host before TLD lookup to fix case-sensitivity issue.
### Fixed
- Fixed `$payload->json` access on possibly-null `$payload` in `LoginListener`
using null-safe operator (`?->`).
- Fixed `validReturn()` not checking `false` return from `parse_url()`, which
could cause a `TypeError` on malformed URLs.
- Added `isHit()` race condition check in `AcceptListener` and `AllowListener`
between `hasItem()` and `getItem()` calls.
- Added `try/finally` in `Kernel::terminate()` so `parent::terminate()` always
runs even if `persist()` throws an exception.
- Added input validation to `GenerateBackupCodesCommand` — rejects count < 1.
### Changed
- Disabled unused Symfony sessions in `framework.yaml` (preauth implements its
own cookie/cache-based session management).
- Standardized git tag format to use `v` prefix (`v1.0.0` instead of `1.0.0`).
- Updated CI workflows to use `v*.*.*` tag pattern and strip `v` prefix for
Docker image tags.
- Removed stale `develop` branch from CI triggers.
- Fixed `publish.yaml` to use `git remote set-url` on re-runs instead of
failing when the remote already exists.
- Explicitly install `curl` in the Docker final image (needed for healthcheck).
- Added `declare(strict_types=1)` to all interface files.
- Added `#[AsCommand]` attribute to `GenerateBackupCodesCommand`.
- Fixed `BackupCodeInterface` default count to match implementation (10).
- Used `Response::HTTP_INTERNAL_SERVER_ERROR` constant in `GetTotpTrait`
instead of literal `500`.
## [0.10.0] - 2026-08-11
### Added
- PHP-CS-Fixer with PSR-12 configuration and CI check.
## [0.9.0] - 2026-07-15
### Added
- PHPUnit test suite — 222 tests, 100% code coverage (lines, methods, classes).
## [0.8.1] - 2026-05-30
### Fixed
- Bug fixes and cleanup from develop branch merge.
## [0.8.0] - 2026-05-29
### Changed
- Renamed form fields for clarity.
- Fixed invalid login bug.
## [0.7.0] - 2026-05-29
### Added
- Single-use backup codes via `app:generate-backup-codes` console command.
- Cache persistence improvement — only write changed keys to file storage.
### Removed
- Static password and lookup token (security risks).
### Changed
- Updated to PHP 8.5, updated dependencies.
## [0.6.0] - 2026-02-10
### Added
- Optional (disabled by default) ability to lookup token by static password.
## [0.5.0] - 2026-01-17
### Added
- Optional (disabled by default) ability to use a static password as backup auth.
### Changed
- Nonce-related cleanup.
## [0.4.1] - 2025-12-26
### Fixed
- Bug which can occur if cache files are deleted.
## [0.4.0] - 2025-12-26
### Changed
- Massive rewrite to listener-based architecture instead of controllers.
- Login payload sent via `X-Preauth` header instead of GET request parameters.
- Enhanced cookie security.
- Removed icon system and asset system.
## [0.3.0] - 2025-12-15
### Changed
- **Breaking:** Default port and transport changed to HTTP on port 80.
- **Breaking:** Environment variable names have changed.
- Refactored to Symfony 7.4 with FrankenPHP.
## [0.2.0] - 2025-12-03
### Added
- Login rate limiting (burst + upper window).
- Error page for rate-limited clients ("too many requests").
- Example Docker Compose file.
## [0.1.0] - 2025-11-14
### Added
- Docker image published to Docker Hub.
- PHP-FPM based, code in `src/`, templates in separate files.
## [0.0.1] - 2024-06-26
### Notes
- Started as a single-file script in Caddy config. Hardcoded TOTP secret,
zero flexibility, but functional. Ran quietly in production for about a
year before any real development began.
+74
View File
@@ -0,0 +1,74 @@
# Contributing to Preauth
Thank you for your interest in contributing to Preauth! This document
outlines the process for contributing to the project.
## Development Setup
1. Clone the repository
2. Install dependencies: `composer install`
3. Copy `.env.example` to `.env` and configure as needed
4. Run tests: `vendor/bin/phpunit`
## Code Style
This project follows [PSR-12](https://www.php-fig.org/psr/psr-12/) and
includes `php-cs-fixer` as a dev dependency.
```bash
# Check for style violations
vendor/bin/php-cs-fixer fix --dry-run --diff
# Auto-fix
vendor/bin/php-cs-fixer fix
```
All code must pass the style check before it can be merged.
## Testing
All code changes must include tests. The project maintains 100% code
coverage — new code must be fully tested.
```bash
# Run tests
vendor/bin/phpunit
# Run with coverage (requires Xdebug)
XDEBUG_MODE=coverage vendor/bin/phpunit --coverage-text
```
### Test Structure
- **Unit tests** go in `tests/Unit/` and mirror the `src/` directory structure
- **Functional tests** go in `tests/Functional/` and test the full HTTP kernel
- Use the support traits (`TotpTestHelper`, `ListenerTestHelper`) for
reusable test fixtures
## Pull Request Process
1. Create a feature branch from `main`
2. Make your changes, ensuring tests pass and code style is clean
3. Update documentation if needed (README, CHANGELOG, docs/)
4. Submit a pull request to `main`
### Commit Messages
Use conventional commit format:
- `feat:` new feature
- `fix:` bug fix
- `docs:` documentation only
- `refactor:` code change that neither fixes a bug nor adds a feature
- `test:` adding or correcting tests
- `chore:` build process, tooling, etc.
## Architecture
Preauth is an event-listener-driven Symfony application (no controllers).
See `ROADMAP.md` for the full architecture overview and design decisions.
## License
By contributing, you agree that your contributions will be licensed under
the MIT License.
+14
View File
@@ -1,3 +1,17 @@
{
frankenphp {
# Restart each PHP worker thread after this many requests, containing
# slow memory growth across long uptime. Preserves the 7.4-era default
# loop count of runtime/frankenphp-symfony (500) after the Symfony 8.1
# upgrade. Set MAX_REQUESTS=0 to disable restarts. The Dockerfile bakes
# in the default of 500 via build arg; override at runtime with:
# docker run -e MAX_REQUESTS=5000 ...
# For full control, the stock FRANKENPHP_CONFIG env var can inject any
# directive under this block instead.
max_requests {$MAX_REQUESTS}
}
}
http:// http://
root public/ root public/
rewrite index.php rewrite index.php
+352
View File
@@ -0,0 +1,352 @@
# Design Considerations — Preauth
## Summary
Preauth is a well-architected TOTP-based authentication gateway that has evolved from a single-file script into a clean, event-listener-driven Symfony application with 100% test coverage. The codebase demonstrates strong security fundamentals (host-prefixed cookies, nonce-based replay protection, rate limiting, backup code system) and thoughtful operational design (dual-layer cache with change tracking, FrankenPHP worker mode).
This document was originally prepared as a design review. Items that have been addressed are marked with ✅ and include a reference to the commit or change that resolved them. Items still open are marked with ⬜ and remain as recommendations for future work.
---
## 0. Passkey implementation notes
Four decisions are worth recording because the reasoning is not obvious from the
code, and each looks like an odd choice without it.
### 0.1 The signature counter is checked leniently, against the library's default
`webauthn-lib`'s default checker requires a *strictly increasing* counter. That
is wrong for the passkeys this feature targets: a synchronised passkey reports a
constant `0` forever, so the default rejects a brand-new credential on its
**first** login. Measured against the installed version: stored `0`, reported
`0` → `CounterException`.
The failure mode is what makes this worth a note. It cannot happen in a unit
test that increments the counter — only on real hardware, and only for the most
common kind of passkey. `PasskeyCounterChecker` therefore accepts equal-or-greater
and rejects only a counter that moves *backwards*. Clone detection is explicitly
not claimed as a property of this feature.
### 0.2 The ceremony replies are the only browser-facing 2xx
`SecurityHeadersListener` applies `no-store` to non-2xx responses only, on the
assumption that a 2xx is consumed by the proxy's `forward_auth` check. That
assumption is false for a ceremony reply: the auth subdomain is `reverse_proxy`-ed
with no `forward_auth` in front of it, so the JSON goes straight to the browser.
Left alone it would be cacheable, and a browser could replay a stale challenge.
The producer marks the response (`PasskeyListener` or `LoginManager`) and the
caching policy lives in one place that consumes the marker, rather than being
duplicated at each site that happens to return 2xx.
### 0.3 Registration is a checkbox on the login form, not an endpoint
A separate `register-begin` endpoint was the first design and would have been a
vulnerability: it hands out a challenge without proving anything. The TOTP check
is what authorises registration, and that check happens inside `LoginManager` as
part of an ordinary login submission — so `LoginManager` is where the ceremony
starts.
There is no session cookie to check at that point either, which makes the point
neatly: the whole flow is what *produces* the session, so anything gated on one
cannot be part of it. The capability at `register-finish` is the single-use
ceremony id, issued server-side and bound to the identity that passed the check.
### 0.4 Both login paths share one session-issuing implementation
`SessionIssuer` was extracted from `LoginManager` when the passkey ceremony
needed the same behaviour. Two implementations would have drifted, and the most
likely place to drift is cookie attributes — where a difference is invisible
until it breaks in a browser, on one path only. A functional test compares the
cookies the two paths produce, field by field.
---
## 1. Security
### 1.1 Missing Security Response Headers [HIGH PRIORITY] ✅ Addressed
**Current state:** Fixed. A `SecurityHeadersListener` (response event, priority 0) now sets the following headers on all main-request responses:
```
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'
Referrer-Policy: strict-origin-when-cross-origin
Strict-Transport-Security: max-age=31536000
```
The inline `<script>` and `<style>` in the templates mean a CSP with `'unsafe-inline'` for `script-src` and `style-src` is the strictest practical policy today. Moving scripts/styles to external files would allow a stricter CSP in the future.
### 1.2 Remote-User Header Value is User-Controlled [HIGH PRIORITY] ✅ Addressed
**Current state:** Fixed. The `Remote-User` header value is now configurable via the `REMOTE_USER` environment variable, which supports four modes:
- **`session`** (default, backward-compatible): Sends the session id, as before. The value is still sanitized via `makeCacheKey()`.
- **`static`**: Sends a fixed string (configurable via `REMOTE_USER_STATIC`, default `authenticated`) for all authenticated requests. This eliminates the user-controlled header issue entirely.
- **`mapped`**: Looks up the session id in a configured map (`REMOTE_USER_MAP`, format: `id1:user1,id2:user2`) and sends the mapped value. Falls back to the session id if not found in the map. This is the path to multi-user support.
- **`none`**: Omits the `Remote-User` header entirely. Caddy's `forward_auth` still accepts the request based on the 200 status code.
The `RemoteUserMode` enum (`src/Enum/RemoteUserMode.php`) encapsulates the modes. `StringTrait::authSuccessResponse()` resolves the header value based on the configured mode, and `ConfigBag` handles parsing the map string and validating the mode (invalid values fall back to `session`). `AcceptListener` now receives `ConfigBag` as a constructor dependency to support this.
### 1.3 No CSRF Protection on POST Form Login [MEDIUM PRIORITY] ✅ Addressed
**Current state:** Resolved through documentation and analysis. The nonce system provides CSRF protection for the POST form path: nonces are server-generated, single-use, and have a 120-second TTL. An attacker cannot forge a POST request without first loading the login page to obtain a valid nonce, which requires being on the auth subdomain. The `LoginListener` class docblock and `login.html.twig` template comment now explicitly document this CSRF protection model. The AJAX (header) path embeds the nonce in the base64url payload.
### 1.4 TOTP Verification Leeway May Be Too Generous [LOW PRIORITY] ✅ Addressed
**Current state:** Fixed. The TOTP verification window has been reduced from 10 periods (±5 minutes) to 1 period (±30 seconds). With the default 30-second TOTP period, a code is now valid for at most 90 seconds (the current window plus one window on each side), down from the previous 50 seconds per window with 10-period leeway. The ROADMAP has been updated to reflect this change.
### 1.5 Backup Code Logging Reveals Code Value [LOW PRIORITY] ✅ Addressed
**Current state:** Fixed. The debug log in `BackupCodeManager::verifyAndConsume()` no longer includes the backup key name. It now logs only the hit/miss and valid/invalid status: `"checking backup code: HIT & VALID"` or `"checking backup code: miss & invalid"`.
### 1.6 TOTP Object Reconstructed on Every Verification [LOW PRIORITY] ⬜ Open
**Current state:** `GetTotpTrait::getTotp()` calls `OTHP\Factory::loadFromProvisioningUri()` on every invocation. This parses the OTP URI string and constructs a new TOTP object each time a token is verified.
**Note:** An attempt was made to memoize the TOTP object within the request cycle, but PHP 8.4's `readonly` class constraint prevents traits from defining mutable properties in `readonly` classes (`LoginManager` and `BackupCodeManager` are both `final readonly`). Resolving this would require either removing `readonly` from these classes, using a separate memoization service, or refactoring `GetTotpTrait` into a dedicated injectable service.
**Why:** This is a minor performance concern — URI parsing and TOTP object construction happen on every login attempt. In a FrankenPHP worker process that handles many requests, this adds unnecessary overhead. It's not a security issue, but it's an easy optimization if the readonly constraint is relaxed.
### 1.7 CSS Injection in Style Template [MEDIUM PRIORITY] ✅ Addressed
**Current state:** Fixed. Environment-configured color values (`bg_color`, `fg_color`, `error_color`) in `_style.html.twig` are now escaped with Twig's `|e('css')` filter to prevent CSS injection from malicious environment variable values.
### 1.8 $payload->json Access on Possibly-Null Payload [HIGH PRIORITY] ✅ Addressed
**Current state:** Fixed. In `LoginListener::onKernelRequest()`, the `$payload->json` access on a possibly-null `$payload` has been replaced with `$payload?->json ?? true`, and `$payload->id` with `$payload?->id ?? ''`. This prevents a crash when a login attempt is detected (e.g., via the `X-Preauth` header) but the payload is invalid (malformed base64, non-object JSON, etc.).
### 1.9 validReturn() Doesn't Check false from parse_url [MEDIUM PRIORITY] ✅ Addressed
**Current state:** Fixed. `DomainManager::validReturn()` now checks for `false` and empty string in addition to `null` when examining the return value of `parse_url($url, PHP_URL_HOST)`. This prevents a `TypeError` on malformed URLs that `filter_var(FILTER_VALIDATE_URL)` accepts but `parse_url` cannot parse.
### 1.10 Incomplete TLD List in DomainManager [HIGH PRIORITY] ✅ Addressed
**Current state:** Fixed. The TLD lookup table in `DomainManager` has been significantly expanded with many previously missing multi-part TLDs, including `.com.au`, `.co.jp`, `.com.br`, `.co.kr`, `.com.tw`, `.co.za`, and dozens more. Without these entries, domains like `evil.com.au` would incorrectly match `auth.example.com.au` (both would resolve to base `com.au`), creating an open redirect vulnerability. The host is also now lowercased before TLD lookup to fix a case-sensitivity issue.
---
## 2. Architecture & Code Quality
### 2.1 Trait-Based Dependency Injection Pattern [MEDIUM PRIORITY] ⬜ Open
**Current state:** Several traits (`HasLoggerTrait`, `GetTotpTrait`, `MakeNonceTrait`) use `#[Required]` attribute for setter injection into `readonly` classes. For example, `LoginManager` receives `$config`, `$logger`, and `$nonceCache` via traits rather than through its constructor. The constructor only accepts three parameters; the rest are wired via setter methods called by the service container after construction.
**Recommendation:** Move these dependencies into the constructors of the classes that use them. If multiple classes share the same dependencies, that's fine — PHP constructors can accept many parameters, and it makes the dependency graph explicit. Alternatively, create a shared `Dependencies` value object that bundles logger, config, and nonce cache.
**Why:** The trait-based setter injection pattern makes it non-obvious what dependencies a class has — you have to look at both the constructor and all the traits it uses. It also creates a temporal coupling issue: the object exists in a partially-constructed state between construction and setter calls. With `readonly` classes, this works only because the trait properties are declared in the trait, not the class, which is a subtle language detail that could confuse future maintainers. Standard constructor injection is more explicit, testable, and conventional in Symfony.
### 2.2 Duplicated Cookie Logic Between LoginManager and InterceptListener [MEDIUM PRIORITY] ✅ Addressed
**Current state:** Resolved. The duplicated cookie name and domain selection logic has been extracted into two shared methods on `CookieNameTrait`:
- `sessionCookieName(DomainInterface $domainManager): string` — Returns the appropriate cookie name (`__Host-Http-Preauth` or `__Http-Domain-Preauth`) based on whether central auth is active.
- `sessionCookieDomain(DomainInterface $domainManager, string $host): ?string` — Returns the cookie domain for central auth mode, or null for single-domain mode.
`LoginManager::setCookie()`, `AcceptListener::onKernelRequest()`, and `InterceptListener::pruneInvalidCookie()` all now use these shared methods. The fragile "changes here must be reflected in InterceptListener::pruneInvalidCookie()" comment has been removed.
### 2.3 MonitorCacheKeys Instantiated Multiple Times for Same Pool [MEDIUM PRIORITY] ⬜ Open
**Current state:** `MonitorCacheKeys` is a decorator that tracks cache key changes. It's instantiated independently in `PersistCache`, `LoginManager`, and `BackupCodeManager`, each wrapping the same underlying `CacheItemPoolInterface`. The key list (`__key_list`) and change list (`__chg_list`) are stored in the cache itself, so the instances share state — but each instance calls `initialize()` in its constructor if the lists don't exist yet, and each `save()`/`saveDeferred()` call triggers additional metadata writes.
**Recommendation:** Register `MonitorCacheKeys` as a decorated service in the DI container (using Symfony's `decorates` feature) so there's a single instance per cache pool. Or, make `MonitorCacheKeys` a stateless service that's injected once, rather than having each consumer create its own wrapper.
**Why:** Multiple instances wrapping the same pool is wasteful — each `save()` call triggers a cascade of metadata operations (update key list, log change, commit). With three instances, a single cache write could trigger nine additional cache operations. A single decorator service would be more efficient and would make the lifecycle clearer.
### 2.4 Payload Base64url Decoding Has Broken Padding [MEDIUM PRIORITY] ✅ Already Correct
**Current state:** Not an issue. The code correctly uses:
```php
$base64 = strtr($base64url, '-_', '+/');
$base64 .= str_repeat('=', (4 - strlen($base64) % 4) % 4);
```
This was fixed in a prior commit ("Fix docs, add .dockerignore, fix base64url padding, fix typo"). The original review incorrectly reported the use of `str_pad`; the implementation now correctly uses `str_repeat` to add the proper number of `=` padding characters.
### 2.5 Symfony Sessions Enabled But Unused [LOW PRIORITY] ✅ Addressed
**Current state:** Fixed. `config/packages/framework.yaml` now has `session: false` with a comment explaining that preauth implements its own cookie/cache-based session management and does not use Symfony's session subsystem.
### 2.6 config/reference.php Committed to Repository [LOW PRIORITY] ✅ Already Handled
**Current state:** Not an issue. `config/reference.php` is already listed in `.gitignore` under the project-specific section and is not tracked in version control.
### 2.7 Public Properties on Payload DTO [LOW PRIORITY] ⬜ Open
**Current state:** `Payload` uses public properties (`$id`, `$token`, `$nonce`, `$json`, `$scope`) with no encapsulation. The object is mutable after construction.
**Recommendation:** Consider making `Payload` a `readonly` class (PHP 8.4+ supports `readonly` classes natively) with a constructor that takes all fields, or use Symfony's `Stringable`/value object patterns. Since `LoginManager` mutates `$payload->scope` (downgrading IP to Cookie), the current design requires mutability — but this could be handled by returning a new instance instead.
**Why:** Immutable DTOs are safer to pass around, especially in an event-driven system where the same object might be referenced by multiple listeners. The current mutation in `LoginManager::checkToken()` (changing `$payload->scope`) is a side effect that's not obvious from the method signature.
### 2.8 Duplicated "hi $id" Response Construction [LOW PRIORITY] ✅ Addressed
**Current state:** Fixed. The duplicated `new Response("hi $id", headers: ['Content-Type' => 'text/plain', 'Remote-User' => $id])` pattern in `AcceptListener`, `AllowListener`, and `LoginManager` has been extracted into `StringTrait::authSuccessResponse(string $id): Response`, which all three classes now use.
### 2.9 Duplicated Constants [LOW PRIORITY] ✅ Addressed
**Current state:** Fixed. The duplicated `'2999-12-31'` far-future date string (previously in `Utilities::makeTotp()` and `BackupCodeManager::verifyAndConsume()`/`saveCodes()`) and the `128` max input length (previously in `StringTrait::makeCacheKey()` and `Payload::create()`) have been extracted into `AppConstants::FAR_FUTURE_DATE` and `AppConstants::MAX_INPUT_LENGTH` respectively.
---
## 3. Testing
### 3.1 No Tests for Concurrent Access / Race Conditions [LOW PRIORITY] ⬜ Open
**Current state:** The test suite is excellent — 222 tests, 100% coverage, good edge case coverage. However, there are no tests for concurrent access scenarios, such as two requests using the same nonce simultaneously, or cache initialization race conditions in `MonitorCacheKeys`.
**Recommendation:** Add a few integration tests that simulate concurrent access (e.g., using process forks or mock caches with delays). At minimum, document that concurrent access is expected to be handled by APCu's atomic operations.
**Why:** `MonitorCacheKeys::initialize()` checks if key lists exist and creates them if not — under concurrent startup, two instances could both see missing lists and both call `initialize()`. This is likely fine because APCu operations are atomic, but it's worth having a test or at least a documented assumption. The race condition between `hasItem()` and `getItem()` in `AcceptListener` and `AllowListener` is now handled with an `isHit()` check, but is not tested.
### 3.2 No Security-Focused Test Suite [LOW PRIORITY] ⬜ Open
**Current state:** Security behaviors (nonce replay, backup code reuse, rate limiting) are tested as part of the functional and unit tests, but there's no dedicated security test suite that systematically probes for common vulnerabilities.
**Recommendation:** Consider adding a `tests/Security/` directory with tests for: XSS attempts in the username field, header injection via the `return` parameter, cookie attribute verification (Secure, HttpOnly, SameSite), and response header presence (now that security headers are added).
**Why:** For an authentication gateway, security testing deserves its own focused suite that's easy to find and extend. This also makes it easier for security reviewers to understand what's been tested.
---
## 4. Docker & Deployment
### 4.1 Healthcheck Depends on curl Which May Not Be Installed [MEDIUM PRIORITY] ✅ Addressed
**Current state:** Fixed. The Dockerfile now explicitly installs `curl` in the final image with `apt-get install -y --no-install-recommends curl` and cleans up the apt lists to keep the image small.
### 4.2 Typo in bin/franken.sh [LOW PRIORITY] ✅ Already Fixed / Addressed
**Current state:** Fixed. The typo (`digtialadapt` → `digitaladapt`) was corrected in a prior commit. The script has since been further improved: the hardcoded `APP_SECRET` has been removed (now uses the `APP_SECRET` environment variable or generates a random secret), and the `docker container rm` command now suppresses errors when the container doesn't exist.
### 4.3 No .dockerignore File [LOW PRIORITY] ✅ Already Handled
**Current state:** Not an issue. A `.dockerignore` file exists and excludes `.git/`, `.gitignore`, `var/`, `vendor/`, `tests/`, `.phpunit.cache/`, `docs/`, `*.md`, `.env`, `.env.test`, `.env.local`, and `composer.phar` from the Docker build context. This was added in a prior commit.
### 4.4 Dockerfile Uses PHP 8.5 Which Is Bleeding Edge [LOW PRIORITY] ⬜ Open (Deliberate)
**Current state:** The Dockerfile uses `php:8.5-trixie` for the build stage and `dunglas/frankenphp:php8.5-trixie` for the final image. `composer.json` requires `php >= 8.4`. The CI workflow in `tests.yaml` also uses PHP 8.5.
**Recommendation:** This is a deliberate choice and likely fine for a personal project. If broader compatibility is desired, consider testing against both PHP 8.4 and 8.5 in CI. The `composer.json` already allows 8.4+.
---
## 5. Error Handling
### 5.1 Cache Exceptions Propagate as 500 Errors [MEDIUM PRIORITY] ✅ Addressed
**Current state:** Fixed. Cache operations in `AcceptListener::onKernelRequest()` and `AllowListener::onKernelRequest()` are now wrapped in try/catch blocks that catch `Psr\Cache\InvalidArgumentException`. On a cache error, the listener logs the error at `error` level and returns without setting a response — causing the request to fall through to the next listener, which will eventually present the login page. This is a "fail closed" approach: if the cache is unavailable, the user is not authenticated.
**Note:** `LoginManager::checkToken()` and `BackupCodeManager::verifyAndConsume()` still declare `@throws InvalidArgumentException`. These are called from `LoginListener`, which does not catch the exception. A cache failure during login verification would still result in a 500 error. This is a lower-priority concern since login failures already result in a 401 response path.
### 5.2 No Global Exception Handling for Auth Flow [LOW PRIORITY] ⬜ Open
**Current state:** There is no `ExceptionListener` or `ErrorController` configured. Symfony's default error handling will produce a generic error page for uncaught exceptions. In dev mode (`APP_DEBUG=1`), this shows a full stack trace.
**Recommendation:** Add a simple exception listener that catches exceptions from the auth flow and returns a clean 401 or 503 response with the login page or error template. Alternatively, configure `framework.error_controller` to use a custom controller that renders the error template.
**Why:** For an auth gateway, every response should be intentional. A raw Symfony error page (even in production mode) doesn't match the styled login/error pages and could leak information about the internal architecture.
### 5.3 Kernel::terminate() Not Using try/finally [MEDIUM PRIORITY] ✅ Addressed
**Current state:** Fixed. `Kernel::terminate()` now wraps `$this->persistCache->persist()` in a `try` block with a `finally` block that calls `parent::terminate()`. This ensures that the Symfony kernel termination always runs, even if the cache persistence throws an exception.
---
## 6. Frontend
### 6.1 document.write() in Login Script [MEDIUM PRIORITY] ✅ Addressed
**Current state:** Fixed. The `document.open(); document.write(html); document.close();` pattern in `_script.html.twig` has been replaced with `document.documentElement.innerHTML = html;`. This avoids the deprecated `document.write()` call and is compatible with the Content-Security-Policy now set by `SecurityHeadersListener`.
### 6.2 No Input Sanitization in Username Echo [LOW PRIORITY] ⬜ Open
**Current state:** In `login.html.twig`, the username is echoed back into the input value: `value="{{ username }}"`. The username comes from the sanitized `makeCacheKey()` output, which restricts to `[A-Za-z0-9_.]`, so HTML injection is not possible with the current sanitization. Twig's auto-escaping is also on by default.
**Recommendation:** Add Twig's `escape` filter explicitly for defense-in-depth: `value="{{ username|e('html_attr') }}"`. Also consider whether the `message` variable in `<p id="preauth-message">{{ message|default }}</p>` could ever contain user input.
**Why:** While the current sanitization prevents XSS, relying on `makeCacheKey()` for HTML safety is an implicit coupling between cache key logic and output safety. If `makeCacheKey()` were ever relaxed to allow more characters, the template would become vulnerable. Twig auto-escaping handles HTML body context, but `html_attr` escaping is more appropriate for attribute contexts.
---
## 7. Configuration
### 7.1 No Validation of Environment Variables [LOW PRIORITY] ✅ Addressed
**Current state:** Fixed. Environment variables in `config/services.yaml` now use Symfony's env var processors for type casting:
- `app.cookie_ttl: '%env(int:COOKIE_TTL)%'`
- `app.subdomain_redirect: '%env(bool:SUBDOMAIN_REDIRECT)%'`
- `app.ip_ttl: '%env(int:IP_TTL)%'`
- `app.teapot: '%env(bool:TEAPOT)%'`
This ensures invalid values fail fast at container compilation rather than at runtime with a confusing type error. The `rate_limiter.yaml` already used `%env(int:...)%` — this pattern is now applied consistently.
### 7.2 APP_SECRET Not Used Meaningfully [LOW PRIORITY] ✅ Addressed (Documented)
**Current state:** `APP_SECRET` is configured in `framework.yaml` and is required by Symfony. Preauth doesn't use Symfony sessions (now explicitly disabled), CSRF tokens, or signed cookies — the main uses of `APP_SECRET`. The README now documents that `APP_SECRET` is a Symfony requirement and that session cookies are random ULIDs looked up in cache, not signed tokens. The hardcoded `APP_SECRET` in `bin/franken.sh` has also been removed.
---
## 8. Documentation
### 8.1 Missing Security Model Documentation [MEDIUM PRIORITY] ✅ Addressed
**Current state:** Addressed. The README now includes a comprehensive "Security Model" section under "Architecture" that covers:
- Cookie security attributes (`__Host-` prefix, `SameSite=Strict`, `Secure`, `HttpOnly`)
- Nonce system (15-byte random, single-use, 120s TTL)
- TOTP verification window (±1 period / ±30 seconds)
- Backup codes (case-insensitive, single-use, alphanumeric)
- Rate limiting (per-IP, compound sliding window, cannot be disabled)
- Security headers (CSP, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, HSTS)
A dedicated `docs/SECURITY.md` with the full threat model and `Remote-User` guidance (see item 1.2) could still be valuable as a standalone document.
### 8.2 Missing CHANGELOG.md [MEDIUM PRIORITY] ✅ Addressed
**Current state:** Fixed. A `CHANGELOG.md` has been created following the [Keep a Changelog](https://keepachangelog.com/) format, with full version history from v0.0.1 through the unreleased v1.0 changes. The version history was previously inline in the README.
### 8.3 Missing CONTRIBUTING.md [LOW PRIORITY] ✅ Addressed
**Current state:** Fixed. A `CONTRIBUTING.md` has been created with development setup instructions, code style guidelines, testing requirements, PR process, commit message conventions, and architecture overview.
### 8.4 Stale Branch References in ROADMAP [LOW PRIORITY] ✅ Addressed
**Current state:** Fixed. The ROADMAP's branch status table has been updated to reflect that all feature branches have been pruned and development uses a feature-branch + PR workflow into `main`. Completed security review items are now checked off, and the TOTP leeway description has been updated from "10-second leeway" to "±1 period leeway (±30 seconds)".
---
## 9. CI & Workflows
### 9.1 Inconsistent Tag Format [MEDIUM PRIORITY] ✅ Addressed
**Current state:** Fixed. Git tags are now standardized on the `v` prefix (e.g., `v1.0.0` instead of `1.0.0`). The Docker workflow (`docker.yaml`) now triggers on `v*.*.*` tag patterns and includes a step to extract the version number without the `v` prefix for the Docker image tag. The existing un-prefixed tags (`0.7.0` through `0.10.0`) remain in the repository but all future releases will use the `v` prefix.
### 9.2 Stale develop Branch in CI Triggers [LOW PRIORITY] ✅ Addressed
**Current state:** Fixed. The `tests.yaml` and `develop.yaml` workflows no longer reference the `develop` branch, which has been pruned. CI now triggers on `main` only (for push) and `main` only (for pull requests).
### 9.3 publish.yaml Fails on Re-run [LOW PRIORITY] ✅ Addressed
**Current state:** Fixed. The GitHub sync workflow (`publish.yaml`) now uses `git remote add ... 2>/dev/null || git remote set-url ...` instead of bare `git remote add`, which would fail if the remote already existed from a previous run.
---
## What's Done Well
- **Listener-based architecture** is a good fit for this use case — each listener has a single responsibility, and the priority chain creates a clear request processing pipeline.
- **Cookie security** is excellent: `__Host-` prefix, `Secure`, `HttpOnly`, `SameSite=Strict`, and a separate non-prefixed cookie for domain-scoped central auth. Cookie name and domain selection logic is now shared via `CookieNameTrait::sessionCookieName()` and `sessionCookieDomain()`.
- **Nonce-based replay protection** with single-use, TTL-limited nonces and collision retry is well-designed. The nonce also serves as CSRF protection for the POST form path.
- **Rate limiting** with compound sliding windows (burst + sustained) and the humorous teapot option is practical and well-implemented.
- **Test suite** is exemplary: 100% coverage, good use of test helpers, functional tests that exercise the full kernel, and edge cases like ULID collisions and nonce reuse.
- **Dual-layer cache** (APCu + filesystem with change tracking) is a clever solution for persistence without a database.
- **Backup code system** with single-use enforcement, case-insensitivity, and audit trail (keeping consumed codes with `false` value) is well thought out. Backup code values are no longer logged.
- **Interfaces** (`LoginInterface`, `DomainInterface`, `BackupCodeInterface`) enable clean mocking in tests. All now have `declare(strict_types=1)`.
- **FrankenPHP worker mode** via the Caddyfile and Dockerfile is a modern, performant serving strategy.
- **Security headers** are now set on all responses via `SecurityHeadersListener`.
- **Error handling** in cache-dependent listeners now fails closed (denies access on cache errors) rather than propagating 500 errors.
---
*Originally prepared as a design review. Updated to reflect the state of the `fix/v1.0-must-fix` branch.*
+110 -51
View File
@@ -1,69 +1,128 @@
# use build image, to simplify final image # syntax=docker/dockerfile:1.7
#
# PreAuth — one app, one image.
#
# Multi-stage FrankenPHP build: dependencies in a builder, the runtime image
# only gets the finished tree. Runtime: FrankenPHP worker mode, non-root,
# state on /data. TLS is terminated upstream of the container; FrankenPHP
# serves :80.
#
# Build context: the whole tree (`COPY . .`), narrowed by .dockerignore. The
# allowlist that used to live in the eight `COPY ./x /app/x` below is in that
# file now — a directory that must ship is a directory it does not exclude.
#
# Secrets are injected at runtime as env vars, never baked in (§8.12).
# ── Stage: build — composer dependencies + prod app ────────────────────────
FROM php:8.5-trixie AS build FROM php:8.5-trixie AS build
# install APCu and composer # Build-time set: git (composer resolves packages over VCS) and unzip (dist
RUN pecl install apcu && \ # extraction). Neither reaches the runtime image.
docker-php-ext-enable apcu RUN apt-get update \
COPY --from=composer /usr/bin/composer /usr/bin/composer && apt-get install -y --no-install-recommends git unzip \
RUN apt-get update && \ && rm -rf /var/lib/apt/lists/*
apt-get install -y unzip git
# symfony required environment variables # APCu and Composer, both only needed to compile the application.
ENV APP_DEBUG=0 RUN pecl install apcu \
ENV APP_ENV=prod && docker-php-ext-enable apcu
ENV APP_SHARE_DIR=/data/preauth COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
# load application into build image
RUN mkdir -p /data/preauth
RUN mkdir -p /app/bin
WORKDIR /app WORKDIR /app
COPY ./bin/console /app/bin/console
COPY ./config /app/config
COPY ./public /app/public
COPY ./src /app/src
COPY ./templates /app/templates
COPY ./composer.json /app/composer.json
COPY ./composer.lock /app/composer.lock
COPY ./symfony.lock /app/symfony.lock
# install application dependencies # Manifests first so the dependency layer only rebuilds when they change.
RUN composer install --no-dev --optimize-autoloader COPY composer.json composer.lock symfony.lock ./
RUN composer dump-env prod --empty RUN composer install --no-dev --no-interaction --prefer-dist \
--optimize-autoloader --no-scripts
# start creating final image # Copy the application. .dockerignore keeps vendor/, var/, tests/ and the
FROM dunglas/frankenphp:php8.5-trixie # local env files out of the context; composer install has already run, so
# its vendor/ wins.
COPY . .
# install APCu # src/ was not in the context when composer install ran, so the authoritative
RUN pecl install apcu && \ # classmap has to be rebuilt now that the application code is present.
docker-php-ext-enable apcu #
# There is deliberately no `composer dump-env` step: preauth does not depend
# on symfony/dotenv (it is absent from composer.lock), so nothing reads a
# .env file at runtime and the dump would only add a dead file. Runtime
# configuration comes from the environment, with the defaults documented in
# config/services.yaml.
RUN composer dump-autoload --classmap-authoritative --no-dev
# symfony required environment variables # Build-time smoke of the autoloader + config compile. No APP_SECRET is
ENV APP_DEBUG=0 # needed: %env(APP_SECRET)% is not resolved at compile time, and the cache is
ENV APP_ENV=prod # cleared afterwards anyway — the real warm-up runs at container start with
ENV APP_SHARE_DIR=/data/preauth # the injected secrets (entrypoint; §8.12).
#
# The cache is written to the share dir, not var/cache: the runtime image
# ships without a warmed var/cache, so the first container start does the
# build for its own APP_SECRET (and the pages/ filesystem pool needs a
# writable dir owned by the app user).
RUN APP_ENV=prod APP_SHARE_DIR=/data/preauth bin/console cache:warmup \
&& rm -rf var/cache/* var/log/*
# ── Stage: app — the runtime image ─────────────────────────────────────────
FROM dunglas/frankenphp:1-php8.5-trixie AS app
# Runtime set: curl is the HEALTHCHECK's probe; APCu is the state store.
# The base image ships the install-php-extensions script, which builds the
# extension and removes its own build dependencies afterwards — so git,
# autoconf and gcc never reach this stage the way `pecl install` needed them.
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& install-php-extensions apcu \
&& install-php-extensions intl \
&& rm -rf /var/lib/apt/lists/*
# PHP configuration. The packaged production baseline is copied in first
# (the base image ships the template, not an active php.ini), then the app's
# own overrides are layered on top of it — they restate the security-critical
# switches so the intent survives a base-image default changing underneath us.
COPY docker/php.ini $PHP_INI_DIR/conf.d/zz-preauth.ini
RUN cp $PHP_INI_DIR/php.ini-production $PHP_INI_DIR/php.ini
COPY docker/Caddyfile /etc/frankenphp/Caddyfile
COPY docker/entrypoint.sh /usr/local/bin/entrypoint
RUN chmod +x /usr/local/bin/entrypoint
# load application into final image
WORKDIR /app WORKDIR /app
COPY --from=build /data/preauth /data/preauth
COPY --from=build /app /app COPY --from=build /app /app
# configure container # Non-root runtime user (Guiding Light §6.4). uid/gid 1000, same convention
COPY ./Caddyfile /etc/frankenphp/Caddyfile # as task-loom/task-weaver/context-shuttle. /data holds the cache pools the
RUN cp $PHP_INI_DIR/php.ini-production $PHP_INI_DIR/php.ini # app writes at runtime, /config is Caddy's own XDG dir.
RUN echo 'expose_php = off' > $PHP_INI_DIR/conf.d/restrict.ini RUN groupadd --system --gid 1000 app \
# console needs apc to manage cache && useradd --system --uid 1000 --gid app \
RUN echo 'apc.enable_cli = on' > $PHP_INI_DIR/conf.d/console.ini --home-dir /app --shell /usr/sbin/nologin app \
&& mkdir -p /data/preauth /config \
&& chown -R app:app /app /data
# app uses var folder for cache storage USER app
# FrankenPHP listens on :80; TLS is terminated by the external proxy.
# APP_SHARE_DIR points the filesystem cache pools (sessions, rate limiter)
# at the volume. MAX_REQUESTS is a build arg so images can bake in a
# different worker-recycle default; the Caddyfile placeholder reads it.
ARG MAX_REQUESTS=500
ENV APP_ENV=prod \
APP_DEBUG=0 \
APP_SHARE_DIR=/data/preauth \
SERVER_NAME=:80 \
MAX_REQUESTS=$MAX_REQUESTS
# Persistent state: cache pools (sessions, backup codes, rate limits) and
# Caddy's data. Only /data is needed at runtime; /config is declared because
# the base image points XDG_CONFIG_HOME at it.
VOLUME ["/config", "/data"] VOLUME ["/config", "/data"]
# runs http on standard port
EXPOSE 80 EXPOSE 80
# healthcheck # Liveness: Caddy's own admin endpoint, bound to loopback inside the
HEALTHCHECK --interval=5m \ # container, exactly as the base image declares it (restated here so the
--retries=3 \ # probe does not depend on the upstream default staying put). The app's own
--start-interval=1s \ # routes cannot serve this: an unauthenticated request gets the login page
--start-period=10s \ # with a 401, so `curl -f` against HTTP would always report unhealthy.
--timeout=2s \ HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD curl http://localhost || exit 1 CMD curl -f http://localhost:2019/metrics || exit 1
ENTRYPOINT ["/usr/local/bin/entrypoint"]
CMD ["frankenphp", "run", "--config", "/etc/frankenphp/Caddyfile"]
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 digitaladapt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+482
View File
@@ -0,0 +1,482 @@
# Preauth — Project Roadmap
## Project Overview
Preauth is a pre-authentication gate for self-hosted services. It sits
between a reverse proxy (Caddy's `forward_auth`) and your web service,
requiring a TOTP code (or backup code) before traffic ever reaches the
protected application. It is **not** a replacement for the service's own
authentication — it's a gate that prevents outsiders from even seeing
what service is running.
- **Location:** `projects/preauth/`
- **Framework:** Symfony 8.1 (PHP ≥ 8.4)
- **Serving:** FrankenPHP (Docker image)
- **Cache:** Dual-layer — APCu (in-memory) + file-based persistence
- **Auth:** TOTP (single secret) + single-use backup codes
- **Production status:** Running in production since June 2024
### Current Production Use
| Service | Purpose |
|-------------|--------------------------------------------------|
| Bitwarden | Password manager — always accessible, invisible to the world |
| Microbin | Sharing text blobs and small files across devices |
| Gitea | Code hosting — some DNS configs must be public |
---
## Architecture
### Request Flow
```
Client → Caddy → forward_auth → Preauth listeners (priority order) → 200/401/418
```
1. **AcceptListener** (priority 99) — Checks for valid session cookie.
If found → `200 OK` + `Remote-User` header → Caddy proxies to backend.
2. **AllowListener** (priority 88) — If `IP_TTL` is enabled, checks for
valid IP-based session. If found → `200 OK` + `Remote-User`.
3. **PublicAccessListener** (priority 84) — If `PUBLIC_PATHS` is
configured and the request matches a public path pattern, applies
per-IP rate limiting. Within limit → `200 OK`. Over limit → `429`.
Authenticated users never reach this listener.
4. **RejectListener** (priority 77) — Rate-limiting gate. If IP has
exceeded login attempt threshold → `418 I'm a Teapot` (or `429`).
5. **LoginListener** (priority 66) — Detects login attempts via
`X-Preauth` header (base64url JSON) or POST form on auth subdomain.
Validates TOTP/backup codes through `LoginManager`.
6. **InterceptListener** (priority 55) — Fallback: if no listener has
set a response, either redirects to auth subdomain (central auth) or
renders the Twig login page with a fresh nonce.
### Key Design Decisions
- **No controllers** — Entirely event-listener-driven. Clean separation
of concerns, each listener handles one stage of the auth flow.
- **Dual-layer cache** — APCu for fast in-memory lookups, file-based
storage for persistence across container restarts. `MonitorCacheKeys`
wraps the PSR-6 pool to track key changes for efficient persistence
(only write what changed).
- **`__Host-` prefixed cookies** — `SameSite=Strict`, `Secure`,
`HttpOnly`. Central auth mode uses a separate `__Http-Domain-Preauth`
cookie name (domain-scoped, no `__Host-` prefix).
- **Nonce system** — 15-byte random nonces, single-use, 120s TTL, with
retry-on-collision (up to 3 attempts).
- **TOTP with ±1 period leeway (±30 seconds)** — Accommodates clock drift.
- **Backup codes** — Case-insensitive alphanumeric, single-use, stored
in cache with year-2999 expiry. Generated via console command.
- **Domain awareness** — `DomainManager` handles multi-part TLDs
(`.co.uk`, `.com.au`, etc.) with a built-in TLD lookup table.
- **Interfaces** — `LoginInterface`, `DomainInterface`,
`BackupCodeInterface` extracted to support testing (mockable).
---
## Test Suite Status
### Current Results
| Metric | Value |
|--------------|--------------------------------|
| **Tests** | 293 |
| **Assertions** | 605 |
| **Pass** | 222 (100%) |
| **Fail** | 0 |
| **Errors** | 0 |
| **Warnings** | 0 |
| **Time** | ~0.56s (without coverage) |
| | ~1.31s (with coverage) |
### Code Coverage
| Metric | Percentage |
|----------|---------------------|
| **Lines** | **100.00%** (442/442) |
| **Methods** | **100.00%** (83/83) |
| **Classes** | **100.00%** (21/21) |
Every class, method, and line in `src/` is covered.
### Source → Test Mapping
| Source File | Test File | Type |
|------------------------------------------|----------------------------------------------------|----------|
| `Clock.php` | `Unit/ClockTest.php` | Unit |
| `ConfigBag.php` | `Unit/ConfigBagTest.php` | Unit |
| `Kernel.php` | (covered via functional tests) | Functional |
| `MonitorCacheKeys.php` | `Unit/MonitorCacheKeysTest.php` | Unit |
| `PersistCache.php` | `Unit/PersistCacheTest.php` | Unit |
| `Utilities.php` | `Unit/UtilitiesTest.php` | Unit |
| `Command/GenerateBackupCodesCommand.php` | `Unit/Command/GenerateBackupCodesCommandTest.php` | Unit |
| `Data/Payload.php` | `Unit/Data/PayloadTest.php` | Unit |
| `Enum/Scope.php` | `Unit/Enum/ScopeTest.php` | Unit |
| `Listener/AcceptListener.php` | `Unit/Listener/AcceptListenerTest.php` | Unit |
| `Listener/PublicAccessListener.php` | `Unit/Listener/PublicAccessListenerTest.php` | Unit |
| `Listener/AllowListener.php` | `Unit/Listener/AllowListenerTest.php` | Unit |
| `Listener/InterceptListener.php` | `Unit/Listener/InterceptListenerTest.php` | Unit |
| `Listener/LoginListener.php` | `Unit/Listener/LoginListenerTest.php` | Unit |
| `Listener/RejectListener.php` | `Unit/Listener/RejectListenerTest.php` | Unit |
| `Service/BackupCodeManager.php` | `Unit/Service/BackupCodeManagerTest.php` | Unit |
| `Service/DomainManager.php` | `Unit/Service/DomainManagerTest.php` | Unit |
| `Service/PublicPathMatcher.php` | `Unit/Service/PublicPathMatcherTest.php` | Unit |
| `Service/LoginManager.php` | `Unit/Service/LoginManagerTest.php` | Unit |
| `Trait/CookieNameTrait.php` | `Unit/Trait/CookieNameTraitTest.php` | Unit |
| `Trait/GetTotpTrait.php` | `Unit/Trait/GetTotpTraitTest.php` | Unit |
| `Trait/HasLoggerTrait.php` | `Unit/Trait/HasLoggerTraitTest.php` | Unit |
| `Trait/MakeNonceTrait.php` | `Unit/Trait/MakeNonceTraitTest.php` | Unit |
| `Trait/StringTrait.php` | `Unit/Trait/StringTraitTest.php` | Unit |
| *(All listeners + services)* | `Functional/AuthenticationFlowTest.php` | Functional |
| *(Public access flow)* | `Functional/PublicAccessFlowTest.php` | Functional |
### Test Quality Assessment
**Strengths:**
- **100% coverage** — every line, method, and class.
- **Well-structured test hierarchy** — Unit tests per class, functional
tests for the full HTTP kernel flow. Two support traits
(`TotpTestHelper`, `ListenerTestHelper`) provide reusable fixtures
(frozen clock, deterministic TOTP, Twig environment, mock rate
limiters).
- **Edge cases well-covered** — ULID collision handling, nonce collision
retries, spent nonces, invalid payloads (bad base64, non-object JSON,
arrays, null, booleans), empty/whitespace fields, field truncation,
multibyte characters in cache keys, multi-part TLD domain matching,
cookie pruning on invalid sessions.
- **Both positive and negative paths** — Every listener tests both
success and failure scenarios.
- **Security-conscious testing** — Backup code single-use enforcement,
case-insensitivity, character stripping, rate limit teapot vs.
too-many-requests, return URL validation (prevents open redirect),
cookie security attributes.
- **Realistic functional tests** — `AuthenticationFlowTest` goes through
the actual Symfony kernel: fetches nonces from rendered HTML, submits
TOTP codes, verifies cookies are set, tests the full login →
authenticated access cycle.
- **Smart test infrastructure** — `KernelBrowser::disableReboot()` used
in functional tests so nonces persist across requests (matching
production APCu behavior).
**Status: Test suite goal is met.** 222 tests, 100% coverage, all passing.
---
## Roadmap
### Phase 1 — Public but Rate-Limited Access ✅ Completed (v1.1)
**Goal:** Allow select services to be publicly accessible (no TOTP
required) but with aggressive per-IP rate limiting to prevent bot
traffic from overwhelming the server.
**Context:** The user previously made Gitea semi-public (view but no
login), but bot traffic slowed the server and consumed all household
bandwidth, forcing it back to fully private. The solution isn't more
authentication — it's bandwidth/resource protection for public-facing
services.
**Implementation:**
- New config variables:
- `PUBLIC_PATHS` — Comma-separated path patterns with `*` (single
segment) and `**` (cross-segment) wildcard support. Optional host
prefix (e.g., `code.example.com/public/**`). When empty (default),
the feature is fully disabled.
- `PUBLIC_BURST_COUNT` / `PUBLIC_BURST_TIME` — Burst rate limiting
(default: 100 requests per 60 seconds).
- `PUBLIC_UPPER_COUNT` / `PUBLIC_UPPER_TIME` — Sustained rate limiting
(default: 500 requests per 3600 seconds).
- New listener: **PublicAccessListener** (priority 84, after
AcceptListener and AllowListener, before RejectListener):
- Checks if the request path matches a configured public path pattern.
- If public and within rate limit → `200 OK` (no `Remote-User` header).
- If public and over rate limit → `429 Too Many Requests` with
`Retry-After` header.
- Authenticated users bypass this listener entirely (AcceptListener
or AllowListener returns 200 first).
- New service: **PublicPathMatcher** — Parses path patterns and matches
request paths with wildcard support.
- Separate `public_limiter` compound rate limiter (independent from
the login attempt rate limiter).
- [x] Design public path detection mechanism (path-based with wildcards)
- [x] Implement `PublicAccessListener` with separate rate limiter pool
- [x] Add config variables and defaults
- [x] Update Caddyfile example with public service snippet
- [x] Tests for public mode (within limit, over limit, burst behavior)
- [x] Documentation in README
### Phase 2 — Session Management & Audit
**Goal:** Give visibility into who has access and when it was granted.
- [ ] **Active sessions view** — Console command or simple API endpoint
to list active sessions (cookie-based and IP-based), showing:
- Session ID / username
- IP address
- First auth timestamp
- Last seen timestamp
- Scope (cookie vs. IP)
- [ ] **Session revocation** — Console command to revoke a specific
session by ID or revoke all sessions for an IP.
- [ ] **Audit log** — Log every successful and failed authentication
attempt to a persistent store (file-based JSONL, similar to the email
integration's audit log):
```json
{
"timestamp": "2025-01-15T14:23:01Z",
"ip": "192.168.1.50",
"action": "login_success",
"username": "mom",
"method": "totp"
}
```
- [ ] Tests for all new commands and endpoints
### Phase 2b — Backup Code System Completion
**Goal:** Finish the backup code system — the core logic is solid but
the management surface is incomplete.
**What already exists:**
- ✅ `BackupCodeManager::generate()` — Creates codes, saves to cache
with year-2999 expiry
- ✅ `BackupCodeManager::expire()` — Deletes all `backup_` prefixed
keys from cache
- ✅ `BackupCodeManager::verifyAndConsume()` — Validates and marks code
as used (sets value to `false`, keeps the key for audit trail)
- ✅ `app:generate-backup-codes [count]` console command
- ✅ Tests for all of the above (100% coverage)
**What's missing:**
- [ ] **`app:list-backup-codes` command** — Show backup code status:
- Total codes generated
- How many are still valid (unused)
- How many have been spent (and optionally when)
- Output format: table with status column (✅ valid / ⛔ used)
- Note: spent codes are kept in cache with value `false`, so we can
distinguish "used" from "never existed" — this is good design
- [ ] **`app:expire-backup-codes` command** — Wrap the existing
`BackupCodeManager::expire()` method in a console command. Should:
- Show how many codes are being expired before confirmation
- Support `--force` flag to skip confirmation prompt
- Call `persistCache->boot()` and `persistCache->persist()` like the
generate command does (since `Kernel::terminate()` doesn't run in
CLI)
- [ ] **Notification on backup code use** — When
`verifyAndConsume()` consumes a backup code, fire a notification
through configurable channels:
- Discord webhook (we already have the `discord.sh` infrastructure)
- ntfy
- Email (once email integration is available)
- Webhook (generic HTTP POST for future integrations)
- Config variables:
- `BACKUP_CODE_NOTIFY=discord,ntfy` — comma-separated channels
- `BACKUP_CODE_NOTIFY_WEBHOOK=''` — generic webhook URL
- Message should include: timestamp, IP address, username, and how
many valid codes remain
- Architecture: `BackupCodeManager` dispatches an event
(e.g. `BackupCodeUsedEvent`) after consuming a code. A listener
handles the notification dispatch. This keeps the notification
logic out of the backup code manager itself.
- [ ] **Low-codes warning** — If backup codes fall below a threshold
(e.g. 3 remaining), include a warning in the notification and/or
surface it in the `list-backup-codes` command output
- [ ] Tests for all new commands and notification dispatch
### Phase 2c — Passkey Authentication
**Status: complete.** See `docs/passkey-auth-subdomain-plan.md` for the full
plan, the evidence behind each decision, and the deviations noted below.
**Goal:** Add WebAuthn/FIDO2 passkey support as an alternative
authentication method alongside TOTP and backup codes.
**Context:** Passkeys are the modern standard for passwordless auth.
They're phishing-resistant (domain-bound), use biometrics or device
PINs, and are significantly more user-friendly than typing 6-digit
codes. For a pre-auth gate that friends and family use, passkeys would
be a major UX improvement — especially for non-technical users who
struggle with TOTP apps.
**What was built**, and how it differs from the sketch above:
- **A Symfony bundle was not used**, only `web-auth/webauthn-lib`. The bundle
brings a database-backed credential repository and a controller setup that do
not fit a no-database, listener-only application; the library alone is a
clean fit and its types are confined to `PasskeyManager` and
`PasskeyCeremonyFactory` so a major-version rename touches two files.
- **Registration happens in the browser, not a console command.** The checkbox
on the login form is authorised by the TOTP code in the same submission, so
it needs no separate token and no CLI. This also settles the "how does the
identity get specified" question: it is the identity that just authenticated.
- **Central auth is a hard prerequisite.** A passkey is scoped to one relying
party, so passkeys require `SUBDOMAIN_REDIRECT` + `AUTH_SUBDOMAIN`; the RP ID
is always that base domain. Without it the feature stays off, rather than
quietly scoping credentials to a single host.
- **HTTPS is required with no exemption**, development included, since an
`http://` escape hatch is how the same weakness reaches production.
- **Failed attempts share the TOTP rate-limit budget**, so passkeys cannot be
used to sidestep a lockout.
- **Attestation is `none`**, measured rather than assumed — see SECURITY.md and
plan §2.3.
**Remaining work:** none for the feature itself. Discoverable-credential
(usernameless) login is possible but not needed, since the login page already
lists registered credentials.
- [ ] Console command: `app:list-passkeys` — show registered devices
- [ ] Console command: `app:remove-passkey` — revoke a passkey
- [ ] Config: `PASSKEY_ENABLED=false` — enable/disable passkey auth
- [ ] Tests for registration, authentication, and revocation
- [ ] Consider: should passkeys be a *replacement* for TOTP or an
*alternative*? (Probably alternative — keep TOTP as fallback)
### Phase 3 — Multi-User Support
**Goal:** Support multiple TOTP users for household/family access.
*Note: This is a significant feature that changes the single-secret
model. It should only be pursued if the single-secret + backup codes
approach proves insufficient for the use case.*
- [ ] Multiple TOTP secrets, each with a label (e.g., "mom", "dad",
"friend")
- [ ] Per-user backup codes
- [ ] Per-user session tracking (the `username` field in Payload already
supports this — sessions are already tagged with an ID)
- [ ] Console command to add/remove/list users
- [ ] Consider: should the login page ask for a username, or should all
TOTP codes be tried against all secrets? (Username is better —
it's already in the payload.)
- [ ] Tests for multi-user scenarios
### Phase 4 — Polish & Hardening
**Goal:** Production hardening and quality-of-life improvements.
- [ ] **Docker image improvements:**
- Multi-arch builds (amd64 + arm64 for Raspberry Pi)
- Smaller image size (alpine-based if feasible)
- Better health check (actual endpoint, not just `curl localhost`)
- [ ] **GitHub/Gitea repository polish:**
- ✅ Comprehensive README with setup guide, architecture overview, and
configuration reference
- Contributing guidelines
- ✅ Changelog formalised (CHANGELOG.md)
- ✅ CI workflows (tests + php-cs-fixer on push/PR, Docker image on tag)
- [ ] **Security review:**
- ✅ CSRF protection on the POST form login — nonce system documented
- ✅ Security headers added (X-Content-Type-Options, X-Frame-Options, CSP, etc.)
- Review nonce entropy and cache key collision space
- Consider session fixation protections
- [ ] **Frontend improvements:**
- Mobile-responsive login page audit
- Accessibility audit (ARIA labels, keyboard navigation)
- Dark mode (if not already — the teal background suggests it might
already be dark-themed)
- [ ] **Logging improvements:**
- Structured logging (JSON format option) for easier parsing
- Log rotation configuration
- Debug mode documentation
---
## Feature Thoughts
Based on the review, here are features that might be missing or worth
considering, keeping in mind that preauth is a **gate**, not a full
identity provider:
### High Value
1. **Public but rate-limited mode** (Phase 1) — Directly solves the
Gitea bot traffic problem. This is the most impactful missing
feature.
2. **Passkey authentication** (Phase 2c) — Phishing-resistant,
passwordless auth that's far more user-friendly than TOTP for
non-technical family members. The modern standard for this kind
of gate.
3. **Backup code notifications** (Phase 2b) — When a backup code is
used, you should know about it immediately. This is a security-critical
event — it means someone lost their device or is locked out of their
TOTP app. Discord/ntfy/email notification should fire automatically.
4. **Backup code management commands** (Phase 2b) — The `generate`
command exists, but `list` and `expire` commands are missing despite
the underlying methods (`expire()`) already being implemented.
5. **Session visibility and revocation** (Phase 2) — Currently there's
no way to see who has access or revoke a session without clearing
the entire cache. For a security tool, this is important.
6. **Audit log** (Phase 2) — For a security gate, not having an audit
trail of logins (successful and failed) is a gap. The data is logged
at debug level, but not persisted in a queryable format.
### Medium Value
4. **Health check endpoint** — The Dockerfile has a `HEALTHCHECK` that
just `curl`s localhost, but a dedicated `/health` endpoint that
verifies cache connectivity would be more meaningful.
5. **Graceful degradation** — If the file-based cache is corrupted or
unavailable, does preauth fail open or closed? Should be documented
and tested. (Currently the `PersistCache` handles this in `boot()`,
but edge cases around partial corruption could be explored.)
6. **Rate limit headers** — Adding `X-RateLimit-Remaining` and
`Retry-After` headers to rate-limited responses would help legitimate
clients back off gracefully.
### Lower Value (Nice to Have)
7. **WebSocket support** — If protected services use WebSocket
connections, does `forward_auth` handle the upgrade handshake? This
is likely a Caddy configuration concern, but worth documenting.
8. **Theming presets** — Beyond the current env-var colour config,
preset themes or custom CSS upload could be nice for personalisation.
9. **TOTP secret rotation** — Console command to generate a new TOTP
secret and invalidate all existing sessions. Useful if a device is
lost or compromised.
10. **Per-service authentication policies** — Different services could
require different authentication strength (e.g., Bitwarden requires
TOTP + recent login, Microbin accepts any valid session). This would
need Caddy configuration support to pass the policy to preauth.
---
## Branch Status
| Branch | Status | Notes |
|--------|--------|-------|
| `main` (0.10.0) | Production | Current stable release |
All feature branches have been pruned. Development uses a feature-branch + PR workflow into `main`.
---
## Relationship to Other Projects
| Project | Integration |
|---------|-------------|
| MCP server | Preauth could be registered as an MCP command for session management ("revoke all sessions", "who's logged in?") |
| Email integration | Audit log entries could be included in morning summary ("2 failed login attempts from 203.0.113.50 overnight") |
| Discord/ntfy | Alert on backup code usage, suspicious activity (rate limit triggered, multiple failed attempts from new IP), low backup code count |
---
*Prepared by Lyra, your office-side assistant. ✨*
+124
View File
@@ -0,0 +1,124 @@
# Security Policy
## Supported Versions
| Version | Supported |
|---------|-----------|
| unreleased (v1 development) | ✅ |
## Reporting a Vulnerability
Report vulnerabilities privately to **security@digitaladapt.com** (or open a private
security advisory on the repository). Please include reproduction steps and affected
versions. You will receive an acknowledgement within 48 hours and a status update at
least weekly until resolution.
**Do not open a public issue for a suspected vulnerability.** preauth is an
authentication gateway — it sits in front of every protected service, so a
weakness here is a weakness everywhere behind it.
## Security model summary
preauth implements the auth half of the `forward_auth` pattern: a reverse proxy
calls it per request to decide whether a request may reach the upstream service.
- **Two outcomes per request: allow or intercept.** `AcceptListener` /
`RejectListener` / `InterceptListener` decide, and the decision is made on
every request rather than cached — a cached auth session is an anti-pattern
(GUIDING-LIGHT §3.3d), which is also why this project gets **no service
worker**.
- **The login flow is never cached.** The login page, failed logins, redirects
and rate-limit responses are sent with
`Cache-Control: no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0, s-maxage=0`.
An aggressive cache (notably older Safari) replaying a stale pre-auth response
presents to the user as being logged back out after a refresh.
- **Headers are set by the app, not left to the proxy.** `X-Content-Type-Options:
nosniff`, `X-Frame-Options: DENY`, a Content-Security-Policy, and
`Strict-Transport-Security: max-age=31536000`. Docs recommend mirroring the
caching headers at the edge as defence in depth, but the app does not depend
on it.
- **TOTP is required.** Secrets come from `TOTP_URI`; if it is unset the app
generates one and prints it for enrolment. Login state is carried in a signed
payload (`src/Data/Payload.php`) bound to a nonce and a scope, not in a
server-side session store.
- **Rate limiting is on by default**, with the block response configurable
(`TEAPOT=false` returns 429 rather than 418).
- **`REMOTE_USER` is trusted input, not a secret.** In `remote_user` modes the
gateway accepts an upstream-asserted identity, so the upstream must be the
only path to the app. Do not expose preauth directly to the internet for this
mode.
- **`.env` is never committed; secrets are env vars injected at runtime.** Real
secrets belong in `.env.local` or `bin/console secrets:set`, read via
`%env(...)%`. `.env.example` and `.env.test` are the committed env files.
### Passkeys (WebAuthn)
Off by default (`PASSKEY_ENABLED=0`). When on, the following hold:
- **Registration requires a valid TOTP code.** The checkbox rides on an
ordinary login submission, and the code check in that same request is what
authorises the ceremony. There is no enrolment token, no CLI path, and no way
to create a credential without already holding the secret. The identity comes
from the authenticated session, never from the request body.
- **The challenge is server-authoritative and single-use.** It is generated and
stored server-side; the client's copy is never trusted. The stored record is
deleted *before* verification runs, so a failed or replayed attempt cannot be
retried against the same challenge. Records live in the in-memory `nonceCache`
with a 300-second TTL and deliberately do not survive a restart.
- **Only the derived origin is accepted.** The allowed origin is always
`https://{AUTH_SUBDOMAIN}`, computed from configuration and never from the
request. `http://` is therefore rejected regardless of how the request
arrived, and there is no setting that re-enables it. The library's deprecated
`setSecuredRelyingPartyId()` escape hatch is not used, and development uses
real TLS instead of an exemption.
- **The RP ID is the base domain**, so a credential is scoped to every service
on that domain. This is the intended behaviour and the reason central auth is
a hard prerequisite: without a single shared domain there is no sane RP ID.
- **Failures are indistinguishable.** An unknown credential, a bad signature
and a wrong origin all produce the same response as a wrong TOTP code, so the
endpoint cannot be used to enumerate credentials.
- **Failures share the login rate-limit budget.** A failed ceremony costs the
same token as a wrong code, and once the limit is reached every method is
blocked. Passkeys cannot be used to sidestep a lockout, and the resource guard
that bounds ceremony *starts* is deliberately separate, so a legitimate login
never spends failure budget.
- **The signature counter is not a security control.** Most passkeys —
anything synchronised through a keychain — report a constant counter, so a
counter-based clone check would lock users out of their own credentials.
preauth accepts an unchanged counter and rejects only one that moves
*backwards*, which is the only signal the value can carry. **Clone detection is
deliberately not a property this feature claims.**
- **Attestation is deliberately not requested** (`attestation: 'none'`).
Attestation conveyance is only a preference a client may ignore, and the FIDO
metadata service is bypassed both by the zero AAGUID that privacy-preserving
passkeys already send and by self attestation — while still refusing
legitimate authenticators newer than its cached blob. This was measured rather
than assumed; see §2.3 of
`docs/passkey-auth-subdomain-plan.md` for the evidence. **Revisit if** a
deployment needs to prove which make and model of authenticator is enrolled,
or if a policy (rather than a preference) requires attested keys — in which
case the metadata service must be pinned and kept current, and the zero-AAGUID
case decided explicitly rather than by omission.
- **The ceremony replies are not cacheable.** They are the only 2xx this
application returns straight to a browser (every other 2xx is consumed by the
proxy's `forward_auth` check), so they carry the same anti-caching headers as
the rest of the login flow.
## Scope
In scope: the application code in `src/`, the shipped `Caddyfile`, the
`Dockerfile`, and anything that affects the allow/intercept decision.
Out of scope: the `forward_auth` integration at the edge (a host-proxy
configuration concern, see `docs/examples/Caddyfile`) and the security of the
services preauth protects.
## Deployment note
preauth runs as a container and drops privileges via `USER` (Guiding Light
§6.4): the image runs as the non-root `app` user (uid/gid 1000) and owns the
state paths it needs. Only `/data` is written at runtime — the cache pools
behind sessions, backup codes and rate limiting — and `/config` is declared
because the base image points Caddy's XDG config dir there. If you pin a
different `user:` in your compose file, that user must be able to write to
both paths — otherwise login state and backup codes cannot be persisted.
Executable
+265
View File
@@ -0,0 +1,265 @@
#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# PreAuth Dev Server Script
#
# Manages a local PHP dev server for end-to-end development and testing.
# Binds to 0.0.0.0 so the app is accessible via a reverse proxy (Caddy) for
# browser-based visual verification.
#
# PreAuth is a TOTP-based authentication gateway. It uses APCu for nonce/cache
# and filesystem for session persistence — no database needed. The dev server
# runs with APP_ENV=dev and APP_DEBUG=1 for live troubleshooting.
#
# Self-bootstrapping: the `start` command checks for required system packages
# (PHP, extensions, tools), Composer, and project dependencies — installing
# them automatically if missing. This means the script works even after a
# terminal reset/reboot, embracing the self-cleaning container design.
#
# Usage:
# bin/dev.sh start Start the dev server (auto-installs deps if needed)
# bin/dev.sh stop Stop the dev server
# bin/dev.sh status Check if the dev server is running
# bin/dev.sh restart Stop and start the dev server
#
# Port assignment (P-R-E = 7-7-3):
# 8773 → https://preauth.lyra-dev.devgnome.com
# ─────────────────────────────────────────────────────────────────────────────
set -euo pipefail
# ── Configuration ───────────────────────────────────────────────────────────
PORT=8773
HOST="0.0.0.0"
ENV="dev"
DEV_SECRET="dev_secret_not_for_production_use_only"
PID_FILE="var/.dev-server.pid"
LOG_FILE="var/log/dev-server.log"
# Required PHP extensions (checked via php -m)
REQUIRED_PHP_EXTS=(
ctype
iconv
mbstring
apcu
dom
SimpleXML
xml
)
# Apt packages for PHP + extensions
# Note: preauth uses Symfony 8.1 which requires PHP >=8.4.
# We install PHP 8.4 (available in Debian 13/Trixie) for consistency.
PHP_APT_PACKAGES=(
php8.4-cli
php8.4-common # ctype, iconv
php8.4-mbstring
php8.4-xml # dom, SimpleXML, xml
php8.4-opcache
php8.4-readline
php8.4-apcu # APCu — critical for nonce cache, rate limiter, sessions
)
# System tools needed
SYSTEM_TOOLS=(
git
unzip
curl
)
# Resolve project root (script lives in bin/)
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$PROJECT_ROOT"
# Ensure var directory structure exists
mkdir -p var/log var/share
# ── Helpers ─────────────────────────────────────────────────────────────────
is_running() {
if [[ ! -f "$PID_FILE" ]]; then
return 1
fi
local pid
pid="$(cat "$PID_FILE")"
if [[ -z "$pid" ]] || ! kill -0 "$pid" 2>/dev/null; then
return 1
fi
return 0
}
print_status() {
if is_running; then
local pid
pid="$(cat "$PID_FILE")"
echo "✅ PreAuth dev server is RUNNING"
echo " PID: $pid"
echo " URL: http://localhost:${PORT}"
echo " Exposed: http://${HOST}:${PORT}"
echo " Dev URL: https://preauth.lyra-dev.devgnome.com"
echo " Logs: ${LOG_FILE}"
else
echo "⛔ PreAuth dev server is STOPPED"
fi
}
# ── Bootstrap ───────────────────────────────────────────────────────────────
# Ensures all system packages, Composer, and project dependencies are present.
# Idempotent — if everything is already installed, checks are fast no-ops.
# This is what makes the script survive terminal resets/reboots.
bootstrap() {
local needed_packages=()
# ── Check system tools ──
for tool in "${SYSTEM_TOOLS[@]}"; do
if ! command -v "$tool" &>/dev/null; then
needed_packages+=("$tool")
fi
done
# ── Check PHP and required extensions ──
local php_needs_install=false
if ! command -v php &>/dev/null; then
php_needs_install=true
else
for ext in "${REQUIRED_PHP_EXTS[@]}"; do
if ! php -m 2>/dev/null | grep -iq "^${ext}$"; then
php_needs_install=true
break
fi
done
fi
if [[ "$php_needs_install" == "true" ]]; then
needed_packages+=("${PHP_APT_PACKAGES[@]}")
fi
# ── Install missing packages ──
if [[ ${#needed_packages[@]} -gt 0 ]]; then
echo "→ Installing missing system packages: ${needed_packages[*]}…"
sudo apt-get update -qq
sudo apt-get install -y -qq "${needed_packages[@]}"
fi
# ── Ensure APCu is enabled for CLI ──
# PreAuth's console commands need APCu; the Dockerfile sets apc.enable_cli=1
local apcu_ini="/etc/php/8.4/mods-available/apcu.ini"
if [[ -f "$apcu_ini" ]] && ! grep -q 'apc.enable_cli' "$apcu_ini" 2>/dev/null; then
echo "→ Enabling APCu CLI support…"
echo 'apc.enable_cli=1' | sudo tee -a "$apcu_ini" >/dev/null
fi
# ── Ensure Composer is available ──
if ! command -v composer &>/dev/null; then
echo "→ Installing Composer…"
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
sudo chmod +x /usr/local/bin/composer
fi
# ── Ensure project dependencies are installed ──
if [[ ! -d "vendor/" ]]; then
echo "→ Installing Composer dependencies…"
APP_ENV=dev composer install --no-interaction
fi
}
# ── Commands ────────────────────────────────────────────────────────────────
start() {
if is_running; then
echo "⚠️ Dev server is already running (PID $(cat "$PID_FILE"))"
print_status
exit 0
fi
echo "→ Starting PreAuth dev server on ${HOST}:${PORT}…"
# Self-bootstrap: ensure all dependencies are present
bootstrap
echo "→ Clearing dev cache…"
APP_ENV="$ENV" \
APP_DEBUG=1 \
APP_SECRET="$DEV_SECRET" \
php bin/console cache:clear 2>&1 | tail -3
echo "→ Starting PHP dev server…"
APP_ENV="$ENV" \
APP_DEBUG=1 \
APP_SECRET="$DEV_SECRET" \
APP_SHARE_DIR="${PROJECT_ROOT}/var/share" \
nohup php -S "${HOST}:${PORT}" -t public/ > "$LOG_FILE" 2>&1 &
local pid=$!
echo "$pid" > "$PID_FILE"
# Give it a moment to boot
sleep 2
if is_running; then
echo ""
print_status
else
echo "❌ Failed to start dev server. Check logs:"
echo " ${LOG_FILE}"
tail -20 "$LOG_FILE" 2>/dev/null || true
rm -f "$PID_FILE"
exit 1
fi
}
stop() {
if ! is_running; then
echo "⚠️ Dev server is not running."
rm -f "$PID_FILE"
exit 0
fi
local pid
pid="$(cat "$PID_FILE")"
echo "→ Stopping dev server (PID ${pid})…"
kill "$pid" 2>/dev/null || true
# Wait for graceful shutdown
local count=0
while kill -0 "$pid" 2>/dev/null && [[ $count -lt 10 ]]; do
sleep 0.5
count=$((count + 1))
done
# Force kill if still alive
if kill -0 "$pid" 2>/dev/null; then
echo "→ Process didn't exit gracefully, sending SIGKILL…"
kill -9 "$pid" 2>/dev/null || true
fi
rm -f "$PID_FILE"
echo "✅ Dev server stopped."
}
restart() {
stop
sleep 1
start
}
# ── Main ────────────────────────────────────────────────────────────────────
usage() {
echo "Usage: bin/dev.sh {start|stop|status|restart}"
echo ""
echo "Commands:"
echo " start Start the dev server (auto-installs deps if needed)"
echo " stop Stop the dev server"
echo " status Check if the dev server is running"
echo " restart Restart the dev server"
exit 1
}
case "${1:-}" in
start) start ;;
stop) stop ;;
status) print_status ;;
restart) restart ;;
*) usage ;;
esac
+8 -7
View File
@@ -1,13 +1,14 @@
#!/bin/sh #!/bin/sh
# Dev utility — builds and runs the preauth container locally.
# Not for production use.
# APP_SECRET should be set in your environment or .env file.
docker container rm preauth docker container rm preauth 2>/dev/null
docker build . -t digtialadapt/preauth:dev docker build . -t digitaladapt/preauth:dev
docker run --name preauth \ docker run --name preauth \
-e APP_ENV=dev \ -e APP_ENV=dev \
-e APP_DEBUG=true \ -e APP_DEBUG=true \
-e APP_SECRET=f88a1074691c40415be4439345b79f69 \ -e APP_SECRET="${APP_SECRET:-$(openssl rand -hex 16)}" \
-e APP_SHARE_DIR=var/share \ -e APP_SHARE_DIR=/app/var/share \
-e DEFAULT_URI=http://localhost \
-v ./var/share:/app/var/share \
-p 8000:80 \ -p 8000:80 \
digtialadapt/preauth:dev digitaladapt/preauth:dev
Executable
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env php
<?php
require dirname(__DIR__).'/vendor/phpunit/phpunit/phpunit';
+28 -16
View File
@@ -4,22 +4,22 @@
"minimum-stability": "stable", "minimum-stability": "stable",
"prefer-stable": true, "prefer-stable": true,
"require": { "require": {
"php": ">=8.4", "php": "^8.5",
"ext-ctype": "*", "ext-ctype": "*",
"ext-iconv": "*", "ext-iconv": "*",
"bacon/bacon-qr-code": "^3.1.1", "bacon/bacon-qr-code": "^3.1.1",
"runtime/frankenphp-symfony": "^1.0.0",
"spomky-labs/otphp": "^11.4.2", "spomky-labs/otphp": "^11.4.2",
"symfony/cache": "7.4.*", "symfony/cache": "8.1.*",
"symfony/console": "7.4.*", "symfony/console": "8.1.*",
"symfony/flex": "^2.11", "symfony/flex": "^2.11",
"symfony/framework-bundle": "7.4.*", "symfony/framework-bundle": "8.1.*",
"symfony/mime": "7.4.*", "symfony/mime": "8.1.*",
"symfony/rate-limiter": "7.4.*", "symfony/rate-limiter": "8.1.*",
"symfony/runtime": "7.4.*", "symfony/runtime": "8.1.*",
"symfony/twig-bundle": "7.4.*", "symfony/twig-bundle": "8.1.*",
"symfony/uid": "7.4.*", "symfony/uid": "8.1.*",
"symfony/yaml": "7.4.*" "symfony/yaml": "8.1.*",
"web-auth/webauthn-lib": "^5.3"
}, },
"config": { "config": {
"allow-plugins": { "allow-plugins": {
@@ -28,13 +28,21 @@
"symfony/runtime": true "symfony/runtime": true
}, },
"bump-after-update": true, "bump-after-update": true,
"sort-packages": true "sort-packages": true,
"platform": {
"php": "8.5.0"
}
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"App\\": "src/" "App\\": "src/"
} }
}, },
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"replace": { "replace": {
"symfony/polyfill-ctype": "*", "symfony/polyfill-ctype": "*",
"symfony/polyfill-iconv": "*", "symfony/polyfill-iconv": "*",
@@ -61,12 +69,16 @@
"symfony/symfony": "*" "symfony/symfony": "*"
}, },
"extra": { "extra": {
"runtime": {
"class": "Runtime\\FrankenPhpSymfony\\Runtime"
},
"symfony": { "symfony": {
"allow-contrib": false, "allow-contrib": false,
"require": "7.4.*" "require": "8.1.*"
} }
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.95",
"phpstan/phpstan": "^2.1",
"phpunit/phpunit": "^13.2",
"symfony/browser-kit": "8.1.*",
"symfony/css-selector": "8.1.*"
} }
} }
Generated
+5208 -560
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
return [ return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true], Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true], Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
+4
View File
@@ -10,6 +10,10 @@ framework:
adapters: cache.adapter.apcu adapters: cache.adapter.apcu
sessionStorage: sessionStorage:
adapters: cache.adapter.filesystem adapters: cache.adapter.filesystem
publicRateLimitCache:
adapters: cache.adapter.apcu
passkeyRateLimitCache:
adapters: cache.adapter.apcu
# Unique name of your app: used to compute stable namespaces for cache keys. # Unique name of your app: used to compute stable namespaces for cache keys.
prefix_seed: digitaladapt/preauth prefix_seed: digitaladapt/preauth
+3 -2
View File
@@ -5,5 +5,6 @@ framework:
trusted_proxies: 'private_ranges' trusted_proxies: 'private_ranges'
trusted_headers: ['x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto'] trusted_headers: ['x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto']
# Note that the session will be started ONLY if you read or write from it. # Sessions are disabled — preauth implements its own cookie/cache-based
session: true # session management and does not use Symfony's session subsystem.
session: false
+3
View File
@@ -0,0 +1,3 @@
framework:
property_info:
with_constructor_extractor: true
+26
View File
@@ -13,3 +13,29 @@ framework:
login_limiter: login_limiter:
policy: compound policy: compound
limiters: [burst, upper] limiters: [burst, upper]
public_burst:
policy: 'sliding_window'
limit: '%env(int:PUBLIC_BURST_COUNT)%'
interval: '%env(int:PUBLIC_BURST_TIME)% seconds'
cache_pool: 'publicRateLimitCache'
public_upper:
policy: 'sliding_window'
limit: '%env(int:PUBLIC_UPPER_COUNT)%'
interval: '%env(int:PUBLIC_UPPER_TIME)% seconds'
cache_pool: 'publicRateLimitCache'
public_limiter:
policy: compound
limiters: [public_burst, public_upper]
# bounds how many ceremonies one caller can *start*.
#
# This is a resource guard, NOT part of the login budget: D3 makes the
# existing login_limiter the single shared budget for every login method,
# and a legitimate `begin` must not consume failure budget. Without this,
# an unauthenticated caller could fill the ceremony cache with records.
passkey_begin_burst:
policy: 'sliding_window'
limit: '%env(int:PASSKEY_BEGIN_BURST_COUNT)%'
interval: '%env(int:PASSKEY_BEGIN_BURST_TIME)% seconds'
cache_pool: 'passkeyRateLimitCache'
+16
View File
@@ -0,0 +1,16 @@
framework:
cache:
app: cache.adapter.array
pools:
nonceCache:
adapters: cache.adapter.array
rateLimitCache:
adapters: cache.adapter.array
sessionCache:
adapters: cache.adapter.array
sessionStorage:
adapters: cache.adapter.array
publicRateLimitCache:
adapters: cache.adapter.array
passkeyRateLimitCache:
adapters: cache.adapter.array
+4
View File
@@ -0,0 +1,4 @@
framework:
test: true
session:
storage_factory_id: session.storage.factory.mock_file
+6
View File
@@ -15,4 +15,10 @@ twig:
teapot_message: '%env(TEAPOT_MESSAGE)%' teapot_message: '%env(TEAPOT_MESSAGE)%'
too_many_title: '%env(TOO_MANY_TITLE)%' too_many_title: '%env(TOO_MANY_TITLE)%'
too_many_message: '%env(TOO_MANY_MESSAGE)%' too_many_message: '%env(TOO_MANY_MESSAGE)%'
passkey_button_name: '%env(PASSKEY_BUTTON_NAME)%'
passkey_register_name: '%env(PASSKEY_REGISTER_NAME)%'
debug: '%env(SHELL_VERBOSITY)%' debug: '%env(SHELL_VERBOSITY)%'
# `passkeys` is computed per request by the controller-facing templates via
# PasskeyPolicyInterface, never from an env var, so that availability and the
# D1/D4 prerequisites cannot drift apart.
+2
View File
@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
if (file_exists(dirname(__DIR__). if (file_exists(dirname(__DIR__).
'/var/cache/prod/App_KernelProdContainer.preload.php') '/var/cache/prod/App_KernelProdContainer.preload.php')
) { ) {
-844
View File
@@ -1,844 +0,0 @@
<?php
// This file is auto-generated and is for apps only. Bundles SHOULD NOT rely on its content.
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
use Symfony\Component\Config\Loader\ParamConfigurator as Param;
/**
* This class provides array-shapes for configuring the services and bundles of an application.
*
* Services declared with the config() method below are autowired and autoconfigured by default.
*
* This is for apps only. Bundles SHOULD NOT use it.
*
* Example:
*
* ```php
* // config/services.php
* namespace Symfony\Component\DependencyInjection\Loader\Configurator;
*
* return App::config([
* 'services' => [
* 'App\\' => [
* 'resource' => '../src/',
* ],
* ],
* ]);
* ```
*
* @psalm-type ImportsConfig = list<string|array{
* resource: string,
* type?: string|null,
* ignore_errors?: bool,
* }>
* @psalm-type ParametersConfig = array<string, scalar|\UnitEnum|array<scalar|\UnitEnum|array<mixed>|Param|null>|Param|null>
* @psalm-type ArgumentsType = list<mixed>|array<string, mixed>
* @psalm-type CallType = array<string, ArgumentsType>|array{0:string, 1?:ArgumentsType, 2?:bool}|array{method:string, arguments?:ArgumentsType, returns_clone?:bool}
* @psalm-type TagsType = list<string|array<string, array<string, mixed>>> // arrays inside the list must have only one element, with the tag name as the key
* @psalm-type CallbackType = string|array{0:string|ReferenceConfigurator,1:string}|\Closure|ReferenceConfigurator
* @psalm-type DeprecationType = array{package: string, version: string, message?: string}
* @psalm-type DefaultsType = array{
* public?: bool,
* tags?: TagsType,
* resource_tags?: TagsType,
* autowire?: bool,
* autoconfigure?: bool,
* bind?: array<string, mixed>,
* }
* @psalm-type InstanceofType = array{
* shared?: bool,
* lazy?: bool|string,
* public?: bool,
* properties?: array<string, mixed>,
* configurator?: CallbackType,
* calls?: list<CallType>,
* tags?: TagsType,
* resource_tags?: TagsType,
* autowire?: bool,
* bind?: array<string, mixed>,
* constructor?: string,
* }
* @psalm-type DefinitionType = array{
* class?: string,
* file?: string,
* parent?: string,
* shared?: bool,
* synthetic?: bool,
* lazy?: bool|string,
* public?: bool,
* abstract?: bool,
* deprecated?: DeprecationType,
* factory?: CallbackType,
* configurator?: CallbackType,
* arguments?: ArgumentsType,
* properties?: array<string, mixed>,
* calls?: list<CallType>,
* tags?: TagsType,
* resource_tags?: TagsType,
* decorates?: string,
* decoration_inner_name?: string,
* decoration_priority?: int,
* decoration_on_invalid?: 'exception'|'ignore'|null,
* autowire?: bool,
* autoconfigure?: bool,
* bind?: array<string, mixed>,
* constructor?: string,
* from_callable?: CallbackType,
* }
* @psalm-type AliasType = string|array{
* alias: string,
* public?: bool,
* deprecated?: DeprecationType,
* }
* @psalm-type PrototypeType = array{
* resource: string,
* namespace?: string,
* exclude?: string|list<string>,
* parent?: string,
* shared?: bool,
* lazy?: bool|string,
* public?: bool,
* abstract?: bool,
* deprecated?: DeprecationType,
* factory?: CallbackType,
* arguments?: ArgumentsType,
* properties?: array<string, mixed>,
* configurator?: CallbackType,
* calls?: list<CallType>,
* tags?: TagsType,
* resource_tags?: TagsType,
* autowire?: bool,
* autoconfigure?: bool,
* bind?: array<string, mixed>,
* constructor?: string,
* }
* @psalm-type StackType = array{
* stack: list<DefinitionType|AliasType|PrototypeType|array<class-string, ArgumentsType|null>>,
* public?: bool,
* deprecated?: DeprecationType,
* }
* @psalm-type ServicesConfig = array{
* _defaults?: DefaultsType,
* _instanceof?: InstanceofType,
* ...<string, DefinitionType|AliasType|PrototypeType|StackType|ArgumentsType|null>
* }
* @psalm-type ExtensionType = array<string, mixed>
* @psalm-type FrameworkConfig = array{
* secret?: scalar|Param|null,
* http_method_override?: bool|Param, // Set true to enable support for the '_method' request parameter to determine the intended HTTP method on POST requests. // Default: false
* allowed_http_method_override?: list<string|Param>|null,
* trust_x_sendfile_type_header?: scalar|Param|null, // Set true to enable support for xsendfile in binary file responses. // Default: "%env(bool:default::SYMFONY_TRUST_X_SENDFILE_TYPE_HEADER)%"
* ide?: scalar|Param|null, // Default: "%env(default::SYMFONY_IDE)%"
* test?: bool|Param,
* default_locale?: scalar|Param|null, // Default: "en"
* set_locale_from_accept_language?: bool|Param, // Whether to use the Accept-Language HTTP header to set the Request locale (only when the "_locale" request attribute is not passed). // Default: false
* set_content_language_from_locale?: bool|Param, // Whether to set the Content-Language HTTP header on the Response using the Request locale. // Default: false
* enabled_locales?: list<scalar|Param|null>,
* trusted_hosts?: list<scalar|Param|null>,
* trusted_proxies?: mixed, // Default: ["%env(default::SYMFONY_TRUSTED_PROXIES)%"]
* trusted_headers?: list<scalar|Param|null>,
* error_controller?: scalar|Param|null, // Default: "error_controller"
* handle_all_throwables?: bool|Param, // HttpKernel will handle all kinds of \Throwable. // Default: true
* csrf_protection?: bool|array{
* enabled?: scalar|Param|null, // Default: null
* stateless_token_ids?: list<scalar|Param|null>,
* check_header?: scalar|Param|null, // Whether to check the CSRF token in a header in addition to a cookie when using stateless protection. // Default: false
* cookie_name?: scalar|Param|null, // The name of the cookie to use when using stateless protection. // Default: "csrf-token"
* },
* form?: bool|array{ // Form configuration
* enabled?: bool|Param, // Default: false
* csrf_protection?: bool|array{
* enabled?: scalar|Param|null, // Default: null
* token_id?: scalar|Param|null, // Default: null
* field_name?: scalar|Param|null, // Default: "_token"
* field_attr?: array<string, scalar|Param|null>,
* },
* },
* http_cache?: bool|array{ // HTTP cache configuration
* enabled?: bool|Param, // Default: false
* debug?: bool|Param, // Default: "%kernel.debug%"
* trace_level?: "none"|"short"|"full"|Param,
* trace_header?: scalar|Param|null,
* default_ttl?: int|Param,
* private_headers?: list<scalar|Param|null>,
* skip_response_headers?: list<scalar|Param|null>,
* allow_reload?: bool|Param,
* allow_revalidate?: bool|Param,
* stale_while_revalidate?: int|Param,
* stale_if_error?: int|Param,
* terminate_on_cache_hit?: bool|Param,
* },
* esi?: bool|array{ // ESI configuration
* enabled?: bool|Param, // Default: false
* },
* ssi?: bool|array{ // SSI configuration
* enabled?: bool|Param, // Default: false
* },
* fragments?: bool|array{ // Fragments configuration
* enabled?: bool|Param, // Default: false
* hinclude_default_template?: scalar|Param|null, // Default: null
* path?: scalar|Param|null, // Default: "/_fragment"
* },
* profiler?: bool|array{ // Profiler configuration
* enabled?: bool|Param, // Default: false
* collect?: bool|Param, // Default: true
* collect_parameter?: scalar|Param|null, // The name of the parameter to use to enable or disable collection on a per request basis. // Default: null
* only_exceptions?: bool|Param, // Default: false
* only_main_requests?: bool|Param, // Default: false
* dsn?: scalar|Param|null, // Default: "file:%kernel.cache_dir%/profiler"
* collect_serializer_data?: bool|Param, // Enables the serializer data collector and profiler panel. // Default: false
* },
* workflows?: bool|array{
* enabled?: bool|Param, // Default: false
* workflows?: array<string, array{ // Default: []
* audit_trail?: bool|array{
* enabled?: bool|Param, // Default: false
* },
* type?: "workflow"|"state_machine"|Param, // Default: "state_machine"
* marking_store?: array{
* type?: "method"|Param,
* property?: scalar|Param|null,
* service?: scalar|Param|null,
* },
* supports?: list<scalar|Param|null>,
* definition_validators?: list<scalar|Param|null>,
* support_strategy?: scalar|Param|null,
* initial_marking?: list<scalar|Param|null>,
* events_to_dispatch?: list<string|Param>|null,
* places?: list<array{ // Default: []
* name?: scalar|Param|null,
* metadata?: array<string, mixed>,
* }>,
* transitions?: list<array{ // Default: []
* name?: string|Param,
* guard?: string|Param, // An expression to block the transition.
* from?: list<array{ // Default: []
* place?: string|Param,
* weight?: int|Param, // Default: 1
* }>,
* to?: list<array{ // Default: []
* place?: string|Param,
* weight?: int|Param, // Default: 1
* }>,
* weight?: int|Param, // Default: 1
* metadata?: array<string, mixed>,
* }>,
* metadata?: array<string, mixed>,
* }>,
* },
* router?: bool|array{ // Router configuration
* enabled?: bool|Param, // Default: false
* resource?: scalar|Param|null,
* type?: scalar|Param|null,
* cache_dir?: scalar|Param|null, // Deprecated: Setting the "framework.router.cache_dir.cache_dir" configuration option is deprecated. It will be removed in version 8.0. // Default: "%kernel.build_dir%"
* default_uri?: scalar|Param|null, // The default URI used to generate URLs in a non-HTTP context. // Default: null
* http_port?: scalar|Param|null, // Default: 80
* https_port?: scalar|Param|null, // Default: 443
* strict_requirements?: scalar|Param|null, // set to true to throw an exception when a parameter does not match the requirements set to false to disable exceptions when a parameter does not match the requirements (and return null instead) set to null to disable parameter checks against requirements 'true' is the preferred configuration in development mode, while 'false' or 'null' might be preferred in production // Default: true
* utf8?: bool|Param, // Default: true
* },
* session?: bool|array{ // Session configuration
* enabled?: bool|Param, // Default: false
* storage_factory_id?: scalar|Param|null, // Default: "session.storage.factory.native"
* handler_id?: scalar|Param|null, // Defaults to using the native session handler, or to the native *file* session handler if "save_path" is not null.
* name?: scalar|Param|null,
* cookie_lifetime?: scalar|Param|null,
* cookie_path?: scalar|Param|null,
* cookie_domain?: scalar|Param|null,
* cookie_secure?: true|false|"auto"|Param, // Default: "auto"
* cookie_httponly?: bool|Param, // Default: true
* cookie_samesite?: null|"lax"|"strict"|"none"|Param, // Default: "lax"
* use_cookies?: bool|Param,
* gc_divisor?: scalar|Param|null,
* gc_probability?: scalar|Param|null,
* gc_maxlifetime?: scalar|Param|null,
* save_path?: scalar|Param|null, // Defaults to "%kernel.cache_dir%/sessions" if the "handler_id" option is not null.
* metadata_update_threshold?: int|Param, // Seconds to wait between 2 session metadata updates. // Default: 0
* sid_length?: int|Param, // Deprecated: Setting the "framework.session.sid_length.sid_length" configuration option is deprecated. It will be removed in version 8.0. No alternative is provided as PHP 8.4 has deprecated the related option.
* sid_bits_per_character?: int|Param, // Deprecated: Setting the "framework.session.sid_bits_per_character.sid_bits_per_character" configuration option is deprecated. It will be removed in version 8.0. No alternative is provided as PHP 8.4 has deprecated the related option.
* },
* request?: bool|array{ // Request configuration
* enabled?: bool|Param, // Default: false
* formats?: array<string, string|list<scalar|Param|null>>,
* },
* assets?: bool|array{ // Assets configuration
* enabled?: bool|Param, // Default: false
* strict_mode?: bool|Param, // Throw an exception if an entry is missing from the manifest.json. // Default: false
* version_strategy?: scalar|Param|null, // Default: null
* version?: scalar|Param|null, // Default: null
* version_format?: scalar|Param|null, // Default: "%%s?%%s"
* json_manifest_path?: scalar|Param|null, // Default: null
* base_path?: scalar|Param|null, // Default: ""
* base_urls?: list<scalar|Param|null>,
* packages?: array<string, array{ // Default: []
* strict_mode?: bool|Param, // Throw an exception if an entry is missing from the manifest.json. // Default: false
* version_strategy?: scalar|Param|null, // Default: null
* version?: scalar|Param|null,
* version_format?: scalar|Param|null, // Default: null
* json_manifest_path?: scalar|Param|null, // Default: null
* base_path?: scalar|Param|null, // Default: ""
* base_urls?: list<scalar|Param|null>,
* }>,
* },
* asset_mapper?: bool|array{ // Asset Mapper configuration
* enabled?: bool|Param, // Default: false
* paths?: array<string, scalar|Param|null>,
* excluded_patterns?: list<scalar|Param|null>,
* exclude_dotfiles?: bool|Param, // If true, any files starting with "." will be excluded from the asset mapper. // Default: true
* server?: bool|Param, // If true, a "dev server" will return the assets from the public directory (true in "debug" mode only by default). // Default: true
* public_prefix?: scalar|Param|null, // The public path where the assets will be written to (and served from when "server" is true). // Default: "/assets/"
* missing_import_mode?: "strict"|"warn"|"ignore"|Param, // Behavior if an asset cannot be found when imported from JavaScript or CSS files - e.g. "import './non-existent.js'". "strict" means an exception is thrown, "warn" means a warning is logged, "ignore" means the import is left as-is. // Default: "warn"
* extensions?: array<string, scalar|Param|null>,
* importmap_path?: scalar|Param|null, // The path of the importmap.php file. // Default: "%kernel.project_dir%/importmap.php"
* importmap_polyfill?: scalar|Param|null, // The importmap name that will be used to load the polyfill. Set to false to disable. // Default: "es-module-shims"
* importmap_script_attributes?: array<string, scalar|Param|null>,
* vendor_dir?: scalar|Param|null, // The directory to store JavaScript vendors. // Default: "%kernel.project_dir%/assets/vendor"
* precompress?: bool|array{ // Precompress assets with Brotli, Zstandard and gzip.
* enabled?: bool|Param, // Default: false
* formats?: list<scalar|Param|null>,
* extensions?: list<scalar|Param|null>,
* },
* },
* translator?: bool|array{ // Translator configuration
* enabled?: bool|Param, // Default: false
* fallbacks?: list<scalar|Param|null>,
* logging?: bool|Param, // Default: false
* formatter?: scalar|Param|null, // Default: "translator.formatter.default"
* cache_dir?: scalar|Param|null, // Default: "%kernel.cache_dir%/translations"
* default_path?: scalar|Param|null, // The default path used to load translations. // Default: "%kernel.project_dir%/translations"
* paths?: list<scalar|Param|null>,
* pseudo_localization?: bool|array{
* enabled?: bool|Param, // Default: false
* accents?: bool|Param, // Default: true
* expansion_factor?: float|Param, // Default: 1.0
* brackets?: bool|Param, // Default: true
* parse_html?: bool|Param, // Default: false
* localizable_html_attributes?: list<scalar|Param|null>,
* },
* providers?: array<string, array{ // Default: []
* dsn?: scalar|Param|null,
* domains?: list<scalar|Param|null>,
* locales?: list<scalar|Param|null>,
* }>,
* globals?: array<string, string|array{ // Default: []
* value?: mixed,
* message?: string|Param,
* parameters?: array<string, scalar|Param|null>,
* domain?: string|Param,
* }>,
* },
* validation?: bool|array{ // Validation configuration
* enabled?: bool|Param, // Default: false
* cache?: scalar|Param|null, // Deprecated: Setting the "framework.validation.cache.cache" configuration option is deprecated. It will be removed in version 8.0.
* enable_attributes?: bool|Param, // Default: true
* static_method?: list<scalar|Param|null>,
* translation_domain?: scalar|Param|null, // Default: "validators"
* email_validation_mode?: "html5"|"html5-allow-no-tld"|"strict"|"loose"|Param, // Default: "html5"
* mapping?: array{
* paths?: list<scalar|Param|null>,
* },
* not_compromised_password?: bool|array{
* enabled?: bool|Param, // When disabled, compromised passwords will be accepted as valid. // Default: true
* endpoint?: scalar|Param|null, // API endpoint for the NotCompromisedPassword Validator. // Default: null
* },
* disable_translation?: bool|Param, // Default: false
* auto_mapping?: array<string, array{ // Default: []
* services?: list<scalar|Param|null>,
* }>,
* },
* annotations?: bool|array{
* enabled?: bool|Param, // Default: false
* },
* serializer?: bool|array{ // Serializer configuration
* enabled?: bool|Param, // Default: false
* enable_attributes?: bool|Param, // Default: true
* name_converter?: scalar|Param|null,
* circular_reference_handler?: scalar|Param|null,
* max_depth_handler?: scalar|Param|null,
* mapping?: array{
* paths?: list<scalar|Param|null>,
* },
* default_context?: array<string, mixed>,
* named_serializers?: array<string, array{ // Default: []
* name_converter?: scalar|Param|null,
* default_context?: array<string, mixed>,
* include_built_in_normalizers?: bool|Param, // Whether to include the built-in normalizers // Default: true
* include_built_in_encoders?: bool|Param, // Whether to include the built-in encoders // Default: true
* }>,
* },
* property_access?: bool|array{ // Property access configuration
* enabled?: bool|Param, // Default: false
* magic_call?: bool|Param, // Default: false
* magic_get?: bool|Param, // Default: true
* magic_set?: bool|Param, // Default: true
* throw_exception_on_invalid_index?: bool|Param, // Default: false
* throw_exception_on_invalid_property_path?: bool|Param, // Default: true
* },
* type_info?: bool|array{ // Type info configuration
* enabled?: bool|Param, // Default: false
* aliases?: array<string, scalar|Param|null>,
* },
* property_info?: bool|array{ // Property info configuration
* enabled?: bool|Param, // Default: false
* with_constructor_extractor?: bool|Param, // Registers the constructor extractor.
* },
* cache?: array{ // Cache configuration
* prefix_seed?: scalar|Param|null, // Used to namespace cache keys when using several apps with the same shared backend. // Default: "_%kernel.project_dir%.%kernel.container_class%"
* app?: scalar|Param|null, // App related cache pools configuration. // Default: "cache.adapter.filesystem"
* system?: scalar|Param|null, // System related cache pools configuration. // Default: "cache.adapter.system"
* directory?: scalar|Param|null, // Default: "%kernel.share_dir%/pools/app"
* default_psr6_provider?: scalar|Param|null,
* default_redis_provider?: scalar|Param|null, // Default: "redis://localhost"
* default_valkey_provider?: scalar|Param|null, // Default: "valkey://localhost"
* default_memcached_provider?: scalar|Param|null, // Default: "memcached://localhost"
* default_doctrine_dbal_provider?: scalar|Param|null, // Default: "database_connection"
* default_pdo_provider?: scalar|Param|null, // Default: null
* pools?: array<string, array{ // Default: []
* adapters?: list<scalar|Param|null>,
* tags?: scalar|Param|null, // Default: null
* public?: bool|Param, // Default: false
* default_lifetime?: scalar|Param|null, // Default lifetime of the pool.
* provider?: scalar|Param|null, // Overwrite the setting from the default provider for this adapter.
* early_expiration_message_bus?: scalar|Param|null,
* clearer?: scalar|Param|null,
* }>,
* },
* php_errors?: array{ // PHP errors handling configuration
* log?: mixed, // Use the application logger instead of the PHP logger for logging PHP errors. // Default: true
* throw?: bool|Param, // Throw PHP errors as \ErrorException instances. // Default: true
* },
* exceptions?: array<string, array{ // Default: []
* log_level?: scalar|Param|null, // The level of log message. Null to let Symfony decide. // Default: null
* status_code?: scalar|Param|null, // The status code of the response. Null or 0 to let Symfony decide. // Default: null
* log_channel?: scalar|Param|null, // The channel of log message. Null to let Symfony decide. // Default: null
* }>,
* web_link?: bool|array{ // Web links configuration
* enabled?: bool|Param, // Default: false
* },
* lock?: bool|string|array{ // Lock configuration
* enabled?: bool|Param, // Default: false
* resources?: array<string, string|list<scalar|Param|null>>,
* },
* semaphore?: bool|string|array{ // Semaphore configuration
* enabled?: bool|Param, // Default: false
* resources?: array<string, scalar|Param|null>,
* },
* messenger?: bool|array{ // Messenger configuration
* enabled?: bool|Param, // Default: false
* routing?: array<string, string|array{ // Default: []
* senders?: list<scalar|Param|null>,
* }>,
* serializer?: array{
* default_serializer?: scalar|Param|null, // Service id to use as the default serializer for the transports. // Default: "messenger.transport.native_php_serializer"
* symfony_serializer?: array{
* format?: scalar|Param|null, // Serialization format for the messenger.transport.symfony_serializer service (which is not the serializer used by default). // Default: "json"
* context?: array<string, mixed>,
* },
* },
* transports?: array<string, string|array{ // Default: []
* dsn?: scalar|Param|null,
* serializer?: scalar|Param|null, // Service id of a custom serializer to use. // Default: null
* options?: array<string, mixed>,
* failure_transport?: scalar|Param|null, // Transport name to send failed messages to (after all retries have failed). // Default: null
* retry_strategy?: string|array{
* service?: scalar|Param|null, // Service id to override the retry strategy entirely. // Default: null
* max_retries?: int|Param, // Default: 3
* delay?: int|Param, // Time in ms to delay (or the initial value when multiplier is used). // Default: 1000
* multiplier?: float|Param, // If greater than 1, delay will grow exponentially for each retry: this delay = (delay * (multiple ^ retries)). // Default: 2
* max_delay?: int|Param, // Max time in ms that a retry should ever be delayed (0 = infinite). // Default: 0
* jitter?: float|Param, // Randomness to apply to the delay (between 0 and 1). // Default: 0.1
* },
* rate_limiter?: scalar|Param|null, // Rate limiter name to use when processing messages. // Default: null
* }>,
* failure_transport?: scalar|Param|null, // Transport name to send failed messages to (after all retries have failed). // Default: null
* stop_worker_on_signals?: list<scalar|Param|null>,
* default_bus?: scalar|Param|null, // Default: null
* buses?: array<string, array{ // Default: {"messenger.bus.default":{"default_middleware":{"enabled":true,"allow_no_handlers":false,"allow_no_senders":true},"middleware":[]}}
* default_middleware?: bool|string|array{
* enabled?: bool|Param, // Default: true
* allow_no_handlers?: bool|Param, // Default: false
* allow_no_senders?: bool|Param, // Default: true
* },
* middleware?: list<string|array{ // Default: []
* id?: scalar|Param|null,
* arguments?: list<mixed>,
* }>,
* }>,
* },
* scheduler?: bool|array{ // Scheduler configuration
* enabled?: bool|Param, // Default: false
* },
* disallow_search_engine_index?: bool|Param, // Enabled by default when debug is enabled. // Default: true
* http_client?: bool|array{ // HTTP Client configuration
* enabled?: bool|Param, // Default: false
* max_host_connections?: int|Param, // The maximum number of connections to a single host.
* default_options?: array{
* headers?: array<string, mixed>,
* vars?: array<string, mixed>,
* max_redirects?: int|Param, // The maximum number of redirects to follow.
* http_version?: scalar|Param|null, // The default HTTP version, typically 1.1 or 2.0, leave to null for the best version.
* resolve?: array<string, scalar|Param|null>,
* proxy?: scalar|Param|null, // The URL of the proxy to pass requests through or null for automatic detection.
* no_proxy?: scalar|Param|null, // A comma separated list of hosts that do not require a proxy to be reached.
* timeout?: float|Param, // The idle timeout, defaults to the "default_socket_timeout" ini parameter.
* max_duration?: float|Param, // The maximum execution time for the request+response as a whole.
* bindto?: scalar|Param|null, // A network interface name, IP address, a host name or a UNIX socket to bind to.
* verify_peer?: bool|Param, // Indicates if the peer should be verified in a TLS context.
* verify_host?: bool|Param, // Indicates if the host should exist as a certificate common name.
* cafile?: scalar|Param|null, // A certificate authority file.
* capath?: scalar|Param|null, // A directory that contains multiple certificate authority files.
* local_cert?: scalar|Param|null, // A PEM formatted certificate file.
* local_pk?: scalar|Param|null, // A private key file.
* passphrase?: scalar|Param|null, // The passphrase used to encrypt the "local_pk" file.
* ciphers?: scalar|Param|null, // A list of TLS ciphers separated by colons, commas or spaces (e.g. "RC3-SHA:TLS13-AES-128-GCM-SHA256"...)
* peer_fingerprint?: array{ // Associative array: hashing algorithm => hash(es).
* sha1?: mixed,
* pin-sha256?: mixed,
* md5?: mixed,
* },
* crypto_method?: scalar|Param|null, // The minimum version of TLS to accept; must be one of STREAM_CRYPTO_METHOD_TLSv*_CLIENT constants.
* extra?: array<string, mixed>,
* rate_limiter?: scalar|Param|null, // Rate limiter name to use for throttling requests. // Default: null
* caching?: bool|array{ // Caching configuration.
* enabled?: bool|Param, // Default: false
* cache_pool?: string|Param, // The taggable cache pool to use for storing the responses. // Default: "cache.http_client"
* shared?: bool|Param, // Indicates whether the cache is shared (public) or private. // Default: true
* max_ttl?: int|Param, // The maximum TTL (in seconds) allowed for cached responses. Null means no cap. // Default: null
* },
* retry_failed?: bool|array{
* enabled?: bool|Param, // Default: false
* retry_strategy?: scalar|Param|null, // service id to override the retry strategy. // Default: null
* http_codes?: array<string, array{ // Default: []
* code?: int|Param,
* methods?: list<string|Param>,
* }>,
* max_retries?: int|Param, // Default: 3
* delay?: int|Param, // Time in ms to delay (or the initial value when multiplier is used). // Default: 1000
* multiplier?: float|Param, // If greater than 1, delay will grow exponentially for each retry: delay * (multiple ^ retries). // Default: 2
* max_delay?: int|Param, // Max time in ms that a retry should ever be delayed (0 = infinite). // Default: 0
* jitter?: float|Param, // Randomness in percent (between 0 and 1) to apply to the delay. // Default: 0.1
* },
* },
* mock_response_factory?: scalar|Param|null, // The id of the service that should generate mock responses. It should be either an invokable or an iterable.
* scoped_clients?: array<string, string|array{ // Default: []
* scope?: scalar|Param|null, // The regular expression that the request URL must match before adding the other options. When none is provided, the base URI is used instead.
* base_uri?: scalar|Param|null, // The URI to resolve relative URLs, following rules in RFC 3985, section 2.
* auth_basic?: scalar|Param|null, // An HTTP Basic authentication "username:password".
* auth_bearer?: scalar|Param|null, // A token enabling HTTP Bearer authorization.
* auth_ntlm?: scalar|Param|null, // A "username:password" pair to use Microsoft NTLM authentication (requires the cURL extension).
* query?: array<string, scalar|Param|null>,
* headers?: array<string, mixed>,
* max_redirects?: int|Param, // The maximum number of redirects to follow.
* http_version?: scalar|Param|null, // The default HTTP version, typically 1.1 or 2.0, leave to null for the best version.
* resolve?: array<string, scalar|Param|null>,
* proxy?: scalar|Param|null, // The URL of the proxy to pass requests through or null for automatic detection.
* no_proxy?: scalar|Param|null, // A comma separated list of hosts that do not require a proxy to be reached.
* timeout?: float|Param, // The idle timeout, defaults to the "default_socket_timeout" ini parameter.
* max_duration?: float|Param, // The maximum execution time for the request+response as a whole.
* bindto?: scalar|Param|null, // A network interface name, IP address, a host name or a UNIX socket to bind to.
* verify_peer?: bool|Param, // Indicates if the peer should be verified in a TLS context.
* verify_host?: bool|Param, // Indicates if the host should exist as a certificate common name.
* cafile?: scalar|Param|null, // A certificate authority file.
* capath?: scalar|Param|null, // A directory that contains multiple certificate authority files.
* local_cert?: scalar|Param|null, // A PEM formatted certificate file.
* local_pk?: scalar|Param|null, // A private key file.
* passphrase?: scalar|Param|null, // The passphrase used to encrypt the "local_pk" file.
* ciphers?: scalar|Param|null, // A list of TLS ciphers separated by colons, commas or spaces (e.g. "RC3-SHA:TLS13-AES-128-GCM-SHA256"...).
* peer_fingerprint?: array{ // Associative array: hashing algorithm => hash(es).
* sha1?: mixed,
* pin-sha256?: mixed,
* md5?: mixed,
* },
* crypto_method?: scalar|Param|null, // The minimum version of TLS to accept; must be one of STREAM_CRYPTO_METHOD_TLSv*_CLIENT constants.
* extra?: array<string, mixed>,
* rate_limiter?: scalar|Param|null, // Rate limiter name to use for throttling requests. // Default: null
* caching?: bool|array{ // Caching configuration.
* enabled?: bool|Param, // Default: false
* cache_pool?: string|Param, // The taggable cache pool to use for storing the responses. // Default: "cache.http_client"
* shared?: bool|Param, // Indicates whether the cache is shared (public) or private. // Default: true
* max_ttl?: int|Param, // The maximum TTL (in seconds) allowed for cached responses. Null means no cap. // Default: null
* },
* retry_failed?: bool|array{
* enabled?: bool|Param, // Default: false
* retry_strategy?: scalar|Param|null, // service id to override the retry strategy. // Default: null
* http_codes?: array<string, array{ // Default: []
* code?: int|Param,
* methods?: list<string|Param>,
* }>,
* max_retries?: int|Param, // Default: 3
* delay?: int|Param, // Time in ms to delay (or the initial value when multiplier is used). // Default: 1000
* multiplier?: float|Param, // If greater than 1, delay will grow exponentially for each retry: delay * (multiple ^ retries). // Default: 2
* max_delay?: int|Param, // Max time in ms that a retry should ever be delayed (0 = infinite). // Default: 0
* jitter?: float|Param, // Randomness in percent (between 0 and 1) to apply to the delay. // Default: 0.1
* },
* }>,
* },
* mailer?: bool|array{ // Mailer configuration
* enabled?: bool|Param, // Default: false
* message_bus?: scalar|Param|null, // The message bus to use. Defaults to the default bus if the Messenger component is installed. // Default: null
* dsn?: scalar|Param|null, // Default: null
* transports?: array<string, scalar|Param|null>,
* envelope?: array{ // Mailer Envelope configuration
* sender?: scalar|Param|null,
* recipients?: list<scalar|Param|null>,
* allowed_recipients?: list<scalar|Param|null>,
* },
* headers?: array<string, string|array{ // Default: []
* value?: mixed,
* }>,
* dkim_signer?: bool|array{ // DKIM signer configuration
* enabled?: bool|Param, // Default: false
* key?: scalar|Param|null, // Key content, or path to key (in PEM format with the `file://` prefix) // Default: ""
* domain?: scalar|Param|null, // Default: ""
* select?: scalar|Param|null, // Default: ""
* passphrase?: scalar|Param|null, // The private key passphrase // Default: ""
* options?: array<string, mixed>,
* },
* smime_signer?: bool|array{ // S/MIME signer configuration
* enabled?: bool|Param, // Default: false
* key?: scalar|Param|null, // Path to key (in PEM format) // Default: ""
* certificate?: scalar|Param|null, // Path to certificate (in PEM format without the `file://` prefix) // Default: ""
* passphrase?: scalar|Param|null, // The private key passphrase // Default: null
* extra_certificates?: scalar|Param|null, // Default: null
* sign_options?: int|Param, // Default: null
* },
* smime_encrypter?: bool|array{ // S/MIME encrypter configuration
* enabled?: bool|Param, // Default: false
* repository?: scalar|Param|null, // S/MIME certificate repository service. This service shall implement the `Symfony\Component\Mailer\EventListener\SmimeCertificateRepositoryInterface`. // Default: ""
* cipher?: int|Param, // A set of algorithms used to encrypt the message // Default: null
* },
* },
* secrets?: bool|array{
* enabled?: bool|Param, // Default: true
* vault_directory?: scalar|Param|null, // Default: "%kernel.project_dir%/config/secrets/%kernel.runtime_environment%"
* local_dotenv_file?: scalar|Param|null, // Default: "%kernel.project_dir%/.env.%kernel.environment%.local"
* decryption_env_var?: scalar|Param|null, // Default: "base64:default::SYMFONY_DECRYPTION_SECRET"
* },
* notifier?: bool|array{ // Notifier configuration
* enabled?: bool|Param, // Default: false
* message_bus?: scalar|Param|null, // The message bus to use. Defaults to the default bus if the Messenger component is installed. // Default: null
* chatter_transports?: array<string, scalar|Param|null>,
* texter_transports?: array<string, scalar|Param|null>,
* notification_on_failed_messages?: bool|Param, // Default: false
* channel_policy?: array<string, string|list<scalar|Param|null>>,
* admin_recipients?: list<array{ // Default: []
* email?: scalar|Param|null,
* phone?: scalar|Param|null, // Default: ""
* }>,
* },
* rate_limiter?: bool|array{ // Rate limiter configuration
* enabled?: bool|Param, // Default: true
* limiters?: array<string, array{ // Default: []
* lock_factory?: scalar|Param|null, // The service ID of the lock factory used by this limiter (or null to disable locking). // Default: "auto"
* cache_pool?: scalar|Param|null, // The cache pool to use for storing the current limiter state. // Default: "cache.rate_limiter"
* storage_service?: scalar|Param|null, // The service ID of a custom storage implementation, this precedes any configured "cache_pool". // Default: null
* policy?: "fixed_window"|"token_bucket"|"sliding_window"|"compound"|"no_limit"|Param, // The algorithm to be used by this limiter.
* limiters?: list<scalar|Param|null>,
* limit?: int|Param, // The maximum allowed hits in a fixed interval or burst.
* interval?: scalar|Param|null, // Configures the fixed interval if "policy" is set to "fixed_window" or "sliding_window". The value must be a number followed by "second", "minute", "hour", "day", "week" or "month" (or their plural equivalent).
* rate?: array{ // Configures the fill rate if "policy" is set to "token_bucket".
* interval?: scalar|Param|null, // Configures the rate interval. The value must be a number followed by "second", "minute", "hour", "day", "week" or "month" (or their plural equivalent).
* amount?: int|Param, // Amount of tokens to add each interval. // Default: 1
* },
* }>,
* },
* uid?: bool|array{ // Uid configuration
* enabled?: bool|Param, // Default: true
* default_uuid_version?: 7|6|4|1|Param, // Default: 7
* name_based_uuid_version?: 5|3|Param, // Default: 5
* name_based_uuid_namespace?: scalar|Param|null,
* time_based_uuid_version?: 7|6|1|Param, // Default: 7
* time_based_uuid_node?: scalar|Param|null,
* },
* html_sanitizer?: bool|array{ // HtmlSanitizer configuration
* enabled?: bool|Param, // Default: false
* sanitizers?: array<string, array{ // Default: []
* allow_safe_elements?: bool|Param, // Allows "safe" elements and attributes. // Default: false
* allow_static_elements?: bool|Param, // Allows all static elements and attributes from the W3C Sanitizer API standard. // Default: false
* allow_elements?: array<string, mixed>,
* block_elements?: list<string|Param>,
* drop_elements?: list<string|Param>,
* allow_attributes?: array<string, mixed>,
* drop_attributes?: array<string, mixed>,
* force_attributes?: array<string, array<string, string|Param>>,
* force_https_urls?: bool|Param, // Transforms URLs using the HTTP scheme to use the HTTPS scheme instead. // Default: false
* allowed_link_schemes?: list<string|Param>,
* allowed_link_hosts?: list<string|Param>|null,
* allow_relative_links?: bool|Param, // Allows relative URLs to be used in links href attributes. // Default: false
* allowed_media_schemes?: list<string|Param>,
* allowed_media_hosts?: list<string|Param>|null,
* allow_relative_medias?: bool|Param, // Allows relative URLs to be used in media source attributes (img, audio, video, ...). // Default: false
* with_attribute_sanitizers?: list<string|Param>,
* without_attribute_sanitizers?: list<string|Param>,
* max_input_length?: int|Param, // The maximum length allowed for the sanitized input. // Default: 0
* }>,
* },
* webhook?: bool|array{ // Webhook configuration
* enabled?: bool|Param, // Default: false
* message_bus?: scalar|Param|null, // The message bus to use. // Default: "messenger.default_bus"
* routing?: array<string, array{ // Default: []
* service?: scalar|Param|null,
* secret?: scalar|Param|null, // Default: ""
* }>,
* },
* remote-event?: bool|array{ // RemoteEvent configuration
* enabled?: bool|Param, // Default: false
* },
* json_streamer?: bool|array{ // JSON streamer configuration
* enabled?: bool|Param, // Default: false
* },
* }
* @psalm-type TwigConfig = array{
* form_themes?: list<scalar|Param|null>,
* globals?: array<string, array{ // Default: []
* id?: scalar|Param|null,
* type?: scalar|Param|null,
* value?: mixed,
* }>,
* autoescape_service?: scalar|Param|null, // Default: null
* autoescape_service_method?: scalar|Param|null, // Default: null
* base_template_class?: scalar|Param|null, // Deprecated: The child node "base_template_class" at path "twig.base_template_class" is deprecated.
* cache?: scalar|Param|null, // Default: true
* charset?: scalar|Param|null, // Default: "%kernel.charset%"
* debug?: bool|Param, // Default: "%kernel.debug%"
* strict_variables?: bool|Param, // Default: "%kernel.debug%"
* auto_reload?: scalar|Param|null,
* optimizations?: int|Param,
* default_path?: scalar|Param|null, // The default path used to load templates. // Default: "%kernel.project_dir%/templates"
* file_name_pattern?: list<scalar|Param|null>,
* paths?: array<string, mixed>,
* date?: array{ // The default format options used by the date filter.
* format?: scalar|Param|null, // Default: "F j, Y H:i"
* interval_format?: scalar|Param|null, // Default: "%d days"
* timezone?: scalar|Param|null, // The timezone used when formatting dates, when set to null, the timezone returned by date_default_timezone_get() is used. // Default: null
* },
* number_format?: array{ // The default format options for the number_format filter.
* decimals?: int|Param, // Default: 0
* decimal_point?: scalar|Param|null, // Default: "."
* thousands_separator?: scalar|Param|null, // Default: ","
* },
* mailer?: array{
* html_to_text_converter?: scalar|Param|null, // A service implementing the "Symfony\Component\Mime\HtmlToTextConverter\HtmlToTextConverterInterface". // Default: null
* },
* }
* @psalm-type ConfigType = array{
* imports?: ImportsConfig,
* parameters?: ParametersConfig,
* services?: ServicesConfig,
* framework?: FrameworkConfig,
* twig?: TwigConfig,
* "when@dev"?: array{
* imports?: ImportsConfig,
* parameters?: ParametersConfig,
* services?: ServicesConfig,
* framework?: FrameworkConfig,
* twig?: TwigConfig,
* },
* "when@prod"?: array{
* imports?: ImportsConfig,
* parameters?: ParametersConfig,
* services?: ServicesConfig,
* framework?: FrameworkConfig,
* twig?: TwigConfig,
* },
* ...<string, ExtensionType|array{ // extra keys must follow the when@%env% pattern or match an extension alias
* imports?: ImportsConfig,
* parameters?: ParametersConfig,
* services?: ServicesConfig,
* ...<string, ExtensionType>,
* }>
* }
*/
final class App
{
/**
* @param ConfigType $config
*
* @psalm-return ConfigType
*/
public static function config(array $config): array
{
/** @var ConfigType $config */
$config = AppReference::config($config);
return $config;
}
}
namespace Symfony\Component\Routing\Loader\Configurator;
/**
* This class provides array-shapes for configuring the routes of an application.
*
* Example:
*
* ```php
* // config/routes.php
* namespace Symfony\Component\Routing\Loader\Configurator;
*
* return Routes::config([
* 'controllers' => [
* 'resource' => 'routing.controllers',
* ],
* ]);
* ```
*
* @psalm-type RouteConfig = array{
* path: string|array<string,string>,
* controller?: string,
* methods?: string|list<string>,
* requirements?: array<string,string>,
* defaults?: array<string,mixed>,
* options?: array<string,mixed>,
* host?: string|array<string,string>,
* schemes?: string|list<string>,
* condition?: string,
* locale?: string,
* format?: string,
* utf8?: bool,
* stateless?: bool,
* }
* @psalm-type ImportConfig = array{
* resource: string,
* type?: string,
* exclude?: string|list<string>,
* prefix?: string|array<string,string>,
* name_prefix?: string,
* trailing_slash_on_root?: bool,
* controller?: string,
* methods?: string|list<string>,
* requirements?: array<string,string>,
* defaults?: array<string,mixed>,
* options?: array<string,mixed>,
* host?: string|array<string,string>,
* schemes?: string|list<string>,
* condition?: string,
* locale?: string,
* format?: string,
* utf8?: bool,
* stateless?: bool,
* }
* @psalm-type AliasConfig = array{
* alias: string,
* deprecated?: array{package:string, version:string, message?:string},
* }
* @psalm-type RoutesConfig = array{
* "when@dev"?: array<string, RouteConfig|ImportConfig|AliasConfig>,
* "when@prod"?: array<string, RouteConfig|ImportConfig|AliasConfig>,
* ...<string, RouteConfig|ImportConfig|AliasConfig>
* }
*/
final class Routes
{
/**
* @param RoutesConfig $config
*
* @psalm-return RoutesConfig
*/
public static function config(array $config): array
{
return $config;
}
}
+71 -4
View File
@@ -27,6 +27,16 @@ parameters:
# once blocked, do we respond with "I'm a teapot", false to use "Too many requests" # once blocked, do we respond with "I'm a teapot", false to use "Too many requests"
env(TEAPOT): '1' # boolean env(TEAPOT): '1' # boolean
# --- remote-user header ---
# Controls the value sent in the Remote-User header on successful auth.
# session: the session id (default, backward-compatible)
# static: a fixed string (set via REMOTE_USER_STATIC)
# mapped: look up session id in REMOTE_USER_MAP (format: id1:user1,id2:user2)
# none: do not send the Remote-User header at all
env(REMOTE_USER): 'session'
env(REMOTE_USER_STATIC): 'authenticated'
env(REMOTE_USER_MAP): ''
# --- rate limiting --- # --- rate limiting ---
# Note: rate limiting can *NOT* be disabled, but you could allow hundreds of logins a second # Note: rate limiting can *NOT* be disabled, but you could allow hundreds of logins a second
# rate limiting, default is the lower of 2 per 30 seconds or 10 per hour # rate limiting, default is the lower of 2 per 30 seconds or 10 per hour
@@ -35,6 +45,32 @@ parameters:
env(UPPER_COUNT): 10 # 10 per hour env(UPPER_COUNT): 10 # 10 per hour
env(UPPER_TIME): 3600 # seconds (1 hour) env(UPPER_TIME): 3600 # seconds (1 hour)
# --- public access (rate-limited, no auth required) ---
# Comma-separated path patterns for public access. Wildcards: * (single
# segment), ** (cross segments). Optional host prefix: host.com/path/**
# When empty (default), the feature is fully disabled.
env(PUBLIC_PATHS): ''
env(PUBLIC_BURST_COUNT): 100 # max requests per burst window per IP
env(PUBLIC_BURST_TIME): 60 # burst window in seconds
env(PUBLIC_UPPER_COUNT): 500 # max requests per sustained window per IP
env(PUBLIC_UPPER_TIME): 3600 # sustained window in seconds (1 hour)
# --- passkey authentication ---
# Requires central auth (SUBDOMAIN_REDIRECT=1 + AUTH_SUBDOMAIN) and HTTPS.
# Enabling this without central auth makes the container fail at cache warmup
# rather than offering a feature that cannot work.
env(PASSKEY_ENABLED): '0' # boolean, 1 to offer passkeys on the auth subdomain
env(PASSKEY_RP_NAME): '' # blank to use TITLE
env(PASSKEY_USER_VERIFICATION): 'required' # required|preferred|discouraged
env(PASSKEY_TIMEOUT): '60000' # milliseconds
# Extra options, custom labels
env(PASSKEY_BUTTON_NAME): 'Sign in with a passkey'
env(PASSKEY_REGISTER_NAME): 'Register this device as a passkey'
# bounds how many ceremonies one caller can start (resource guard, not the
# login budget — see config/packages/rate_limiter.yaml)
env(PASSKEY_BEGIN_BURST_COUNT): 30
env(PASSKEY_BEGIN_BURST_TIME): 60
# --- styling options --- # --- styling options ---
env(TITLE): 'Pre-Authentication System' env(TITLE): 'Pre-Authentication System'
env(BG_COLOR): '#029386' # teal env(BG_COLOR): '#029386' # teal
@@ -56,16 +92,35 @@ parameters:
# --- application variables --- # --- application variables ---
app.totp_uri: '%env(TOTP_URI)%' app.totp_uri: '%env(TOTP_URI)%'
app.cookie_ttl: '%env(COOKIE_TTL)%' app.cookie_ttl: '%env(int:COOKIE_TTL)%'
app.subdomain_redirect: '%env(SUBDOMAIN_REDIRECT)%' app.subdomain_redirect: '%env(bool:SUBDOMAIN_REDIRECT)%'
app.auth_subdomain: '%env(AUTH_SUBDOMAIN)%' app.auth_subdomain: '%env(AUTH_SUBDOMAIN)%'
app.ip_ttl: '%env(IP_TTL)%' app.ip_ttl: '%env(int:IP_TTL)%'
app.teapot: '%env(TEAPOT)%' app.teapot: '%env(bool:TEAPOT)%'
app.remote_user: '%env(REMOTE_USER)%'
app.remote_user_static: '%env(REMOTE_USER_STATIC)%'
app.remote_user_map: '%env(REMOTE_USER_MAP)%'
app.public_paths: '%env(PUBLIC_PATHS)%'
app.public_burst_count: '%env(int:PUBLIC_BURST_COUNT)%'
app.public_burst_time: '%env(int:PUBLIC_BURST_TIME)%'
app.public_upper_count: '%env(int:PUBLIC_UPPER_COUNT)%'
app.public_upper_time: '%env(int:PUBLIC_UPPER_TIME)%'
app.error_message: '%env(ERROR_MESSAGE)%' app.error_message: '%env(ERROR_MESSAGE)%'
app.teapot_title: '%env(TEAPOT_TITLE)%' app.teapot_title: '%env(TEAPOT_TITLE)%'
app.too_many_title: '%env(TOO_MANY_TITLE)%' app.too_many_title: '%env(TOO_MANY_TITLE)%'
app.title: '%env(TITLE)%'
app.passkey_enabled: '%env(bool:PASSKEY_ENABLED)%'
app.passkey_rp_name: '%env(PASSKEY_RP_NAME)%'
app.passkey_user_verification: '%env(PASSKEY_USER_VERIFICATION)%'
app.passkey_timeout: '%env(int:PASSKEY_TIMEOUT)%'
app.passkey_button_name: '%env(PASSKEY_BUTTON_NAME)%'
app.passkey_register_name: '%env(PASSKEY_REGISTER_NAME)%'
services: services:
# default configuration for services in *this* file # default configuration for services in *this* file
@@ -80,3 +135,15 @@ services:
# add more service definitions when explicit configuration is needed # add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones # please note that last definitions always *replace* previous ones
# the boot-time passkey configuration check runs during `cache:warmup`, so a
# misconfigured deployment fails to start instead of failing in a browser
App\Service\PasskeyPolicyInterface: '@App\Service\PasskeyPolicy'
App\Service\PasskeyInterface: '@App\Service\PasskeyManager'
App\Service\PasskeyCeremonyStoreInterface: '@App\Service\PasskeyCeremonyStore'
App\Service\PasskeyCredentialStoreInterface: '@App\Service\PasskeyCredentialStore'
App\Service\SessionIssuerInterface: '@App\Service\SessionIssuer'
# the ceremony factory takes no constructor arguments and holds no state, so
# it is built once and shared rather than re-created per ceremony
App\Service\PasskeyCeremonyFactory: ~
+63
View File
@@ -0,0 +1,63 @@
# Preauth build config
#
# CI (develop.yaml / docker.yaml) invokes this with --file so the compose
# file that lives in the same directory is not merged in as extra targets.
#
# DOCKERHUB_TARGET is the org/repo (Gitea Settings → Variables)
# CI sets TAG=latest + VERSION=<v-stripped> for tag pushes,
# TAG=develop for pushes to main.
#
# MAX_REQUESTS=0 docker buildx bake # specify variables to override
variable "DOCKERHUB_TARGET" {
default = "digitaladapt/preauth"
description = "Docker Hub repo/org (Gitea repo variable DOCKERHUB_TARGET)."
}
variable "TAG" {
default = "latest"
description = "Base tag for this build: latest (release), develop (main push), or a version."
}
variable "VERSION" {
default = ""
description = "Optional full version (v stripped) to also tag with; empty for develop builds."
}
variable "MAX_REQUESTS" {
default = "500"
description = "Restart each FrankenPHP worker thread after N requests (0 disables). Baked in at build time; the same env var overrides it at runtime."
}
group "default" {
targets = ["app"]
}
target "app" {
dockerfile = "Dockerfile"
target = "app"
context = "."
platforms = ["linux/amd64", "linux/arm64"]
# Layer cache. The shared docker-publish.yaml sets cache-from/cache-to for
# its `action` backend but NOT for `bake`, so specifying it here is what keeps
# CI builds warm. preauth compiles APCu from source (pecl) in both stages, so
# a cold build is expensive.
#
# Local builds outside CI have no GHA cache service, so override:
# docker buildx bake --set 'app.cache-to=' --set 'app.cache-from='
cache-from = ["type=gha"]
cache-to = ["type=gha,mode=max"]
# The Dockerfile declares ARG MAX_REQUESTS=500 for plain `docker build`.
# It is repeated explicitly here so CI's value is visible and can be changed
# in this file instead of in a workflow. Keep the two defaults in sync.
args = {
MAX_REQUESTS = "${MAX_REQUESTS}"
}
tags = concat(
["${DOCKERHUB_TARGET}:${TAG}"],
VERSION != "" ? ["${DOCKERHUB_TARGET}:${VERSION}"] : [],
)
}
+36
View File
@@ -0,0 +1,36 @@
# PreAuth — Caddyfile / FrankenPHP app config.
#
# The container serves plain HTTP on :80; TLS is terminated by the upstream
# proxy. SERVER_NAME=:80 is set in the Dockerfile.
#
# This is the config the image ships (/etc/frankenphp/Caddyfile). The
# Caddyfile in the repository root is the example for host-side setups.
{
frankenphp {
# Restart each PHP worker thread after this many requests, containing
# slow memory growth across long uptime. Preserves the 7.4-era default
# loop count of runtime/frankenphp-symfony (500) after the Symfony 8.1
# upgrade. Set MAX_REQUESTS=0 to disable restarts. The Dockerfile bakes
# in the default of 500 via build arg; override at runtime with:
# docker run -e MAX_REQUESTS=5000 ...
# For full control, the stock FRANKENPHP_CONFIG env var can inject any
# directive under this block instead.
max_requests {$MAX_REQUESTS}
}
# The admin API is deliberately left at its default: bound to 127.0.0.1
# inside the container, where it is the target of the image's
# HEALTHCHECK. It is not reachable from outside the container. Do NOT set
# `admin off` here without also changing that probe — the app has no 2xx
# liveness route to fall back on, because every anonymous request is
# answered with the login page and a 401.
}
http:// {
root public/
rewrite index.php
php {
root /app/public
worker index.php
}
}
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
#
# PreAuth container entrypoint.
#
# Responsibilities:
# 1. Warm the prod cache with the injected secrets.
# 2. Hand off to CMD (FrankenPHP server, or a console override:
# `docker exec -it preauth bin/console app:generate-backup-codes`).
#
# Secrets are env vars injected at runtime, never baked into images (§8.12).
# The container has no shell to hand out otherwise — it runs as an unprivileged
# user with a nologin shell — so the real boot validation is
# `cache:warmup` failing here, which is also what makes it worth doing.
set -e
if [ "$APP_ENV" = "prod" ]; then
echo "Warming cache..."
php bin/console cache:warmup
fi
exec "$@"
+41
View File
@@ -0,0 +1,41 @@
; PreAuth php.ini overrides — merged on top of the FrankenPHP base image
; defaults.
;
; The base image ships no php.ini (only the php.ini-production template), so
; the production switches that matter are stated explicitly here rather than
; inherited — verified against a real boot: without them the response carries
; `X-Powered-By: PHP/8.5.10` and errors would render into the body.
;
; PreAuth keeps its session state in APCu plus a filesystem cache pool, so the
; settings that matter most are the cache ones.
; Never advertise the interpreter, never print errors to the client. This is
; an authentication gateway: a stack trace in a 500 body is an information
; leak. Errors go to stderr for the log collector.
expose_php = Off
display_errors = Off
log_errors = On
error_log = /proc/self/fd/2
memory_limit = 256M
upload_max_filesize = 2M
post_max_size = 8M
; OPcache for the FrankenPHP worker: the image is immutable, so timestamps
; never need revalidating. The CLI console also runs the app, hence
; enable_cli = 1.
opcache.enable = 1
opcache.enable_cli = 1
opcache.validate_timestamps = 0
opcache.memory_consumption = 128
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 20000
; APCu — nonce cache, rate limiter and session cache all live in it, and the
; console needs it too (`bin/console` commands manage cache state).
apc.enabled = 1
apc.enable_cli = 1
apc.shm_size = 64M
apc.ttl = 0
date.timezone = UTC
-28
View File
@@ -1,28 +0,0 @@
# example of securing full service
# TODO replace domain and service name and port
service.example.com {
forward_auth preauth {
uri {uri}
copy_headers Remote-User
}
reverse_proxy service-container:80
}
# you can choose to only restrict select paths
# or any other Caddy match criteria, if desired
# IE: https://protected.example.com/secure/
protected.example.com {
# note any request that does not start with "/secure/" is NOT protected
forward_auth /secure/* preauth {
uri {uri}
copy_headers Remote-User
}
reverse_proxy protected-service:9000
}
# optionally, if you want to use a subdomain for centeral preauth
# set SUBDOMAIN_REDIRECT to true
# and AUTH_SUBDOMAIN to match the subdomain you use here
auth.example.com {
reverse_proxy preauth
}
-55
View File
@@ -1,55 +0,0 @@
# --- main options ---
# URI containing secret and config for TOTP, which determines the token to login
# app will generate one, if not provided, but you should copy it to your .env file
# format: "otpauth://totp/<label>?secret=<secret-key>"
#TOTP_URI='' # blank to have the app generate one at random
# how long will someone stay logged in, measured in seconds, zero for DEFAULT
#COOKIE_TTL=2592000 # default 30 days
# we can use a central auth, so that users only need to login once to have access to
# multiple services. Requires using sub-domains under the same domain.
# IE: if enabled have "service-one.example.com" redirect "auth.example.com", and after
# successful auth, user can visit "service-two.example.com" without having to login again.
#SUBDOMAIN_REDIRECT=false # default disabled, boolean
#AUTH_SUBDOMAIN='' # blank, hostname we send user to, to see login page
# --- extra options ---
# how long do we allow *ALL* traffic from an ip address after successful login
# could be useful if you have a system which does not handle cookies
#IP_TTL=0 # default disabled, time in seconds
# once blocked, do we respond with "I'm a teapot", false to use "Too many requests"
#TEAPOT=true # default enabled, boolean
# --- rate limiting ---
# Note: rate limiting can *NOT* be disabled, but you could allow hundreds of logins a second
# rate limiting, default is the lower of 2 per 30 seconds or 10 per hour
#BURST_COUNT=2 # 2 per 30 seconds
#BURST_TIME=30 # seconds
#UPPER_COUNT=10 # 10 per hour
#UPPER_TIME=3600 # seconds (1 hour)
# --- styling options ---
#TITLE='Pre-Authentication System'
#BG_COLOR='#029386' # teal
#FG_COLOR='#ffffff' # white
#ERROR_COLOR='#ffb16d' # apricot (light orange)
#ID_NAME='Session ID'
#TOKEN_NAME='Authentication Token'
#SUBMIT_NAME='Submit'
#ERROR_MESSAGE='Unsuccessful login attempt'
# title and message to use on block page, if teapot is true
#TEAPOT_TITLE="I'm a teapot"
#TEAPOT_MESSAGE='I refuse to brew coffee'
# title and message to use on block page, if teapot is false
#TOO_MANY_TITLE='Too many requests'
#TOO_MANY_MESSAGE='Try again later'
# --- debug options ---
#SHELL_VERBOSITY=0 # set to "3" to log debug
+107
View File
@@ -0,0 +1,107 @@
# --- main options ---
# URI containing secret and config for TOTP, which determines the token to login
# app will generate one, if not provided, but you should copy it to your .env file
# format: "otpauth://totp/<label>?secret=<secret-key>"
#TOTP_URI='' # blank to have the app generate one at random
# how long will someone stay logged in, measured in seconds, zero for DEFAULT
#COOKIE_TTL=2592000 # default 30 days
# we can use a central auth, so that users only need to login once to have access to
# multiple services. Requires using sub-domains under the same domain.
# IE: if enabled have "service-one.example.com" redirect "auth.example.com", and after
# successful auth, user can visit "service-two.example.com" without having to login again.
#SUBDOMAIN_REDIRECT=false # default disabled, boolean
#AUTH_SUBDOMAIN='' # blank, hostname we send user to, to see login page
# --- passkey authentication ---
# Passkeys (Touch ID / Windows Hello / security keys) as an alternative to TOTP.
#
# REQUIRES central authentication (SUBDOMAIN_REDIRECT=true plus AUTH_SUBDOMAIN)
# and HTTPS. Passkeys are bound to a relying party that spans the base domain,
# which only exists when central auth is configured; and browsers refuse to run
# a ceremony over plain HTTP.
#
# Enabling this without central auth is a hard error: the container fails at
# start-up (cache:warmup) rather than offering a passkey button that cannot work.
#
# There is deliberately no option to allow an http:// origin, and none to relax
# the requirement for local development. See the README for the local TLS setup.
#PASSKEY_ENABLED=false # default disabled, boolean
#PASSKEY_RP_NAME='' # blank to use TITLE
#PASSKEY_USER_VERIFICATION='required' # required | preferred | discouraged
#PASSKEY_TIMEOUT=60000 # ceremony timeout in milliseconds
#PASSKEY_BUTTON_NAME='Sign in with a passkey'
#PASSKEY_REGISTER_NAME='Register this device as a passkey'
#PASSKEY_BEGIN_BURST_COUNT=30 # ceremonies one caller may start per window
#PASSKEY_BEGIN_BURST_TIME=60 # window for the above, in seconds
# --- extra options ---
# how long do we allow *ALL* traffic from an ip address after successful login
# could be useful if you have a system which does not handle cookies
#IP_TTL=0 # default disabled, time in seconds
# once blocked, do we respond with "I'm a teapot", false to use "Too many requests"
#TEAPOT=true # default enabled, boolean
# --- server / worker options ---
# (container/deployment only) restart each FrankenPHP worker thread after
# this many requests, containing memory growth across long uptime;
# matching the default from the old runtime/frankenphp-symfony package.
# 0 disables restarts. consumed by the Caddyfile, not the PHP app.
#MAX_REQUESTS=500 # default 500
# --- remote-user header ---
# Controls the value sent in the Remote-User header on successful auth.
# session: the session id (default, backward-compatible)
# static: a fixed string (set via REMOTE_USER_STATIC)
# mapped: look up session id in REMOTE_USER_MAP (format: id1:user1,id2:user2)
# none: do not send the Remote-User header at all
#REMOTE_USER=session
#REMOTE_USER_STATIC=authenticated
#REMOTE_USER_MAP=''
# --- rate limiting ---
# Note: rate limiting can *NOT* be disabled, but you could allow hundreds of logins a second
# rate limiting, default is the lower of 2 per 30 seconds or 10 per hour
#BURST_COUNT=2 # 2 per 30 seconds
#BURST_TIME=30 # seconds
#UPPER_COUNT=10 # 10 per hour
#UPPER_TIME=3600 # seconds (1 hour)
# --- public access (rate-limited, no auth required) ---
# Comma-separated path patterns for public access. Wildcards:
# * matches any chars within one path segment (not crossing /)
# ** matches any chars including / (crosses path segments)
# Optional host prefix: host.example.com/path/**
# When empty (default), the feature is fully disabled.
#PUBLIC_PATHS=''
#PUBLIC_BURST_COUNT=100 # max requests per burst window per IP
#PUBLIC_BURST_TIME=60 # burst window in seconds
#PUBLIC_UPPER_COUNT=500 # max requests per sustained window per IP
#PUBLIC_UPPER_TIME=3600 # sustained window in seconds (1 hour)
# --- styling options ---
#TITLE='Pre-Authentication System'
#BG_COLOR='#029386' # teal
#FG_COLOR='#ffffff' # white
#ERROR_COLOR='#ffb16d' # apricot (light orange)
#ID_NAME='Session ID'
#TOKEN_NAME='Authentication Token'
#SUBMIT_NAME='Submit'
#ERROR_MESSAGE='Unsuccessful login attempt'
# title and message to use on block page, if teapot is true
#TEAPOT_TITLE="I'm a teapot"
#TEAPOT_MESSAGE='I refuse to brew coffee'
# title and message to use on block page, if teapot is false
#TOO_MANY_TITLE='Too many requests'
#TOO_MANY_MESSAGE='Try again later'
# --- debug options ---
#SHELL_VERBOSITY=0 # set to "3" to log debug
+110
View File
@@ -0,0 +1,110 @@
# preauth example Caddyfile
# --- anti-caching guard for the login flow ---
# The login page, failed logins, redirects, and rate-limit pages must never
# be stored or replayed by a browser or intermediate cache. If they are,
# an aggressive cache (notably older Safari) can resurrect a stale pre-auth
# response — appearing to log a user back out after a refresh. preauth
# sends these headers itself; mirroring them here with `header_down` keeps
# the guarantee at the edge. Import this snippet inside every `forward_auth`
# block:
#
# forward_auth preauth { ...; import preauth_no_store }
#
# Note: 2xx auth responses are consumed by Caddy's forward_auth check and
# never reach the browser, and the protected service's own responses are
# not affected — so the cache headers of your services are left alone.
(preauth_no_store) {
header_down Cache-Control "no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0, s-maxage=0"
header_down Pragma "no-cache"
header_down Expires "0"
header_down Surrogate-Control "no-store"
header_down Vary "*"
}
# example of securing full service
# TODO replace domain and service name and port
service.example.com {
forward_auth preauth {
uri {uri}
copy_headers Remote-User
import preauth_no_store
}
reverse_proxy service-container:80
}
# you can choose to only restrict select paths
# or any other Caddy match criteria, if desired
# IE: https://protected.example.com/secure/
protected.example.com {
# note any request that does not start with "/secure/" is NOT protected
forward_auth /secure/* preauth {
uri {uri}
copy_headers Remote-User
import preauth_no_store
}
reverse_proxy protected-service:9000
}
# optionally, if you want to use a subdomain for central preauth
# set SUBDOMAIN_REDIRECT to true
# and AUTH_SUBDOMAIN to match the subdomain you use here
#
# Passkeys (PASSKEY_ENABLED) require this block AND HTTPS: the ceremony runs
# here and the credential is scoped to the base domain. Caddy provisions a
# certificate automatically for a real hostname, so nothing extra is needed in
# production. This block is also deliberately NOT behind forward_auth — the
# browser talks to it directly during a ceremony.
auth.example.com {
reverse_proxy preauth
}
# --- local development with passkeys ---
# Browsers only allow a WebAuthn ceremony over HTTPS, and preauth does not offer
# an exemption for http://localhost (that would be a way to run passkeys
# insecurely in production). So to exercise passkeys locally, give yourself a
# real hostname and a locally-trusted certificate:
#
# 1. Point the names at your machine:
# # /etc/hosts
# 127.0.0.1 auth.preauthtest.local app.preauthtest.local
# 2. Trust a certificate for them (mkcert installs a local CA):
# mkcert auth.preauthtest.local app.preauthtest.local
#
# 3. In preauth's .env:
# SUBDOMAIN_REDIRECT=true
# AUTH_SUBDOMAIN=auth.preauthtest.local
# PASSKEY_ENABLED=true
#
# 4. Terminate TLS here and proxy to the container:
#
# auth.preauthtest.local, "*.preauthtest.local" {
# tls /path/to/auth.preauthtest.local+1.pem /path/to/auth.preauthtest.local+1-key.pem
# reverse_proxy preauth
# }
#
# Note "localhost" itself cannot be used: it has no base domain, so central
# auth cannot be configured and passkeys stay disabled.
# --- public rate-limited access (v1.1) ---
# Configure PUBLIC_PATHS env var to specify which paths are public.
# Example: PUBLIC_PATHS=/public/**
# Unauthenticated visitors to public paths are rate-limited separately
# from login attempts. Authenticated users bypass the public rate limiter.
#
# This example protects all of Gitea except /public/** which is
# publicly accessible but rate-limited (e.g., 100 req/min, 500 req/hr).
git.example.com {
forward_auth preauth {
uri {uri}
copy_headers Remote-User
import preauth_no_store
}
reverse_proxy gitea:3000
}
# In preauth's .env:
# PUBLIC_PATHS=/public/**
# PUBLIC_BURST_COUNT=100
# PUBLIC_BURST_TIME=60
# PUBLIC_UPPER_COUNT=500
# PUBLIC_UPPER_TIME=3600
@@ -1,7 +1,8 @@
services: services:
preauth: preauth:
env_file: env_file:
# TODO rename "example.env" to ".env", edit as needed # copy ".env.example" to ".env", edit as needed, and put APP_SECRET
# in it (any long random string).
# strongly recommend setting TOTP_URI, if not provided the app # strongly recommend setting TOTP_URI, if not provided the app
# will generate one for you, please copy it into your .env file # will generate one for you, please copy it into your .env file
- .env - .env
@@ -9,8 +10,10 @@ services:
- 80 - 80
image: digitaladapt/preauth:latest image: digitaladapt/preauth:latest
restart: unless-stopped restart: unless-stopped
# if you wish to set the user, you must make sure that the user # The image runs as the non-root `app` user (uid/gid 1000) and creates
# can write to /config and /data within the container # its state directories owned by that user, so a named volume inherits
# the right ownership on first start — no `user:` override is needed.
# If you pin one anyway, it must be able to write /config and /data.
#user: <uid>:<gid> #user: <uid>:<gid>
volumes: volumes:
- preauth-config:/config - preauth-config:/config
@@ -19,4 +22,3 @@ services:
volumes: volumes:
preauth-config: preauth-config:
preauth-data: preauth-data:
+849
View File
@@ -0,0 +1,849 @@
# Plan — Passkey Authentication for the Dedicated Auth Subdomain
**Status:** 📋 Draft for review — no application code written yet
**Target:** next minor release (version to confirm — see Q1.1)
**Prepared:** 2026-09-26 against `main` @ `0458d9b`
**Revised:** 2026-09-27 — review round 2 (D4/D5, §2.3)
**Verified against:** `web-auth/webauthn-lib` 5.3.9 on PHP 8.5.11 / Symfony 8.1
---
## 0. Decisions locked in (from review feedback)
Five clarifications from the project owner reshape this plan. They are
**decisions**, not options, and everything below follows from them.
| # | Decision | Consequence |
|---|---|---|
| **D1** | **Central auth (dedicated auth subdomain) is a hard prerequisite** for passkeys. Without it, a passkey would collide with / confuse the passkey for the protected service itself. | Passkeys are simply **not offered** unless `SUBDOMAIN_REDIRECT=true` *and* `AUTH_SUBDOMAIN` is set. The RP ID is *always* `authBase()`. There is no single-host passkey mode, no per-service RP ID, and no ambiguity to document away. |
| **D2** | **Registration happens in the browser**, initiated by a simple "register passkey" checkbox on the login form — not a CLI command. | Registration reuses the existing login form, nonce/CSRF machinery and TOTP verification. This also **answers the identity question**: the identity is the `Session ID` field the user already types, exactly as with TOTP. |
| **D3** | **Rate limiting covers all forms of login.** If an IP is rate-limited, that includes passkeys. | Passkey ceremonies run **behind** the existing `RejectListener` gate and consume the **same** login limiter budget on failure. No way to sidestep a lockout by switching methods. |
| **D4** | **HTTPS is required — in development too.** No "secured relying party" exemption is supported, deprecated or otherwise. | The derived allowed-origin is *always* `https://…`, built from config and never from the request. The `PASSKEY_ALLOWED_ORIGINS` escape hatch from the first draft is **deleted**. Local development uses real TLS (§4.2). HTTPS becomes part of the boot-time assertion alongside D1 (Q3.1). |
| **D5** | **Attestation is `none`, deliberately.** The "set a real value instead" instinct was tested and is wrong *here* — every alternative is either broken or bypassable (§2.3). | Records are anonymous: zero AAGUID, `EmptyTrustPath`. No metadata service, no `web-token/jwt-library` dependency, no download of the FIDO BLOB. `SECURITY.md` states the reasoning and the conditions that would change it. |
Consequences worth stating plainly:
- The separate `passkey_limiter`, `PASSKEY_ENABLED=false` default, and the whole
"should we support single-host passkeys?" question from the first draft are
**gone**. D1 removes the configuration matrix; D3 removes the second limiter.
- The first draft's §7 (CLI registration, enrolment tokens, `--identity`) is
**deleted**. D2 replaces it with a checkbox.
- D4 keeps D1 exactly as strict — HTTPS is an **additional** requirement, never a
relaxation. D5 is the one place where "use the stricter-sounding option" loses,
and §2.3 shows the measurements behind that.
---
## 1. Goal
Let a user authenticate with a passkey (Touch ID, Windows Hello, Android
biometrics, hardware security key) instead of typing a 6-digit TOTP code —
served from the dedicated auth subdomain, where one passkey unlocks every
service on the base domain.
TOTP and backup codes remain and are never removed (Q2.1).
---
## 2. What the spike proved
The first draft contained claims that had not been executed. They now have been:
the library was installed, and a script performed a **complete registration and
assertion ceremony with real ES256 cryptography**, plus the negative cases.
**Environment:** PHP 8.5.11, Composer 2.10.3, `web-auth/webauthn-lib` **5.3.9**.
Baseline suite green before and after install: **313 tests / 738 assertions**.
`composer audit`: *"No security vulnerability advisories found."*
`.ci/conformance.sh --profile=auth-gateway`: **all 35 checks pass**.
### 2.1 Confirmed correct
| Claim | Result |
|---|---|
| Installs on PHP 8.5 + Symfony 8.1 with no conflicts | ✅ resolves to 5.3.9; `lint:container`, `lint:yaml`, `lint:twig` all pass |
| Only needs `ext-json` + `ext-openssl` | ✅ (`ext-openssl` is present in every official PHP image, so `Dockerfile` needs **no** extension work) |
| No Symfony Security bundle, no Doctrine, no bundler | ✅ `CeremonyStepManagerFactory` + `Authenticator*ResponseValidator::create()` are pure; the `webauthn-symfony-bundle` is unnecessary |
| rpId `example.com` admits an origin on `auth.example.com` | ✅ assertion ACCEPTED |
| …and also on `app.example.com` with the *same* credential | ✅ ACCEPTED — one passkey across all subdomains, as designed |
| Credential is cryptographically bound to the rpId | ✅ a forged `rpIdHash` is rejected: *"rpId hash mismatch"* |
| An origin outside the allow-list is rejected | ✅ *"Invalid origin. Not in the list of allowed origins."* |
| Wrong origin / wrong challenge rejected | ✅ `AuthenticatorResponseVerificationException` in both cases |
| CSP `publickey-credentials-*` do **not** inherit `default-src` | ✅ confirmed in the CSP3 spec (§6.8.3 fallback list omits WebAuthn directives) — the CSP change in §5.5 is required |
| base64url credential IDs survive `makeCacheKey()` without collision | ✅ 200 000 random 32-byte IDs, zero collisions |
| `attestation: 'none'` yields an anonymous record | ✅ `attestationType="none"`, zero AAGUID, `EmptyTrustPath` (§2.3, config A) |
| Origin scheme can never be inferred from the request | ✅ the scheme comes from the single allow-list string; an `https://` entry rejects an `http://` origin (§4.2) |
| `localhost` cannot accidentally enable passkeys | ✅ `baseDomain('localhost') === null` ⇒ `authBase() === null` ⇒ D1 unsatisfied (§4.2) |
| `auth.localhost` *does* satisfy D1 | ✅ `authBase() === 'auth.localhost'` (§4.2) |
| No MDS ⇒ no `web-token/jwt-library` needed | ✅ `FidoAllianceCompliantMetadataService` throws unless the JWT library is present; not installed, and MDS is not used (D5) |
### 2.2 Corrections to the first draft (things that would have bitten us)
| # | First draft said | Reality | Impact |
|---|---|---|---|
| **C1** | "`CredentialRecord` is JSON-serializable, so it fits the no-database constraint." | It is a **plain class**, not `JsonSerializable`. Persistence goes through `WebauthnSerializerFactory` (a Symfony Serializer with ~25 custom normalizers). | The store must use that factory. `symfony/serializer`, `property-info`, `property-access` arrive as transitive deps — no extra work, but the store can't just `json_encode()`. |
| **C2** | (unstated) treat option objects as plain JSON | `json_encode($creationOptions)` **throws** `JsonException: Malformed UTF-8` — the challenge is raw binary. Options **must** be serialized by the same factory, which base64url-encodes binary fields. | Both the `begin` payload and the stored record go through one `SerializerInterface`. Caught immediately by the spike; would otherwise have been a runtime 500 on first test. |
| **C3** | "the package carries 3 published advisories" | `composer audit` against 5.3.9 reports **none**. | No remediation work; record the clean audit in the CHANGELOG. |
| **C4** | counter handling not mentioned | Counter replay raises `CounterException`, which can **mask** the real reason a verification failed. | Test helper must use an incrementing counter per ceremony, or negative tests give false passes (this actually happened during the spike and had to be fixed). |
| **C5** | "keep the library default" for the counter | The default requires a strictly *increasing* counter. Measured: stored `0`, reported `0` → `CounterException`. A synchronised passkey reports `0` forever, so **every** such credential fails on its **first** login — and only on real hardware, since a test helper that increments never reproduces it. | `PasskeyCounterChecker` accepts `>=` and rejects strictly backwards. Pinned by `PasskeyCounterCheckerTest`, including a test asserting the library default still rejects `0`/`0` so this reasoning is re-checked if the dependency is upgraded. |
| **C5** | separate `passkey_limiter` + `publicRateLimitCache`-style pool | Decision D3 makes it redundant for the *login* budget. | Drop it. One small limiter remains, for a different purpose (§5.4). |
### 2.3 Attestation: why `none`, measured rather than assumed
The review asked the right question — *"is there any downside to `null`, and if it
needs a note in `SECURITY.md`, shouldn't we set a real value?"* — so it was
tested instead of argued. Seven configurations were run against 5.3.9
(`spike_attestation.php`, `spike_att2.php`). Results are summarised, not
predicted:
| # | Configuration | Outcome | What the server actually learns |
|---|---|---|---|
| **A** | `attestation=none`, `fmt=none` | ✅ accepted | `attestationType="none"`, aaguid all-zero, `EmptyTrustPath`. **Nothing.** |
| **B** | `attestation=direct`, `fmt=packed` **self**, no MDS | ✅ accepted | A real AAGUID string — but no metadata to interpret it against, so it is untrusted and uninterpretable. |
| **C** | `attestation=direct`, `fmt=packed` **basic** (`x5c` cert), no MDS | ❌ **rejected** | *"The Metadata Statement Repository is mandatory when requesting attestation objects."* |
| **C2** | …same, MDS enabled, metadata **empty** | ❌ **rejected** | *"The Metadata Statement for the AAGUID … is missing."* This is the real cost of MDS: **every** authenticator must be known in advance. |
| **C3** | MDS enabled, but the client sends a **zero** AAGUID | ✅ **accepted** | *"Null AAGUID detected. Skipping metadata verification."* — **MDS is bypassable by design.** |
| **C4** | MDS enabled, `fmt=packed` **self** attestation, AAGUID **unknown** to MDS | ✅ **accepted** | `processSelfAttestation()` returns early when the AAGUID has no metadata entry, so **self attestation is never refused by MDS** — even a *known-unknown* device passes. |
| **D** | `attestation=direct` requested, client sends `fmt=none` | ✅ **accepted** | Asking for `direct` does **not** compel compliance — conveyance is a *preference*, so the RP cannot force it. |
Three conclusions follow, and they are the reason D5 is `none`:
1. **Attestation cannot be *enforced*, only *requested*.** Configuration D shows a
client answering a `direct` request with `none` and being accepted regardless.
Any policy that depends on the client cooperating is not a security control.
2. **MDS is bypassable two different ways.** C3 is the decisive row: a zero AAGUID
short-circuits metadata verification *before* the repository is ever consulted.
Since passkeys from Apple/Google/Windows deliberately send zero AAGUIDs, an
attacker can present the same shape and skip MDS entirely — while legitimate
users are unaffected. C4 closes the remaining door on the same conclusion: with
`fmt=packed` **self** attestation (the format a software/platform authenticator
can produce without any vendor certificate), `processSelfAttestation()` returns
early when the AAGUID has no metadata entry, so even a device that is *unknown*
to MDS is accepted. Taken together: an MDS deployment refuses honest
certificate-bearing authenticators that postdate its cached BLOB (C2), while
still admitting the bypassable and self-attested cases. That is the worst
combination — friction for legitimate users, no assurance gained.
3. **`none` is not a weaker version of the same check — it is the honest
description of reality.** The property that actually protects users is that the
credential is cryptographically bound to the RP ID and origin (§2.1), which
holds identically in every row above. Attestation answers *"which device model
is this?"* — a question this project does not need to answer, because it does
not run a device-allow-list policy.
**What a real value would actually cost**, for the record: `direct` requires the
metadata repository (C) — verified as a hard failure, not a warning — which means
`web-token/jwt-library`, `symfony/http-client`, a periodic download of the FIDO
Alliance BLOB, certificate-chain validation on every registration, and a new
failure mode where a legitimate new phone is **rejected at enrolment** because its
AAGUID postdates the cached BLOB. All of that to gain a bypassable signal.
> **Where to revisit this.** D5 is the right call *for a self-hosted
gateway that does not distinguish devices*. It stops being the right call if the
project ever wants to (a) refuse specific authenticator models, or (b) prove
enrolment happened on hardware rather than a synced passkey. Both would require
MDS **plus** a decision to reject zero AAGUIDs — which is why the reasoning is
recorded in `SECURITY.md` rather than left implicit in a constant.
---
## 3. The flow, end to end
### 3.1 First-time setup (D2 — in the browser)
```
Browser → https://app.example.com/dashboard
forward_auth → preauth (host=app.example.com) → InterceptListener
matchesAuth() && host !== auth subdomain
⇒ 303 https://auth.example.com/?return=https%3A%2F%2Fapp.example.com%2Fdashboard
Browser → https://auth.example.com/?return=…
┌──────────────────────────────────────────────────────┐
│ Pre-Authentication System │
│ │
│ Session ID: [ lyra ] │
│ Authentication Token:[ 123456 ] │
│ [x] Register this device as a passkey ← new │
│ [ Submit ] │
└──────────────────────────────────────────────────────┘
```
The checkbox only appears when passkeys are available (D1 satisfied) — see §4.
**Submission with the box ticked** becomes a three-step ceremony:
```
1. POST / (auth host), form fields username+totp+nonce+register=passkey
LoginListener → LoginManager verifies TOTP/backup code + nonce [unchanged]
↳ instead of issuing a session, it starts a REGISTRATION ceremony:
stores passkey_reg_<cid> → { challenge, identity, userHandle } (TTL 300s)
⇐ 200 JSON { register: { publicKey: <options>, ceremonyId: <cid> } }
2. Browser: navigator.credentials.create({ publicKey: options })
→ user approves with Touch ID / Windows Hello / security key
3. POST / (auth host) X-Preauth-Passkey: register-finish
body: { ceremonyId, credential: <attestation JSON> }
PasskeyListener → PasskeyManager verifies attestation against the stored
challenge; stores the credential under the identity from the record
⇐ 303 Location: <return url> + Set-Cookie: __Http-Domain-Preauth=…
```
The TOTP check in step 1 is what authorises registration. There is no separate
enrolment token, no CLI, and **no way to create a credential without already
holding a valid TOTP code** — which is exactly the security property the CLI
design was reaching for.
> **Implementation note — where the hand-off actually goes.**
> `LoginListener::onKernelRequest()` is a straight chain: it builds a `Payload`,
> calls `$this->loginManager->checkToken(...)`, and on a non-null response it
> does `$event->setResponse($response); return;` — on `null` it immediately
> scores a failure and consumes a rate-limit token. There is no "authenticated
> but do not issue a session" branch to hook.
>
> So the clean split is: `LoginListener` detects `register=passkey` in the POST
> body and marks the **`Payload`** with the intent; `LoginManager::checkToken()`
> verifies TOTP/backup-code **and the nonce** exactly as it does today, and only
> then, if the intent is set, delegates to the registration ceremony instead of
> issuing a session. That keeps the nonce/CSRF guarantee in the one place that
> already enforces it — the alternative (starting a ceremony from the listener
> before `checkToken` runs) would move nonce validation and would need care to
> avoid double-spending it.
### 3.2 Everyday login (assertion)
```
Browser → https://auth.example.com/?return=…
[ 🔑 Sign in with a passkey ] ← button, one tap
─────────── or use a code ───────────
Session ID: [ … ] Token: [ … ] [ Submit ]
Passkey button:
1. POST / X-Preauth-Passkey: login-begin
⇐ 200 JSON { publicKey: { challenge, rpId, allowCredentials[], … },
ceremonyId }
2. navigator.credentials.get({ publicKey })
3. POST / X-Preauth-Passkey: login-finish body: { ceremonyId, credential }
PasskeyManager verifies the assertion against the stored record
⇐ 303 + cookie, or 401 JSON { message, nonce }
```
No username is typed: the credential carries its own identity (stored at
registration). `allowCredentials` lists all registered credentials, so the OS
picker decides which device to use.
### 3.3 Listener priority (D3)
```
Priority Listener Action
──────── ───────────────────── ─────────────────────────────────────────
99 AcceptListener Valid cookie → 200 OK
88 AllowListener Valid IP session → 200 OK
84 PublicAccessListener Public path + rate limit → 200/429
77 RejectListener LOGIN RATE-LIMIT GATE → 418/429
70 PasskeyListener (new) WebAuthn ceremony → JSON
66 LoginListener TOTP / backup-code login
55 InterceptListener Fallback → redirect or login page
```
**Why 70 — after `RejectListener` and before `LoginListener`:**
- **After 77 (D3):** a rate-limited IP is refused *before* any ceremony can
start. Passkeys cannot be used to sidestep a lockout. This is the whole point
of the reviewer's third clarification, and it reverses the first draft.
- **Before 66:** essential. `LoginListener` treats *any* POST to the auth
subdomain as a login attempt (`$domainManager->getAuthSubdomain() === $host`).
A ceremony `finish` POST has no `username`/`totp`, so `Payload::load()` returns
`null` and the request would be scored as a **failed login and burn a rate-limit
token**. `PasskeyListener` must claim the request first.
`PasskeyListener` sets a response for *every* request carrying its header —
including malformed ones — so control never falls through to
`InterceptListener`, which would render HTML to a `fetch()` caller. (Q3.2)
---
## 4. Availability rule (D1 + D4)
Passkeys are offered **only** when all of these hold:
```php
$passkeysAvailable =
$config->passkeyEnabled() // PASSKEY_ENABLED=1 (default 0)
&& null !== $domainManager->authBase() // SUBDOMAIN_REDIRECT=1 && AUTH_SUBDOMAIN set
&& $domainManager->getAuthSubdomain() === $request->getHost(); // we are ON the auth host
```
…and, separately, the **deployment** must satisfy HTTPS (D4). That is checked
once at boot rather than per request, because "is this request HTTPS" is not the
right question behind a TLS-terminating proxy — see §4.2.
Consequences:
- **RP ID is always `authBase()`** — never the request host, never configurable
per-service. `example.com` for `auth.example.com`.
- **Allowed origins is exactly one entry**: `https://{AUTH_SUBDOMAIN}`, built
from config. Because `InterceptListener` funnels every unauthenticated user to
the auth host, no other origin ever needs to run a ceremony. This is the
tightest configuration that still delivers "one passkey, every service" (§2.1).
- On a protected host, `InterceptListener` already redirects before rendering a
login page, so the checkbox is naturally absent there.
- If someone sets `PASSKEY_ENABLED=1` without central auth, the app must
**fail loudly at boot**, not silently ignore it (Q3.1). A silent ignore is how
you get "I enrolled a passkey and now I can't log in" support tickets.
`rpName` for the OS prompt defaults to `TITLE`.
### 4.1 Identity and userHandle
The identity is the `Session ID` the user typed — the same value TOTP uses, so
`Remote-User` modes (`session`/`static`/`mapped`) keep working unchanged.
- `userHandle` = `hash('sha256', $identity, true)` (32 raw bytes). Fixed length,
stable per identity, and does not leak the label into the authenticator.
- On assertion, the identity is read from the **stored credential record**, not
from the client-returned `userHandle`. The client's copy is never trusted.
- Because registration is gated behind a successful TOTP login, one identity
cannot be registered by someone who does not already hold the TOTP secret.
### 4.2 HTTPS (D4) — enforced, not exempted
D4 removes the exemption system entirely: **there is no code path that accepts an
`http://` origin for passkeys**, and no configuration that re-enables one. The
library's `setSecuredRelyingPartyId()` (deprecated since 5.2, confirmed in
`CeremonyStepManagerFactory`) is **never called**.
Measured behaviour of the origin check (`spike_origin.php`), all with rpId
`example.com`:
| Allowed origins | Client origin | Result |
|---|---|---|
| `https://auth.example.com` | `https://auth.example.com` | ✅ accepted |
| `http://localhost:8000` | `http://localhost:8000` | ✅ accepted — **only** because `http://` was explicitly allow-listed |
| `localhost:8000` (host-only) | `http://localhost:8000` | ❌ rejected |
| `https://auth.example.com` | `http://auth.example.com` | ❌ rejected |
| `https://example.com` +subdomains | `https://app.example.com` | ✅ accepted |
| `https://example.com` +subdomains | `http://app.example.com` | ❌ rejected |
| `https://example.com` (no subdomains) | `https://app.example.com` | ❌ rejected — *"Subdomains are not allowed."* |
The scheme is therefore never inferred from the request; it comes from the single
`https://{AUTH_SUBDOMAIN}` string. Note the second row — the library *will* accept
plain HTTP **if the operator writes it into the allow-list**, which is precisely
the hole D4 closes by deleting `PASSKEY_ALLOWED_ORIGINS`.
**Two gotchas this creates for local development**, both verified against
`DomainManager` (`spike_devhost.php`):
1. `baseDomain('localhost')` returns **`null`** by design, so `authBase()` is also
`null` and **`localhost` can never satisfy D1** — passkeys stay off there no
matter what. `auth.localhost`, by contrast, resolves to `authBase()` of
`auth.localhost` and *does* satisfy D1.
2. Because the origin must be `https://`, dev cannot simply point a browser at
`http://auth.localhost`. The supported dev workflow is therefore **a local TLS
certificate**, not an exemption:
```
# Development with real TLS — the only supported way to exercise passkeys
AUTH_SUBDOMAIN=auth.preauthtest.local
SUBDOMAIN_REDIRECT=true
PASSKEY_ENABLED=1
# /etc/hosts → 127.0.0.1 auth.preauthtest.local app.preauthtest.local
# mkcert auth.preauthtest.local app.preauthtest.local
# Caddy terminates TLS with the mkcert cert and reverse_proxies to :80
```
This is a **documentation and CI** change, not an application-code change: the app
already sits behind a TLS-terminating proxy in production (`docker/Caddyfile`
serves plain HTTP on `:80`, `trusted_headers` includes `x-forwarded-proto`), so
D4 adds no runtime branching. `docs/examples/Caddyfile` gains a TLS-enabled
development block, and the functional tests (§7.2) drive the HTTPS origin directly
because they build `clientDataJSON` by hand — no real TLS needed in the suite.
> **Not `localhost`.** Because D4 forbids `http://`, the classic
> `http://localhost` dev story simply does not apply to passkeys. `localhost` is
> treated as *"passkeys unavailable"*, which keeps D1 intact instead of carving
> out an exception that would then need its own tests.
---
## 5. Design detail
### 5.1 `PasskeyManager` (new service)
Owns both ceremonies. Library types stay inside this class so a future v6 rename
touches one file.
```php
final readonly class PasskeyManager implements PasskeyInterface
{
public function beginLogin(Request $request): array; // → options + ceremonyId
public function finishLogin(array $body, Request $request): ?Response;
public function beginRegistration(string $identity, Request $request): array;
public function finishRegistration(array $body, Request $request): ?Response;
}
```
Built on the verified recipe:
```php
$attestationManager = AttestationStatementSupportManager::create();
$attestationManager->add(NoneAttestationStatementSupport::create()); // D5 (§2.3)
$csm = new CeremonyStepManagerFactory();
$csm->setAllowedOrigins(["https://{$domainManager->getAuthSubdomain()}"]);
$csm->setAlgorithmManager(AlgorithmManager::create()->add(ES256::create()));
$csm->setAttestationStatementSupportManager($attestationManager);
$attestationValidator = AuthenticatorAttestationResponseValidator::create($csm->creationCeremony());
$assertionValidator = AuthenticatorAssertionResponseValidator::create($csm->requestCeremony());
$serializer = (new WebauthnSerializerFactory($attestationManager))->create();
```
- `setSecuredRelyingPartyId()` is **deprecated in 5.2** (confirmed in the source,
`@deprecated since 5.2.0 … Use setAllowedOrigins instead`) — **never called
(D4)**. Development uses real TLS, not an exemption (§4.2).
- `attestation: 'none'` for registration **(D5, §2.3)**; no metadata service, so
neither `web-token/jwt-library` nor `symfony/http-client` is needed — the
latter confirmed absent from the current install, so reaching for MDS would add
a second new dependency, not just code.
- Counter: **replaced the library default** — see §2.2 C5. `ThrowExceptionIfInvalid`
requires a *strictly increasing* counter, which rejects a synchronised passkey
on its first login; `PasskeyCounterChecker` accepts equal-or-greater and still
rejects moves backwards. Clone detection is not relied upon. Test helpers must
still increment (C4).
### 5.2 Ceremony state
Stored in the **`nonceCache`** pool (already APCu, already excluded from
`kernel.reset` in `TestKernel`, already short-lived, and — correctly — *not*
persisted to disk, so ceremonies do not survive a restart):
```
passkey_cer_<ceremonyId> → { type: 'login'|'register',
challenge: <base64url>,
identity?: string, // register only
userHandle?: string, // register only
returnUrl?: string,
createdAt: <iso8601> } TTL 300s
```
- `ceremonyId` is a fresh 15-byte base64url string, issued to the client. The
client's copy of the challenge is **never** trusted; the server-side record is
authoritative.
- **Single-use**: deleted on read at `finish`, before verification, so a failed
or replayed assertion cannot be retried against the same challenge.
- TTL 300 s (5 min) rather than the nonce's 120 s, because a user has to
interact with a biometric prompt.
### 5.3 Credential store (new service)
```php
final readonly class PasskeyCredentialStore implements PasskeyCredentialStoreInterface
{
public function all(): array; // for allowCredentials
public function find(string $credentialId): ?array; // record + metadata
public function save(CredentialRecord $record, string $identity, string $label): void;
public function updateCounter(CredentialRecord $record): void;
public function remove(string $credentialId): bool;
public function count(): int;
}
```
Cache layout in **`sessionCache`** (the persisted pool):
```
passkey_cred_<makeCacheKey(credentialId)> → { record: <serialized CredentialRecord>,
identity: string,
label: string,
createdAt: iso8601,
lastUsedAt: iso8601|null }
passkey_index → { <credentialId>: {identity, label, createdAt}, … }
```
> ⚠️ **Verified gotcha.** `PersistCache::persist()` only flushes keys recorded by
> a `MonitorCacheKeys` instance, and it watches `sessionCache`. `LoginManager`
> and `BackupCodeManager` therefore each wrap their injected pool:
> `$this->sessionCache = new MonitorCacheKeys($sessionCache);`.
> `PasskeyCredentialStore` **must do the same**, or credentials live only in APCu
> and vanish on the next container restart — a bug that would surface only after
> a redeploy. Add an explicit test asserting the write is visible in the
> underlying persistent pool.
`passkey_index` avoids scanning the whole key space for the login page's
`allowCredentials` list.
### 5.4 Rate limiting (D3)
**No new limiter for the login budget.** Instead:
| Event | Limiter behaviour |
|---|---|
| Any request to the auth host, incl. `*-begin` | `RejectListener` (77) gates first — a blocked IP never reaches `PasskeyListener` |
| `login-finish` **failure** | consumes `login_limiter` (1 token) — identical to a wrong TOTP code |
| `register-finish` **failure** | consumes `login_limiter` |
| successful ceremony | consumes nothing |
| `*-begin` | not consumed (a legitimate login must not burn failure budget) |
This satisfies "if the login attempt has been rate limited, that would include
all forms of login": after 10 failures the IP is blocked for *every* method, and
failures from any method count toward the same 10.
To stop `begin`-spam from filling the cache with ceremony records, add **one**
small limiter that bounds *starts* only — it is a resource guard, not the auth
budget:
```yaml
passkey_begin_burst:
policy: 'sliding_window'
limit: '%env(int:PASSKEY_BEGIN_BURST_COUNT)%' # default 30
interval: '%env(int:PASSKEY_BEGIN_BURST_TIME)% seconds' # default 60
cache_pool: 'passkeyRateLimitCache'
```
plus a `passkeyRateLimitCache` pool (APCu in prod, array in test) and an entry in
`tests/TestKernel`'s reset-exclusion list. On over-limit, `begin` answers
`429` with `Retry-After`, matching `PublicAccessListener`. (Q3.6 asks whether this
guard is wanted at all.)
### 5.5 Response caching and CSP
**Caching.** `SecurityHeadersListener` sets `no-store` only on *non-2xx*
responses, on the assumption that 2xx is consumed by `forward_auth`. That is
false here: `begin` returns a **`200` JSON body straight to the browser**, and
the auth subdomain is `reverse_proxy`-ed with no `forward_auth` in front of it at
all. Ceremony responses must therefore be no-store too. Proposed: `PasskeyListener`
marks them with an internal `X-Preauth-Ceremony` header, and
`SecurityHeadersListener` turns that into the full no-store set and strips the
marker — keeping the caching policy in the one place that owns it. (Q3.7)
**CSP.** `publickey-credentials-get` / `publickey-credentials-create` do **not**
fall back to `default-src` (confirmed, §2.1), and the current policy is
`default-src 'none'`. When passkeys are available the policy becomes:
```
default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline';
connect-src 'self'; publickey-credentials-get 'self'; publickey-credentials-create 'self';
```
`connect-src 'self'` must be added **in both modes** — today it is added only for
the inline (non-auth-subdomain) case, but the passkey flow always uses `fetch()`.
When passkeys are unavailable the header is byte-identical to today.
### 5.6 Templates and script
| File | Purpose |
|---|---|
| `templates/_passkey.html.twig` | "Sign in with a passkey" button + `navigator.credentials.get()` handler |
| `templates/login.html.twig` | gains the checkbox (register) and includes the button, both only when available |
| `templates/_passkey_register.html.twig` | `navigator.credentials.create()` handler, driven by the JSON returned in step 1 of §3.1 |
`_script.html.twig` keeps its existing submit handler; ticking the checkbox
switches the submit into the registration branch. Kept as separate templates so
the "passkeys unavailable ⇒ byte-identical login page" property stays testable.
Base64url helpers must mirror the library's encoding exactly (no padding,
`-`/`_` alphabet); the spike's working script is the reference.
### 5.7 Configuration
| Variable | Default | Notes |
|---|---|---|
| `PASSKEY_ENABLED` | `0` | master switch; requires **D1 and D4** or the app fails at boot (Q3.1) |
| `PASSKEY_RP_NAME` | `%env(TITLE)%` | shown by the OS prompt |
| `PASSKEY_USER_VERIFICATION` | `required` | `required`/`preferred`/`discouraged` |
| `PASSKEY_TIMEOUT` | `60000` | ms, passed to the browser |
| `PASSKEY_BEGIN_BURST_COUNT` / `_TIME` | `30` / `60` | §5.4 resource guard |
| `PASSKEY_BUTTON_NAME` | `Sign in with a passkey` | styling-option family |
| `PASSKEY_REGISTER_NAME` | `Register this device as a passkey` | checkbox label |
> **Deleted by D4:** `PASSKEY_ALLOWED_ORIGINS`. The allowed origin is always
> derived as `https://{AUTH_SUBDOMAIN}` and there is no override — see §4.2.
Defaults preserve today's behaviour exactly.
---
## 6. Files
**New**
| File | Purpose |
|---|---|
| `src/Service/PasskeyManager.php` + `PasskeyInterface.php` | both ceremonies, library types contained |
| `src/Service/PasskeyCredentialStore.php` + interface | cache-backed records + index |
| `src/Listener/PasskeyListener.php` | priority 70, header dispatch, JSON |
| `templates/_passkey.html.twig` | login button + assertion script |
| `templates/_passkey_register.html.twig` | registration script |
| `tests/Support/PasskeyTestHelper.php` | ES256 generator, ceremony builder, incrementing counter (C4) |
| `tests/Unit/Service/PasskeyManagerTest.php` | ceremony control flow |
| `tests/Unit/Service/PasskeyCredentialStoreTest.php` | storage, index, persistence, key collisions |
| `tests/Unit/Listener/PasskeyListenerTest.php` | every branch |
| `tests/Functional/PasskeyFlowTest.php` | real crypto end-to-end (§7.2) |
**Changed**
| File | Change |
|---|---|
| `composer.json` / `composer.lock` / `symfony.lock` | `web-auth/webauthn-lib: ^5.3` (done on the spike branch) |
| `phpunit.dist.xml` | recipe-added `doctrine/deprecations` triggers (spike artefact — keep) |
| `config/packages/property_info.yaml` | recipe-added (spike artefact — keep) |
| `config/services.yaml` | `app.passkey_*` parameters |
| `config/packages/rate_limiter.yaml` | `passkey_begin_burst` |
| `config/packages/cache.yaml` + `test/cache.yaml` | `passkeyRateLimitCache` |
| `config/packages/twig.yaml` | passkey globals |
| `src/ConfigBag.php` | `passkeyEnabled()`, `rpName()`, `userVerification()`, `timeout()`, labels |
| `src/Kernel.php` or a compiler pass | boot-time check that **D1 and D4** hold when enabled (Q3.1, §4.2) |
| `src/Listener/SecurityHeadersListener.php` | CSP additions; ceremony no-store marker |
| `src/Listener/LoginListener.php` | detect `register=passkey` on the POST and mark the `Payload` with the intent (see §3.1 note) |
| `src/Service/LoginManager.php` | on success-with-intent, delegate to the registration ceremony instead of issuing a session; extract the session-issuing tail (Q3.8) |
| `templates/login.html.twig` | checkbox + button |
| `tests/TestKernel.php` | `passkeyRateLimitCache` in the reset-exclusion list |
| `tests/Support/ListenerTestHelper.php` | passkey limiter factory |
| `.env.test`, `docs/examples/.env.example`, `docs/examples/Caddyfile`, `docs/examples/compose.yaml` | config + docs; **TLS dev block** (§4.2) |
| `readme.md`, `CHANGELOG.md`, `ROADMAP.md`, `SECURITY.md`, `DESIGN_CONSIDERATIONS.md` | §9 |
---
## 7. Testing
### 7.1 Reusing the spike
`tests/Support/PasskeyTestHelper.php` is the spike's working code, refactored:
ES256 keypair → COSE key → `authenticatorData` → sign → JSON. Two rules learned
the hard way:
- **Increment the counter every ceremony** (C4), or a negative test can pass for
the wrong reason (`CounterException` masking the real failure).
- **Serialise options through `WebauthnSerializerFactory`**, never `json_encode` (C2).
### 7.2 Cases
| Case | Expected |
|---|---|
| Register on `auth.example.com` (rpId `example.com`), then assert from the same host | ✅ 303, `__Http-Domain-Preauth`, `Domain=example.com`, `Remote-User` |
| Assert the same credential from `app.example.com` | ✅ success by design — asserted explicitly so the scope is documented in code |
| Register while `PASSKEY_ENABLED=0` / without central auth | ❌ checkbox absent; `begin` inert; no cache writes |
| Registration submitted with a **bad TOTP** | ❌ 401, no ceremony started, login limiter consumed |
| Registration with a **spent nonce** | ❌ 401, no ceremony |
| `begin` from a rate-limited IP | ❌ 418/429 from `RejectListener`, never reaches passkey code |
| Failed assertion | ❌ 401, **login limiter consumed** (D3) |
| Failed assertion × N, then a correct TOTP | ❌ still blocked — shared budget |
| Assertion replayed with the same `ceremonyId` | ❌ 401 (record deleted on read) |
| Unknown `credentialId` | ❌ 401, same generic message as a bad TOTP (no enumeration) |
| Origin not in the allow-list | ❌ 401 (`Invalid origin…`) |
| **`http://` origin with the derived `https://` allow-list** | ❌ 401 — D4; asserted explicitly so the exemption cannot creep back |
| **`PASSKEY_ALLOWED_ORIGINS` is not consulted** | ❌ setting it has no effect (D4) |
| **`PASSKEY_ENABLED=1` with `AUTH_SUBDOMAIN=localhost`** | ❌ boot failure — D1 unsatisfiable (§4.2) |
| **`PASSKEY_ENABLED=1` on plain HTTP deployment** | ❌ boot failure — D4 (Q3.1) |
| Forged `rpIdHash` | ❌ 401 (`rpId hash mismatch`) |
| Zero AAGUID / self attestation payload | ✅ accepted exactly as a `none` record would be — documents D5's reasoning in code |
| Ceremony responses | ✅ full no-store header set |
| Login page when passkeys unavailable | ✅ byte-identical to today |
| Persistence | ✅ a saved credential is present in the **persistent** pool, not just APCu |
| `begin` spam | ✅ bounded by `passkey_begin_burst` |
### 7.3 Gates
Baseline to preserve: **313 tests / 738 assertions**, 100 % line/method/class
coverage, `phpstan` level 6 clean, `php-cs-fixer` clean, `composer audit` clean,
conformance 35/35. Note `phpunit.dist.xml` runs with `failOnDeprecation=true`, so
deprecations from the new dependency must be watched (the recipe already added
the `doctrine/deprecations` triggers).
---
## 8. Implementation order
**Status: complete.** All steps below are implemented and on
`feat/passkey-auth-subdomain`. Two deviations from the order as written, both
noted inline.
Each step is independently committable and leaves the suite green.
1. **Dependency** *(done on the spike branch)* — `composer require
web-auth/webauthn-lib`; suite + lints + audit + conformance verified.
2. **Availability + config** — `ConfigBag` accessors, `services.yaml`, boot-time
**D1 + D4** assertion, Twig globals, test env. Feature fully inert; assert the
login page is unchanged. Includes the TLS development setup in
`docs/examples/` (§4.2), so contributors can exercise the feature locally.
3. **Credential store** — with `MonitorCacheKeys` wrapping and the persistence
test. No WebAuthn types needed yet (`CredentialRecord` can be stubbed).
4. **`PasskeyManager`** — both ceremonies, ceremony state, single-use deletion,
limiter consumption on failure. Unit-tested with a stubbed validator.
5. **`PasskeyListener`** — priority 70, header dispatch, always terminate,
no-store marker. Unit-test every branch incl. "post-shaped request must not
reach `LoginListener`".
> **Deviation 1 — done after step 6.** The listener needs the shared session
> issuing that step 6 extracts, so the order had to be inverted.
>
> **Deviation 2 — three operations, not four.** `register-begin` is not a
> listener operation, and the first implementation was wrong to make it one.
> It would have handed out a challenge without proving anything; there is
> also no session cookie to check at that point, since the whole flow is what
> produces the session. The ceremony is started by `LoginManager`, after it
> verifies the code and nonce. A test pins that the listener refuses the
> operation.
6. **Extract session issuing** from `LoginManager` so both paths share it —
prove equality against the existing `LoginManagerTest`/`AuthenticationFlowTest`
before touching anything else (Q3.8).
> Verified as intended: all 18 existing `LoginManagerTest` cases passed
> unchanged, and a functional test now compares the two paths' cookies
> field by field.
7. **Registration UI** — checkbox in `login.html.twig`, the `Payload`-intent
hand-off described in §3.1, `_passkey_register.html.twig`.
> Note: the separate script template was not needed — both handlers share
> helpers, so `_passkey.html.twig` holds them and `login.html.twig` stays a
> single readable file. The checkbox is also **not** rendered where the form
> does not POST, since registration authorises itself with the code carried
> in that submission.
8. **Login UI + CSP** — `_passkey.html.twig`, `SecurityHeadersListener`, extend
`CacheControlFlowTest` and `SecurityHeadersListenerTest`.
9. **Functional tests** with real crypto (§7.2).
10. **Docs** (§9) and **final gates**, then PR to `main`.
---
## 9. Documentation
| File | Update |
|---|---|
| `readme.md` | "Passkey Authentication" section: **the central-auth prerequisite**, **the HTTPS requirement (development included)**, enabling, the checkbox, the passkey button, RP ID, fallbacks |
| `CHANGELOG.md` | `[Unreleased]` `Added`/`Security`; record library 5.3.9 and the clean audit |
| `ROADMAP.md` | Phase 2c done, noting the deviations from the original sketch (browser registration, no bundle, D1/D3/D4/D5) |
| `SECURITY.md` | ceremony model, challenge TTL/one-shot, RP ID scope, **the D5 attestation rationale and the conditions that would reverse it (§2.3)**, HTTPS-only origins, counter caveat, shared rate-limit budget |
| `DESIGN_CONSIDERATIONS.md` | the 2xx-caching gap; `CredentialRecord` serialization; the shared-limiter decision; **why attestation was deliberately declined** |
| `docs/examples/.env.example` | new variables; **note that `PASSKEY_ALLOWED_ORIGINS` does not exist by design** |
| `docs/examples/Caddyfile` | auth-subdomain block already `reverse_proxy`-ed; **add a TLS-enabled development block (§4.2)** and note why the plain-HTTP shortcut is not offered |
---
## 10. Risks
| # | Risk | Mitigation |
|---|---|---|
| R1 | RP ID / origin misconfiguration | D1 removes the matrix: RP ID is always `authBase()`, origins is always the auth host. Asserted by tests. |
| R2 | Ceremony responses cached (first browser-facing 2xx) | §5.5 marker + `CacheControlFlowTest` cases |
| R3 | CSP blocks the ceremony | §5.5 directives; verify in a real browser during staging (Q3.9) |
| R4 | Library churn (v5 renamed types; `setSecuredRelyingPartyId` deprecated) | pin `^5.3`; library types contained in `PasskeyManager`; avoid deprecated calls |
| R5 | Credential loss on restart | `MonitorCacheKeys` wrap + explicit persistence test (§5.3) |
| R6 | Non-technical users lose their passkey device | TOTP/backup codes unchanged and always available; the checkbox is opt-in |
| R7 | `begin` cache-fill | §5.4 resource guard |
| R8 | New transitive deps (`symfony/serializer`, `property-info`) | already installed as part of the spike; container lint passes |
| R9 | **A deployment enables passkeys without TLS, and the feature silently half-works** | D4 + the extended boot assertion (§4.2, Q3.1): `PASSKEY_ENABLED=1` in a non-HTTPS configuration **fails at `cache:warmup`** instead of failing later in the browser |
| R10 | **"We should verify the device" creeps back in as a requirement** | §2.3 records the measurements and the two conditions that would justify revisiting; a functional test asserts a zero-AAGUID payload is handled deliberately, so any change is a visible, reviewed diff |
---
## 11. Remaining open questions
D1–D5 removed most of the first draft's 22 questions. These are what is left;
each has a proposal, so "yes" is a valid answer.
**Q1.1 — Version target.** `CHANGELOG.md`'s `[Unreleased]` heading still says
v1.1 while git tags reach `v1.3.0`. Target the next minor and repair the heading
in a separate labelled commit? *Proposal: yes.*
**Q1.2 — Where the checkbox appears.** *Proposal: always visible when passkeys
are available (same as the login button), since a user who has just landed on
the auth page is exactly the person most likely to be enrolling a new device.*
**Q1.3 — What if the same device registers twice** (same identity, second
passkey)? *Proposal: allow it — the OS may legitimately create a second
credential, and `excludeCredentials` will let the authenticator dedupe. `Q2.6`
of the first draft (a cap) becomes: cap at a configurable N (default 20).*
**Q2.1 — Re-confirm: TOTP stays?** *Proposal: yes, unchanged, and never
disabled by enabling passkeys.*
**Q3.1 — How to enforce the D1 prerequisite.** Boot-time hard failure when
`PASSKEY_ENABLED=1` without central auth, or log a warning and disable?
*Proposal: **hard failure** at container start (`cache:warmup`) — a silent
disable is how you get "my passkey stopped working" tickets.* **Extended by D4:**
the same boot check also asserts HTTPS, so "enabled but unusable" cannot ship.
The check is on **configuration**, not on the request, because behind a TLS
terminating proxy `isSecure()` is not authoritative (§4.2).
**Q3.2 — Always terminate a ceremony with JSON?** *Proposal: yes — any request
carrying `X-Preauth-Passkey` gets a JSON response, never the HTML login page.*
**Q3.3 — Attestation policy.** **RESOLVED — D5: `none`.** Measured, not assumed:
`direct` cannot be enforced (config D), MDS is bypassable by the zero AAGUIDs that
real passkeys send (config C3), and requiring MDS would reject legitimate new
authenticators (config C2) while adding two dependencies. Full evidence and the
conditions that would reverse it are in **§2.3**. *Set a real value instead*
was considered and rejected on the evidence.
**Q3.4 — Local development over HTTP.** **RESOLVED — D4: not supported.** No
`securedRelyingPartyId` exemption, deprecated or otherwise; local development uses
real TLS with a local certificate (§4.2). `PASSKEY_ALLOWED_ORIGINS` is deleted.
Note `localhost` deliberately cannot satisfy D1, so there is no half-configured
state to document away.
**Q3.5 — Counter checking.** **Resolved during implementation: the proposal was
wrong and was reversed.** The assumption "many passkeys always report 0" was
correct, but the conclusion "so the default is harmless" was not — the default
*rejects* a reported 0 against a stored 0, so the very case it was assumed to
tolerate is the case it fails. Replaced with `PasskeyCounterChecker` (accept
`>=`, reject strictly backwards). See §2.2 C5.
**Q3.6 — Keep the `begin` resource guard?** It is not part of the login budget
(D3 governs that) — it only bounds cache-fill. *Proposal: keep it; it is ~15
lines and mirrors the existing `public_limiter` pattern.*
**Q3.7 — Caching-policy mechanism.** `X-Preauth-Ceremony` marker header consumed
by `SecurityHeadersListener` (keeps cache policy in one place), or set headers
directly in `PasskeyListener`? *Proposal: the marker.*
**Q3.8 — Extract the session-issuing tail from `LoginManager`?** *Proposal: yes,
as its own commit — duplicating cookie/redirect/`Remote-User` logic is how the
two paths drift.*
**Q3.9 — Browser matrix.** Which browsers must be verified by hand on staging
(iOS Safari, Chrome, Firefox, and a hardware key) before release? *Proposal: all
four; note the CSP directive is the most likely divergence.*
---
### Resolved in this round
| Question | Resolution |
|---|---|
| Q3.3 — attestation value | **D5: `none`**, with measurements in §2.3 |
| Q3.4 — dev over HTTP | **D4: real TLS only**; `PASSKEY_ALLOWED_ORIGINS` deleted (§4.2) |
| Q3.1 — boot check scope | extended to assert **D1 *and* D4** |
---
## 12. Rollback
- `PASSKEY_ENABLED=0` (the default) makes the feature inert; reverting is
redeploying the previous image tag. No migrations.
- If passkeys were enabled and are rolled back, credential records remain in
`sessionCache`/filesystem under `passkey_*` keys, unread by the old code.
Sessions continue to work; nothing is invalidated.
- The dependency addition reverts with `composer.lock`.
---
## 13. Notes for the reviewer
- **Round 2 added D4 (HTTPS required, no exemptions) and D5 (attestation stays
`none`, on measured evidence).** D4 is covered in §4.2, D5 in §2.3; the two
questions that drove them are marked resolved in §11.
- Three claims in this revision were **measured, not reasoned**: the attestation
matrix (§2.3), the origin/HTTPS behaviour (§4.2), and the `localhost` × D1
interaction (§4.2). Scripts: `spike_attestation.php`, `spike_att2.php`,
`spike_origin.php`, `spike_devhost.php`.
- Incidentally confirmed while testing: `symfony/http-client` is **not** in the
current install, so MDS would have been a second new dependency, not a drop-in.
- The spike branch (`spike/passkey-deps`) currently carries `composer.json`,
`composer.lock`, `symfony.lock`, `phpunit.dist.xml` and
`config/packages/property_info.yaml` changes. Decide whether step 2 continues
on that branch or starts fresh from `main`.
- The spike scripts themselves were **removed** from the working tree (kept in
`/tmp/spike-backup/` for reference) so they never reach a PR; the reusable
parts are folded into `tests/Support/PasskeyTestHelper.php` in step 9.
- The environment details (PHP 8.5.11 via Sury, Composer, `pcov`) are local to
this container and are not a project change.
---
*End of plan.*
+229
View File
@@ -0,0 +1,229 @@
# Upgrade Plan: Symfony 7.4 → 8.1
**Status:** ✅ Implemented on branch `feat/symfony-8.1-upgrade-plan`
(Phases 0–3 & state audit complete; Phases 4–5 = staging + release)
**Target:** Symfony `8.1.*` (all symfony components)
**Was:** Symfony `7.4.*` → **resolved 8.1.2–8.1.6**
**Prepared:** 2026-09-07
---
## Implementation results
| Phase | Result |
|-------|--------|
| 0 Deprecation sweep | ✅ Clean — suite runs with `failOnDeprecation=true`, zero hits on 7.4; the 8.x jump needed **no app code changes**. |
| 1 Composer bump | ✅ `runtime/frankenphp-symfony` removed, `extra.runtime` deleted, all `symfony/*` at `8.1.*` (framework-bundle 8.1.6, twig-bundle 8.1.2); ride-alongs PHPUnit 13.3.2, Twig 3.28, otphp 11.5. Boots on **v8.1.6**. |
| 2 Config refresh | ✅ `config/reference.php` is gitignored, auto-regenerated by Flex. Prod `cache:clear`+`cache:warmup`, `lint:container`/`lint:yaml`/`lint:twig` all pass. |
| 3 Tests | ✅ **295 tests / 612 assertions green** on 8.1; php-cs-fixer 0 fixable files. |
| State audit | ✅ All `src/` services are `final readonly` with ctor-injected deps — no mutable state, kernel reuse under `FrankenPhpWorkerRunner` is safe. |
| Loop-max parity | ✅ `Caddyfile` sets `max_requests {$MAX_REQUESTS}`; default **500** baked into the image via Docker build arg (matches old package default), runtime-overridable. See §2 note. |
Phases 4–5 (staging smoke + release) are pending — everything else in
this document describes what was planned **and is now done**.
---
## 1. Why we can leapfrog 8.0
Symfony 7.4 and 8.0 were released simultaneously (Nov 2025) and are
feature-identical — 8.0 is simply 7.4 with the deprecated code removed.
Because preauth is **already on 7.4**, we are on the last LTS bridge
release. The only gating question for 8.x is whether we still trigger
any deprecations. If `composer test` runs clean under 7.4 with
`SYMFONY_DEPRECATIONS_HELPER` strict, upgrading straight to 8.1 is safe
and avoids a double-bump of `composer.json` / `composer.lock`.
Symfony 8.1 (May 2026 cycle) also brings a runtime improvement we
directly benefit from (see §3).
Prerequisites:
- ✅ PHP: Symfony 8.x requires PHP **>= 8.4**; composer.json already
requires `>= 8.4`, Docker and CI run 8.5. No PHP work needed.
- ⚠️ Deprecations: must be inventoried and fixed before the version bump
(see Phase 0).
## 2. The `runtime/frankenphp-symfony` removal
We currently use the community runtime package for FrankenPHP worker
mode, wired in two places in `composer.json`:
```json
"require": {
"runtime/frankenphp-symfony": "^1.0.0",
},
"extra": {
"runtime": {
"class": "Runtime\\FrankenPhpSymfony\\Runtime"
},
}
```
As of Symfony 7.4+, `symfony/runtime` ships its own
`Symfony\Component\Runtime\Runner\FrankenPhpWorkerRunner`, and **in 8.1
the runtime handles FrankenPHP worker mode natively** (including new
8.1 support for returning a `Response` from worker mode). The
community package is redundant.
**Actions:**
1. `composer remove runtime/frankenphp-symfony` (as part of the 8.1 bump
in §4 — do it in the same `composer update` to keep one lockfile diff).
2. Delete the entire `extra.runtime` block from `composer.json` so the
default `Symfony\Component\Runtime\GenericRuntime` is used; the
built-in `FrankenPhpWorkerRunner` is auto-selected when
`frankenphp_handle_request()` exists (i.e. inside FrankenPHP worker
mode). Falling back to plain `APP_RUNTIME=Symfony\...\Runtime` env
override is possible but should not be needed.
3. Verify `symfony.lock` — Flex should drop the
`runtime/frankenphp-symfony` entry automatically on removal.
4. `public/index.php` needs **no change** — it already just returns the
Kernel closure via `autoload_runtime.php`.
**Note on loop_max:** the old package exposed
`FRANKENPHP_LOOP_MAX` (default 500). The built-in runner does not
read that env var. We never set it, so behavior is unchanged — but
check staging memory usage under worker mode and, if ever needed,
control restarts via FrankenPHP's own `worker ... num N` / max-requests
options in the Caddyfile instead.
## 3. composer.json changes
### `require`
| Package | From | To |
|--------------------------|------------|---------|
| `symfony/cache` | `7.4.*` | `8.1.*` |
| `symfony/console` | `7.4.*` | `8.1.*` |
| `symfony/framework-bundle`| `7.4.*` | `8.1.*` |
| `symfony/mime` | `7.4.*` | `8.1.*` |
| `symfony/rate-limiter` | `7.4.*` | `8.1.*` |
| `symfony/runtime` | `7.4.*` | `8.1.*` |
| `symfony/twig-bundle` | `7.4.*` | `8.1.*` |
| `symfony/uid` | `7.4.*` | `8.1.*` |
| `symfony/yaml` | `7.4.*` | `8.1.*` |
| ~~`runtime/frankenphp-symfony`~~ | `^1.0.0` | **removed** |
`symfony/flex` (`^2.11`), `bacon/bacon-qr-code` (^3) and
`spomky-labs/otphp` (^11) are compatible with 8.x — no change expected,
but let composer confirm during the update.
### `require-dev`
| Package | From | To |
|--------------------------|---------|---------|
| `symfony/browser-kit` | `7.4.*` | `8.1.*` |
| `symfony/css-selector` | `7.4.*` | `8.1.*` |
`phpunit/phpunit ^13.2` and `friendsofphp/php-cs-fixer` already support
PHP 8.5 / Symfony 8.
### `extra`
```diff
"extra": {
- "runtime": {
- "class": "Runtime\\FrankenPhpSymfony\\Runtime"
- },
"symfony": {
"allow-contrib": false,
- "require": "7.4.*"
+ "require": "8.1.*"
}
}
```
### One-shot command
```bash
composer update \
"symfony/*" \
--with-all-dependencies
# plus explicit remove of runtime/frankenphp-symfony beforehand
```
(Or edit composer.json, then `composer update` wholesale — the repo has
few non-Symfony deps, so a full update is low-risk.)
## 4. Config / recipes to re-sync
After the bump, run `composer recipes:update` (or
`symfony console recipes:update`) and review diffs for:
- `symfony/framework-bundle` — check `config/packages/framework.yaml`
for new/changed defaults (session, cache, http_method_override, etc.).
Our `config/reference.php` dump is generated from 7.4 config; it
**must be regenerated** after upgrade
(`bin/console config:dump-reference` equivalents) or it will document
stale defaults.
- `symfony/twig-bundle`, `symfony/rate-limiter` — verify
`config/packages/*.yaml` against new reference defaults.
- `symfony/runtime` — new recipe may update `public/index.php`; accept
only if it's a no-op for our shape.
Also review `bundles.php` (only Framework + Twig today — no removals
expected in 8.x) and `config/preload.php`.
## 5. Code-level risk review
Preauth deliberately avoids the Security component (custom listeners +
`ConfigBag`), which removes the biggest 8.0 BC-break surface
(`security.yaml` reshaping, authenticator changes). Remaining surface:
- **Listeners** (`src/Listener/*`): built on HttpKernel events — stable
API, but `KernelEvents` signatures gained native types in 8.0; our
listeners already declare types, verify covariance after upgrade.
- **`Kernel.php`**: confirm no overridden methods whose signatures
changed in 8.0 (MicroKernelTrait is stable; likely no-op).
- **`symfony/console`** (GenerateBackupCodesCommand): 8.0 removed
command `setName()`/aliases-in-constructor legacy paths — we use
`#[AsCommand]`, fine. `Command::execute()` must return `int` — verify.
- **`spomky-labs/otphp`** and **`bacon/bacon-qr-code`**: third-party;
confirm versions resolved are marked Symfony-8 compatible.
- **PHPUnit 13**: no changes needed, but watch for deprecations printed
after the Symfony bump (new `trigger_deprecation` calls in 8.1).
Canonical checklist: read `symfony/symfony` **UPGRADE-8.0.md** and
**UPGRADE-8.1.md** sections for the components we require
(cache, console, framework-bundle, mime, rate-limiter, runtime,
twig-bundle, uid, yaml) and tick each item against this codebase.
## 6. Docker / CI
- `Dockerfile`: no base-image change needed
(`dunglas/frankenphp:php8.5-trixie` + `php:8.5-trixie` builder).
Rebuild after composer.lock update; remove nothing — FrankenPHP itself
stays.
- `Caddyfile`: unchanged (worker mode config is FrankenPHP-side, not
runtime-package-side).
- `.gitea/workflows/tests.yaml`: PHP 8.5 already — unchanged.
- `composer dump-env prod --empty` step stays.
## 7. Rollout plan
| Phase | Step | Exit criteria |
|-------|------|---------------|
| 0 | **Deprecation sweep on 7.4**: run `SYMFONY_DEPRECATIONS_HELPER=max[total]=0 composer test` (or phpunit directly) + run the app in dev with the profiler/log; fix every direct deprecation. | Zero deprecations from `App\` code; only acceptable vendor ones documented. |
| 1 | **composer bump**: branch `feat/symfony-8.1`; edit composer.json per §3–§4; `composer remove runtime/frankenphp-symfony`; `composer update`; re-sync recipes. | Installs clean on PHP 8.5; `bin/console about` shows 8.1.x. |
| 2 | **Config refresh**: regenerate `config/reference.php`; review framework/twig/rate-limiter defaults; commit config changes. | `cache:clear` + warmup pass in dev & prod envs. |
| 3 | **Tests**: full phpunit suite + php-cs-fixer; fix failures (expected: minor — event/type related). | Suite green in CI. |
| 4 | **Staging smoke**: build image, run under FrankenPHP worker mode; verify TOTP login flow, backup codes, rate limiting (burst + teapot mode), public paths, central-auth subdomain flow; watch memory across >500 requests to confirm threads recycle via the Caddyfile `max_requests` setting (see §2 note). | No state leaks across worker requests; worker threads recycle at the configured request count; healthcheck passes. |
| 5 | **Docs + release**: update readme/DESIGN_CONSIDERATIONS ("symfony 8.1, built-in FrankenPHP runtime"); tag a minor release per CHANGELOG conventions. | Release published; image rebuilt & pushed. |
**Rollback:** the upgrade is a single composer.lock + config diff.
Rollback = `git revert` the bump commit + redeploy previous image tag.
No data/schema migrations are involved (no database).
## 8. Open questions — resolved during implementation
- [x] ~~Confirm none of our listeners/services relied on implicit behavior
of `Runtime\FrankenPhpSymfony\Runner`.~~ **Resolved:** audited every
class in `src/` — all are `final readonly` with constructor-injected
dependencies and no mutable state. No `ResetInterface` needed; kernel
reuse across worker requests is safe.
- [x] ~~Decide whether to pin `symfony/*` as `8.1.*` or `^8.1`.~~
**Resolved:** kept minor-pinned `8.1.*`, matching repo convention.
- [x] ~~Regenerate `config/reference.php` — scripted or manual dump?~~
**Resolved:** it's gitignored and auto-regenerated by Flex on
`composer update`; already refreshed for 8.1 during the bump.
+340
View File
@@ -0,0 +1,340 @@
# v1.1 Plan — Public Rate-Limited Access
## Goal
Allow preauth to provide rate-limited unauthenticated access to select
public paths. Authenticated users bypass the public rate limiter entirely.
Non-public paths continue to trigger the existing auth flow.
**Practical example:** Allow anyone to visit
`https://code.devgnome.com/public/*` in Gitea, but limit them to 100
requests/minute and 500 requests/hour per IP.
---
## How It Works
When a request arrives and the user is **not authenticated** (no valid
cookie or IP session), the new `PublicAccessListener` checks whether the
request path matches any configured public path pattern. If it does:
1. The public rate limiter is consulted (separate from the login limiter).
2. If within limits → `200 OK` (no `Remote-User` header). Caddy proxies
to the backend.
3. If over limits → `429 Too Many Requests` with a `Retry-After` header.
If the path does **not** match any public pattern, the request falls
through to the existing auth flow (RejectListener → LoginListener →
InterceptListener → login page or redirect).
**Authenticated users** never reach the `PublicAccessListener` because
`AcceptListener` (priority 99) or `AllowListener` (priority 88) will have
already set a `200` response before `PublicAccessListener` runs.
### Listener Priority Chain (updated)
```
Priority Listener Action
──────── ───────────────── ──────────────────────────────────────
99 AcceptListener Valid cookie → 200 OK
88 AllowListener Valid IP session → 200 OK
84 PublicAccessListener Public path + rate limit check → 200 or 429
77 RejectListener Login rate-limit gate → 418/429
66 LoginListener Login attempt handling
55 InterceptListener Fallback → redirect or login page
```
`PublicAccessListener` runs at priority 84 — after auth checks (so
authenticated users bypass it) but before `RejectListener` (so public
access is not subject to the login rate limiter).
---
## Configuration
### Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `PUBLIC_PATHS` | `''` (disabled) | Comma-separated path patterns. Wildcard `*` supported. |
| `PUBLIC_BURST_COUNT` | `100` | Max requests per burst window per IP |
| `PUBLIC_BURST_TIME` | `60` | Burst window in seconds |
| `PUBLIC_UPPER_COUNT` | `500` | Max requests per sustained window per IP |
| `PUBLIC_UPPER_TIME` | `3600` | Sustained window in seconds (1 hour) |
**When `PUBLIC_PATHS` is empty (default), the feature is completely
disabled and has zero effect on existing behavior.**
### Path Pattern Syntax
- Patterns are matched against the request **path** only (query string
is ignored).
- Patterns must start with `/`.
- `*` matches any sequence of characters within a single path segment
(not crossing `/`).
- `**` matches any sequence of characters including `/` (crosses path
segments).
- No other regex or special characters are supported — patterns are
literal strings with `*` wildcards.
**Examples:**
| Pattern | Matches | Does NOT match |
|---------|---------|----------------|
| `/public` | `/public` | `/public/`, `/public/xyz` |
| `/public/*` | `/public/anything`, `/public/xyz` | `/public`, `/public/a/b` |
| `/public/**` | `/public/anything`, `/public/a/b/c` | `/public` |
| `/public` | `/public` | `/public/xyz` |
| `/api/*/status` | `/api/v1/status`, `/api/v2/status` | `/api/v1/v2/status` |
### Domain-Scoped Paths (when using auth subdomain)
When `SUBDOMAIN_REDIRECT=true` and `AUTH_SUBDOMAIN` is set, the user may
want public paths on specific subdomains only. In this case, `PUBLIC_PATHS`
can optionally include a domain prefix:
```
PUBLIC_PATHS='code.devgnome.com/public/**,auth.devgnome.com/health'
```
When no domain prefix is given, the path matches on **any** host. When a
domain prefix is given, it only matches on that specific host.
When **not** using an auth subdomain (the common case), paths without a
domain prefix match on all hosts. Domain-prefixed entries can still be
used to restrict to specific hosts.
### Rate Limiter
A new `public_limiter` compound rate limiter is added to
`rate_limiter.yaml`, following the same pattern as the existing
`login_limiter`. It uses a `publicRateLimitCache` pool (APCu in
production, array adapter in tests).
---
## New Files
| File | Purpose |
|------|---------|
| `src/Service/PublicPathMatcher.php` | Service that parses `PUBLIC_PATHS` and matches request paths against patterns |
| `src/Service/PublicPathMatcherInterface.php` | Interface for testability |
| `src/Listener/PublicAccessListener.php` | Listener that checks public paths and applies rate limiting |
## Modified Files
| File | Changes |
|------|---------|
| `config/services.yaml` | Add `PUBLIC_PATHS` and related env vars + parameters |
| `config/packages/rate_limiter.yaml` | Add `public_burst`, `public_upper`, `public_limiter` |
| `config/packages/cache.yaml` | Add `publicRateLimitCache` pool |
| `config/packages/test/cache.yaml` | Add `publicRateLimitCache` pool (array adapter) |
| `src/ConfigBag.php` | Add `publicPaths()` method returning parsed path patterns |
| `tests/TestKernel.php` | Add `publicRateLimitCache` to reset exclusion list |
| `tests/Support/ListenerTestHelper.php` | Add helper for public rate limiter factory |
| `docs/example.env` | Document new env vars |
| `.env.test` | Add test defaults for public paths vars |
| `.env` | Add dev defaults for public paths vars |
| `docs/Caddyfile` | Add example of public + protected service config |
| `CHANGELOG.md` | Add v1.1 section |
| `ROADMAP.md` | Mark Phase 1 as in-progress / completed |
| `readme.md` | Document public access feature |
## New Test Files
| File | Coverage |
|------|----------|
| `tests/Unit/Service/PublicPathMatcherTest.php` | Pattern parsing, matching, wildcards, domain scoping |
| `tests/Unit/Listener/PublicAccessListenerTest.php` | Listener logic: public path match → 200, non-public → pass through, rate limited → 429, authenticated → not reached |
| `tests/Functional/PublicAccessFlowTest.php` | End-to-end: public path accessible, rate limit enforced, non-public path shows login, authenticated user bypasses public rate limit |
---
## Implementation Order
1. **`PublicPathMatcher`** — Pure path matching logic, no dependencies.
Parse the `PUBLIC_PATHS` string into pattern entries (each with
optional host + path pattern). Convert `*`/`**` wildcards to regex.
Match a given (host, path) against all patterns.
2. **Config** — Add env vars to `services.yaml`, add rate limiter to
`rate_limiter.yaml`, add cache pool to `cache.yaml` + test cache.
3. **`ConfigBag`** — Add `publicPaths()` returning the raw string (the
`PublicPathMatcher` does the parsing). Or add the `PublicPathMatcher`
as a service that receives the raw string via autowiring.
4. **`PublicAccessListener`** — Inject `PublicPathMatcherInterface`,
`RateLimiterFactoryInterface` (target `public_limiter`), and
`ConfigBag`. On `RequestEvent`:
- If no public paths configured → return immediately.
- If request already has a response → return (auth listeners ran first).
- Check if (host, path) matches any public pattern.
- If no match → return (fall through to auth flow).
- If match → consume(1) from public rate limiter.
- If over limit → set 429 response with `Retry-After`.
- If within limit → set 200 response (plain text, no `Remote-User`).
5. **Tests** — Unit tests for `PublicPathMatcher` and
`PublicAccessListener`, functional tests for the full flow.
6. **Documentation** — Update all docs.
7. **Lint + Test** — Run php-cs-fixer + phpunit, fix any issues.
8. **Commit + Push + PR.**
---
## Key Design Decisions
### Why priority 84?
- Must be **after** `AcceptListener` (99) and `AllowListener` (88) so
authenticated users never hit the public rate limiter.
- Must be **before** `RejectListener` (77) so public access is not
blocked by the login attempt rate limiter.
- Must be **before** `LoginListener` (66) so login attempts on public
paths are still processed (though this is an edge case — a login
attempt on a public path would set a response in `PublicAccessListener`
before `LoginListener` runs, which is correct: you don't need to login
to access a public path).
**Wait — actually this is a problem.** If someone sends an `X-Preauth`
header on a public path, `PublicAccessListener` would return 200 before
`LoginListener` can process the login. But that's actually fine — if the
path is public, they don't need to log in. If they want to authenticate,
they can visit a non-public path.
**Revised approach:** `PublicAccessListener` should only return 200 for
**GET/HEAD** requests to public paths, or all methods? For a gate like
this, all methods should be allowed on public paths — the backend
service (e.g., Gitea) handles its own authorization for write
operations.
### Why a separate rate limiter?
The existing `login_limiter` rate limits **login attempts** (failures).
The public rate limiter rate limits **all requests** to public paths.
They serve different purposes and need independent counters. Using the
same limiter would mean public traffic could exhaust the login attempt
budget, or vice versa.
### Why `Retry-After` header?
It's a standard HTTP header (RFC 7231) that tells clients how long to
wait before retrying. Legitimate clients (browsers, API consumers) and
crawlers respect it.
### Why no `Remote-User` header on public responses?
The `Remote-User` header tells the backend who the authenticated user
is. For public access, there is no authenticated user. Sending
`Remote-User: public` or similar could confuse the backend. The backend
should treat requests without `Remote-User` as anonymous.
### Path matching: query strings
Query strings are **ignored** for path matching. `/public?foo=bar`
matches the pattern `/public`. This is implemented by using
`$request->getPathInfo()` which returns the path without query string.
---
## Edge Cases
1. **Empty `PUBLIC_PATHS`** → Feature disabled, zero impact on existing
behavior. All tests pass unchanged.
2. **Authenticated user visits a public path** → `AcceptListener` or
`AllowListener` returns 200 before `PublicAccessListener` runs. The
public rate limiter is never consulted.
3. **Public path rate limit exceeded** → 429 with `Retry-After` header.
The response uses the error template (same as login rate limit) but
always with 429 status (never teapot — teapot is for login failures).
4. **Non-public path on a host that has some public paths** → Falls
through to the normal auth flow. Login page or redirect.
5. **`PUBLIC_PATHS` with whitespace** → Trimmed during parsing.
`PUBLIC_PATHS='/public, /api'` is equivalent to `/public,/api`.
6. **Invalid patterns** (not starting with `/`) → Silently ignored
during parsing. Logged at debug level.
7. **Login attempt on a public path** → `PublicAccessListener` returns
200 before `LoginListener` runs. This is correct behavior — if the
path is public, no login is needed.
8. **Subdomain redirect mode + public paths** → If using an auth
subdomain, requests to the auth subdomain itself should never be
treated as public. The `PublicAccessListener` should skip requests
where `host === authSubdomain`.
---
## Test Strategy
### Unit Tests — `PublicPathMatcherTest`
- Empty string → no patterns → matches nothing
- Single path `/public` → matches exact, not `/public/`
- Wildcard `/public/*` → matches `/public/x`, not `/public`, not `/public/a/b`
- Double wildcard `/public/**` → matches `/public/a/b/c`
- Multiple patterns comma-separated
- Domain-prefixed pattern `host.example.com/public/**`
- Path without domain prefix matches any host
- Whitespace trimming
- Invalid patterns (no leading `/`) ignored
- Case sensitivity (paths are case-sensitive, hosts are case-insensitive)
### Unit Tests — `PublicAccessListenerTest`
- No public paths configured → returns without setting response
- Non-public path → returns without setting response
- Public path, within rate limit → sets 200 response
- Public path, rate limit exceeded → sets 429 response with Retry-After
- Public path, response already set by earlier listener → returns
- Auth subdomain request → skipped (even if path matches)
- Uses `ListenerTestHelper` for mock rate limiters and collaborators
### Functional Tests — `PublicAccessFlowTest`
- Public path accessible without authentication → 200
- Non-public path without auth → 401 (login page)
- Rate limit enforcement: multiple requests exceed burst → 429
- Authenticated user visits public path → 200 with Remote-User (bypasses public limiter)
- 429 response includes Retry-After header
- Query string ignored for path matching
- Wildcard matching works end-to-end
---
## Documentation Updates
### README
New section: **"Public Rate-Limited Access"** under Configuration.
- Explain the feature and use case
- Document all env vars
- Show path pattern syntax with examples
- Show Caddyfile configuration for public + protected services
- Note that authenticated users bypass the public rate limiter
### CHANGELOG
New `[Unreleased]` → v1.1 section with all new features.
### ROADMAP
Mark Phase 1 items as completed.
### docs/example.env
Add all new env vars with comments.
### docs/Caddyfile
Add example showing a service with both public and protected paths.
+733
View File
@@ -0,0 +1,733 @@
parameters:
ignoreErrors:
-
message: '#^Method App\\Clock\:\:now\(\) overrides method Psr\\Clock\\ClockInterface\:\:now\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Clock.php
-
message: '#^Method App\\Command\\GenerateBackupCodesCommand\:\:configure\(\) overrides method Symfony\\Component\\Console\\Command\\Command\:\:configure\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Command/GenerateBackupCodesCommand.php
-
message: '#^Method App\\Command\\GenerateBackupCodesCommand\:\:execute\(\) overrides method Symfony\\Component\\Console\\Command\\Command\:\:execute\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Command/GenerateBackupCodesCommand.php
-
message: '#^Class App\\Data\\Payload has an uninitialized property \$id\. Give it default value or assign it in the constructor\.$#'
identifier: property.uninitialized
count: 1
path: src/Data/Payload.php
-
message: '#^Class App\\Data\\Payload has an uninitialized property \$json\. Give it default value or assign it in the constructor\.$#'
identifier: property.uninitialized
count: 1
path: src/Data/Payload.php
-
message: '#^Class App\\Data\\Payload has an uninitialized property \$nonce\. Give it default value or assign it in the constructor\.$#'
identifier: property.uninitialized
count: 1
path: src/Data/Payload.php
-
message: '#^Class App\\Data\\Payload has an uninitialized property \$scope\. Give it default value or assign it in the constructor\.$#'
identifier: property.uninitialized
count: 1
path: src/Data/Payload.php
-
message: '#^Class App\\Data\\Payload has an uninitialized property \$token\. Give it default value or assign it in the constructor\.$#'
identifier: property.uninitialized
count: 1
path: src/Data/Payload.php
-
message: '#^Method App\\Data\\Payload\:\:load\(\) has parameter \$input with generic class Symfony\\Component\\HttpFoundation\\InputBag but does not specify its types\: TInput$#'
identifier: missingType.generics
count: 1
path: src/Data/Payload.php
-
message: '#^Class App\\Kernel has an uninitialized property \$persistCache\. Give it default value or assign it in the constructor\.$#'
identifier: property.uninitialized
count: 1
path: src/Kernel.php
-
message: '#^Method App\\Kernel\:\:boot\(\) overrides method Symfony\\Component\\HttpKernel\\Kernel\:\:boot\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Kernel.php
-
message: '#^Method App\\Kernel\:\:terminate\(\) overrides method Symfony\\Component\\HttpKernel\\Kernel\:\:terminate\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Kernel.php
-
message: '#^Class App\\Listener\\AcceptListener has an uninitialized readonly property \$logger\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Listener/AcceptListener.php
-
message: '#^Readonly property App\\Listener\\AcceptListener\:\:\$logger is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: src/Listener/AcceptListener.php
-
message: '#^Class App\\Listener\\AllowListener has an uninitialized readonly property \$logger\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Listener/AllowListener.php
-
message: '#^Readonly property App\\Listener\\AllowListener\:\:\$logger is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: src/Listener/AllowListener.php
-
message: '#^Class App\\Listener\\InterceptListener has an uninitialized readonly property \$logger\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Listener/InterceptListener.php
-
message: '#^Class App\\Listener\\InterceptListener has an uninitialized readonly property \$nonceCache\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Listener/InterceptListener.php
-
message: '#^Property App\\Listener\\InterceptListener\:\:\$config is never read, only written\.$#'
identifier: property.onlyWritten
count: 1
path: src/Listener/InterceptListener.php
-
message: '#^Readonly property App\\Listener\\InterceptListener\:\:\$logger is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 2
path: src/Listener/InterceptListener.php
-
message: '#^Readonly property App\\Listener\\InterceptListener\:\:\$nonceCache is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: src/Listener/InterceptListener.php
-
message: '#^Class App\\Listener\\PasskeyListener has an uninitialized readonly property \$logger\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Listener/PasskeyListener.php
-
message: '#^Class App\\Listener\\PasskeyListener has an uninitialized readonly property \$nonceCache\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Listener/PasskeyListener.php
-
message: '#^Readonly property App\\Listener\\PasskeyListener\:\:\$logger is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 2
path: src/Listener/PasskeyListener.php
-
message: '#^Readonly property App\\Listener\\PasskeyListener\:\:\$nonceCache is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: src/Listener/PasskeyListener.php
-
message: '#^Class App\\Listener\\LoginListener has an uninitialized readonly property \$logger\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Listener/LoginListener.php
-
message: '#^Class App\\Listener\\LoginListener has an uninitialized readonly property \$nonceCache\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Listener/LoginListener.php
-
message: '#^Readonly property App\\Listener\\LoginListener\:\:\$logger is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 2
path: src/Listener/LoginListener.php
-
message: '#^Readonly property App\\Listener\\LoginListener\:\:\$nonceCache is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: src/Listener/LoginListener.php
-
message: '#^Using nullsafe property access "\?\-\>id" on left side of \?\? is unnecessary\. Use \-\> instead\.$#'
identifier: nullsafe.neverNull
count: 1
path: src/Listener/LoginListener.php
-
message: '#^Using nullsafe property access "\?\-\>json" on left side of \?\? is unnecessary\. Use \-\> instead\.$#'
identifier: nullsafe.neverNull
count: 1
path: src/Listener/LoginListener.php
-
message: '#^Class App\\Listener\\PublicAccessListener has an uninitialized readonly property \$logger\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Listener/PublicAccessListener.php
-
message: '#^Readonly property App\\Listener\\PublicAccessListener\:\:\$logger is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: src/Listener/PublicAccessListener.php
-
message: '#^Using nullsafe method call on non\-nullable type DateTimeImmutable\. Use \-\> instead\.$#'
identifier: nullsafe.neverNull
count: 1
path: src/Listener/PublicAccessListener.php
-
message: '#^Class App\\Listener\\RejectListener has an uninitialized readonly property \$logger\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Listener/RejectListener.php
-
message: '#^Readonly property App\\Listener\\RejectListener\:\:\$logger is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: src/Listener/RejectListener.php
-
message: '#^Method App\\MonitorCacheKeys\:\:allValid\(\) has parameter \$keys with no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: src/MonitorCacheKeys.php
-
message: '#^Method App\\MonitorCacheKeys\:\:clear\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:clear\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/MonitorCacheKeys.php
-
message: '#^Method App\\MonitorCacheKeys\:\:commit\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:commit\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/MonitorCacheKeys.php
-
message: '#^Method App\\MonitorCacheKeys\:\:deleteItem\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:deleteItem\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/MonitorCacheKeys.php
-
message: '#^Method App\\MonitorCacheKeys\:\:deleteItems\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:deleteItems\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/MonitorCacheKeys.php
-
message: '#^Method App\\MonitorCacheKeys\:\:getChanges\(\) return type has no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: src/MonitorCacheKeys.php
-
message: '#^Method App\\MonitorCacheKeys\:\:getItem\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:getItem\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/MonitorCacheKeys.php
-
message: '#^Method App\\MonitorCacheKeys\:\:getItems\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:getItems\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/MonitorCacheKeys.php
-
message: '#^Method App\\MonitorCacheKeys\:\:getKeys\(\) return type has no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: src/MonitorCacheKeys.php
-
message: '#^Method App\\MonitorCacheKeys\:\:hasItem\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:hasItem\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/MonitorCacheKeys.php
-
message: '#^Method App\\MonitorCacheKeys\:\:save\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:save\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/MonitorCacheKeys.php
-
message: '#^Method App\\MonitorCacheKeys\:\:saveDeferred\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:saveDeferred\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/MonitorCacheKeys.php
-
message: '#^Class App\\Service\\BackupCodeManager has an uninitialized readonly property \$config\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Service/BackupCodeManager.php
-
message: '#^Class App\\Service\\BackupCodeManager has an uninitialized readonly property \$logger\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Service/BackupCodeManager.php
-
message: '#^Method App\\Service\\BackupCodeManager\:\:expire\(\) overrides method App\\Service\\BackupCodeInterface\:\:expire\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Service/BackupCodeManager.php
-
message: '#^Method App\\Service\\BackupCodeManager\:\:generate\(\) overrides method App\\Service\\BackupCodeInterface\:\:generate\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Service/BackupCodeManager.php
-
message: '#^Method App\\Service\\BackupCodeManager\:\:saveCodes\(\) has parameter \$codes with no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: src/Service/BackupCodeManager.php
-
message: '#^Method App\\Service\\BackupCodeManager\:\:verifyAndConsume\(\) overrides method App\\Service\\BackupCodeInterface\:\:verifyAndConsume\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Service/BackupCodeManager.php
-
message: '#^Readonly property App\\Service\\BackupCodeManager\:\:\$config is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: src/Service/BackupCodeManager.php
-
message: '#^Readonly property App\\Service\\BackupCodeManager\:\:\$logger is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: src/Service/BackupCodeManager.php
-
message: '#^Method App\\Service\\DomainManager\:\:authBase\(\) overrides method App\\Service\\DomainInterface\:\:authBase\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Service/DomainManager.php
-
message: '#^Method App\\Service\\DomainManager\:\:getAuthSubdomain\(\) overrides method App\\Service\\DomainInterface\:\:getAuthSubdomain\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Service/DomainManager.php
-
message: '#^Method App\\Service\\DomainManager\:\:matchesAuth\(\) overrides method App\\Service\\DomainInterface\:\:matchesAuth\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Service/DomainManager.php
-
message: '#^Method App\\Service\\DomainManager\:\:validReturn\(\) overrides method App\\Service\\DomainInterface\:\:validReturn\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Service/DomainManager.php
-
message: '#^Class App\\Service\\LoginManager has an uninitialized readonly property \$config\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Service/LoginManager.php
-
message: '#^Class App\\Service\\LoginManager has an uninitialized readonly property \$logger\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Service/LoginManager.php
-
message: '#^Class App\\Service\\SessionIssuer has an uninitialized readonly property \$logger\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Service/SessionIssuer.php
-
message: '#^Readonly property App\\Service\\SessionIssuer\:\:\$logger is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: src/Service/SessionIssuer.php
-
message: '#^Class App\\Service\\LoginManager has an uninitialized readonly property \$nonceCache\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: src/Service/LoginManager.php
-
message: '#^Readonly property App\\Service\\LoginManager\:\:\$config is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: src/Service/LoginManager.php
-
message: '#^Readonly property App\\Service\\LoginManager\:\:\$logger is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: src/Service/LoginManager.php
-
message: '#^Readonly property App\\Service\\LoginManager\:\:\$nonceCache is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: src/Service/LoginManager.php
-
message: '#^Method App\\Service\\PublicPathMatcher\:\:isEmpty\(\) overrides method App\\Service\\PublicPathMatcherInterface\:\:isEmpty\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Service/PublicPathMatcher.php
-
message: '#^Method App\\Service\\PublicPathMatcher\:\:matches\(\) overrides method App\\Service\\PublicPathMatcherInterface\:\:matches\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: src/Service/PublicPathMatcher.php
-
message: '#^Method App\\Tests\\Functional\\AuthenticationFlowTest\:\:createClient\(\) has parameter \$options with no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: tests/Functional/AuthenticationFlowTest.php
-
message: '#^Method App\\Tests\\Functional\\AuthenticationFlowTest\:\:createClient\(\) has parameter \$server with no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: tests/Functional/AuthenticationFlowTest.php
-
message: '#^Method App\\Tests\\Functional\\AuthenticationFlowTest\:\:createClient\(\) overrides method Symfony\\Bundle\\FrameworkBundle\\Test\\WebTestCase\:\:createClient\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Functional/AuthenticationFlowTest.php
-
message: '#^Method App\\Tests\\Functional\\AuthenticationFlowTest\:\:encodePayload\(\) has parameter \$data with no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: tests/Functional/AuthenticationFlowTest.php
-
message: '#^Method App\\Tests\\Functional\\AuthenticationFlowTest\:\:loginPayload\(\) is unused\.$#'
identifier: method.unused
count: 1
path: tests/Functional/AuthenticationFlowTest.php
-
message: '#^Method App\\Tests\\Functional\\CacheControlFlowTest\:\:createClient\(\) has parameter \$options with no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: tests/Functional/CacheControlFlowTest.php
-
message: '#^Method App\\Tests\\Functional\\CacheControlFlowTest\:\:createClient\(\) has parameter \$server with no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: tests/Functional/CacheControlFlowTest.php
-
message: '#^Method App\\Tests\\Functional\\CacheControlFlowTest\:\:createClient\(\) overrides method Symfony\\Bundle\\FrameworkBundle\\Test\\WebTestCase\:\:createClient\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Functional/CacheControlFlowTest.php
-
message: '#^Method App\\Tests\\Functional\\CacheControlFlowTest\:\:encodePayload\(\) has parameter \$data with no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: tests/Functional/CacheControlFlowTest.php
-
message: '#^Method App\\Tests\\Functional\\PublicAccessFlowTest\:\:createClient\(\) has parameter \$options with no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: tests/Functional/PublicAccessFlowTest.php
-
message: '#^Method App\\Tests\\Functional\\PublicAccessFlowTest\:\:createClient\(\) has parameter \$server with no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: tests/Functional/PublicAccessFlowTest.php
-
message: '#^Method App\\Tests\\Functional\\PublicAccessFlowTest\:\:createClient\(\) overrides method Symfony\\Bundle\\FrameworkBundle\\Test\\WebTestCase\:\:createClient\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Functional/PublicAccessFlowTest.php
-
message: '#^Method App\\Tests\\Functional\\PublicAccessFlowTest\:\:encodePayload\(\) has parameter \$data with no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: tests/Functional/PublicAccessFlowTest.php
-
message: '#^Method App\\Tests\\TestKernel\:\:build\(\) overrides method Symfony\\Component\\DependencyInjection\\Kernel\\AbstractKernel\:\:build\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/TestKernel.php
-
message: '#^Method Symfony\\Component\\DependencyInjection\\Compiler\\CompilerPassInterface@anonymous/tests/TestKernel\.php\:31\:\:process\(\) overrides method Symfony\\Component\\DependencyInjection\\Compiler\\CompilerPassInterface\:\:process\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/TestKernel.php
-
message: '#^Method App\\Tests\\Unit\\Command\\GenerateBackupCodesCommandTest\:\:makeManagerStub\(\) has parameter \$generatedCodes with no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: tests/Unit/Command/GenerateBackupCodesCommandTest.php
-
message: '#^Call to static method PHPUnit\\Framework\\Assert\:\:assertNull\(\) with null will always evaluate to true\.$#'
identifier: staticMethod.alreadyNarrowedType
count: 2
path: tests/Unit/Enum/ScopeTest.php
-
message: '#^Method App\\Tests\\Unit\\Listener\\LoginListenerTest\:\:encodePayload\(\) has parameter \$data with no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: tests/Unit/Listener/LoginListenerTest.php
-
message: '#^Call to static method PHPUnit\\Framework\\Assert\:\:assertIsString\(\) with string will always evaluate to true\.$#'
identifier: staticMethod.alreadyNarrowedType
count: 1
path: tests/Unit/Service/BackupCodeManagerTest.php
-
message: '#^Call to static method PHPUnit\\Framework\\Assert\:\:assertTrue\(\) with true will always evaluate to true\.$#'
identifier: staticMethod.alreadyNarrowedType
count: 1
path: tests/Unit/Service/BackupCodeManagerTest.php
-
message: '#^Call to an undefined method App\\Service\\BackupCodeInterface\:\:method\(\)\.$#'
identifier: method.notFound
count: 20
path: tests/Unit/Service/LoginManagerTest.php
-
message: '#^Class App\\Tests\\Unit\\Service\\LoginManagerTest has an uninitialized property \$backupCodeManager\. Give it default value or assign it in the constructor\.$#'
identifier: property.uninitialized
count: 1
path: tests/Unit/Service/LoginManagerTest.php
-
message: '#^Class App\\Tests\\Unit\\Service\\LoginManagerTest has an uninitialized property \$domainManager\. Give it default value or assign it in the constructor\.$#'
identifier: property.uninitialized
count: 1
path: tests/Unit/Service/LoginManagerTest.php
-
message: '#^Class App\\Tests\\Unit\\Service\\LoginManagerTest has an uninitialized property \$pool\. Give it default value or assign it in the constructor\.$#'
identifier: property.uninitialized
count: 1
path: tests/Unit/Service/LoginManagerTest.php
-
message: '#^Class class@anonymous/tests/Unit/Trait/GetTotpTraitTest\.php\:22 has an uninitialized readonly property \$config\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: tests/Unit/Trait/GetTotpTraitTest.php
-
message: '#^Readonly property class@anonymous/tests/Unit/Trait/GetTotpTraitTest\.php\:22\:\:\$config is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: tests/Unit/Trait/GetTotpTraitTest.php
-
message: '#^Class App\\Tests\\Unit\\Trait\\HasLoggerTraitTest has an uninitialized readonly property \$logger\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: tests/Unit/Trait/HasLoggerTraitTest.php
-
message: '#^Readonly property App\\Tests\\Unit\\Trait\\HasLoggerTraitTest\:\:\$logger is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: tests/Unit/Trait/HasLoggerTraitTest.php
-
message: '#^Class class@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:25 has an uninitialized readonly property \$logger\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Class class@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:25 has an uninitialized readonly property \$nonceCache\. Assign it in the constructor\.$#'
identifier: property.uninitializedReadonly
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:145\:\:expiresAfter\(\) overrides method Psr\\Cache\\CacheItemInterface\:\:expiresAfter\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:145\:\:expiresAt\(\) overrides method Psr\\Cache\\CacheItemInterface\:\:expiresAt\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:145\:\:get\(\) overrides method Psr\\Cache\\CacheItemInterface\:\:get\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:145\:\:getKey\(\) overrides method Psr\\Cache\\CacheItemInterface\:\:getKey\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:145\:\:isHit\(\) overrides method Psr\\Cache\\CacheItemInterface\:\:isHit\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:145\:\:set\(\) overrides method Psr\\Cache\\CacheItemInterface\:\:set\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemPoolInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:128\:\:clear\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:clear\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemPoolInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:128\:\:commit\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:commit\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemPoolInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:128\:\:deleteItem\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:deleteItem\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemPoolInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:128\:\:deleteItems\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:deleteItems\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemPoolInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:128\:\:getItem\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:getItem\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemPoolInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:128\:\:getItems\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:getItems\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemPoolInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:128\:\:getItems\(\) return type has no value type specified in iterable type iterable\.$#'
identifier: missingType.iterableValue
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemPoolInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:128\:\:hasItem\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:hasItem\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemPoolInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:128\:\:save\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:save\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Method Psr\\Cache\\CacheItemPoolInterface@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:128\:\:saveDeferred\(\) overrides method Psr\\Cache\\CacheItemPoolInterface\:\:saveDeferred\(\) but is missing the \#\[\\Override\] attribute\.$#'
identifier: method.missingOverride
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Readonly property class@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:25\:\:\$logger is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Readonly property class@anonymous/tests/Unit/Trait/MakeNonceTraitTest\.php\:25\:\:\$nonceCache is assigned outside of the constructor\.$#'
identifier: property.readOnlyAssignNotInConstructor
count: 1
path: tests/Unit/Trait/MakeNonceTraitTest.php
-
message: '#^Call to function method_exists\(\) with ''Symfony\\\\Component\\\\Dotenv\\\\Dotenv'' and ''bootEnv'' will always evaluate to false\.$#'
identifier: function.impossibleType
count: 1
path: tests/bootstrap.php
-
message: '#^Call to method bootEnv\(\) on an unknown class Symfony\\Component\\Dotenv\\Dotenv\.$#'
identifier: class.notFound
count: 1
path: tests/bootstrap.php
-
message: '#^Class Symfony\\Component\\Dotenv\\Dotenv not found\.$#'
identifier: class.notFound
count: 1
path: tests/bootstrap.php
-
message: '#^Instantiated class Symfony\\Component\\Dotenv\\Dotenv not found\.$#'
identifier: class.notFound
count: 1
path: tests/bootstrap.php
+116
View File
@@ -0,0 +1,116 @@
# phpstan.neon.dist — canonical shared PHPStan config.
#
# Copy verbatim into a project root. This is a LEAF file: it has no
# project-specific content, so "sync it" means "overwrite it", never merge.
# Do not hand-edit per repo — change it here and re-sync, or the five copies
# drift back apart (GUIDING-LIGHT §8.2).
#
# Baseline: level 6 for application code. Raise per project as it gets clean;
# the goal recorded in GUIDING-LIGHT §2.2 is level 6 minimum everywhere.
#
# Adopt incrementally:
# 1. vendor/bin/phpstan analyse --generate-baseline
# 2. Commit the result over the empty phpstan-baseline.neon that ships with this
# 3. Ratchet `level` up as the baseline shrinks
# Never replace a fix with an ignoreErrors entry — see reportIgnoresWithoutComments.
#
# IMPORTANT — every key below is VERIFIED against phpstan.org/config-reference.
# PHPStan 2.x errors on unknown keys, but a plausible-looking wrong key copied
# from a blog post is a common way to lose an afternoon. If you add a key,
# confirm it there first. Extension-specific keys (symfony.*, doctrine.*,
# phpstan-deprecation-rules, etc.) are deliberately NOT set here — see the
# commented block at the bottom for why and how to opt in per project.
parameters:
level: 6
paths:
- src
- tests
# ── High-signal checks (all verified key names) ──────────────────────────
# An `@var` that contradicts the assignment is almost always a real bug.
reportWrongPhpDocTypeInVarTag: true
# A `@var` that only widens the inferred type is usually an unnecessary cast.
reportAnyTypeWideningInVarTag: true
# `@param`/`@return` that contradict the native signature.
reportStaticMethodSignatures: true
# An ignoreErrors entry with no explanatory comment is a smell.
reportIgnoresWithoutComments: true
# Forces every ignore to still match something. Without this, ignores
# accumulate forever and nobody notices when the underlying bug is fixed.
reportUnmatchedIgnoredErrors: true
# Catch `Foo` vs `foo` in function names — matters for Windows devs and
# for correctness under strict autoloading.
checkFunctionNameCase: true
# Typed properties that are read before they are definitely initialised.
checkUninitializedProperties: true
# Respect #[Override] so refactors in parent classes cannot silently stop
# overriding a method that got renamed.
checkMissingOverrideMethodAttribute: true
checkMissingOverridePropertyAttribute: true
# Static analysis cannot see through sprintf, so mis-ordered placeholders
# are otherwise invisible until runtime.
checkStrictPrintfPlaceholderTypes: true
# Dynamic properties are deprecated in PHP 8.2+ and are a common source of
# typos that would otherwise fail silently at runtime.
checkDynamicProperties: true
# All five repos have this file (verified); the kernel boot lives here.
bootstrapFiles:
- tests/bootstrap.php
ignoreErrors:
# Symfony's createClient() returns KernelBrowser, but some test helpers
# are typed against the narrower legacy interface.
# reportUnmatched:false so this does not fail the build once the
# offending helper is typed properly.
#
# NOTE the layout: the dash sits alone and the keys are indented under
# it. This is the form used verbatim in PHPStan's own documentation.
# (The more compact `- message: ...` / continuation form is also valid
# NEON, but NOT every NEON parser in the wild handles it — the PHP
# parser PHPStan uses handles both, Python's neon-py handles neither
# reliably. Staying with the documented form avoids the argument.)
-
message: '#Call to an undefined method Symfony\\Component\\HttpFoundation\\Session\\SessionInterface::#'
reportUnmatched: false
includes:
# Ships EMPTY with this config. A repo overwrites it when it runs
# --generate-baseline. It must exist: a missing `includes` target is a hard
# error, not a silent skip, which is why the empty file is committed rather
# than the include being made conditional.
- phpstan-baseline.neon
# ─────────────────────────────────────────────────────────────────────────────
# OPTIONAL EXTENSIONS — commented out on purpose.
#
# These keys are owned by PHPStan *extensions*, not core. If the extension is
# not installed, or the key name drifts between extension majors, analysis
# fails outright. So they are opt-in per project rather than shared.
#
# Symfony — resolves service ids, autowiring, and container params from the
# compiled container. Requires phpstan/phpstan-symfony. Uncomment AND make sure
# the path exists (warm the dev cache first, or let the test bootstrap do it).
#
# symfony:
# containerXmlPath: var/cache/dev/App_KernelDevDebugContainer.xml
#
# Doctrine — validates DQL against the actual mapping. Requires
# phpstan/phpstan-doctrine. `repositoryClass` must name a class that EXISTS in
# the project; setting it to a class you do not have is an instant failure.
#
# doctrine:
# repositoryClass: App\Repository\YourBaseRepository
# ─────────────────────────────────────────────────────────────────────────────
+57
View File
@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.readthedocs.io/en/latest/configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
colors="true"
failOnDeprecation="true"
failOnNotice="true"
failOnWarning="true"
bootstrap="tests/bootstrap.php"
cacheDirectory=".phpunit.cache"
>
<php>
<ini name="display_errors" value="1" />
<ini name="error_reporting" value="-1" />
<server name="APP_ENV" value="test" force="true" />
<server name="SHELL_VERBOSITY" value="-1" />
<server name="KERNEL_CLASS" value="App\Tests\TestKernel" />
<!-- fixed TOTP secret so functional tests can compute valid codes -->
<server name="TOTP_URI" value="otpauth://totp/Test-TOTP?secret=JBSWY3DPEHPK3PXP" />
<server name="APP_SECRET" value="test_secret_key_change_me" />
<!-- high rate limits so functional tests don't get blocked -->
<server name="BURST_COUNT" value="10000" />
<server name="UPPER_COUNT" value="10000" />
<!-- public access: enable for functional tests with low limits -->
<server name="PUBLIC_PATHS" value="/public/**" />
<server name="PUBLIC_BURST_COUNT" value="3" />
<server name="PUBLIC_BURST_TIME" value="60" />
<server name="PUBLIC_UPPER_COUNT" value="10000" />
<server name="PUBLIC_UPPER_TIME" value="3600" />
</php>
<testsuites>
<testsuite name="Project Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<source ignoreSuppressionOfDeprecations="true"
ignoreIndirectDeprecations="true"
restrictNotices="true"
restrictWarnings="true"
>
<include>
<directory>src</directory>
</include>
<deprecationTrigger>
<method>Doctrine\Deprecations\Deprecation::trigger</method>
<method>Doctrine\Deprecations\Deprecation::delegateTriggerToBackend</method>
<function>trigger_deprecation</function>
</deprecationTrigger>
</source>
<extensions>
</extensions>
</phpunit>
+2 -1
View File
@@ -1,10 +1,11 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
use App\Kernel; use App\Kernel;
require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return function (array $context) { return static function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']); return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
}; };
+348 -42
View File
@@ -1,68 +1,374 @@
# Preauth # Preauth
For when you want to expose a web service without letting the whole world try to access it. Because sometimes you want both a belt and suspenders.
I found myself needing to make my personal Nextcloud instance available outside my VPN, but was worried since it has had authentication exploits in the past. A lightweight TOTP authentication gateway for self-hosted web services.
So, I built a simple authentication gateway, which eventually turned into this project. Preauth sits between your reverse proxy (Caddy) and your web service,
requiring a TOTP code before traffic ever reaches the protected application.
It is **not** a replacement for your service's own authentication — it's a
gate that prevents outsiders from even seeing what service is running.
It sits between your reverse proxy and web service to add extra protection, while still being easy to access from anywhere. For when you want a belt and suspenders.
## Requirements ## Features
* Docker - **TOTP authentication** — Time-based one-time passwords (compatible with
* Caddy (as a reverse proxy) Google Authenticator, Authy, 1Password, etc.)
* a web service you want to secure - **Backup codes** — Single-use backup codes for when TOTP devices are lost
- **Caddy native** — Designed for Caddy's `forward_auth` directive
- **Docker-first** — Single container, persistent volumes, no database
- **Rate limiting** — Per-IP burst and sustained limits (cannot be disabled)
- **Public rate-limited access** — Optional, allow unauthenticated access
to specific paths with separate rate limiting (e.g., public Gitea repos)
- **Central auth** — Optional subdomain-based SSO across multiple services
- **IP-based bypass** — Optional, for services that don't handle cookies
- **Customizable** — Colors, labels, messages, and error text via env vars
- **Teapot mode** — Respond with `418 I'm a Teapot` when rate-limited
(because it's more fun than `429 Too Many Requests`)
- **Cookie security** — `__Host-` prefixed cookies with `SameSite=Strict`,
`Secure`, and `HttpOnly`
- **Nonce system** — Single-use nonces prevent replay and CSRF attacks
- **Dual-layer cache** — APCu for speed, file-based persistence for restarts
It may be possible to use some other reverse proxy, but for now, I'm going to stick with just Caddy. ## Quick Start
There is an example Caddyfile in /docs/ and env.example file to get you started. Within the Caddyfile is a snippet, which makes it easy to wrap your web service with preauth. ### 1. Pull the Docker image
When someone tries to reach your protected web service, Caddy will check with preauth if they are allowed, if their preauth cookie is missing, invalid, or expired, we will show them to a login screen. ```bash
docker pull digitaladapt/preauth:latest
```
I say login, but it's really just a TOTP code (6-digit code which changes every 30 second). But once they enter the right code,they'll get their cookie and be shown the protected service. It is also possible to allow all requests from an approved IP address, but that is disabled by default. ### 2. Create your environment file
First time you spin up the docker container it will generate a TOTP secret (which you'll load into your authenticator app); or generate you own. ```bash
# Generate a TOTP secret to get started
openssl rand -base64 30
```
Be sure to save that TOTP secret to your docker environment, so that it persists beyond removing the container. Create a `.env` file (see `docs/examples/.env.example` for all options):
## Backup Codes ```env
APP_SECRET=your-random-secret-here
TOTP_URI=otpauth://totp/Preauth?secret=YOUR_SECRET
COOKIE_TTL=2592000
```
It is possible to generate single-use backup codes via a console command within the docker container. > If `TOTP_URI` is left blank, the app will generate one on first run
> and print it to the container logs. Copy it to your `.env` file.
```shell ### 3. Start the container
```bash
docker compose up -d
```
See `docs/examples/compose.yaml` for an example Docker Compose file.
### 4. Configure Caddy
```caddyfile
service.example.com {
forward_auth preauth {
uri {uri}
copy_headers Remote-User
# keep the login flow out of browser/proxy caches
header_down Cache-Control "no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0, s-maxage=0"
header_down Pragma "no-cache"
header_down Expires "0"
header_down Surrogate-Control "no-store"
header_down Vary "*"
}
reverse_proxy your-service:80
}
```
See `docs/examples/Caddyfile` for more examples, including path-specific protection
and central auth subdomain configuration. The `header_down` lines above are
optional — preauth already sends these headers itself — but they guarantee
at the edge that no part of the login flow is ever cached. (2xx auth
responses are consumed by `forward_auth` and never reach the browser, so
your service's own cache headers are unaffected.)
### 5. Generate backup codes (optional)
```bash
docker exec -t preauth bin/console app:generate-backup-codes [count=10] docker exec -t preauth bin/console app:generate-backup-codes [count=10]
``` ```
### History ## Requirements
#### v0.7.0 (May 29th, 2026)
Added ability to generate single-use backup codes.
Removed static password and lookup token, as they were security risks.
Updated to PHP 8.5, updated dependencies.
#### v0.6.0 (Feb 10th, 2026) - **Docker** — Preauth runs as a Docker container
Added optional (disabled by default) ability to lookup token by static password. - **Caddy** — As your reverse proxy (uses `forward_auth` directive)
- **A web service** — The application you want to protect
#### v0.5.0 (Jan 17th, 2026) Other reverse proxies with similar `forward_auth` / `auth_request`
Nonce related cleanup; added optional (disabled by default) ability to use a static password as a backup means of authentication. capabilities may work, but only Caddy is officially supported.
#### v0.4.1 (Dec 26th, 2025) ## Configuration
Fixed bug which can occur if you delete cache files.
#### v0.4.0 (Dec 26th, 2025) All configuration is via environment variables. See `docs/examples/.env.example`
Massive rewrite to switch to using listeners instead of controller, header for login payload instead of get request, removed icon system, asset system, was able to remove all the domain processing, enhanced cookie security, and more. for the complete reference.
#### v0.3.0 (Dec 15th, 2025) ### Main Options
Includes significant breaking changes.
Default port and transportation changed to http via port 80.
Names of environment variables have changed.
#### v0.2.0 (Dec 3rd, 2025) | Variable | Default | Description |
Now with login rate limiting. |----------|---------|-------------|
New page for client error (too many requests). | `TOTP_URI` | _(empty)_ | TOTP provisioning URI. If blank, one is generated on first run. |
Made example docker compose. | `COOKIE_TTL` | `2592000` | Session duration in seconds (default: 30 days). |
| `SUBDOMAIN_REDIRECT` | `0` | Enable central auth across subdomains (boolean). |
| `AUTH_SUBDOMAIN` | _(empty)_ | Hostname for central auth (e.g., `auth.example.com`). |
#### v0.1.0 (Nov 14th, 2025) ### Extra Options
Now an actual project, docker image pushed to docker hub, which uses php-fpm, code into a src folder, templates into separate files.
#### v0.0.1 (June 26th, 2024) | Variable | Default | Description |
Started off as a single file script which was part of my caddy config. Hardcoded TOTP secret, zero flexibility, but functional. Would stay like that, quietly working in production for about a full year before any real change. |----------|---------|-------------|
| `IP_TTL` | `0` | Seconds to allow all traffic from an IP after login (0 = disabled). |
| `TEAPOT` | `1` | Respond with 418 instead of 429 when rate-limited (boolean). |
| `MAX_REQUESTS` | `500` | Restart each FrankenPHP worker thread after this many requests to contain memory growth (`0` = unlimited). Maps to the Caddyfile `max_requests` directive. |
### Remote-User Header
The `Remote-User` header sent to backends on successful auth is configurable:
| Variable | Default | Description |
|----------|---------|-------------|
| `REMOTE_USER` | `session` | Mode: `session`, `static`, `mapped`, or `none`. |
| `REMOTE_USER_STATIC` | `authenticated` | Value sent when mode is `static`. |
| `REMOTE_USER_MAP` | _(empty)_ | Comma-separated map for `mapped` mode (e.g. `alice:admin,bob:user`). |
- **`session`** (default): Sends the session id. Backward-compatible.
- **`static`**: Sends a fixed string for all authenticated requests.
- **`mapped`**: Looks up the session id in the map; falls back to session id if not found.
- **`none`**: Omits the header entirely (Caddy still accepts based on status code).
### Rate Limiting
Rate limiting **cannot be disabled**. It uses a compound sliding window:
| Variable | Default | Description |
|----------|---------|-------------|
| `BURST_COUNT` | `2` | Max attempts per burst window. |
| `BURST_TIME` | `30` | Burst window in seconds. |
| `UPPER_COUNT` | `10` | Max attempts per upper window. |
| `UPPER_TIME` | `3600` | Upper window in seconds (1 hour). |
### Passkey Authentication
Passkeys (WebAuthn) can replace the TOTP code for everyday logins, while the
code remains the way a new device is enrolled.
**Two prerequisites, both enforced.** The feature refuses to operate without
them rather than degrading quietly:
1. **Central auth must be configured** (`SUBDOMAIN_REDIRECT=true` and a real
`AUTH_SUBDOMAIN`). A passkey is scoped to one relying party, so there has to
be a single shared domain for the whole family of services. Without it,
passkeys are switched off — they would otherwise be scoped to a single host
and confuse users with multiple, unrelated passkeys.
2. **HTTPS is required, in development too.** There is no `http://localhost`
exemption and no setting that re-enables one, because such an exemption is
exactly how the same weakness ends up enabled in production. To exercise
passkeys locally, see the TLS note in `docs/examples/Caddyfile`.
`localhost` therefore cannot be used for passkeys: it has no base domain, so
central auth cannot be configured at all.
| Variable | Default | Description |
|----------|---------|-------------|
| `PASSKEY_ENABLED` | `0` | Master switch. Enabling it without the prerequisites above makes the container fail at startup, rather than offering a feature that cannot work. |
| `PASSKEY_RP_NAME` | `TITLE` | Name shown in the authenticator prompt. |
| `PASSKEY_USER_VERIFICATION` | `required` | `required`, `preferred`, or `discouraged`. An unrecognised value falls back to `required`, never to something weaker. |
| `PASSKEY_TIMEOUT` | `60000` | Ceremony timeout in milliseconds. |
| `PASSKEY_BUTTON_NAME` | `Sign in with a passkey` | Label for the sign-in button. |
| `PASSKEY_REGISTER_NAME` | `Register this device as a passkey` | Label for the registration checkbox. |
| `PASSKEY_BEGIN_BURST_COUNT` | `30` | Ceremonies one caller may start per window. A resource guard, not part of the login budget. |
| `PASSKEY_BEGIN_BURST_TIME` | `60` | Window for the above, in seconds. |
**Registering a device.** Log in with your code as usual, tick *Register this
device as a passkey*, and approve the prompt. The TOTP check in that same
submission is what authorises the registration — there is no separate enrolment
token and no CLI command, so a passkey cannot be created without already holding
a valid code.
**Logging in.** Once registered, *Sign in with a passkey* signs you in with a
fingerprint, face, or device PIN instead of typing a code. Failed passkey
attempts count against the same rate-limit budget as wrong codes, so passkeys
cannot be used to sidestep a lockout, and after the limit is reached *every*
method is blocked equally.
> **On signature counters.** Many passkeys (anything synchronised through a
> keychain) report a constant counter, so a counter-based clone check would lock
> users out of their own credentials. Preauth accepts an unchanged counter and
> rejects only one that moves *backwards*. Clone detection is deliberately not a
> property this feature claims — see `SECURITY.md`.
### Public Rate-Limited Access
Preauth can provide rate-limited unauthenticated access to select public
paths. This is useful for exposing public content (e.g., public repositories
in Gitea) without requiring TOTP authentication, while protecting server
resources from bot traffic.
When `PUBLIC_PATHS` is configured, requests to matching paths from
unauthenticated users are allowed through with a separate rate limiter.
Authenticated users bypass the public rate limiter entirely.
| Variable | Default | Description |
|----------|---------|-------------|
| `PUBLIC_PATHS` | `''` (disabled) | Comma-separated path patterns. See below. |
| `PUBLIC_BURST_COUNT` | `100` | Max requests per burst window per IP. |
| `PUBLIC_BURST_TIME` | `60` | Burst window in seconds. |
| `PUBLIC_UPPER_COUNT` | `500` | Max requests per sustained window per IP. |
| `PUBLIC_UPPER_TIME` | `3600` | Sustained window in seconds (1 hour). |
**Path pattern syntax:**
- Patterns are matched against the request path only (query string ignored).
- Patterns must start with `/`.
- `*` matches one or more characters within a single path segment (not crossing `/`).
- `**` matches zero or more characters including `/` (crosses path segments).
- An optional host prefix can restrict a pattern to a specific host
(e.g., `code.example.com/public/**`).
| Pattern | Matches | Does NOT match |
|---------|---------|----------------|
| `/public` | `/public` | `/public/`, `/public/repo` |
| `/public/*` | `/public/repo` | `/public`, `/public/a/b` |
| `/public/**` | `/public/repo`, `/public/a/b/c` | `/public` |
| `host.com/api/**` | `host.com/api/v1/status` | `other.com/api/v1/status` |
**Example:** Allow public access to Gitea's `/public/` paths:
```env
PUBLIC_PATHS=/public/**
PUBLIC_BURST_COUNT=100
PUBLIC_BURST_TIME=60
PUBLIC_UPPER_COUNT=500
PUBLIC_UPPER_TIME=3600
```
When a visitor exceeds the rate limit, they receive a `429 Too Many Requests`
response with a `Retry-After` header. When within limits, they receive a
`200 OK` response (with no `Remote-User` header). Authenticated users receive
`200 OK` with their `Remote-User` header as normal.
### Styling
All UI text and colors are configurable:
| Variable | Default | Description |
|----------|---------|-------------|
| `TITLE` | `Pre-Authentication System` | Page title. |
| `BG_COLOR` | `#029386` | Background color. |
| `FG_COLOR` | `#ffffff` | Foreground (text) color. |
| `ERROR_COLOR` | `#ffb16d` | Error message color. |
| `ID_NAME` | `Session ID` | Label for the ID field. |
| `TOKEN_NAME` | `Authentication Token` | Label for the TOTP field. |
| `SUBMIT_NAME` | `Submit` | Submit button text. |
| `ERROR_MESSAGE` | `Unsuccessful login attempt` | Failed login message. |
| `TEAPOT_TITLE` | `I'm a teapot` | Title when rate-limited (teapot mode). |
| `TEAPOT_MESSAGE` | `I refuse to brew coffee` | Message when rate-limited (teapot mode). |
| `TOO_MANY_TITLE` | `Too many requests` | Title when rate-limited (non-teapot). |
| `TOO_MANY_MESSAGE` | `Try again later` | Message when rate-limited (non-teapot). |
## Architecture
```
Client → Caddy → forward_auth → Preauth listeners → 200/401/418
```
Preauth is entirely event-listener-driven (no controllers). Each request
passes through a priority-ordered chain of listeners:
1. **AcceptListener** (priority 99) — Checks for valid session cookie.
2. **AllowListener** (priority 88) — Checks for valid IP-based session.
3. **PublicAccessListener** (priority 84) — If public paths are configured,
allows rate-limited unauthenticated access to matching paths.
4. **RejectListener** (priority 77) — Rate-limiting gate.
5. **PasskeyListener** (priority 70) — WebAuthn ceremonies, when enabled.
6. **LoginListener** (priority 66) — Processes login attempts.
7. **InterceptListener** (priority 55) — Renders login page or redirects.
8. **SecurityHeadersListener** (response) — Adds security headers.
`PasskeyListener` sits deliberately between the rate-limit gate and the login
handler: **after** `RejectListener`, so a blocked IP never reaches a ceremony;
and **before** `LoginListener`, because that listener treats any POST to the auth
subdomain as a login attempt, and a ceremony request carries no code — it would
otherwise be counted as a failed login and burn rate-limit budget on every
legitimate passkey sign-in.
### Security Model
- **Cookies**: `__Host-` prefixed, `SameSite=Strict`, `Secure`, `HttpOnly`
- **Nonces**: 15-byte random, single-use, 120-second TTL
- **TOTP**: ±1 period leeway (±30 seconds) for clock drift
- **Backup codes**: Case-insensitive, single-use, alphanumeric
- **Rate limiting**: Per-IP, compound sliding window, cannot be disabled
- **Security headers**: CSP, X-Frame-Options, X-Content-Type-Options,
Referrer-Policy, HSTS
- **No cacheable login flow**: The login page, failed logins, redirects,
and rate-limit pages are sent with strict anti-caching headers
(`no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0,
s-maxage=0` plus `Pragma`, `Expires`, `Surrogate-Control`, and
`Vary: *`), and the login form's `fetch()` opts out of the HTTP cache.
Successful (2xx) responses are deliberately excluded — they are
consumed by the proxy's `forward_auth` check and never reach the
browser, so a protected service's own caching is not affected.
Passkey ceremony replies are the one exception: they are the only 2xx
this application returns straight to a browser, so they carry the same
anti-caching headers.
- **Passkeys**: registerable only after a valid TOTP code; challenge is
server-issued and single-use; RP ID is always the base domain; only the
derived `https://` origin is ever accepted; a failed attempt is
indistinguishable from a wrong code and shares its rate-limit budget.
### Cache
Preauth uses a dual-layer cache:
- **APCu** (in-memory) — Fast session and nonce lookups
- **Filesystem** — Persistent storage for container restarts
`MonitorCacheKeys` wraps the PSR-6 cache pool to track changes, so only
modified items are persisted to disk on shutdown.
## Development
### Code Style
This project follows [PSR-12](https://www.php-fig.org/psr/psr-12/) and
includes `php-cs-fixer` as a dev dependency.
```bash
# Check for style violations
vendor/bin/php-cs-fixer fix --dry-run --diff
# Auto-fix
vendor/bin/php-cs-fixer fix
```
### Running Tests
```bash
vendor/bin/phpunit
```
The test suite includes 293 tests with 100% code coverage (lines, methods,
and classes). Both unit tests and functional tests (full HTTP kernel flow)
are included.
### Requirements
- PHP 8.4+
- Composer
- Xdebug (for coverage reports)
## License
MIT — see `license.txt`.
## Project Status
Running in production since June 2024, protecting multiple self-hosted
services. The core authentication gate is complete and battle-tested.
See `ROADMAP.md` for planned features and `CHANGELOG.md` for version history.
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App;
/**
* Shared application constants.
*/
final class AppConstants
{
/**
* Far-future expiration date used for persistent cache items
* (TOTP secrets, backup codes) that should effectively never expire.
* Per PSR-6, if no expiration is set, the implementation may set a
* default — we use this to be explicit.
*/
public const string FAR_FUTURE_DATE = '2999-12-31';
/**
* Maximum length for user-supplied input fields (id, nonce, token).
* Also used for cache key truncation.
*/
public const int MAX_INPUT_LENGTH = 128;
/**
* Marks a response as WebAuthn ceremony output.
*
* A ceremony reply is the only 2xx this application returns straight to a
* browser — every other 2xx is consumed by the reverse proxy's forward_auth
* check. So it is the only one that needs the no-store treatment, and this
* marker is how `SecurityHeadersListener` recognises it without the caching
* policy being duplicated at each site that produces one.
*
* It lives here rather than on a listener because both `PasskeyListener`
* (finish) and `LoginManager` (the registration hand-off) produce them.
*/
public const string PASSKEY_CEREMONY_MARKER = 'X-Preauth-Ceremony';
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace App\CacheWarmer;
use App\Exception\PasskeyConfigurationException;
use App\Service\PasskeyPolicyInterface;
use Override;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
/**
* Fails the build (or container start) when passkeys are enabled in a
* configuration that cannot support them.
*
* `docker/entrypoint.sh` runs `cache:warmup` on every production boot with the
* real environment already injected, so a misconfiguration is caught while the
* container is starting — the deployment aborts — rather than surfacing later as
* a passkey button that silently never works.
*
* The warmer is **not** optional: an optional warmer may be skipped, which would
* let a bad configuration through.
*/
final readonly class PasskeyConfigurationWarmer implements CacheWarmerInterface
{
public function __construct(
private PasskeyPolicyInterface $passkeyPolicy,
) {
}
/**
* @return string[]
*
* @throws PasskeyConfigurationException when passkeys are enabled but unusable
*/
#[Override]
public function warmUp(string $cacheDir, ?string $buildDir = null): array
{
$this->passkeyPolicy->assertConfigurationIsUsable();
return [];
}
/**
* Never optional: skipping this warmer would defeat its entire purpose.
*/
#[Override]
public function isOptional(): bool
{
return false;
}
}
+5 -2
View File
@@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App; namespace App;
@@ -8,8 +9,10 @@ use Psr\Clock\ClockInterface;
use Symfony\Component\DependencyInjection\Attribute\AsAlias; use Symfony\Component\DependencyInjection\Attribute\AsAlias;
#[AsAlias(ClockInterface::class)] #[AsAlias(ClockInterface::class)]
final readonly class Clock implements ClockInterface { final readonly class Clock implements ClockInterface
public function now(): DateTimeImmutable { {
public function now(): DateTimeImmutable
{
return new DateTimeImmutable(); return new DateTimeImmutable();
} }
} }
+15 -5
View File
@@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Command; namespace App\Command;
@@ -6,14 +7,18 @@ namespace App\Command;
use App\PersistCache; use App\PersistCache;
use App\Service\BackupCodeInterface; use App\Service\BackupCodeInterface;
use Psr\Cache\InvalidArgumentException; use Psr\Cache\InvalidArgumentException;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\InvalidArgumentException as ConsoleInvalidArgumentException;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
/** simple console command to generate backup codes /** simple console command to generate backup codes
* usage: php bin/console app:generate-backup-codes [count] */ * usage: php bin/console app:generate-backup-codes [count] */
final class GenerateBackupCodesCommand extends Command { #[AsCommand(name: 'app:generate-backup-codes')]
final class GenerateBackupCodesCommand extends Command
{
public function __construct( public function __construct(
private readonly BackupCodeInterface $manager, private readonly BackupCodeInterface $manager,
private readonly PersistCache $persistCache, private readonly PersistCache $persistCache,
@@ -21,22 +26,27 @@ final class GenerateBackupCodesCommand extends Command {
parent::__construct(); parent::__construct();
} }
protected function configure(): void { protected function configure(): void
$this->setName('app:generate-backup-codes'); {
$this->setDescription('Generate single‑use backup codes') $this->setDescription('Generate single-use backup codes')
->addArgument('count', InputArgument::OPTIONAL, 'Number of codes to generate', 10); ->addArgument('count', InputArgument::OPTIONAL, 'Number of codes to generate', 10);
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
protected function execute(InputInterface $input, OutputInterface $output): int { protected function execute(InputInterface $input, OutputInterface $output): int
{
/* since Kernel::terminate() does not get called, we must boot and persist explicitly */ /* since Kernel::terminate() does not get called, we must boot and persist explicitly */
$this->persistCache->boot(); $this->persistCache->boot();
$count = (int) $input->getArgument('count'); $count = (int) $input->getArgument('count');
if ($count < 1) {
throw new ConsoleInvalidArgumentException('Count must be a positive integer.');
}
$codes = $this->manager->generate($count); $codes = $this->manager->generate($count);
foreach ($codes as $code) { foreach ($codes as $code) {
$output->writeln($code); $output->writeln($code);
} }
$this->persistCache->persist(); $this->persistCache->persist();
return Command::SUCCESS; return Command::SUCCESS;
} }
} }
+143 -9
View File
@@ -1,13 +1,17 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App; namespace App;
use App\Enum\RemoteUserMode;
use App\Enum\UserVerification;
use Psr\Cache\InvalidArgumentException; use Psr\Cache\InvalidArgumentException;
use Psr\Clock\ClockInterface; use Psr\Clock\ClockInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\DependencyInjection\Attribute\Autowire;
final readonly class ConfigBag { final readonly class ConfigBag
{
private ClockInterface $clock; private ClockInterface $clock;
private int $cookieTtl; private int $cookieTtl;
private string $totpUri; private string $totpUri;
@@ -16,6 +20,20 @@ final readonly class ConfigBag {
private string $errorMessage; private string $errorMessage;
private string $teapotTitle; private string $teapotTitle;
private string $tooManyTitle; private string $tooManyTitle;
private RemoteUserMode $remoteUserMode;
private string $remoteUserStatic;
/** @var array<string,string> */
private array $remoteUserMap;
private string $title;
private bool $passkeyEnabled;
private string $passkeyRpName;
private UserVerification $passkeyUserVerification;
private int $passkeyTimeout;
private string $passkeyButtonName;
private string $passkeyRegisterName;
/** Passkey ceremony timeout in milliseconds (WebAuthn default). */
private const int DEFAULT_PASSKEY_TIMEOUT = 60000;
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function __construct( public function __construct(
@@ -28,6 +46,16 @@ final readonly class ConfigBag {
#[Autowire('%app.error_message%')] string $errorMessage, #[Autowire('%app.error_message%')] string $errorMessage,
#[Autowire('%app.teapot_title%')] string $teapotTitle, #[Autowire('%app.teapot_title%')] string $teapotTitle,
#[Autowire('%app.too_many_title%')] string $tooManyTitle, #[Autowire('%app.too_many_title%')] string $tooManyTitle,
#[Autowire('%app.remote_user%')] string $remoteUserMode,
#[Autowire('%app.remote_user_static%')] string $remoteUserStatic,
#[Autowire('%app.remote_user_map%')] string $remoteUserMap,
#[Autowire('%app.title%')] string $title = 'Pre-Authentication System',
#[Autowire('%app.passkey_enabled%')] bool $passkeyEnabled = false,
#[Autowire('%app.passkey_rp_name%')] string $passkeyRpName = '',
#[Autowire('%app.passkey_user_verification%')] string $passkeyUserVerification = 'required',
#[Autowire('%app.passkey_timeout%')] int $passkeyTimeout = self::DEFAULT_PASSKEY_TIMEOUT,
#[Autowire('%app.passkey_button_name%')] string $passkeyButtonName = 'Sign in with a passkey',
#[Autowire('%app.passkey_register_name%')] string $passkeyRegisterName = 'Register this device as a passkey',
) { ) {
$this->clock = $clock; $this->clock = $clock;
$this->cookieTtl = $cookieTtl; $this->cookieTtl = $cookieTtl;
@@ -37,37 +65,143 @@ final readonly class ConfigBag {
$this->errorMessage = $errorMessage; $this->errorMessage = $errorMessage;
$this->teapotTitle = $teapotTitle; $this->teapotTitle = $teapotTitle;
$this->tooManyTitle = $tooManyTitle; $this->tooManyTitle = $tooManyTitle;
$this->remoteUserMode = RemoteUserMode::tryFrom($remoteUserMode) ?? RemoteUserMode::Session;
$this->remoteUserStatic = $remoteUserStatic;
$this->remoteUserMap = $this->parseUserMap($remoteUserMap);
$this->title = $title;
$this->passkeyEnabled = $passkeyEnabled;
$this->passkeyRpName = $passkeyRpName;
$this->passkeyUserVerification = UserVerification::fromConfig($passkeyUserVerification);
$this->passkeyTimeout = $passkeyTimeout > 0 ? $passkeyTimeout : self::DEFAULT_PASSKEY_TIMEOUT;
$this->passkeyButtonName = $passkeyButtonName;
$this->passkeyRegisterName = $passkeyRegisterName;
} }
public function clock(): ClockInterface { /**
* Parse a comma-separated map string ("id1:user1,id2:user2") into an array.
*
* @return array<string,string>
*/
private function parseUserMap(string $map): array
{
if ('' === $map) {
return [];
}
$result = [];
foreach (explode(',', $map) as $pair) {
$parts = explode(':', trim($pair), 2);
if (2 === \count($parts)) {
$result[trim($parts[0])] = trim($parts[1]);
}
}
return $result;
}
public function clock(): ClockInterface
{
return $this->clock; return $this->clock;
} }
public function cookieTtl(): int { public function cookieTtl(): int
{
return $this->cookieTtl; return $this->cookieTtl;
} }
public function totpUri(): string { public function totpUri(): string
{
return $this->totpUri; return $this->totpUri;
} }
public function ipTtl(): ?int { public function ipTtl(): ?int
{
return $this->ipTtl; return $this->ipTtl;
} }
public function teapot(): bool { public function teapot(): bool
{
return $this->teapot; return $this->teapot;
} }
public function errorMessage(): string { public function errorMessage(): string
{
return $this->errorMessage; return $this->errorMessage;
} }
public function teapotTitle(): string { public function teapotTitle(): string
{
return $this->teapotTitle; return $this->teapotTitle;
} }
public function tooManyTitle(): string { public function tooManyTitle(): string
{
return $this->tooManyTitle; return $this->tooManyTitle;
} }
public function remoteUserMode(): RemoteUserMode
{
return $this->remoteUserMode;
}
public function remoteUserStatic(): string
{
return $this->remoteUserStatic;
}
/**
* @return array<string,string>
*/
public function remoteUserMap(): array
{
return $this->remoteUserMap;
}
public function title(): string
{
return $this->title;
}
/**
* Whether the passkey feature is switched on by configuration.
*
* This says nothing about whether the configuration is *usable* — that is
* {@see Service\PasskeyPolicyInterface::isEnabled()}, which also
* requires the central-auth prerequisite (D1).
*/
public function passkeyEnabled(): bool
{
return $this->passkeyEnabled;
}
/** Relying-party name shown in the authenticator prompt; blank falls back to the title. */
public function passkeyRpName(): string
{
return $this->passkeyRpName;
}
/** User-verification requirement; an unrecognised value falls back to `required`. */
public function passkeyUserVerification(): string
{
return $this->passkeyUserVerification->value;
}
/** Ceremony timeout in milliseconds. */
public function passkeyTimeout(): int
{
return $this->passkeyTimeout;
}
/** Label for the "sign in with a passkey" button. */
public function passkeyButtonName(): string
{
return $this->passkeyButtonName;
}
/** Label for the "register this device" checkbox. */
public function passkeyRegisterName(): string
{
return $this->passkeyRegisterName;
}
} }
+49
View File
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Data;
use DateTimeImmutable;
use Webauthn\CredentialRecord;
/**
* A stored passkey: the WebAuthn credential plus the application metadata that
* ties it to a visitor of this gateway.
*
* The credential itself carries the public key and signature counter; the
* metadata here records *whose* passkey it is and when it was used. The identity
* is deliberately read from this record on assertion rather than from the value
* the client returns, which is never trusted.
*/
final readonly class PasskeyCredential
{
public function __construct(
public CredentialRecord $record,
/** The session id this passkey authenticates, as typed at registration. */
public string $identity,
/** Operator-facing description, shown so a user can tell their keys apart. */
public string $label,
public DateTimeImmutable $createdAt,
public ?DateTimeImmutable $lastUsedAt = null,
) {
}
/**
* A copy of this credential with the signature counter and last-used time
* refreshed after a successful assertion.
*
* The counter is only ever observed, never enforced — many passkeys report a
* constant zero, so treating it as a clone signal would lock users out.
*/
public function withUsage(CredentialRecord $updated, DateTimeImmutable $usedAt): self
{
return new self(
$updated,
$this->identity,
$this->label,
$this->createdAt,
$usedAt,
);
}
}
+44 -21
View File
@@ -1,75 +1,98 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Data; namespace App\Data;
use App\AppConstants;
use App\Enum\Scope; use App\Enum\Scope;
use Symfony\Component\HttpFoundation\InputBag; use Symfony\Component\HttpFoundation\InputBag;
/** when scope is IP but ip-access is disabled, scope is to be considered cookie */ /** when scope is IP but ip-access is disabled, scope is to be considered cookie */
final class Payload { final class Payload
{
public string $id; /* session name, identifying who is logging in */ public string $id; /* session name, identifying who is logging in */
public string $token; /* TOTP, typically six digits */ public string $token; /* TOTP, typically six digits */
public string $nonce; /* random unique string, to block duplicate submissions */ public string $nonce; /* random unique string, to block duplicate submissions */
public bool $json; /* should we return json (for the login page) */ public bool $json; /* should we return json (for the login page) */
public Scope $scope; /* type of access being requested */ public Scope $scope; /* type of access being requested */
public static function decode(string $base64url): ?Payload { /**
* The caller ticked "register this device as a passkey".
*
* Carried on the payload rather than handled by the listener, because the
* TOTP check is what authorises registration — so the intent has to reach
* `LoginManager`, which is where that check (and the nonce check) already
* happens. Starting a ceremony any earlier would move nonce validation and
* risk spending it twice.
*/
public bool $register = false;
public static function decode(string $base64url): ?self
{
/* convert the base64url into json string */ /* convert the base64url into json string */
$json = base64_decode(str_pad(strtr($base64url, '-_', '+/'), $base64 = strtr($base64url, '-_', '+/');
strlen($base64url) % 4, '=' $base64 .= str_repeat('=', (4 - \strlen($base64) % 4) % 4);
), true); $json = base64_decode($base64, true);
if ($json) { if ($json) {
/* convert the json string into real data */ /* convert the json string into real data */
$data = json_decode($json); $data = json_decode($json);
if (is_object($data)) { if (\is_object($data)) {
return Payload::create($data); return self::create($data);
} }
} }
return null; return null;
} }
public static function load(InputBag $input): ?Payload { public static function load(InputBag $input): ?self
{
/* convert form data into real data */ /* convert form data into real data */
if ($input->has('username') && $input->has('nonce') && $input->has('totp')) { if ($input->has('username') && $input->has('nonce') && $input->has('totp')) {
return Payload::create((object)[ return self::create((object) [
'id' => $input->get('username'), 'id' => $input->get('username'),
'nonce' => $input->get('nonce'), 'nonce' => $input->get('nonce'),
'token' => $input->get('totp'), 'token' => $input->get('totp'),
'register' => $input->get('register'),
'json' => false, 'json' => false,
]); ]);
} }
return null; return null;
} }
public static function create(object $data): ?Payload { public static function create(object $data): ?self
{
/* if missing required fields id, nonce, or token */ /* if missing required fields id, nonce, or token */
if (strlen(trim($data->id ?? '')) < 1 || if ('' === trim($data->id ?? '')
strlen(trim($data->nonce ?? '')) < 1 || || '' === trim($data->nonce ?? '')
strlen(trim($data->token ?? '')) < 1 || '' === trim($data->token ?? '')
) { ) {
/* returns null as the input is invalid */ /* returns null as the input is invalid */
return null; return null;
} }
/* all input is limited */ /* all input is limited */
$payload = new Payload(); $payload = new self();
$payload->id = mb_substr(trim($data->id), 0, 128); $payload->id = mb_substr(trim($data->id), 0, AppConstants::MAX_INPUT_LENGTH);
$payload->nonce = mb_substr(trim($data->nonce), 0, 128); $payload->nonce = mb_substr(trim($data->nonce), 0, AppConstants::MAX_INPUT_LENGTH);
$payload->json = ($data->json ?? true); $payload->json = ($data->json ?? true);
$payload->register = (bool) ($data->register ?? false);
$payload->scope = Scope::tryFrom($data->scope ?? '') ?? Scope::Cookie; $payload->scope = Scope::tryFrom($data->scope ?? '') ?? Scope::Cookie;
$payload->token = mb_substr(trim($data->token), 0, 128); $payload->token = mb_substr(trim($data->token), 0, AppConstants::MAX_INPUT_LENGTH);
return Payload::constrict($payload); return self::constrict($payload);
} }
public function toString(): string { public function toString(): string
{
return json_encode($this); return json_encode($this);
} }
private static function constrict(Payload $payload): Payload { private static function constrict(self $payload): self
{
/* When scope is None, json will be considered false. */ /* When scope is None, json will be considered false. */
if ($payload->scope === Scope::None) { if (Scope::None === $payload->scope) {
$payload->json = false; $payload->json = false;
} }
+23
View File
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Enum;
/**
* Controls what value is sent in the Remote-User header on auth success.
*/
enum RemoteUserMode: string
{
/** Send the session id (current/default behaviour). */
case Session = 'session';
/** Send a fixed static string for all authenticated requests. */
case Static = 'static';
/** Look up the session id in a configured map and send the mapped value. */
case Mapped = 'mapped';
/** Do not send the Remote-User header at all. */
case None = 'none';
}
+3 -1
View File
@@ -1,10 +1,12 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Enum; namespace App\Enum;
/** scope defines the context of how a session is persisted */ /** scope defines the context of how a session is persisted */
enum Scope: string { enum Scope: string
{
case Cookie = 'cookie'; case Cookie = 'cookie';
case Ip = 'ip'; case Ip = 'ip';
case None = 'none'; case None = 'none';
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Enum;
/**
* User-verification requirement passed to the authenticator at passkey time.
*
* Mirrors the WebAuthn `userVerification` option without leaking the library's
* constants into application configuration.
*/
enum UserVerification: string
{
/** Require a biometric/PIN check (default). */
case Required = 'required';
/** Ask for it, but allow a plain user-presence tap to succeed. */
case Preferred = 'preferred';
/** Never prompt for verification; presence alone is enough. */
case Discouraged = 'discouraged';
/**
* Parse a configured value, falling back to the safest option.
*
* An unrecognised value must never silently weaken the requirement, so the
* fallback is the strictest case rather than the most permissive one.
*/
public static function fromConfig(string $value): self
{
return self::tryFrom(trim($value)) ?? self::Required;
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Exception;
use RuntimeException;
/**
* Thrown when passkeys are enabled in a configuration that cannot support them.
*
* This is deliberately fatal: the alternative is a feature that appears to be
* switched on but cannot complete a single ceremony, which surfaces to the user
* as "my passkey stopped working" rather than as a deployment error.
*
* Raised during cache warm-up so that a misconfigured container fails to start
* instead of failing later, in a browser.
*/
final class PasskeyConfigurationException extends RuntimeException
{
}
+10 -4
View File
@@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App; namespace App;
@@ -9,13 +10,15 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Kernel as BaseKernel; use Symfony\Component\HttpKernel\Kernel as BaseKernel;
final class Kernel extends BaseKernel { class Kernel extends BaseKernel
{
use MicroKernelTrait; use MicroKernelTrait;
private PersistCache $persistCache; private PersistCache $persistCache;
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function boot(): void { public function boot(): void
{
parent::boot(); parent::boot();
$this->persistCache = $this->container->get(PersistCache::class); $this->persistCache = $this->container->get(PersistCache::class);
@@ -23,9 +26,12 @@ final class Kernel extends BaseKernel {
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function terminate(Request $request, Response $response): void { public function terminate(Request $request, Response $response): void
{
try {
$this->persistCache->persist(); $this->persistCache->persist();
} finally {
parent::terminate($request, $response); parent::terminate($request, $response);
} }
} }
}
+33 -15
View File
@@ -1,45 +1,63 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Listener; namespace App\Listener;
use App\ConfigBag;
use App\Service\DomainInterface; use App\Service\DomainInterface;
use App\Trait\CookieNameTrait; use App\Trait\CookieNameTrait;
use App\Trait\HasLoggerTrait; use App\Trait\HasLoggerTrait;
use App\Trait\StringTrait; use App\Trait\StringTrait;
use Psr\Cache\CacheItemPoolInterface; use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException; use Psr\Cache\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Attribute\Target;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener; use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\Event\RequestEvent;
final readonly class AcceptListener { final readonly class AcceptListener
{
use CookieNameTrait; use CookieNameTrait;
use HasLoggerTrait; use HasLoggerTrait;
use StringTrait; use StringTrait;
public function __construct( public function __construct(
private CacheItemPoolInterface $sessionCache, #[Target('sessionCache')] private CacheItemPoolInterface $sessionCache,
private DomainInterface $domainManager, private DomainInterface $domainManager,
) {} private ConfigBag $config,
) {
}
/** @throws InvalidArgumentException */
#[AsEventListener(priority: 99)] #[AsEventListener(priority: 99)]
public function onKernelRequest(RequestEvent $event): void { public function onKernelRequest(RequestEvent $event): void
{
/* check if they sent the correct preauth cookie */ /* check if they sent the correct preauth cookie */
$cookieName = $this->domainManager->authBase() ?$this->authCookieName() : $this->cookieName(); $cookieName = $this->sessionCookieName($this->domainManager);
if ($event->getRequest()->cookies->has($cookieName)) { if (!$event->getRequest()->cookies->has($cookieName)) {
return;
}
$cookie = $event->getRequest()->cookies->get($cookieName); $cookie = $event->getRequest()->cookies->get($cookieName);
$cookieKey = $this->makeCacheKey("cookie_$cookie"); $cookieKey = $this->makeCacheKey("cookie_$cookie");
if ($cookie && $this->sessionCache->hasItem($cookieKey)) {
try {
if (!$cookie || !$this->sessionCache->hasItem($cookieKey)) {
return;
}
/* cookie sent corresponds to valid existing session */ /* cookie sent corresponds to valid existing session */
$id = $this->sessionCache->getItem($cookieKey)->get(); $item = $this->sessionCache->getItem($cookieKey);
if (!$item->isHit()) {
/* race condition: item was removed between hasItem and getItem */
return;
}
$id = $item->get();
$this->logger->debug("has valid cookie-session: $id"); $this->logger->debug("has valid cookie-session: $id");
$event->setResponse(new Response("hi $id", headers: [ $event->setResponse($this->authSuccessResponse($id, $this->config));
'Content-Type' => 'text/plain', } catch (InvalidArgumentException $e) {
'Remote-User' => $id, /* cache failure — fail closed (don't authenticate) */
])); $this->logger->error("cache error in AcceptListener: {$e->getMessage()}");
}
} }
} }
} }
+30 -14
View File
@@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Listener; namespace App\Listener;
@@ -8,33 +9,48 @@ use App\Trait\HasLoggerTrait;
use App\Trait\StringTrait; use App\Trait\StringTrait;
use Psr\Cache\CacheItemPoolInterface; use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException; use Psr\Cache\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Attribute\Target;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener; use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\Event\RequestEvent;
final readonly class AllowListener { final readonly class AllowListener
{
use HasLoggerTrait; use HasLoggerTrait;
use StringTrait; use StringTrait;
public function __construct( public function __construct(
private CacheItemPoolInterface $sessionCache, #[Target('sessionCache')] private CacheItemPoolInterface $sessionCache,
private ConfigBag $config, private ConfigBag $config,
) {} ) {
}
/** @throws InvalidArgumentException */
#[AsEventListener(priority: 88)] #[AsEventListener(priority: 88)]
public function onKernelRequest(RequestEvent $event): void { public function onKernelRequest(RequestEvent $event): void
if ($this->config->ipTtl() > 0) { {
if ($this->config->ipTtl() <= 0) {
return;
}
$ipKey = $this->makeCacheKey("ip_{$event->getRequest()->getClientIp()}"); $ipKey = $this->makeCacheKey("ip_{$event->getRequest()->getClientIp()}");
if ($this->sessionCache->hasItem($ipKey)) {
try {
if (!$this->sessionCache->hasItem($ipKey)) {
return;
}
/* ip address corresponds to valid existing session */ /* ip address corresponds to valid existing session */
$id = $this->sessionCache->getItem($ipKey)->get(); $item = $this->sessionCache->getItem($ipKey);
if (!$item->isHit()) {
/* race condition: item was removed between hasItem and getItem */
return;
}
$id = $item->get();
$this->logger->debug("has valid ip-session: $id"); $this->logger->debug("has valid ip-session: $id");
$event->setResponse(new Response("hi $id", headers: [ $event->setResponse($this->authSuccessResponse($id, $this->config));
'Content-Type' => 'text/plain', } catch (InvalidArgumentException $e) {
'Remote-User' => $id, /* cache failure — fail closed (don't authenticate) */
])); $this->logger->error("cache error in AllowListener: {$e->getMessage()}");
}
} }
} }
} }
+29 -16
View File
@@ -1,10 +1,12 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Listener; namespace App\Listener;
use App\ConfigBag; use App\ConfigBag;
use App\Service\DomainInterface; use App\Service\DomainInterface;
use App\Service\PasskeyPolicyInterface;
use App\Trait\CookieNameTrait; use App\Trait\CookieNameTrait;
use App\Trait\HasLoggerTrait; use App\Trait\HasLoggerTrait;
use App\Trait\MakeNonceTrait; use App\Trait\MakeNonceTrait;
@@ -18,7 +20,8 @@ use Twig\Error\LoaderError;
use Twig\Error\RuntimeError; use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError; use Twig\Error\SyntaxError;
final readonly class InterceptListener { final readonly class InterceptListener
{
use CookieNameTrait; use CookieNameTrait;
use HasLoggerTrait; use HasLoggerTrait;
use MakeNonceTrait; use MakeNonceTrait;
@@ -27,48 +30,58 @@ final readonly class InterceptListener {
private ConfigBag $config, private ConfigBag $config,
private DomainInterface $domainManager, private DomainInterface $domainManager,
private Environment $twig, private Environment $twig,
) {} private PasskeyPolicyInterface $passkeyPolicy,
) {
}
/** @throws InvalidArgumentException|RuntimeError|SyntaxError|LoaderError */ /** @throws InvalidArgumentException|RuntimeError|SyntaxError|LoaderError */
#[AsEventListener(priority: 55)] #[AsEventListener(priority: 55)]
public function onKernelRequest(RequestEvent $event): void { public function onKernelRequest(RequestEvent $event): void
{
/* by this point, we know that the request we have is: /* by this point, we know that the request we have is:
* not already authorized, nor already rate-limited, * not already authorized, nor already rate-limited,
* nor submitting login credentials; so redirect or present the login page now */ * nor submitting login credentials; so redirect or present the login page now */
if ($this->domainManager->getAuthSubdomain() !== $event->getRequest()->getHost() && if ($this->domainManager->getAuthSubdomain() !== $event->getRequest()->getHost()
$this->domainManager->matchesAuth($event->getRequest()->getHost()) && $this->domainManager->matchesAuth($event->getRequest()->getHost())
) { ) {
/* host matches base-domain of auth, but not on auth subdomain, redirect */ /* host matches base-domain of auth, but not on auth subdomain, redirect */
$query = http_build_query(['return' => $event->getRequest()->getUri()]); $query = http_build_query(['return' => $event->getRequest()->getUri()]);
$event->setResponse(new Response('', Response::HTTP_SEE_OTHER, $event->setResponse(new Response(
['Location' => "https://{$this->domainManager->getAuthSubdomain()}/?$query"] '',
Response::HTTP_SEE_OTHER,
['Location' => "https://{$this->domainManager->getAuthSubdomain()}/?$query"],
)); ));
} else { } else {
$this->logger->debug("presenting login page: {$event->getRequest()->getClientIp()}"); $this->logger->debug("presenting login page: {$event->getRequest()->getClientIp()}");
$content = $this->twig->render('login.html.twig', [ $content = $this->twig->render('login.html.twig', [
'nonce' => $this->makeNonce(), 'nonce' => $this->makeNonce(),
'post' => $this->domainManager->getAuthSubdomain() === $event->getRequest()->getHost(), 'post' => $this->domainManager->getAuthSubdomain() === $event->getRequest()->getHost(),
/* only offered when the feature is usable *for this request* — the
* same computation that decides whether the ceremony endpoints
* will answer, so the UI cannot offer what the server refuses */
'passkeys' => $this->passkeyPolicy->isAvailableFor($event->getRequest()),
]); ]);
$hasCookie = (bool) $event->getRequest()->cookies->get( $hasCookie = (bool) $event->getRequest()->cookies->get(
$this->domainManager->authBase() ? $this->authCookieName() : $this->cookieName() $this->sessionCookieName($this->domainManager),
); );
$event->setResponse($this->pruneInvalidCookie(new Response($content, $event->setResponse($this->pruneInvalidCookie(new Response(
Response::HTTP_UNAUTHORIZED, ['Content-Type' => 'text/html'] $content,
Response::HTTP_UNAUTHORIZED,
['Content-Type' => 'text/html'],
), $hasCookie, $event->getRequest()->getHost())); ), $hasCookie, $event->getRequest()->getHost()));
} }
} }
private function pruneInvalidCookie(Response $response, bool $hasCookie, string $host): Response { private function pruneInvalidCookie(Response $response, bool $hasCookie, string $host): Response
{
if ($hasCookie) { if ($hasCookie) {
/* input here must match LoginListener::setCookie() */
$response->headers->clearCookie( $response->headers->clearCookie(
$this->domainManager->authBase() ? $this->authCookieName() : $this->cookieName(), $this->sessionCookieName($this->domainManager),
'/', '/',
/* if using central auth, only set the domain if the host matches */ $this->sessionCookieDomain($this->domainManager, $host),
$this->domainManager->matchesAuth($host) ? $this->domainManager->authBase() : null,
true, true,
true, true,
Cookie::SAMESITE_STRICT Cookie::SAMESITE_STRICT,
); );
} }
+33 -10
View File
@@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Listener; namespace App\Listener;
@@ -7,6 +8,7 @@ use App\ConfigBag;
use App\Data\Payload; use App\Data\Payload;
use App\Service\DomainInterface; use App\Service\DomainInterface;
use App\Service\LoginInterface; use App\Service\LoginInterface;
use App\Service\PasskeyPolicyInterface;
use App\Trait\CookieNameTrait; use App\Trait\CookieNameTrait;
use App\Trait\HasLoggerTrait; use App\Trait\HasLoggerTrait;
use App\Trait\MakeNonceTrait; use App\Trait\MakeNonceTrait;
@@ -23,7 +25,17 @@ use Twig\Error\LoaderError;
use Twig\Error\RuntimeError; use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError; use Twig\Error\SyntaxError;
final readonly class LoginListener { /**
* Handles login attempts via X-Preauth header (AJAX) or POST form submission.
*
* CSRF Protection: The nonce field serves as CSRF protection for the POST form
* path. Nonces are server-generated, single-use, and have a 120-second TTL.
* An attacker cannot forge a POST request without first loading the login page
* to obtain a valid nonce, which requires being on the auth subdomain.
* For the AJAX (header) path, the nonce is embedded in the base64url payload.
*/
final readonly class LoginListener
{
use CookieNameTrait; use CookieNameTrait;
use HasLoggerTrait; use HasLoggerTrait;
use MakeNonceTrait; use MakeNonceTrait;
@@ -37,13 +49,15 @@ final readonly class LoginListener {
private DomainInterface $domainManager, private DomainInterface $domainManager,
private LoginInterface $loginManager, private LoginInterface $loginManager,
private ConfigBag $config, private ConfigBag $config,
private PasskeyPolicyInterface $passkeyPolicy,
) { ) {
$this->rateLimiter = $rateLimiter; $this->rateLimiter = $rateLimiter;
} }
/** @throws InvalidArgumentException|LoaderError|RuntimeError|SyntaxError */ /** @throws InvalidArgumentException|LoaderError|RuntimeError|SyntaxError */
#[AsEventListener(priority: 66)] #[AsEventListener(priority: 66)]
public function onKernelRequest(RequestEvent $event): void { public function onKernelRequest(RequestEvent $event): void
{
$payload = null; $payload = null;
$response = null; $response = null;
@@ -51,8 +65,8 @@ final readonly class LoginListener {
/* if request contains our "X-Preauth" header */ /* if request contains our "X-Preauth" header */
$data = $event->getRequest()->headers->get($this->headerName()); $data = $event->getRequest()->headers->get($this->headerName());
$payload = Payload::decode($data); $payload = Payload::decode($data);
} else if ($event->getRequest()->isMethod(Request::METHOD_POST) && } elseif ($event->getRequest()->isMethod(Request::METHOD_POST)
$this->domainManager->getAuthSubdomain() === $event->getRequest()->getHost() && $this->domainManager->getAuthSubdomain() === $event->getRequest()->getHost()
) { ) {
/* if request is a POST to the auth-subdomain */ /* if request is a POST to the auth-subdomain */
$payload = Payload::load($event->getRequest()->getPayload()); $payload = Payload::load($event->getRequest()->getPayload());
@@ -68,6 +82,7 @@ final readonly class LoginListener {
/* token or backup-code authentication was successful */ /* token or backup-code authentication was successful */
if ($response) { if ($response) {
$event->setResponse($response); $event->setResponse($response);
return; return;
} }
} }
@@ -76,18 +91,25 @@ final readonly class LoginListener {
$limitReached = $this->logFailure($event->getRequest()); $limitReached = $this->logFailure($event->getRequest());
$this->logger->debug("logging failure for: {$event->getRequest()->getClientIp()}"); $this->logger->debug("logging failure for: {$event->getRequest()->getClientIp()}");
$event->setResponse($this->makeFailedResponse($limitReached, $payload->json ?? true, $event->setResponse($this->makeFailedResponse(
$event->getRequest()->getHost(), $this->makeCacheKey($payload ? $payload->id : '') $limitReached,
$payload?->json ?? true,
$event->getRequest()->getHost(),
$this->makeCacheKey($payload?->id ?? ''),
$event->getRequest(),
)); ));
} }
private function logFailure(Request $request): bool { private function logFailure(Request $request): bool
{
$limiter = $this->rateLimiter->create($request->getClientIp()); $limiter = $this->rateLimiter->create($request->getClientIp());
return ($limiter->consume(1)->getRemainingTokens() < 1);
return $limiter->consume(1)->getRemainingTokens() < 1;
} }
/** @throws InvalidArgumentException|RuntimeError|SyntaxError|LoaderError */ /** @throws InvalidArgumentException|RuntimeError|SyntaxError|LoaderError */
private function makeFailedResponse(bool $limited, bool $json, string $host, string $username): Response { private function makeFailedResponse(bool $limited, bool $json, string $host, string $username, Request $request): Response
{
if ($limited) { if ($limited) {
$status = $this->config->teapot() ? Response::HTTP_I_AM_A_TEAPOT $status = $this->config->teapot() ? Response::HTTP_I_AM_A_TEAPOT
: Response::HTTP_TOO_MANY_REQUESTS; : Response::HTTP_TOO_MANY_REQUESTS;
@@ -102,6 +124,7 @@ final readonly class LoginListener {
'nonce' => $this->makeNonce(), 'nonce' => $this->makeNonce(),
'post' => $this->domainManager->getAuthSubdomain() === $host, 'post' => $this->domainManager->getAuthSubdomain() === $host,
'username' => $username, 'username' => $username,
'passkeys' => $this->passkeyPolicy->isAvailableFor($request),
]; ];
if ($json) { if ($json) {
@@ -112,6 +135,6 @@ final readonly class LoginListener {
$content = $this->twig->render('login.html.twig', $answer); $content = $this->twig->render('login.html.twig', $answer);
} }
return new Response($content, $status, ["Content-Type" => $contentType]); return new Response($content, $status, ['Content-Type' => $contentType]);
} }
} }
+278
View File
@@ -0,0 +1,278 @@
<?php
declare(strict_types=1);
namespace App\Listener;
use App\AppConstants;
use App\ConfigBag;
use App\Enum\Scope;
use App\Service\DomainInterface;
use App\Service\PasskeyInterface;
use App\Service\PasskeyPolicyInterface;
use App\Service\SessionIssuerInterface;
use App\Trait\HasLoggerTrait;
use App\Trait\MakeNonceTrait;
use App\Trait\StringTrait;
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Attribute\Target;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\RateLimiter\RateLimiterFactoryInterface;
/**
* Serves the passkey ceremonies.
*
* **Priority 70 — the whole design turns on this number.**
*
* - *After* `RejectListener` (77), so a rate-limited IP never reaches this code.
* Passkeys cannot be used to sidestep a lockout; that is decision D3.
* - *Before* `LoginListener` (66), which is essential rather than tidy:
* `LoginListener` treats **any** POST to the auth subdomain as a login attempt,
* and a ceremony `finish` body has no `username`/`totp`, so `Payload::load()`
* returns null and the request would be scored as a failed login — burning a
* rate-limit token for every legitimate passkey login.
*
* **Three operations, not four.** `register-begin` is deliberately *absent*: a
* registration ceremony may only be started after a valid TOTP code, which is
* presented to `LoginManager` as part of the form submission. `LoginManager`
* therefore starts that ceremony and returns its options with the login
* response. Exposing `register-begin` here would be a way to obtain a challenge
* **without proving anything**, which is the vulnerability rather than the
* feature — there is no session cookie to check at that point either, since the
* whole flow is what *produces* the session.
*
* **Every** request carrying the dispatch header gets a response, including
* malformed ones. Falling through would let `InterceptListener` render HTML to a
* `fetch()` caller.
*/
final readonly class PasskeyListener
{
use HasLoggerTrait;
use MakeNonceTrait;
use StringTrait;
/**
* Marks a request as a ceremony call, and its value selects the operation.
*
* A distinct header rather than overloading `X-Preauth`: that one carries a
* base64url `Payload` and is parsed as such.
*/
public const string HEADER = 'X-Preauth-Passkey';
public const string BEGIN_LOGIN = 'login-begin';
public const string FINISH_LOGIN = 'login-finish';
public const string FINISH_REGISTER = 'register-finish';
private RateLimiterFactoryInterface $beginLimiter;
private RateLimiterFactoryInterface $loginLimiter;
public function __construct(
#[Target('passkey_begin_burst')] RateLimiterFactoryInterface $beginLimiter,
#[Target('login_limiter')] RateLimiterFactoryInterface $loginLimiter,
private PasskeyInterface $passkeys,
private PasskeyPolicyInterface $policy,
private SessionIssuerInterface $sessionIssuer,
private DomainInterface $domainManager,
private ConfigBag $config,
) {
$this->beginLimiter = $beginLimiter;
$this->loginLimiter = $loginLimiter;
}
/**
* @throws InvalidArgumentException
*/
#[AsEventListener(priority: 70)]
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
$operation = $request->headers->get(self::HEADER);
if (null === $operation) {
return;
}
/* Ceremonies exist only on the auth subdomain. Elsewhere the header is
* ignored entirely, so this listener cannot be used to probe other hosts. */
if ($this->domainManager->getAuthSubdomain() !== $request->getHost()) {
return;
}
$event->setResponse($this->dispatch($operation, $request));
}
private function dispatch(string $operation, Request $request): Response
{
/* not available => behave as if the feature does not exist */
if (!$this->policy->isAvailableFor($request)) {
return $this->ceremonyResponse($this->error('Passkeys are not available.', $request));
}
return $this->ceremonyResponse(match ($operation) {
self::BEGIN_LOGIN => $this->beginLogin($request),
self::FINISH_LOGIN => $this->finishLogin($request),
self::FINISH_REGISTER => $this->finishRegistration($request),
default => $this->error('Unknown passkey operation.', $request),
});
}
private function beginLogin(Request $request): Response
{
if ($limit = $this->beginBurstExceeded($request)) {
return $limit;
}
return $this->json($this->passkeys->beginLogin());
}
private function finishLogin(Request $request): Response
{
$credential = $this->passkeys->finishLogin($this->body($request));
if (null === $credential) {
/* A failed ceremony consumes the same budget as a wrong TOTP code
* (D3), so passkey guesses cannot outpace code guesses. */
return $this->failure($request);
}
$this->logger->debug("passkey login succeeded for: {$credential->identity}");
return $this->sessionIssuer->issue($credential->identity, Scope::Cookie, $request, true);
}
/**
* The ceremony was authorised by the TOTP-gated hand-off in `LoginManager`,
* so the capability here is the single-use `ceremonyId` itself: it is
* server-issued, stored against the identity that passed the check, and
* consumed on use.
*/
private function finishRegistration(Request $request): Response
{
$credential = $this->passkeys->finishRegistration($this->body($request));
if (null === $credential) {
return $this->failure($request);
}
$this->logger->debug("passkey registered for: {$credential->identity}");
return $this->sessionIssuer->issue($credential->identity, Scope::Cookie, $request, true);
}
/**
* Bounds how many ceremonies one caller can start.
*
* A resource guard, not the login budget: a legitimate `begin` must not spend
* failure budget, but an unbounded `begin` could fill the ceremony cache.
*/
private function beginBurstExceeded(Request $request): ?Response
{
$limit = $this->beginLimiter->create((string) $request->getClientIp())->consume(1);
if ($limit->isAccepted()) {
return null;
}
$retryAfter = max(1, $limit->getRetryAfter()->getTimestamp() - time());
$this->logger->debug("passkey begin rate-limited: {$request->getClientIp()}");
$response = $this->error('Too many passkey attempts, please slow down.', $request);
$response->setStatusCode(Response::HTTP_TOO_MANY_REQUESTS);
$response->headers->set('Retry-After', (string) $retryAfter);
return $response;
}
/**
* A failed ceremony is indistinguishable from a wrong TOTP code, and spends
* the same shared budget — including the same 418/429 outcome when exhausted.
*/
private function failure(Request $request): Response
{
$limited = $this->loginLimiter
->create((string) $request->getClientIp())
->consume(1)
->getRemainingTokens() < 1;
$this->logger->debug("passkey ceremony failed for: {$request->getClientIp()}");
if ($limited) {
$response = $this->error(
$this->config->teapot() ? $this->config->teapotTitle() : $this->config->tooManyTitle(),
$request,
);
$response->setStatusCode(
$this->config->teapot() ? Response::HTTP_I_AM_A_TEAPOT : Response::HTTP_TOO_MANY_REQUESTS,
);
return $response;
}
$response = $this->error($this->config->errorMessage(), $request);
$response->setStatusCode(Response::HTTP_UNAUTHORIZED);
return $response;
}
/**
* Mark a reply as ceremony output so the no-store policy can find it.
*
* These are the only browser-facing 2xx responses this application produces,
* and `SecurityHeadersListener` otherwise assumes any 2xx is consumed by
* `forward_auth` and leaves it cacheable.
*/
private function ceremonyResponse(Response $response): Response
{
$response->headers->set(AppConstants::PASSKEY_CEREMONY_MARKER, '1');
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* A JSON error carrying a fresh nonce and the same shape the login page
* expects, so the caller can fall back to the TOTP form without a reload.
*
* @throws InvalidArgumentException
*/
private function error(string $message, Request $request): Response
{
return new Response(
(string) json_encode([
'message' => $message,
'nonce' => $this->makeNonce(),
'post' => $this->domainManager->getAuthSubdomain() === $request->getHost(),
'username' => '',
]),
Response::HTTP_UNAUTHORIZED,
);
}
/**
* @param array<string,mixed> $payload
*/
private function json(array $payload): Response
{
return new Response((string) json_encode($payload), Response::HTTP_OK);
}
/**
* @return array<string,mixed>
*/
private function body(Request $request): array
{
$raw = $request->getContent();
if ('' === $raw) {
return [];
}
$decoded = json_decode($raw, true);
return \is_array($decoded) ? $decoded : [];
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace App\Listener;
use App\Service\DomainInterface;
use App\Service\PublicPathMatcherInterface;
use App\Trait\HasLoggerTrait;
use Symfony\Component\DependencyInjection\Attribute\Target;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\RateLimiter\RateLimiterFactoryInterface;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
/**
* Allows rate-limited unauthenticated access to configured public paths.
*
* Runs at priority 84 — after AcceptListener (99) and AllowListener (88)
* so authenticated users bypass this listener entirely, but before
* RejectListener (77) and LoginListener (66) so public traffic is not
* subject to the login rate limiter.
*
* When the request path matches a configured public path pattern:
* - If within rate limit → 200 OK (no Remote-User header)
* - If over rate limit → 429 Too Many Requests with Retry-After header
*
* Non-matching paths fall through to the normal auth flow.
*/
final readonly class PublicAccessListener
{
use HasLoggerTrait;
private RateLimiterFactoryInterface $rateLimiter;
public function __construct(
private PublicPathMatcherInterface $pathMatcher,
private DomainInterface $domainManager,
private Environment $twig,
#[Target('public_limiter')] RateLimiterFactoryInterface $rateLimiter,
) {
$this->rateLimiter = $rateLimiter;
}
/** @throws SyntaxError|RuntimeError|LoaderError */
#[AsEventListener(priority: 84)]
public function onKernelRequest(RequestEvent $event): void
{
if ($this->pathMatcher->isEmpty()) {
return;
}
$request = $event->getRequest();
$host = $request->getHost();
$path = $request->getPathInfo();
// Never treat the auth subdomain itself as public
if ($this->domainManager->getAuthSubdomain() === $host) {
return;
}
if (!$this->pathMatcher->matches($host, $path)) {
return;
}
// Path is public — apply rate limiting
$limiter = $this->rateLimiter->create($request->getClientIp());
$limit = $limiter->consume(1);
if ($limit->isAccepted()) {
$this->logger->debug("public access granted: {$request->getClientIp()} -> $path");
$event->setResponse(new Response(
'',
Response::HTTP_OK,
[
'Content-Type' => 'text/plain',
'Retry-After' => (string) $limit->getRemainingTokens(),
],
));
} else {
$retryAfter = $limit->getRetryAfter()?->getTimestamp() - time();
$retryAfter = max(1, $retryAfter);
$this->logger->debug("public access rate-limited: {$request->getClientIp()} -> $path");
$html = $this->twig->render('error.html.twig');
$event->setResponse(new Response(
$html,
Response::HTTP_TOO_MANY_REQUESTS,
[
'Content-Type' => 'text/html',
'Retry-After' => (string) $retryAfter,
],
));
}
}
}
+11 -6
View File
@@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Listener; namespace App\Listener;
@@ -8,15 +9,16 @@ use App\Trait\HasLoggerTrait;
use App\Trait\StringTrait; use App\Trait\StringTrait;
use Symfony\Component\DependencyInjection\Attribute\Target; use Symfony\Component\DependencyInjection\Attribute\Target;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener; use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\RateLimiter\RateLimiterFactoryInterface; use Symfony\Component\RateLimiter\RateLimiterFactoryInterface;
use Twig\Environment; use Twig\Environment;
use Twig\Error\LoaderError; use Twig\Error\LoaderError;
use Twig\Error\RuntimeError; use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError; use Twig\Error\SyntaxError;
final readonly class RejectListener { final readonly class RejectListener
{
use HasLoggerTrait; use HasLoggerTrait;
use StringTrait; use StringTrait;
@@ -32,15 +34,18 @@ final readonly class RejectListener {
/** @throws SyntaxError|RuntimeError|LoaderError */ /** @throws SyntaxError|RuntimeError|LoaderError */
#[AsEventListener(priority: 77)] #[AsEventListener(priority: 77)]
public function onKernelRequest(RequestEvent $event): void { public function onKernelRequest(RequestEvent $event): void
{
/* check if they have made too many failed login attempts */ /* check if they have made too many failed login attempts */
$limiter = $this->rateLimiter->create($event->getRequest()->getClientIp()); $limiter = $this->rateLimiter->create($event->getRequest()->getClientIp());
if ($limiter->consume(0)->getRemainingTokens() < 1) { if ($limiter->consume(0)->getRemainingTokens() < 1) {
$this->logger->debug("already blocked: {$event->getRequest()->getClientIp()}"); $this->logger->debug("already blocked: {$event->getRequest()->getClientIp()}");
$html = $this->twig->render('error.html.twig'); $html = $this->twig->render('error.html.twig');
$event->setResponse(new Response($html, ($this->config->teapot() $event->setResponse(new Response(
? Response::HTTP_I_AM_A_TEAPOT : Response::HTTP_TOO_MANY_REQUESTS), $html,
['Content-Type' => 'text/html'] $this->config->teapot()
? Response::HTTP_I_AM_A_TEAPOT : Response::HTTP_TOO_MANY_REQUESTS,
['Content-Type' => 'text/html'],
)); ));
} }
} }
+116
View File
@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace App\Listener;
use App\AppConstants;
use App\Service\DomainInterface;
use App\Service\PasskeyPolicyInterface;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
/**
* Adds security-related HTTP response headers to all responses.
* These headers help protect against XSS, clickjacking, MIME-type
* sniffing, and referrer leakage.
*/
final readonly class SecurityHeadersListener
{
public function __construct(
private DomainInterface $domainManager,
private PasskeyPolicyInterface $passkeyPolicy,
) {
}
#[AsEventListener(priority: 0)]
public function onKernelResponse(ResponseEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$response = $event->getResponse();
$headers = $response->headers;
/* prevent MIME-type sniffing */
$headers->set('X-Content-Type-Options', 'nosniff');
/* prevent clickjacking — this app is never framed */
$headers->set('X-Frame-Options', 'DENY');
/* control referrer information sent to other sites */
$headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
/* Content-Security-Policy — the login page uses inline styles
* and scripts (via Twig includes), so we allow 'unsafe-inline'
* for those. No external resources are loaded.
*
* When subdomain redirection is off (or the request is not on
* the auth subdomain), the login form is served inline on the
* protected host and submission is performed via a same-origin
* fetch() call in _script.html.twig. That fetch is blocked by
* the default 'none' policy, so we add connect-src 'self' only
* in that case — the least privilege needed to make the form
* work. On the auth subdomain the form POSTs normally and no
* inline script is included, so the stricter policy applies. */
$inlineScript = $this->domainManager->getAuthSubdomain() !== $event->getRequest()->getHost();
$csp = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline';";
/* `publickey-credentials-get`/`-create` do NOT fall back to default-src,
* so without these directives the browser refuses the ceremony even
* though the script itself is allowed to run. `connect-src 'self'` is
* needed in both modes here, because the passkey flow always talks to
* the server with fetch(). */
if ($this->passkeyPolicy->isAvailableFor($event->getRequest())) {
$csp .= " connect-src 'self'; publickey-credentials-get 'self'; publickey-credentials-create 'self';";
} elseif ($inlineScript) {
$csp .= " connect-src 'self';";
}
$headers->set('Content-Security-Policy', $csp);
/* HSTS — enforce HTTPS for one year (app is designed for HTTPS behind a proxy) */
$headers->set('Strict-Transport-Security', 'max-age=31536000');
/* Prevent any part of the login flow from being cached: the login
* page, failed logins, redirects, and rate-limit/error pages must
* never be stored or replayed by the browser or an intermediate
* cache — older Safari builds in particular may otherwise resurrect
* a stale pre-auth response, appearing to log the user out after a
* refresh or showing a previous session after logging in again.
*
* Only non-2xx responses are touched: the 2xx responses that grant
* access ("already authenticated" or public) are consumed by the
* reverse proxy's forward_auth check before reaching the browser,
* and the protected service's own cache headers must remain
* untouched.
*
* A ceremony reply is the exception that proves the rule: it is a 2xx
* that goes straight to the browser, because the auth subdomain has no
* forward_auth in front of it. Left alone it would be cacheable, so a
* browser could replay a stale challenge. `PasskeyListener` marks those
* responses and the marker is stripped here. */
if (!$response->isSuccessful()) {
$this->applyNoStore($headers);
return;
}
if ($headers->has(AppConstants::PASSKEY_CEREMONY_MARKER)) {
$headers->remove(AppConstants::PASSKEY_CEREMONY_MARKER);
$this->applyNoStore($headers);
}
}
private function applyNoStore(ResponseHeaderBag $headers): void
{
$headers->set('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0, s-maxage=0');
$headers->set('Pragma', 'no-cache');
$headers->set('Expires', '0');
$headers->set('Surrogate-Control', 'no-store');
$headers->set('Vary', '*');
}
}
+57 -30
View File
@@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App; namespace App;
@@ -10,7 +11,8 @@ use Psr\Cache\InvalidArgumentException;
/* we must *NOT* store the key-list item or values within this object /* we must *NOT* store the key-list item or values within this object
* because it can change from outside this object instance */ * because it can change from outside this object instance */
final readonly class MonitorCacheKeys implements CacheItemPoolInterface { final readonly class MonitorCacheKeys implements CacheItemPoolInterface
{
private const string KEY_LIST = '__key_list'; private const string KEY_LIST = '__key_list';
private const string CHANGE_LIST = '__chg_list'; private const string CHANGE_LIST = '__chg_list';
public const int UPDATED = 1; public const int UPDATED = 1;
@@ -19,7 +21,8 @@ final readonly class MonitorCacheKeys implements CacheItemPoolInterface {
private CacheItemPoolInterface $cache; private CacheItemPoolInterface $cache;
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function __construct(CacheItemPoolInterface $cache) { public function __construct(CacheItemPoolInterface $cache)
{
$this->cache = $cache; $this->cache = $cache;
$items = $cache->getItems([self::KEY_LIST, self::CHANGE_LIST]); $items = $cache->getItems([self::KEY_LIST, self::CHANGE_LIST]);
foreach ($items as $item) { foreach ($items as $item) {
@@ -31,7 +34,8 @@ final readonly class MonitorCacheKeys implements CacheItemPoolInterface {
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
private function initialize(): void { private function initialize(): void
{
$keyList = $this->cache->getItem(self::KEY_LIST); $keyList = $this->cache->getItem(self::KEY_LIST);
$changeList = $this->cache->getItem(self::CHANGE_LIST); $changeList = $this->cache->getItem(self::CHANGE_LIST);
$keyList->set([]); $keyList->set([]);
@@ -42,51 +46,66 @@ final readonly class MonitorCacheKeys implements CacheItemPoolInterface {
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function getKeys(): array { public function getKeys(): array
{
$keyList = $this->cache->getItem(self::KEY_LIST); $keyList = $this->cache->getItem(self::KEY_LIST);
return array_keys($keyList->get() ?? []); return array_keys($keyList->get() ?? []);
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function getChanges(): array { public function getChanges(): array
{
$changeList = $this->cache->getItem(self::CHANGE_LIST); $changeList = $this->cache->getItem(self::CHANGE_LIST);
return $changeList->get() ?? []; return $changeList->get() ?? [];
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function markClean(): void { public function markClean(): void
{
$changeList = $this->cache->getItem(self::CHANGE_LIST); $changeList = $this->cache->getItem(self::CHANGE_LIST);
$changeList->set([]); $changeList->set([]);
$this->cache->save($changeList); $this->cache->save($changeList);
} }
public function getItem(string $key): CacheItemInterface { /** @throws InvalidArgumentException */
public function getItem(string $key): CacheItemInterface
{
return $this->cache->getItem($key); return $this->cache->getItem($key);
} }
/** @return CacheItemInterface[] /** @return CacheItemInterface[]
* @throws InvalidArgumentException */ * @throws InvalidArgumentException */
public function getItems(array $keys = []): iterable { public function getItems(array $keys = []): iterable
{
return $this->cache->getItems($keys); return $this->cache->getItems($keys);
} }
public function hasItem(string $key): bool { /** @throws InvalidArgumentException */
public function hasItem(string $key): bool
{
return $this->cache->hasItem($key); return $this->cache->hasItem($key);
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function clear(): bool { public function clear(): bool
{
/* only bother clearing the pool if it is not empty */ /* only bother clearing the pool if it is not empty */
if (!empty($this->getKeys())) { if (!empty($this->getKeys())) {
$response = $this->cache->clear(); $response = $this->cache->clear();
$this->initialize(); $this->initialize();
return $response; return $response;
} }
return true; return true;
} }
public function deleteItem(string $key): bool { /** @throws InvalidArgumentException */
public function deleteItem(string $key): bool
{
$this->isValid($key); $this->isValid($key);
$keyList = $this->cache->getItem(self::KEY_LIST); $keyList = $this->cache->getItem(self::KEY_LIST);
$keyValues = $keyList->get(); $keyValues = $keyList->get();
@@ -94,21 +113,23 @@ final readonly class MonitorCacheKeys implements CacheItemPoolInterface {
unset($keyValues[$key]); unset($keyValues[$key]);
$keyList->set($keyValues); $keyList->set($keyValues);
$this->cache->saveDeferred($keyList); $this->cache->saveDeferred($keyList);
$this->logChange($key, MonitorCacheKeys::REMOVED); $this->logChange($key, self::REMOVED);
$this->cache->commit(); $this->cache->commit();
} }
return $this->cache->deleteItem($key); return $this->cache->deleteItem($key);
} }
public function deleteItems(array $keys): bool { /** @throws InvalidArgumentException */
public function deleteItems(array $keys): bool
{
$this->allValid($keys); $this->allValid($keys);
$keyList = $this->cache->getItem(self::KEY_LIST); $keyList = $this->cache->getItem(self::KEY_LIST);
$keyValues = $keyList->get(); $keyValues = $keyList->get();
foreach ($keys as $key) { foreach ($keys as $key) {
if (isset($keyValues[$key])) { if (isset($keyValues[$key])) {
unset($keyValues[$key]); unset($keyValues[$key]);
$this->logChange($key, MonitorCacheKeys::REMOVED); $this->logChange($key, self::REMOVED);
} }
} }
$keyList->set($keyValues); $keyList->set($keyValues);
@@ -119,23 +140,30 @@ final readonly class MonitorCacheKeys implements CacheItemPoolInterface {
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function save(CacheItemInterface $item): bool { public function save(CacheItemInterface $item): bool
{
$this->update($item); $this->update($item);
return $this->cache->save($item); return $this->cache->save($item);
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function saveDeferred(CacheItemInterface $item): bool { public function saveDeferred(CacheItemInterface $item): bool
{
$this->update($item); $this->update($item);
return $this->cache->saveDeferred($item); return $this->cache->saveDeferred($item);
} }
public function commit(): bool { /** @throws InvalidArgumentException */
public function commit(): bool
{
return $this->cache->commit(); return $this->cache->commit();
} }
/** @throws InvalidArgumentException|OutOfBoundsException */ /** @throws InvalidArgumentException|OutOfBoundsException */
private function update(CacheItemInterface $item): void { private function update(CacheItemInterface $item): void
{
$this->isValid($item->getKey()); $this->isValid($item->getKey());
$keyList = $this->cache->getItem(self::KEY_LIST); $keyList = $this->cache->getItem(self::KEY_LIST);
$keyValues = $keyList->get(); $keyValues = $keyList->get();
@@ -147,27 +175,26 @@ final readonly class MonitorCacheKeys implements CacheItemPoolInterface {
} }
/** @throws OutOfBoundsException */ /** @throws OutOfBoundsException */
private function isValid(string $key): void { private function isValid(string $key): void
if ($key === self::KEY_LIST || $key === self::CHANGE_LIST) { {
throw new OutOfBoundsException( if (self::KEY_LIST === $key || self::CHANGE_LIST === $key) {
'Can not modify the private key or change lists' throw new OutOfBoundsException('Can not modify the private key or change lists');
);
} }
} }
/** @throws OutOfBoundsException */ /** @throws OutOfBoundsException */
private function allValid(array $keys): void { private function allValid(array $keys): void
if (in_array(self::KEY_LIST, $keys, true) || {
in_array(self::CHANGE_LIST, $keys, true) if (\in_array(self::KEY_LIST, $keys, true)
|| \in_array(self::CHANGE_LIST, $keys, true)
) { ) {
throw new OutOfBoundsException( throw new OutOfBoundsException('Can not modify the private key or change lists');
'Can not modify the private key or change lists'
);
} }
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
private function logChange(string $key, int $code = MonitorCacheKeys::UPDATED): void { private function logChange(string $key, int $code = self::UPDATED): void
{
$changeList = $this->cache->getItem(self::CHANGE_LIST); $changeList = $this->cache->getItem(self::CHANGE_LIST);
$changeValues = $changeList->get(); $changeValues = $changeList->get();
$changeValues[$key] = $code; $changeValues[$key] = $code;
+10 -5
View File
@@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App; namespace App;
@@ -6,24 +7,27 @@ namespace App;
use Psr\Cache\CacheItemPoolInterface; use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException; use Psr\Cache\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Attribute\Autoconfigure; use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;
use Symfony\Component\DependencyInjection\Attribute\Target;
/* need autoconfigure so we get it from the service container in Kernel->boot() */ /* need autoconfigure so we get it from the service container in Kernel->boot() */
#[Autoconfigure(public: true)] #[Autoconfigure(public: true)]
final readonly class PersistCache { final readonly class PersistCache
{
private MonitorCacheKeys $sessionCache; private MonitorCacheKeys $sessionCache;
private MonitorCacheKeys $sessionStorage; private MonitorCacheKeys $sessionStorage;
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function __construct( public function __construct(
CacheItemPoolInterface $sessionCache, #[Target('sessionCache')] CacheItemPoolInterface $sessionCache,
CacheItemPoolInterface $sessionStorage, #[Target('sessionStorage')] CacheItemPoolInterface $sessionStorage,
) { ) {
$this->sessionCache = new MonitorCacheKeys($sessionCache); $this->sessionCache = new MonitorCacheKeys($sessionCache);
$this->sessionStorage = new MonitorCacheKeys($sessionStorage); $this->sessionStorage = new MonitorCacheKeys($sessionStorage);
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function boot(): void { public function boot(): void
{
/* the caches are considered warm as soon as they are not empty */ /* the caches are considered warm as soon as they are not empty */
if (empty($this->sessionCache->getKeys())) { if (empty($this->sessionCache->getKeys())) {
$items = $this->sessionStorage->getItems($this->sessionStorage->getKeys()); $items = $this->sessionStorage->getItems($this->sessionStorage->getKeys());
@@ -36,7 +40,8 @@ final readonly class PersistCache {
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function persist(): void { public function persist(): void
{
/* we only need to persist the changes made to the cache (if any) */ /* we only need to persist the changes made to the cache (if any) */
$changes = $this->sessionCache->getChanges(); $changes = $this->sessionCache->getChanges();
if ($changes) { if ($changes) {
+11 -5
View File
@@ -1,26 +1,32 @@
<?php <?php
namespace App\Service; declare(strict_types=1);
namespace App\Service;
use Exception; use Exception;
use Psr\Cache\InvalidArgumentException; use Psr\Cache\InvalidArgumentException;
/** backup-codes are case‑insensitive alphanumeric strings /** backup-codes are case‑insensitive alphanumeric strings
* they are single-use and marked as used after successful authentication */ * they are single-use and marked as used after successful authentication */
interface BackupCodeInterface { interface BackupCodeInterface
/** generate a set of backup-codes and return them {
/** generate a set of backup-codes and return them.
* @param int $count Number of codes to generate * @param int $count Number of codes to generate
*
* @return string[] Generated backup codes * @return string[] Generated backup codes
*
* @throws InvalidArgumentException|Exception */ * @throws InvalidArgumentException|Exception */
public function generate(int $count = 0): array; public function generate(int $count = 10): array;
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function expire(): void; public function expire(): void;
/** check if backup-code is valid and mark it as used /** check if backup-code is valid and mark it as used.
* @param string $code Code supplied by the client * @param string $code Code supplied by the client
*
* @return bool true if the code is valid and unused * @return bool true if the code is valid and unused
*
* @throws InvalidArgumentException */ * @throws InvalidArgumentException */
public function verifyAndConsume(string $code): bool; public function verifyAndConsume(string $code): bool;
} }
+36 -18
View File
@@ -1,93 +1,110 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Service; namespace App\Service;
use App\AppConstants;
use App\MonitorCacheKeys; use App\MonitorCacheKeys;
use App\Trait\GetTotpTrait;
use App\Trait\HasLoggerTrait; use App\Trait\HasLoggerTrait;
use App\Trait\StringTrait; use App\Trait\StringTrait;
use DateTimeImmutable; use DateTimeImmutable;
use Exception; use Exception;
use Psr\Cache\CacheItemPoolInterface; use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException; use Psr\Cache\InvalidArgumentException;
use App\Trait\GetTotpTrait; use Symfony\Component\DependencyInjection\Attribute\Target;
/** backup-codes are case‑insensitive alphanumeric strings /** backup-codes are case‑insensitive alphanumeric strings
* they are single-use and marked as used after successful authentication */ * they are single-use and marked as used after successful authentication */
final readonly class BackupCodeManager implements BackupCodeInterface { final readonly class BackupCodeManager implements BackupCodeInterface
{
use GetTotpTrait; use GetTotpTrait;
use HasLoggerTrait; use HasLoggerTrait;
use StringTrait; use StringTrait;
private const int DEFAULT_COUNT = 10; private const int DEFAULT_COUNT = 10;
/* php base_convert() will break if given too long of an input */ /* php base_convert() will break if given too long of an input */
const int MAX_LENGTH = 64; public const int MAX_LENGTH = 64;
private CacheItemPoolInterface $sessionCache; private CacheItemPoolInterface $sessionCache;
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function __construct(CacheItemPoolInterface $sessionCache) { public function __construct(
#[Target('sessionCache')] CacheItemPoolInterface $sessionCache,
) {
$this->sessionCache = new MonitorCacheKeys($sessionCache); $this->sessionCache = new MonitorCacheKeys($sessionCache);
} }
/** generate a set of backup-codes and return them /** generate a set of backup-codes and return them.
* @param int $count Number of codes to generate * @param int $count Number of codes to generate
*
* @return string[] Generated backup codes * @return string[] Generated backup codes
*
* @throws InvalidArgumentException|Exception */ * @throws InvalidArgumentException|Exception */
public function generate(int $count = self::DEFAULT_COUNT): array { public function generate(int $count = self::DEFAULT_COUNT): array
{
$length = min($this->getTotp()->getDigits() + 2, self::MAX_LENGTH); $length = min($this->getTotp()->getDigits() + 2, self::MAX_LENGTH);
$codes = []; $codes = [];
for ($i = 0; $i < $count; $i++) { for ($i = 0; $i < $count; ++$i) {
/* output is alphanumeric string of given length */ /* output is alphanumeric string of given length */
$codes[] = strtolower(str_pad(substr(base_convert(bin2hex( $codes[] = strtolower(str_pad(substr(base_convert(bin2hex(
random_bytes($length) random_bytes($length),
), 16, 36), 0, $length), $length, '0', STR_PAD_LEFT)); ), 16, 36), 0, $length), $length, '0', \STR_PAD_LEFT));
} }
$this->saveCodes($codes); $this->saveCodes($codes);
$this->logger->info("generated {$count} backup codes"); $this->logger->info("generated {$count} backup codes");
return $codes; return $codes;
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function expire(): void { public function expire(): void
{
$itemsToRemove = []; $itemsToRemove = [];
foreach ($this->sessionCache->getKeys() as $key) { foreach ($this->sessionCache->getKeys() as $key) {
if (str_starts_with($key, 'backup_')) { if (str_starts_with($key, 'backup_')) {
$itemsToRemove[] = $key; $itemsToRemove[] = $key;
} }
} }
if (count($itemsToRemove) > 0) { if (\count($itemsToRemove) > 0) {
$this->sessionCache->deleteItems($itemsToRemove); $this->sessionCache->deleteItems($itemsToRemove);
} }
} }
/** check if backup-code is valid and mark it as used /** check if backup-code is valid and mark it as used.
* @param string $code Code supplied by the client * @param string $code Code supplied by the client
*
* @return bool true if the code is valid and unused * @return bool true if the code is valid and unused
*
* @throws InvalidArgumentException */ * @throws InvalidArgumentException */
public function verifyAndConsume(string $code): bool { public function verifyAndConsume(string $code): bool
{
/* remove unallowed characters, since backup codes are case-insensitive alphanumeric */ /* remove unallowed characters, since backup codes are case-insensitive alphanumeric */
$backupKey = 'backup_'.preg_replace('/[^a-z0-9]+/', '', strtolower($code)); $backupKey = 'backup_'.preg_replace('/[^a-z0-9]+/', '', strtolower($code));
$backupItem = $this->sessionCache->getItem($this->makeCacheKey($backupKey)); $backupItem = $this->sessionCache->getItem($this->makeCacheKey($backupKey));
$this->logger->debug("checking backup code '{$backupKey}': " . ($backupItem->isHit() ? 'HIT & ' : 'miss & ') . ($backupItem->get() ? 'VALID' : 'invalid')); $this->logger->debug('checking backup code: '.($backupItem->isHit() ? 'HIT & ' : 'miss & ').($backupItem->get() ? 'VALID' : 'invalid'));
if ($backupItem->isHit() && $backupItem->get()) { if ($backupItem->isHit() && $backupItem->get()) {
$this->logger->debug("valid backup code"); $this->logger->debug('valid backup code');
/* mark backup code as spent */ /* mark backup code as spent */
$backupItem->set(false); /* used */ $backupItem->set(false); /* used */
/* per PSR6, if no expiration is set, implementation may set a default, /* per PSR6, if no expiration is set, implementation may set a default,
* we want this to keep forever, so a few hundred years should do it */ * we want this to keep forever, so a few hundred years should do it */
$backupItem->expiresAt(DateTimeImmutable::createFromFormat( $backupItem->expiresAt(DateTimeImmutable::createFromFormat(
'Y-m-d', '2999-12-31' 'Y-m-d',
AppConstants::FAR_FUTURE_DATE,
)); ));
$this->sessionCache->save($backupItem); $this->sessionCache->save($backupItem);
return true; return true;
} }
return false; return false;
} }
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
private function saveCodes(array $codes): void { private function saveCodes(array $codes): void
{
foreach ($codes as $code) { foreach ($codes as $code) {
$backupItem = $this->sessionCache->getItem($this->makeCacheKey(strtolower("backup_$code"))); $backupItem = $this->sessionCache->getItem($this->makeCacheKey(strtolower("backup_$code")));
/* mark backup code as ready */ /* mark backup code as ready */
@@ -95,7 +112,8 @@ final readonly class BackupCodeManager implements BackupCodeInterface {
/* per PSR6, if no expiration is set, implementation may set a default, /* per PSR6, if no expiration is set, implementation may set a default,
* we want this to keep forever, so a few hundred years should do it */ * we want this to keep forever, so a few hundred years should do it */
$backupItem->expiresAt(DateTimeImmutable::createFromFormat( $backupItem->expiresAt(DateTimeImmutable::createFromFormat(
'Y-m-d', '2999-12-31' 'Y-m-d',
AppConstants::FAR_FUTURE_DATE,
)); ));
$this->sessionCache->saveDeferred($backupItem); $this->sessionCache->saveDeferred($backupItem);
} }
+9 -6
View File
@@ -1,23 +1,26 @@
<?php <?php
declare(strict_types=1);
namespace App\Service; namespace App\Service;
interface DomainInterface { interface DomainInterface
/** IE: "auth.example.com" or null if not using a separate subdomain {
/** IE: "auth.example.com" or null if not using a separate subdomain.
* @return ?string Returns auth subdomain if configured, otherwise null */ * @return ?string Returns auth subdomain if configured, otherwise null */
public function getAuthSubdomain(): ?string; public function getAuthSubdomain(): ?string;
/** check if given url is an acceptable url for redirection /** check if given url is an acceptable url for redirection.
* @param string $url Where we are thinking of sending the user * @param string $url Where we are thinking of sending the user
*
* @return bool Returns true if it is acceptable to send the user there */ * @return bool Returns true if it is acceptable to send the user there */
public function validReturn(string $url): bool; public function validReturn(string $url): bool;
/** check if host-base matches auth-base /** check if host-base matches auth-base.
* @param string $host
* @return bool returns true if and only if host matches base domain of auth */ * @return bool returns true if and only if host matches base domain of auth */
public function matchesAuth(string $host): bool; public function matchesAuth(string $host): bool;
/** IE: "example.com" if central auth is something like "auth.example.com" /** IE: "example.com" if central auth is something like "auth.example.com".
* @return string|null returns base domain if we are doing central auth */ * @return string|null returns base domain if we are doing central auth */
public function authBase(): ?string; public function authBase(): ?string;
} }
+130 -34
View File
@@ -1,28 +1,109 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Service; namespace App\Service;
use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\DependencyInjection\Attribute\Autowire;
final readonly class DomainManager implements DomainInterface { final readonly class DomainManager implements DomainInterface
{
/* top-level-domains which are known to have multiple parts */ /* top-level-domains which are known to have multiple parts */
private const array TLD = [ private const array TLD = [
'ai' => ['com', 'net', 'off', 'org'], 'ai' => ['com', 'net', 'off', 'org'],
'am' => ['radio'], 'am' => ['radio'],
'com' => ['br','cn','co','de','eu','gr','it','jpn','mex','ru','sa','uk','us','za'], 'at' => ['ac', 'co', 'gv', 'or'],
'au' => ['com', 'net', 'org', 'edu', 'gov', 'asn', 'id'],
'az' => ['com', 'net', 'org'],
'bd' => ['com', 'net', 'org', 'gov', 'mil', 'ac'],
'br' => ['com', 'net', 'org', 'gov', 'mil', 'eco', 'emp', 'g12', 'ind', 'inf', 'rec', 'tur', 'tv', 'edu', 'far', 'gov', 'gru', 'jor', 'leg', 'lec', 'med', 'nom', 'not', 'ppg', 'pro', 'psi', 'pub', 'slg', 'srv', 'tec', 'tmp', 'vip', 'vlog', 'wiki', 'zlg'],
'by' => ['com', 'net', 'org', 'gov', 'mil', 'of'],
'ca' => ['ab', 'bc', 'mb', 'nb', 'nf', 'nl', 'ns', 'nt', 'nu', 'on', 'pe', 'qc', 'sk', 'yk'],
'cc' => [],
'cn' => ['com', 'net', 'org', 'gov', 'edu', 'ac', 'bj', 'sh', 'tj', 'cq', 'he', 'sx', 'nm', 'ln', 'jl', 'hl', 'js', 'zj', 'ah', 'fj', 'jx', 'sd', 'ha', 'hb', 'hn', 'gd', 'gx', 'hi', 'sc', 'gz', 'yn', 'sn', 'gs', 'qh', 'nx', 'xj', 'tw', 'hk', 'mo'],
'co' => ['com', 'net', 'org', 'gov', 'mil', 'edu', 'arts', 'firm', 'info', 'int', 'nom', 'rec', 'web'],
'com' => ['br', 'cn', 'co', 'de', 'eu', 'gr', 'it', 'jpn', 'mex', 'ru', 'sa', 'uk', 'us', 'za', 'au', 'bh', 'bo', 'cn', 'ec', 'eg', 'gt', 'hk', 'hn', 'il', 'in', 'jp', 'kr', 'kw', 'lb', 'lv', 'my', 'mx', 'ng', 'ni', 'np', 'pe', 'pf', 'pg', 'ph', 'pk', 'pl', 'pr', 'py', 'sa', 'sg', 'sv', 'tr', 'tw', 'ua', 'uy', 've', 'vn', 'ye'],
'de' => ['com'], 'de' => ['com'],
'dk' => ['co'],
'ec' => ['com', 'net', 'org', 'gov', 'mil', 'edu', 'fin', 'med', 'pro'],
'ee' => ['com', 'org', 'pri'],
'eg' => ['com', 'net', 'org', 'gov', 'edu', 'mil'],
'es' => ['com', 'nom', 'org', 'edu', 'gob'],
'eu' => [],
'fi' => ['aland'],
'fm' => ['radio'], 'fm' => ['radio'],
'fr' => ['com', 'nom', 'tm', 'asso', 'gouv', 'pol'],
'ge' => ['com', 'net', 'org', 'edu', 'gov', 'mil'],
'gg' => ['co', 'net', 'org'], 'gg' => ['co', 'net', 'org'],
'in' => ['co','firm','gen','ind','net','org'], 'gr' => ['com', 'net', 'org', 'gov', 'edu', 'mil'],
'hk' => ['com', 'net', 'org', 'gov', 'edu', 'idv'],
'hu' => ['co', '2000', 'privat', 'sport', 'tm', 'erotica', 'sex', 'video', 'info', 'org', 'net', 'gov', 'edu', 'mil', 'press', 'biz'],
'id' => ['ac', 'biz', 'co', 'desa', 'go', 'mil', 'my', 'net', 'or', 'sch', 'web'],
'ie' => ['gov'],
'il' => ['ac', 'co', 'gov', 'idf', 'k12', 'muni', 'net', 'org'],
'in' => ['co', 'firm', 'gen', 'ind', 'net', 'org', 'ac', 'edu', 'res', 'gov', 'mil'],
'iq' => ['com', 'net', 'org', 'gov', 'edu', 'mil'],
'ir' => ['ac', 'co', 'gov', 'id', 'net', 'org', 'sch'],
'is' => ['net', 'com', 'org', 'edu', 'gov', 'int'],
'it' => ['ab', 'ag', 'al', 'an', 'ao', 'ap', 'aq', 'ar', 'at', 'av', 'ba', 'bg', 'bi', 'bl', 'bn', 'bo', 'br', 'bs', 'bt', 'bz', 'ca', 'cb', 'ce', 'ch', 'cl', 'cn', 'co', 'cr', 'cs', 'ct', 'cz', 'en', 'fc', 'fe', 'fg', 'fi', 'fm', 'fr', 'ge', 'go', 'gr', 'im', 'is', 'kr', 'lc', 'le', 'li', 'lo', 'lt', 'lu', 'mb', 'mc', 'me', 'mi', 'mn', 'mo', 'ms', 'mt', 'na', 'no', 'nu', 'or', 'pa', 'pc', 'pd', 'pe', 'pg', 'pi', 'pn', 'po', 'pr', 'pt', 'pu', 'pv', 'pz', 're', 'rg', 'ri', 'rm', 'rn', 'ro', 'sa', 'si', 'so', 'sp', 'sr', 'ss', 'su', 'sv', 'ta', 'te', 'tn', 'to', 'tp', 'tr', 'ts', 'tv', 'ud', 'va', 'vb', 'vc', 've', 'vi', 'vr', 'vt', 'vv', 'edu', 'gov', 'abruzzo', 'basilicata', 'calabria', 'campania', 'emilia-romagna', 'friuli-ve-giulia', 'lazio', 'liguria', 'lombardia', 'marche', 'molise', 'piemonte', 'puglia', 'sardegna', 'sicilia', 'toscana', 'trentino-a-adige', 'umbria', 'valle-aosta', 'veneto'],
'je' => ['co', 'net', 'org'], 'je' => ['co', 'net', 'org'],
'mx' => ['com','net','org'], 'jo' => ['com', 'net', 'org', 'gov', 'edu', 'mil', 'sch'],
'net' => ['gb','hu','in','jp','se','uk'], 'jp' => ['ac', 'ad', 'co', 'ed', 'go', 'gr', 'lg', 'ne', 'or'],
'nz' => ['co','net','org'], 'ke' => ['co', 'ne', 'or', 'ac', 'go', 'me', 'mobi', 'info', 'sc', 'pro'],
'org' => ['ae','us'], 'kg' => ['com', 'net', 'org', 'gov', 'mil', 'edu'],
'ph' => ['com','net','org'], 'kr' => ['ac', 'co', 'go', 'hs', 'kg', 'mil', 'ms', 'ne', 'or', 'pe', 're', 'seoul', 'busan', 'daegu', 'incheon', 'gwangju', 'daejeon', 'ulsan', 'gyeonggi', 'gangwon', 'chungbuk', 'chungnam', 'jeonbuk', 'jeonnam', 'gyeongbuk', 'gyeongnam', 'jeju', 'sejong'],
'se' => ['com'], 'kz' => ['com', 'net', 'org', 'edu', 'gov', 'mil'],
'uk' => ['co','me','org'], 'li' => [],
'lt' => ['gov'],
'lv' => ['com', 'net', 'org', 'edu', 'gov', 'mil', 'id', 'asn', 'conf'],
'ly' => ['com', 'net', 'org', 'gov', 'edu', 'sch', 'med', 'id'],
'ma' => ['co', 'net', 'org', 'gov', 'press', 'ac'],
'mk' => ['com', 'net', 'org', 'edu', 'gov', 'inf', 'name', 'pro'],
'mx' => ['com', 'net', 'org', 'gov', 'edu', 'mil'],
'my' => ['com', 'net', 'org', 'gov', 'edu', 'mil', 'name'],
'na' => ['com', 'net', 'org', 'alt', 'edu', 'gov', 'mil', 'pro'],
'net' => ['gb', 'hu', 'in', 'jp', 'se', 'uk', 'cn', 'nz'],
'ng' => ['com', 'net', 'org', 'gov', 'edu', 'mil', 'sch', 'name', 'gov'],
'ni' => ['ac', 'co', 'com', 'edu', 'gob', 'mil', 'net', 'nom', 'org'],
'nl' => ['bv', 'co'],
'no' => ['fhs', 'folkebibl', 'kommune', 'mil', 'stat', 'priv', 'vgs', 'dep', 'kommune'],
'nz' => ['co', 'net', 'org', 'ac', 'geek', 'gen', 'maori', 'school', 'parliament', 'govt', 'health', 'mil', 'crii', 'archie', 'geek', 'govt', 'health', 'maori', 'school'],
'om' => ['com', 'net', 'org', 'gov', 'edu', 'med', 'mil', 'sch'],
'org' => ['ae', 'us', 'lu'],
'pe' => ['com', 'net', 'org', 'gob', 'edu', 'mil', 'nom'],
'ph' => ['com', 'net', 'org', 'gov', 'edu', 'mil'],
'pk' => ['com', 'net', 'org', 'fam', 'biz', 'edu', 'gov', 'web'],
'pl' => ['com', 'net', 'org', 'aid', 'agro', 'atm', 'auto', 'biz', 'edu', 'gmina', 'gsm', 'info', 'mail', 'miasta', 'media', 'mil', 'ngo', 'nom', 'pc', 'powiat', 'priv', 'realestate', 'rel', 'sex', 'shop', 'sklep', 'sos', 'szkola', 'targi', 'tm', 'tourism', 'travel', 'turystyka', 'gov', 'ap', 'augov', 'bedzin', 'bialystok', 'bielawa', 'bierun', 'boleslawiec', 'bydgoszcz', 'bytom', 'cieszyn', 'czeladz', 'czest', 'dlugoleka', 'elblag', 'elk', 'glogow', 'gniezno', 'gorlice', 'gorzow', 'grodzisk', 'grudziadz', 'ilk', 'jaworzno', 'jelenia-gora', 'jgora', 'kalisz', 'kazimierz-dolny', 'karpacz', 'kartuzy', 'kaszuby', 'katowice', 'kepno', 'ketrzyn', 'klodzko', 'kobierzyce', 'kolobrzeg', 'konin', 'konskowola', 'krapkowice', 'krakow', 'krasnik', 'krasno', 'krosniewice', 'kutno', 'lapy', 'lebork', 'legnica', 'lezajsk', 'limanowa', 'lomza', 'lowicz', 'lubin', 'lukow', 'malbork', 'malopolska', 'mazowsze', 'mazury', 'mielec', 'milicz', 'mielno', 'mragowo', 'naklo', 'nowaruda', 'nysa', 'olawa', 'olecko', 'olkusz', 'olsztyn', 'opoczno', 'opole', 'ostrowiec', 'ostroleka', 'ostrowwlkp', 'pila', 'pisz', 'podhale', 'podlasie', 'polkowice', 'pomorze', 'pomorse', 'prochowice', 'pruszkow', 'przeworsk', 'pulawy', 'rabka', 'rawa-maz', 'rybnik', 'rzeszow', 'sanok', 'sejny', 'siedlce', 'slask', 'slupsk', 'sosnowiec', 'stalowa-wola', 'skoczow', 'starachowice', 'stargard', 'suwalki', 'swidnica', 'swiebodzin', 'swinoujscie', 'szczecin', 'szczytno', 'tarnobrzeg', 'tgory', 'turek', 'tychy', 'ustka', 'walbrzych', 'warmia', 'warszawa', 'waw', 'wegrow', 'wielun', 'wlocl', 'wloclawek', 'wodzislaw', 'wolomin', 'wroclaw', 'zachpomor', 'zagan', 'zarow', 'zgora', 'zgorzelec', 'plug'],
'pr' => ['ac', 'co', 'edu', 'gov', 'info', 'island', 'pro', 'net', 'org'],
'pt' => ['com', 'net', 'org', 'gov', 'edu', 'int', 'publ'],
'py' => ['com', 'net', 'org', 'gov', 'edu', 'mil', 'co'],
'qa' => ['com', 'net', 'org', 'gov', 'edu', 'mil', 'sch', 'name'],
'ro' => ['com', 'net', 'org', 'nom', 'rec', 'info', 'arts', 'com', 'firm', 'tm', 'www', 'store', 'nt', 'ngo', 'pro', 'tm', 'com', 'arts', 'rec', 'store', 'info', 'nom', 'nt', 'org', 'shop', 'firm', 'www', 'rest', 'travel', 'transport', 'tourism', 'press', 'media', 'medical', 'med', 'law', 'jobs', 'inst', 'individual', 'insinfo', 'guru', 'fit', 'engineering', 'expert', 'energy', 'economy', 'dot', 'dog', 'dev', 'design', 'dem', 'dental', 'craft', 'corp', 'consulting', 'construction', 'company', 'com', 'club', 'cloud', 'coach', 'city', 'cinema', 'church', 'chat', 'casino', 'cars', 'care', 'cards', 'broke', 'blog', 'bio', 'bid', 'band', 'auto', 'audio', 'attorney', 'apartments', 'app', 'art', 'archi', 'architects', 'arena', 'architects', 'associates', 'attorney', 'auction', 'auto', 'baby', 'band', 'bank', 'bar', 'bargains', 'beer', 'berlin', 'best', 'bet', 'bid', 'bike', 'bingo', 'bio', 'black', 'blog', 'blue', 'boats', 'bond', 'boo', 'book', 'boutique', 'build', 'builders', 'business', 'buzz', 'cab', 'cafe', 'call', 'cam', 'camp', 'capital', 'care', 'careers', 'cars', 'cash', 'casino', 'catering', 'center', 'ceo', 'ceramics', 'cfd', 'ch', 'chat', 'church', 'city', 'claims', 'cleaning', 'click', 'clinic', 'clothing', 'cloud', 'club', 'coach', 'codes', 'coffee', 'college', 'community', 'company', 'computer', 'condos', 'construction', 'consulting', 'contact', 'cooking', 'cool', 'country', 'courses', 'cpa', 'craft', 'credit', 'creditcard', 'cricket', 'cruise', 'cuisinella', 'cymru', 'dabur', 'dance', 'date', 'dating', 'deals', 'degree', 'delivery', 'democrat', 'dental', 'design', 'dev', 'diamonds', 'diet', 'digital', 'direct', 'directory', 'discount', 'dog', 'domains', 'doos', 'download', 'ec', 'edu', 'education', 'energy', 'engineering', 'enterprises', 'equipment', 'estate', 'events', 'exchange', 'expert', 'exposed', 'express', 'fail', 'faith', 'family', 'fan', 'farm', 'fashion', 'film', 'finance', 'financial', 'fish', 'fit', 'fitness', 'flights', 'florist', 'flowers', 'football', 'forex', 'forsale', 'foundation', 'fun', 'fund', 'furniture', 'futbol', 'fyi', 'gal', 'gallery', 'game', 'garden', 'gift', 'gifts', 'gives', 'glass', 'global', 'gold', 'golf', 'graphics', 'gratis', 'green', 'gripe', 'group', 'guru', 'health', 'healthcare', 'help', 'helsinki', 'here', 'hiphop', 'hiv', 'holdings', 'holiday', 'homes', 'horse', 'host', 'hosting', 'house', 'how', 'immo', 'immobilien', 'in', 'industries', 'info', 'ink', 'institute', 'insure', 'international', 'investments', 'irish', 'jewelry', 'kaufen', 'kids', 'kim', 'kitchen', 'kiwi', 'kred', 'land', 'law', 'lawyer', 'legal', 'lgbt', 'lifestyle', 'lighting', 'limited', 'limo', 'link', 'live', 'loan', 'loans', 'lol', 'london', 'love', 'ltd', 'ltda', 'luxury', 'maison', 'management', 'market', 'marketing', 'markets', 'media', 'memorial', 'men', 'menu', 'miami', 'mobi', 'moda', 'moe', 'mom', 'money', 'monster', 'mortgage', 'movie', 'nagoya', 'name', 'navy', 'net', 'network', 'news', 'ngo', 'ninja', 'nyc', 'observer', 'okinawa', 'one', 'ong', 'onl', 'online', 'ooo', 'org', 'organic', 'osaka', 'paris', 'partners', 'parts', 'party', 'photo', 'photography', 'photos', 'pics', 'pictures', 'pink', 'pizza', 'place', 'plumbing', 'plus', 'poker', 'porn', 'press', 'pro', 'productions', 'properties', 'property', 'pub', 'qpon', 'realtor', 'realty', 'recipes', 'red', 'rehab', 'reise', 'reisen', 'rent', 'rentals', 'repair', 'report', 'rest', 'restaurant', 'review', 'reviews', 'rich', 'rip', 'rocks', 'rodeo', 'run', 'saarland', 'sale', 'salon', 'sarl', 'save', 'saxo', 'school', 'schule', 'science', 'services', 'sex', 'sexy', 'sg', 'shop', 'shopping', 'show', 'singles', 'site', 'ski', 'soccer', 'social', 'software', 'solar', 'solutions', 'space', 'store', 'stream', 'studio', 'study', 'style', 'supplies', 'supply', 'support', 'surgery', 'systems', 'tax', 'taxi', 'team', 'tech', 'technology', 'tennis', 'thai', 'tips', 'tires', 'tirol', 'today', 'tokyo', 'tools', 'top', 'tour', 'tours', 'town', 'toys', 'trade', 'trading', 'training', 'travel', 'tube', 'university', 'uno', 'vacations', 'vegas', 'ventures', 'vet', 'viajes', 'video', 'villas', 'vin', 'vision', 'vlaanderen', 'vodka', 'vote', 'voting', 'voto', 'voyage', 'wales', 'watch', 'webcam', 'website', 'wedding', 'wien', 'wiki', 'win', 'wine', 'work', 'works', 'world', 'wtf', 'xxx', 'xyz', 'yoga', 'yokohama', 'zone'],
'ru' => ['ac', 'com', 'edu', 'int', 'net', 'org', 'pp', 'adygeya', 'altai', 'amur', 'arkhangelsk', 'astrakhan', 'bashkiria', 'belgorod', 'bir', 'bryansk', 'buryatia', 'cbg', 'chel', 'chelyabinsk', 'chita', 'chukotka', 'chuvashia', 'dagestan', 'dudinka', 'e-burg', 'grozny', 'irkutsk', 'ivanovo', 'izhevsk', 'jar', 'joshkar-ola', 'kalmykia', 'kaluga', 'kamchatka', 'karelia', 'kazan', 'kchr', 'kemerovo', 'khabarovsk', 'khakassia', 'khv', 'kirov', 'koenigsberg', 'komi', 'kostroma', 'krasnodar', 'krasnoyarsk', 'kuban', 'kurgan', 'kursk', 'lipetsk', 'magadan', 'mari', 'mari-el', 'marine', 'mil', 'mordovia', 'mosreg', 'msk', 'murmansk', 'nalchik', 'nnov', 'nov', 'novosibirsk', 'nsk', 'omsk', 'orenburg', 'oryol', 'palana', 'penza', 'perm', 'ptz', 'rnd', 'ryazan', 'sakhalin', 'samara', 'saratov', 'simbirsk', 'smolensk', 'spb', 'stavropol', 'stv', 'surgut', 'tambov', 'tatarstan', 'tom', 'tomsk', 'tsaritsyn', 'tsk', 'tula', 'tuva', 'tver', 'tyumen', 'udm', 'udmurtia', 'ulan-ude', 'vladikavkaz', 'vladimir', 'vladivostok', 'volgograd', 'vologda', 'voronezh', 'vrn', 'vyatka', 'yakutia', 'yamal', 'yaroslavl', 'yevrey'],
'sa' => ['com', 'net', 'org', 'gov', 'med', 'pub', 'edu', 'sch'],
'sb' => ['com', 'net', 'org', 'edu', 'gov'],
'sc' => ['com', 'net', 'org', 'gov', 'edu'],
'se' => ['a', 'ac', 'b', 'bd', 'brand', 'c', 'd', 'e', 'f', 'fh', 'fhsk', 'fhv', 'g', 'h', 'i', 'k', 'komforb', 'kommunal', 'komvux', 'kunskapsforb', 'l', 'lanbib', 'm', 'n', 'naturbruksgymn', 'o', 'org', 'p', 'parti', 'pp', 'press', 'r', 's', 't', 'tm', 'u', 'v', 'w', 'x', 'y', 'z'],
'sg' => ['com', 'net', 'org', 'gov', 'edu', 'per'],
'sh' => ['com', 'net', 'org', 'gov', 'mil', 'edu'],
'sk' => ['co', 'com', 'edu', 'gov', 'mil', 'net', 'org', 'nfo'],
'st' => ['co', 'com', 'consulado', 'edu', 'embaixada', 'gov', 'mil', 'net', 'org', 'principe', 'saotome', 'store'],
'su' => ['abkhazia', 'adygeya', 'ak', 'altai', 'amur', 'arkhangelsk', 'astrakhan', 'bashkiria', 'belgorod', 'bir', 'bryansk', 'buryatia', 'cbg', 'chel', 'chelyabinsk', 'chita', 'chukotka', 'chuvashia', 'dagestan', 'dudinka', 'e-burg', 'grozny', 'irkutsk', 'ivanovo', 'izhevsk', 'jar', 'joshkar-ola', 'kalmykia', 'kaluga', 'kamchatka', 'karelia', 'kazan', 'kchr', 'kemerovo', 'khabarovsk', 'khakassia', 'khv', 'kirov', 'koenigsberg', 'komi', 'kostroma', 'krasnodar', 'krasnoyarsk', 'kuban', 'kurgan', 'kursk', 'lipetsk', 'magadan', 'mari', 'mari-el', 'marine', 'mil', 'mordovia', 'mosreg', 'msk', 'murmansk', 'nalchik', 'nnov', 'nov', 'novosibirsk', 'nsk', 'omsk', 'orenburg', 'oryol', 'palana', 'penza', 'perm', 'ptz', 'rnd', 'ryazan', 'sakhalin', 'samara', 'saratov', 'simbirsk', 'smolensk', 'spb', 'stavropol', 'stv', 'surgut', 'tambov', 'tatarstan', 'tom', 'tomsk', 'tsaritsyn', 'tsk', 'tula', 'tuva', 'tver', 'tyumen', 'udm', 'udmurtia', 'ulan-ude', 'vladikavkaz', 'vladimir', 'vladivostok', 'volgograd', 'vologda', 'voronezh', 'vrn', 'vyatka', 'yakutia', 'yamal', 'yaroslavl', 'yevrey', 'com', 'net', 'org', 'gov', 'pp', 'edu'],
'sv' => ['com', 'edu', 'gob', 'org', 'red'],
'sy' => ['com', 'net', 'org', 'gov', 'edu', 'mil', 'name'],
'th' => ['ac', 'co', 'go', 'in', 'mi', 'net', 'or'],
'tj' => ['ac', 'biz', 'co', 'com', 'edu', 'gov', 'go', 'info', 'int', 'mil', 'name', 'net', 'nic', 'nom', 'org', 'pro', 'test', 'web'],
'tn' => ['agrinet', 'com', 'defense', 'edunet', 'ens', 'fin', 'gov', 'ind', 'info', 'intl', 'min', 'nat', 'net', 'org', 'perso', 'rnrt', 'rns', 'rnu', 'tourism', 'turen'],
'tr' => ['com', 'net', 'org', 'gov', 'biz', 'info', 'mil', 'edu', 'tv', 'bbs', 'k12', 'pol', 'bel', 'dr', 'gen', 'av', 'bbs', 'k12', 'name', 'tel', 'nc', 'web', 'tsk', 'bel', 'pol', 'edu'],
'tw' => ['com', 'net', 'org', 'edu', 'gov', 'mil', 'idv', 'game', 'ebiz', 'club', 'gnu'],
'ua' => ['com', 'net', 'org', 'edu', 'gov', 'in', 'at', 'cn', 'crimea', 'dn', 'dnepropetrovsk', 'donetsk', 'dp', 'if', 'ivano-frankivsk', 'kh', 'kharkov', 'kherson', 'khmelnitskiy', 'kiev', 'kirovograd', 'km', 'kr', 'ks', 'kv', 'lg', 'lt', 'lugansk', 'lutsk', 'lv', 'lviv', 'mk', 'mk.ua', 'mykolaiv', 'net', 'nikolaev', 'od', 'odessa', 'pl', 'poltava', 'rovno', 'rv', 'sebastopol', 'sm', 'sumy', 'te', 'ternopil', 'uz', 'uzhgorod', 'vinnica', 'vn', 'volyn', 'yalta', 'zaporizhzhe', 'zhitomir', 'zp', 'zt'],
'uk' => ['co', 'me', 'org', 'ltd', 'plc', 'net', 'sch', 'ac', 'gov', 'nhs', 'police', 'mod', 'nhs', 'parliament'],
'us' => ['ak', 'al', 'ar', 'as', 'az', 'ca', 'co', 'ct', 'dc', 'de', 'fl', 'ga', 'gu', 'hi', 'ia', 'id', 'il', 'in', 'ks', 'ky', 'la', 'ma', 'md', 'me', 'mi', 'mn', 'mo', 'ms', 'mt', 'nc', 'nd', 'ne', 'nh', 'nj', 'nm', 'nv', 'ny', 'oh', 'ok', 'or', 'pa', 'pr', 'ri', 'sc', 'sd', 'tn', 'tx', 'ut', 'vi', 'vt', 'va', 'wa', 'wi', 'wv', 'wy', 'dni', 'fed', 'isa', 'kids', 'nsn'],
'uy' => ['com', 'net', 'org', 'gub', 'mil', 'edu'],
've' => ['co', 'com', 'edu', 'gob', 'info', 'net', 'org', 'web'],
'vn' => ['com', 'net', 'org', 'edu', 'gov', 'int', 'ac', 'biz', 'info', 'name', 'pro', 'health'],
'yu' => ['ac', 'co', 'edu', 'gov', 'org'],
'za' => ['ac', 'alt', 'co', 'edu', 'gov', 'law', 'mil', 'net', 'ngo', 'nom', 'org', 'school', 'tm', 'web'],
]; ];
private bool $subdomainRedirect; private bool $subdomainRedirect;
@@ -36,30 +117,35 @@ final readonly class DomainManager implements DomainInterface {
$this->authSubdomain = $authSubdomain; $this->authSubdomain = $authSubdomain;
} }
/** IE: "auth.example.com" or null if not using a separate subdomain /** IE: "auth.example.com" or null if not using a separate subdomain.
* @return ?string Returns auth subdomain if configured, otherwise null */ * @return ?string Returns auth subdomain if configured, otherwise null */
public function getAuthSubdomain(): ?string { public function getAuthSubdomain(): ?string
{
if ($this->authBase()) { if ($this->authBase()) {
return $this->authSubdomain; return $this->authSubdomain;
} }
return null; return null;
} }
/** check if given url is an acceptable url for redirection /** check if given url is an acceptable url for redirection.
* @param string $url Where we are thinking of sending the user * @param string $url Where we are thinking of sending the user
*
* @return bool Returns true if it is acceptable to send the user there */ * @return bool Returns true if it is acceptable to send the user there */
public function validReturn(string $url): bool { public function validReturn(string $url): bool
{
/* ensure url is valid and, when using an auth subdomain, /* ensure url is valid and, when using an auth subdomain,
* that the url host matches the base domain */ * that the url host matches the base domain */
if (!filter_var($url, FILTER_VALIDATE_URL)) { if (!filter_var($url, \FILTER_VALIDATE_URL)) {
return false; return false;
} }
if ($this->authBase()) { if ($this->authBase()) {
$host = parse_url($url, PHP_URL_HOST); $host = parse_url($url, \PHP_URL_HOST);
if ($host === null) { if (null === $host || false === $host || '' === $host) {
return false; return false;
} }
/* do not send the user to another domain */ /* do not send the user to another domain */
return $this->matchesAuth($host); return $this->matchesAuth($host);
} }
@@ -67,54 +153,64 @@ final readonly class DomainManager implements DomainInterface {
return true; return true;
} }
/** check if host-base matches auth-base /** check if host-base matches auth-base.
* @param string $host
* @return bool returns true if and only if host matches base domain of auth */ * @return bool returns true if and only if host matches base domain of auth */
public function matchesAuth(string $host): bool { public function matchesAuth(string $host): bool
{
$hostBase = $this->baseDomain($host); $hostBase = $this->baseDomain($host);
$authBase = $this->baseDomain($this->authSubdomain); $authBase = $this->baseDomain($this->authSubdomain);
return $this->subdomainRedirect && $this->authSubdomain &&
$authBase && $authBase === $hostBase; return $this->subdomainRedirect && $this->authSubdomain
&& $authBase && $authBase === $hostBase;
} }
/** IE: "example.com" if central auth is something like "auth.example.com" /** IE: "example.com" if central auth is something like "auth.example.com".
* @return string|null returns base domain if we are doing central auth */ * @return string|null returns base domain if we are doing central auth */
public function authBase(): ?string { public function authBase(): ?string
{
if ($this->subdomainRedirect && $this->authSubdomain && $this->baseDomain($this->authSubdomain)) { if ($this->subdomainRedirect && $this->authSubdomain && $this->baseDomain($this->authSubdomain)) {
return $this->baseDomain($this->authSubdomain); return $this->baseDomain($this->authSubdomain);
} }
return null; return null;
} }
/** this lets us determine the base domain of the given ip, localhost, or domain /** this lets us determine the base domain of the given ip, localhost, or domain
* "service.example.co.uk" into "example.co.uk" and "service.example.com" into "example.com" * "service.example.co.uk" into "example.co.uk" and "service.example.com" into "example.com"
* things like "localhost" and "8.8.8.8" will return null * things like "localhost" and "8.8.8.8" will return null.
*
* @param string $host ip, localhost, or domain with zero or more subdomains * @param string $host ip, localhost, or domain with zero or more subdomains
*
* @return ?string returns null if host is ip or localhost otherwise domain with all subdomains removed */ * @return ?string returns null if host is ip or localhost otherwise domain with all subdomains removed */
private function baseDomain(string $host): ?string { private function baseDomain(string $host): ?string
{
/* if host is an ip address (or localhost), leave it as is */ /* if host is an ip address (or localhost), leave it as is */
if (filter_var($host, FILTER_VALIDATE_IP) || $host === 'localhost') { if (filter_var($host, \FILTER_VALIDATE_IP) || 'localhost' === $host) {
return null; return null;
} }
$parts = explode('.', $host); $parts = explode('.', strtolower($host));
$keep = $this->baseLength($parts); $keep = $this->baseLength($parts);
$parts = array_slice($parts, -$keep); $parts = \array_slice($parts, -$keep);
return implode('.', $parts); return implode('.', $parts);
} }
/** IE: ["www", "example", "com"] or ["www", "example", "co", "uk"] /** IE: ["www", "example", "com"] or ["www", "example", "co", "uk"].
* @param string[] $parts pieces of a domain split by "." dot * @param string[] $parts pieces of a domain split by "." dot
*
* @return int typically 2 but sometimes 3 */ * @return int typically 2 but sometimes 3 */
private function baseLength(array $parts): int { private function baseLength(array $parts): int
$length = count($parts); {
$length = \count($parts);
$baseLength = min(2, $length); $baseLength = min(2, $length);
/* check if host should retain 3 parts, due to TLD */ /* check if host should retain 3 parts, due to TLD */
if (count($parts) > 2 && isset(self::TLD[$parts[$length-1]]) && if (\count($parts) > 2 && isset(self::TLD[$parts[$length - 1]])
in_array($parts[$length-2], self::TLD[$parts[$length-1]], true) && \in_array($parts[$length - 2], self::TLD[$parts[$length - 1]], true)
) { ) {
$baseLength = min(3, $length); $baseLength = min(3, $length);
} }
return $baseLength; return $baseLength;
} }
} }
+4 -1
View File
@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace App\Service; namespace App\Service;
use App\Data\Payload; use App\Data\Payload;
@@ -7,7 +9,8 @@ use Psr\Cache\InvalidArgumentException;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
interface LoginInterface { interface LoginInterface
{
/** @throws InvalidArgumentException */ /** @throws InvalidArgumentException */
public function checkToken(Payload $payload, Request $request): ?Response; public function checkToken(Payload $payload, Request $request): ?Response;
} }
+84 -105
View File
@@ -1,148 +1,127 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Service; namespace App\Service;
use App\AppConstants;
use App\Data\Payload; use App\Data\Payload;
use App\Enum\Scope; use App\Enum\Scope;
use App\MonitorCacheKeys;
use App\Trait\CookieNameTrait;
use App\Trait\GetTotpTrait; use App\Trait\GetTotpTrait;
use App\Trait\MakeNonceTrait; use App\Trait\MakeNonceTrait;
use App\Trait\StringTrait; use App\Trait\StringTrait;
use Psr\Cache\CacheItemPoolInterface; use Override;
use Psr\Cache\InvalidArgumentException; use Psr\Cache\InvalidArgumentException;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException; use Throwable;
use Symfony\Component\Uid\Ulid;
final readonly class LoginManager implements LoginInterface { /**
use CookieNameTrait; * Authenticates a TOTP code (or backup code) and, on success, either grants
* access or starts a passkey registration.
*
* The "grant access" half lives in {@see SessionIssuer} so the passkey ceremony
* produces an identical response. This class keeps the part genuinely specific
* to code-based login: verifying the code and enforcing the single-use nonce.
*
* **Why the registration hand-off lives here.** Ticking "register this device"
* turns the form submission into a registration ceremony, and the TOTP check is
* what authorises it. That check — and the nonce check — already happen here, so
* a ceremony started anywhere earlier would mean validating the nonce somewhere
* new and risking spending it twice.
*/
final readonly class LoginManager implements LoginInterface
{
use GetTotpTrait; use GetTotpTrait;
use MakeNonceTrait; use MakeNonceTrait;
use StringTrait; use StringTrait;
private CacheItemPoolInterface $sessionCache;
/** @throws InvalidArgumentException */
public function __construct( public function __construct(
CacheItemPoolInterface $sessionCache,
private BackupCodeInterface $backupCodeManager, private BackupCodeInterface $backupCodeManager,
private DomainInterface $domainManager, private SessionIssuerInterface $sessionIssuer,
private PasskeyInterface $passkeys,
) { ) {
$this->sessionCache = new MonitorCacheKeys($sessionCache);
} }
/** @throws InvalidArgumentException */ /**
public function checkToken(Payload $payload, Request $request): ?Response { * @throws InvalidArgumentException
*/
#[Override]
public function checkToken(Payload $payload, Request $request): ?Response
{
/* when scope is IP but ip-access is disabled, scope is to be considered cookie */ /* when scope is IP but ip-access is disabled, scope is to be considered cookie */
if ($payload->scope === Scope::Ip && ! $this->config->ipTtl()) { if (Scope::Ip === $payload->scope && !$this->config->ipTtl()) {
/* requested to grant ip access, but that is not enabled */ /* requested to grant ip access, but that is not enabled */
$payload->scope = Scope::Cookie; $payload->scope = Scope::Cookie;
} }
if ($this->getTotp()->verify($payload->token, null, 10) || if (!$this->getTotp()->verify($payload->token, null, 1)
$this->backupCodeManager->verifyAndConsume($payload->token) && !$this->backupCodeManager->verifyAndConsume($payload->token)
) { ) {
return null;
}
/* token is correct (TOTP or Backup) */ /* token is correct (TOTP or Backup) */
/* if server nonce is found and is valid */ /* if server nonce is found and is valid */
$nonceItem = $this->nonceCache->getItem($this->makeCacheKey($payload->nonce)); $nonceItem = $this->nonceCache->getItem($this->makeCacheKey($payload->nonce));
if ($nonceItem->isHit() && $nonceItem->get()) { if (!$nonceItem->isHit() || !$nonceItem->get()) {
/* mark nonce as spent */
$nonceItem->set(false); /* invalid */
$nonceItem->expiresAfter(LoginManager::NONCE_TTL); /* keep briefly */
$this->nonceCache->save($nonceItem);
/* token authentication successful, grant access and set response */
$cleanId = $this->makeCacheKey($payload->id);
/* if they just want this one page, return ok, to grant them access */
$response = new Response("hi $cleanId", headers: [
'Content-Type' => 'text/plain',
'Remote-User' => $cleanId,
]);
if ($payload->scope !== Scope::None) {
/* grant access based on the requested scope */
if ($payload->scope === Scope::Cookie) {
$response->headers->setCookie($this->setCookie($cleanId, $request->getHost()));
} else if ($payload->scope === Scope::Ip) {
$this->setIp($cleanId, $request->getClientIp());
}
if ($payload->json) {
$contentType = 'application/json';
$content = json_encode([
'message' => 'Login successful',
'nonce' => null,
]);
} else {
$contentType = 'text/html';
$content = "hi $cleanId, please reload";
}
$location = $request->query->has('return') &&
$this->domainManager->validReturn($request->query->get('return')) ?
"{$request->query->get('return')}" :
"{$request->getPathInfo()}{$request->getQueryString()}";
/* force redirect to use GET method (important when using central auth) */
$response->setContent($content)
->setStatusCode(Response::HTTP_SEE_OTHER)
->headers->set('Location', $location);
$response->headers->set('Content-Type', $contentType);
}
$this->logger->debug("successful login for: $cleanId");
return $response;
}
}
return null; return null;
} }
/** @throws InvalidArgumentException */ /* mark nonce as spent */
private function setCookie(string $id, string $host): Cookie { $nonceItem->set(false); /* invalid */
/* successful auth with token, store session and set the cookie */ $nonceItem->expiresAfter(self::NONCE_TTL); /* keep briefly */
$ulid = new Ulid(); $this->nonceCache->save($nonceItem);
$sessionCookie = $this->sessionCache->getItem(
$this->makeCacheKey("cookie_$ulid")
);
if ($sessionCookie->isHit()) {
/* it is supposed to be impossible to have collisions */
$this->logger->error("aborting: ULID collision");
throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'Internal Server Error');
}
$sessionCookie->set($id);
$sessionCookie->expiresAfter($this->config->cookieTtl());
$this->sessionCache->save($sessionCookie);
/* when using subdomain-auth we have to use a different cookie name, as the /* the code and the nonce are both good from here on */
* "__Host-Http-" prefix we normally use does not allow domain to be set */
/* changes here must be reflected in InterceptListener::pruneInvalidCookie() */ if ($payload->register && $payload->json) {
return Cookie::create( return $this->startRegistration($payload);
name: $this->domainManager->authBase() ? $this->authCookieName() : $this->cookieName(), }
value: $ulid->toString(),
expire: time() + $this->config->cookieTtl(), return $this->sessionIssuer->issue(
path: '/', $payload->id,
/* if using central auth, only set the domain if the host matches */ $payload->scope,
domain: $this->domainManager->matchesAuth($host) ? $this->domainManager->authBase() : null, $request,
secure: true, $payload->json,
httpOnly: true,
sameSite: Cookie::SAMESITE_STRICT,
); );
} }
/** @throws InvalidArgumentException */ /**
private function setIp(string $id, string $ip): void { * The registration hand-off: authorisation is already proven, so this issues
/* successful auth with token, requested scope of ip (and ip access enabled) */ * the ceremony options back to the page instead of a session.
$ipKey = $this->makeCacheKey("ip_$ip"); *
* `SessionIssuer` is deliberately not involved — the session is granted only
* once the new credential has actually been verified, at `register-finish`.
*
* **JSON only.** The checkbox is submitted through the same `X-Preauth` AJAX
* path as an ordinary login, so a failed attempt comes back as JSON carrying
* a fresh nonce. On the plain form-post path it would be HTML, the script's
* `response.json()` would throw, and — worse — the fresh nonce would be lost,
* so the user's retry would fail against a nonce that had already been spent.
* A non-JSON submission is therefore treated as an ordinary login; WebAuthn
* needs scripting regardless, so it is the checkbox that is the enhancement
* here, not the underlying login.
*/
private function startRegistration(Payload $payload): ?Response
{
try {
$payloadOut = $this->passkeys->beginRegistration($payload->id);
} catch (Throwable) {
/* a ceremony that cannot start must not become a 500 on the login
* page; falling through to the caller's failure path is the same
* treatment a wrong code gets */
return null;
}
$sessionIp = $this->sessionCache->getItem($ipKey); $response = new Response(
$sessionIp->set($id); (string) json_encode(['register' => $payloadOut]),
$sessionIp->expiresAfter($this->config->ipTtl()); Response::HTTP_OK,
$this->sessionCache->save($sessionIp); ['Content-Type' => 'application/json'],
);
$response->headers->set(AppConstants::PASSKEY_CEREMONY_MARKER, '1');
return $response;
} }
} }
+177
View File
@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
namespace App\Service;
use Cose\Algorithm\Manager;
use Cose\Algorithm\Signature\ECDSA\ES256;
use RuntimeException;
use Symfony\Component\Serializer\Serializer;
use Throwable;
use Webauthn\AttestationStatement\AttestationStatementSupportManager;
use Webauthn\AttestationStatement\NoneAttestationStatementSupport;
use Webauthn\AuthenticatorAssertionResponseValidator;
use Webauthn\AuthenticatorAttestationResponseValidator;
use Webauthn\CeremonyStep\CeremonyStepManagerFactory;
use Webauthn\CredentialRecord;
use Webauthn\Denormalizer\WebauthnSerializerFactory;
use Webauthn\Exception\InvalidDataException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
/**
* Builds the WebAuthn collaborators, and is the one place that knows how they
* are wired.
*
* Everything that touches webauthn-lib types goes through here, so a library
* major version that renames or moves those types is a single-file change
* instead of a hunt through the codebase.
*
* **Attestation is deliberately `none`.** The alternatives were measured and
* rejected: attestation conveyance is only a preference a client may ignore,
* and the FIDO metadata service is bypassed both by the zero AAGUID that
* privacy-preserving passkeys already send and by self attestation — while
* still refusing legitimate authenticators that postdate its cached blob. See
* `docs/passkey-auth-subdomain-plan.md` §2.3 for the evidence, and `SECURITY.md`
* for the conditions that would justify revisiting it.
*/
final readonly class PasskeyCeremonyFactory
{
private AttestationStatementSupportManager $attestationStatementSupportManager;
private PasskeyCounterChecker $counterChecker;
public function __construct()
{
$manager = AttestationStatementSupportManager::create();
$manager->add(NoneAttestationStatementSupport::create());
$this->attestationStatementSupportManager = $manager;
$this->counterChecker = new PasskeyCounterChecker();
}
/**
* The wire form of the ceremony options, ready to JSON-encode for the client.
*
* Goes through the serializer rather than `json_encode()`, because the
* challenge is raw binary: `json_encode()` rejects it outright, and the
* serializer base64url-encodes exactly the fields the browser expects. Using
* one path here and another at verification time is how a challenge silently
* stops matching, so both go through this factory.
*
* @return array<string,mixed>
*/
public function optionsAsArray(PublicKeyCredentialCreationOptions|PublicKeyCredentialRequestOptions $options): array
{
return $this->serializer()->normalize($options, 'json');
}
/**
* Validator for the registration ceremony.
*
* The origins are passed in rather than read from a request, so the scheme
* and host can only ever come from configuration. This is what makes D4
* enforceable: an `http://` origin is never presented to the library as
* acceptable, no matter how the request arrived at the container.
*
* @param string[] $allowedOrigins
*/
public function creationCeremonyValidator(array $allowedOrigins): AuthenticatorAttestationResponseValidator
{
return AuthenticatorAttestationResponseValidator::create(
$this->ceremonyStepManagerFactory($allowedOrigins)->creationCeremony(),
);
}
/**
* Validator for the login (assertion) ceremony.
*
* @param string[] $allowedOrigins
*/
public function requestCeremonyValidator(array $allowedOrigins): AuthenticatorAssertionResponseValidator
{
return AuthenticatorAssertionResponseValidator::create(
$this->ceremonyStepManagerFactory($allowedOrigins)->requestCeremony(),
);
}
/**
* The ceremony steps shared by both ceremonies.
*
* `setSecuredRelyingPartyId()` is deliberately never called: it is deprecated
* in 5.2 and, more importantly, it is the escape hatch that would let an
* `http://` origin through. Development uses real TLS instead (D4).
*
* @param string[] $allowedOrigins
*/
private function ceremonyStepManagerFactory(array $allowedOrigins): CeremonyStepManagerFactory
{
$factory = new CeremonyStepManagerFactory();
$factory->setAllowedOrigins($allowedOrigins);
$factory->setAlgorithmManager(Manager::create()->add(ES256::create()));
$factory->setAttestationStatementSupportManager($this->attestationStatementSupportManager);
/* replace the library default, which rejects the constant-zero counter
* that synchronised passkeys report — see PasskeyCounterChecker */
$factory->setCounterChecker($this->counterChecker);
return $factory;
}
/**
* The serializer for every WebAuthn value: credential records, ceremony
* options, and the client's response.
*
* This must be used instead of `json_encode()`. Options carry raw binary
* (the challenge) which `json_encode()` rejects outright, and
* `CredentialRecord` is not `JsonSerializable` at all — the serializer
* base64url-encodes those fields and is required for a correct round-trip.
*
* The concrete `Serializer` is returned because the library's own return
* type (`SerializerInterface`) only declares `serialize()`/`deserialize()`,
* while this class also needs `normalize()`/`denormalize()`.
*/
public function serializer(): Serializer
{
$serializer = (new WebauthnSerializerFactory($this->attestationStatementSupportManager))->create();
/* the library's declared return type is the narrower interface, so this
* narrows it back — failing loudly if a future version ever returns
* something else, rather than erroring at the first ceremony */
if (!$serializer instanceof Serializer) {
throw new RuntimeException('Expected the WebAuthn serializer to be a '.Serializer::class.'.');
}
return $serializer;
}
public function attestationStatementSupportManager(): AttestationStatementSupportManager
{
return $this->attestationStatementSupportManager;
}
/**
* Serialize a credential record for storage.
*
* @throws InvalidDataException
*/
public function serializeCredential(CredentialRecord $record): string
{
return $this->serializer()->serialize($record, 'json');
}
/**
* Rebuild a credential record previously written by {@see serializeCredential()}.
*
* Returns null rather than throwing when the stored payload is unusable: a
* corrupt entry must degrade to "this passkey is unavailable", never to a
* 500 on the login page.
*/
public function deserializeCredential(string $json): ?CredentialRecord
{
try {
return $this->serializer()->deserialize($json, CredentialRecord::class, 'json');
} catch (Throwable) {
return null;
}
}
}
+168
View File
@@ -0,0 +1,168 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Trait\StringTrait;
use DateTimeImmutable;
use Exception;
use Override;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Attribute\Target;
/**
* Short-lived server-side state for an in-flight WebAuthn ceremony.
*
* **The client's copy of the challenge is never trusted.** Starting a ceremony
* issues the challenge *and* a separate opaque `ceremonyId`; only the
* server-side record keyed by that id is authoritative at `finish`. A client
* that swaps in its own challenge is therefore comparing against a value the
* server never issued.
*
* **Single-use.** {@see consume()} deletes the record *before* the caller
* verifies anything, so a failed or replayed `finish` cannot be retried against
* the same challenge.
*
* **Deliberately not persisted.** This uses the `nonceCache` pool, which is APCu
* and stays in memory. A ceremony that does not complete within its TTL *should*
* evaporate — persisting it would only widen the replay window across restarts.
*/
final readonly class PasskeyCeremonyStore implements PasskeyCeremonyStoreInterface
{
use StringTrait;
private const string PREFIX = 'passkey_cer_';
/** Ceremonies live 5 minutes: a user has to interact with a biometric prompt. */
public const int CEREMONY_TTL = 300;
/** 15 bytes fits neatly into a base64url string without padding. */
private const int CEREMONY_ID_BYTES = 15;
/** 32-byte challenge, per WebAuthn's recommendation. */
private const int CHALLENGE_BYTES = 32;
public function __construct(
#[Target('nonceCache')] private CacheItemPoolInterface $nonceCache,
) {
}
/**
* @return array{ceremonyId: string, challenge: string}
*
* @throws Exception
* @throws InvalidArgumentException
*/
#[Override]
public function startLogin(): array
{
/* @var array{ceremonyId: string, challenge: string} */
return $this->store(PasskeyCeremonyStoreInterface::TYPE_LOGIN, [
'challenge' => random_bytes(self::CHALLENGE_BYTES),
]);
}
/**
* @return array{ceremonyId: string, challenge: string, userHandle: string}
*
* @throws Exception
* @throws InvalidArgumentException
*/
#[Override]
public function startRegistration(string $identity): array
{
/* @var array{ceremonyId: string, challenge: string, userHandle: string} */
return $this->store(PasskeyCeremonyStoreInterface::TYPE_REGISTER, [
'challenge' => random_bytes(self::CHALLENGE_BYTES),
'identity' => $identity,
/* Derived from the identity rather than taken from the client, so a
* caller cannot register a credential against an identity it did not
* authenticate as. Fixed length, stable per identity, and it does not
* leak the label into the authenticator. */
'userHandle' => hash('sha256', $identity, true),
]);
}
/**
* Read and destroy a ceremony, returning its record.
*
* Returns null when the id is unknown, expired, already consumed, or was
* started for the other ceremony type. The caller cannot distinguish these
* cases, and does not need to.
*
* @return array{challenge: string, identity?: string, userHandle?: string}|null
*
* @throws InvalidArgumentException
*/
#[Override]
public function consume(string $ceremonyId, string $expectedType): ?array
{
$key = $this->key($ceremonyId);
$item = $this->nonceCache->getItem($key);
if (!$item->isHit()) {
return null;
}
$payload = $item->get();
/* delete before validating: a malformed or replayed record must not be
* usable again even if the checks below reject it */
$this->nonceCache->deleteItem($key);
if (!\is_array($payload)
|| ($payload['type'] ?? null) !== $expectedType
|| !isset($payload['challenge'])
|| !\is_string($payload['challenge'])
) {
return null;
}
/** @var array{challenge: string, identity?: string, userHandle?: string} $payload */
$payload = array_filter(
$payload,
static fn (string $key): bool => \in_array($key, ['challenge', 'identity', 'userHandle'], true),
\ARRAY_FILTER_USE_KEY,
);
return $payload;
}
/**
* @param array<string,string> $payload
*
* @return array<string,string>
*
* @throws Exception
* @throws InvalidArgumentException
*/
private function store(string $type, array $payload): array
{
$ceremonyId = rtrim(strtr(base64_encode(random_bytes(self::CEREMONY_ID_BYTES)), '+/', '-_'), '=');
$item = $this->nonceCache->getItem($this->key($ceremonyId));
$item->set([
'type' => $type,
...$payload,
'createdAt' => new DateTimeImmutable()->format(\DATE_ATOM),
]);
$item->expiresAfter(self::CEREMONY_TTL);
$this->nonceCache->save($item);
return ['ceremonyId' => $ceremonyId, ...$payload];
}
/**
* The ceremony id is hashed rather than passed through `makeCacheKey()`,
* because that sanitises the base64url alphabet into `_` and is therefore
* not injective — two distinct ids could collide on one cache slot.
*
* @throws InvalidArgumentException
*/
private function key(string $ceremonyId): string
{
return $this->makeCacheKey(self::PREFIX.hash('sha256', $ceremonyId));
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Service;
/**
* Server-side storage for in-flight WebAuthn ceremonies.
*
* Kept separate from {@see PasskeyManager} so the security-critical properties —
* the challenge is server-authoritative and single-use — are testable without
* constructing a real authenticator response.
*/
interface PasskeyCeremonyStoreInterface
{
public const string TYPE_LOGIN = 'login';
public const string TYPE_REGISTER = 'register';
/**
* Start a login (assertion) ceremony.
*
* @return array{ceremonyId: string, challenge: string}
*/
public function startLogin(): array;
/**
* Start a registration (attestation) ceremony for an already-authenticated
* identity.
*
* @return array{ceremonyId: string, challenge: string, userHandle: string}
*/
public function startRegistration(string $identity): array;
/**
* Read and destroy a ceremony.
*
* Returns null when the id is unknown, expired, already consumed, or was
* started for the other ceremony type.
*
* @return array{challenge: string, identity?: string, userHandle?: string}|null
*/
public function consume(string $ceremonyId, string $expectedType): ?array;
}
+52
View File
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace App\Service;
use Override;
use Webauthn\Counter\CounterChecker;
use Webauthn\CredentialRecord;
use Webauthn\Exception\CounterException;
/**
* Signature-counter policy for passkey assertions.
*
* **Why this replaces the library default.** `ThrowExceptionIfInvalid` (the
* default wired up by `CeremonyStepManagerFactory`) requires the reported
* counter to be *strictly greater* than the stored one. That is wrong for the
* passkeys this feature targets: platform passkeys are synchronised through the
* OS keychain, and a synchronised authenticator reports a constant `0` forever
* (the spec permits it, and the multi-device design effectively requires it).
* Measured against the installed library:
*
* stored 0, reported 0 -> `ThrowExceptionIfInvalid` throws `CounterException`
*
* so with the default checker a brand-new synced passkey fails on its *first*
* login — and only on real hardware, never in a unit test that increments the
* counter. That is the worst possible failure shape, so the default is not used.
*
* **What is kept.** A counter that goes *backwards* still fails. That is the one
* signal the counter can carry (a cloned authenticator replaying an older
* assertion), and rejecting it costs nothing because a genuine synchronised
* passkey only ever reports the same value or a larger one.
*
* Note this is defence in depth and not relied upon for security: a
* synchronised passkey's counter carries no clone signal at all, which is why
* `SECURITY.md` records that clone detection is explicitly not a property this
* feature claims. The real protections are per-credential challenge binding,
* origin/RP-ID checks, and the user-verification requirement.
*/
final readonly class PasskeyCounterChecker implements CounterChecker
{
/**
* @throws CounterException when the reported counter moves backwards
*/
#[Override]
public function check(CredentialRecord $credentialRecord, int $currentCounter): void
{
if ($currentCounter < $credentialRecord->counter) {
throw CounterException::create($currentCounter, $credentialRecord->counter, 'The signature counter moved backwards, which can indicate a cloned authenticator.');
}
}
}
+266
View File
@@ -0,0 +1,266 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\AppConstants;
use App\Data\PasskeyCredential;
use App\MonitorCacheKeys;
use App\Trait\StringTrait;
use DateTimeImmutable;
use Override;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Attribute\Target;
use Webauthn\CredentialRecord;
/**
* @see PasskeyCredentialStoreInterface
*
* **Persistence.** The pool is wrapped in a {@see MonitorCacheKeys}, exactly
* as `LoginManager` and `BackupCodeManager` do. Without that wrapper the
* credentials would live only in the APCu-side pool and disappear on the next
* container restart, because `PersistCache::persist()` only flushes keys that a
* monitor recorded. `PasskeyCredentialStoreTest` asserts visibility in the
* underlying persistent pool, not just the wrapped one.
*
* **Layout.**
* passkey_cred_<key(credentialId)> -> serialized credential + metadata
* passkey_index -> credentialId => {identity, label, createdAt}
*
* The index exists so the login page can build `allowCredentials` without
* enumerating the whole key space, and so a corrupt credential cannot make the
* list disappear entirely.
*/
final readonly class PasskeyCredentialStore implements PasskeyCredentialStoreInterface
{
use StringTrait;
private const string PREFIX = 'passkey_cred_';
private const string INDEX_KEY = 'passkey_index';
private MonitorCacheKeys $sessionCache;
/**
* @throws InvalidArgumentException
*/
public function __construct(
#[Target('sessionCache')] CacheItemPoolInterface $sessionCache,
private PasskeyCeremonyFactory $ceremonyFactory,
) {
$this->sessionCache = new MonitorCacheKeys($sessionCache);
}
/**
* @throws InvalidArgumentException
*/
#[Override]
public function all(): array
{
$credentials = [];
foreach ($this->credentialIds() as $credentialId) {
$credential = $this->find($credentialId);
if (null !== $credential) {
$credentials[] = $credential;
}
}
return $credentials;
}
/**
* @throws InvalidArgumentException
*/
#[Override]
public function find(string $credentialId): ?PasskeyCredential
{
$item = $this->sessionCache->getItem($this->credentialKey($credentialId));
if (!$item->isHit()) {
return null;
}
$payload = $item->get();
if (!\is_array($payload)
|| !isset($payload['record'], $payload['identity'], $payload['label'], $payload['createdAt'])
) {
return null;
}
$record = $this->ceremonyFactory->deserializeCredential((string) $payload['record']);
if (null === $record) {
return null;
}
/* Guard against an index/record mismatch: the stored record decides which
* credential id it answers to. */
if (!hash_equals($record->publicKeyCredentialId, $credentialId)) {
return null;
}
return new PasskeyCredential(
$record,
(string) $payload['identity'],
(string) $payload['label'],
new DateTimeImmutable((string) $payload['createdAt']),
isset($payload['lastUsedAt']) ? new DateTimeImmutable((string) $payload['lastUsedAt']) : null,
);
}
/**
* @throws InvalidArgumentException
*/
#[Override]
public function findByIdentity(string $identity): array
{
$matches = [];
foreach ($this->all() as $credential) {
if (hash_equals($credential->identity, $identity)) {
$matches[] = $credential;
}
}
return $matches;
}
/**
* @throws InvalidArgumentException
*/
#[Override]
public function save(PasskeyCredential $credential): void
{
$credentialId = $credential->record->publicKeyCredentialId;
$item = $this->sessionCache->getItem($this->credentialKey($credentialId));
$item->set([
'record' => $this->ceremonyFactory->serializeCredential($credential->record),
'identity' => $credential->identity,
'label' => $credential->label,
'createdAt' => $credential->createdAt->format(\DATE_ATOM),
'lastUsedAt' => $credential->lastUsedAt?->format(\DATE_ATOM),
]);
/* per PSR6, if no expiration is set, implementation may set a default,
* we want this to keep forever, so a few hundred years should do it */
$item->expiresAt($this->forever());
$this->sessionCache->save($item);
$this->writeIndexEntry($credentialId, [
'identity' => $credential->identity,
'label' => $credential->label,
'createdAt' => $credential->createdAt->format(\DATE_ATOM),
]);
}
/**
* @throws InvalidArgumentException
*/
#[Override]
public function updateUsage(CredentialRecord $record): void
{
$existing = $this->find($record->publicKeyCredentialId);
if (null === $existing) {
return;
}
$this->save($existing->withUsage($record, new DateTimeImmutable()));
}
/**
* @throws InvalidArgumentException
*/
#[Override]
public function remove(string $credentialId): bool
{
$index = $this->readIndex();
$existed = \array_key_exists($credentialId, $index);
unset($index[$credentialId]);
$this->writeIndex($index);
return $this->sessionCache->deleteItem($this->credentialKey($credentialId)) || $existed;
}
/**
* @throws InvalidArgumentException
*/
#[Override]
public function count(): int
{
return \count($this->credentialIds());
}
/**
* Credential ids from the index only.
*
* Deliberately not `getKeys()`: keys are truncated to a fixed length by
* `makeCacheKey()`, so enumerating them cannot reliably recover a full
* credential id. The index stores the ids verbatim.
*
* @return string[]
*
* @throws InvalidArgumentException
*/
private function credentialIds(): array
{
return array_keys($this->readIndex());
}
/**
* @return array<string,array{identity: string, label: string, createdAt: string}>
*
* @throws InvalidArgumentException
*/
private function readIndex(): array
{
$item = $this->sessionCache->getItem(self::INDEX_KEY);
$index = $item->isHit() ? $item->get() : null;
return \is_array($index) ? $index : [];
}
/**
* @param array<string,array{identity: string, label: string, createdAt: string}> $index
*
* @throws InvalidArgumentException
*/
private function writeIndex(array $index): void
{
$item = $this->sessionCache->getItem(self::INDEX_KEY);
$item->set($index);
$item->expiresAt($this->forever());
$this->sessionCache->save($item);
}
/**
* @param array{identity: string, label: string, createdAt: string} $entry
*
* @throws InvalidArgumentException
*/
private function writeIndexEntry(string $credentialId, array $entry): void
{
$index = $this->readIndex();
$index[$credentialId] = $entry;
$this->writeIndex($index);
}
/** Credentials and the index are kept indefinitely; only removal clears them. */
private function forever(): DateTimeImmutable
{
return DateTimeImmutable::createFromFormat('Y-m-d', AppConstants::FAR_FUTURE_DATE);
}
/**
* Cache key for one credential id.
*
* The id is hashed rather than passed through `makeCacheKey()`, because that
* sanitises the base64url alphabet into a single `_` and is therefore not
* injective: "abc-def" and "abc_def" both become "abc_def", so two distinct
* credentials could share one cache slot and one of them would silently
* overwrite the other. A hash is injective for practical purposes and keeps
* the key within the allowed character set.
*/
private function credentialKey(string $credentialId): string
{
return self::PREFIX.hash('sha256', $credentialId);
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Data\PasskeyCredential;
use Webauthn\CredentialRecord;
/**
* Persistence for registered passkeys, backed by the `sessionCache` pool so that
* credentials survive a container restart the same way sessions do.
*
* The identity is stored alongside the credential and is authoritative on
* assertion: the `userHandle` a client returns is attacker-controlled and is
* compared for consistency but never used to decide who is logging in.
*/
interface PasskeyCredentialStoreInterface
{
/**
* Every registered credential, for the login ceremony's `allowCredentials`.
*
* Credentials whose stored payload cannot be read are skipped rather than
* failing the ceremony, so one bad entry cannot lock everyone out.
*
* @return PasskeyCredential[]
*/
public function all(): array;
/**
* Look up a single credential by its raw credential id.
*/
public function find(string $credentialId): ?PasskeyCredential;
/**
* Every credential belonging to one identity.
*
* @return PasskeyCredential[]
*/
public function findByIdentity(string $identity): array;
/**
* Persist a newly registered credential.
*/
public function save(PasskeyCredential $credential): void;
/**
* Record that a credential was just used, refreshing its counter.
*/
public function updateUsage(CredentialRecord $record): void;
/**
* Forget a credential.
*
* @return bool true when a credential was removed
*/
public function remove(string $credentialId): bool;
public function count(): int;
}
+58
View File
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Data\PasskeyCredential;
use Throwable;
/**
* Both WebAuthn ceremonies, expressed without any library types in the
* signature so callers never depend on webauthn-lib directly.
*/
interface PasskeyInterface
{
/**
* Step 1 of the login ceremony: issue a challenge and the credential list.
*
* @return array{publicKey: mixed, ceremonyId: string}
*
* @throws Throwable
*/
public function beginLogin(): array;
/**
* Step 3 of the login ceremony: verify an assertion.
*
* Null means "not authenticated", and the caller must not distinguish
* between the possible causes.
*
* @param array<string,mixed> $body
*
* @throws Throwable
*/
public function finishLogin(array $body): ?PasskeyCredential;
/**
* Step 1 of the registration ceremony. Only reachable once the caller has
* already authenticated with a TOTP code.
*
* @return array{publicKey: mixed, ceremonyId: string}
*
* @throws Throwable
*/
public function beginRegistration(string $identity): array;
/**
* Step 3 of the registration ceremony: verify an attestation and store the
* credential.
*
* Null means "not registered".
*
* @param array<string,mixed> $body
*
* @throws Throwable
*/
public function finishRegistration(array $body): ?PasskeyCredential;
}
+312
View File
@@ -0,0 +1,312 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Data\PasskeyCredential;
use App\Service\PasskeyCeremonyStoreInterface as Ceremonies;
use DateTimeImmutable;
use Override;
use ParagonIE\ConstantTime\Base64UrlSafe;
use Throwable;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\AuthenticatorSelectionCriteria;
use Webauthn\CredentialRecord;
use Webauthn\PublicKeyCredential;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialDescriptor;
use Webauthn\PublicKeyCredentialParameters;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialRpEntity;
use Webauthn\PublicKeyCredentialUserEntity;
/**
* Owns both WebAuthn ceremonies.
*
* **Library containment.** Every `Webauthn\*` type used by the application is
* referenced in this file and {@see PasskeyCeremonyFactory}, so a v6 rename
* touches two files rather than the whole codebase.
*
* **What is never trusted.** The challenge (server-authoritative, single-use —
* see {@see PasskeyCeremonyStore}), the `userHandle` (read from the stored
* credential, never from the client), and the credential id (it selects which
* stored record to verify against). The library performs the cryptographic
* verification of origin, RP ID hash, challenge, user presence/verification and
* signature; this class supplies the inputs and interprets the outcome.
*/
final readonly class PasskeyManager implements PasskeyInterface
{
/** ES256 is mandatory for WebAuthn; other algorithms buy nothing here. */
private const int COSE_ALGORITHM_ES256 = -7;
public function __construct(
private PasskeyPolicyInterface $policy,
private Ceremonies $ceremonies,
private PasskeyCredentialStoreInterface $credentials,
private PasskeyCeremonyFactory $factory,
) {
}
/**
* Step 1 of the login ceremony.
*
* @return array{publicKey: mixed, ceremonyId: string}
*
* @throws Throwable
*/
#[Override]
public function beginLogin(): array
{
$ceremony = $this->ceremonies->startLogin();
$options = new PublicKeyCredentialRequestOptions(
$ceremony['challenge'],
$this->policy->rpId(),
$this->credentialDescriptors(),
$this->policy->userVerification(),
$this->policy->timeout(),
);
return [
'publicKey' => $this->factory->optionsAsArray($options),
'ceremonyId' => $ceremony['ceremonyId'],
];
}
/**
* Step 3 of the login ceremony: verify the assertion and report the identity.
*
* Returns null on any failure — the caller must not be able to distinguish
* "unknown credential" from "bad signature" from "wrong origin", or the
* endpoint becomes an oracle for credential enumeration.
*
* @param array<string,mixed> $body
*
* @throws Throwable
*/
#[Override]
public function finishLogin(array $body): ?PasskeyCredential
{
$ceremonyId = $this->stringOrNull($body['ceremonyId'] ?? null);
$credentialJson = $body['credential'] ?? null;
if (null === $ceremonyId || !\is_array($credentialJson)) {
return null;
}
$ceremony = $this->ceremonies->consume($ceremonyId, Ceremonies::TYPE_LOGIN);
if (null === $ceremony) {
return null;
}
$publicKeyCredential = $this->deserializeCredential($credentialJson);
if (!$publicKeyCredential instanceof PublicKeyCredential
|| !$publicKeyCredential->response instanceof AuthenticatorAssertionResponse
) {
return null;
}
/* the credential id selects the record: an attacker cannot nominate a
* different credential than the one they hold the key for.
*
* Inside the try: a cache failure must degrade to "this passkey is
* unavailable", never to a 500 on the login page. */
try {
$stored = $this->credentials->find($publicKeyCredential->rawId);
if (null === $stored) {
return null;
}
$updated = $this->factory
->requestCeremonyValidator($this->policy->allowedOrigins())
->check(
$stored->record,
$publicKeyCredential->response,
$this->requestOptions($ceremony['challenge']),
$this->policy->authSubdomain(),
$stored->record->userHandle,
);
} catch (Throwable) {
/* deliberately not surfaced: see the note above */
return null;
}
$this->credentials->updateUsage($updated);
return $stored->withUsage($updated, new DateTimeImmutable());
}
/**
* Step 1 of the registration ceremony. Only reachable once the caller has
* already proven possession of the TOTP secret (see the flow in the plan).
*
* @return array{publicKey: mixed, ceremonyId: string}
*
* @throws Throwable
*/
#[Override]
public function beginRegistration(string $identity): array
{
$ceremony = $this->ceremonies->startRegistration($identity);
return [
'publicKey' => $this->factory->optionsAsArray($this->creationOptions(
$ceremony['challenge'],
$identity,
$ceremony['userHandle'],
)),
'ceremonyId' => $ceremony['ceremonyId'],
];
}
/**
* Step 3 of the registration ceremony: verify the attestation and persist
* the credential under the identity that was authenticated in step 1.
*
* @param array<string,mixed> $body
*
* @throws Throwable
*/
#[Override]
public function finishRegistration(array $body): ?PasskeyCredential
{
$ceremonyId = $this->stringOrNull($body['ceremonyId'] ?? null);
$credentialJson = $body['credential'] ?? null;
if (null === $ceremonyId || !\is_array($credentialJson)) {
return null;
}
$ceremony = $this->ceremonies->consume($ceremonyId, Ceremonies::TYPE_REGISTER);
if (null === $ceremony || !isset($ceremony['identity'], $ceremony['userHandle'])) {
return null;
}
$publicKeyCredential = $this->deserializeCredential($credentialJson);
if (!$publicKeyCredential instanceof PublicKeyCredential
|| !$publicKeyCredential->response instanceof AuthenticatorAttestationResponse
) {
return null;
}
try {
$record = $this->factory
->creationCeremonyValidator($this->policy->allowedOrigins())
->check(
$publicKeyCredential->response,
$this->creationOptions(
$ceremony['challenge'],
$ceremony['identity'],
$ceremony['userHandle'],
),
$this->policy->authSubdomain(),
);
} catch (Throwable) {
return null;
}
$credential = new PasskeyCredential(
$record,
$ceremony['identity'],
$this->labelFor($record),
new DateTimeImmutable(),
);
try {
$this->credentials->save($credential);
} catch (Throwable) {
/* a store that cannot persist a credential must not report success:
* the user would believe the passkey was registered and then find it
* missing at the next login */
return null;
}
return $credential;
}
private function requestOptions(string $challenge): PublicKeyCredentialRequestOptions
{
return new PublicKeyCredentialRequestOptions(
$challenge,
$this->policy->rpId(),
$this->credentialDescriptors(),
/* userVerification must be present for the library to enforce the
* user-verified flag; it is not re-read from the client request */
$this->policy->userVerification(),
$this->policy->timeout(),
);
}
private function creationOptions(string $challenge, string $identity, string $userHandle): PublicKeyCredentialCreationOptions
{
return new PublicKeyCredentialCreationOptions(
new PublicKeyCredentialRpEntity($this->policy->rpName(), $this->policy->rpId()),
new PublicKeyCredentialUserEntity($identity, $userHandle, $identity),
$challenge,
[PublicKeyCredentialParameters::create('public-key', self::COSE_ALGORITHM_ES256)],
new AuthenticatorSelectionCriteria(
/* a passkey for this device, which is what the "register this
* device" checkbox promises */
AuthenticatorSelectionCriteria::AUTHENTICATOR_ATTACHMENT_PLATFORM,
$this->policy->userVerification(),
AuthenticatorSelectionCriteria::RESIDENT_KEY_REQUIREMENT_PREFERRED,
),
/* D5: 'none' — see the plan §2.3 and SECURITY.md */
'none',
/* also discourage registering the same device twice */
$this->credentialDescriptors(),
$this->policy->timeout(),
);
}
/**
* Descriptors for every stored credential, used both as `allowCredentials`
* on login and as `excludeCredentials` on registration.
*
* @return PublicKeyCredentialDescriptor[]
*/
private function credentialDescriptors(): array
{
$descriptors = [];
foreach ($this->credentials->all() as $credential) {
$descriptors[] = PublicKeyCredentialDescriptor::create(
'public-key',
$credential->record->publicKeyCredentialId,
$credential->record->transports,
);
}
return $descriptors;
}
/**
* @param array<string,mixed> $data
*/
private function deserializeCredential(array $data): ?PublicKeyCredential
{
try {
return $this->factory->serializer()->denormalize($data, PublicKeyCredential::class, 'json');
} catch (Throwable) {
return null;
}
}
/**
* A short, stable description so a user can tell their keys apart.
*
* Derived from the credential id because the AAGUID is not a reliable
* identity without the FIDO metadata service, which D5 deliberately does
* not use.
*/
private function labelFor(CredentialRecord $record): string
{
return 'Passkey '.substr(Base64UrlSafe::encodeUnpadded($record->publicKeyCredentialId), 0, 8);
}
private function stringOrNull(mixed $value): ?string
{
return \is_string($value) && '' !== $value ? $value : null;
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\ConfigBag;
use App\Exception\PasskeyConfigurationException;
use Override;
use Symfony\Component\HttpFoundation\Request;
/**
* @see PasskeyPolicyInterface for the decisions this class enforces
*
* **On scheme handling (D4).** The container serves plain HTTP and sits behind a
* TLS-terminating proxy, so the application never learns the public scheme from
* its own configuration — only from `X-Forwarded-Proto`, which Symfony resolves
* through `trusted_proxies` / `trusted_headers` in `framework.yaml`. The scheme
* is therefore enforced two independent ways rather than asserted at boot:
*
* 1. The allowed origin is hardcoded to `https://` here and is never taken from
* the request, so the library's origin check rejects an `http://` ceremony
* no matter how the request arrived.
* 2. {@see isAvailableFor()} additionally requires the request to be secure, so
* a visitor on a non-secure connection is never shown a passkey button that
* the browser would refuse to act on.
*/
final readonly class PasskeyPolicy implements PasskeyPolicyInterface
{
private const string SCHEME = 'https';
public function __construct(
private ConfigBag $config,
private DomainInterface $domainManager,
) {
}
#[Override]
public function isEnabled(): bool
{
return $this->config->passkeyEnabled() && null !== $this->domainManager->authBase();
}
#[Override]
public function isAvailableFor(Request $request): bool
{
return $this->isEnabled()
&& $request->isSecure()
&& $this->domainManager->getAuthSubdomain() === $request->getHost();
}
#[Override]
public function rpId(): string
{
return $this->domainManager->authBase() ?? throw $this->notConfigured();
}
#[Override]
public function allowedOrigins(): array
{
return [self::SCHEME.'://'.$this->authSubdomain()];
}
#[Override]
public function authSubdomain(): string
{
$subdomain = $this->domainManager->getAuthSubdomain();
return $subdomain ?? throw $this->notConfigured();
}
#[Override]
public function rpName(): string
{
return $this->config->passkeyRpName() ?: $this->config->title();
}
#[Override]
public function userVerification(): string
{
return $this->config->passkeyUserVerification();
}
#[Override]
public function timeout(): int
{
return $this->config->passkeyTimeout();
}
/**
* @throws PasskeyConfigurationException
*/
#[Override]
public function assertConfigurationIsUsable(): void
{
if (!$this->config->passkeyEnabled()) {
return;
}
/* D1: without a base domain there is no RP ID and no shared credential */
if (null === $this->domainManager->authBase()) {
throw new PasskeyConfigurationException('PASSKEY_ENABLED is on, but central authentication is not configured. Passkeys require SUBDOMAIN_REDIRECT=1 together with a valid AUTH_SUBDOMAIN whose base domain can be determined (a domain such as "auth.example.com" — not "localhost" and not an IP address). Either configure central authentication or set PASSKEY_ENABLED=0.');
}
/* D4: the subdomain must be a real domain able to present a TLS certificate.
* authBase() returning null already excludes localhost and bare IPs, so
* this guards against an auth subdomain that is a single label. */
if (!str_contains($this->authSubdomain(), '.')) {
throw new PasskeyConfigurationException('AUTH_SUBDOMAIN must be a fully qualified domain name (for example "auth.example.com") because passkeys require HTTPS and a certificate cannot be issued for a single-label host.');
}
}
private function notConfigured(): PasskeyConfigurationException
{
return new PasskeyConfigurationException(
'Passkeys are enabled but central authentication is not configured, '
.'so no relying party identity is available.',
);
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Exception\PasskeyConfigurationException;
use Symfony\Component\HttpFoundation\Request;
/**
* Single source of truth for whether passkeys may be offered, and under which
* relying-party identity.
*
* Two project decisions are enforced here and nowhere else:
*
* - **D1 — central auth is a prerequisite.** A passkey is only meaningful when
* the whole base domain shares one relying party, so passkeys are unavailable
* unless `SUBDOMAIN_REDIRECT` is on and `AUTH_SUBDOMAIN` resolves to a base
* domain. The RP ID is therefore always that base domain.
*
* - **D4 — HTTPS is required, with no exemption.** The origin handed to the
* browser is built here as `https://{authSubdomain}` and is *never* derived
* from the incoming request, so an `http://` origin can never be accepted.
* The deprecated `setSecuredRelyingPartyId()` escape hatch is not used, and
* there is deliberately no configuration override that could reintroduce one.
*/
interface PasskeyPolicyInterface
{
/**
* True when passkeys are switched on by configuration AND that configuration
* satisfies D1. Availability to a particular visitor additionally requires
* {@see isAvailableFor()}.
*/
public function isEnabled(): bool;
/**
* Whether the passkey UI should be offered for this request.
*
* Requires the feature to be enabled, the request to be aimed at the auth
* subdomain (the only place a ceremony may run), and the visitor to actually
* be on HTTPS — see the note on scheme handling in {@see PasskeyPolicy}.
*/
public function isAvailableFor(Request $request): bool;
/**
* The relying party ID: always the base domain of the auth subdomain.
*
* @throws PasskeyConfigurationException when passkeys are enabled without D1
*/
public function rpId(): string;
/**
* Relying party origins allowed to complete a ceremony.
*
* Always exactly one entry, always `https://`, always derived from
* configuration rather than from the request (D4).
*
* @return string[]
*
* @throws PasskeyConfigurationException when passkeys are enabled without D1
*/
public function allowedOrigins(): array;
/** The auth subdomain that ceremonies must be served from. */
public function authSubdomain(): string;
/** Human-readable name shown in the authenticator prompt. */
public function rpName(): string;
/** `required`, `preferred` or `discouraged`. */
public function userVerification(): string;
/** Ceremony timeout in milliseconds, as passed to the browser. */
public function timeout(): int;
/**
* Fails hard when passkeys are enabled in a configuration that cannot work.
*
* Called during cache warm-up so a misconfigured deployment never reaches a
* browser: the container refuses to start instead.
*
* @throws PasskeyConfigurationException
*/
public function assertConfigurationIsUsable(): void;
}
+141
View File
@@ -0,0 +1,141 @@
<?php
declare(strict_types=1);
namespace App\Service;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
/**
* Matches request paths against configured public path patterns.
*
* Patterns are provided as a comma-separated string in the format:
* /path/pattern, host.example.com/path/pattern, or a mix.
*
* Wildcards:
* - * matches any characters within a single path segment (not crossing /)
* - ** matches any characters including / (crosses path segments)
*
* Query strings are not part of the pattern — matching is against the
* path only.
*/
final readonly class PublicPathMatcher implements PublicPathMatcherInterface
{
/** @var list<array{host: ?string, regex: string}> */
private array $patterns;
public function __construct(
#[Autowire('%app.public_paths%')] string $publicPaths,
) {
$this->patterns = $this->parse($publicPaths);
}
public function isEmpty(): bool
{
return [] === $this->patterns;
}
public function matches(string $host, string $path): bool
{
if ([] === $this->patterns) {
return false;
}
$host = strtolower($host);
foreach ($this->patterns as $entry) {
if (null !== $entry['host'] && $entry['host'] !== $host) {
continue;
}
if (1 === preg_match($entry['regex'], $path)) {
return true;
}
}
return false;
}
/**
* Parse the comma-separated PUBLIC_PATHS string into pattern entries.
*
* @return list<array{host: ?string, regex: string}>
*/
private function parse(string $publicPaths): array
{
if ('' === trim($publicPaths)) {
return [];
}
$patterns = [];
foreach (explode(',', $publicPaths) as $raw) {
$entry = trim($raw);
if ('' === $entry) {
continue;
}
// Check for a host prefix (anything before the first /)
$host = null;
$path = $entry;
if (preg_match('/^([a-z0-9.-]+)(\/.*)$/i', $entry, $m)) {
$host = strtolower($m[1]);
$path = $m[2];
}
// Validate path starts with /
if (!str_starts_with($path, '/')) {
continue;
}
$patterns[] = [
'host' => $host,
'regex' => $this->compilePattern($path),
];
}
return $patterns;
}
/**
* Convert a wildcard path pattern into a regex string.
*
* Star becomes a character class matching one or more non-slash chars.
* Double-star at end of pattern matches zero or more of any char.
* Double-star followed by slash matches zero or more path segments.
* Other characters are escaped as literal regex.
*/
private function compilePattern(string $pattern): string
{
$regex = '';
$length = \strlen($pattern);
$i = 0;
while ($i < $length) {
// Check for ** (must be at current position)
if ($i + 1 < $length && '*' === $pattern[$i] && '*' === $pattern[$i + 1]) {
$i += 2;
if ($i >= $length) {
// ** at end of pattern: zero or more chars including /
$regex .= '.*';
} elseif ('/' === $pattern[$i]) {
// /**/ in middle: zero or more intermediate segments
$regex .= '(?:.*/)?';
++$i; // skip the / after **
} else {
// ** not followed by / or end, treat as .*
$regex .= '.*';
}
} elseif ('*' === $pattern[$i]) {
$regex .= '[^/]+';
++$i;
} else {
$regex .= preg_quote($pattern[$i], '#');
++$i;
}
}
return '#^'.$regex.'$#';
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Service;
/**
* Matches request paths against configured public path patterns.
*
* Patterns support simple wildcards:
* - `*` matches any characters within a single path segment (not crossing `/`)
* - `**` matches any characters including `/` (crosses path segments)
*
* Patterns may optionally include a host prefix (e.g. `example.com/public/**`).
* When no host prefix is given, the pattern matches on any host.
*/
interface PublicPathMatcherInterface
{
/**
* Returns true if the given host and path match any configured public pattern.
*
* @param string $host The request host (e.g. "code.example.com")
* @param string $path The request path (e.g. "/public/repo/issues")
*/
public function matches(string $host, string $path): bool;
/**
* Returns true if no public paths are configured (feature is disabled).
*/
public function isEmpty(): bool;
}
+151
View File
@@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\ConfigBag;
use App\Enum\Scope;
use App\MonitorCacheKeys;
use App\Trait\CookieNameTrait;
use App\Trait\HasLoggerTrait;
use App\Trait\StringTrait;
use Override;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Attribute\Target;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Uid\Ulid;
/**
* Grants access once an identity has been authenticated, by whatever method.
*
* Extracted from `LoginManager` so the passkey ceremony and the TOTP form
* produce **byte-identical** outcomes. Two implementations would inevitably
* drift — most likely in cookie attributes, where a difference is invisible
* until it breaks in a browser.
*
* This class deliberately knows nothing about *how* authentication happened; it
* only records the result.
*
* @see SessionIssuerInterface
*/
final readonly class SessionIssuer implements SessionIssuerInterface
{
use CookieNameTrait;
use HasLoggerTrait;
use StringTrait;
private MonitorCacheKeys $sessionCache;
/**
* @throws InvalidArgumentException
*/
public function __construct(
#[Target('sessionCache')] CacheItemPoolInterface $sessionCache,
private DomainInterface $domainManager,
private ConfigBag $config,
) {
$this->sessionCache = new MonitorCacheKeys($sessionCache);
}
/**
* @throws InvalidArgumentException
*/
#[Override]
public function issue(string $identity, Scope $scope, Request $request, bool $json): Response
{
/* the same normalisation LoginManager has always applied, so cache keys
* and Remote-User values stay identical between the two login paths */
$cleanId = $this->makeCacheKey($identity);
$response = $this->authSuccessResponse($cleanId, $this->config);
/* when the caller only wanted this one page, there is nothing to store */
if (Scope::None === $scope) {
$this->logger->debug("successful login for: $cleanId");
return $response;
}
if (Scope::Cookie === $scope) {
$response->headers->setCookie($this->setCookie($cleanId, $request->getHost()));
} elseif (Scope::Ip === $scope) {
$this->setIp($cleanId, (string) $request->getClientIp());
}
if ($json) {
$contentType = 'application/json';
$content = (string) json_encode([
'message' => 'Login successful',
'nonce' => null,
]);
} else {
$contentType = 'text/html';
$content = "hi $cleanId, please reload";
}
$location = $request->query->has('return')
&& $this->domainManager->validReturn((string) $request->query->get('return')) ?
"{$request->query->get('return')}" :
"{$request->getPathInfo()}{$request->getQueryString()}";
/* force redirect to use GET method (important when using central auth) */
$response->setContent($content)
->setStatusCode(Response::HTTP_SEE_OTHER)
->headers->set('Location', $location);
$response->headers->set('Content-Type', $contentType);
$this->logger->debug("successful login for: $cleanId");
return $response;
}
/**
* @throws InvalidArgumentException
*/
private function setCookie(string $id, string $host): Cookie
{
/* successful auth with token, store session and set the cookie */
$ulid = new Ulid();
$sessionCookie = $this->sessionCache->getItem(
$this->makeCacheKey("cookie_$ulid"),
);
if ($sessionCookie->isHit()) {
/* it is supposed to be impossible to have collisions */
$this->logger->error('aborting: ULID collision');
throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'Internal Server Error');
}
$sessionCookie->set($id);
$sessionCookie->expiresAfter($this->config->cookieTtl());
$this->sessionCache->save($sessionCookie);
return Cookie::create(
name: $this->sessionCookieName($this->domainManager),
value: $ulid->toString(),
expire: time() + $this->config->cookieTtl(),
path: '/',
domain: $this->sessionCookieDomain($this->domainManager, $host),
secure: true,
httpOnly: true,
sameSite: Cookie::SAMESITE_STRICT,
);
}
/**
* @throws InvalidArgumentException
*/
private function setIp(string $id, string $ip): void
{
/* successful auth with token, requested scope of ip (and ip access enabled) */
$ipKey = $this->makeCacheKey("ip_$ip");
$sessionIp = $this->sessionCache->getItem($ipKey);
$sessionIp->set($id);
$sessionIp->expiresAfter($this->config->ipTtl());
$this->sessionCache->save($sessionIp);
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Enum\Scope;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Grants access after a successful authentication, regardless of method.
*
* Exists so the TOTP form and the passkey ceremony cannot drift apart: they must
* produce identical cookies, headers and redirects, and the only reliable way to
* guarantee that is for both to call the same code.
*/
interface SessionIssuerInterface
{
/**
* Record the authenticated identity according to the requested scope and
* build the response the caller should return.
*
* @param string $identity the session id, as typed by the user
* @param Scope $scope whether to set a cookie, an IP session, or neither
* @param bool $json JSON for an AJAX caller, HTML for a form post
*/
public function issue(string $identity, Scope $scope, Request $request, bool $json): Response;
}
+30 -4
View File
@@ -1,22 +1,48 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Trait; namespace App\Trait;
trait CookieNameTrait { use App\Service\DomainInterface;
trait CookieNameTrait
{
private const string COOKIE_NAME = '__Host-Http-Preauth'; private const string COOKIE_NAME = '__Host-Http-Preauth';
private const string AUTH_COOKIE_NAME = '__Http-Domain-Preauth'; private const string AUTH_COOKIE_NAME = '__Http-Domain-Preauth';
private const string HEADER_NAME = 'X-Preauth'; private const string HEADER_NAME = 'X-Preauth';
final protected function cookieName(): string { final protected function cookieName(): string
{
return static::COOKIE_NAME; return static::COOKIE_NAME;
} }
final protected function authCookieName(): string { final protected function authCookieName(): string
{
return static::AUTH_COOKIE_NAME; return static::AUTH_COOKIE_NAME;
} }
final protected function headerName(): string { final protected function headerName(): string
{
return static::HEADER_NAME; return static::HEADER_NAME;
} }
/**
* Returns the appropriate cookie name based on whether central auth is active.
* Uses the __Host- prefix for single-domain mode (no Domain attribute),
* and a non-prefixed name for central auth (Domain attribute required).
*/
final protected function sessionCookieName(DomainInterface $domainManager): string
{
return $domainManager->authBase() ? $this->authCookieName() : $this->cookieName();
}
/**
* Returns the cookie domain for central auth mode, or null for single-domain.
* The domain is only set when the host matches the auth base domain.
*/
final protected function sessionCookieDomain(DomainInterface $domainManager, string $host): ?string
{
return $domainManager->matchesAuth($host) ? $domainManager->authBase() : null;
}
} }
+11 -5
View File
@@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Trait; namespace App\Trait;
@@ -6,24 +7,29 @@ namespace App\Trait;
use App\ConfigBag; use App\ConfigBag;
use OTPHP\Factory; use OTPHP\Factory;
use OTPHP\TOTPInterface; use OTPHP\TOTPInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Contracts\Service\Attribute\Required; use Symfony\Contracts\Service\Attribute\Required;
trait GetTotpTrait { trait GetTotpTrait
{
protected readonly ConfigBag $config; protected readonly ConfigBag $config;
#[Required] #[Required]
public function setConfig(ConfigBag $config): void { public function setConfig(ConfigBag $config): void
{
$this->config = $config; $this->config = $config;
} }
protected function getTotp(): TOTPInterface { protected function getTotp(): TOTPInterface
{
$otp = Factory::loadFromProvisioningUri( $otp = Factory::loadFromProvisioningUri(
$this->config->totpUri(), $this->config->clock() $this->config->totpUri(),
$this->config->clock(),
); );
if ($otp instanceof TOTPInterface) { if ($otp instanceof TOTPInterface) {
return $otp; return $otp;
} }
throw new HttpException(500, 'Internal Server Exception'); throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'Internal Server Error');
} }
} }
+5 -2
View File
@@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Trait; namespace App\Trait;
@@ -6,11 +7,13 @@ namespace App\Trait;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Contracts\Service\Attribute\Required; use Symfony\Contracts\Service\Attribute\Required;
trait HasLoggerTrait { trait HasLoggerTrait
{
protected readonly LoggerInterface $logger; protected readonly LoggerInterface $logger;
#[Required] #[Required]
public function setLogger(LoggerInterface $logger): void { public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger; $this->logger = $logger;
} }
} }
+14 -9
View File
@@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Trait; namespace App\Trait;
@@ -6,11 +7,13 @@ namespace App\Trait;
use Exception; use Exception;
use Psr\Cache\CacheItemPoolInterface; use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException; use Psr\Cache\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Attribute\Target;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Contracts\Service\Attribute\Required; use Symfony\Contracts\Service\Attribute\Required;
trait MakeNonceTrait { trait MakeNonceTrait
{
use HasLoggerTrait; use HasLoggerTrait;
use StringTrait; use StringTrait;
@@ -21,26 +24,27 @@ trait MakeNonceTrait {
protected readonly CacheItemPoolInterface $nonceCache; protected readonly CacheItemPoolInterface $nonceCache;
#[Required] #[Required]
public function setNonceCache(CacheItemPoolInterface $nonceCache): void { public function setNonceCache(
#[Target('nonceCache')] CacheItemPoolInterface $nonceCache,
): void {
$this->nonceCache = $nonceCache; $this->nonceCache = $nonceCache;
} }
/** @throws InvalidArgumentException|Exception */ /** @throws InvalidArgumentException|Exception */
protected function makeNonce(int $retries = 3): string { protected function makeNonce(int $retries = 3): string
{
/* convert raw binary into base64url */ /* convert raw binary into base64url */
$nonce = rtrim(strtr(base64_encode(random_bytes( $nonce = rtrim(strtr(base64_encode(random_bytes(
static::NONCE_LENGTH static::NONCE_LENGTH,
)), '+/', '-_'), '='); )), '+/', '-_'), '=');
$nonceItem = $this->nonceCache->getItem($this->makeCacheKey($nonce)); $nonceItem = $this->nonceCache->getItem($this->makeCacheKey($nonce));
if ($nonceItem->isHit()) { if ($nonceItem->isHit()) {
if ($retries < 1) { if ($retries < 1) {
$this->logger->error("aborting: multiple nonce collisions"); $this->logger->error('aborting: multiple nonce collisions');
throw new HttpException( throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'Internal Server Error');
Response::HTTP_INTERNAL_SERVER_ERROR,
'Internal Server Error'
);
} }
/* managed to have a collision, try again */ /* managed to have a collision, try again */
return $this->makeNonce($retries - 1); return $this->makeNonce($retries - 1);
} }
@@ -49,6 +53,7 @@ trait MakeNonceTrait {
$nonceItem->expiresAfter(static::NONCE_TTL); $nonceItem->expiresAfter(static::NONCE_TTL);
$this->logger->debug("added nonce: $nonce"); $this->logger->debug("added nonce: $nonce");
$this->nonceCache->save($nonceItem); $this->nonceCache->save($nonceItem);
return $nonce; return $nonce;
} }
} }
+43 -3
View File
@@ -1,13 +1,53 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace App\Trait; namespace App\Trait;
trait StringTrait { use App\AppConstants;
use App\ConfigBag;
use App\Enum\RemoteUserMode;
use Symfony\Component\HttpFoundation\Response;
trait StringTrait
{
/* cache keys can safely use alphanumeric, "_", and ".", remove the rest */ /* cache keys can safely use alphanumeric, "_", and ".", remove the rest */
private const string KEY_REGEX = '/[^A-Za-z0-9_.]+/'; private const string KEY_REGEX = '/[^A-Za-z0-9_.]+/';
public function makeCacheKey(string $name): string { public function makeCacheKey(string $name): string
return mb_substr(preg_replace(static::KEY_REGEX, '_', $name), 0, 128); {
return mb_substr(preg_replace(static::KEY_REGEX, '_', $name), 0, AppConstants::MAX_INPUT_LENGTH);
}
/**
* Build the plain-text success response body and headers for an
* authenticated request. The body is a simple greeting that includes
* the session id. The Remote-User header is set (or omitted) based on
* the configured remote-user mode.
*/
public function authSuccessResponse(string $id, ConfigBag $config): Response
{
$headers = ['Content-Type' => 'text/plain'];
$headerValue = $this->resolveRemoteUser($id, $config);
if (null !== $headerValue) {
$headers['Remote-User'] = $headerValue;
}
return new Response("hi $id", headers: $headers);
}
/**
* Resolve the Remote-User header value based on the configured mode.
* Returns null when the header should not be sent.
*/
private function resolveRemoteUser(string $id, ConfigBag $config): ?string
{
return match ($config->remoteUserMode()) {
RemoteUserMode::Session => $id,
RemoteUserMode::Static => $config->remoteUserStatic(),
RemoteUserMode::Mapped => $config->remoteUserMap()[$id] ?? $id,
RemoteUserMode::None => null,
};
} }
} }

Some files were not shown because too many files have changed in this diff Show More