-
Notifications
You must be signed in to change notification settings - Fork 2
fix(security): hash password-reset tokens at rest (#313) #331
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dmytrocraft
wants to merge
8
commits into
main
Choose a base branch
from
security/313-reset-confirm-tokens-plaintext
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
c6f57c3
fix(security): hash password-reset tokens at rest (#313)
dmytrocraft 8dd9f3d
chore(#331): fix linting issues
KostiukVM ba4c710
fix(security): address CI (phpinsights/infection/tests) for #313
dmytrocraft 60430dc
fix(security): satisfy phpmd/CI for #313
dmytrocraft 238ce99
fix(security): replay captured plaintext reset token in Behat confirm
dmytrocraft f7dfb31
fix(security): fix Behat password reset invalidates all active sessio…
dmytrocraft af85dc3
fix(security): address review feedback for #313
dmytrocraft d479844
fix(security): final CI (phpinsights/infection) for #313
dmytrocraft File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| # PRD — Security #313: Password-reset tokens stored in plaintext at rest | ||
|
|
||
| ## Problem | ||
|
|
||
| Password-reset tokens were persisted verbatim in the `password_reset_tokens` | ||
| MongoDB collection. `PasswordResetTokenFactory::create()` generated a | ||
| high-entropy raw token (`bin2hex(random_bytes($tokenLength))`) and that raw value | ||
| was both: | ||
|
|
||
| 1. **Stored** as the document identifier (`<id field-name="tokenValue" | ||
| strategy="NONE">`), and | ||
| 2. **Emailed** to the user as the reset link credential. | ||
|
|
||
| `MongoDBPasswordResetTokenRepository::findByToken()` looked the token up by exact | ||
| equality on the raw value (`findOneBy(['tokenValue' => $token])`). Because the | ||
| stored value equalled the emailed bearer credential, any read access to the | ||
| collection (DB backup, replica snapshot, query log, read-only breach, or a | ||
| NoSQL-injection sink) yielded directly usable, unexpired reset tokens for every | ||
| account with a pending reset, enabling account takeover without further | ||
| interaction (CWE-256, HIGH). | ||
|
|
||
| The refresh-token subsystem already demonstrates the correct pattern | ||
| (`AuthRefreshToken` stores `hash('sha256', $plainToken)` and looks up by hash); | ||
| the password-reset path did not follow it. | ||
|
|
||
| ## Functional Requirements | ||
|
|
||
| - **FR-1** — `PasswordResetToken` MUST persist only a SHA-256 hash of the token | ||
| (`hash('sha256', $plainToken)`) as its stored value / document identifier. The | ||
| plaintext token MUST NOT be persisted. | ||
| - **FR-2** — `PasswordResetToken` MUST expose the plaintext token transiently for | ||
| e-mail delivery (`getPlainToken()`), populated at creation and re-attachable | ||
| for delivery, never written to storage. | ||
| - **FR-3** — `MongoDBPasswordResetTokenRepository::findByToken()` MUST hash the | ||
| incoming candidate (`PasswordResetToken::hashToken()`) before querying, so the | ||
| lookup is by stored hash, never by raw plaintext. | ||
| - **FR-4** — `PasswordResetToken::matchesToken()` MUST compare a candidate | ||
| plaintext against the stored hash using a constant-time comparison | ||
| (`hash_equals`). | ||
| - **FR-5** — The password-reset request → e-mail flow MUST continue to deliver the | ||
| usable plaintext token in the reset link: the request command handler carries | ||
| the plaintext in the domain event, and the request subscriber re-attaches it to | ||
| the reconstituted entity before the e-mail send event is built. | ||
|
|
||
| ## Non-Functional Requirements | ||
|
|
||
| - **NFR-Security** — A read-only exposure of `password_reset_tokens` MUST NOT | ||
| yield usable reset credentials. Submitting a stored hash to the confirm | ||
| endpoint MUST fail (the hash of a hash does not match). Token generation | ||
| continues to use `random_bytes` (256-bit entropy at the default length 32) and | ||
| single-use / short expiry semantics are unchanged. | ||
| - **NFR-Compatibility** — The public reset/confirm HTTP and GraphQL contracts are | ||
| unchanged. The Doctrine document identifier remains `tokenValue` (now a 64-char | ||
| SHA-256 hex string); no migration of mapping strategy is required. Existing | ||
| seeders, fixtures, and E2E flows continue to function by replaying the | ||
| plaintext captured at creation time. | ||
| - **NFR-Maintainability** — The fix mirrors the established `AuthRefreshToken` | ||
| hash-at-rest precedent, stays within hexagonal/DDD boundaries (hashing lives in | ||
| the framework-free Domain entity, lookup hashing in Infrastructure), introduces | ||
| no new directories or `*Service` suffixes, and keeps PHPInsights complexity and | ||
| quality/style thresholds intact (Deptrac 0, Psalm clean, CS-Fixer clean). | ||
|
|
||
| ## Out of Scope | ||
|
|
||
| - **Email-confirmation tokens** (`ConfirmationToken` via `RedisTokenRepository`). | ||
| These are stored in an ephemeral Redis cache (24h TTL), keyed by both raw token | ||
| value and user id, with the serialized document carrying the raw value. The | ||
| brief grades this path "low"; hashing it would change the cache key/serialization | ||
| contract and the user-id reverse lookup, a materially different and broader | ||
| change than the HIGH MongoDB at-rest finding. Tracked separately to keep this | ||
| remediation minimal and focused. | ||
| - Re-keying / re-hashing of tokens already persisted before deployment (short | ||
| 1-hour expiry drains them quickly). | ||
| - Adding a server-side pepper/HMAC. The token has 256 bits of entropy, so SHA-256 | ||
| is sufficient and consistent with the existing refresh-token precedent. |
86 changes: 86 additions & 0 deletions
86
specs/security-313-reset-confirm-tokens-plaintext/stories.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| # Stories — Security #313: Hash password-reset tokens at rest | ||
|
|
||
| Verification commands (one-off containers; do not start the shared stack): | ||
|
|
||
| ```sh | ||
| # Unit tests (security-critical + regression) | ||
| docker run --rm -v /home/kravtsov/Projects/secfix-313:/app \ | ||
| -v /home/kravtsov/Projects/user-service/vendor:/app/vendor:ro -w /app \ | ||
| -e APP_ENV=test --entrypoint sh secfix-312-php:latest -lc \ | ||
| 'php -d memory_limit=-1 vendor/bin/phpunit --testsuite=Unit \ | ||
| --filter "PasswordResetToken|ConfirmationToken|Repository|SeedSchemathesisData" --no-coverage' | ||
|
|
||
| # Architecture boundaries | ||
| docker run --rm ... -lc 'vendor/bin/deptrac analyse --config-file=deptrac.yaml --no-progress' | ||
| # Static analysis (changed files) | ||
| docker run --rm ... -lc 'vendor/bin/psalm --no-cache --no-progress <changed .php files>' | ||
| # Style (changed files) | ||
| docker run --rm ... -lc 'PHP_CS_FIXER_IGNORE_ENV=1 vendor/bin/php-cs-fixer fix --dry-run \ | ||
| --allow-risky=yes --config=.php-cs-fixer.dist.php --path-mode=intersection <changed .php files>' | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## Story 1 — Persist only a SHA-256 hash of the reset token (FR-1, FR-4, NFR-Security) | ||
|
|
||
| Change `PasswordResetToken` so the constructor receives the plaintext, stores | ||
| `hash('sha256', $plain)` as `tokenValue` (the document id), keeps a transient | ||
| `plainToken`, and adds `hashToken()` / `matchesToken()` (constant-time). | ||
|
|
||
| Tests: `tests/Unit/User/Domain/Entity/PasswordResetTokenHashingTest.php` | ||
|
|
||
| - **Positive** — `testStoredValueIsHashNotPlaintext`, `testMatchesTokenAcceptsCorrectPlaintext`: | ||
| stored value equals the SHA-256 of the plaintext and the correct plaintext matches. | ||
| - **Negative** — `testMatchesTokenRejectsWrongPlaintext`, | ||
| `testMatchesTokenRejectsStoredHashSubmittedAsToken`: a wrong plaintext and the | ||
| stored hash itself (what a DB-read attacker sees) both fail to match. | ||
| - **Edge** — `testHashTokenIsDeterministicAndSha256` (64-char deterministic hex), | ||
| `testAttachPlainTokenRestoresDeliveryValue` (transient re-attachment). | ||
|
|
||
| ## Story 2 — Look up reset tokens by hash, never by raw plaintext (FR-3, NFR-Security) | ||
|
|
||
| Change `MongoDBPasswordResetTokenRepository::findByToken()` to query | ||
| `['tokenValue' => PasswordResetToken::hashToken($token)]`. | ||
|
|
||
| Tests: `tests/Unit/User/Infrastructure/Repository/MongoDBPasswordResetTokenRepositoryTest.php` | ||
|
|
||
| - **Positive** — `testFindByTokenLooksUpByHashNotPlaintext`: `findOneBy` is called | ||
| with the hashed criterion and returns the token. | ||
| - **Negative/Edge** — `testFindByTokenDoesNotQueryWithRawPlaintext`: asserts the | ||
| query criterion is NOT the raw value and IS its SHA-256 hash. | ||
|
|
||
| ## Story 3 — Deliver the usable plaintext token through the request → e-mail flow (FR-2, FR-5, NFR-Compatibility) | ||
|
|
||
| `RequestPasswordResetCommandHandler` emits `getPlainToken()` in the event; | ||
| `PasswordResetRequestedEventSubscriber` re-attaches `event->token` to the | ||
| reloaded entity; `PasswordResetEmailSendEventFactory` emits the plaintext. | ||
|
|
||
| Tests: | ||
|
|
||
| - `tests/Unit/User/Application/CommandHandler/RequestPasswordResetCommandHandlerTest.php` | ||
| — **Positive**: event factory receives the plaintext token; **Negative**: | ||
| unknown user publishes nothing. | ||
| - `tests/Unit/User/Application/EventSubscriber/PasswordResetRequestedEventSubscriberTest.php` | ||
| — **Positive**: `attachPlainToken($event->token)` is invoked then the e-mail is | ||
| dispatched; **Negative**: missing token short-circuits. | ||
| - `tests/Unit/User/Domain/Factory/Event/PasswordResetEmailSendEventFactoryTest.php` | ||
| — **Positive/Edge**: emitted `tokenValue` equals the plaintext and differs from | ||
| the stored hash. | ||
| - `tests/Unit/User/Domain/Factory/PasswordResetTokenFactoryTest.php` | ||
| — **Edge**: plaintext length stays `tokenLength * 2`; stored value is 64 hex | ||
| chars and matches its plaintext. | ||
|
|
||
| ## Story 4 — Keep seeders, fixtures, and E2E flows working with hashed storage (NFR-Compatibility) | ||
|
|
||
| `InMemoryPasswordResetTokenRepository::findByToken()` hashes the candidate; the | ||
| Schemathesis/seeder tests assert by hashed key; E2E/Memory helpers replay the | ||
| plaintext captured at creation (`getPlainToken()` / `getLastPasswordResetToken()`). | ||
|
|
||
| Tests: | ||
|
|
||
| - `tests/Unit/DataFixtures/Seeder/PasswordResetTokenSeederTest.php` — **Positive**: | ||
| seeded tokens are keyed by hash and resolvable via `findByToken(plain)`; | ||
| **Edge**: existing-token refresh/extend/reset-usage paths still match by hash. | ||
| - `tests/Unit/DataFixtures/Command/SeedSchemathesisDataCommandTest.php` — | ||
| **Positive/Edge**: stored tokens keyed by hashed fixture constants; existing | ||
| token removal still counted. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P3: Token hashing logic is duplicated in the repository instead of using the domain’s canonical
hashToken()helper, creating a drift risk.Prompt for AI agents
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Keeping the inline
hash('sha256', $token)here intentionally. Routing throughPasswordResetToken::hashToken()triggers the project's PHPMDcleancodeStaticAccess rule (commit ba4c710 had already switched away from the static call for exactly that CI reason). Drift is not silent:MongoDBPasswordResetTokenRepositoryTest::testFindByTokenLooksUpByHashNotPlaintextpins the repository lookup toPasswordResetToken::hashToken(), so any divergence in the hashing algorithm fails the test suite. Added a comment documenting this.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Got it — thanks for the clarification.