Skip to content

Fix empty backup code when appending codes for a user with none - #958

Merged
kasparsd merged 6 commits into
WordPress:masterfrom
faithcoder:fix/956-generate-codes-with-method-append-stores-an-empty
Sep 28, 2026
Merged

kasparsd merged 6 commits into
WordPress:masterfrom
faithcoder:fix/956-generate-codes-with-method-append-stores-an-empty

Conversation

@faithcoder

@faithcoder faithcoder commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

What?

Generating backup codes with 'method' => 'append' for a user who has no existing codes no longer stores an extra, empty code that can never be validated or removed.

Fixes #956

Why?

generate_codes() cast get_user_meta( ..., true ) directly to an array. For a user with no stored codes that meta value is '', and (array) '' evaluates to array( '' ) rather than an empty array, so an empty string was permanently appended ahead of the real hashes. codes_remaining_for_user() then reports one more code than the user actually holds, causing two problems:

  • A user with zero usable codes is still offered recovery codes at login.
  • The low-codes warning reports one code too many.

How?

Replaced the bare (array) cast with an is_array() guard before assigning the existing hashes, matching the pattern already used by codes_remaining_for_user() and validate_code(). Added a regression test for the append-with-no-existing-codes case.

Use of AI Tools

AI assistance: Yes
Tool(s): OpenCode
Model(s): deepseek-v4-pro
Used for: Root-cause analysis, fix implementation, and test authoring; the final diff and validation were reviewed by the contributor.

Testing Instructions

  1. npm run composer -- test -- --filter Tests_Two_Factor_Backup_Codes
  2. npm test (full suite)
  3. Manual reproduction from the issue:
$user  = get_user_by( 'login', 'someone' ); // no backup codes yet
$codes = Two_Factor_Backup_Codes::get_instance()->generate_codes( $user, array( 'method' => 'append' ) );

count( $codes );                                              // 10
count( get_user_meta( $user->ID, '_two_factor_backup_codes', true ) ); // 10 (was 11)
Two_Factor_Backup_Codes::codes_remaining_for_user( $user );   // 10 (was 11)

Screenshots or screencast

Not applicable (no UI changes).

Changelog Entry

Fixed - Generating backup codes with the append method no longer stores an empty entry for users with no existing codes.

Open WordPress Playground Preview

@github-actions

github-actions Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Co-authored-by: faithcoder <faithcoder@git.wordpress.org>
Co-authored-by: kasparsd <kasparsd@git.wordpress.org>
Co-authored-by: masteradhoc <masteradhoc@git.wordpress.org>
Co-authored-by: dknauss <dpknauss@git.wordpress.org>

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes backup-code generation with append for users without existing codes, preventing an empty stored entry.

Changes:

  • Guard existing metadata with is_array() before appending.
  • Add regression coverage for empty accounts.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Summary
tests/providers/class-two-factor-backup-codes.php Adds regression test coverage.
providers/class-two-factor-backup-codes.php Prevents empty backup-code entries.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

@masteradhoc masteradhoc added this to the 0.17.0 milestone Aug 21, 2026

@masteradhoc masteradhoc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thanks to @dknauss for the detailed Issue and the PR @faithcoder.

@masteradhoc masteradhoc modified the milestones: 0.17.0, 0.18.0 Sep 25, 2026
MrLBRD added a commit to MrLBRD/two-factor that referenced this pull request Sep 28, 2026
Intègre les 175 commits accumulés depuis c8c8823 (20/09), dont la release
stable 0.17.0 publiée le 28/09 — la première depuis la 0.16.0 du 27/03.

Correctif de sécurité déterminant pour ce fork : WordPress#989 empêche un mot de passe
classique de contourner la 2FA sur REST et XML-RPC. Notre code testait
`did_action( 'application_password_did_authenticate' )`, vrai dès que
n'importe quel utilisateur s'était authentifié par application password
pendant la requête ; upstream scope désormais la vérification par ID
(`$app_password_auth_user_ids`). Les autres correctifs de sécurité de la
release (WordPress#877, WordPress#973, WordPress#980) étaient déjà présents ici.

Trois PR qui composaient le fork sont maintenant mergées upstream : WordPress#927
(fail-safe), WordPress#917 (rate-limit) et WordPress#882. Notre implémentation locale de WordPress#927
et celle d'upstream sont identiques, d'où l'absence de conflit sur
class-two-factor-core.php. Le fork ne repose plus que sur WordPress#845 (enforcement
par rôle, approuvée le 24/09 mais non mergée) et WordPress#958.

Résolution des trois conflits, upstream retenu dans les trois cas :
- tests/class-two-factor-core.php : nos noms de tests contredisaient leurs
  propres assertions (« invalidates » pour un token vérifié « preserved ») ;
  upstream les renomme et ajoute test_clear_login_rate_limit.
- tests/providers/class-two-factor-email.php : ajout de trois tests de
  lockout côté upstream, aucun test perdu ici.
- readme.txt : notre seul apport propre, la documentation du filtre
  two_factor_fallback_provider_for_user, est déjà dans leur version.

Validation (wp-env, WordPress 7.1 / PHP 7.4) : PHPUnit 308 tests et 932
assertions OK sur les suites single et multisite, dont 10/10 pour le groupe
enforcement ; PHPCS 29/29 ; PHPStan 0 erreur ; build OK. Le merge apporte
une suite multisite et le support WP-CLI, d'où le passage de 218 à 308
tests et la nouvelle dépendance php-stubs/wp-cli-stubs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@kasparsd

Copy link
Copy Markdown
Collaborator

I updated this to introduce a new helper method that returns the sanitized hashed code list, which is always an array and correctly works around empty strings being stored as values.

@kasparsd
kasparsd merged commit ef64666 into WordPress:master Sep 28, 2026
25 checks passed
MrLBRD added a commit to MrLBRD/two-factor that referenced this pull request Nov 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

generate_codes() with 'method' => 'append' stores an empty code when the user has none

5 participants