commit b60b829b96978f2bd2d12ef66509afb3908a8f98 Author: Italo Date: Tue Jun 14 05:17:04 2022 -0400 First release diff --git a/.assets/buymeacoffee.png b/.assets/buymeacoffee.png new file mode 100644 index 0000000..7ce4b19 Binary files /dev/null and b/.assets/buymeacoffee.png differ diff --git a/.assets/ko-fi.png b/.assets/ko-fi.png new file mode 100644 index 0000000..f4f27df Binary files /dev/null and b/.assets/ko-fi.png differ diff --git a/.assets/patreon.png b/.assets/patreon.png new file mode 100644 index 0000000..1161c33 Binary files /dev/null and b/.assets/patreon.png differ diff --git a/.assets/paypal.png b/.assets/paypal.png new file mode 100644 index 0000000..d28f8f6 Binary files /dev/null and b/.assets/paypal.png differ diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..df8e24c --- /dev/null +++ b/.editorconfig @@ -0,0 +1,18 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at http://editorconfig.org + +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[*.yml] +indent_size = 2 \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f358bea --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# Path-based git attributes +# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html + +# Ignore all test and documentation with "export-ignore". +/.gitattributes export-ignore +/.gitignore export-ignore +/phpunit.xml.dist export-ignore +/tests export-ignore +/.editorconfig export-ignore +/.github export-ignore +/.assets export-ignore diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..7052579 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# Help me support this package + +patreon: PackagesForLaravel +ko_fi: DarkGhostHunter +custom: ['https://www.buymeacoffee.com/darkghosthunter', 'https://paypal.me/darkghosthunter'] diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..9aaef6c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,113 @@ +name: Bug Report +description: File a bug report +title: "[X.x] What does happen that is considered an error or bug?" +labels: ["bug"] +assignees: + - DarkGhostHunter +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! + The more detailed this bug report is, the faster it can be reviewed and fixed. + - type: input + id: version-php-os + attributes: + label: PHP & Platform + description: Exact PHP and Platform (OS) versions using this package. + placeholder: 8.1.2 - Ubuntu 22.04 x64 + validations: + required: true + - type: input + id: version-laravel + attributes: + label: Laravel version + description: Exact Laravel version using this package. + placeholder: 9.2.3 + validations: + required: true + - type: input + id: version-authenticator + attributes: + label: Authenticator type + description: If applicable, exact authenticator you're using. + placeholder: YubiKey 5, iPhone 7s, Samsung Galaxy S11+... + validations: + required: false + - type: input + id: version-os-browser + attributes: + label: OS and Browser versions + description: If applicable, exact OS and Browser versions + placeholder: Android 12.0 - Chrome 102.0.5005.99 + validations: + required: false + - type: checkboxes + id: requirements + attributes: + label: Have you done this? + options: + - label: I am willing to share my stack trace and logs + required: true + - label: I can reproduce this bug in isolation (vanilla Laravel install) + required: true + - label: I can suggest a workaround as a Pull Request + required: false + - type: textarea + id: expectation + attributes: + label: Expectation + description: Write what you expect to (correctly) happen. + placeholder: When I do this, I expect to this to happen. + validations: + required: true + - type: textarea + id: description + attributes: + label: Description + description: Write what (incorrectly) happens instead. + placeholder: Instead, when I do this, I receive that. + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: Reproduction + description: Paste the code to assert in a test, or just comment with the repository with the bug. + render: php + placeholder: | + $test = Laragear::make()->break(); + + static::assertFalse($test); + + // or comment with "https://github.com/my-name/my-bug-report" + validations: + required: true + - type: textarea + id: logs + attributes: + label: Stack trace & logs + description: If you have a stack trace, you can copy it here. You may hide sensible information. + placeholder: This is automatically formatted into code, no need for backticks. + render: shell + validations: + required: false + - type: textarea + id: attestation-assertion + attributes: + label: Attestation / Assertion objects + description: If applicable, add the Attestation and Assertion objects you have debugged. + placeholder: This is automatically formatted into Javascript, no need for backticks. + render: javascript + validations: + required: false + - type: dropdown + id: supporter + attributes: + label: Are you a Patreon supporter? + description: Patreon supporters get priority review, fixing and responses. Are you not? [Become one!](https://patreon.com/packagesforlaravel) + options: + - Yes, with my username + - No, don't give priority to this + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..c9ea26b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,53 @@ +name: Feature request +description: Suggest a feature for this package +title: "[X.x] Add this cool feature for this package" +labels: ["enhancement"] +assignees: + - DarkGhostHunter +body: + - type: markdown + attributes: + value: | + Thanks for contributing to this package! + New features keep this package fresh and fun for everybody to use. + - type: checkboxes + id: requirements + attributes: + label: Please check these requirements + options: + - label: This feature helps everyone using this package + required: true + - label: It's feasible and maintainable + required: true + - label: It's non breaking + required: true + - label: I issued a PR with the implementation (optional) + required: false + - type: textarea + id: description + attributes: + label: Description + description: Describe how the feature works + placeholder: This new feature would accomplish this, and would be cool to integrate it to the package because... + validations: + required: true + - type: textarea + id: sample + attributes: + label: Code sample + description: Sample a small snippet on how the feature works + placeholder: | + Laragear::newFeature()->cool(); + render: php + validations: + required: true + - type: dropdown + id: supporter + attributes: + label: Are you a Patreon supporter? + description: Patreon supporters get priority review, fixing and responses. Are you not? [Become one!](https://patreon.com/packagesforlaravel) + options: + - Yes, with my username + - No, don't give priority to this + validations: + required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..20d7f5a --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,33 @@ + + +# Description + +This feature/fix allows to... + +# Code samples + +```php +Laragear::sample(); +``` + + diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..7995edd --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 +updates: +- package-ecosystem: composer + directory: "/" + schedule: + interval: daily + time: "09:00" + open-pull-requests-limit: 10 diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml new file mode 100644 index 0000000..420454f --- /dev/null +++ b/.github/workflows/php.yml @@ -0,0 +1,50 @@ +name: Tests + +on: + push: + pull_request: + +jobs: + test: + + runs-on: ubuntu-latest + strategy: + fail-fast: true + matrix: + php: [ 8.0, 8.1 ] + laravel: [ 9.* ] + dependency-version: [ prefer-stable, prefer-lowest ] + include: + - laravel: 9.* + testbench: 7.* + + name: PHP ${{ matrix.php }} - Laravel ${{ matrix.laravel }} - ${{ matrix.dependency-version }} + + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: mbstring, intl + coverage: xdebug + + - name: Cache dependencies + uses: actions/cache@v2 + with: + path: ~/.composer/cache/files + key: ${{ runner.os }}-laravel-${{ matrix.laravel }}-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }} + restore-keys: ${{ runner.os }}-laravel-${{ matrix.laravel }}-php-${{ matrix.php }}-composer- + + - name: Install dependencies + run: | + composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-progress --no-update + composer update --${{ matrix.dependency-version }} --prefer-dist --no-progress + - name: Run Tests + run: composer run-script test + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v2 + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e18303b --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.idea +build +composer.lock +docs +vendor +coverage +.phpunit.result.cache diff --git a/.styleci.yml b/.styleci.yml new file mode 100644 index 0000000..606f430 --- /dev/null +++ b/.styleci.yml @@ -0,0 +1,2 @@ +preset: laravel +version: 8.1 diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..2efb876 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) Italo Israel Baeza Cabrera +Copyright (c) 2021 Lukas Buchs (Attestation Object & Formats, Authenticator Data parts) +Copyright (c) 2018 Thomas Bleeker (CBOR & ByteBuffer part) + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b477647 --- /dev/null +++ b/README.md @@ -0,0 +1,683 @@ +# WebAuthn +[![Latest Version on Packagist](https://img.shields.io/packagist/v/laragear/webauthn.svg)](https://packagist.org/packages/laragear/webauthn) [![Latest stable test run](https://github.com/Laragear/WebAuthn/workflows/Tests/badge.svg)](https://github.com/Laragear/WebAuthn/actions) [![Codecov coverage](https://codecov.io/gh/Laragear/WebAuthn/branch/1.x/graph/badge.svg?token=BJMBVZNPM8)](https://codecov.io/gh/Laragear/WebAuthn) [![Maintainability](https://api.codeclimate.com/v1/badges/64241e25adb0f55d7ba1/maintainability)](https://codeclimate.com/github/Laragear/WebAuthn/maintainability) [![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=Laragear_WebAuthn&metric=alert_status)](https://sonarcloud.io/dashboard?id=Laragear_WebAuthn) [![Laravel Octane Compatibility](https://img.shields.io/badge/Laravel%20Octane-Compatible-success?style=flat&logo=laravel)](https://laravel.com/docs/9.x/octane#introduction) + +Authenticate users with fingerprints, patterns and biometric data. + +```php +use Laragear\WebAuthn\Http\Requests\AssertedRequest; + +public function login(AssertedRequest $request) +{ + $user = $request->login(); + + return response()->json(['message' => "Welcome back, $user->name!"]); +} +``` + +## Keep this package free + +[![](.assets/patreon.png)](https://patreon.com/packagesforlaravel)[![](.assets/ko-fi.png)](https://ko-fi.com/DarkGhostHunter)[![](.assets/buymeacoffee.png)](https://www.buymeacoffee.com/darkghosthunter)[![](.assets/paypal.png)](https://www.paypal.com/paypalme/darkghosthunter) + +Your support allows me to keep this package free, up-to-date and maintainable. Alternatively, you can **[spread the word!](http://twitter.com/share?text=I%20am%20using%20this%20cool%20PHP%20package&url=https://github.com%2FLaragear%2FWebAuthn&hashtags=PHP,Laravel)** + +## Requirements + +* PHP 8.0 or later, with `ext-openssl`. +* Laravel 9.x or later. + +## Installation + +Require this package into your project using Composer: + +```bash +composer require laragear/webauthn +``` + +## How does it work? + +WebAuthn authentication process consists in two _ceremonies_: attestation, and assertion. + +Attestation is the process of registering in the app a new public key from the authenticated user device. For that to work, the user must exist, and the device or browser must support WebAuthn. + +Assertion is the process of pushing a cryptographic challenge to the device, and checking the response is valid using the public key already registered inside the application. + +The private key doesn't leave the device, and there are no shared passwords to remember. + +## Set up + +We need to make sure your users can register their devices and authenticate with them. + +1. [Add the `eloquent-webauthn` driver](#1-add-the-eloquent-webauthn-driver) +2. [Create the `webauthn_credentials` table](#2-create-the-webauthn_credentials-table) +3. [Implement the contract and trait](#3-implement-the-contract-and-trait) + +After that, you can quickly start WebAuthn with the included controllers and helpers to make your life easier. + +4. [Register the controllers](#4-register-the-controllers) +5. [Use the Javascript helper](#5-use-the-javascript-helper) + +### 1. Add the `eloquent-webauthn` driver + +Laragear WebAuthn works by extending the Eloquent User Provider with an additional check to find a user for the given WebAuthn Credentials (Assertion). This makes this WebAuthn package compatible with any guard you may have. + +Simply go into your `auth.php` configuration file, change the driver from `eloquent` to `eloquent-webauthn`, and add the `password_fallback` to `true`. + +```php +return [ + // ... + + 'providers' => [ + 'users' => [ + 'driver' => 'eloquent-webauthn', + 'model' => App\User::class, + 'password_fallback' => true, + ], + ] +]; +``` + +The `password_fallback` indicates the User Provider should fall back to validate the password when the request is not a WebAuthn Assertion. It's enabled to seamlessly use both classic and WebAuthn authentication procedures. + +### 2. Create the `webauthn_credentials` table + +Create the `webauthn_credentials` table by publishing the migration file and migrating the table: + +```shell +php artisan vendor:publish --provider="Laragear\WebAuthn\WebAuthnServiceProvider" --tag="migrations" +php artisan migrate +``` + +> You may edit the migration to your liking, like adding new columns, but **not** to remove them or change their name. + +### 3. Implement the contract and trait + +Add the `WebAuthnAuthenticatable` contract and the `WebAuthnAuthentication` trait to the User class, or any other that uses authentication. + +```php +configureRateLimiting(); + + $this->routes(function () { + Route::middleware('api') + ->prefix('api') + ->group(base_path('routes/api.php')); + + Route::middleware('web') + ->group(base_path('routes/web.php')); + + // WebAuthn Routes + Route::middleware('web') + ->group(base_path('routes/webauthn.php')); + }); +} +``` + +Along with the routes, the authentication controllers will be located at `App\Http\Controllers\WebAuthn`, which these routes point them toward automatically. + +### 5. Use the Javascript helper + +This package includes a simple but convenient script to handle WebAuthn Attestation and Assertion. To use it, just publish the `webauthn.js` asset into your application public resources. + +```shell +php artisan vendor:publish --provider="Laragear\WebAuthn\WebAuthnServiceProvider" --tag="js" +``` + +You will receive the `resources/js/vendor/webauthn/webauthn.js` file which you can include into your authentication views and use it programmatically, anyway you want. For example, compiling it [through Laravel Mix](https://laravel.com/docs/9.x/mix#working-with-scripts) into your application global Javascript. + +```html + + + + + + + +``` + +You can copy-paste this helper into your authentication routes, or import it into a bundler like [Laravel Vite](https://github.com/laravel/vite-plugin), [Webpack](https://webpack.js.org/), [parcel](https://parceljs.org/), or many more. If the script doesn't suit your needs, you're free to create your own. + +### Requests and Responses parameters + +Both `register()` and `login()` accept different parameters for the initial request to the server, and the subsequent response to the server. For example, you can use this to _remember_ the user being authenticated. + +```javascript +new WebAuthn().login({ + email: document.getElementById('email').value, // Initial request to the server +}, { + remember: document.getElementById('remember').checked ? 'on' : null, // Response from the authenticator +}) +``` + +### Custom routes + +By default, the helper assumes you're using the [default WebAuthn routes](#4-register-the-controllers). If you're using different routes for WebAuthn, you can set them at runtime. Here is good place to use [ziggy](https://github.com/tighten/ziggy) if it's in your project. + +```javascript +const webAuthn = new WebAuthn({ + registerOptions: 'webauthn/register/options', + register: 'webauthn/register', + + loginOptions: 'webauthn/login/options', + login: 'webauthn/login', +}); +``` + +### Headers + +You may add headers to all WebAuthn authentication requests using the second parameter of the `WebAuthn` constructor. These headers will be present on all requests made by the instance. + +```javascript +const webAuthn = new WebAuthn({}, { + 'X-Colors': 'red', +}); +``` + +> You may use a different `WebAuthn` instances with different headers for both Attestation and Assertion. + +## Attestation + +Attestation is the _ceremony_ to create WebAuthn Credentials. To create an Attestable Response that the user device can understand, use the `AttestationRequest::toCreate()` form request. + +```php +use Laragear\WebAuthn\Http\Requests\AttestationRequest; + +public function createChallenge(AttestationRequest $request) +{ + return $request->toCreate(); +} +``` + +The device will receive the "instructions" to make a key, and will respond with it. You can use the `AttestedRequest` form request and its `save()` method to persist the WebAuthn key if it is valid. The request will automatically return a Validation exception if something fails. + +```php +use Laragear\WebAuthn\Http\Requests\AttestedRequest; + +public function register(AttestedRequest $attestation) +{ + $attestation->save(); + + return 'Now you can login without passwords!'; +} +``` + +You may pass an array, or a callback, to the `save()`, which will allow you to modify the underlying WebAuthn Eloquent Model before saving it. For example, we could add an alias for the key present in the Request data. + +```php +use Laragear\WebAuthn\Http\Requests\AttestedRequest; + +public function register(AttestedRequest $request) +{ + $request->validate(['alias' => 'nullable|string']); + + $attestation->save($request->input('alias')); +} +``` + +### Attestation User verification + +By default, the authenticator decides how to verify user when creating a credential. Some may ask to press a "Continue" button to confirm presence, others will verify the User with biometrics, patterns or passwords. + +You can override this using `fastRegistration()` to only check for user presence if possible, or `secureRegistration()` to actively verify the User. + +```php +use Laragear\WebAuthn\Http\Requests\AttestationRequest; + +public function createChallenge(AttestationRequest $request) +{ + return $request->fastRegistration()->toCreate(); +} +``` + +### Userless/One-touch/Typeless Login + +Userless/One-touch/Typeless login This enables one click/tap login, without the need to specify the user credentials (like the email) beforehand. + +For this to work, the device has to save the "username id" inside itself. Some authenticators _may_ save it regardless, others may be not compatible. To make this mandatory when creating the WebAuthn Credential, use the `userless()` method of the `AttestationRequest` form request. + +```php +use Laragear\WebAuthn\Http\Requests\AttestationRequest; + +public function registerDevice(AttestationRequest $request) +{ + return $request->userless()->toCreate(); +} +``` + +> The Authenticator WILL require [user verification](#attestation-user-verification) on login when using `userless()`. Its highly probable the user will also be asked for [user verification on login](#assertion-user-verification), as it will depend on the authenticator itself. + +### Multiple credentials per device + +By default, during Attestation, the device will be informed about the existing enabled credentials already registered in the application. This way the device can avoid creating another one for the same purpose. + +You can enable multiple credentials per device using `allowDuplicates()`, which in turn will always return an empty list of credentials to exclude. This way the authenticator will _think_ there are no already stored credentials for your app. + +```php +use Laragear\WebAuthn\Http\Requests\AttestationRequest; + +public function registerDevice(AttestationRequest $request) +{ + return $request->allowDuplicates()->make(); +} +``` + +## Assertion + +The Assertion procedure also follows a two-step procedure: the user will input its username, the server will return the IDs of the WebAuthn credentials to use, and the device pick one to sign the response. If you're using [userless login](#userlessone-touchtypeless-login), only the challenge is returned. + +First, use the `AssertionRequest::toVerify()` form request. It will automatically create an assertion for the user that matches the credentials, or a blank one in case you're using [userless login](#userlessone-touchtypeless-login). Otherwise, you may set stricter validation rules to always ask for credentials. + +```php +use Laragear\WebAuthn\Http\Requests\AssertionRequest; + +public function createChallenge(AssertionRequest $request) +{ + $request->validate(['email' => 'sometimes|email']); + + return $request->toVerify($request->only('email')); +} +``` + +After that, you may receive the challenge using the `AssertedRequest` request object by just type-hinting it in the controller. + +Since the authentication is pretty much straightforward, you only need to check if the `login()` method returns the newly authenticated user or `null` when it fails. When it's a success, it will take care of [regenerating the session](https://laravel.com/docs/9.x/session#regenerating-the-session-id) for you. + +```php +use Laragear\WebAuthn\Http\Requests\AssertedRequest; + +public function createChallenge(AssertedRequest $request) +{ + $user = $request->login(); + + return $user + ? response("Welcome back, $user->name!"); + : response('Something went wrong, try again!'); +} +``` + +If you need greater control on the Assertion procedure, you may want to [Assert manually](#manually-attesting-and-asserting). + +> If you have [debugging enabled](https://laravel.com/docs/9.x/configuration#debug-mode) the assertion error during authentication will be logged in your application logs, which by default is `storage/logs/laravel.log`. + +### Assertion User Verification + +In the same style of [attestation user verification](#attestation-user-verification), the authenticator decides if it should verify the user on login or not. + +You may only require the user presence with `fastLogin()`, or actively verify the user with `secureLogin()`. + +```php +use Laragear\WebAuthn\Http\Requests\AssertionRequest; + +public function createChallenge(AssertionRequest $request) +{ + $request->validate(['email' => 'sometimes|email']); + + return $request->fastLogin()->toVerify($request->only('email')); +} +``` + +### Password Fallback + +By default, the `eloquent-webauthn` can be used to log in users with passwords when the credentials are not a WebAuthn JSON payload. This way, your normal Authentication flow is unaffected: + +```php +use Illuminate\Support\Facades\Auth; + +public function login(Request $request) +{ + $request->validate(['email' => 'required|email', 'password' => 'required|string']); + + if (Auth::attempt($request->only('email', 'password'))) { + return redirect()->home(); + } + + return back()->withErrors(['email' => 'No user found with these credentials']); +} +``` + +You may disable the fallback to only allow WebAuthn authentication by [setting `password_fallback` to `false`](#1-add-the-eloquent-webauthn-driver). This may force you to handle classic user/password using a separate guard. + +### Detecting Cloned Credentials + +During assertion, the package will automatically detect if a Credential as been cloned by comparing how many times the user has logged in with it. + +If it's detected as cloned, the Credential gets blacklisted, a [`CredentialCloned`](#events) event is fired, and the Assertion gets denied. + +You can use the event to warn the user: + +```php +use Illuminate\Support\Facades\Event; +use Laragear\WebAuthn\Events\CredentialCloned; +use App\Notifications\SecureYourDevice; + +Event::listen(CredentialCloned::class, function ($cloned) { + $notification = new SecureYourDevice($cloned->credential); + + $cloned->credential->user->notify($notification); +}); +``` + +## Managing Credentials + +The purpose of the `WebAuthnAuthenticatable` contract is to allow managing credentials within the User instance. The most useful methods are: + +* `webAuthnData()`: Returns the non-variable WebAuthn user data to create credentials. +* `flushCredentials()`: Removes all credentials. You can exclude credentials by their id. +* `disableAllCredentials()`: Disables all credentials. You can exclude credentials by their id. +* `makeWebAuthnCredential()`: Creates a new WebAuthn Credential instance. +* `webAuthnCredentials()`: [One-to-Many](https://laravel.com/docs/9.x/eloquent-relationships#one-to-many-polymorphic-relations) relation to query for WebAuthn Credentials. + +You can use these methods to, for example, find a credential to blacklist, or disable WebAuthn completely by flushing all registered devices. + +## Events + +The following events are fired by this package, which you can [hook into in your application](https://laravel.com/docs/9.x/events): + +| Event | Description | +|----------------------|-----------------------------------------------------------------------| +| `CredentialCreated` | An User has registered a new WebAuthn Credential through Attestation. | +| `CredentialEnabled` | A disabled WebAuthn Credential was enabled using `enable()`. | +| `CredentialDisabled` | A enabled WebAuthn Credential was disabled using `disable()`. | +| `CredentialCloned` | A WebAuthn Credential was detected as cloned dring Assertion. | + +## Manually Attesting and Asserting + +If you want to manually Attest and Assert users, you may instance their respective pipelines used for both WebAuthn Ceremonies: + +| Pipeline | Description | +|------------------------|------------------------------------------------------------------| +| `AttestationCreator` | Creates a request to create a WebAuthn Credential. | +| `AttestationValidator` | Validates a response with the WebAuthn Credential and stores it. | +| `AssertionCreator` | Creates a request to validate a WebAuthn Credential. | +| `AssertionValidator` | Validates a response for a WebAuthn Credential. | + +All of these pipelines **require** the current Request to work, as is used to generate Challenges in the Session and validate different parts of the authentication data. + +For example, you may manually authenticate a user with its WebAuthn Credentials `AssertionValidator` pipeline. + +```php +use Laragear\WebAuthn\Assertion\Validator\AssertionValidation; +use Laragear\WebAuthn\Assertion\Validator\AssertionValidator; +use Illuminate\Support\Facades\Auth; + +public function authenticate(Request $request, AssertionValidator $assertion) +{ + $credential = $assertion + ->send(new AssertionValidation($request)) + ->thenReturn() + ->credential; + + Auth::login($credential->user); + + return "Welcome aboard, {$credential->user->name}!"; +} +``` + +Since these are Laravel Pipelines, you're free to push additional pipes: + +```php +use Laragear\WebAuthn\Assertion\Validator\AssertionValidator; + +public function addPipes(AssertionValidator $attestation) +{ + $attestation->pipe(VerifyUserIsAwesome::class, NotifyIfAssertionFailed::class); +} +``` + +> The pipes list and the pipes themselves are **not** covered by API changes, and are marked as `internal`. These may change between versions without notice. + +## Advanced Configuration + +Laragear WebAuthn was made to work out-of-the-box, but you can override the configuration by simply publishing the config file. + +```shell +php artisan vendor:publish --provider="Laragear\WebAuthn\WebAuthnServiceProvider" --tag="config" +``` + +After that, you will receive the `config/webauthn.php` config file with an array like this: + +```php + [ + 'name' => env('WEBAUTHN_NAME', env('APP_NAME')), + 'id' => env('WEBAUTHN_ID'), + ], + 'challenge' => [ + 'bytes' => 16, + 'timeout' => 60, + 'key' => '_webauthn', + ] +]; +``` + +### Relaying Party Information + +```php +return [ + 'relaying_party' => [ + 'name' => env('WEBAUTHN_NAME', env('APP_NAME')), + 'id' => env('WEBAUTHN_ID'), + ], +]; +``` + +The _Relaying Party_ is just a way to uniquely identify your application in the user device: + +* `name`: The name of the application. Defaults to the application name. +* `id`: An unique ID the application, like the site domain. If `null`, the device may fill it internally, usually as the full domain. + +> WebAuthn authentication only work on the top domain it was registered. + +### Challenge configuration + +```php +return [ + 'challenge' => [ + 'bytes' => 16, + 'timeout' => 60, + 'key' => '_webauthn', + ] +]; +``` + +The outgoing challenges are random string of bytes. This controls how many bytes, the seconds which the challenge is valid, and the session key used to store the challenge while its being resolved by the device. + +## Laravel UI, Jetstream, Fortify, Sanctum, Breeze, Inertia and Livewire + +In _theory_ this package should work without any problems with these packages, but you may need to override or _redirect_ the authentication flow (read: method codes) to one using WebAuthn. + +There is no support for using WebAuthn with these packages because these are meant to be used with classic user-password authentication. Any issue regarding these packages will be shot down with extreme prejudice. + +If you think WebAuthn is critical for these packages, [consider supporting this package](#keep-this-package-free). + +## FAQ + +* **Does this work with any browser?** + +[Yes](https://caniuse.com/#feat=webauthn). In the case of old browsers, you should have a fallback detection script. This can be asked with [the included Javascript helper](#5-use-the-javascript-helper) in a breeze: + +```javascript +if (WebAuthn.doesntSupportWebAuthn()) { + alert('Your device is not secure enough to use this site!'); +} +``` + +* **Does this store the user fingerprints, PINs or patterns in my site?** + +No. WebAuthn only stores a cryptographic public key generated randomly by the device. + +* **Can a phishing site steal WebAuthn credentials and use them in my site?** + +No. WebAuthn _kills the phishing_ because, unlike passwords, the private key never leaves the device. + +* **Can WebAuthn data identify a particular device?** + +No, unless explicitly [requested](https://www.w3.org/TR/webauthn-2/#attestation-conveyance) and consented. This package doesn't support other attestation conveyances than `none`, so it's never transmitted. + +* **Are my user's classic passwords safe?** + +Yes, as long you are hashing them as you should. This is done by Laravel by default. You can also [disable them](#password-fallback). + +* **Can a user register two or more different _devices_ for the same account?** + +Yes. + +* **Can a user register two or more credentials in the same device?** + +Not by default, but [you can enable it](#multiple-credentials-per-device). + +* **If a user loses his device, can he register a new device?** + +Yes. If you're not using a [password fallback](#password-fallback), you may need to create a logic to register a new device using an email. It's assumed he is reading his email using a trusted device. + +* **What's the difference between disabling and deleting a credential?** + +Disabling a credential doesn't delete it, so it's useful as a blacklisting mechanism and these can also be re-enabled. When the credential is deleted, it goes away forever. + +* **Can a user delete its credentials from its device?** + +Yes. If it does, the other part of the credentials in your server gets virtually orphaned. You may want to show the user a list of registered credentials in the application to delete them. + +* **How secure is this against passwords or 2FA?** + +Extremely secure since it works only on HTTPS (or `localhost`), no password or codes are exchanged nor visible in the screen. + +* **Can I deactivate the password fallback? Can I enforce only WebAuthn authentication?** + +[Yes](#password-fallback). Just be sure to create recovery helpers to avoid locking out your users. + +* **Does this includes a frontend Javascript?** + +[Yes](#5-use-the-javascript-helper), but it's very _basic_. + +* **Does WebAuthn eliminate bots? Can I forget about _captchas_?** + +No, you still need to use [captcha](https://github.com/Laragear/ReCaptcha), honeypots, or other mechanisms to stop bots. + +* **Does this encodes/decode the WebAuthn data automatically in the frontend?** + +Yes, the included [WebAuthn Helper](#5-use-the-javascript-helper) does it automatically for you. + +* **Does this encrypts the public keys?** + +Yes, public keys are encrypted when saved into the database. + +* **Does this include a credential recovery routes?** + +No. You're free to create your own flow for recovery. + +* **Can I use my smartphone as authenticator through my PC or Mac?** + +It depends. This is entirely up to hardware, OS and browser vendor themselves. + +* **Why my device doesn't show Windows Hello/Passkey/TouchId/FaceId/pattern/fingerprint authentication?** + +By default, this WebAuthn implementation accepts _almost_ everything. Some combinations of devices, OS and Web browsers may differ on what to make available for WebAuthn authentication. For example, Windows 7 only supports USB keys. + +* **Why my device doesn't work at all with this package?** + +This package supports WebAuthn 2.0, which is [W3C Recommendation](https://www.w3.org/TR/webauthn-2). Your device/OS/browser may be using an unsupported version. There are no plans to support older specs. + +* **I'm trying to test this in my development server, but it doesn't work** + +Use `localhost` exclusively, not `127.0.0.1`, or use a proxy to tunnel your site through HTTPS. WebAuthn only works on `localhost` or under `HTTPS` only. + +* **Why this package supports only `none` attestation conveyance?** + +Because `direct`, `indirect` and `enterprise` attestations are mostly used on high-security high-risk scenarios, where an entity has total control on the devices used to authenticate. + +If you deem this feature critical for you, [**consider supporting this package**](#keep-this-package-free). + +* **Can I allow logins with only USB keys?** + +No. The user can use whatever to authenticate in your app. This may be enabled on future versions. + +* **Everytime I make attestations or assertions, it says no challenge exists!** + +Remember that your WebAuthn routes must use Sessions, because the Challenge gets saved there. + +## Laravel Octane Compatibility + +* There are no singletons using a stale application instance. +* There are no singletons using a stale config instance. +* There are no singletons using a stale request instance. +* There are no static properties written during a request. + +There should be no problems using this package with Laravel Octane. + +## Security + +These are some details about this WebAuthn implementation: + +* Registration (attestation) and Login (assertion) challenges use the current request session. +* Only one ceremony can be done at a time. +* Challenges are pulled from the session on resolution, independently of their result. +* All challenges and ceremonies expire at 60 seconds. +* WebAuthn User Handle is UUID v4, reusable if another credential exists. +* Credentials can be blacklisted (enabled/disabled). +* Public Keys are encrypted in the database automatically. + +If you discover any security related issues, please email darkghosthunter@gmail.com instead of using the issue tracker. + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. + +Contains Code from [Lukas Buchs WebAuthn 2.0](https://github.com/lbuchs/WebAuthn) implementation. The MIT License (MIT) where applicable. + +Laravel is a Trademark of Taylor Otwell. Copyright © 2011-2022 Laravel LLC. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..27d3b3c --- /dev/null +++ b/composer.json @@ -0,0 +1,94 @@ +{ + "name": "laragear/webauthn", + "description": "Authenticate your users with biometric data, devices or USB keys.", + "type": "library", + "license": "MIT", + "minimum-stability": "stable", + "prefer-stable": true, + "keywords": [ + "laravel", + "webauthn", + "authentication", + "faceid", + "touchid", + "windows hello", + "passkeys" + ], + "homepage": "https://github.com/laragear/webauthn", + "authors": [ + { + "name": "Lukas Buchs", + "role": "Original developer" + }, + { + "name": "Italo Israel Baeza Cabrera", + "email": "DarkGhostHunter@Gmail.com", + "role": "Developer", + "homepage": "https://patreon.com/packagesforlaravel" + } + ], + "support": { + "source": "https://github.com/Laragear/TwoFactor", + "issues": "https://github.com/Laragear/TwoFactor/issues" + }, + "require": { + "php" : ">=8.0.2", + "ext-openssl": "*", + "ext-json" : "*", + "illuminate/auth": "9.*", + "illuminate/http": "9.*", + "illuminate/session": "9.*", + "illuminate/support": "9.*", + "illuminate/config": "9.*", + "illuminate/database": "9.*", + "illuminate/encryption": "9.*" + }, + "require-dev": { + "orchestra/testbench": "7.*", + "phpunit/phpunit": "^9.5", + "mockery/mockery": "^1.5" + }, + "autoload": { + "psr-4": { + "Laragear\\WebAuthn\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Tests\\": "tests", + "App\\Http\\Controllers\\WebAuthn\\": "stubs/controllers" + } + }, + "scripts": { + "test": "vendor/bin/phpunit --coverage-clover build/logs/clover.xml", + "test-coverage": "vendor/bin/phpunit --coverage-html coverage" + }, + "config": { + "sort-packages": true + }, + "extra": { + "laravel": { + "providers": [ + "Laragear\\WebAuthn\\WebAuthnServiceProvider" + ] + } + }, + "funding": [ + { + "type": "Patreon", + "url": "https://patreon.com/PackagesForLaravel" + }, + { + "type": "Ko-Fi", + "url": "https://ko-fi.com/DarkGhostHunter" + }, + { + "type": "Buy me a cofee", + "url": "https://www.buymeacoffee.com/darkghosthunter" + }, + { + "type": "Paypal", + "url": "https://paypal.me/darkghosthunter" + } + ] +} diff --git a/config/webauthn.php b/config/webauthn.php new file mode 100644 index 0000000..6031393 --- /dev/null +++ b/config/webauthn.php @@ -0,0 +1,37 @@ + [ + 'name' => env('WEBAUTHN_NAME', config('app.name')), + 'id' => env('WEBAUTHN_ID'), + ], + + /* + |-------------------------------------------------------------------------- + | Challenge configuration + |-------------------------------------------------------------------------- + | + | When making challenges your application needs to push at least 16 bytes + | of randomness. Since we need to later check them, we'll also store the + | bytes for a small amount of time inside this current request session. + | + */ + + 'challenge' => [ + 'bytes' => 16, + 'timeout' => 60, + 'key' => '_webauthn', + ], +]; diff --git a/database/migrations/2022_07_01_000000_create_webauthn_credentials.php b/database/migrations/2022_07_01_000000_create_webauthn_credentials.php new file mode 100644 index 0000000..b5798e0 --- /dev/null +++ b/database/migrations/2022_07_01_000000_create_webauthn_credentials.php @@ -0,0 +1,79 @@ +timestamp('last_login_at')->nullable(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down(): void + { + Schema::dropIfExists('webauthn_credentials'); + } + + /** + * Generate the default blueprint for the WebAuthn credentials table. + * + * @param \Illuminate\Database\Schema\Blueprint $table + * @return void + */ + protected static function defaultBlueprint(Blueprint $table): void + { + $table->string('id')->primary(); + + $table->morphs('authenticatable'); + + // This is the user UUID that is generated automatically when a credential for the + // given user is created. If a second credential is created, this UUID is queried + // and then copied on top of the new one, this way the real User ID doesn't change. + $table->uuid('user_id'); + + // The app may allow the user to name or rename a credential to a friendly name, + // like "John's iPhone" or "Office Computer". + $table->string('alias')->nullable(); + + // Allows to detect cloned credentials when the assertion does not have this same counter. + $table->unsignedBigInteger('counter')->nullable(); + // Who created the credential. Should be the same reported by the Authenticator. + $table->string('rp_id'); + // Where the credential was created. Should be the same reported by the Authenticator. + $table->string('origin'); + $table->json('transports')->nullable(); + $table->uuid('aaguid')->nullable(); // GUID are essentially UUID + + // This is the public key the credential uses to verify the challenges. + $table->text('public_key'); + // The attestation of the public key. + $table->string('attestation_format')->default('none'); + // This would hold the certificate chain for other different attestation formats. + $table->json('certificates')->nullable(); + + // A way to disable the credential without deleting it. + $table->timestamp('disabled_at')->nullable(); + $table->timestamps(); + } +}; diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..115d353 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,30 @@ + + + + + src/ + + + + + + + + tests + stubs/controllers/WebAuthnLoginController.php + stubs/controllers/WebAuthnRegisterController.php + + + + + + + + + + + + diff --git a/resources/js/webauthn.js b/resources/js/webauthn.js new file mode 100644 index 0000000..1f0aaaa --- /dev/null +++ b/resources/js/webauthn.js @@ -0,0 +1,313 @@ +/** + * MIT License + * + * Copyright (c) Italo Israel Baeza Cabrera + * + * 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. + */ + +class WebAuthn { + /** + * Routes for WebAuthn assertion (login) and attestation (register). + * + * @type {{registerOptions: string, register: string, loginOptions: string, login: string, }} + */ + #routes = { + registerOptions: "webauthn/register/options", + register: "webauthn/register", + loginOptions: "webauthn/login/options", + login: "webauthn/login", + } + + /** + * Headers to use in ALL requests done. + * + * @type {{Accept: string, "Content-Type": string, "X-Requested-With": string}} + */ + #headers = { + "Accept": "application/json", + "Content-Type": "application/json", + "X-Requested-With": "XMLHttpRequest" + }; + + /** + * If set to true, the credentials option will be set to 'include' on all fetch calls, + * or else it will use the default 'same-origin'. Use this if the backend is not the + * same origin as the client or the XSRF protection will break without the session. + * + * @type {boolean} + */ + #includeCredentials = false + + /** + * Create a new WebAuthn instance. + * + * @param routes {{registerOptions: string, register: string, loginOptions: string, login: string}} + * @param headers {{string}} + * @param includeCredentials {boolean} + * @param xsrfToken {string|null} + */ + constructor(routes = {}, headers = {}, includeCredentials = false, xsrfToken = null) { + Object.assign(this.#routes, routes); + Object.assign(this.#headers, headers); + + this.#includeCredentials = includeCredentials; + + // If the developer didn't issue an XSRF token, we will find it ourselves. + this.#headers["X-CSRF-TOKEN"] ??= xsrfToken ?? WebAuthn.#firstInputWithXsrfToken; + } + + /** + * Returns the XSRF token if it exists as a form input tag. + * + * @returns string + * @throws TypeError + */ + static get #firstInputWithXsrfToken() { + // First, try finding an CSRF Token in the head. + let token = Array.from(document.head.getElementsByTagName("meta")) + .find(element => element.name === "csrf-token"); + + if (token) { + return token.content; + } + + // Then, try to find a hidden input containing the CSRF token. + token = Array.from(document.getElementsByTagName('input')) + .find(input => input.name === "_token" && input.type === "hidden") + + if (token) { + return token.value; + } + + // We didn't find it, and since is required, we will bail out. + throw new TypeError('Ensure a CSRF token is manually set, or there is meta tag named "csrf-token".'); + } + + /** + * Returns a fetch promise to resolve later. + * + * @param data {Object} + * @param route {string} + * @param headers {{string}} + * @returns {Promise} + */ + #fetch(data, route, headers = {}) { + return fetch(route, { + method: "POST", + credentials: this.#includeCredentials ? "include" : "same-origin", + redirect: "error", + headers: {...this.#headers, ...headers}, + body: JSON.stringify(data) + }); + } + + /** + * Decodes a BASE64 URL string into a normal string. + * + * @param input {string} + * @returns {string|Iterable} + */ + static #base64UrlDecode(input) { + input = input.replace(/-/g, "+").replace(/_/g, "/"); + + const pad = input.length % 4; + + if (pad) { + if (pad === 1) { + throw new Error("InvalidLengthError: Input base64url string is the wrong length to determine padding"); + } + + input += new Array(5 - pad).join("="); + } + + return atob(input); + } + + /** + * Transform a string into Uint8Array instance. + * + * @param input {string} + * @param useAtob {boolean} + * @returns {Uint8Array} + */ + static #uint8Array(input, useAtob = false) { + return Uint8Array.from( + useAtob ? atob(input) : WebAuthn.#base64UrlDecode(input), c => c.charCodeAt(0) + ); + } + + /** + * Encodes an array of bytes to a BASE64 URL string + * + * @param arrayBuffer {ArrayBuffer|Uint8Array} + * @returns {string} + */ + static #arrayToBase64String(arrayBuffer) { + return btoa(String.fromCharCode(...new Uint8Array(arrayBuffer))); + } + + /** + * Parses the Public Key Options received from the Server for the browser. + * + * @param publicKey {Object} + * @returns {Object} + */ + #parseIncomingServerOptions(publicKey) { + console.debug(publicKey); + + publicKey.challenge = WebAuthn.#uint8Array(publicKey.challenge); + + if ('user' in publicKey) { + publicKey.user = { + ...publicKey.user, + id: WebAuthn.#uint8Array(publicKey.user.id) + }; + } + + [ + "excludeCredentials", + "allowCredentials" + ] + .filter(key => key in publicKey) + .forEach(key => { + publicKey[key] = publicKey[key].map(data => { + return {...data, id: WebAuthn.#uint8Array(data.id)}; + }); + }); + + console.log(publicKey); + + return publicKey; + } + + /** + * Parses the outgoing credentials from the browser to the server. + * + * @param credentials {Credential|PublicKeyCredential} + * @return {{response: {string}, rawId: string, id: string, type: string}} + */ + #parseOutgoingCredentials(credentials) { + let parseCredentials = { + id: credentials.id, + type: credentials.type, + rawId: WebAuthn.#arrayToBase64String(credentials.rawId), + response: {} + }; + + [ + "clientDataJSON", + "attestationObject", + "authenticatorData", + "signature", + "userHandle" + ] + .filter(key => key in credentials.response) + .forEach(key => parseCredentials.response[key] = WebAuthn.#arrayToBase64String(credentials.response[key])); + + return parseCredentials; + } + + /** + * Handles the response from the Server. + * + * Throws the entire response if is not OK (HTTP 2XX). + * + * @param response {Response} + * @returns Promise + * @throws Response + */ + static #handleResponse(response) { + if (!response.ok) { + throw response; + } + + // Here we will do a small trick. Since most of the responses from the server + // are JSON, we will automatically parse the JSON body from the response. If + // it's not JSON, we will push the body verbatim and let the dev handle it. + return new Promise((resolve) => { + response + .json() + .then((json) => resolve(json)) + .catch(() => resolve(response.body)); + }); + } + + /** + * Register the user credentials from the browser/device. + * + * You can add request input if you are planning to register a user with WebAuthn from scratch. + * + * @param request {{string}} + * @param response {{string}} + * @returns Promise + */ + async register(request = {}, response = {}) { + const optionsResponse = await this.#fetch(request, this.#routes.registerOptions); + const json = await optionsResponse.json(); + const publicKey = this.#parseIncomingServerOptions(json); + const credentials = await navigator.credentials.create({publicKey}); + const publicKeyCredential = this.#parseOutgoingCredentials(credentials); + + Object.assign(publicKeyCredential, response); + + return await this.#fetch(publicKeyCredential, this.#routes.register).then(WebAuthn.#handleResponse); + } + + /** + * Log in a user with his credentials. + * + * If no credentials are given, the app may return a blank assertion for userless login. + * + * @param request {{string}} + * @param response {{string}} + * @returns Promise + */ + async login(request = {}, response = {}) { + const optionsResponse = await this.#fetch(request, this.#routes.loginOptions); + const json = await optionsResponse.json(); + const publicKey = this.#parseIncomingServerOptions(json); + const credentials = await navigator.credentials.get({publicKey}); + const publicKeyCredential = this.#parseOutgoingCredentials(credentials); + + Object.assign(publicKeyCredential, response); + + console.log(publicKeyCredential); + + return await this.#fetch(publicKeyCredential, this.#routes.login, response).then(WebAuthn.#handleResponse); + } + + /** + * Checks if the browser supports WebAuthn. + * + * @returns {boolean} + */ + static supportsWebAuthn() { + return typeof PublicKeyCredential != "undefined"; + } + + /** + * Checks if the browser doesn't support WebAuthn. + * + * @returns {boolean} + */ + static doesntSupportWebAuthn() { + return !this.supportsWebAuthn(); + } +} diff --git a/routes/webauthn.php b/routes/webauthn.php new file mode 100644 index 0000000..1283986 --- /dev/null +++ b/routes/webauthn.php @@ -0,0 +1,17 @@ +group(static function (): void { + Route::post('webauthn/register/options', [WebAuthnRegisterController::class, 'options']) + ->name('webauthn.register.options'); + Route::post('webauthn/register', [WebAuthnRegisterController::class, 'register']) + ->name('webauthn.register'); + + Route::post('webauthn/login/options', [WebAuthnLoginController::class, 'options']) + ->name('webauthn.login.options'); + Route::post('webauthn/login', [WebAuthnLoginController::class, 'login']) + ->name('webauthn.login'); +}); diff --git a/src/Assertion/Creator/AssertionCreation.php b/src/Assertion/Creator/AssertionCreation.php new file mode 100644 index 0000000..bc1a4e1 --- /dev/null +++ b/src/Assertion/Creator/AssertionCreation.php @@ -0,0 +1,36 @@ +json = new JsonTransport(); + } +} diff --git a/src/Assertion/Creator/AssertionCreator.php b/src/Assertion/Creator/AssertionCreator.php new file mode 100644 index 0000000..3953433 --- /dev/null +++ b/src/Assertion/Creator/AssertionCreator.php @@ -0,0 +1,23 @@ +json->set('timeout', $this->config->get('webauthn.challenge.timeout') * 1000); + + return $next($assertion); + } +} diff --git a/src/Assertion/Creator/Pipes/CreateAssertionChallenge.php b/src/Assertion/Creator/Pipes/CreateAssertionChallenge.php new file mode 100644 index 0000000..0a4860b --- /dev/null +++ b/src/Assertion/Creator/Pipes/CreateAssertionChallenge.php @@ -0,0 +1,45 @@ +acceptedCredentials?->isNotEmpty()) { + $options['credentials'] = $assertion->acceptedCredentials->map->getKey()->toArray(); + } + + $challenge = $this->storeChallenge($assertion->request, $assertion->userVerification, $options); + + $assertion->json->set('challenge', $challenge->data); + + return $next($assertion); + } +} diff --git a/src/Assertion/Creator/Pipes/MayRequireUserVerification.php b/src/Assertion/Creator/Pipes/MayRequireUserVerification.php new file mode 100644 index 0000000..d8b537f --- /dev/null +++ b/src/Assertion/Creator/Pipes/MayRequireUserVerification.php @@ -0,0 +1,25 @@ +userVerification) { + $assertion->json->set('userVerification', $assertion->userVerification); + } + + return $next($assertion); + } +} diff --git a/src/Assertion/Creator/Pipes/MayRetrieveCredentialsIdForUser.php b/src/Assertion/Creator/Pipes/MayRetrieveCredentialsIdForUser.php new file mode 100644 index 0000000..424cc0e --- /dev/null +++ b/src/Assertion/Creator/Pipes/MayRetrieveCredentialsIdForUser.php @@ -0,0 +1,51 @@ +user) { + $assertion->acceptedCredentials = $assertion->user->webAuthnCredentials()->get(['id', 'transports']); + + if ($assertion->acceptedCredentials->isNotEmpty()) { + $assertion->json->set('allowCredentials', $this->parseCredentials($assertion->acceptedCredentials)); + } + } + + return $next($assertion); + } + + /** + * Adapt all credentials into an `allowCredentials` digestible array. + * + * @param \Illuminate\Database\Eloquent\Collection $credentials + * @return \Illuminate\Support\Collection + */ + protected function parseCredentials(EloquentCollection $credentials): Collection + { + return $credentials->map(static function (WebAuthnCredential $credential): array { + return array_filter([ + 'id' => $credential->getKey(), + 'type' => 'public-key', + 'transports' => $credential->transports + ]); + }); + } +} diff --git a/src/Assertion/Validator/AssertionValidation.php b/src/Assertion/Validator/AssertionValidation.php new file mode 100644 index 0000000..7f55adb --- /dev/null +++ b/src/Assertion/Validator/AssertionValidation.php @@ -0,0 +1,35 @@ +user) { + $this->validateUser($validation); + + if ($validation->request->json('response.userHandle')) { + $this->validateId($validation); + } + } else { + $this->validateId($validation); + } + + return $next($validation); + } + + /** + * Validate the user owns the Credential if it already exists in the validation procedure. + * + * @param \Laragear\WebAuthn\Assertion\Validator\AssertionValidation $validation + * @return void + */ + protected function validateUser(AssertionValidation $validation): void + { + if ($validation->credential->authenticatable()->isNot($validation->user)) { + throw AssertionException::make('User is not owner of the stored credential.'); + } + } + + /** + * Validate the user ID of the response. + * + * @param \Laragear\WebAuthn\Assertion\Validator\AssertionValidation $validation + * @return void + */ + protected function validateId(AssertionValidation $validation): void + { + $handle = $validation->request->json('response.userHandle'); + + if (! $handle || ! hash_equals(Uuid::fromString($validation->credential->user_id)->getHex()->toString(), $handle)) { + throw AssertionException::make('User ID is not owner of the stored credential.'); + } + } + +} diff --git a/src/Assertion/Validator/Pipes/CheckCredentialIsWebAuthnGet.php b/src/Assertion/Validator/Pipes/CheckCredentialIsWebAuthnGet.php new file mode 100644 index 0000000..73b48e1 --- /dev/null +++ b/src/Assertion/Validator/Pipes/CheckCredentialIsWebAuthnGet.php @@ -0,0 +1,30 @@ +clientDataJson->type !== 'webauthn.get') { + throw AssertionException::make('Client Data type is not [webauthn.get].'); + } + + return $next($validation); + } +} diff --git a/src/Assertion/Validator/Pipes/CheckOriginSecure.php b/src/Assertion/Validator/Pipes/CheckOriginSecure.php new file mode 100644 index 0000000..f193e90 --- /dev/null +++ b/src/Assertion/Validator/Pipes/CheckOriginSecure.php @@ -0,0 +1,15 @@ + is greater than storedSignCount: + * Update storedSignCount to be the value of authData.signCount. + * -> less than or equal to storedSignCount: + * This is a signal that the authenticator may be cloned, i.e. at least two copies of the + * credential private key may exist and are being used in parallel. Relying Parties + * should incorporate this information into their risk scoring. Whether the Relying + * Party updates storedSignCount in this case, or not, or fails the authentication + * ceremony or not, is Relying Party-specific. + * + * @internal + */ +class CheckPublicKeyCounterCorrect +{ + /** + * Handle the incoming Assertion Validation. + * + * @param \Laragear\WebAuthn\Assertion\Validator\AssertionValidation $validation + * @param \Closure $next + * @return mixed + * @throws \Laragear\WebAuthn\Exceptions\AssertionException + */ + public function handle(AssertionValidation $validation, Closure $next): mixed + { + if ($this->hasCounter($validation) && $this->counterBelowStoredCredential($validation)) { + $validation->credential->disable(); + + CredentialCloned::dispatch($validation->credential, $validation->authenticatorData->counter); + + throw AssertionException::make('Credential counter not over stored counter.'); + } + + return $next($validation); + } + + /** + * Check if the incoming credential or the stored credential have a counter. + * + * @param \Laragear\WebAuthn\Assertion\Validator\AssertionValidation $validation + * @return bool + */ + protected function hasCounter(AssertionValidation $validation): bool + { + return $validation->credential->counter + || $validation->authenticatorData->counter; + } + + /** + * Check if the credential counter is equal or higher than what the authenticator reports. + * + * @param \Laragear\WebAuthn\Assertion\Validator\AssertionValidation $validation + * @return bool + */ + protected function counterBelowStoredCredential(AssertionValidation $validation): bool + { + return $validation->authenticatorData->counter <= $validation->credential->counter; + } +} diff --git a/src/Assertion/Validator/Pipes/CheckPublicKeySignature.php b/src/Assertion/Validator/Pipes/CheckPublicKeySignature.php new file mode 100644 index 0000000..7b91584 --- /dev/null +++ b/src/Assertion/Validator/Pipes/CheckPublicKeySignature.php @@ -0,0 +1,68 @@ +credential->public_key); + + if (!$publicKey) { + throw AssertionException::make('Stored Public Key is invalid.'); + } + + $signature = base64_decode($validation->request->json('response.signature', '')); + + if (!$signature) { + throw AssertionException::make('Signature is empty.'); + } + + $this->validateSignature($validation, $publicKey, $signature); + + return $next($validation); + } + + /** + * Validate the signature from the assertion. + * + * @param \Laragear\WebAuthn\Assertion\Validator\AssertionValidation $validation + * @param string $signature + * @param \OpenSSLAsymmetricKey $publicKey + * @return void + * @throws \Laragear\WebAuthn\Exceptions\AssertionException + */ + public function validateSignature( + AssertionValidation $validation, + OpenSSLAsymmetricKey $publicKey, + string $signature + ): void { + $verifiable = base64_decode($validation->request->json('response.authenticatorData')) + .hash('sha256', base64_decode($validation->request->json('response.clientDataJSON')), true); + + if (openssl_verify($verifiable, $signature, $publicKey, OPENSSL_ALGO_SHA256) !== 1) { + throw AssertionException::make('Signature is invalid.'); + } + } +} diff --git a/src/Assertion/Validator/Pipes/CheckRelyingPartyHashSame.php b/src/Assertion/Validator/Pipes/CheckRelyingPartyHashSame.php new file mode 100644 index 0000000..eadc1b5 --- /dev/null +++ b/src/Assertion/Validator/Pipes/CheckRelyingPartyHashSame.php @@ -0,0 +1,36 @@ +authenticatorData; + } + + /** + * Return the Relying Party ID from the config or credential. + * + * @param \Laragear\WebAuthn\Assertion\Validator\AssertionValidation|\Laragear\WebAuthn\Attestation\Validator\AttestationValidation $validation + * @return string + */ + protected function relyingPartyId(AssertionValidation|AttestationValidation $validation): string + { + return $validation->credential->rp_id; + } +} diff --git a/src/Assertion/Validator/Pipes/CheckRelyingPartyIdContained.php b/src/Assertion/Validator/Pipes/CheckRelyingPartyIdContained.php new file mode 100644 index 0000000..9c294da --- /dev/null +++ b/src/Assertion/Validator/Pipes/CheckRelyingPartyIdContained.php @@ -0,0 +1,13 @@ +request->json('type') !== 'public-key') { + throw AssertionException::make('Response type is not [public-key].'); + } + + return $next($validation); + } +} diff --git a/src/Assertion/Validator/Pipes/CheckUserInteraction.php b/src/Assertion/Validator/Pipes/CheckUserInteraction.php new file mode 100644 index 0000000..e825d0a --- /dev/null +++ b/src/Assertion/Validator/Pipes/CheckUserInteraction.php @@ -0,0 +1,13 @@ +request->json('response.authenticatorData', '')); + + if (!$data) { + throw AssertionException::make('Authenticator Data does not exist or is empty.'); + } + + try { + $validation->authenticatorData = AuthenticatorData::fromBinary($data); + } catch (DataException $e) { + throw AssertionException::make($e->getMessage()); + } + + return $next($validation); + } +} diff --git a/src/Assertion/Validator/Pipes/CompileClientDataJson.php b/src/Assertion/Validator/Pipes/CompileClientDataJson.php new file mode 100644 index 0000000..1208589 --- /dev/null +++ b/src/Assertion/Validator/Pipes/CompileClientDataJson.php @@ -0,0 +1,13 @@ + is greater than storedSignCount: + * Update storedSignCount to be the value of authData.signCount. + * -> less than or equal to storedSignCount: + * This is a signal that the authenticator may be cloned, i.e. at least two copies of the + * credential private key may exist and are being used in parallel. Relying Parties + * should incorporate this information into their risk scoring. Whether the Relying + * Party updates storedSignCount in this case, or not, or fails the authentication + * ceremony or not, is Relying Party-specific. + * + * @internal + */ +class IncrementCredentialCounter +{ + /** + * Handle the incoming Assertion Validation. + * + * @param \Laragear\WebAuthn\Assertion\Validator\AssertionValidation $validation + * @param \Closure $next + * @return mixed + */ + public function handle(AssertionValidation $validation, Closure $next): mixed + { + $validation->credential->syncCounter($validation->authenticatorData->counter); + + return $next($validation); + } +} diff --git a/src/Assertion/Validator/Pipes/RetrieveChallenge.php b/src/Assertion/Validator/Pipes/RetrieveChallenge.php new file mode 100644 index 0000000..55face7 --- /dev/null +++ b/src/Assertion/Validator/Pipes/RetrieveChallenge.php @@ -0,0 +1,13 @@ +request->json('id'); + + // First, always check the challenge credentials before finding the real one. + if ($this->credentialNotInChallenge($id, $validation->challenge->properties)) { + throw AssertionException::make('Credential is not on accepted list.'); + } + + // We can now find the credential. + $validation->credential = WebAuthnCredential::whereKey($id)->first(); + + if (!$validation->credential) { + throw AssertionException::make('Credential ID does not exist.'); + } + + if ($validation->credential->isDisabled()) { + throw AssertionException::make('Credential ID is blacklisted.'); + } + + return $next($validation); + } + + /** + * Check if the previous Assertion request specified a credentials list to accept. + * + * @param string $id + * @param array $properties + * @return bool + */ + protected function credentialNotInChallenge(string $id, array $properties): bool + { + return isset($properties['credentials']) && ! in_array($id, $properties['credentials'], true); + } +} diff --git a/src/Attestation/AttestationObject.php b/src/Attestation/AttestationObject.php new file mode 100644 index 0000000..3741153 --- /dev/null +++ b/src/Attestation/AttestationObject.php @@ -0,0 +1,26 @@ +relyingPartyIdHash); + } + + /** + * Checks if the Relying Party ID hash is not the same as the one issued. + * + * @param string $relyingPartyId + * @param bool $hash + * @return bool + */ + public function hasNotSameRPIdHash(string $relyingPartyId, bool $hash = true): bool + { + return ! $this->hasSameRPIdHash($relyingPartyId, $hash); + } + + /** + * Check if the user was present during the authentication. + * + * @return bool + */ + public function wasUserPresent(): bool + { + return $this->flags->userPresent; + } + + /** + * Check if the user was absent during the authentication. + * + * @return bool + */ + public function wasUserAbsent(): bool + { + return ! $this->wasUserPresent(); + } + + /** + * Check if the user was actively verified by the authenticator. + * + * @return bool + */ + public function wasUserVerified(): bool + { + return $this->flags->userVerified; + } + + /** + * Check if the user was not actively verified by the authenticator. + * + * @return bool + */ + public function wasUserNotVerified(): bool + { + return ! $this->wasUserVerified(); + } + + /** + * Returns the public key in PEM format. + * + * @return string + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + public function getPublicKeyPem(): string + { + $der = match ($this->attestedCredentialData->credentialPublicKey->kty) { + self::$EC2_TYPE => $this->getEc2Der(), + self::$RSA_TYPE => $this->getRsaDer(), + default => throw new DataException('Invalid credential public key type [kty].'), + }; + + $pem = '-----BEGIN PUBLIC KEY-----'."\n"; + $pem .= chunk_split(base64_encode($der), 64, "\n"); + $pem .= '-----END PUBLIC KEY-----'."\n"; + + return $pem; + } + + /** + * Returns the public key in U2F format. + * + * @return string + */ + public function getPublicKeyU2F(): string + { + return "\x04". // ECC uncompressed + $this->attestedCredentialData->credentialPublicKey->x. + $this->attestedCredentialData->credentialPublicKey->y; + } + + /** + * Returns DER encoded EC2 key + * + * @return string + */ + protected function getEc2Der(): string + { + return $this->derSequence( + $this->derSequence( + $this->derOid("\x2A\x86\x48\xCE\x3D\x02\x01"). // OID 1.2.840.10045.2.1 ecPublicKey + $this->derOid("\x2A\x86\x48\xCE\x3D\x03\x01\x07") // 1.2.840.10045.3.1.7 prime256v1 + ). + $this->derBitString($this->getPublicKeyU2F()) + ); + } + + /** + * Returns DER encoded RSA key. + * + * @return string + */ + protected function getRsaDer(): string + { + return $this->derSequence( + $this->derSequence( + $this->derOid("\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01"). // OID 1.2.840.113549.1.1.1 rsaEncryption + $this->derNullValue() + ). + $this->derBitString( + $this->derSequence( + $this->derUnsignedInteger($this->attestedCredentialData->credentialPublicKey->n). + $this->derUnsignedInteger($this->attestedCredentialData->credentialPublicKey->e) + ) + ) + ); + } + + /** + * Returns the length of a DER encoded string. + * + * @param int $der + * @return string + */ + protected function derLength(int $der): string + { + if ($der < 128) { + return chr($der); + } + + $lenBytes = ''; + + while ($der > 0) { + $lenBytes = chr($der % 256).$lenBytes; + $der = intdiv($der, 256); + } + + return chr(0x80 | strlen($lenBytes)).$lenBytes; + } + + /** + * Encode a string as DER. + * + * @param string $contents + * @return string + */ + protected function derSequence(string $contents): string + { + return "\x30".$this->derLength(strlen($contents)).$contents; + } + + /** + * Encode something an ID of zero as DER. + * + * @param string $encoded + * @return string + */ + protected function derOid(string $encoded): string + { + return "\x06".$this->derLength(strlen($encoded)).$encoded; + } + + /** + * Encode the bit string as DER. + * + * @param string $bytes + * @return string + */ + protected function derBitString(string $bytes): string + { + return "\x03".$this->derLength(strlen($bytes) + 1)."\x00".$bytes; + } + + /** + * Encode a null value as DER. + * + * @return string + */ + protected function derNullValue(): string + { + return "\x05\x00"; + } + + /** + * Encode a unsigned integer as DER. + * + * @param string $bytes + * @return string + */ + protected function derUnsignedInteger(string $bytes): string + { + $len = strlen($bytes); + + // Remove leading zero bytes + for ($i = 0; $i < ($len - 1); $i++) { + if (ord($bytes[$i]) !== 0) { + break; + } + } + if ($i !== 0) { + $bytes = substr($bytes, $i); + } + + // If most significant bit is set, prefix with another zero to prevent it being seen as negative number + if ((ord($bytes[0]) & 0x80) !== 0) { + $bytes = "\x00".$bytes; + } + + return "\x02".$this->derLength(strlen($bytes)).$bytes; + } + + /** + * Create a new Authenticator data from a binary string. + * + * @param string $binary + * @return static + * @throws \Laragear\WebAuthn\Exceptions\DataException + * @codeCoverageIgnore + */ + public static function fromBinary(string $binary): static + { + if (strlen($binary) < 37) { + throw new DataException('Authenticator Data: Invalid input.'); + } + + $relyingPartyIdHash = substr($binary, 0, 32); + + // flags (1 byte) + $flags = static::readFlags(unpack('Cflags', $binary[32])['flags']); + + // signature counter: 32-bit unsigned big-endian integer. + $counter = unpack('Nsigncount', substr($binary, 33, 4))['signcount']; + + $offset = 37; + + $attestedCredentialData = $flags->attestedDataIncluded + ? static::readAttestData($binary, $offset) + : (object) null; + + $extensionData = $flags->extensionDataIncluded + ? static::readExtensionData(substr($binary, $offset)) + : []; + + return new static($relyingPartyIdHash, $flags, $counter, $attestedCredentialData, $extensionData); + } + + /** + * Reads the flags from flag byte array. + * + * @param string $binFlag + * @return object{userPresent: bool, userVerified: bool, attestedDataIncluded: bool, extensionDataIncluded: bool} + */ + protected static function readFlags(string $binFlag): object + { + $flags = (object) [ + 'bit_0' => (bool) ($binFlag & 1), + 'bit_1' => (bool) ($binFlag & 2), + 'bit_2' => (bool) ($binFlag & 4), + 'bit_3' => (bool) ($binFlag & 8), + 'bit_4' => (bool) ($binFlag & 16), + 'bit_5' => (bool) ($binFlag & 32), + 'bit_6' => (bool) ($binFlag & 64), + 'bit_7' => (bool) ($binFlag & 128), + 'userPresent' => false, + 'userVerified' => false, + 'attestedDataIncluded' => false, + 'extensionDataIncluded' => false, + ]; + + // named flags + $flags->userPresent = $flags->bit_0; + $flags->userVerified = $flags->bit_2; + $flags->attestedDataIncluded = $flags->bit_6; + $flags->extensionDataIncluded = $flags->bit_7; + + return $flags; + } + + /** + * Reads the attestation data. + * + * @param string $binary + * @param int $endOffset + * @return object{aaguid: int|bool, credentialId: string, credentialPublicKey: string} + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + protected static function readAttestData(string $binary, int &$endOffset): object + { + if (strlen($binary) <= 55) { + throw new DataException('Attested data is missing'); + } + + // Byte length L of Credential ID, 16-bit unsigned big-endian integer. + $length = unpack('nlength', substr($binary, 53, 2))['length']; + + // Set end offset + $endOffset = 55 + $length; + + return (object) [ + 'aaguid' => substr($binary, 37, 16), + 'credentialId' => new ByteBuffer(substr($binary, 55, $length)), + 'credentialPublicKey' => static::readCredentialPublicKey($binary, 55 + $length, $endOffset) + ]; + } + + /** + * Read COSE key-encoded elliptic curve public key in EC2 format. + * + * @param string $binary + * @param int $offset + * @param int $endOffset + * @return object + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + protected static function readCredentialPublicKey(string $binary, int $offset, int &$endOffset): object + { + $enc = CborDecoder::decodePortion($binary, $offset, $endOffset); + + // COSE key-encoded elliptic curve public key in EC2 format + $publicKey = (object) [ + 'kty' => $enc[static::$COSE_KTY], + 'alg' => $enc[static::$COSE_ALG] + ]; + + switch ($publicKey->alg) { + case static::$EC2_ES256: + static::readCredentialPublicKeyES256($publicKey, $enc); + break; + case static::$RSA_RS256: + static::readCredentialPublicKeyRS256($publicKey, $enc); + break; + } + + return $publicKey; + } + + /** + * Extracts ES256 information from COSE encoding. + * + * @param object $publicKey + * @param array $cose + * @return object + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + protected static function readCredentialPublicKeyES256(object $publicKey, array $cose): object + { + $publicKey->crv = $cose[self::$COSE_CRV]; + $publicKey->x = $cose[self::$COSE_X] instanceof ByteBuffer ? $cose[self::$COSE_X]->getBinaryString() : null; + $publicKey->y = $cose[self::$COSE_Y] instanceof ByteBuffer ? $cose[self::$COSE_Y]->getBinaryString() : null; + + if ($publicKey->kty !== self::$EC2_TYPE) { + throw new DataException('Public key not in EC2 format'); + } + + if ($publicKey->alg !== self::$EC2_ES256) { + throw new DataException('Signature algorithm not ES256'); + } + + if ($publicKey->crv !== self::$EC2_P256) { + throw new DataException('Curve not P-256'); + } + + if (strlen($publicKey->x) !== 32) { + throw new DataException('Invalid X-coordinate'); + } + + if (strlen($publicKey->y) !== 32) { + throw new DataException('Invalid Y-coordinate'); + } + + return $publicKey; + } + + /** + * Extract RS256 information from COSE. + * + * @param object $publicKey + * @param array $enc + * @return void + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + protected static function readCredentialPublicKeyRS256(object $publicKey, array $enc): void + { + $publicKey->n = $enc[self::$COSE_N] instanceof ByteBuffer ? $enc[self::$COSE_N]->getBinaryString() : null; + $publicKey->e = $enc[self::$COSE_E] instanceof ByteBuffer ? $enc[self::$COSE_E]->getBinaryString() : null; + + if ($publicKey->kty !== self::$RSA_TYPE) { + throw new DataException('Public key not in RSA format'); + } + + if ($publicKey->alg !== self::$RSA_RS256) { + throw new DataException('Signature algorithm not ES256'); + } + + if (strlen($publicKey->n) !== 256) { + throw new DataException('Invalid RSA modulus'); + } + + if (strlen($publicKey->e) !== 3) { + throw new DataException('Invalid RSA public exponent'); + } + } + + /** + * Reads CBOR encoded extension data. + * + * @param string $binary + * @return array + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + protected static function readExtensionData(string $binary): array + { + $ext = CborDecoder::decode($binary); + + return is_array($ext) ? $ext : throw new DataException('Invalid extension data'); + } +} diff --git a/src/Attestation/Creator/AttestationCreation.php b/src/Attestation/Creator/AttestationCreation.php new file mode 100644 index 0000000..e63bfa0 --- /dev/null +++ b/src/Attestation/Creator/AttestationCreation.php @@ -0,0 +1,40 @@ +json = new JsonTransport(); + } +} diff --git a/src/Attestation/Creator/AttestationCreator.php b/src/Attestation/Creator/AttestationCreator.php new file mode 100644 index 0000000..3761d51 --- /dev/null +++ b/src/Attestation/Creator/AttestationCreator.php @@ -0,0 +1,28 @@ +json->set('pubKeyCredParams', [ + ['type' => 'public-key', 'alg' => -7], + ['type' => 'public-key', 'alg' => -257], + ]); + + // Currently we don't support direct attestation. In other words, it won't ask + // for attestation data from the authenticator to cross-check later against + // root certificates. We may add this in the future, but not guaranteed. + $attestable->json->set('attestation', 'none'); + + return $next($attestable); + } +} diff --git a/src/Attestation/Creator/Pipes/AddRelyingParty.php b/src/Attestation/Creator/Pipes/AddRelyingParty.php new file mode 100644 index 0000000..edec1a0 --- /dev/null +++ b/src/Attestation/Creator/Pipes/AddRelyingParty.php @@ -0,0 +1,41 @@ +json->set('rp.name', $this->config->get('webauthn.relying_party.name')); + + if ($id = $this->config->get('webauthn.relying_party.id')) { + $attestable->json->set('rp.id', $id); + } + + return $next($attestable); + } +} diff --git a/src/Attestation/Creator/Pipes/AddUserDescriptor.php b/src/Attestation/Creator/Pipes/AddUserDescriptor.php new file mode 100644 index 0000000..e3f0852 --- /dev/null +++ b/src/Attestation/Creator/Pipes/AddUserDescriptor.php @@ -0,0 +1,33 @@ +user->webAuthnData(); + + // Create a new User UUID if it doesn't existe already in the credentials. + $config['id'] = $attestable->user->webAuthnCredentials()->value('user_id') + ?: Str::uuid()->getHex()->toString(); + + $attestable->json->set('user', $config); + + return $next($attestable); + } +} diff --git a/src/Attestation/Creator/Pipes/CreateAttestationChallenge.php b/src/Attestation/Creator/Pipes/CreateAttestationChallenge.php new file mode 100644 index 0000000..d6c4b09 --- /dev/null +++ b/src/Attestation/Creator/Pipes/CreateAttestationChallenge.php @@ -0,0 +1,49 @@ +json->set('timeout', $this->config->get('webauthn.challenge.timeout') * 1000); + + $challenge = $this->storeChallenge($attestable->request, $attestable->userVerification, [ + 'user_uuid' => $attestable->json->get('user.id'), + 'user_handle' => $attestable->json->get('user.name'), + ]); + + $attestable->json->set('challenge', $challenge->data); + + return $next($attestable); + } +} diff --git a/src/Attestation/Creator/Pipes/MayPreventDuplicateCredentials.php b/src/Attestation/Creator/Pipes/MayPreventDuplicateCredentials.php new file mode 100644 index 0000000..71ee893 --- /dev/null +++ b/src/Attestation/Creator/Pipes/MayPreventDuplicateCredentials.php @@ -0,0 +1,51 @@ +uniqueCredentials) { + $attestable->json->set('excludeCredentials', $this->credentials($attestable->user)); + } + + return $next($attestable); + } + + /** + * Returns a collection of credentials ready to be inserted into the Attestable JSON. + * + * @param \Laragear\WebAuthn\Contracts\WebAuthnAuthenticatable $user + * @return array + */ + protected function credentials(WebAuthnAuthenticatable $user): array + { + return $user + ->webAuthnCredentials() + ->get(['id', 'transports']) + ->map(static function (WebAuthnCredential $credential): array { + return array_filter([ + 'id'=> $credential->getKey(), + 'type' => 'public-key', + 'transports' => $credential->transports + ]); + }) + ->toArray(); + } +} diff --git a/src/Attestation/Creator/Pipes/MayRequireUserVerification.php b/src/Attestation/Creator/Pipes/MayRequireUserVerification.php new file mode 100644 index 0000000..41a67d7 --- /dev/null +++ b/src/Attestation/Creator/Pipes/MayRequireUserVerification.php @@ -0,0 +1,28 @@ +userVerification) { + $attestable->json->set('authenticatorSelection.userVerification', $attestable->userVerification); + } + + return $next($attestable); + } +} diff --git a/src/Attestation/Creator/Pipes/SetResidentKeyConfiguration.php b/src/Attestation/Creator/Pipes/SetResidentKeyConfiguration.php new file mode 100644 index 0000000..e6e6759 --- /dev/null +++ b/src/Attestation/Creator/Pipes/SetResidentKeyConfiguration.php @@ -0,0 +1,38 @@ +residentKey) { + $attestable->json->set('authenticatorSelection.residentKey', $attestable->residentKey); + + $verifiesUser = $attestable->residentKey === WebAuthn::RESIDENT_KEY_REQUIRED; + + $attestable->json->set('authenticatorSelection.requireResidentKey', $verifiesUser); + + if ($verifiesUser) { + $attestable->userVerification = WebAuthn::USER_VERIFICATION_REQUIRED; + } + } + + + return $next($attestable); + } +} diff --git a/src/Attestation/Formats/Format.php b/src/Attestation/Formats/Format.php new file mode 100644 index 0000000..8379398 --- /dev/null +++ b/src/Attestation/Formats/Format.php @@ -0,0 +1,53 @@ +createChallenge($verify, $options); + + $request->session()->put($this->config->get('webauthn.challenge.key'), $challenge); + + return $challenge; + } + + /** + * Creates a Challenge using the default timeout. + * + * @param string|null $verify + * @param array $options + * @return \Laragear\WebAuthn\Challenge + */ + protected function createChallenge(?string $verify, array $options = []): Challenge + { + return Challenge::random( + $this->config->get('webauthn.challenge.bytes'), + $this->config->get('webauthn.challenge.timeout'), + $verify === WebAuthn::USER_VERIFICATION_REQUIRED, + $options, + ); + } +} diff --git a/src/Attestation/Validator/AttestationValidation.php b/src/Attestation/Validator/AttestationValidation.php new file mode 100644 index 0000000..550e4ac --- /dev/null +++ b/src/Attestation/Validator/AttestationValidation.php @@ -0,0 +1,35 @@ +clientDataJson->type !== 'webauthn.create') { + throw AttestationException::make('Response is not for creating WebAuthn Credentials.'); + } + + return $next($validation); + } +} diff --git a/src/Attestation/Validator/Pipes/CheckChallengeSame.php b/src/Attestation/Validator/Pipes/CheckChallengeSame.php new file mode 100644 index 0000000..f710ab1 --- /dev/null +++ b/src/Attestation/Validator/Pipes/CheckChallengeSame.php @@ -0,0 +1,17 @@ +attestationObject->authenticatorData; + } + + /** + * Return the Relying Party ID from the config or credential. + * + * @param \Laragear\WebAuthn\Assertion\Validator\AssertionValidation|\Laragear\WebAuthn\Attestation\Validator\AttestationValidation $validation + * @return string + */ + protected function relyingPartyId(AssertionValidation|AttestationValidation $validation): string + { + return $this->config->get('webauthn.relaying_party.id') ?? $this->config->get('app.url'); + } +} diff --git a/src/Attestation/Validator/Pipes/CheckRelyingPartyIdContained.php b/src/Attestation/Validator/Pipes/CheckRelyingPartyIdContained.php new file mode 100644 index 0000000..7692b48 --- /dev/null +++ b/src/Attestation/Validator/Pipes/CheckRelyingPartyIdContained.php @@ -0,0 +1,17 @@ +decodeCborBase64($validation->request); + + // Here we would receive the attestation formats and decode them. Since we're + // only support the universal "none" we can just check if it's equal or not. + // Later we may support multiple authenticator formats through a PHP match. + if ($data['fmt'] !== 'none') { + throw AttestationException::make("Format name [{$data['fmt']}] is invalid."); + } + + try { + $authenticatorData = AuthenticatorData::fromBinary($data['authData']->getBinaryString()); + } catch (DataException $e) { + throw AttestationException::make($e->getMessage()); + } + + $validation->attestationObject = new AttestationObject( + $authenticatorData, new None($data, $authenticatorData), $data['fmt'] + ); + + return $next($validation); + } + + /** + * Returns an array map from a BASE64 encoded CBOR string. + * + * @param \Illuminate\Http\Request $request + * @return array + * @throws \Laragear\WebAuthn\Exceptions\AttestationException + */ + #[ArrayShape(["fmt" => "string", "attStmt" => "array", "authData" => ByteBuffer::class])] + protected function decodeCborBase64(Request $request): array + { + try { + $data = CborDecoder::decode(base64_decode($request->json('response.attestationObject', ''))); + } catch (DataException $e) { + throw AttestationException::make($e->getMessage()); + } + + if (!is_array($data)) { + throw AttestationException::make('CBOR Object is anything but an array.'); + } + + if (!isset($data['fmt']) || !is_string($data['fmt'])) { + throw AttestationException::make('Format is missing or invalid.'); + } + + if (!isset($data['attStmt']) || !is_array($data['attStmt'])) { + throw AttestationException::make('Statement is missing or invalid.'); + } + + if (!isset($data['authData']) || !$data['authData'] instanceof ByteBuffer) { + throw AttestationException::make('Authenticator Data is missing or invalid.'); + } + + return $data; + } +} diff --git a/src/Attestation/Validator/Pipes/CompileClientDataJson.php b/src/Attestation/Validator/Pipes/CompileClientDataJson.php new file mode 100644 index 0000000..39dc55d --- /dev/null +++ b/src/Attestation/Validator/Pipes/CompileClientDataJson.php @@ -0,0 +1,20 @@ +credentialAlreadyExists($validation)) { + throw AttestationException::make('Credential ID already exists in the database.'); + } + + return $next($validation); + } + + /** + * Finds a WebAuthn Credential by the issued ID. + * + * @param \Laragear\WebAuthn\Attestation\Validator\AttestationValidation $validation + * @return bool + */ + protected function credentialAlreadyExists(AttestationValidation $validation): bool + { + return WebAuthnCredential::whereKey($validation->request->json('id'))->exists(); + } +} diff --git a/src/Attestation/Validator/Pipes/MakeWebAuthnCredential.php b/src/Attestation/Validator/Pipes/MakeWebAuthnCredential.php new file mode 100644 index 0000000..0be0b97 --- /dev/null +++ b/src/Attestation/Validator/Pipes/MakeWebAuthnCredential.php @@ -0,0 +1,70 @@ +credential = $validation->user->makeWebAuthnCredential([ + 'id' => $validation->request->json('id'), + + 'user_id' => $validation->challenge->properties['user_uuid'], + 'alias' => $validation->request->json('response.alias'), + + 'counter' => $validation->attestationObject->authenticatorData->counter, + 'rp_id' => $this->config->get('webauthn.relaying_party.id') ?? $this->config->get('app.url'), + 'origin' => $validation->clientDataJson->origin, + 'transports' => $validation->request->json('response.transports'), + 'aaguid' => Uuid::fromBytes($validation->attestationObject->authenticatorData->attestedCredentialData->aaguid), + + 'public_key' => $this->getPublicKeyAsPem($validation), + 'attestation_format' => $validation->attestationObject->formatName, + ]); + + return $next($validation); + } + + /** + * Returns a public key from the credentials as a PEM string. + * + * @param \Laragear\WebAuthn\Attestation\Validator\AttestationValidation $validation + * @return string + */ + protected function getPublicKeyAsPem(AttestationValidation $validation): string + { + try { + return $validation->attestationObject->authenticatorData->getPublicKeyPem(); + } catch (DataException $e) { + throw AttestationException::make($e->getMessage()); + } + } +} diff --git a/src/Attestation/Validator/Pipes/RetrieveChallenge.php b/src/Attestation/Validator/Pipes/RetrieveChallenge.php new file mode 100644 index 0000000..f36a5b2 --- /dev/null +++ b/src/Attestation/Validator/Pipes/RetrieveChallenge.php @@ -0,0 +1,13 @@ +model, WebAuthnAuthenticatable::class) && $this->isSignedChallenge($credentials)) { + /** @noinspection PhpIncompatibleReturnTypeInspection */ + return $this->newModelQuery() + ->whereHas('webAuthnCredentials', static function (Builder $query) use ($credentials): void { + $query->whereKey($credentials['id'])->whereEnabled(); + }) + ->first(); + } + + return parent::retrieveByCredentials($credentials); + } + + /** + * Check if the credentials are for a public key signed challenge + * + * @param array $credentials + * @return bool + */ + protected function isSignedChallenge(array $credentials): bool + { + return isset($credentials['id'], $credentials['rawId'], $credentials['response'], $credentials['type']); + } + + /** + * Validate a user against the given credentials. + * + * @param \Illuminate\Contracts\Auth\Authenticatable|\Laragear\WebAuthn\Contracts\WebAuthnAuthenticatable $user + * @param array $credentials + * + * @return bool + */ + public function validateCredentials($user, array $credentials): bool + { + if ($user instanceof WebAuthnAuthenticatable && $this->isSignedChallenge($credentials)) { + return $this->validateWebAuthn(); + } + + // If the fallback is enabled, we will validate the credential password. + return $this->fallback && parent::validateCredentials($user, $credentials); + } + + /** + * Validate the WebAuthn assertion. + * + * @return bool + */ + protected function validateWebAuthn(): bool + { + try { + $this->validator->send(new AssertionValidation(request()))->thenReturn(); + } catch (AssertionException $e) { + // If we're debugging, like under local development, push the error to the logger. + if (config('app.debug')) { + logger($e->getMessage()); + } + + return false; + } + + return true; + } +} diff --git a/src/ByteBuffer.php b/src/ByteBuffer.php new file mode 100644 index 0000000..abd948e --- /dev/null +++ b/src/ByteBuffer.php @@ -0,0 +1,472 @@ +dataLength = strlen($binaryData); + } + + /** + * Returns the length of the ByteBuffer data. + * + * @return int + */ + public function getDataLength(): int + { + return $this->dataLength; + } + + /** + * Check if the length of the data is greater than zero. + * + * @return bool + */ + public function hasLength(): bool + { + return (bool) $this->dataLength; + } + + /** + * Check if the length of the data is zero. + * + * @return bool + */ + public function hasNoLength(): bool + { + return !$this->hasLength(); + } + + /** + * Returns the binary string verbatim. + * + * @return string + */ + public function getBinaryString(): string + { + return $this->binaryData; + } + + /** + * Check if both Byte Buffers are equal using `hash_equals`. + * + * @param \Laragear\WebAuthn\ByteBuffer|string $buffer + * @return bool + */ + public function hashEqual(self|string $buffer): bool + { + if ($buffer instanceof static) { + $buffer = $buffer->getBinaryString(); + } + + return hash_equals($this->binaryData, $buffer); + } + + /** + * Check if both Byte Buffers are not equal using `hash_equals`. + * + * @param \Laragear\WebAuthn\ByteBuffer|string $buffer + * @return bool + */ + public function hashNotEqual(self|string $buffer): bool + { + return ! $this->hashEqual($buffer); + } + + /** + * Returns a certain portion of these bytes. + * + * @param int $offset + * @param int|null $length + * @return string + */ + public function getBytes(int $offset = 0, int $length = null): string + { + $length ??= $this->dataLength; + + if ($offset < 0 || $length < 0 || ($offset + $length > $this->dataLength)) { + throw new InvalidArgumentException('ByteBuffer: Invalid offset or length.'); + } + + return substr($this->binaryData, $offset, $length); + } + + /** + * Returns the value of a single byte. + * + * @param int $offset + * @return int + */ + public function getByteVal(int $offset = 0): int + { + if (!$byte = $this->binaryData[$offset] ?? null) { + throw new InvalidArgumentException('ByteBuffer: Invalid offset'); + } + + return ord($byte); + } + + /** + * Returns the value of a single unsigned 16-bit integer. + * + * @param int $offset + * @return mixed + */ + public function getUint16Val(int $offset = 0): int + { + if ($offset < 0 || ($offset + 2) > $this->dataLength) { + throw new InvalidArgumentException('ByteBuffer: Invalid offset'); + } + + return unpack('n', $this->binaryData, $offset)[1]; + } + + /** + * Returns the value of a single unsigned 32-bit integer. + * + * @param int $offset + * @return mixed + */ + public function getUint32Val(int $offset = 0): int + { + if ($offset < 0 || ($offset + 4) > $this->dataLength) { + throw new InvalidArgumentException('ByteBuffer: Invalid offset'); + } + + $val = unpack('N', $this->binaryData, $offset)[1]; + + // Signed integer overflow causes signed negative numbers + if ($val < 0) { + throw new OutOfBoundsException('ByteBuffer: Value out of integer range.'); + } + + return $val; + } + + /** + * Returns the value of a single unsigned 64-bit integer. + * + * @param int $offset + * @return int + */ + public function getUint64Val(int $offset): int + { + if (PHP_INT_SIZE < 8) { + throw new OutOfBoundsException('ByteBuffer: 64-bit values not supported by this system'); + } + + if ($offset < 0 || ($offset + 8) > $this->dataLength) { + throw new InvalidArgumentException('ByteBuffer: Invalid offset'); + } + + $val = unpack('J', $this->binaryData, $offset)[1]; + + // Signed integer overflow causes signed negative numbers + if ($val < 0) { + throw new OutOfBoundsException('ByteBuffer: Value out of integer range.'); + } + + return $val; + } + + /** + * Returns the value of a single 16-bit float. + * + * @param int $offset + * @return float + */ + public function getHalfFloatVal(int $offset = 0): float + { + // FROM spec pseudo decode_half(unsigned char *halfp) + $half = $this->getUint16Val($offset); + + $exp = ($half >> 10) & 0x1f; + $mant = $half & 0x3ff; + + if ($exp === 0) { + $val = $mant * (2 ** -24); + } elseif ($exp !== 31) { + $val = ($mant + 1024) * (2 ** ($exp - 25)); + } else { + $val = ($mant === 0) ? INF : NAN; + } + + return ($half & 0x8000) ? -$val : $val; + } + + /** + * Returns the value of a single 32-bit float. + * + * @param int $offset + * @return float + */ + public function getFloatVal(int $offset = 0): float + { + if ($offset < 0 || ($offset + 4) > $this->dataLength) { + throw new InvalidArgumentException('ByteBuffer: Invalid offset'); + } + + return unpack('G', $this->binaryData, $offset)[1]; + } + + /** + * Returns the value of a single 64-bit float. + * + * @param int $offset + * @return float + */ + public function getDoubleVal(int $offset = 0): float + { + if ($offset < 0 || ($offset + 8) > $this->dataLength) { + throw new InvalidArgumentException('ByteBuffer: Invalid offset'); + } + return unpack('E', $this->binaryData, $offset)[1]; + } + + /** + * Transforms the ByteBuffer JSON into a generic Object. + * + * @param int $jsonFlags + * @return object + * @throws \JsonException + */ + public function toObject(int $jsonFlags = 0): object + { + return json_decode($this->binaryData, null, 512, JSON_THROW_ON_ERROR | $jsonFlags); + } + + /** + * Returns a Base64 URL representation of the byte buffer. + * + * @return string + */ + public function toBase64Url(): string + { + return static::encodeBase64Url($this->binaryData); + } + + /** + * Specify data which should be serialized to JSON. + * + * @return string + */ + public function jsonSerialize(): string + { + return $this->toBase64Url(); + } + + /** + * Returns a hexadecimal representation of the ByteBuffer. + * + * @return string + */ + public function toHex(): string + { + return bin2hex($this->binaryData); + } + + /** + * object to string + * + * @return string + */ + public function __toString(): string + { + return $this->toHex(); + } + + /** + * Convert the object to its JSON representation. + * + * @param int $options + * @return string + */ + public function toJson($options = 0): string + { + return $this->jsonSerialize(); + } + + /** + * Returns an array of data for serialization. + * + * @return array + */ + #[ArrayShape(['binaryData' => "string"])] + public function __serialize(): array + { + return ['binaryData' => static::encodeBase64Url($this->binaryData)]; + } + + /** + * Serializable-Interface + * + * @param array $data + */ + public function __unserialize(array $data): void + { + $this->binaryData = static::decodeBase64Url($data['binaryData']); + $this->dataLength = strlen($this->binaryData); + } + + /** + * Create a ByteBuffer from a BASE64 URL encoded string. + * + * @param string $base64url + * @return static + */ + public static function fromBase64Url(string $base64url): static + { + if (false === $bin = self::decodeBase64Url($base64url)) { + throw new InvalidArgumentException('ByteBuffer: Invalid base64 url string'); + } + + return new ByteBuffer($bin); + } + + /** + * Create a ByteBuffer from a BASE64 encoded string. + * + * @param string $base64 + * @return static + */ + public static function fromBase64(string $base64): static + { + if (false === $bin = base64_decode($base64)) { + throw new InvalidArgumentException('ByteBuffer: Invalid base64 string'); + } + + return new ByteBuffer($bin); + } + + /** + * Create a ByteBuffer from a hexadecimal string. + * + * @param string $hex + * @return static + */ + public static function fromHex(string $hex): static + { + if (false === $bin = hex2bin($hex)) { + throw new InvalidArgumentException('ByteBuffer: Invalid hex string'); + } + + return new static($bin); + } + + /** + * Create a random ByteBuffer + * + * @param int $length + * @return static + */ + public static function makeRandom(int $length): static + { + return new static(random_bytes($length)); + } + + /** + * Decodes a BASE64 URL string. + * + * @param string $data + * @return string|false + */ + protected static function decodeBase64Url(string $data): string|false + { + return base64_decode(strtr($data, '-_', '+/').str_repeat('=', 3 - (3 + strlen($data)) % 4)); + } + + /** + * Encodes a BASE64 URL string. + * + * @param string $data + * @return string|false + */ + protected static function encodeBase64Url(string $data): string|false + { + return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); + } +} diff --git a/src/CborDecoder.php b/src/CborDecoder.php new file mode 100644 index 0000000..972a8f4 --- /dev/null +++ b/src/CborDecoder.php @@ -0,0 +1,335 @@ +getDataLength()) { + throw new DataException('CBOR: Unused bytes after data item.'); + } + + return $result; + } + + /** + * Decodes a portion of the Byte Buffer. + * + * @param ByteBuffer|string $bufOrBin + * @param int $startOffset + * @param int|null $endOffset + * @return \Laragear\WebAuthn\ByteBuffer|array|bool|float|int|string|null + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + public static function decodePortion(ByteBuffer|string $bufOrBin, int $startOffset, ?int &$endOffset = null): ByteBuffer|array|bool|float|int|string|null + { + $buf = $bufOrBin instanceof ByteBuffer ? $bufOrBin : new ByteBuffer($bufOrBin); + + $offset = $startOffset; + $data = static::parseItem($buf, $offset); + $endOffset = $offset; + + return $data; + } + + /** + * Parses a single item of the Byte Buffer. + * + * @param ByteBuffer $buf + * @param int $offset + * @return \Laragear\WebAuthn\ByteBuffer|array|bool|float|int|string|null + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + protected static function parseItem(ByteBuffer $buf, int &$offset): ByteBuffer|array|bool|float|int|string|null + { + $first = $buf->getByteVal($offset++); + $type = $first >> 5; + $val = $first & 0b11111; + + if ($type === static::CBOR_MAJOR_FLOAT_SIMPLE) { + return static::parseFloatSimple($val, $buf, $offset); + } + + $val = static::parseExtraLength($val, $buf, $offset); + + try { + return static::parseItemData($type, $val, $buf, $offset); + } catch (InvalidArgumentException $e) { + throw new DataException($e->getMessage()); + } + } + + /** + * Parses a simple float value. + * + * @param int $val + * @param \Laragear\WebAuthn\ByteBuffer $buf + * @param int $offset + * @return bool|float|null + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + protected static function parseFloatSimple(int $val, ByteBuffer $buf, int &$offset): bool|float|null + { + switch ($val) { + case 24: + $val = $buf->getByteVal($offset); + $offset++; + return static::parseSimpleValue($val); + case 25: + $floatValue = $buf->getHalfFloatVal($offset); + $offset += 2; + return $floatValue; + case 26: + $floatValue = $buf->getFloatVal($offset); + $offset += 4; + return $floatValue; + case 27: + $floatValue = $buf->getDoubleVal($offset); + $offset += 8; + return $floatValue; + case 28: + case 29: + case 30: + throw new DataException('Reserved value used.'); + case 31: + throw new DataException('Indefinite length is not supported.'); + default: + return static::parseSimpleValue($val); + } + } + + /** + * Parses a simple value from CBOR. + * + * @param int $val + * @return bool|null + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + protected static function parseSimpleValue(int $val): ?bool + { + return match ($val) { + 20 => false, + 21 => true, + 22 => null, + default => throw new DataException(sprintf('Unsupported simple value %d.', $val)) + }; + } + + /** + * Parses the CBOR extra length. + * + * @param int $val + * @param \Laragear\WebAuthn\ByteBuffer $buf + * @param int $offset + * @return int + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + protected static function parseExtraLength(int $val, ByteBuffer $buf, int &$offset): int + { + switch ($val) { + case 24: + $val = $buf->getByteVal($offset); + $offset++; + return $val; + case 25: + $val = $buf->getUint16Val($offset); + $offset += 2; + return $val; + case 26: + $val = $buf->getUint32Val($offset); + $offset += 4; + return $val; + case 27: + $val = $buf->getUint64Val($offset); + $offset += 8; + return $val; + case 28: + case 29: + case 30: + throw new DataException('Reserved value used.'); + case 31: + throw new DataException('Indefinite length is not supported.'); + default: + return $val; + } + } + + /** + * Parses the data inside a Byte Buffer. + * + * @param int $type + * @param int $val + * @param \Laragear\WebAuthn\ByteBuffer $buf + * @param $offset + * @return \Laragear\WebAuthn\ByteBuffer|array|bool|float|int|string|null + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + protected static function parseItemData( + int $type, + int $val, + ByteBuffer $buf, + &$offset + ): ByteBuffer|array|bool|float|int|string|null { + switch ($type) { + case static::CBOR_MAJOR_UNSIGNED_INT: // uint + return $val; + + case static::CBOR_MAJOR_NEGATIVE_INT: + return -1 - $val; + + case static::CBOR_MAJOR_BYTE_STRING: + $data = $buf->getBytes($offset, $val); + $offset += $val; + return new ByteBuffer($data); // bytes + + case static::CBOR_MAJOR_TEXT_STRING: + $data = $buf->getBytes($offset, $val); + $offset += $val; + return $data; // UTF-8 + + case static::CBOR_MAJOR_ARRAY: + return static::parseArray($buf, $offset, $val); + + case static::CBOR_MAJOR_MAP: + return static::parseMap($buf, $offset, $val); + + case static::CBOR_MAJOR_TAG: + return static::parseItem($buf, $offset); // 1 embedded data item + } + + throw new DataException(sprintf('Unknown major type %d.', $type)); + } + + /** + * Parses an array with string keys. + * + * @param \Laragear\WebAuthn\ByteBuffer $buffer + * @param int $offset + * @param int $count + * @return array + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + protected static function parseMap(ByteBuffer $buffer, int &$offset, int $count): array + { + $map = []; + + for ($i = 0; $i < $count; $i++) { + $mapKey = static::parseItem($buffer, $offset); + $mapVal = static::parseItem($buffer, $offset); + + if (!is_int($mapKey) && !is_string($mapKey)) { + throw new DataException('Can only use strings or integers as map keys'); + } + + $map[$mapKey] = $mapVal; + } + + return $map; + } + + /** + * Parses an array from the byte buffer. + * + * @param \Laragear\WebAuthn\ByteBuffer $buf + * @param int $offset + * @param int $count + * @return array + * @throws \Laragear\WebAuthn\Exceptions\DataException + */ + protected static function parseArray(ByteBuffer $buf, int &$offset, int $count): array + { + $arr = []; + + for ($i = 0; $i < $count; $i++) { + $arr[] = static::parseItem($buf, $offset); + } + + return $arr; + } +} diff --git a/src/Challenge.php b/src/Challenge.php new file mode 100644 index 0000000..92e899c --- /dev/null +++ b/src/Challenge.php @@ -0,0 +1,52 @@ +timeout = Date::now()->addSeconds($this->timeout)->getTimestamp(); + } + + /** + * Check if the current challenge has expired in time and no longer valid. + * + * @return bool + */ + public function hasExpired(): bool + { + return Date::createFromTimestamp($this->timeout)->isPast(); + } + + /** + * Creates a new Challenge instance using a random ByteBuffer of the given length. + * + * @param int $length + * @param int $timeout + * @param bool $verify + * @param array $options + * @return static + */ + public static function random(int $length, int $timeout, bool $verify = true, array $options = []): static + { + return new static(ByteBuffer::makeRandom($length), $timeout, $verify, $options); + } +} diff --git a/src/ClientDataJson.php b/src/ClientDataJson.php new file mode 100644 index 0000000..e150000 --- /dev/null +++ b/src/ClientDataJson.php @@ -0,0 +1,18 @@ + "Assertion Error: $message"]); + } +} diff --git a/src/Exceptions/AttestationException.php b/src/Exceptions/AttestationException.php new file mode 100644 index 0000000..3853532 --- /dev/null +++ b/src/Exceptions/AttestationException.php @@ -0,0 +1,20 @@ + "Attestation Error: $message"]); + } +} diff --git a/src/Exceptions/DataException.php b/src/Exceptions/DataException.php new file mode 100644 index 0000000..2cb963b --- /dev/null +++ b/src/Exceptions/DataException.php @@ -0,0 +1,11 @@ + "string", 'rawId' => "string", 'response.authenticatorData' => "string", + 'response.clientDataJSON' => "string", 'response.signature' => "string", 'response.userHandle' => "string", + 'type' => "string" + ])] + public function rules(): array + { + return [ + 'id' => 'required|string', + 'rawId' => 'required|string', + 'response.authenticatorData' => 'required|string', + 'response.clientDataJSON' => 'required|string', + 'response.signature' => 'required|string', + 'response.userHandle' => 'sometimes|nullable', + 'type' => 'required|string', + ]; + } + + /** + * Check if the login request wants to remember the user as stateful. + * + * @return bool + */ + public function hasRemember(): bool + { + return $this->hasHeader('X-WebAuthn-Remember') + || $this->hasHeader('WebAuthn-Remember') + || $this->filled('remember'); + } + + /** + * Logs in the user for this assertion request. + * + * @param string|null $guard + * @return \Laragear\WebAuthn\Contracts\WebAuthnAuthenticatable&\Illuminate\Contracts\Auth\Authenticatable|null + */ + public function login(string $guard = null, bool $remember = null, bool $destroySession = false): ?WebAuthnAuthenticatable + { + $auth = Auth::guard($guard); + + if ($auth->attempt($this->validated(), $remember ?? $this->hasRemember())) { + $this->session()->regenerate($destroySession); + + return $auth->user(); + } + + return null; + } +} diff --git a/src/Http/Requests/AssertionRequest.php b/src/Http/Requests/AssertionRequest.php new file mode 100644 index 0000000..81c5256 --- /dev/null +++ b/src/Http/Requests/AssertionRequest.php @@ -0,0 +1,149 @@ +assertion ??= new AssertionCreation($this); + } + + /** + * Sets the WebAuthn-compatible guard to use. + * + * @param string $guard + * @return $this + */ + public function guard(string $guard): static + { + $this->guard = $guard; + + return $this; + } + + /** + * Makes the authenticator to only check for user presence on login. + * + * @return $this + */ + public function fastLogin(): static + { + $this->assertion()->userVerification = WebAuthn::USER_VERIFICATION_DISCOURAGED; + + return $this; + } + + /** + * Makes the authenticator to always verify the user thoroughly on login. + * + * @return $this + */ + public function secureLogin(): static + { + $this->assertion()->userVerification = WebAuthn::USER_VERIFICATION_REQUIRED; + + return $this; + } + + /** + * Creates an assertion challenge for a user if found. + * + * @param \Laragear\WebAuthn\Contracts\WebAuthnAuthenticatable|string|int|array|null $credentials + * @return \Illuminate\Contracts\Support\Responsable + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + public function toVerify(WebAuthnAuthenticatable|string|int|array|null $credentials = []): Responsable + { + $this->assertion()->user = $this->findUser($credentials); + + return $this->container + ->make(AssertionCreator::class) + ->send($this->assertion) + ->then(static function (AssertionCreation $creation): Responsable { + return $creation->json; + }); + } + + /** + * Try to find a user to create an assertion procedure. + * + * @param \Laragear\WebAuthn\Contracts\WebAuthnAuthenticatable|array|int|string|null $credentials + * @return \Laragear\WebAuthn\Contracts\WebAuthnAuthenticatable|null + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function findUser(WebAuthnAuthenticatable|array|int|string|null $credentials): ?WebAuthnAuthenticatable + { + if (!$credentials) { + return null; + } + + if ($credentials instanceof WebAuthnAuthenticatable) { + return $credentials; + } + + // If the developer is using a string or integer, we will understand its trying to + // retrieve by its ID, otherwise we will fall back to credentials. Once done, we + // will check it uses WebAuthn if is not null, otherwise we'll fail miserably. + $user = is_string($credentials) || is_int($credentials) + ? Auth::guard($this->guard)->getProvider()->retrieveById($credentials) + : Auth::guard($this->guard)->getProvider()->retrieveByCredentials($credentials); + + if ($user && ! $user instanceof WebAuthnAuthenticatable) { + $guard = $this->guard ?? $this->container->make('config')->get('auth.defaults.guard'); + + throw new InvalidArgumentException( + "The user found for the [$guard] auth guard is not an instance of [WebAuthnAuthenticatable]." + ); + } + + return $user; + } +} diff --git a/src/Http/Requests/AttestationRequest.php b/src/Http/Requests/AttestationRequest.php new file mode 100644 index 0000000..828a5d9 --- /dev/null +++ b/src/Http/Requests/AttestationRequest.php @@ -0,0 +1,120 @@ +passesAuthorization()) { + $this->failedAuthorization(); + } + } + + /** + * Determine if the user is authorized to make this request. + * + * @param \Laragear\WebAuthn\Contracts\WebAuthnAuthenticatable|null $user + * @return bool + */ + public function authorize(?WebAuthnAuthenticatable $user): bool + { + return (bool) $user; + } + + /** + * Returns the existing attestation instance. + * + * @return \Laragear\WebAuthn\Attestation\Creator\AttestationCreation + */ + protected function attestation(): AttestationCreation + { + return $this->attestation ??= new AttestationCreation($this->user(), $this); + } + + /** + * Makes the authenticator to only check for user presence on registration. + * + * @return $this + */ + public function fastRegistration(): static + { + $this->attestation()->userVerification = WebAuthn::USER_VERIFICATION_DISCOURAGED; + + return $this; + } + + /** + * Makes the authenticator to always verify the user thoroughly on registration. + * + * @return $this + */ + public function secureRegistration(): static + { + $this->attestation()->userVerification = WebAuthn::USER_VERIFICATION_REQUIRED; + + return $this; + } + + /** + * Tells the authenticator use this credential to login instantly, instead of asking for one. + * + * @return $this + */ + public function userless(): static + { + $this->attestation()->residentKey = WebAuthn::RESIDENT_KEY_REQUIRED; + + return $this; + } + + /** + * Allows the device to create multiple credentials for the same user for this app. + * + * @return $this + */ + public function allowDuplicates(): static + { + $this->attestation()->uniqueCredentials = false; + + return $this; + } + + /** + * Returns a response with the instructions to create a WebAuthn Credential. + * + * @return \Illuminate\Contracts\Support\Responsable + */ + public function toCreate(): Responsable + { + return $this->container + ->make(AttestationCreator::class) + ->send($this->attestation()) + ->then(static function (AttestationCreation $creation): Responsable { + return $creation->json; + }); + } +} diff --git a/src/Http/Requests/AttestedRequest.php b/src/Http/Requests/AttestedRequest.php new file mode 100644 index 0000000..cc814ce --- /dev/null +++ b/src/Http/Requests/AttestedRequest.php @@ -0,0 +1,89 @@ + "string", 'rawId' => "string", 'response' => "string", 'response.clientDataJSON' => "string", + 'response.attestationObject' => "string", 'type' => "string" + ])] + public function rules(): array + { + return [ + 'id' => 'required|string', + 'rawId' => 'required|string', + 'response' => 'required|array', + 'response.clientDataJSON' => 'required|string', + 'response.attestationObject' => 'required|string', + 'type' => 'required|string', + ]; + } + + /** + * Handle a passed validation attempt. + * + * @return void + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function passedValidation(): void + { + $this->credential = $this->container->make(AttestationValidator::class) + ->send(new AttestationValidation($this->user(), $this)) + ->then(static function (AttestationValidation $validation): WebAuthnCredential { + return $validation->credential; + }); + } + + /** + * Save and return the generated WebAuthn Credentials. + * + * @param array|callable $saving + * @return string + */ + public function save(array|callable $saving = []): string + { + is_callable($saving) ? $saving($this->credential) : $this->credential->forceFill($saving); + + $this->credential->save(); + + CredentialCreated::dispatch($this->user(), $this->credential); + + return $this->credential->getKey(); + } +} diff --git a/src/JsonTransport.php b/src/JsonTransport.php new file mode 100644 index 0000000..4c75881 --- /dev/null +++ b/src/JsonTransport.php @@ -0,0 +1,106 @@ +json, $key, $value); + } + + /** + * Retrieves a value from the underlying JSON array. + * + * @param string $key + * @param string|int|null $default + * @return string|int|null + */ + public function get(string $key, string|int $default = null): string|int|null + { + return Arr::get($this->json, $key, $default); + } + + /** + * Convert the object to its JSON representation. + * + * @param int $options + * @return string + */ + public function toJson($options = 0): string + { + return json_encode($this->jsonSerialize(), JSON_THROW_ON_ERROR | $options); + } + + /** + * Get the instance as an array. + * + * @return array + */ + public function toArray() + { + return $this->json; + } + + /** + * Specify data which should be serialized to JSON. + * + * @return array + */ + public function jsonSerialize(): array + { + return $this->toArray(); + } + + /** + * Returns a string representation of the object. + * + * @return string + */ + public function __toString(): string + { + return $this->toJson(); + } + + /** + * Create an HTTP response that represents the object. + * + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function toResponse($request): JsonResponse + { + return new JsonResponse($this); + } +} diff --git a/src/Models/WebAuthnCredential.php b/src/Models/WebAuthnCredential.php new file mode 100644 index 0000000..48c8f98 --- /dev/null +++ b/src/Models/WebAuthnCredential.php @@ -0,0 +1,195 @@ + + * + * @method static \Illuminate\Database\Eloquent\Builder|static query() + * @method \Illuminate\Database\Eloquent\Builder|static newQuery() + * @method static static make(array $attributes = []) + * @method static static create(array $attributes = []) + * @method static static forceCreate(array $attributes) + * @method \Laragear\WebAuthn\Models\WebAuthnCredential firstOrNew(array $attributes = [], array $values = []) + * @method \Laragear\WebAuthn\Models\WebAuthnCredential firstOrFail($columns = ['*']) + * @method \Laragear\WebAuthn\Models\WebAuthnCredential firstOrCreate(array $attributes, array $values = []) + * @method \Laragear\WebAuthn\Models\WebAuthnCredential firstOr($columns = ['*'], \Closure $callback = null) + * @method \Laragear\WebAuthn\Models\WebAuthnCredential firstWhere($column, $operator = null, $value = null, $boolean = 'and') + * @method \Laragear\WebAuthn\Models\WebAuthnCredential updateOrCreate(array $attributes, array $values = []) + * @method static|null first($columns = ['*']) + * @method static static findOrFail($id, $columns = ['*']) + * @method static static findOrNew($id, $columns = ['*']) + * @method static static|null find($id, $columns = ['*']) + * + * @property-read string $id + * + * @property-read string $user_id + * @property string|null $alias + * + * @property-read int $counter + * @property-read string $rp_id + * @property-read string $origin + * @property-read array|null $transports + * @property-read string $aaguid + * + * @property-read string $public_key + * @property-read string $attestation_format + * @property-read array $certificates + * + * @property-read \Illuminate\Support\Carbon|null $disabled_at + * + * @property-read \Laragear\WebAuthn\ByteBuffer $binary_id + * + * @property-read \Illuminate\Support\Carbon $updated_at + * @property-read \Illuminate\Support\Carbon $created_at + * + * @property-read \Laragear\WebAuthn\Contracts\WebAuthnAuthenticatable $authenticatable + * + * @method \Illuminate\Database\Eloquent\Builder|static whereEnabled() + * @method \Illuminate\Database\Eloquent\Builder|static whereDisabled() + */ +class WebAuthnCredential extends Model +{ + /** + * The table associated with the model. + * + * @var string + */ + protected $table = 'webauthn_credentials'; + + /** + * The "type" of the primary key ID. + * + * @var string + */ + protected $keyType = 'string'; + + /** + * Indicates if the IDs are auto-incrementing. + * + * @var bool + */ + public $incrementing = false; + + /** + * The attributes that should be cast. + * + * @var array + */ + protected $casts = [ + 'counter' => 'int', + 'transports' => 'array', + 'public_key' => 'encrypted', + 'certificates' => 'array', + 'disabled_at' => 'timestamp', + ]; + + /** + * The attributes that should be visible in serialization. + * + * @var array + */ + protected $visible = ['id', 'origin', 'alias', 'aaguid', 'attestation_format', 'disabled_at', 'is_enabled']; + + /** + * @return \Illuminate\Database\Eloquent\Relations\MorphTo&\Laragear\WebAuthn\Contracts\WebAuthnAuthenticatable + */ + public function authenticatable(): MorphTo + { + return $this->morphTo('authenticatable'); + } + + /** + * Filter the query by enabled credentials. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function scopeWhereEnabled(Builder $query): Builder + { + return $query->whereNull('disabled_at'); + } + /** + * Filter the query by disabled credentials. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function scopeWhereDisabled(Builder $query): Builder + { + return $query->whereNotNull('disabled_at'); + } + + /** + * Check if the credential is enabled. + * + * @return bool + */ + public function isEnabled(): bool + { + return null === $this->attributes['disabled_at']; + } + + /** + * Check if the credential is disabled. + * + * @return bool + */ + public function isDisabled(): bool + { + return !$this->isEnabled(); + } + + /** + * Enables the credential to be used with WebAuthn. + * + * @return void + */ + public function enable(): void + { + $wasDisabled = (bool) $this->attributes['disabled_at']; + + $this->attributes['disabled_at'] = null; + + $this->save(); + + if ($wasDisabled) { + CredentialEnabled::dispatch($this); + } + } + + /** + * Disables the credential for WebAuthn. + * + * @return void + */ + public function disable(): void + { + $wasEnabled = ! $this->attributes['disabled_at']; + + $this->setAttribute('disabled_at', $this->freshTimestamp())->save(); + + if ($wasEnabled) { + CredentialDisabled::dispatch($this); + } + } + + /** + * Increments the assertion counter by 1. + * + * @param int $counter + * @return void + */ + public function syncCounter(int $counter): void + { + $this->attributes['counter'] = $counter; + + $this->save(); + } +} diff --git a/src/SharedPipes/CheckChallengeSame.php b/src/SharedPipes/CheckChallengeSame.php new file mode 100644 index 0000000..ed629b2 --- /dev/null +++ b/src/SharedPipes/CheckChallengeSame.php @@ -0,0 +1,37 @@ +clientDataJson->challenge->hasNoLength()) { + static::throw($validation, "Response has an empty challenge."); + } + + if ($validation->clientDataJson->challenge->hashNotEqual($validation->challenge->data)) { + static::throw($validation, "Response challenge is not equal."); + } + + return $next($validation); + } +} diff --git a/src/SharedPipes/CheckOriginSecure.php b/src/SharedPipes/CheckOriginSecure.php new file mode 100644 index 0000000..34c3c8d --- /dev/null +++ b/src/SharedPipes/CheckOriginSecure.php @@ -0,0 +1,50 @@ +clientDataJson->origin) { + static::throw($validation, 'Response has an empty origin.'); + } + + $origin = parse_url($validation->clientDataJson->origin); + + if (!$origin || !isset($origin['host'], $origin['scheme'])) { + static::throw($validation, 'Response origin is invalid.'); + } + + if ($origin['host'] !== 'localhost' && $origin['scheme'] !== 'https') { + static::throw($validation, 'Response not made to a secure server (localhost or HTTPS).'); + } + + return $next($validation); + } +} diff --git a/src/SharedPipes/CheckRelyingPartyHashSame.php b/src/SharedPipes/CheckRelyingPartyHashSame.php new file mode 100644 index 0000000..15c38ba --- /dev/null +++ b/src/SharedPipes/CheckRelyingPartyHashSame.php @@ -0,0 +1,70 @@ +relyingPartyId($validation), PHP_URL_HOST); + + if ($this->authenticatorData($validation)->hasNotSameRPIdHash($relayingParty)) { + static::throw($validation, 'Response has different Relying Party ID hash.'); + } + + return $next($validation); + } + + /** + * Return the Attestation data to check the RP ID Hash. + * + * @param \Laragear\WebAuthn\Attestation\Validator\AttestationValidation|\Laragear\WebAuthn\Assertion\Validator\AssertionValidation $validation + * @return \Laragear\WebAuthn\Attestation\AuthenticatorData + */ + abstract protected function authenticatorData( + AttestationValidation|AssertionValidation $validation + ): AuthenticatorData; + + /** + * Return the Relying Party ID from the config or credential. + * + * @param \Laragear\WebAuthn\Assertion\Validator\AssertionValidation|\Laragear\WebAuthn\Attestation\Validator\AttestationValidation $validation + * @return string + */ + abstract protected function relyingPartyId(AssertionValidation|AttestationValidation $validation): string; +} diff --git a/src/SharedPipes/CheckRelyingPartyIdContained.php b/src/SharedPipes/CheckRelyingPartyIdContained.php new file mode 100644 index 0000000..54d1c6b --- /dev/null +++ b/src/SharedPipes/CheckRelyingPartyIdContained.php @@ -0,0 +1,57 @@ +clientDataJson->origin, PHP_URL_HOST)) { + static::throw($validation, 'Relaying Party ID is invalid.'); + } + + $current = parse_url( + $this->config->get('webauthn.relaying_party.id') ?? $this->config->get('app.url'), PHP_URL_HOST + ); + + // Check the host is the same or is a subdomain of the current config domain. + if (hash_equals($current, $host) || Str::is("*.$current", $host)) { + return $next($validation); + } + + static::throw($validation, 'Relaying Party ID not scoped to current.'); + } +} diff --git a/src/SharedPipes/CheckUserInteraction.php b/src/SharedPipes/CheckUserInteraction.php new file mode 100644 index 0000000..bf82ee4 --- /dev/null +++ b/src/SharedPipes/CheckUserInteraction.php @@ -0,0 +1,48 @@ +attestationObject->authenticatorData->wasUserAbsent() + : $validation->authenticatorData->wasUserAbsent(); + + if ($notPresent) { + static::throw($validation, 'Response did not have the user present.'); + } + + // Only verify the user if the challenge required it. + if ($validation->challenge->verify) { + $notVerified = $validation instanceof AttestationValidation + ? $validation->attestationObject->authenticatorData->wasUserNotVerified() + : $validation->authenticatorData->wasUserNotVerified(); + + if ($notVerified) { + static::throw($validation, 'Response did not verify the user.'); + } + } + + return $next($validation); + } +} diff --git a/src/SharedPipes/CompileClientDataJson.php b/src/SharedPipes/CompileClientDataJson.php new file mode 100644 index 0000000..5c29201 --- /dev/null +++ b/src/SharedPipes/CompileClientDataJson.php @@ -0,0 +1,57 @@ +request->json('response.clientDataJSON', '')), false, 32, JSON_THROW_ON_ERROR + ); + } catch (JsonException) { + static::throw($validation, 'Client Data JSON is invalid or malformed.'); + } + + if (!$object) { + static::throw($validation, 'Client Data JSON is empty.'); + } + + foreach (['type', 'origin', 'challenge'] as $key) { + if (!isset($object->{$key})) { + static::throw($validation, "Client Data JSON does not contain the [$key] key."); + } + } + + $validation->clientDataJson = new ClientDataJson( + $object->type, $object->origin, ByteBuffer::fromBase64Url($object->challenge) + ); + + return $next($validation); + } +} diff --git a/src/SharedPipes/RetrieveChallenge.php b/src/SharedPipes/RetrieveChallenge.php new file mode 100644 index 0000000..b07aeb3 --- /dev/null +++ b/src/SharedPipes/RetrieveChallenge.php @@ -0,0 +1,66 @@ +challenge = $this->retrieveChallenge($validation->request); + + if (!$validation->challenge) { + static::throw($validation, 'Challenge does not exist.'); + } + + return $next($validation); + } + + /** + * Pulls an Attestation challenge from the Cache. + * + * @param \Illuminate\Http\Request $request + * @return \Laragear\WebAuthn\Challenge|null + */ + protected function retrieveChallenge(Request $request): ?Challenge + { + /** @var \Laragear\WebAuthn\Challenge|null $challenge */ + $challenge = $request->session()->pull($this->config->get('webauthn.challenge.key')); + + if (!$challenge || $challenge->hasExpired()) { + return null; + } + + return $challenge; + } +} diff --git a/src/SharedPipes/ThrowsCeremonyException.php b/src/SharedPipes/ThrowsCeremonyException.php new file mode 100644 index 0000000..a0f42b5 --- /dev/null +++ b/src/SharedPipes/ThrowsCeremonyException.php @@ -0,0 +1,29 @@ + $webAuthnCredentials + * + * @see \Laragear\WebAuthn\Contracts\WebAuthnAuthenticatable + * @see \Laragear\WebAuthn\Models\WebAuthnCredential + */ +trait WebAuthnAuthentication +{ + /** + * Returns displayable data to be used to create WebAuthn Credentials. + * + * @return array{name: string, displayName: string} + */ + #[ArrayShape(['name' => "string", 'displayName' => "string"])] + public function webAuthnData(): array + { + return [ + 'name' => $this->email, + 'displayName' => $this->name, + ]; + } + + /** + * Removes all credentials previously registered. + * + * @param string ...$except + * @return void + */ + public function flushCredentials(string ...$except): void + { + if ($this->relationLoaded('webAuthnCredentials') && $this->webAuthnCredentials instanceof Collection) { + $partitioned = $this->webAuthnCredentials + ->partition(static function (WebAuthnCredential $credential) use ($except): bool { + return in_array($credential->getKey(), $except, true); + }); + + $partitioned->first()->each->delete(); + + $this->setRelation('webAuthnCredentials', $partitioned->last()); + + return; + } + + $this->webAuthnCredentials()->whereKeyNot($except)->delete(); + } + + /** + * Disables all credentials for the user. + * + * @param string ...$except + * @return void + */ + public function disableAllCredentials(string ...$except): void + { + if ($this->relationLoaded('webAuthnCredentials') && $this->webAuthnCredentials instanceof Collection) { + $this->webAuthnCredentials + ->each(static function (WebAuthnCredential $credential) use ($except): bool { + if ($credential->isEnabled() && in_array($credential->getKey(), $except, true)) { + $credential->disable(); + } + }); + } else { + $this->webAuthnCredentials()->whereKeyNot($except)->update(['is_enabled' => false]); + } + } + + /** + * Makes an instance of a WebAuthn Credential attached to this user. + * + * @param array $properties + * @return \Laragear\WebAuthn\Models\WebAuthnCredential + */ + public function makeWebAuthnCredential(array $properties): Models\WebAuthnCredential + { + return $this->webAuthnCredentials()->make()->forceFill($properties); + } + + /** + * Returns a queryable relationship for its WebAuthn Credentials. + * + * @return \Illuminate\Database\Eloquent\Relations\MorphMany&\Laragear\WebAuthn\Models\WebAuthnCredential + */ + public function webAuthnCredentials(): MorphMany + { + return $this->morphMany(Models\WebAuthnCredential::class, 'authenticatable'); + } +} diff --git a/src/WebAuthnServiceProvider.php b/src/WebAuthnServiceProvider.php new file mode 100644 index 0000000..4fc7984 --- /dev/null +++ b/src/WebAuthnServiceProvider.php @@ -0,0 +1,115 @@ +mergeConfigFrom(static::CONFIG, 'webauthn'); + + $this->registerUser(); + + $this->registerUserProvider(); + } + + /** + * Boot the service provider. + * + * @return void + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + public function boot(): void + { + if ($this->app->runningInConsole()) { + $this->publishesMigrations(static::MIGRATIONS); + $this->publishes([static::ROUTES => $this->app->basePath('routes/webauthn.php')], 'routes'); + $this->publishes([static::CONTROLLERS => $this->app->path('Http/Controllers/WebAuthn')], 'controllers'); + $this->publishes([static::JS => $this->app->resourcePath('js/vendor/webauthn')], 'js'); + } + } + + /** + * Publishes migrations from the given path. + * + * @param array|string $paths + * @param string $groups + * @return void + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function publishesMigrations(array|string $paths, string $groups = 'migrations'): void + { + $prefix = now()->format('Y_m_d_His'); + + $files = []; + + foreach ($this->app->make('files')->files($paths) as $file) { + $filename = preg_replace('/^[\d|_]+/', '', $file->getFilename()); + + $files[$file->getRealPath()] = $this->app->databasePath("migrations/{$prefix}_$filename"); + } + + $this->publishes($files, $groups); + } + + /** + * Registers the Web Authenticatable User. + * + * @return void + */ + protected function registerUser(): void + { + $this->app->bind( + Contracts\WebAuthnAuthenticatable::class, + static function (Application $app): ?Contracts\WebAuthnAuthenticatable { + $user = $app->make(AuthenticatableContract::class); + + return $user instanceof WebAuthnAuthenticatable ? $user : null; + } + ); + } + + /** + * Extends the Authentication Factory with a WebAuthn Eloquent-Compatible User Provider. + * + * @return void + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function registerUserProvider(): void + { + $this->callAfterResolving('auth', static function (AuthManager $auth): void { + $auth->provider( + 'eloquent-webauthn', + static function (Application $app, array $config): Auth\WebAuthnUserProvider { + return new Auth\WebAuthnUserProvider( + $app->make('hash'), + $config['model'], + $app->make(Assertion\Validator\AssertionValidator::class), + $config['password_fallback'] ?? true, + ); + } + ); + }); + } +} diff --git a/stubs/controllers/WebAuthnLoginController.php b/stubs/controllers/WebAuthnLoginController.php new file mode 100644 index 0000000..d0e9570 --- /dev/null +++ b/stubs/controllers/WebAuthnLoginController.php @@ -0,0 +1,34 @@ +toVerify($request->validate(['email' => 'sometimes|email|string'])); + } + + /** + * Log the user in. + * + * @param \Laragear\WebAuthn\Http\Requests\AssertedRequest $request + * @return \Illuminate\Http\Response + */ + public function login(AssertedRequest $request): Response + { + return response()->noContent($request->login() ? 204 : 422); + } +} diff --git a/stubs/controllers/WebAuthnRegisterController.php b/stubs/controllers/WebAuthnRegisterController.php new file mode 100644 index 0000000..d6ce459 --- /dev/null +++ b/stubs/controllers/WebAuthnRegisterController.php @@ -0,0 +1,40 @@ +fastRegistration() +// ->userless() +// ->allowDuplicates() + ->toCreate(); + } + + /** + * Registers a device for further WebAuthn authentication. + * + * @param \Laragear\WebAuthn\Http\Requests\AttestedRequest $request + * @return \Illuminate\Http\Response + */ + public function register(AttestedRequest $request): Response + { + $request->save(); + + return response()->noContent(); + } +} diff --git a/tests/Assertion/CreatorTest.php b/tests/Assertion/CreatorTest.php new file mode 100644 index 0000000..4b5fb4d --- /dev/null +++ b/tests/Assertion/CreatorTest.php @@ -0,0 +1,187 @@ +request = Request::create('https://test.app/webauthn/create', 'POST'); + $this->user = WebAuthnAuthenticatableUser::forceCreate([ + 'name' => 'test', + 'email' => 'test@email.com', + 'password' => 'test_password', + ]); + + $this->creator = new AssertionCreator($this->app); + $this->creation = new AssertionCreation($this->request); + + $this->startSession(); + $this->request->setLaravelSession($this->app->make('session.store')); + } + + protected function response(): TestResponse + { + return $this->createTestResponse( + $this->creator->send($this->creation)->thenReturn()->json->toResponse($this->request) + ); + } + + public function test_uses_config_timeout(): void + { + config(['webauthn.challenge.timeout' => 120]); + + $this->freezeSecond(); + + $this->response() + ->assertSessionHas('_webauthn', static function (Challenge $challenge): bool { + return now()->addMinutes(2)->getTimestamp() === $challenge->timeout; + }) + ->assertJson([ + 'timeout' => 120000, + 'challenge' => session('_webauthn')->data->toBase64Url(), + ]); + } + + public function test_response_defaults_without_credentials(): void + { + $this->user->webAuthnCredentials()->make()->forceFill([ + 'id' => 'test_id', + 'user_id' => Uuid::NIL, + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost:8000', + 'aaguid' => Uuid::NIL, + 'public_key' => 'test_key', + 'attestation_format' => 'none', + ]); + + $this->response() + ->assertSessionHas('_webauthn', function (Challenge $challenge): bool { + static::assertSame(now()->addMinute()->getTimestamp(), $challenge->timeout); + static::assertFalse($challenge->verify); + + return true; + }) + ->assertJson([ + 'timeout' => 60000, + 'challenge' => session('_webauthn')->data->toBase64Url(), + ]); + } + + public function test_response_doesnt_add_credentials_if_user_has_no_credentials(): void + { + $this->creation->user = $this->user; + + $this->response() + ->assertJson([ + 'timeout' => 60000, + 'challenge' => session('_webauthn')->data->toBase64Url(), + ]); + } + + public function test_response_adds_accepted_credentials_if_there_is_credentials(): void + { + $this->creation->user = $this->user; + + $this->user->webAuthnCredentials()->make()->forceFill([ + 'id' => 'test_id', + 'user_id' => Uuid::NIL, + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost:8000', + 'aaguid' => Uuid::NIL, + 'public_key' => 'test_key', + 'attestation_format' => 'none', + ])->save(); + + $this->response() + ->assertJson([ + 'timeout' => 60000, + 'challenge' => session('_webauthn')->data->toBase64Url(), + 'allowCredentials' => [ + ['id' => 'test_id', 'type' => 'public-key'] + ] + ]); + } + + public function test_response_doesnt_add_credentials_blacklisted(): void + { + $this->creation->user = $this->user; + + $this->user->webAuthnCredentials()->make()->forceFill([ + 'id' => 'test_id', + 'user_id' => Uuid::NIL, + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost:8000', + 'aaguid' => Uuid::NIL, + 'public_key' => 'test_key', + 'attestation_format' => 'none', + 'disabled_at' => now(), + ])->save(); + + $this->response() + ->assertJson([ + 'timeout' => 60000, + 'challenge' => session('_webauthn')->data->toBase64Url(), + ]); + } + + public function test_forces_user_verification(): void + { + $this->creation->userVerification = WebAuthn::USER_VERIFICATION_REQUIRED; + + $this->response() + ->assertSessionHas('_webauthn', function (Challenge $challenge): bool { + return $challenge->verify; + }) + ->assertJson([ + 'timeout' => 60000, + 'challenge' => session('_webauthn')->data->toBase64Url(), + 'userVerification' => WebAuthn::USER_VERIFICATION_REQUIRED, + ]); + } + + public function test_challenge_includes_accepted_credentials(): void + { + $this->creation->user = $this->user; + + $this->user->webAuthnCredentials()->make()->forceFill([ + 'id' => 'test_id', + 'user_id' => Uuid::NIL, + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost:8000', + 'aaguid' => Uuid::NIL, + 'public_key' => 'test_key', + 'attestation_format' => 'none', + ])->save(); + + $this->response() + ->assertSessionHas('_webauthn', function (Challenge $challenge): bool { + return in_array('test_id', $challenge->properties['credentials'], true); + }); + } +} diff --git a/tests/Assertion/ValidationTest.php b/tests/Assertion/ValidationTest.php new file mode 100644 index 0000000..39b86ac --- /dev/null +++ b/tests/Assertion/ValidationTest.php @@ -0,0 +1,623 @@ +request = Request::create( + 'https://test.app/webauthn/create', 'POST', content: json_encode(FakeAuthenticator::assertionResponse()) + ); + + $this->user = WebAuthnAuthenticatableUser::forceCreate([ + 'name' => FakeAuthenticator::ATTESTATION_USER['displayName'], + 'email' => FakeAuthenticator::ATTESTATION_USER['name'], + 'password' => 'test_password', + ]); + + $this->validator = new AssertionValidator($this->app); + $this->validation = new AssertionValidation($this->request); + + $this->freezeSecond(); + + $this->challenge = new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ASSERTION_CHALLENGE)), 60, false, + ); + + $this->session(['_webauthn' => $this->challenge]); + + $this->request->setLaravelSession($this->app->make('session.store')); + + $this->credential = DB::table('webauthn_credentials')->insert([ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'authenticatable_type' => WebAuthnAuthenticatableUser::class, + 'authenticatable_id' => 1, + 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07', + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost', + 'aaguid' => Uuid::NIL, + 'attestation_format' => 'none', + 'public_key' => 'eyJpdiI6Imp0U0NVeFNNbW45KzEvMXpad2p2SUE9PSIsInZhbHVlIjoic0VxZ2I1WnlHM2lJakhkWHVkK2kzMWtibk1IN2ZlaExGT01qOElXMDdRTjhnVlR0TDgwOHk1S0xQUy9BQ1JCWHRLNzRtenNsMml1dVQydWtERjFEU0h0bkJGT2RwUXE1M1JCcVpablE2Y2VGV2YvVEE2RGFIRUE5L0x1K0JIQXhLVE1aNVNmN3AxeHdjRUo2V0hwREZSRTJYaThNNnB1VnozMlVXZEVPajhBL3d3ODlkTVN3bW54RTEwSG0ybzRQZFFNNEFrVytUYThub2IvMFRtUlBZamoyZElWKzR1bStZQ1IwU3FXbkYvSm1FU2FlMTFXYUo0SG9kc1BDME9CNUNKeE9IelE5d2dmNFNJRXBKNUdlVzJ3VHUrQWJZRFluK0hib0xvVTdWQ0ZISjZmOWF3by83aVJES1dxbU9Zd1lhRTlLVmhZSUdlWmlBOUFtcTM2ZVBaRWNKNEFSQUhENk5EaC9hN3REdnVFbm16WkRxekRWOXd4cVcvZFdKa2tlWWJqZWlmZnZLS0F1VEVCZEZQcXJkTExiNWRyQmxsZWtaSDRlT3VVS0ZBSXFBRG1JMjRUMnBKRXZxOUFUa2xxMjg2TEplUzdscVo2UytoVU5SdXk1OE1lcFN6aU05ZkVXTkdIM2tKM3Q5bmx1TGtYb1F5bGxxQVR3K3BVUVlia1VybDFKRm9lZDViNzYraGJRdmtUb2FNTEVGZmZYZ3lYRDRiOUVjRnJpcTVvWVExOHJHSTJpMnVBZ3E0TmljbUlKUUtXY2lSWDh1dE5MVDNRUzVRSkQrTjVJUU8rSGhpeFhRRjJvSEdQYjBoVT0iLCJtYWMiOiI5MTdmNWRkZGE5OTEwNzQ3MjhkYWVhYjRlNjk0MWZlMmI5OTQ4YzlmZWI1M2I4OGVkMjE1MjMxNjUwOWRmZTU2IiwidGFnIjoiIn0=', + 'updated_at' => now(), + 'created_at' => now(), + ]); + } + + protected function validate(): AssertionValidation + { + return $this->validator->send($this->validation)->thenReturn(); + } + + public function test_assertion_allows_user_instance(): void + { + $this->validation->user = WebAuthnAuthenticatableUser::query()->first(); + + static::assertInstanceOf(AssertionValidation::class, $this->validator->send($this->validation)->thenReturn()); + } + + public function test_assertion_allows_user_instance_without_user_handle(): void + { + $this->validation->user = WebAuthnAuthenticatableUser::query()->first(); + + $response = FakeAuthenticator::assertionResponse(); + + unset($response['response']['userHandle']); + + $this->request->setJson(new ParameterBag($response)); + + static::assertInstanceOf(AssertionValidation::class, $this->validator->send($this->validation)->thenReturn()); + } + + public function test_assertion_increases_counter(): void + { + static::assertInstanceOf(AssertionValidation::class, $this->validator->send($this->validation)->thenReturn()); + + $this->assertDatabaseHas(WebAuthnCredential::class, [ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'counter' => 1, + ]); + } + + public function test_assertion_credential_without_zero_counter_is_valid_and_not_incremented(): void + { + $this->app->resolving(CheckPublicKeyCounterCorrect::class, function (): void { + $this->validation->authenticatorData->counter = 0; + }); + + $this->validate(); + + $this->assertDatabaseHas(WebAuthnCredential::class, [ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'counter' => 0, + ]); + } + + public function test_challenge_fails_if_not_found(): void + { + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Challenge does not exist.'); + + $this->session(['_webauthn' => null]); + + $this->validate(); + } + + public function test_fails_if_challenge_exists_but_is_expired(): void + { + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Challenge does not exist.'); + + $this->travelTo(now()->addMinute()->addSecond()); + + $this->validate(); + } + + public function test_challenge_is_pulled_from_session(): void + { + $this->validate(); + + static::assertNull(session('_webauthn')); + } + + public function test_credential_id_check_fail_if_not_in_request_array(): void + { + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Credential is not on accepted list.'); + + $this->challenge->properties['credentials'] = ['4bde1e58dba94de4ab307f46611165cb']; + + $this->validate(); + } + + public function test_credential_id_check_fails_if_doesnt_exist(): void + { + DB::table('webauthn_credentials')->where('id', FakeAuthenticator::CREDENTIAL_ID)->delete(); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Credential ID does not exist.'); + + $this->validate(); + } + + public function test_credential_id_check_fails_if_disabled(): void + { + DB::table('webauthn_credentials')->where('id', FakeAuthenticator::CREDENTIAL_ID)->update([ + 'disabled_at' => now(), + ]); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Credential ID is blacklisted.'); + + $this->validate(); + } + + public function test_credential_check_if_not_for_user_id(): void + { + DB::table('webauthn_credentials')->where('id', FakeAuthenticator::CREDENTIAL_ID)->update([ + 'user_id' => '4bde1e58dba94de4ab307f46611165cb', + ]); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: User ID is not owner of the stored credential.'); + + $this->validate(); + } + + public function test_credential_check_fails_if_not_for_user_instance(): void + { + $this->user->setAttribute('id', 2)->save(); + + $this->validation->user = $this->user; + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: User is not owner of the stored credential.'); + + $this->validate(); + } + + public function test_type_check_fails_if_not_public_key(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['type'] = 'invalid'; + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Response type is not [public-key].'); + + $this->validate(); + } + + public function test_authenticator_data_fails_if_empty(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['authenticatorData'] = ''; + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Authenticator Data does not exist or is empty.'); + + $this->validate(); + } + + public function test_authenticator_data_fails_if_invalid(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['authenticatorData'] = 'invalid'; + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Authenticator Data: Invalid input.'); + + $this->validate(); + } + + public function test_compiling_client_data_json_fails_if_invalid(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['clientDataJSON'] = 'foo'; + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Client Data JSON is invalid or malformed.'); + + $this->validate(); + } + + public function test_compiling_client_data_json_fails_if_empty(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode(json_encode([])); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Client Data JSON is empty.'); + + $this->validate(); + } + + public function test_compiling_client_data_json_fails_if_type_missing(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode(json_encode(['origin' => '', 'challenge' => ''])); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Client Data JSON does not contain the [type] key.'); + + $this->validate(); + } + + public function test_compiling_client_data_json_fails_if_origin_missing(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode(json_encode(['type' => '', 'challenge' => ''])); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Client Data JSON does not contain the [origin] key.'); + + $this->validate(); + } + + public function test_compiling_client_data_json_fails_if_challenge_missing(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode(json_encode(['type' => '', 'origin' => ''])); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Client Data JSON does not contain the [challenge] key.'); + + $this->validate(); + } + + public function test_action_checks_fails_if_not_webauthn_create(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode(['type' => 'invalid', 'origin' => '', 'challenge' => '']) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Client Data type is not [webauthn.get].'); + + $this->validate(); + } + + public function test_check_challenge_fails_if_challenge_is_empty(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode(['type' => 'webauthn.get', 'origin' => 'https://localhost', 'challenge' => '']) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Response has an empty challenge.'); + + $this->validate(); + } + + public function test_check_challenge_fails_if_challenge_is_not_equal(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode(['type' => 'webauthn.get', 'origin' => 'https://localhost', 'challenge' => 'invalid']) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Response challenge is not equal.'); + + $this->validate(); + } + + public function test_check_origin_fails_if_empty(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode(['type' => 'webauthn.get', 'origin' => '', 'challenge' => FakeAuthenticator::ASSERTION_CHALLENGE]) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Response has an empty origin.'); + + $this->validate(); + } + + public function test_check_origin_fails_if_invalid_host(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode(['type' => 'webauthn.get', 'origin' => 'invalid', 'challenge' => FakeAuthenticator::ASSERTION_CHALLENGE]) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Response origin is invalid.'); + + $this->validate(); + } + + public function test_check_origin_fails_if_unsecure(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + /** @noinspection HttpUrlsUsage */ + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode(['type' => 'webauthn.get', 'origin' => 'http://unsecure.com', 'challenge' => FakeAuthenticator::ASSERTION_CHALLENGE]) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Response not made to a secure server (localhost or HTTPS).'); + + $this->validate(); + } + + public function test_rp_id_fails_if_empty(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode([ + 'type' => 'webauthn.get', + 'origin' => '', + 'challenge' => FakeAuthenticator::ASSERTION_CHALLENGE + ]) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Response has an empty origin.'); + + $this->validate(); + } + + public function test_rp_id_fails_if_not_equal(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode([ + 'type' => 'webauthn.get', + 'origin' => 'https://otherhost.com', + 'challenge' => FakeAuthenticator::ASSERTION_CHALLENGE + ]) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Relaying Party ID not scoped to current.'); + + $this->validate(); + } + + public function test_rp_id_fails_if_not_contained(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode([ + 'type' => 'webauthn.get', + 'origin' => 'https://invalidlocalhost', + 'challenge' => FakeAuthenticator::ASSERTION_CHALLENGE + ]) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Relaying Party ID not scoped to current.'); + + $this->validate(); + } + + public function test_rp_id_fails_if_hash_not_same(): void + { + DB::table('webauthn_credentials')->where('id', FakeAuthenticator::CREDENTIAL_ID)->update([ + 'rp_id' => 'https://otherorigin.com', + ]); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Response has different Relying Party ID hash.'); + + $this->validate(); + } + + public function test_check_user_interaction_fails_if_user_not_present(): void + { + $this->app->resolving(CheckUserInteraction::class, function (): void { + $this->validation->authenticatorData = Mockery::mock(AuthenticatorData::class); + + $this->validation->authenticatorData->expects('wasUserAbsent')->andReturnTrue(); + }); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Response did not have the user present.'); + + $this->validate(); + } + + public function test_check_user_interaction_fails_if_user_verification_was_required(): void + { + $this->challenge->verify = true; + + $this->app->resolving(CheckUserInteraction::class, function (): void { + $this->validation->authenticatorData = Mockery::mock(AuthenticatorData::class); + + $this->validation->authenticatorData->expects('wasUserAbsent')->andReturnFalse(); + $this->validation->authenticatorData->expects('wasUserNotVerified')->andReturnTrue(); + }); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Response did not verify the user.'); + + $this->validate(); + } + + public function test_signature_fails_if_credential_public_key_invalid(): void + { + DB::table('webauthn_credentials')->where('id', FakeAuthenticator::CREDENTIAL_ID)->update([ + 'public_key' => Crypt::encryptString('invalid') + ]); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Stored Public Key is invalid.'); + + $this->validate(); + } + + public function test_signature_fails_if_response_signature_empty(): void + { + $invalid = FakeAuthenticator::assertionResponse(); + + $invalid['response']['signature'] = base64_encode(''); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Signature is empty.'); + + $this->validate(); + } + + public function test_signature_fails_if_invalid(): void + { + DB::table('webauthn_credentials')->where('id', FakeAuthenticator::CREDENTIAL_ID)->update([ + 'public_key' => Crypt::encryptString("-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnBadZo+CnNdUHvzCWuLN +TFsXTCjsHH5A+aUtIImsJsbTKmYsYtOuiOwEgcGglKEJV0MwzV4v2SDQzSirwLEr +isis4qV6Q3a0ZyZcYhgyMzvkk5CtDhpzxhsmFwiMSGt9gVRE8cOxGDQX2jTPfqyk +xZTkoXKEHevq8kl5PBCPsaWskrWsySw9mmqNCmIjhE2Evgarm0Xq7yq5h62H2ZzF +T3U5C0H32I9cTPk6f/SVke+GMseVRiLleltJMNl0CAcKGBmJpQfeLFlKmOc15Wql +wuMegjGULD9dPQvZS5uX+P0bHYfXq5V/HTwrR9FmkEdhq5YB9nE6RkE6Fbs5f+LI +hQIDAQAB +-----END PUBLIC KEY-----") + ]); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Signature is invalid.'); + + $this->validate(); + } + + public function test_counter_fails_if_authenticator_counts_same_as_stored_counter(): void + { + $event = Event::fake([CredentialCloned::class, CredentialDisabled::class]); + + DB::table('webauthn_credentials')->where('id', FakeAuthenticator::CREDENTIAL_ID)->update([ + 'counter' => 1 + ]); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Credential counter not over stored counter.'); + + try { + $this->validate(); + } catch (Throwable $e) { + $event->assertDispatched(CredentialCloned::class); + $event->assertDispatched(CredentialDisabled::class); + $this->assertDatabaseHas(WebAuthnCredential::class, [ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'disabled_at' => now()->toDateTimeString(), + ]); + + throw $e; + } + } + + public function test_counter_fails_if_authenticator_counts_below_as_stored_counter(): void + { + $event = Event::fake([CredentialCloned::class, CredentialDisabled::class]); + + DB::table('webauthn_credentials')->where('id', FakeAuthenticator::CREDENTIAL_ID)->update([ + 'counter' => 2 + ]); + + $this->expectException(AssertionException::class); + $this->expectExceptionMessage('Assertion Error: Credential counter not over stored counter.'); + + try { + $this->validate(); + } catch (Throwable $e) { + $event->assertDispatched(CredentialCloned::class); + $event->assertDispatched(CredentialDisabled::class); + $this->assertDatabaseHas(WebAuthnCredential::class, [ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'disabled_at' => now()->toDateTimeString(), + ]); + + throw $e; + } + } +} diff --git a/tests/Attestation/CreatorTest.php b/tests/Attestation/CreatorTest.php new file mode 100644 index 0000000..9ef1190 --- /dev/null +++ b/tests/Attestation/CreatorTest.php @@ -0,0 +1,191 @@ +request = Request::create('https://test.app/webauthn/create', 'POST'); + $this->user = WebAuthnAuthenticatableUser::forceCreate([ + 'name' => 'test', + 'email' => 'test@email.com', + 'password' => 'test_password', + ]); + + $this->creator = new AttestationCreator($this->app); + $this->creation = new AttestationCreation($this->user, $this->request); + + $this->startSession(); + $this->request->setLaravelSession($this->app->make('session.store')); + } + + protected function response(): TestResponse + { + return $this->createTestResponse( + $this->creator->send($this->creation)->thenReturn()->json->toResponse($this->request) + ); + } + + public function test_base_structure(): void + { + $this->freezeSecond(); + + $this->response() + ->assertSessionHas('_webauthn', function (Challenge $challenge): bool { + static::assertSame(now()->addMinute()->getTimestamp(), $challenge->timeout); + static::assertTrue(Uuid::isValid(Uuid::fromString($challenge->properties['user_uuid']))); + static::assertSame('test@email.com', $challenge->properties['user_handle']); + static::assertFalse($challenge->verify); + + return true; + }) + ->assertJson([ + 'rp' => [ + 'name' => 'Laravel' + ], + 'user' => [ + 'name' => 'test@email.com', + 'displayName' => 'test', + 'id' => session('_webauthn')->properties['user_uuid'], + ], + 'pubKeyCredParams' => [ + ['type' => 'public-key', 'alg' => -7], + ['type' => 'public-key', 'alg' => -257], + ], + 'attestation' => 'none', + 'timeout' => 60000, + 'challenge' => session('_webauthn')->data->toBase64Url(), + ]); + } + + public function test_uses_relaying_party_config(): void + { + config(['webauthn.relying_party' => [ + 'id' => 'https://foo.bar', + 'name' => 'foo', + ]]); + + $this->response()->assertJsonFragment([ + 'rp' => [ + 'id' => 'https://foo.bar', + 'name' => 'foo', + ], + ]); + } + + public function test_asks_for_user_verification(): void + { + $this->creation->userVerification = WebAuthn::USER_VERIFICATION_REQUIRED; + + $this->response() + ->assertSessionHas('_webauthn', static function (Challenge $challenge): bool { + return $challenge->verify; + }) + ->assertJsonFragment([ + 'authenticatorSelection' => [ + 'userVerification' => 'required' + ] + ]); + } + + public function test_asks_for_user_presence(): void + { + $this->creation->userVerification = WebAuthn::USER_VERIFICATION_DISCOURAGED; + + $this->response() + ->assertSessionHas('_webauthn', static function (Challenge $challenge): bool { + return ! $challenge->verify; + }) + ->assertJsonFragment([ + 'authenticatorSelection' => [ + 'userVerification' => 'discouraged' + ] + ]); + } + + public function test_asks_for_resident_key(): void + { + $this->creation->residentKey = WebAuthn::RESIDENT_KEY_REQUIRED; + + $this->response() + ->assertSessionHas('_webauthn', static function (Challenge $challenge): bool { + return $challenge->verify; + }) + ->assertJsonFragment([ + 'authenticatorSelection' => [ + 'residentKey' => 'required', + 'requireResidentKey' => true, + 'userVerification' => 'required' + ], + ]); + } + + public function test_user_reuses_uuid_from_other_credential(): void + { + $this->user->webAuthnCredentials()->make()->forceFill([ + 'id' => 'test_id', + 'user_id' => $uuid = Str::uuid(), + 'rp_id' => 'test', + 'origin' => 'test', + 'public_key' => 'test', + ])->save(); + + $this->response() + ->assertJsonPath('user.id', $uuid->toString()); + } + + public function test_adds_existing_credentials_if_unique_by_default(): void + { + $this->user->webAuthnCredentials()->make()->forceFill([ + 'id' => 'test_id', + 'user_id' => Str::uuid(), + 'rp_id' => 'test', + 'origin' => 'test', + 'public_key' => 'test', + ])->save(); + + $this->response() + ->assertJsonFragment([ + 'excludeCredentials' => [ + ['id'=> 'test_id', 'type' => 'public-key',] + ] + ]); + } + + public function test_doesnt_adds_credentials_if_allows_duplicates(): void + { + $this->creation->uniqueCredentials = false; + + $this->user->webAuthnCredentials()->make()->forceFill([ + 'id' => 'test_id', + 'user_id' => Str::uuid(), + 'rp_id' => 'test', + 'origin' => 'test', + 'public_key' => 'test', + ])->save(); + + $this->response()->assertJsonMissingPath('excludeCredentials'); + } +} diff --git a/tests/Attestation/ValidationTest.php b/tests/Attestation/ValidationTest.php new file mode 100644 index 0000000..d9d408e --- /dev/null +++ b/tests/Attestation/ValidationTest.php @@ -0,0 +1,621 @@ +request = Request::create( + 'https://test.app/webauthn/create', 'POST', content: json_encode(FakeAuthenticator::attestationResponse()) + ); + + $this->user = WebAuthnAuthenticatableUser::forceCreate([ + 'name' => FakeAuthenticator::ATTESTATION_USER['displayName'], + 'email' => FakeAuthenticator::ATTESTATION_USER['name'], + 'password' => 'test_password', + ]); + + $this->validator = new AttestationValidator($this->app); + $this->validation = new AttestationValidation($this->user, $this->request); + + $this->freezeSecond(); + + $this->challenge = new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ATTESTATION_CHALLENGE)), + 60, + false, + ['user_uuid' => FakeAuthenticator::ATTESTATION_USER['id']] + ); + + $this->session(['_webauthn' => $this->challenge]); + + $this->request->setLaravelSession($this->app->make('session.store')); + } + + protected function validate(): AttestationValidation + { + return $this->validator->send($this->validation)->thenReturn(); + } + + public function test_validates_attestation_and_instances_webauthn_credential(): void + { + $validation = $this->validator->send($this->validation)->thenReturn(); + + static::assertInstanceOf(AttestationValidation::class, $validation); + + static::assertFalse($validation->credential->exists); + + $validation->credential->save(); + + $this->assertModelExists($validation->credential); + + $this->assertDatabaseHas(WebAuthnCredential::class, [ + 'id' => $validation->credential->id, + 'authenticatable_type' => WebAuthnAuthenticatableUser::class, + 'authenticatable_id' => 1, + 'user_id' => $validation->credential->user_id, + 'alias' => null, + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost', + 'transports' => null, + 'aaguid' => Uuid::NIL, + 'attestation_format' => 'none', + 'certificates' => null, + 'disabled_at' => null, + ]); + + $key = DB::table('webauthn_credentials')->value('public_key'); + + static::assertSame($validation->credential->public_key, Crypt::decryptString($key)); + } + + public function test_validates_attestation_for_scoped_origin(): void + { + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode([ + 'type' => 'webauthn.create', + 'origin' => 'https://scoped.localhost', + 'challenge' => $this->challenge->data->toBase64Url() + ]) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + static::assertInstanceOf(AttestationValidation::class, $this->validator->send($this->validation)->thenReturn()); + } + + public function test_fails_if_challenge_does_not_exists(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Challenge does not exist.'); + + $this->session(['_webauthn' => null]); + + $this->validate(); + } + + public function test_fails_if_challenge_exists_but_is_expired(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Challenge does not exist.'); + + $this->travelTo(now()->addMinute()->addSecond()); + + $this->validate(); + } + + public function test_challenge_is_pulled_from_session(): void + { + $this->validate(); + + static::assertNull(session('_webauthn')); + } + + public function test_compiling_client_data_json_fails_if_invalid(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Client Data JSON is invalid or malformed.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = 'foo'; + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_client_data_json_fails_if_empty(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Client Data JSON is empty.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode(json_encode([])); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_client_data_json_fails_if_type_missing(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Client Data JSON does not contain the [type] key.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode(json_encode(['origin' => '', 'challenge' => ''])); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_client_data_json_fails_if_origin_missing(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Client Data JSON does not contain the [origin] key.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode(json_encode(['type' => '', 'challenge' => ''])); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_client_data_json_fails_if_challenge_missing(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Client Data JSON does not contain the [challenge] key.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode(json_encode(['type' => '', 'origin' => ''])); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_attestation_object_fails_if_invalid(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: CBOR Object is anything but an array.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['attestationObject'] = base64_encode(hex2bin('1A499602D2')); // 1234567890 in CBOR + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_attestation_object_fails_if_fmt_missing(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Format is missing or invalid.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['attestationObject'] = base64_encode(hex2bin('A26761747453746D746068617574684461746160')); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_attestation_object_fails_if_fmt_not_string(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Format is missing or invalid.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['attestationObject'] = base64_encode( + hex2bin('A363666D74016761747453746D746068617574684461746160') + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_attestation_object_fails_if_attStmt_missing(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Statement is missing or invalid.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['attestationObject'] = base64_encode( + hex2bin('A263666D74647465737468617574684461746160') + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_attestation_object_fails_if_attStmt_not_array(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Statement is missing or invalid.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['attestationObject'] = base64_encode( + hex2bin('A363666D746474657374686175746844617461606761747453746D7400') + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_attestation_object_fails_if_authData_missing(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Authenticator Data is missing or invalid.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['attestationObject'] = base64_encode( + hex2bin('A263666D7464746573746761747453746D7480') + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_attestation_object_fails_if_authData_not_byte_buffer(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Authenticator Data is missing or invalid.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['attestationObject'] = base64_encode( + hex2bin('A363666D7464746573746761747453746D7481006861757468446174611A001E8480') + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_attestation_object_fails_if_fmt_not_none(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Format name [invalid] is invalid.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['attestationObject'] = base64_encode( + hex2bin('A363666D7467696E76616C69646761747453746D74A068617574684461746159016749960DE5880E8C687434170F6476605B8FE4AEB9A28632C7995CF3BA831D97634500000000000000000000000000000000000000000020ECFE96F4E099C876F2EA374218CAF33001E97DFDF8FC7F657257FC2E0BC9AF9DA401030339010020590100C3BD9A5E8971F49A2A88A6A161441E61A514BD63E77C1BE40AAAC08D3DFE4070FC37A0B739954A5150AA88A35E562E962B6D77B8EFACBACD90D2C6F93C3C5CBFD0194FA370713C673B1E0B3CEAC4A94B95C5D41EF0E0078309E0CAF6E3F1D10EF8418B4761842AC61F2B7C9F99595076C7BEEFE41E786BC9C013663054A0B3D3F0BE4FEA906696317BE1E2BD2FF299D6FA430E1A762AF69D0F0BC4CAF2FD16AB6EFA685055933FDE65E2C2232C344BE80EEB309975CBE55772887E7ADBFC38E9F68860DB11B466663FCF40C1F7529E274D6687EB237D41B62838540528CE6943664464ADA55B0F510782D5837AF07780BB7A675EF1D3FA29F39D1B472A7B80852143010001') + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_authenticator_data_fails_if_invalid_binary(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Authenticator Data: Invalid input.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['attestationObject'] = base64_encode( + hex2bin('A363666D74646E6F6E656761747453746D74A06861757468446174614849960DE5880E8C6D') + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_compiling_authenticator_data_fails_if_invalid_length(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: ByteBuffer: Invalid offset or length.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['attestationObject'] = base64_encode( + hex2bin('A363666D74646E6F6E656761747453746D74A068617574684461746159016649960DE5880E8C687434170F6476605B8FE4AEB9A28632C7995CF3BA831D97634500000000000000000000000000000000000000000020ECFE96F4E099C876F2EA374218CAF33001E97DFDF8FC7F657257FC2E0BC9AF9DA401030339010020590100C3BD9A5E8971F49A2A88A6A161441E61A514BD63E77C1BE40AAAC08D3DFE4070FC37A0B739954A5150AA88A35E562E962B6D77B8EFACBACD90D2C6F93C3C5CBFD0194FA370713C673B1E0B3CEAC4A94B95C5D41EF0E0078309E0CAF6E3F1D10EF8418B4761842AC61F2B7C9F99595076C7BEEFE41E786BC9C013663054A0B3D3F0BE4FEA906696317BE1E2BD2FF299D6FA430E1A762AF69D0F0BC4CAF2FD16AB6EFA685055933FDE65E2C2232C344BE80EEB309975CBE55772887E7ADBFC38E9F68860DB11B466663FCF40C1F7529E274D6687EB237D41B62838540528CE6943664464ADA55B0F510782D5837AF07780BB7A675EF1D3FA29F39D1B472A7B808521430100') + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_action_checks_fails_if_not_webauthn_create(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Response is not for creating WebAuthn Credentials.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode(['type' => 'invalid', 'origin' => '', 'challenge' => '']) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_check_challenge_fails_if_challenge_is_empty(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Response has an empty challenge.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode(['type' => 'webauthn.create', 'origin' => '', 'challenge' => '']) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_check_challenge_fails_if_challenge_is_not_equal(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Response challenge is not equal.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode(['type' => 'webauthn.create', 'origin' => '', 'challenge' => 'invalid']) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_check_origin_fails_if_empty(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Response has an empty origin.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode(['type' => 'webauthn.create', 'origin' => '', 'challenge' => FakeAuthenticator::ATTESTATION_CHALLENGE]) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_check_origin_fails_if_invalid_host(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Response origin is invalid.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode(['type' => 'webauthn.create', 'origin' => 'invalid', 'challenge' => FakeAuthenticator::ATTESTATION_CHALLENGE]) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_check_origin_fails_if_unsecure(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Response not made to a secure server (localhost or HTTPS).'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode(['type' => 'webauthn.create', 'origin' => 'http://unsecure.com', 'challenge' => FakeAuthenticator::ATTESTATION_CHALLENGE]) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_rp_id_fails_if_empty(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Response has an empty origin.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode([ + 'type' => 'webauthn.create', + 'origin' => '', + 'challenge' => FakeAuthenticator::ATTESTATION_CHALLENGE + ]) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_rp_id_fails_if_not_equal(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Relaying Party ID not scoped to current.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode([ + 'type' => 'webauthn.create', + 'origin' => 'https://otherhost.com', + 'challenge' => FakeAuthenticator::ATTESTATION_CHALLENGE + ]) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_rp_id_fails_if_not_contained(): void + { + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Relaying Party ID not scoped to current.'); + + $invalid = FakeAuthenticator::attestationResponse(); + + $invalid['response']['clientDataJSON'] = base64_encode( + json_encode([ + 'type' => 'webauthn.create', + 'origin' => 'https://invalidlocalhost', + 'challenge' => FakeAuthenticator::ATTESTATION_CHALLENGE + ]) + ); + + $this->request->setJson(new ParameterBag($invalid)); + + $this->validate(); + } + + public function test_rp_id_fails_if_hash_not_same(): void + { + $this->app->when(CheckRelyingPartyHashSame::class) + ->needs(ConfigContract::class) + ->give(static function (): Repository { + return tap(new Repository())->set('webauthn.relaying_party.id', 'https://otherhost.com'); + }); + + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Response has different Relying Party ID hash.'); + + $this->validate(); + } + + public function test_check_user_interaction_fails_if_user_not_present(): void + { + $this->app->resolving(CheckUserInteraction::class, function (): void { + $this->validation->attestationObject = new AttestationObject( + $auth = Mockery::mock(AuthenticatorData::class), + new None([], $auth), + 'none', + ); + + $auth->expects('wasUserAbsent')->andReturnTrue(); + }); + + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Response did not have the user present.'); + + $this->validate(); + } + + public function test_check_user_interaction_fails_if_user_verification_was_required(): void + { + $this->challenge->verify = true; + + $this->app->resolving(CheckUserInteraction::class, function (): void { + $this->validation->attestationObject = new AttestationObject( + $auth = Mockery::mock(AuthenticatorData::class), + new None([], $auth), + 'none', + ); + + $auth->expects('wasUserAbsent')->andReturnFalse(); + $auth->expects('wasUserNotVerified')->andReturnTrue(); + }); + + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Response did not verify the user.'); + + $this->validate(); + } + + public function test_credential_duplicate_check_fails_if_already_exists(): void + { + $this->app->resolving(CredentialIdShouldNotBeDuplicated::class, static function (): void { + DB::table('webauthn_credentials')->insert([ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'authenticatable_type' => WebAuthnAuthenticatableUser::class, + 'authenticatable_id' => 1, + 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07', + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost', + 'aaguid' => Uuid::NIL, + 'attestation_format' => 'none', + 'public_key' => 'test_key', + 'updated_at' => now(), + 'created_at' => now(), + ]); + }); + + $this->expectException(AttestationException::class); + $this->expectExceptionMessage('Attestation Error: Credential ID already exists in the database.'); + + $this->validate(); + } +} diff --git a/tests/Auth/EloquentWebAuthnProviderTest.php b/tests/Auth/EloquentWebAuthnProviderTest.php new file mode 100644 index 0000000..06b49e5 --- /dev/null +++ b/tests/Auth/EloquentWebAuthnProviderTest.php @@ -0,0 +1,148 @@ +make('config')->set('auth.providers.users.driver', 'eloquent-webauthn'); + $app->make('config')->set('auth.providers.users.model', WebAuthnAuthenticatableUser::class); + } + + protected function afterRefreshingDatabase(): void + { + WebAuthnAuthenticatableUser::forceCreate([ + 'name' => FakeAuthenticator::ATTESTATION_USER['displayName'], + 'email' => FakeAuthenticator::ATTESTATION_USER['name'], + 'password' => '$2y$10$c/yQW6o.mEiCfys7enU29.4ETjmg/jdw.4puMTWbceEFGijejPkSW', // password + ]); + + WebAuthnCredential::forceCreate([ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'authenticatable_type' => WebAuthnAuthenticatableUser::class, + 'authenticatable_id' => 1, + 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07', + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost', + 'aaguid' => Uuid::NIL, + 'attestation_format' => 'none', + 'public_key' => 'test_key', + ]); + } + + public function test_retrieves_user_using_webauthn(): void + { + $provider = Auth::createUserProvider('users'); + + $retrieved = $provider->retrieveByCredentials([ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'rawId' => 'raw', + 'response' => ['something'], + 'type' => 'public-key', + ]); + + static::assertTrue(WebAuthnAuthenticatableUser::query()->first()->is($retrieved)); + + $retrieved = $provider->retrieveByCredentials([ + 'id' => '27EdS6eTDHCTa9Y73G9gY1b81yVJuuiu1TTyorFicBf', + 'rawId' => 'raw', + 'response' => ['something'], + 'type' => 'public-key', + ]); + + static::assertNull($retrieved); + } + + public function test_retrieves_user_using_credentials(): void + { + $provider = Auth::createUserProvider('users'); + + $retrieved = $provider->retrieveByCredentials([ + 'email' => FakeAuthenticator::ATTESTATION_USER['name'], + ]); + + static::assertTrue(WebAuthnAuthenticatableUser::query()->first()->is($retrieved)); + + $retrieved = $provider->retrieveByCredentials([ + 'email' => 'invalid@invalid.com', + ]); + + static::assertNull($retrieved); + } + + public function test_retrieves_user_using_classic_credentials_without_fallback(): void + { + $this->app->make('config')->set('auth.providers.users.password_fallback', false); + + $this->test_retrieves_user_using_credentials(); + } + + public function test_validates_webauthn(): void + { + $this->mock(AssertionValidator::class) + ->expects('send->thenReturn') + ->andReturn(); + + $valid = Auth::createUserProvider('users') + ->validateCredentials(WebAuthnAuthenticatableUser::first(), FakeAuthenticator::assertionResponse()); + + static::assertTrue($valid); + } + + public function test_validates_webauthn_to_false(): void + { + $this->mock(AssertionValidator::class) + ->expects('send->thenReturn') + ->andThrow(AssertionException::make('invalid')); + + $this->instance('log', $logger = Mockery::mock(LoggerInterface::class)); + + $logger->expects('debug') + ->with('Assertion Error: invalid', []) + ->andReturn(); + + $valid = Auth::createUserProvider('users') + ->validateCredentials(WebAuthnAuthenticatableUser::first(), FakeAuthenticator::assertionResponse()); + + static::assertFalse($valid); + } + + public function test_validates_password(): void + { + $valid = Auth::createUserProvider('users') + ->validateCredentials(WebAuthnAuthenticatableUser::first(), ['password' => 'password']); + + static::assertTrue($valid); + } + + public function test_validates_password_to_false(): void + { + $valid = Auth::createUserProvider('users') + ->validateCredentials(WebAuthnAuthenticatableUser::first(), ['password' => 'invalid']); + + static::assertFalse($valid); + } + + public function test_doesnt_validates_password_when_fallback_is_false(): void + { + $this->app->make('config')->set('auth.providers.users.password_fallback', false); + + $valid = Auth::createUserProvider('users') + ->validateCredentials(WebAuthnAuthenticatableUser::first(), ['password' => 'password']); + + static::assertFalse($valid); + } +} diff --git a/tests/FakeAuthenticator.php b/tests/FakeAuthenticator.php new file mode 100644 index 0000000..b7fc62c --- /dev/null +++ b/tests/FakeAuthenticator.php @@ -0,0 +1,60 @@ + 'e8af6f703f8042aa91c30cf72289aa07', + 'name' => 'john@doe.com', + 'displayName' => 'John Doe', + ]; + + public const ATTESTATION_CHALLENGE = 'H04uZbKiqSx+xEcJ7TIYDg=='; + public const ASSERTION_CHALLENGE = 'iXozmynKi+YD2iRvKNbSPA=='; + + /** + * Returns a correct attestation response. + * + * @return array + */ + #[ArrayShape(['id' => "string", 'type' => "string", 'rawId' => "string", 'response' => "string[]"])] + public static function attestationResponse(): array + { + return [ + 'id' => static::CREDENTIAL_ID, + 'type' => 'public-key', + 'rawId' => static::CREDENTIAL_ID_RAW, + 'response' => [ + 'clientDataJSON' => 'eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiSDA0dVpiS2lxU3gteEVjSjdUSVlEZyIsIm9yaWdpbiI6Imh0dHA6Ly9sb2NhbGhvc3QiLCJjcm9zc09yaWdpbiI6ZmFsc2UsIm90aGVyX2tleXNfY2FuX2JlX2FkZGVkX2hlcmUiOiJkbyBub3QgY29tcGFyZSBjbGllbnREYXRhSlNPTiBhZ2FpbnN0IGEgdGVtcGxhdGUuIFNlZSBodHRwczovL2dvby5nbC95YWJQZXgifQ==', + 'attestationObject' => 'o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVkBZ0mWDeWIDoxodDQXD2R2YFuP5K65ooYyx5lc87qDHZdjRQAAAAAAAAAAAAAAAAAAAAAAAAAAACD5U4sUo9j78W4wj+wnuAyWUrvovdWhFQg2PqUv9neoOKQBAwM5AQAgWQEAnBadZo+CnNdUHvzCWuLNTFsXTCjsHH5A+aUtIImsJsbTKmYsYtOuiOwEgcGglKEJV0MwzV4v2SDQzSirwLErisis4qV6Q3a0ZyZcYhgyMzvkk5CtDhpzxhsmFwiMSGt9gVRE8cOxGDQX2jTPfqykxZTkoXKEHevq8kl5PBCPsaWskrWsySw9mmqNCmIjhE2Evgarm0Xq7yq5h62H2ZzFT3U5C0H32I9cTPk6f/SVke+GMseVRiLleltJMNl0C0cKGBmJpQfeLFlKmOc15WqlwuMegjGULD9dPQvZS5uX+P0bHYfXq5V/HTwrR9FmkEdhq5YB9nE6RkE6Fbs5f+LIhSFDAQAB', + ], + ]; + } + + /** + * Returns a correct Assertion response. + * + * @return array + */ + #[ArrayShape(['id' => "string", 'type' => "string", 'rawId' => "string", 'response' => "string[]"])] + public static function assertionResponse(): array + { + return [ + 'id' => static::CREDENTIAL_ID, + 'type' => 'public-key', + 'rawId' => static::CREDENTIAL_ID_RAW, + 'response' => [ + 'clientDataJSON' => 'eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiaVhvem15bktpLVlEMmlSdktOYlNQQSIsIm9yaWdpbiI6Imh0dHA6Ly9sb2NhbGhvc3QiLCJjcm9zc09yaWdpbiI6ZmFsc2V9', + 'authenticatorData' => 'SZYN5YgOjGh0NBcPZHZgW4/krrmihjLHmVzzuoMdl2MFAAAAAQ==', + 'signature' => 'ca4IJ9h8bZnjMbEFuHX1zfX5LcbiPyDVz6sD1/ppR4t8++1DxKa5EdBIrfNlo8FSOv/JSzMrGGUCQvc/Ngj1KnZpO3s9OdTb54/gMDewH/K8EG4wSvxzHdL6sMbP7UUc5Wq1pcdu9MgXY8V+1gftXpzcoaae0X+mLEETgU7eB8jG0mZhVWvE4yQKuDnZA1i9r8oQhqsvG4nUw1BxvR8wAGiRR+R287LaL41k+xum5mS8zEojUmuLSH50miyVxZ4Y+/oyfxG7i+wSYGNSXlW5iNPB+2WupGS7ce4TuOgaFeMmP2a9rzP4m2IBSQoJ2FyrdzR7HwBEewqqrUVbGQw3Aw==', + 'userHandle' => static::ATTESTATION_USER['id'], + ], + ]; + } +} diff --git a/tests/Http/Controllers/StubControllersTest.php b/tests/Http/Controllers/StubControllersTest.php new file mode 100644 index 0000000..c18c033 --- /dev/null +++ b/tests/Http/Controllers/StubControllersTest.php @@ -0,0 +1,65 @@ +group([], __DIR__ . '/../../../routes/webauthn.php'); + } + + public function test_uses_attestation_request(): void + { + $request = $this->mock(AttestationRequest::class); + + $request->expects('fastRegistration')->andReturnSelf(); + $request->expects('toCreate')->andReturn(new JsonTransport()); + + $this->postJson('webauthn/register/options')->assertOk(); + } + + public function test_uses_attested_request(): void + { + $this->mock(AttestedRequest::class)->expects('save')->andReturn(); + + $this->postJson('webauthn/register')->assertNoContent(); + } + + public function test_uses_assertion_request(): void + { + $request = $this->mock(AssertionRequest::class); + + $request->expects('validate') + ->with(['email' => 'sometimes|email|string']) + ->andReturn(['email' => 'email@email.com']); + + $request->expects('toVerify') + ->with(['email' => 'email@email.com']) + ->andReturn(new JsonTransport()); + + $this->postJson('webauthn/login/options')->assertOk(); + } + + public function test_uses_asserted_request(): void + { + $this->mock(AssertedRequest::class)->expects('login')->andReturn(new WebAuthnAuthenticatableUser()); + + $this->postJson('webauthn/login')->assertNoContent(); + } + + public function test_uses_asserted_request_and_fails_login_with_422(): void + { + $this->mock(AssertedRequest::class)->expects('login')->andReturnNull(); + + $this->postJson('webauthn/login')->assertStatus(422); + } +} diff --git a/tests/Http/Requests/AssertedRequestTest.php b/tests/Http/Requests/AssertedRequestTest.php new file mode 100644 index 0000000..dcc5bf0 --- /dev/null +++ b/tests/Http/Requests/AssertedRequestTest.php @@ -0,0 +1,278 @@ + FakeAuthenticator::ATTESTATION_USER['displayName'], + 'email' => FakeAuthenticator::ATTESTATION_USER['name'], + 'password' => 'test_password', + ]); + + DB::table('webauthn_credentials')->insert([ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'authenticatable_type' => WebAuthnAuthenticatableUser::class, + 'authenticatable_id' => 1, + 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07', + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost', + 'aaguid' => Uuid::NIL, + 'attestation_format' => 'none', + 'public_key' => 'eyJpdiI6Imp0U0NVeFNNbW45KzEvMXpad2p2SUE9PSIsInZhbHVlIjoic0VxZ2I1WnlHM2lJakhkWHVkK2kzMWtibk1IN2ZlaExGT01qOElXMDdRTjhnVlR0TDgwOHk1S0xQUy9BQ1JCWHRLNzRtenNsMml1dVQydWtERjFEU0h0bkJGT2RwUXE1M1JCcVpablE2Y2VGV2YvVEE2RGFIRUE5L0x1K0JIQXhLVE1aNVNmN3AxeHdjRUo2V0hwREZSRTJYaThNNnB1VnozMlVXZEVPajhBL3d3ODlkTVN3bW54RTEwSG0ybzRQZFFNNEFrVytUYThub2IvMFRtUlBZamoyZElWKzR1bStZQ1IwU3FXbkYvSm1FU2FlMTFXYUo0SG9kc1BDME9CNUNKeE9IelE5d2dmNFNJRXBKNUdlVzJ3VHUrQWJZRFluK0hib0xvVTdWQ0ZISjZmOWF3by83aVJES1dxbU9Zd1lhRTlLVmhZSUdlWmlBOUFtcTM2ZVBaRWNKNEFSQUhENk5EaC9hN3REdnVFbm16WkRxekRWOXd4cVcvZFdKa2tlWWJqZWlmZnZLS0F1VEVCZEZQcXJkTExiNWRyQmxsZWtaSDRlT3VVS0ZBSXFBRG1JMjRUMnBKRXZxOUFUa2xxMjg2TEplUzdscVo2UytoVU5SdXk1OE1lcFN6aU05ZkVXTkdIM2tKM3Q5bmx1TGtYb1F5bGxxQVR3K3BVUVlia1VybDFKRm9lZDViNzYraGJRdmtUb2FNTEVGZmZYZ3lYRDRiOUVjRnJpcTVvWVExOHJHSTJpMnVBZ3E0TmljbUlKUUtXY2lSWDh1dE5MVDNRUzVRSkQrTjVJUU8rSGhpeFhRRjJvSEdQYjBoVT0iLCJtYWMiOiI5MTdmNWRkZGE5OTEwNzQ3MjhkYWVhYjRlNjk0MWZlMmI5OTQ4YzlmZWI1M2I4OGVkMjE1MjMxNjUwOWRmZTU2IiwidGFnIjoiIn0=', + 'updated_at' => now(), + 'created_at' => now(), + ]); + } + + protected function defineEnvironment($app): void + { + $app->make('config')->set('auth.providers.users.driver', 'eloquent-webauthn'); + $app->make('config')->set('auth.providers.users.model', WebAuthnAuthenticatableUser::class); + } + + protected function defineWebRoutes($router): void + { + $router->post('test', static function (AssertedRequest $request): void { + $request->login(); + }); + } + + public function test_verifies_and_logs_in_user(): void + { + $this->session(['_webauthn' => new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ASSERTION_CHALLENGE)), 60, false, + )]); + + $this->postJson('test', FakeAuthenticator::assertionResponse())->assertOk(); + + $this->assertAuthenticatedAs(WebAuthnAuthenticatableUser::find(1)); + } + + public function test_pulls_challenge_session_key(): void + { + $this->session(['_webauthn' => new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ASSERTION_CHALLENGE)), 60, false, + )]); + + $this->postJson('test', FakeAuthenticator::assertionResponse())->assertOk(); + + static::assertNull(session('_webauthn')); + } + + public function test_logs_in_with_remember_header_x_webauthn_remember(): void + { + $event = Event::fake(Login::class); + + $this->session(['_webauthn' => new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ASSERTION_CHALLENGE)), 60, false, + )]); + + $this->postJson('test', FakeAuthenticator::assertionResponse(), [ + 'X-WebAuthn-Remember' => 1 + ])->assertOk(); + + $event->assertDispatched(Login::class, static function (Login $event): bool { + return $event->remember; + }); + } + + public function test_logs_in_with_remember_header_webauthn_remember(): void + { + $event = Event::fake(Login::class); + + $this->session(['_webauthn' => new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ASSERTION_CHALLENGE)), 60, false, + )]); + + $this->postJson('test', FakeAuthenticator::assertionResponse(), [ + 'WebAuthn-Remember' => 1 + ])->assertOk(); + + $event->assertDispatched(Login::class, static function (Login $event): bool { + return $event->remember; + }); + } + + public function test_logs_in_with_remember_input(): void + { + $event = Event::fake(Login::class); + + $this->session(['_webauthn' => new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ASSERTION_CHALLENGE)), 60, false, + )]); + + $this->postJson('test', array_merge(FakeAuthenticator::assertionResponse(), [ + 'remember' => 'on' + ]))->assertOk(); + + $event->assertDispatched(Login::class, static function (Login $event): bool { + return $event->remember; + }); + } + + public function test_logs_in_with_manual_remember_true(): void + { + $event = Event::fake(Login::class); + + $this->session(['_webauthn' => new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ASSERTION_CHALLENGE)), 60, false, + )]); + + Route::middleware('web')->post('remember', function (AssertedRequest $request) { + $request->login(null, true); + }); + + $this->postJson('remember', FakeAuthenticator::assertionResponse())->assertOk(); + + $event->assertDispatched(Login::class, static function (Login $event): bool { + return $event->remember; + }); + } + + public function test_logs_in_with_manual_remember_false(): void + { + $event = Event::fake(Login::class); + + $this->session(['_webauthn' => new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ASSERTION_CHALLENGE)), 60, false, + )]); + + Route::middleware('web')->post('remember', function (AssertedRequest $request) { + $request->login(null, false); + }); + + $this->postJson('remember', FakeAuthenticator::assertionResponse())->assertOk(); + + $event->assertDispatched(Login::class, static function (Login $event): bool { + return ! $event->remember; + }); + } + + public function test_uses_custom_session_key(): void + { + config(['webauthn.challenge.key' => 'foo']); + + $this->session(['foo' => new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ASSERTION_CHALLENGE)), 60, false, + )]); + + $this->postJson('test', array_merge(FakeAuthenticator::assertionResponse(), [ + 'remember' => 'on' + ]))->assertOk(); + + $this->assertAuthenticatedAs(WebAuthnAuthenticatableUser::find(1)); + } + + public function test_logs_in_with_custom_guard(): void + { + $guard = Auth::guard('web'); + + Auth::expects('guard')->with('foo')->twice()->andReturn($guard); + + Route::middleware('web')->post('custom', function (AssertedRequest $request) { + $request->login('foo'); + }); + + $this->session(['_webauthn' => new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ASSERTION_CHALLENGE)), 60, false, + )]); + + $this->postJson('custom', FakeAuthenticator::assertionResponse())->assertOk(); + + $this->assertAuthenticatedAs(WebAuthnAuthenticatableUser::find(1), 'foo'); + } + + public function test_logs_in_returns_user(): void + { + Route::middleware('web')->post('custom', function (AssertedRequest $request) { + static::assertTrue(WebAuthnAuthenticatableUser::find(1)->is($request->login())); + }); + + $this->session(['_webauthn' => new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ASSERTION_CHALLENGE)), 60, false, + )]); + + $this->postJson('custom', FakeAuthenticator::assertionResponse())->assertOk(); + } + + public function test_fails_validation_if_a_member_is_missing(): void + { + $this->postJson('test', [ + 'id' => 'test_id', + 'response' => [ + 'authenticatorData' => 'test', + 'clientDataJSON' => 'test', + 'signature' => 'test', + 'userHandle' => 'test', + ], + 'type' => 'test' + ]) + ->assertJsonValidationErrorFor('rawId'); + } + + public function test_asserts_with_missing_user_handle(): void + { + $response = FakeAuthenticator::assertionResponse(); + + Arr::forget($response, 'response.userHandle'); + + $this->session(['_webauthn' => new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ASSERTION_CHALLENGE)), 60, false, + )]); + + // We know it's going to fail since the user is not in the validation object, this is just for show. + $this->mock(AssertionValidator::class) + ->expects('send->thenReturn') + ->andReturn(); + + $this->postJson('test', $response)->assertOk(); + + $this->assertAuthenticatedAs(WebAuthnAuthenticatableUser::find(1)); + } + + public function test_destroy_session_on_regeneration(): void + { + Route::middleware('web')->post('custom', function (AssertedRequest $request) { + $request->login(destroySession: true); + }); + + $session = Mockery::mock(\Illuminate\Contracts\Session\Session::class); + + $session->expects('regenerate')->with(true)->andReturn(); + + $this->app->resolving(AssertedRequest::class, function (AssertedRequest $request) use ($session): void { + $request->setLaravelSession($session); + }); + + $this->mock(AssertionValidator::class) + ->expects('send->thenReturn') + ->andReturn(); + + $this->postJson('custom', FakeAuthenticator::assertionResponse())->assertOk(); + } +} diff --git a/tests/Http/Requests/AssertionRequestTest.php b/tests/Http/Requests/AssertionRequestTest.php new file mode 100644 index 0000000..ce5847b --- /dev/null +++ b/tests/Http/Requests/AssertionRequestTest.php @@ -0,0 +1,229 @@ + FakeAuthenticator::ATTESTATION_USER['displayName'], + 'email' => FakeAuthenticator::ATTESTATION_USER['name'], + 'password' => 'test_password', + ]); + } + + protected function defineEnvironment($app): void + { + $app->make('config')->set('auth.providers.users.driver', 'eloquent-webauthn'); + $app->make('config')->set('auth.providers.users.model', WebAuthnAuthenticatableUser::class); + } + + public function test_creates_assertion(): void + { + Route::middleware('web')->post('test', function (AssertionRequest $request) { + return $request->toVerify(); + }); + + $this->postJson('test') + ->assertSessionHas('_webauthn', function (Challenge $challenge): bool { + return !$challenge->verify; + }) + ->assertJson([ + 'timeout' => 60000, + 'challenge' => session('_webauthn')->data->toBase64Url() + ]); + } + + public function test_uses_custom_timeout(): void + { + config(['webauthn.challenge.timeout' => 120]); + + Route::middleware('web')->post('test', function (AssertionRequest $request) { + return $request->toVerify(); + }); + + $this->postJson('test') + ->assertJson([ + 'timeout' => 120000, + 'challenge' => session('_webauthn')->data->toBase64Url() + ]); + } + + public function test_uses_custom_length(): void + { + config(['webauthn.challenge.bytes' => 32]); + + Route::middleware('web')->post('test', function (AssertionRequest $request) { + return $request->toVerify(); + }); + + $this->postJson('test') + ->assertJson([ + 'timeout' => 60000, + 'challenge' => session('_webauthn')->data->toBase64Url() + ]); + + static::assertSame(64, strlen(session('_webauthn')->data->toHex())); + } + + public function test_uses_custom_session_key(): void + { + config(['webauthn.challenge.key' => 'foo']); + + Route::middleware('web')->post('test', function (AssertionRequest $request) { + return $request->toVerify(); + }); + + $this->postJson('test')->assertSessionHas('foo'); + } + + public function test_uses_custom_guard(): void + { + $guard = Auth::guard('web'); + + Auth::partialMock()->expects('guard')->with('foo')->andReturn($guard); + + Route::middleware('web')->post('test', function (AssertionRequest $request) { + return $request->guard('foo')->toVerify(['email' => FakeAuthenticator::ATTESTATION_USER['name']]); + }); + + $this->postJson('test') + ->assertOk() + ->assertJson([ + 'timeout' => 60000, + 'challenge' => session('_webauthn')->data->toBase64Url() + ]); + } + + public function test_guard_fails_if_user_not_webauthn_authenticatable(): void + { + config(['auth.providers.users.driver' => 'eloquent']); + config(['auth.providers.users.model' => User::class]); + + Route::middleware('web')->post('test', function (AssertionRequest $request) { + return $request->guard('web')->toVerify(['email' => FakeAuthenticator::ATTESTATION_USER['name']]); + }); + + $this->postJson('test') + ->assertStatus(500) + ->assertSee('The user found for the [web] auth guard is not an instance of [WebAuthnAuthenticatable].'); + } + + public function test_uses_fast_login(): void + { + Route::middleware('web')->post('test', function (AssertionRequest $request) { + return $request->fastLogin()->toVerify(); + }); + + $this->postJson('test')->assertJson([ + 'timeout' => 60000, + 'userVerification' => 'discouraged', + 'challenge' => session('_webauthn')->data->toBase64Url() + ]); + + static::assertFalse(session('_webauthn')->verify); + } + + public function test_uses_secure_login(): void + { + Route::middleware('web')->post('test', function (AssertionRequest $request) { + return $request->secureLogin()->toVerify(); + }); + + $this->postJson('test')->assertJson([ + 'timeout' => 60000, + 'userVerification' => 'required', + 'challenge' => session('_webauthn')->data->toBase64Url() + ]); + + static::assertTrue(session('_webauthn')->verify); + } + + public function test_uses_verify_with_already_instanced_user(): void + { + Route::middleware('web')->post('test', function (AssertionRequest $request) { + return $request->toVerify(WebAuthnAuthenticatableUser::find(1)); + }); + + $creator = $this->mock(AssertionCreator::class); + + $creator->expects('send')->withArgs(function (AssertionCreation $creation): bool { + return $creation->user->getKey() === 1; + }) + ->andReturnSelf(); + + $creator->expects('then')->andReturn(new JsonTransport()); + + $this->postJson('test')->assertOk(); + } + + public function test_uses_verify_with_user_id(): void + { + Route::middleware('web')->post('test', function (AssertionRequest $request) { + return $request->toVerify(1); + }); + + $creator = $this->mock(AssertionCreator::class); + + $creator->expects('send')->withArgs(function (AssertionCreation $creation): bool { + return $creation->user->getKey() === 1; + }) + ->andReturnSelf(); + + $creator->expects('then')->andReturn(new JsonTransport()); + + $this->postJson('test')->assertOk(); + } + + public function test_uses_verify_with_bad_id_returning_null_user(): void + { + Route::middleware('web')->post('test', function (AssertionRequest $request) { + return $request->toVerify(99); + }); + + $creator = $this->mock(AssertionCreator::class); + + $creator->expects('send')->withArgs(function (AssertionCreation $creation): bool { + return ! $creation->user; + }) + ->andReturnSelf(); + + $creator->expects('then')->andReturn(new JsonTransport()); + + $this->postJson('test')->assertOk(); + } + + public function test_uses_verify_with_bad_credentials_returning_null_user(): void + { + Route::middleware('web')->post('test', function (AssertionRequest $request) { + return $request->toVerify(['email' => 'invalid@email.com']); + }); + + $creator = $this->mock(AssertionCreator::class); + + $creator->expects('send')->withArgs(function (AssertionCreation $creation): bool { + return ! $creation->user; + }) + ->andReturnSelf(); + + $creator->expects('then')->andReturn(new JsonTransport()); + + $this->postJson('test')->assertOk(); + } +} diff --git a/tests/Http/Requests/AttestationRequestTest.php b/tests/Http/Requests/AttestationRequestTest.php new file mode 100644 index 0000000..5e86ab8 --- /dev/null +++ b/tests/Http/Requests/AttestationRequestTest.php @@ -0,0 +1,149 @@ +be( + WebAuthnAuthenticatableUser::forceCreate([ + 'name' => FakeAuthenticator::ATTESTATION_USER['displayName'], + 'email' => FakeAuthenticator::ATTESTATION_USER['name'], + 'password' => 'test_password', + ]) + ); + } + + public function test_forbidden_if_user_not_authenticated(): void + { + Auth::logout(); + + Route::middleware('web')->post('test', function (AttestationRequest $request) { + return $request->toCreate(); + }); + + $this->postJson('test')->assertForbidden(); + } + + public function test_forbidden_if_user_not_webauthn_authenticatable(): void + { + $this->be(new User()); + + Route::middleware('web')->post('test', function (AttestationRequest $request) { + return $request->toCreate(); + }); + + $this->postJson('test')->assertForbidden(); + } + + public function test_returns_response_and_saves_challenge(): void + { + Route::middleware('web')->post('test', function (AttestationRequest $request) { + return $request->toCreate(); + }); + + $this->postJson('test') + ->assertSessionHas('_webauthn', static function (Challenge $challenge): bool { + static::assertFalse($challenge->verify); + + return true; + }); + } + + public function test_uses_custom_session_key(): void + { + config(['webauthn.challenge.key' => 'foo']); + + Route::middleware('web')->post('test', function (AttestationRequest $request) { + return $request->toCreate(); + }); + + $this->postJson('test')->assertSessionHas('foo'); + } + + public function test_uses_fast_registration(): void + { + Route::middleware('web')->post('test', function (AttestationRequest $request) { + return $request->fastRegistration()->toCreate(); + }); + + $this->postJson('test') + ->assertSessionHas('_webauthn', static function (Challenge $challenge): bool { + static::assertFalse($challenge->verify); + + return true; + }) + ->assertJsonPath('authenticatorSelection.userVerification', 'discouraged'); + } + + public function test_uses_secure_registration(): void + { + Route::middleware('web')->post('test', function (AttestationRequest $request) { + return $request->secureRegistration()->toCreate(); + }); + + $this->postJson('test') + ->assertSessionHas('_webauthn', static function (Challenge $challenge): bool { + static::assertTrue($challenge->verify); + + return true; + }) + ->assertJsonPath('authenticatorSelection.userVerification', 'required'); + } + + public function test_uses_userless_and_verifies_user(): void + { + Route::middleware('web')->post('test', function (AttestationRequest $request) { + return $request->userless()->toCreate(); + }); + + $this->postJson('test') + ->assertSessionHas('_webauthn', static function (Challenge $challenge): bool { + static::assertTrue($challenge->verify); + + return true; + }) + ->assertJsonFragment([ + 'authenticatorSelection' => [ + 'residentKey' => 'required', + 'requireResidentKey' => true, + 'userVerification' => 'required' + ], + ]); + } + + public function test_allows_duplicates(): void + { + Route::middleware('web')->post('test', function (AttestationRequest $request) { + return $request->allowDuplicates()->toCreate(); + }); + + WebAuthnCredential::forceCreate([ + 'id' => 'test_id', + 'authenticatable_type' => WebAuthnAuthenticatableUser::class, + 'authenticatable_id' => 1, + 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07', + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost', + 'aaguid' => Uuid::NIL, + 'attestation_format' => 'none', + 'public_key' => 'test_key', + ]); + + $this->postJson('test')->assertJsonMissingPath('excludeCredentials'); + } +} diff --git a/tests/Http/Requests/AttestedRequestTest.php b/tests/Http/Requests/AttestedRequestTest.php new file mode 100644 index 0000000..acaf2af --- /dev/null +++ b/tests/Http/Requests/AttestedRequestTest.php @@ -0,0 +1,176 @@ +be( + WebAuthnAuthenticatableUser::forceCreate([ + 'name' => FakeAuthenticator::ATTESTATION_USER['displayName'], + 'email' => FakeAuthenticator::ATTESTATION_USER['name'], + 'password' => 'test_password', + ]) + ); + } + + protected function defineWebRoutes($router): void + { + $router->post('test', static function (AttestedRequest $request): void { + $request->save(); + }); + } + + public function test_forbidden_if_user_not_authenticated(): void + { + Auth::logout(); + + $this->postJson('test')->assertForbidden(); + } + + public function test_forbidden_if_user_not_webauthn_authenticatable(): void + { + $this->be(new User()); + + $this->postJson('test')->assertForbidden(); + } + + public function test_invalid_if_web_authn_response_not_structured(): void + { + $this->postJson('test', [ + 'id' => 'test', + 'rawId' => 'test', + 'response' => [ + 'clientDataJSON' => 'test', + ], + 'type' => 'test', + ])->assertJsonValidationErrorFor('response.attestationObject'); + } + + public function test_calls_validator_if_valid_and_authorized(): void + { + $this->session(['_webauthn' => new Challenge( + new ByteBuffer( + base64_decode(FakeAuthenticator::ATTESTATION_CHALLENGE)), + 60, + false, + ['user_uuid' => FakeAuthenticator::ATTESTATION_USER['id']] + ) + ]); + + $event = Event::fake(CredentialCreated::class); + + $this->postJson('test', FakeAuthenticator::attestationResponse())->assertOk(); + + $event->assertDispatched(CredentialCreated::class, function (CredentialCreated $event): bool { + return FakeAuthenticator::CREDENTIAL_ID === $event->credential->getKey(); + }); + + $this->assertDatabaseHas(WebAuthnCredential::class, [ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'authenticatable_type' => WebAuthnAuthenticatableUser::class, + 'authenticatable_id' => 1, + ]); + } + + public function test_uses_custom_session_key(): void + { + config(['webauthn.challenge.key' => 'foo']); + + $this->session(['foo' => new Challenge( + new ByteBuffer( + base64_decode(FakeAuthenticator::ATTESTATION_CHALLENGE)), + 60, + false, + ['user_uuid' => FakeAuthenticator::ATTESTATION_USER['id']] + ) + ]); + + $this->postJson('test', FakeAuthenticator::attestationResponse())->assertOk(); + } + + public function test_saves_with_array(): void + { + Route::middleware('web')->post('test', static function (AttestedRequest $request): void { + $request->save(['alias' => 'foo']); + }); + + $this->session(['_webauthn' => new Challenge( + new ByteBuffer( + base64_decode(FakeAuthenticator::ATTESTATION_CHALLENGE)), + 60, + false, + ['user_uuid' => FakeAuthenticator::ATTESTATION_USER['id']] + ) + ]); + + $this->postJson('test', FakeAuthenticator::attestationResponse())->assertOk(); + + $this->assertDatabaseHas(WebAuthnCredential::class, [ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'authenticatable_type' => WebAuthnAuthenticatableUser::class, + 'authenticatable_id' => 1, + 'alias' => 'foo', + ]); + } + + public function test_saves_with_callable(): void + { + Route::middleware('web')->post('test', static function (AttestedRequest $request): void { + $request->save(function ($credential) { + $credential->alias = 'foo'; + }); + }); + + $this->session(['_webauthn' => new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ATTESTATION_CHALLENGE)), + 60, + false, + ['user_uuid' => FakeAuthenticator::ATTESTATION_USER['id']] + ) + ]); + + $this->postJson('test', FakeAuthenticator::attestationResponse())->assertOk(); + + $this->assertDatabaseHas(WebAuthnCredential::class, [ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'authenticatable_type' => WebAuthnAuthenticatableUser::class, + 'authenticatable_id' => 1, + 'alias' => 'foo', + ]); + } + + public function test_saves_return_credential_key(): void + { + $this->session(['_webauthn' => new Challenge( + new ByteBuffer(base64_decode(FakeAuthenticator::ATTESTATION_CHALLENGE)), + 60, + false, + ['user_uuid' => FakeAuthenticator::ATTESTATION_USER['id']] + ) + ]); + + Route::middleware('web')->post('test', static function (AttestedRequest $request): array { + return [$request->save()]; + }); + + $this->postJson('test', FakeAuthenticator::attestationResponse()) + ->assertJson([FakeAuthenticator::CREDENTIAL_ID]); + } +} diff --git a/tests/Models/WebAuthnCredentialTest.php b/tests/Models/WebAuthnCredentialTest.php new file mode 100644 index 0000000..c6a1564 --- /dev/null +++ b/tests/Models/WebAuthnCredentialTest.php @@ -0,0 +1,156 @@ + FakeAuthenticator::ATTESTATION_USER['displayName'], + 'email' => FakeAuthenticator::ATTESTATION_USER['name'], + 'password' => 'test_password', + ]); + + $base = static function (array $override = []): array { + return array_merge([ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'authenticatable_type' => WebAuthnAuthenticatableUser::class, + 'authenticatable_id' => 1, + 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07', + 'counter' => 0, + 'rp_id' => 'http://localhost', + 'origin' => 'http://localhost', + 'aaguid' => Uuid::NIL, + 'attestation_format' => 'none', + 'public_key' => 'test_key', + 'updated_at' => now(), + 'created_at' => now(), + ], $override); + }; + + DB::table('webauthn_credentials')->insert($base()); + + DB::table('webauthn_credentials')->insert($base([ + 'id' => '27EdS6eTDHCTa9Y73G9gY1b81yVJuuiu1TTyorFicBf' + ])); + + DB::table('webauthn_credentials')->insert($base([ + 'id' => 'HLs22xpFT7ilSbYvbARFNf9Q3nVyfczTT9LFhtFT89D', + 'disabled_at' => now()->toDateTimeString(), + ])); + } + + public function test_queries_enabled_credentials(): void + { + static::assertSame(2, WebAuthnCredential::query()->whereEnabled()->count()); + } + + public function test_queries_disabled_credentials(): void + { + static::assertSame(1, WebAuthnCredential::query()->whereDisabled()->count()); + } + + public function test_is_enabled(): void + { + $credential = WebAuthnCredential::find(FakeAuthenticator::CREDENTIAL_ID); + + static::assertTrue($credential->isEnabled()); + static::assertFalse($credential->isDisabled()); + } + + public function test_is_disabled(): void + { + $credential = WebAuthnCredential::find('HLs22xpFT7ilSbYvbARFNf9Q3nVyfczTT9LFhtFT89D'); + + static::assertTrue($credential->isDisabled()); + static::assertFalse($credential->isEnabled()); + } + + public function test_disables_credential(): void + { + $event = Event::fake(); + + $credential = WebAuthnCredential::find(FakeAuthenticator::CREDENTIAL_ID); + + $this->freezeSecond(); + + $credential->disable(); + $credential->disable(); + + $event->assertDispatchedTimes(CredentialDisabled::class); + + $this->assertDatabaseHas(WebAuthnCredential::class, [ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'disabled_at' => now()->toDateTimeString(), + ]); + } + + public function test_enables_credential(): void + { + $event = Event::fake(); + + $credential = WebAuthnCredential::find('HLs22xpFT7ilSbYvbARFNf9Q3nVyfczTT9LFhtFT89D'); + + $this->freezeSecond(); + + $credential->enable(); + $credential->enable(); + + $event->assertDispatchedTimes(CredentialEnabled::class); + + $this->assertDatabaseHas(WebAuthnCredential::class, [ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'disabled_at' => null, + ]); + } + + public function test_syncs_counter(): void + { + $credential = WebAuthnCredential::find(FakeAuthenticator::CREDENTIAL_ID); + + $credential->syncCounter(20); + + $this->assertDatabaseHas(WebAuthnCredential::class, [ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'counter' => 20, + ]); + } + + public function test_authenticatable(): void + { + $user = WebAuthnCredential::find(FakeAuthenticator::CREDENTIAL_ID)->authenticatable; + + static::assertInstanceOf(WebAuthnAuthenticatableUser::class, $user); + } + + public function test_shows_serializes_few_columns(): void + { + $json = WebAuthnCredential::find(FakeAuthenticator::CREDENTIAL_ID)->toJson(); + + static::assertJsonStringEqualsJsonString( + json_encode([ + 'id' => FakeAuthenticator::CREDENTIAL_ID, + 'origin' => 'http://localhost', + 'alias' => null, + 'aaguid' => Uuid::NIL, + 'attestation_format' => 'none', + 'disabled_at' => null, + ]), + $json + ); + } +} diff --git a/tests/Stubs/WebAuthnAuthenticatableUser.php b/tests/Stubs/WebAuthnAuthenticatableUser.php new file mode 100644 index 0000000..e919623 --- /dev/null +++ b/tests/Stubs/WebAuthnAuthenticatableUser.php @@ -0,0 +1,19 @@ +loadLaravelMigrations(); + $this->loadMigrationsFrom(__DIR__ . '/../database/migrations'); + } + + protected function getPackageProviders($app): array + { + return [WebAuthnServiceProvider::class]; + } +}