Validate signup email and password strength
CI / No Debug Code (pull_request) Successful in 3s
CI / Tests (PHP 8.2) (pull_request) Successful in 42s
CI / Tests (PHP 8.1) (pull_request) Successful in 53s
CI / PHPStan (pull_request) Successful in 2m53s
CI / Coding Standards (pull_request) Successful in 2m57s
CI / Tests (PHP 8.3) (pull_request) Successful in 2m44s
CI / Build Plugin Zip (pull_request) Skipped

The password was only ever checked for length. It is now checked on both
sides, with each side doing the job it can actually do.

The browser scores it with zxcvbn, through WordPress's own
password-strength-meter script rather than a second opinion of our own, and
refuses to submit below "medium". That is the nuanced test — it knows
Tr0ub4dor&3 is weaker than it looks — but it is advice a client can decline
to take.

Auth\PasswordPolicy runs on the server and is the rule that holds. It does
not try to reproduce a strength score in PHP; it rejects the categorically
bad, which is what a server can check without shipping a dictionary: too
short, a well-known leaked password, fewer than four distinct characters, or
the user's own name or email inside it. No composition rules — NIST advises
against them, and they mostly produce predictable substitutions.

Both thresholds come from the same two constants, handed to JavaScript by
wp_localize_script, so the sides cannot drift into disagreeing about what
was accepted.

The verdict is attached to the field with setCustomValidity() rather than by
disabling a button. The form has up to three submits plus a "Next" that
already gates on checkValidity(), and an invalid field stops all of them
without any of them needing to know why.

Email validation moved ahead of the password check, since the password is
now checked against the email. A blank form therefore reports the email
first, which also matches the order the fields appear in.

Verified the browser half against a controllable scorer: each score band
blocks or allows as intended, the identity list reaches the meter, and the
gate stays open while zxcvbn's dictionary is still loading — the server
covers that window.

