Files
aneurinandClaude Sonnet 5 afdd53ec4c Add passkeys (WebAuthn): register from the profile, log in without email
New library dependency: lbuchs/webauthn (^2.2, MIT, zero transitive deps
beyond PHP+OpenSSL+Mbstring, both already required). 'none' attestation --
this only confirms "the same device that registered", not hardware
provenance, the standard trust model for a public site's own passkey login.

Backend
- migrations/010: `passkeys` (one row per registered credential: owner,
  credential_id, public_key, sign_count, label) and `webauthn_challenges`
  (short-lived, single-use, bridging each ceremony's "options" and "verify"
  calls -- user_id set for a registration, null for a login since who's
  signing in isn't known until the credential comes back).
- Config: WEBAUTHN_RP_ID (defaults to APP_URL's host) and WEBAUTHN_RP_NAME.
- PasskeyRepository, WebAuthnChallengeRepository, PasskeyController:
  GET/POST /api/passkeys, POST /api/passkeys/options, DELETE
  /api/passkeys/{id} (all auth), plus the public POST /api/auth/passkey/
  options and /verify for login. Registration always asks for a
  discoverable, user-verified credential -- what makes login usernameless:
  the browser offers whatever passkeys it has for the site, no email first.
- SessionPayload now also exposes `has_passkey` on every user object
  (PasskeyRepository::countForUser() > 0), reused by both the profile page
  and the dismissible notice.
- PasskeyTest: auth guards, options response shape, challenge single-use/
  expiry/purpose/cross-user rules, malformed-input handling, list/remove
  CRUD (seeded rows) -- everything short of a real signature, which isn't
  practical from PHPUnit. 73 tests pass.

Frontend
- lib/webauthn.ts: base64url <-> ArrayBuffer conversion and the two
  ceremonies (registerPasskey, loginWithPasskey), matching the API's wire
  format exactly.
- ProfileView: a Passkeys section -- list with Remove buttons, an "Add a
  passkey" form (label pre-filled from a UA guess).
- LoginView: a "Log in with a passkey" button above the email form, shown
  only when the browser supports WebAuthn.
- PasskeyNotice.vue: dismissible banner across the top of the page
  (`user.has_passkey === false`); dismissal is a week-long localStorage
  timestamp.

Verified against the rebuilt container using a Chrome DevTools Protocol
*virtual authenticator* (real ECDSA signing, no human interaction) end to
end: notice shown -> register a passkey -> notice gone (same page and after
navigating) -> log out -> "Log in with a passkey" with no email typed ->
correct account, notice still gone -> remove the passkey -> notice back ->
dismiss -> stays hidden for ~7 days across pages. Along the way, caught and
fixed a real bug: AuthenticatorData::getCredentialId() returns a raw binary
string, not a ByteBuffer like most of this library's other binary fields --
bin2hex() it directly rather than calling ->getHex().

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-04 19:34:53 +01:00

199 lines
8.7 KiB
PHP

<?php
declare(strict_types=1);
namespace Tests;
/**
* The full register/verify and login/verify ceremonies need a real (or
* virtual) authenticator doing actual signing, which isn't practical from
* PHPUnit -- that round trip is exercised in the browser instead (a Chrome
* DevTools Protocol virtual authenticator). These tests cover everything
* that doesn't require a working credential: auth guards, the shape of the
* options responses, the challenge's single-use/expiry/purpose rules, input
* validation, and passkey list/remove CRUD.
*/
final class PasskeyTest extends ApiTestCase
{
public function test_passkey_routes_require_authentication(): void
{
self::assertSame(401, $this->request('GET', '/api/passkeys')->getStatusCode());
self::assertSame(401, $this->request('POST', '/api/passkeys/options')->getStatusCode());
self::assertSame(401, $this->request('POST', '/api/passkeys', ['challenge_id' => 1])->getStatusCode());
self::assertSame(401, $this->request('DELETE', '/api/passkeys/1')->getStatusCode());
}
public function test_a_new_user_has_no_passkeys(): void
{
$auth = $this->authHeader();
self::assertSame([], $this->decode($this->request('GET', '/api/passkeys', null, $auth))['passkeys']);
self::assertFalse($this->decode($this->request('GET', '/api/me', null, $auth))['user']['has_passkey']);
}
public function test_register_options_returns_a_discoverable_resident_key_challenge(): void
{
$auth = $this->authHeader('ada@example.com');
$response = $this->request('POST', '/api/passkeys/options', [], $auth);
self::assertSame(200, $response->getStatusCode());
$body = $this->decode($response);
self::assertIsInt($body['challenge_id']);
$publicKey = $body['options']['publicKey'];
self::assertTrue($publicKey['authenticatorSelection']['requireResidentKey']);
self::assertSame('required', $publicKey['authenticatorSelection']['residentKey']);
self::assertSame('required', $publicKey['authenticatorSelection']['userVerification']);
self::assertSame('ada@example.com', $publicKey['user']['name']);
self::assertNotEmpty($publicKey['challenge']);
}
public function test_login_options_is_public_and_usernameless(): void
{
$response = $this->request('POST', '/api/auth/passkey/options');
self::assertSame(200, $response->getStatusCode());
$publicKey = $this->decode($response)['options']['publicKey'];
self::assertArrayNotHasKey('allowCredentials', $publicKey);
self::assertSame('required', $publicKey['userVerification']);
self::assertNotEmpty($publicKey['challenge']);
}
public function test_register_requires_a_challenge_id_and_credential(): void
{
$auth = $this->authHeader();
self::assertSame(422, $this->request('POST', '/api/passkeys', ['credential' => []], $auth)->getStatusCode());
self::assertSame(422, $this->request('POST', '/api/passkeys', ['challenge_id' => 1], $auth)->getStatusCode());
}
public function test_register_rejects_a_bogus_credential_response(): void
{
$auth = $this->authHeader();
$challengeId = $this->decode($this->request('POST', '/api/passkeys/options', [], $auth))['challenge_id'];
$response = $this->request('POST', '/api/passkeys', [
'challenge_id' => $challengeId,
'credential' => ['response' => ['clientDataJSON' => 'bm90LXJlYWw', 'attestationObject' => 'bm90LXJlYWw']],
], $auth);
self::assertSame(400, $response->getStatusCode());
}
public function test_register_rejects_an_unknown_challenge(): void
{
$auth = $this->authHeader();
$response = $this->request('POST', '/api/passkeys', [
'challenge_id' => 999999,
'credential' => ['response' => ['clientDataJSON' => 'x', 'attestationObject' => 'x']],
], $auth);
self::assertSame(400, $response->getStatusCode());
}
public function test_a_registration_challenge_cannot_be_reused(): void
{
$auth = $this->authHeader();
$challengeId = $this->decode($this->request('POST', '/api/passkeys/options', [], $auth))['challenge_id'];
$body = [
'challenge_id' => $challengeId,
'credential' => ['response' => ['clientDataJSON' => 'bm90LXJlYWw', 'attestationObject' => 'bm90LXJlYWw']],
];
// First attempt fails on the bogus credential (400), but consumes the challenge either way.
$this->request('POST', '/api/passkeys', $body, $auth);
$second = $this->request('POST', '/api/passkeys', $body, $auth);
self::assertSame(400, $second->getStatusCode());
}
public function test_a_registration_challenge_cannot_be_used_for_login(): void
{
$auth = $this->authHeader();
$challengeId = $this->decode($this->request('POST', '/api/passkeys/options', [], $auth))['challenge_id'];
$response = $this->request('POST', '/api/auth/passkey/verify', [
'challenge_id' => $challengeId,
'credential' => ['id' => 'x', 'response' => []],
]);
self::assertSame(400, $response->getStatusCode());
}
public function test_an_expired_registration_challenge_is_rejected(): void
{
$auth = $this->authHeader();
$challengeId = $this->decode($this->request('POST', '/api/passkeys/options', [], $auth))['challenge_id'];
$this->db()->prepare('UPDATE webauthn_challenges SET expires_at = :past WHERE id = :id')->execute([
'past' => gmdate('Y-m-d\TH:i:s\Z', time() - 60),
'id' => $challengeId,
]);
$response = $this->request('POST', '/api/passkeys', [
'challenge_id' => $challengeId,
'credential' => ['response' => ['clientDataJSON' => 'x', 'attestationObject' => 'x']],
], $auth);
self::assertSame(400, $response->getStatusCode());
}
public function test_login_verify_rejects_an_unrecognised_credential(): void
{
$challengeId = $this->decode($this->request('POST', '/api/auth/passkey/options'))['challenge_id'];
$response = $this->request('POST', '/api/auth/passkey/verify', [
'challenge_id' => $challengeId,
'credential' => ['id' => 'bm9uZXhpc3RlbnQ', 'response' => []],
]);
self::assertSame(401, $response->getStatusCode());
}
public function test_login_verify_requires_a_challenge_id_and_credential(): void
{
self::assertSame(422, $this->request('POST', '/api/auth/passkey/verify', ['credential' => ['id' => 'x']])->getStatusCode());
self::assertSame(422, $this->request('POST', '/api/auth/passkey/verify', ['challenge_id' => 1])->getStatusCode());
}
public function test_listing_and_removing_a_passkey(): void
{
$auth = $this->authHeader('holder@example.com');
$userId = $this->decode($this->request('GET', '/api/me', null, $auth))['user']['id'];
$this->seedPasskey($userId, 'cred-1', 'My laptop');
$listed = $this->decode($this->request('GET', '/api/passkeys', null, $auth))['passkeys'];
self::assertCount(1, $listed);
self::assertSame('My laptop', $listed[0]['label']);
self::assertArrayNotHasKey('public_key', $listed[0]);
self::assertArrayNotHasKey('credential_id', $listed[0]);
self::assertTrue($this->decode($this->request('GET', '/api/me', null, $auth))['user']['has_passkey']);
self::assertSame(204, $this->request('DELETE', "/api/passkeys/{$listed[0]['id']}", null, $auth)->getStatusCode());
self::assertSame([], $this->decode($this->request('GET', '/api/passkeys', null, $auth))['passkeys']);
self::assertFalse($this->decode($this->request('GET', '/api/me', null, $auth))['user']['has_passkey']);
}
public function test_a_passkey_can_only_be_removed_by_its_owner(): void
{
$owner = $this->authHeader('owner@example.com');
$other = $this->authHeader('other@example.com');
$ownerId = $this->decode($this->request('GET', '/api/me', null, $owner))['user']['id'];
$passkeyId = $this->seedPasskey($ownerId, 'cred-2', 'Phone');
self::assertSame(404, $this->request('DELETE', "/api/passkeys/{$passkeyId}", null, $other)->getStatusCode());
self::assertCount(1, $this->decode($this->request('GET', '/api/passkeys', null, $owner))['passkeys']);
}
private function seedPasskey(int $userId, string $credentialId, string $label): int
{
$this->db()->prepare(
'INSERT INTO passkeys (user_id, credential_id, public_key, sign_count, label) VALUES (?, ?, ?, 0, ?)'
)->execute([$userId, $credentialId, '-----BEGIN PUBLIC KEY-----test-----END PUBLIC KEY-----', $label]);
return (int) $this->db()->lastInsertId();
}
}