Closes #150

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
2026-07-29 22:13:31 -03:00
co-authored by Claude Opus 5
parent 2878beb221
commit b5b9a7ac54
10 changed files with 574 additions and 21 deletions
+3
View File
@@ -13,6 +13,9 @@ each change under the current top section as you work.
## [1.3.1] ## [1.3.1]
### Security
- Signup now checks the password properly. The form scores it as you type with the same zxcvbn meter wp-admin uses and will not submit a weak one, and the server refuses — regardless of what the browser allowed — anything shorter than 8 characters, one of the well-known leaked passwords, one built from barely any distinct characters, or one containing your own name or email address. Composition rules ("must contain a symbol") are deliberately not imposed: they mostly produce predictable substitutions. Email addresses are validated on the server on every signup path, with a clear message when one is already registered.
### Changed ### Changed
- Signup and the profile page now ask for a **birth year** rather than a full date of birth — a four-digit year between 1900 and the current year, with anything else discarded rather than stored. Students added before this change keep showing a birth year, derived from the date already on file; that old full date is then dropped the first time the record is saved, so the studio ends up holding only what it now asks for. No bulk purge runs, so a site wanting the remaining old dates gone should clear the `us_date_of_birth` user meta directly. - Signup and the profile page now ask for a **birth year** rather than a full date of birth — a four-digit year between 1900 and the current year, with anything else discarded rather than stored. Students added before this change keep showing a birth year, derived from the date already on file; that old full date is then dropped the first time the record is saved, so the studio ends up holding only what it now asks for. No bulk purge runs, so a site wanting the remaining old dates gone should clear the `us_date_of_birth` user meta directly.
- The interface now says **student** where it said "child" and **profile** where it said "family". The `[us_family]` page is headed **Your profile**, its form is **Add a student**, signup asks for a **Student's name**, and the wp-admin students list and student screen both label the relationship **Profile**. Two strings were reworded rather than swapped: the students list reads **Managed by _name_** (a bare "Student of _name_" would read as a teacher's pupil), and a managed account is described as a **managed student account** so it is not confused with the account holder. Internal names — database columns, request parameters, form field names, the `us_family` shortcode and the `us-scheduler/family` block — are unchanged, since they are contracts with existing installs and saved post content. - The interface now says **student** where it said "child" and **profile** where it said "family". The `[us_family]` page is headed **Your profile**, its form is **Add a student**, signup asks for a **Student's name**, and the wp-admin students list and student screen both label the relationship **Profile**. Two strings were reworded rather than swapped: the students list reads **Managed by _name_** (a bare "Student of _name_" would read as a teacher's pupil), and a managed account is described as a **managed student account** so it is not confused with the account holder. Internal names — database columns, request parameters, form field names, the `us_family` shortcode and the `us-scheduler/family` block — are unchanged, since they are contracts with existing installs and saved post content.
+24
View File
@@ -525,6 +525,30 @@
} }
} }
/*
* The live password verdict under the signup field. Colour is a reinforcement,
* not the message — the text says what is wrong on its own, so this still reads
* correctly to anyone who cannot separate the hues.
*/
.us-password-strength {
display: block;
margin-top: 4px;
font-size: 0.85em;
}
.us-password-strength.is-short,
.us-password-strength.is-weak {
color: #c00;
}
.us-password-strength.is-medium {
color: #7a5c00;
}
.us-password-strength.is-strong {
color: #1a7d2e;
}
/* Shown only in block-editor previews (see BlockPreview). */ /* Shown only in block-editor previews (see BlockPreview). */
.us-editor-note { .us-editor-note {
font-size: 0.85em; font-size: 0.85em;
+104
View File
@@ -14,10 +14,113 @@
* block. Ticking the box also takes the guardian's *own* question panel out * block. Ticking the box also takes the guardian's *own* question panel out
* of play — in guardian mode the questions are asked per child, so the * of play — in guardian mode the questions are asked per child, so the
* server ignores those answers and the browser must not demand them. * server ignores those answers and the browser must not demand them.
* 3. **Password strength.** The password is scored with zxcvbn (via WordPress's
* own `wp.passwordStrength`) and a weak one is refused. The server applies
* its own, coarser rule regardless — see `Auth\PasswordPolicy`.
*/ */
(function () { (function () {
'use strict'; 'use strict';
var PASSWORD = window.usSchedulerPassword || {};
/**
* Gate the form on password strength.
*
* The verdict is attached to the field with `setCustomValidity()` rather than
* by disabling the submit button: the form has up to three submits (the plain
* one, the guardian-mode early one, and step two's) plus a "Next" that
* already gates on `checkValidity()`, and an invalid field blocks all of them
* at once without any of them having to know why.
*/
function enhancePassword(form) {
var field = form.querySelector('#us-reg-pass');
var output = form.querySelector('#us-reg-pass-strength');
var strings = PASSWORD.strings || {};
if (!field || !PASSWORD.minScore) {
return;
}
// What the password must not simply repeat back. Mirrors the identity
// check PasswordPolicy makes server-side.
function identity() {
var out = [];
var sources = form.querySelectorAll('#us-reg-email, #us-reg-name');
for (var i = 0; i < sources.length; i++) {
var value = (sources[i].value || '').trim();
if (value) {
out.push(value);
if (value.indexOf('@') > 0) {
out.push(value.split('@')[0]);
}
}
}
return out;
}
function assess() {
var value = field.value || '';
if (!value) {
report('', '');
return;
}
if (value.length < (PASSWORD.minLength || 8)) {
report(strings.short, 'short');
return;
}
// zxcvbn's dictionary is fetched after load, and wp.passwordStrength
// reports -1 until it arrives. Say nothing and allow the submit in that
// window — the server still checks, and the next keystroke re-runs this
// once the dictionary is in.
if (!window.wp || !window.wp.passwordStrength || typeof window.zxcvbn === 'undefined') {
report('', '');
return;
}
var score = window.wp.passwordStrength.meter(value, identity(), '');
if (score < 0) {
report('', '');
return;
}
if (score >= 3) {
report(strings.strong, 'strong');
} else if (score >= PASSWORD.minScore) {
report(strings.medium, 'medium');
} else {
report(score <= 0 ? strings.veryWeak : strings.weak, 'weak');
}
}
/** Show the verdict, and make it the field's validity at the same time. */
function report(message, level) {
var acceptable = '' === level || 'medium' === level || 'strong' === level;
if (output) {
output.textContent = message || '';
output.className = 'us-password-strength' + (level ? ' is-' + level : '');
}
field.setCustomValidity(acceptable ? '' : message || '');
}
field.addEventListener('input', assess);
field.addEventListener('blur', assess);
// The identity check depends on these, so a password typed first and an
// email typed second is still caught.
var sources = form.querySelectorAll('#us-reg-email, #us-reg-name');
for (var i = 0; i < sources.length; i++) {
sources[i].addEventListener('change', assess);
}
}
function enhanceSteps(form) { function enhanceSteps(form) {
var step1 = form.querySelector('[data-step="1"]'); var step1 = form.querySelector('[data-step="1"]');
var step2 = form.querySelector('[data-step="2"]'); var step2 = form.querySelector('[data-step="2"]');
@@ -154,6 +257,7 @@
: null; : null;
enhanceGuardian(forms[i], steps); enhanceGuardian(forms[i], steps);
enhancePassword(forms[i]);
} }
}); });
})(); })();
+34
View File
@@ -77,6 +77,40 @@ confirmation token's SHA-256 hash is stored; the token expires after 48h
| `accepted_at` | DATETIME | When accepted; NULL while pending / for group links | | `accepted_at` | DATETIME | When accepted; NULL while pending / for group links |
| `expires_at` | DATETIME | Explicit expiry (end of the chosen day); set on every group link, NULL for personal invites (which expire 14 days after creation) | | `expires_at` | DATETIME | Explicit expiry (end of the chosen day); set on every group link, NULL for personal invites (which expire 14 days after creation) |
## Email and password validation
Both are checked on the server on every signup path, and the browser is given a
matching but *stricter* job so a bad password is caught before submitting.
**Email**`type="email"` and `required` in the markup, `is_email()` on the
server, then `email_exists()` for "an account already exists for this email". A
personal invite fixes the address and the server always uses the invite's own
value, so a tampered field is ignored rather than validated.
**Password**`Auth\PasswordPolicy` is the authority. It deliberately does
*not* try to reproduce a strength score in PHP; it rejects the categorically
bad, which is what a server can check without shipping a dictionary:
- shorter than `PasswordPolicy::MIN_LENGTH` (8 — NIST SP 800-63B's floor;
composition rules like "must contain a symbol" are deliberately **not** used,
as they push people towards predictable substitutions),
- one of the well-known leaked passwords,
- built from fewer than four distinct characters (`aaaaaaaa`, `abababab`),
- containing the user's own display name, email, or the part before the `@`.
The nuance happens in the browser. `register.js` scores the password with
zxcvbn through WordPress's own `password-strength-meter` script and refuses to
submit below `PasswordPolicy::MIN_SCORE` (2 of 4 — "medium"; enough to stop a
guessable password without demanding a passphrase to book a piano lesson). The
thresholds reach JavaScript via `wp_localize_script()` from the same constants
the server enforces, so the two cannot drift apart.
The verdict is applied with `setCustomValidity()` on the password field rather
than by disabling a button: the form has up to three submits plus a "Next" that
already gates on `checkValidity()`, and an invalid field stops all of them
without any needing to know why. zxcvbn's dictionary loads asynchronously, so
the gate stays open until it arrives — the server is the check that always runs.
## Registration Questions (signup step two) ## Registration Questions (signup step two)
When the studio has configured **account-scope** registration questions When the studio has configured **account-scope** registration questions
(**Offerings → Questions → "Account signup"**, see `registration-questions.md`), the (**Offerings → Questions → "Account signup"**, see `registration-questions.md`), the
+165
View File
@@ -0,0 +1,165 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Auth;
/**
* What counts as an acceptable signup password.
*
* The check is deliberately split across the two sides, because the two sides
* can do different things:
*
* - **The browser** runs zxcvbn (WordPress ships it as `password-strength-meter`)
* and gates the submit button on {@see MIN_SCORE}. That is the nuanced test —
* it knows that `Tr0ub4dor&3` is weaker than `correct horse battery staple` —
* but it is only advice, because anything in a browser can be turned off.
* - **This class** runs on the server and is the rule that actually holds. It
* cannot score a password the way zxcvbn does without shipping a dictionary,
* so it does not pretend to: it rejects the categorically bad — too short,
* the user's own name or email, a password from the well-known lists, or one
* built from almost no distinct characters.
*
* Neither half is sufficient alone, which is the point. A password that clears
* both is not guaranteed strong; one that fails either is definitely not.
*/
class PasswordPolicy {
/**
* Minimum length. NIST SP 800-63B puts the floor at 8 and explicitly advises
* against composition rules ("must contain a symbol") on the grounds that they
* push people towards predictable substitutions. Length plus the checks below
* does more for less annoyance.
*/
public const MIN_LENGTH = 8;
/**
* The zxcvbn score the browser demands before it will let the form submit,
* on WordPress's 0-4 scale: 0-1 weak, 2 medium, 3-4 strong. Two rejects the
* passwords a stranger would guess while still accepting an ordinary
* memorable one — a studio signup form is not a bank.
*/
public const MIN_SCORE = 2;
/**
* How much of the user's own identity has to appear in the password before it
* is refused. Short enough to catch a name inside a longer password, long
* enough that a two- or three-letter coincidence does not trip it.
*/
private const IDENTITY_FRAGMENT_LENGTH = 4;
/** Fewest distinct characters a password may be built from. */
private const MIN_DISTINCT_CHARACTERS = 4;
/**
* Why this password is unacceptable, or null when it passes.
*
* `$email` and `$displayName` are what the same submission is claiming as an
* identity, so they can be checked against the password before either exists
* as a user.
*/
public static function validate( string $password, string $email = '', string $displayName = '' ): ?string {
// Not trimmed: a leading or trailing space is a legitimate character, and
// silently changing what someone typed would lock them out later.
if ( strlen( $password ) < self::MIN_LENGTH ) {
return sprintf(
/* translators: %d: minimum number of characters. */
__( 'Please choose a password of at least %d characters.', 'unsupervised-schedular' ),
self::MIN_LENGTH
);
}
$lower = strtolower( $password );
if ( in_array( $lower, self::commonPasswords(), true ) ) {
return __( 'That password is one of the most commonly used ones. Please choose something less guessable.', 'unsupervised-schedular' );
}
if ( count( array_unique( str_split( $lower ) ) ) < self::MIN_DISTINCT_CHARACTERS ) {
return __( 'Please choose a password built from more than a few repeated characters.', 'unsupervised-schedular' );
}
if ( self::echoesIdentity( $lower, $email, $displayName ) ) {
return __( 'Please choose a password that does not contain your name or email address.', 'unsupervised-schedular' );
}
return null;
}
/**
* Whether the password contains the user's display name, their email address,
* or the part of it before the `@` — the first things anyone guessing would
* try, and the reason "grace2019" is worse than its length suggests.
*/
private static function echoesIdentity( string $lowerPassword, string $email, string $displayName ): bool {
$email = strtolower( trim( $email ) );
$localPart = '' !== $email ? (string) strstr( $email . '@', '@', true ) : '';
$fragments = [ $email, $localPart, strtolower( trim( $displayName ) ) ];
foreach ( $fragments as $fragment ) {
if ( strlen( $fragment ) >= self::IDENTITY_FRAGMENT_LENGTH && str_contains( $lowerPassword, $fragment ) ) {
return true;
}
}
return false;
}
/**
* Passwords common enough that a guess costs nothing. Only entries at least
* {@see MIN_LENGTH} long are worth listing — anything shorter is already
* refused — so this is the long tail of the usual leaked-password lists
* rather than the whole of it. zxcvbn in the browser covers the rest.
*
* @return list<string>
*/
private static function commonPasswords(): array {
return [
'password',
'password1',
'password12',
'password123',
'passw0rd',
'p@ssword',
'p@ssw0rd',
'12345678',
'123456789',
'1234567890',
'123123123',
'qwertyui',
'qwertyuiop',
'qwerty123',
'qwerty12',
'1qaz2wsx',
'zaq12wsx',
'iloveyou',
'princess',
'sunshine',
'football',
'baseball',
'basketball',
'superman',
'batman123',
'trustno1',
'welcome1',
'welcome123',
'letmein1',
'letmein123',
'admin123',
'administrator',
'abc12345',
'abcd1234',
'monkey123',
'dragon123',
'michael1',
'jennifer',
'starwars',
'computer',
'whatever',
'freedom1',
'changeme',
'secret123',
'login123',
];
}
}
+31 -4
View File
@@ -124,6 +124,28 @@ class RegistrationPage {
// needed whenever the form itself is on screen. // needed whenever the form itself is on screen.
if ( $canRegister && '' === $successType ) { if ( $canRegister && '' === $successType ) {
wp_enqueue_script( 'us-scheduler-register' ); wp_enqueue_script( 'us-scheduler-register' );
// The browser gate reads the same numbers the server enforces, so the
// two cannot drift into disagreeing about what it accepted.
wp_localize_script(
'us-scheduler-register',
'usSchedulerPassword',
[
'minLength' => PasswordPolicy::MIN_LENGTH,
'minScore' => PasswordPolicy::MIN_SCORE,
'strings' => [
'short' => sprintf(
/* translators: %d: minimum number of characters. */
__( 'At least %d characters, please.', 'unsupervised-schedular' ),
PasswordPolicy::MIN_LENGTH
),
'veryWeak' => __( 'Too weak — a stranger could guess this.', 'unsupervised-schedular' ),
'weak' => __( 'Still too weak. Try a longer phrase.', 'unsupervised-schedular' ),
'medium' => __( 'Good enough.', 'unsupervised-schedular' ),
'strong' => __( 'Strong password.', 'unsupervised-schedular' ),
],
]
);
} }
ob_start(); ob_start();
@@ -248,10 +270,6 @@ class RegistrationPage {
$password = Val::string( wp_unslash( $_POST['password'] ?? '' ) ); $password = Val::string( wp_unslash( $_POST['password'] ?? '' ) );
$displayName = sanitize_text_field( Val::string( wp_unslash( $_POST['display_name'] ?? '' ) ) ); $displayName = sanitize_text_field( Val::string( wp_unslash( $_POST['display_name'] ?? '' ) ) );
if ( strlen( $password ) < 8 ) {
return esc_html__( 'Please choose a password of at least 8 characters.', 'unsupervised-schedular' );
}
// The email is fixed by a personal invite; group-link signups and // The email is fixed by a personal invite; group-link signups and
// self-signups supply their own. // self-signups supply their own.
if ( $inviteValid && ! $invite->isGroup() ) { if ( $inviteValid && ! $invite->isGroup() ) {
@@ -263,6 +281,15 @@ class RegistrationPage {
} }
} }
// After the email, so the password can be checked against it. The browser
// scores the password with zxcvbn and refuses to submit a weak one, but
// that is advice a client can decline to take — this is the check that
// holds. See PasswordPolicy for why the two halves differ.
$passwordError = PasswordPolicy::validate( $password, $email, $displayName );
if ( null !== $passwordError ) {
return esc_html( $passwordError );
}
$policyForms = $this->signupPolicies(); $policyForms = $this->signupPolicies();
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- each element is coerced to a positive int in the array_map callback; slashes cannot survive integer coercion. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- each element is coerced to a positive int in the array_map callback; slashes cannot survive integer coercion.
$accepted = array_map( static fn( mixed $v ): int => absint( Val::int( $v ) ), (array) ( $_POST['accept'] ?? [] ) ); $accepted = array_map( static fn( mixed $v ): int => absint( Val::int( $v ) ), (array) ( $_POST['accept'] ?? [] ) );
+16 -2
View File
@@ -88,7 +88,21 @@ class ShortcodeRegistrar {
wp_register_script( 'us-scheduler', USC_PLUGIN_URL . 'assets/js/booking.js', [ 'us-scheduler-pricing', 'us-scheduler-guardian' ], USC_VERSION, true ); wp_register_script( 'us-scheduler', USC_PLUGIN_URL . 'assets/js/booking.js', [ 'us-scheduler-pricing', 'us-scheduler-guardian' ], USC_VERSION, true );
wp_register_script( 'us-scheduler-group', USC_PLUGIN_URL . 'assets/js/group-classes.js', [ 'us-scheduler-pricing', 'us-scheduler-guardian' ], USC_VERSION, true ); wp_register_script( 'us-scheduler-group', USC_PLUGIN_URL . 'assets/js/group-classes.js', [ 'us-scheduler-pricing', 'us-scheduler-guardian' ], USC_VERSION, true );
// Progressive enhancement for the two-step registration form (no dependencies). /*
wp_register_script( 'us-scheduler-register', USC_PLUGIN_URL . 'assets/js/register.js', [], USC_VERSION, true ); * Progressive enhancement for the two-step registration form.
*
* `password-strength-meter` is WordPress's own wrapper around zxcvbn, so
* the signup form scores a password exactly the way wp-admin does rather
* than inventing a second opinion. It pulls in `zxcvbn-async`, which
* fetches the (large) dictionary only once the page has loaded — hence
* the guard in register.js for the window where it is not there yet.
*/
wp_register_script(
'us-scheduler-register',
USC_PLUGIN_URL . 'assets/js/register.js',
[ 'password-strength-meter' ],
USC_VERSION,
true
);
} }
} }
+10 -1
View File
@@ -1,6 +1,7 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
use Unsupervised\Schedular\Auth\PasswordPolicy;
use Unsupervised\Schedular\Registration\Question; use Unsupervised\Schedular\Registration\Question;
use Unsupervised\Schedular\Registration\QuestionField; use Unsupervised\Schedular\Registration\QuestionField;
@@ -67,7 +68,15 @@ if (! defined('ABSPATH')) {
</p> </p>
<p> <p>
<label for="us-reg-pass"><?php esc_html_e('Password', 'unsupervised-schedular'); ?></label> <label for="us-reg-pass"><?php esc_html_e('Password', 'unsupervised-schedular'); ?></label>
<input type="password" name="password" id="us-reg-pass" autocomplete="new-password" minlength="8" required> <input type="password" name="password" id="us-reg-pass" autocomplete="new-password" minlength="<?php echo esc_attr((string) PasswordPolicy::MIN_LENGTH); ?>" required aria-describedby="us-reg-pass-strength">
<?php
/*
* Filled in by register.js. `aria-live` announces the verdict as
* it changes, and it starts empty so nothing is announced — or
* takes up space — before anything has been typed.
*/
?>
<span class="us-password-strength" id="us-reg-pass-strength" role="status" aria-live="polite"></span>
</p> </p>
<fieldset class="us-guardian"> <fieldset class="us-guardian">
+118
View File
@@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
namespace Unsupervised\Schedular\Tests\Unit\Auth;
use Unsupervised\Schedular\Auth\PasswordPolicy;
use Unsupervised\Schedular\Tests\Unit\TestCase;
class PasswordPolicyTest extends TestCase
{
public function testAcceptsAnOrdinaryMemorablePassword(): void
{
self::assertNull(PasswordPolicy::validate('thistle-marrow-42', '[email protected]', 'Grace Hopper'));
}
/**
* A leading or trailing space is a character like any other. Trimming it
* would accept a password the user could then never type back.
*/
public function testCountsSurroundingSpaceAsPartOfThePassword(): void
{
self::assertNull(PasswordPolicy::validate(' spaced-out-phrase '));
// Seven characters counting both spaces: one short, and still one short
// after the spaces are counted rather than stripped.
self::assertNotNull(PasswordPolicy::validate(' short '));
}
/**
* @dataProvider tooShort
*/
public function testRejectsAPasswordShorterThanTheMinimum(string $password): void
{
self::assertStringContainsString('at least', (string) PasswordPolicy::validate($password));
}
/** @return array<string, array{string}> */
public static function tooShort(): array
{
return [
'empty' => [''],
'one short' => ['sevench'],
'a few chars' => ['abc'],
];
}
/**
* @dataProvider commonPasswords
*/
public function testRejectsAWellKnownPassword(string $password): void
{
self::assertStringContainsString('commonly used', (string) PasswordPolicy::validate($password));
}
/** @return array<string, array{string}> */
public static function commonPasswords(): array
{
return [
'password123' => ['password123'],
'shouting' => ['PASSWORD123'],
'mixed case' => ['PassWord123'],
'a keyboard walk' => ['qwertyuiop'],
'digits in a row' => ['123456789'],
'the classic' => ['iloveyou'],
];
}
/**
* @dataProvider tooFewDistinctCharacters
*/
public function testRejectsAPasswordBuiltFromAlmostNoDistinctCharacters(string $password): void
{
self::assertStringContainsString('repeated characters', (string) PasswordPolicy::validate($password));
}
/** @return array<string, array{string}> */
public static function tooFewDistinctCharacters(): array
{
return [
'one character' => ['aaaaaaaaaa'],
'two alternating' => ['abababababab'],
'three' => ['abcabcabcabc'],
];
}
/**
* @dataProvider identityEchoes
*/
public function testRejectsAPasswordContainingTheUsersOwnDetails(string $password, string $email, string $name): void
{
self::assertStringContainsString('name or email', (string) PasswordPolicy::validate($password, $email, $name));
}
/** @return array<string, array{string, string, string}> */
public static function identityEchoes(): array
{
return [
'the whole email' => ['[email protected]!', '[email protected]', 'Grace'],
'the local part' => ['grace-hopper-1906', '[email protected]', ''],
'the display name' => ['xxhopperxx-2019', '[email protected]', 'Hopper'],
'differing in case' => ['MyGRACEpassword', '[email protected]', ''],
];
}
/**
* A two- or three-letter overlap with a name is coincidence, not a weakness,
* and refusing it would be baffling to the person typing.
*/
public function testShortIdentityFragmentsDoNotTripTheCheck(): void
{
self::assertNull(PasswordPolicy::validate('bramble-thicket', '[email protected]', 'Bo'));
}
public function testAnEmptyIdentityIsNotTreatedAsContainedInEverything(): void
{
self::assertNull(PasswordPolicy::validate('bramble-thicket', '', ''));
}
}
+69 -14
View File
@@ -37,10 +37,14 @@ class RegistrationPageTest extends TestCase
Functions\when('sanitize_text_field')->alias(static fn ($v) => $v); Functions\when('sanitize_text_field')->alias(static fn ($v) => $v);
Functions\when('sanitize_textarea_field')->alias(static fn ($v) => $v); Functions\when('sanitize_textarea_field')->alias(static fn ($v) => $v);
Functions\when('sanitize_email')->alias(static fn ($v) => $v); Functions\when('sanitize_email')->alias(static fn ($v) => $v);
// Reached on every submit now that the email is validated before the
// password, so the password can be checked against it.
Functions\when('is_email')->alias(static fn (string $v): bool => (bool) preg_match('/^[^@\s]+@[^@\s]+\.[^@\s]+$/', $v));
Functions\when('absint')->alias(static fn ($v) => (int) $v); Functions\when('absint')->alias(static fn ($v) => (int) $v);
Functions\when('current_time')->justReturn('2024-01-01 00:00:00'); Functions\when('current_time')->justReturn('2024-01-01 00:00:00');
Functions\when('wp_enqueue_style')->justReturn(null); Functions\when('wp_enqueue_style')->justReturn(null);
Functions\when('wp_enqueue_script')->justReturn(null); Functions\when('wp_enqueue_script')->justReturn(null);
Functions\when('wp_localize_script')->justReturn(true);
$invites = Mockery::mock(InviteRepository::class); $invites = Mockery::mock(InviteRepository::class);
$policies = Mockery::mock(PolicyRepository::class); $policies = Mockery::mock(PolicyRepository::class);
@@ -110,7 +114,7 @@ class RegistrationPageTest extends TestCase
public function testInviteBranchCreatesAndLogsInTheStudent(): void public function testInviteBranchCreatesAndLogsInTheStudent(): void
{ {
$_POST = [ 'password' => 'password123', 'display_name' => 'Ada' ]; $_POST = [ 'password' => 'thistle-marrow-42', 'display_name' => 'Ada' ];
Functions\when('email_exists')->justReturn(false); Functions\when('email_exists')->justReturn(false);
Functions\when('wp_insert_user')->justReturn(42); Functions\when('wp_insert_user')->justReturn(42);
@@ -127,7 +131,7 @@ class RegistrationPageTest extends TestCase
public function testInviteAcceptanceLinksClassGrantForTheEmail(): void public function testInviteAcceptanceLinksClassGrantForTheEmail(): void
{ {
$_POST = [ 'password' => 'password123', 'display_name' => 'Ada' ]; $_POST = [ 'password' => 'thistle-marrow-42', 'display_name' => 'Ada' ];
Functions\when('email_exists')->justReturn(false); Functions\when('email_exists')->justReturn(false);
Functions\when('wp_insert_user')->justReturn(42); Functions\when('wp_insert_user')->justReturn(42);
@@ -147,7 +151,7 @@ class RegistrationPageTest extends TestCase
public function testOpenBranchCreatesPendingWithoutLoginAndEmails(): void public function testOpenBranchCreatesPendingWithoutLoginAndEmails(): void
{ {
$_POST = [ 'password' => 'password123', 'display_name' => 'Ada', 'email' => '[email protected]' ]; $_POST = [ 'password' => 'thistle-marrow-42', 'display_name' => 'Ada', 'email' => '[email protected]' ];
Functions\when('is_email')->justReturn(true); Functions\when('is_email')->justReturn(true);
Functions\when('email_exists')->justReturn(false); Functions\when('email_exists')->justReturn(false);
@@ -174,7 +178,7 @@ class RegistrationPageTest extends TestCase
public function testGroupInviteCreatesPendingAutoApproveAccountEvenWhenClosed(): void public function testGroupInviteCreatesPendingAutoApproveAccountEvenWhenClosed(): void
{ {
$_POST = [ 'password' => 'password123', 'display_name' => 'Ada', 'email' => '[email protected]' ]; $_POST = [ 'password' => 'thistle-marrow-42', 'display_name' => 'Ada', 'email' => '[email protected]' ];
Functions\when('is_email')->justReturn(true); Functions\when('is_email')->justReturn(true);
Functions\when('email_exists')->justReturn(false); Functions\when('email_exists')->justReturn(false);
@@ -342,7 +346,7 @@ class RegistrationPageTest extends TestCase
public function testRejectsWhenARequiredPolicyIsUnaccepted(): void public function testRejectsWhenARequiredPolicyIsUnaccepted(): void
{ {
$_POST = [ 'password' => 'password123', 'display_name' => 'Ada', 'email' => '[email protected]' ]; $_POST = [ 'password' => 'thistle-marrow-42', 'display_name' => 'Ada', 'email' => '[email protected]' ];
Functions\when('is_email')->justReturn(true); Functions\when('is_email')->justReturn(true);
@@ -361,7 +365,7 @@ class RegistrationPageTest extends TestCase
public function testRejectsWhenARequiredAccountQuestionIsUnanswered(): void public function testRejectsWhenARequiredAccountQuestionIsUnanswered(): void
{ {
$_POST = [ 'password' => 'password123', 'display_name' => 'Ada', 'email' => '[email protected]' ]; $_POST = [ 'password' => 'thistle-marrow-42', 'display_name' => 'Ada', 'email' => '[email protected]' ];
Functions\when('is_email')->justReturn(true); Functions\when('is_email')->justReturn(true);
@@ -381,7 +385,7 @@ class RegistrationPageTest extends TestCase
public function testRecordsAccountAnswersOnSuccess(): void public function testRecordsAccountAnswersOnSuccess(): void
{ {
$_POST = [ $_POST = [
'password' => 'password123', 'password' => 'thistle-marrow-42',
'display_name' => 'Ada', 'display_name' => 'Ada',
'us_answers' => [ '5' => 'By a friend' ], 'us_answers' => [ '5' => 'By a friend' ],
]; ];
@@ -415,7 +419,7 @@ class RegistrationPageTest extends TestCase
public function testMaybeHandleSubmitLogsInInviteAndRedirects(): void public function testMaybeHandleSubmitLogsInInviteAndRedirects(): void
{ {
$_POST = [ 'us_register' => '1', 'password' => 'password123', 'display_name' => 'Ada' ]; $_POST = [ 'us_register' => '1', 'password' => 'thistle-marrow-42', 'display_name' => 'Ada' ];
$_REQUEST = [ 'us_invite' => 'raw-token' ]; $_REQUEST = [ 'us_invite' => 'raw-token' ];
Functions\when('is_user_logged_in')->justReturn(false); Functions\when('is_user_logged_in')->justReturn(false);
@@ -614,7 +618,7 @@ class RegistrationPageTest extends TestCase
public function testGuardianSignupCreatesEachChildAndRecordsTheirAnswers(): void public function testGuardianSignupCreatesEachChildAndRecordsTheirAnswers(): void
{ {
$_POST = [ $_POST = [
'password' => 'password123', 'password' => 'thistle-marrow-42',
'display_name' => 'Grace', 'display_name' => 'Grace',
'us_is_guardian' => '1', 'us_is_guardian' => '1',
'children' => [ 'children' => [
@@ -652,10 +656,61 @@ class RegistrationPageTest extends TestCase
self::assertSame([[101, 'Piano'], [102, 'Violin']], $recorded); self::assertSame([[101, 'Piano'], [102, 'Violin']], $recorded);
} }
/**
* The browser gates on zxcvbn, but that is advice a client can decline to
* take. Nothing is created for a password the server refuses.
*
* @dataProvider refusedPasswords
*/
public function testSignupRefusesAPasswordThePolicyRejects(string $password, string $expected): void
{
$_POST = [
'email' => '[email protected]',
'password' => $password,
'display_name' => 'Grace Hopper',
];
Functions\when('email_exists')->justReturn(false);
Functions\expect('wp_insert_user')->never();
self::assertStringContainsString(
$expected,
$this->submit(new Invite(email: '[email protected]', token: 'hash'), false)
);
}
/** @return array<string, array{string, string}> */
public static function refusedPasswords(): array
{
return [
'too short' => ['abc123', 'at least'],
'a known password' => ['password123', 'commonly used'],
'barely any variety' => ['ababababab', 'repeated characters'],
'their own name' => ['grace-hopper-1906', 'name or email'],
];
}
public function testSignupRefusesAnAddressThatIsNotAnEmail(): void
{
$_POST = [
'email' => 'not-an-email',
'password' => 'thistle-marrow-42',
'display_name' => 'Grace',
];
Functions\when('email_exists')->justReturn(false);
Functions\expect('wp_insert_user')->never();
self::assertStringContainsString(
'valid email address',
$this->submit(null, true)
);
}
public function testGuardianSignupWithNoChildrenIsRejected(): void public function testGuardianSignupWithNoChildrenIsRejected(): void
{ {
$_POST = [ $_POST = [
'password' => 'password123', 'password' => 'thistle-marrow-42',
'display_name' => 'Grace', 'display_name' => 'Grace',
'us_is_guardian' => '1', 'us_is_guardian' => '1',
'children' => [['name' => '', 'birth_year' => '', 'answers' => []]], 'children' => [['name' => '', 'birth_year' => '', 'answers' => []]],
@@ -677,7 +732,7 @@ class RegistrationPageTest extends TestCase
public function testGuardianSignupRejectsAChildMissingARequiredAnswer(): void public function testGuardianSignupRejectsAChildMissingARequiredAnswer(): void
{ {
$_POST = [ $_POST = [
'password' => 'password123', 'password' => 'thistle-marrow-42',
'display_name' => 'Grace', 'display_name' => 'Grace',
'us_is_guardian' => '1', 'us_is_guardian' => '1',
'children' => [ 'children' => [
@@ -704,7 +759,7 @@ class RegistrationPageTest extends TestCase
public function testAFailedChildRollsBackEveryUserCreatedIncludingTheGuardian(): void public function testAFailedChildRollsBackEveryUserCreatedIncludingTheGuardian(): void
{ {
$_POST = [ $_POST = [
'password' => 'password123', 'password' => 'thistle-marrow-42',
'display_name' => 'Grace', 'display_name' => 'Grace',
'us_is_guardian' => '1', 'us_is_guardian' => '1',
'children' => [ 'children' => [
@@ -741,7 +796,7 @@ class RegistrationPageTest extends TestCase
public function testSignupPoliciesAreAcceptedPerChildAndAttributedToTheGuardian(): void public function testSignupPoliciesAreAcceptedPerChildAndAttributedToTheGuardian(): void
{ {
$_POST = [ $_POST = [
'password' => 'password123', 'password' => 'thistle-marrow-42',
'display_name' => 'Grace', 'display_name' => 'Grace',
'us_is_guardian' => '1', 'us_is_guardian' => '1',
'accept' => [3], 'accept' => [3],
@@ -780,7 +835,7 @@ class RegistrationPageTest extends TestCase
public function testANonGuardianSignupIsUnchangedAndCreatesNoChildren(): void public function testANonGuardianSignupIsUnchangedAndCreatesNoChildren(): void
{ {
$_POST = ['password' => 'password123', 'display_name' => 'Ada']; $_POST = ['password' => 'thistle-marrow-42', 'display_name' => 'Ada'];
Functions\when('email_exists')->justReturn(false); Functions\when('email_exists')->justReturn(false);
Functions\when('wp_insert_user')->justReturn(42); Functions\when('wp_insert_user')->justReturn(42);