diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..808f9eb --- /dev/null +++ b/.editorconfig @@ -0,0 +1,18 @@ +root = true + +[*] +charset = utf-8 +end_of_line = crlf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.{cs,csproj,props,targets,sln}] +charset = utf-8-bom + +[*.{json,yml,yaml}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..aac1598 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,23 @@ +version: 2 +updates: + - package-ecosystem: nuget + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 10 + commit-message: + prefix: chore + include: scope + groups: + tests: + patterns: ["xunit*", "AwesomeAssertions"] + ignore: + # Never reintroduce FluentAssertions (commercial license since v8) + - dependency-name: "FluentAssertions" + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + commit-message: + prefix: ci diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index d6dc630..6314637 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -3,55 +3,79 @@ name: NetDevPack - MAIN Publish on: push: branches: [ main ] + workflow_dispatch: + inputs: + version: + description: Existing release to publish again (e.g. 4.0.0). Builds tag v and pushes it to nuget.org. + required: true env: - REPOSITORY_URL: https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json CURRENT_REPO_URL: https://github.com/${{ github.repository }} +permissions: + contents: write + issues: write + pull-requests: write + id-token: write # NuGet trusted publishing (OIDC) + jobs: publish: runs-on: ubuntu-latest - defaults: - run: - working-directory: src + steps: - name: Checkout repository - uses: actions/checkout@v3 - - - name: Setup .NET 8 - uses: actions/setup-dotnet@v3 + uses: actions/checkout@v7 with: - dotnet-version: 8.0.x + fetch-depth: 0 + ref: ${{ inputs.version && format('v{0}', inputs.version) || github.sha }} - - name: Setup .NET 9 - uses: actions/setup-dotnet@v3 + - name: Setup .NET + uses: actions/setup-dotnet@v6 with: - dotnet-version: 9.0.x - - - name: Setup .NET 10 - uses: actions/setup-dotnet@v3 - with: - dotnet-version: 10.0.x + global-json-file: global.json - name: Restore dependencies - run: dotnet restore + run: dotnet restore src/NetDevPack.Fido2.sln - name: Build - run: dotnet build --no-restore + run: dotnet build src/NetDevPack.Fido2.sln --no-restore -c Release + + - name: Test + run: dotnet test --solution src/NetDevPack.Fido2.sln --no-build -c Release - name: Semantic Release id: semantic + if: github.event_name == 'push' uses: cycjimmy/semantic-release-action@v4 with: + semantic_version: 24 extra_plugins: | - @semantic-release/changelog - @semantic-release/git + @semantic-release/changelog@6 + @semantic-release/git@10 + conventional-changelog-conventionalcommits@8 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Resolve version + id: version + if: github.event_name == 'workflow_dispatch' || steps.semantic.outputs.new_release_published == 'true' + env: + VERSION: ${{ inputs.version || steps.semantic.outputs.new_release_version }} + run: | + [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || { echo "::error::Invalid version '$VERSION'"; exit 1; } + echo "value=$VERSION" >> "$GITHUB_OUTPUT" + - name: Generate Package - run: dotnet pack -c Release -o out -p:PackageVersion=${{ steps.semantic.outputs.new_release_version }} -p:RepositoryUrl=${{env.CURRENT_REPO_URL}} + if: steps.version.outputs.value != '' + run: dotnet pack src/NetDevPack.Fido2.EntityFramework.Store/NetDevPack.Fido2.EntityFramework.Store.csproj -c Release -o out -p:Version=${{ steps.version.outputs.value }} -p:RepositoryUrl=${{ env.CURRENT_REPO_URL }} + + - name: NuGet login (trusted publishing) + id: nuget + if: steps.version.outputs.value != '' + uses: NuGet/login@v1 + with: + user: ${{ vars.NUGET_USER }} - name: Publish the package to nuget.org - run: dotnet nuget push ./out/*.nupkg -n -d -k ${{ secrets.NUGET_AUTH_TOKEN}} -s https://api.nuget.org/v3/index.json - \ No newline at end of file + if: steps.version.outputs.value != '' + run: dotnet nuget push ./out/*.nupkg --skip-duplicate -k ${{ steps.nuget.outputs.NUGET_API_KEY }} -s https://api.nuget.org/v3/index.json diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 97e7e87..e9eb9db 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -1,39 +1,37 @@ -name: NetDevPack - MASTER PR +name: NetDevPack - MAIN PR on: pull_request: branches: [ main ] +permissions: + contents: read + jobs: pull-request: runs-on: ubuntu-latest - defaults: - run: - working-directory: src + steps: - name: Checkout repository - uses: actions/checkout@v3 - - - name: Setup .NET 8 - uses: actions/setup-dotnet@v3 + uses: actions/checkout@v7 with: - dotnet-version: 8.0.x + fetch-depth: 0 - - name: Setup .NET 9 - uses: actions/setup-dotnet@v3 + - name: Setup .NET + uses: actions/setup-dotnet@v6 with: - dotnet-version: 9.0.x - - - name: Setup .NET 10 - uses: actions/setup-dotnet@v3 - with: - dotnet-version: 10.0.x + global-json-file: global.json - name: Restore dependencies - run: dotnet restore + run: dotnet restore src/NetDevPack.Fido2.sln - name: Build - run: dotnet build --no-restore + run: dotnet build src/NetDevPack.Fido2.sln --no-restore -c Release - name: Test - run: dotnet test --no-build \ No newline at end of file + run: dotnet test --solution src/NetDevPack.Fido2.sln --no-build -c Release + + - name: Check vulnerable packages + run: | + dotnet list src/NetDevPack.Fido2.sln package --vulnerable --include-transitive 2>&1 | tee vulnerable.txt + ! grep -q "has the following vulnerable packages" vulnerable.txt diff --git a/.releaserc b/.releaserc index d7ae49b..1e6580f 100644 --- a/.releaserc +++ b/.releaserc @@ -1,11 +1,22 @@ { - "branches": ["main"], - - "plugins": [ - "@semantic-release/commit-analyzer", - "@semantic-release/release-notes-generator", - "@semantic-release/changelog", - "@semantic-release/github", - "@semantic-release/git" - ] -} \ No newline at end of file + "branches": [ + "main" + ], + "plugins": [ + [ + "@semantic-release/commit-analyzer", + { + "preset": "conventionalcommits" + } + ], + [ + "@semantic-release/release-notes-generator", + { + "preset": "conventionalcommits" + } + ], + "@semantic-release/changelog", + "@semantic-release/github", + "@semantic-release/git" + ] +} diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..a5c8809 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,11 @@ + + + + latest + + true + all + $(WarningsAsErrors);NU1901;NU1902;NU1903;NU1904 + true + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..79880e0 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,33 @@ + + + + true + true + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/README.MD b/README.MD index 4e82361..a1089a1 100644 --- a/README.MD +++ b/README.MD @@ -1,15 +1,23 @@ # Fido2 EntityFramework.Store -A thin wrapper around [Fido2](https://github.com/passwordless-lib/fido2-net-lib) adding store capabilities to it. +An Entity Framework Core store for [Fido2](https://github.com/passwordless-lib/fido2-net-lib) (WebAuthn / passkeys). -## Purpouse +## Purpose -Provide a better integration between [Fido2](https://github.com/passwordless-lib/fido2-net-lib) library and ASP.NET Identity +Provide a better integration between the [Fido2](https://github.com/passwordless-lib/fido2-net-lib) library and ASP.NET Core Identity. + +## Compatibility + +| NetDevPack.Fido2.EntityFramework.Store | Fido2 | Target framework | +| -------------------------------------- | ----- | ---------------- | +| 4.x | 4.x | .NET 10 (LTS) | +| 3.x | 3.x | .NET 8, .NET 9, .NET 10 | ## How to implement -1. Add at `Program.cs` +1. Add to `Program.cs` ```csharp +builder.Services.AddFido2(builder.Configuration.GetSection("Fido2")); builder.Services.AddFido2Context(); ``` @@ -25,12 +33,79 @@ public class ApplicationDbContext : IdentityDbContext, IFido2Context { } - public DbSet Fido2StoredCredential { get; set; } + public DbSet Fido2StoredCredential { get; set; } } ``` -3. Now you can inject `IFido2Store` to save and recover `StoredCredential` +3. Inject `IFido2Store` to save and recover credentials: +```csharp +// Registration +var credential = await _fido2.MakeNewCredentialAsync(new MakeNewCredentialParams +{ + AttestationResponse = attestationResponse, + OriginalOptions = options, + IsCredentialIdUniqueToUserCallback = async (args, ct) => + !(await _fido2Store.ListCredentialsByPublicKeyIdAsync(args.CredentialId)).Any() +}); +_fido2Store.Store("My security key", fidoUser, StoredCredential.FromRegisteredCredential(credential)); + +// Login +var stored = await _fido2Store.GetCredentialByPublicKeyIdAsync(assertionResponse.RawId); +var result = await _fido2.MakeAssertionAsync(new MakeAssertionParams +{ + AssertionResponse = assertionResponse, + OriginalOptions = options, + StoredPublicKey = stored.PublicKey, + StoredSignatureCounter = stored.SignatureCounter, + IsUserHandleOwnerOfCredentialIdCallback = async (args, ct) => + (await _fido2Store.GetCredentialsByUserHandleAsync(args.UserHandle)).Any(c => c.Descriptor.Id.SequenceEqual(args.CredentialId)) +}); +await _fido2Store.UpdateCounter(result.CredentialId, result.SignCount, result.IsBackedUp); +``` + +## Upgrading from 3.x to 4.x + +4.x targets **.NET 10** and **Fido2 4**. Stay on 3.x for .NET 8/9 or Fido2 3. + +### API changes +- `Fido2NetLib.Development.StoredCredential` does not exist in Fido2 4. The store now uses its own + `NetDevPack.Fido2.EntityFramework.Store.Model.StoredCredential`. It keeps the 3.x property names (`UserId`, `Descriptor`, `PublicKey`, + `UserHandle`, `SignatureCounter`, `CredType`, `RegDate`, `AaGuid`). Replace `using Fido2NetLib.Development;` with + `using NetDevPack.Fido2.EntityFramework.Store.Model;`. +- New `StoredCredential.FromRegisteredCredential(RegisteredPublicKeyCredential)` builds a credential from the result of + `IFido2.MakeNewCredentialAsync`, including transports and backup flags. +- `IFido2Store.GetCredentialByPublicKeyIdAsync` returns `StoredCredential?`. +- `IFido2Store.UpdateCounter(byte[] credentialId, uint counter, bool? isBackedUp = null)` also stores the Backup State flag. +- Fido2 4 itself changed its API: `MakeNewCredentialAsync`, `MakeAssertionAsync`, `RequestNewCredential` and `GetAssertionOptions` now take + `*Params` objects, `MakeAssertionAsync` throws `Fido2VerificationException` instead of returning a status, and options no longer carry + `Status`/`ErrorMessage`. Use `AuthenticatorAssertionRawResponse.RawId` (bytes) to look up credentials, since `Id` is now a string. + See the [Fido2 releases](https://github.com/passwordless-lib/fido2-net-lib/releases). + +### Database schema +Two columns were added to `StoredCredentialDetail`. Nothing was renamed or removed, and existing rows keep working: + +| Column | Type | Default for existing rows | +| ------------------ | ------------- | ------------------------- | +| `IsBackupEligible` | `bool` (not null) | `false` | +| `IsBackedUp` | `bool` (not null) | `false` | + +Create a migration in your application: +```bash +dotnet ef migrations add Fido2StoreV4 -c ApplicationDbContext +dotnet ef database update -c ApplicationDbContext +``` + +The generated migration only adds the two columns with `defaultValue: false`. For SQL Server it is equivalent to: +```sql +ALTER TABLE [Fido2StoredCredential] ADD [IsBackupEligible] bit NOT NULL DEFAULT CAST(0 AS bit); +ALTER TABLE [Fido2StoredCredential] ADD [IsBackedUp] bit NOT NULL DEFAULT CAST(0 AS bit); +``` + +`IsBackedUp` is refreshed on the next successful login when you pass `result.IsBackedUp` to `UpdateCounter`. `IsBackupEligible` cannot be known for credentials registered with 3.x, so it stays `false` for them. ## Demo -Check demo at Source Code. +See the demo in `demo/Fido2.Passwordless`. Docker build context is the repository root: +```bash +docker build -f demo/Fido2.Passwordless/Dockerfile . +``` diff --git a/assets/IconNuget.png b/assets/IconNuget.png new file mode 100644 index 0000000..10c8b9d Binary files /dev/null and b/assets/IconNuget.png differ diff --git a/demo/Fido2.Passwordless/Controllers/PasswordlessController.cs b/demo/Fido2.Passwordless/Controllers/PasswordlessController.cs index 160554e..ee2f30c 100644 --- a/demo/Fido2.Passwordless/Controllers/PasswordlessController.cs +++ b/demo/Fido2.Passwordless/Controllers/PasswordlessController.cs @@ -1,12 +1,12 @@ using Fido2.Passwordless.Models; using Fido2NetLib; -using Fido2NetLib.Development; using Fido2NetLib.Objects; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.WebUtilities; +using NetDevPack.Fido2.EntityFramework.Store.Model; using NetDevPack.Fido2.EntityFramework.Store.Store; using System.Text; using System.Text.Encodings.Web; @@ -73,7 +73,12 @@ public async Task Index(PasswordlessModel model, string returnUrl }; // 2. Verify and make the credentials - var success = await _fido2.MakeNewCredentialAsync(response, options, callback); + var credential = await _fido2.MakeNewCredentialAsync(new MakeNewCredentialParams + { + AttestationResponse = response, + OriginalOptions = options, + IsCredentialIdUniqueToUserCallback = callback + }); // 3. Store the credentials in db var user = new IdentityUser(options.User.Name) @@ -92,16 +97,7 @@ public async Task Index(PasswordlessModel model, string returnUrl Id = Encoding.UTF8.GetBytes(createdUser.Id) // byte representation of userID is required }; - _fido2Store.Store("some-random-alias", fidoUser, new StoredCredential - { - Descriptor = new PublicKeyCredentialDescriptor(success.Result.CredentialId), - PublicKey = success.Result.PublicKey, - UserHandle = success.Result.User.Id, - SignatureCounter = success.Result.Counter, - CredType = success.Result.CredType, - RegDate = DateTime.Now, - AaGuid = success.Result.Aaguid - }); + _fido2Store.Store("some-random-alias", fidoUser, StoredCredential.FromRegisteredCredential(credential, DateTime.Now)); // 5. Default ASP.NET Identity flow. (e-mail confirmation, ReturnUrl, etc.) @@ -163,9 +159,9 @@ public async Task Login(PasswordlessModel.LoginModel login, strin var options = AssertionOptions.FromJson(jsonOptions); // 2. Get registered credential from database - var creds = await _fido2Store.GetCredentialByPublicKeyIdAsync(clientResponse.Id); + var creds = await _fido2Store.GetCredentialByPublicKeyIdAsync(clientResponse.RawId); if (creds is null) - return Json(new AssertionVerificationResult { Status = "error", ErrorMessage = "Unknown Credentials" }); + return Json(new { status = "error", errorMessage = "Unknown Credentials" }); // 3. Get credential counter from database var storedCounter = creds.SignatureCounter; @@ -177,14 +173,29 @@ public async Task Login(PasswordlessModel.LoginModel login, strin return storedCreds.ToList().Exists(c => c.Descriptor.Id.SequenceEqual(args.CredentialId)); }; - // 5. Make the assertion - var res = await _fido2.MakeAssertionAsync(clientResponse, options, creds.PublicKey, storedCounter, callback); - - // 6. Store the updated counter - await _fido2Store.UpdateCounter(res.CredentialId, res.Counter); + // 5. Make the assertion. Fido2 4 throws Fido2VerificationException when the assertion is not valid + VerifyAssertionResult? res = null; + try + { + res = await _fido2.MakeAssertionAsync(new MakeAssertionParams + { + AssertionResponse = clientResponse, + OriginalOptions = options, + StoredPublicKey = creds.PublicKey, + StoredSignatureCounter = storedCounter, + IsUserHandleOwnerOfCredentialIdCallback = callback + }); + + // 6. Store the updated counter and backup state + await _fido2Store.UpdateCounter(res.CredentialId, res.SignCount, res.IsBackedUp); + } + catch (Fido2VerificationException e) + { + _logger.LogWarning(e, "Invalid assertion."); + } // Login at ASP.NET Identity - if (res.Status == "ok") + if (res is not null) { returnUrl ??= Url.Content("~/"); @@ -234,11 +245,12 @@ public async Task GetAssertionOptions([FromQuery] PasswordlessMode }; // 2. Create options - var options = _fido2.GetAssertionOptions( - existingCredentials, - UserVerificationRequirement.Discouraged, - exts - ); + var options = _fido2.GetAssertionOptions(new GetAssertionOptionsParams + { + AllowedCredentials = existingCredentials, + UserVerification = UserVerificationRequirement.Discouraged, + Extensions = exts + }); // 3. Temporarily store options, session/in-memory cache/redis/db var cookieOptions = new CookieOptions() @@ -256,7 +268,7 @@ public async Task GetAssertionOptions([FromQuery] PasswordlessMode catch (Exception e) { - return Json(new AssertionOptions { Status = "error", ErrorMessage = FormatException(e) }); + return Json(new { status = "error", errorMessage = FormatException(e) }); } } @@ -274,7 +286,7 @@ public async Task GetAttestationOptions([FromQuery] PasswordlessM // 2. Create options var authenticatorSelection = new AuthenticatorSelection { - RequireResidentKey = false, + ResidentKey = ResidentKeyRequirement.Discouraged, UserVerification = UserVerificationRequirement.Preferred }; @@ -284,7 +296,14 @@ public async Task GetAttestationOptions([FromQuery] PasswordlessM UserVerificationMethod = true, }; - var options = _fido2.RequestNewCredential(fidoUser, existingKeys.ToList(), authenticatorSelection, AttestationConveyancePreference.None, exts); + var options = _fido2.RequestNewCredential(new RequestNewCredentialParams + { + User = fidoUser, + ExcludeCredentials = existingKeys.ToList(), + AuthenticatorSelection = authenticatorSelection, + AttestationPreference = AttestationConveyancePreference.None, + Extensions = exts + }); // 3. Temporarily store options, session/in-memory cache/redis/db var cookieOptions = new CookieOptions() diff --git a/demo/Fido2.Passwordless/Controllers/UsernamelessController.cs b/demo/Fido2.Passwordless/Controllers/UsernamelessController.cs index 5b28509..98d17de 100644 --- a/demo/Fido2.Passwordless/Controllers/UsernamelessController.cs +++ b/demo/Fido2.Passwordless/Controllers/UsernamelessController.cs @@ -1,10 +1,10 @@ using Fido2.Passwordless.Models; using Fido2NetLib; -using Fido2NetLib.Development; using Fido2NetLib.Objects; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; +using NetDevPack.Fido2.EntityFramework.Store.Model; using NetDevPack.Fido2.EntityFramework.Store.Store; using NetDevPack.Utilities; using System.Text; @@ -69,7 +69,12 @@ public async Task Index(UsernamelessModel model, string returnUrl }; // 2. Verify and make the credentials - var success = await _fido2.MakeNewCredentialAsync(response, options, callback); + var credential = await _fido2.MakeNewCredentialAsync(new MakeNewCredentialParams + { + AttestationResponse = response, + OriginalOptions = options, + IsCredentialIdUniqueToUserCallback = callback + }); // 3. Store the credentials in db var user = new IdentityUser(model.DisplayName.Urlize()) @@ -88,16 +93,7 @@ public async Task Index(UsernamelessModel model, string returnUrl Id = Encoding.UTF8.GetBytes(createdUser.Id) // byte representation of userID is required }; - _fido2Store.Store("Default", fidoUser, new StoredCredential - { - Descriptor = new PublicKeyCredentialDescriptor(success.Result.CredentialId), - PublicKey = success.Result.PublicKey, - UserHandle = success.Result.User.Id, - SignatureCounter = success.Result.Counter, - CredType = success.Result.CredType, - RegDate = DateTime.Now, - AaGuid = success.Result.Aaguid - }); + _fido2Store.Store("Default", fidoUser, StoredCredential.FromRegisteredCredential(credential, DateTime.Now)); // 5. Default ASP.NET Identity flow. (No need for e-mail confirmation, since there is no e-mail involved) @@ -139,9 +135,9 @@ public async Task Login(UsernamelessModel.LoginModel login, strin var options = AssertionOptions.FromJson(jsonOptions); // 2. Get registered credential from database - var creds = await _fido2Store.GetCredentialByPublicKeyIdAsync(clientResponse.Id); + var creds = await _fido2Store.GetCredentialByPublicKeyIdAsync(clientResponse.RawId); if (creds is null) - return Json(new AssertionVerificationResult { Status = "error", ErrorMessage = "Unknown Credentials" }); + return Json(new { status = "error", errorMessage = "Unknown Credentials" }); // 3. Get credential counter from database var storedCounter = creds.SignatureCounter; @@ -153,14 +149,29 @@ public async Task Login(UsernamelessModel.LoginModel login, strin return storedCreds.ToList().Exists(c => c.Descriptor.Id.SequenceEqual(args.CredentialId)); }; - // 5. Make the assertion - var res = await _fido2.MakeAssertionAsync(clientResponse, options, creds.PublicKey, storedCounter, callback); - - // 6. Store the updated counter - await _fido2Store.UpdateCounter(res.CredentialId, res.Counter); + // 5. Make the assertion. Fido2 4 throws Fido2VerificationException when the assertion is not valid + VerifyAssertionResult? res = null; + try + { + res = await _fido2.MakeAssertionAsync(new MakeAssertionParams + { + AssertionResponse = clientResponse, + OriginalOptions = options, + StoredPublicKey = creds.PublicKey, + StoredSignatureCounter = storedCounter, + IsUserHandleOwnerOfCredentialIdCallback = callback + }); + + // 6. Store the updated counter and backup state + await _fido2Store.UpdateCounter(res.CredentialId, res.SignCount, res.IsBackedUp); + } + catch (Fido2VerificationException e) + { + _logger.LogWarning(e, "Invalid assertion."); + } // Login at ASP.NET Identity - if (res.Status == "ok") + if (res is not null) { returnUrl ??= Url.Content("~/"); @@ -204,11 +215,12 @@ public async Task GetAssertionOptions() }; // 2. Create options - var options = _fido2.GetAssertionOptions( - existingCredentials, - UserVerificationRequirement.Discouraged, - exts - ); + var options = _fido2.GetAssertionOptions(new GetAssertionOptionsParams + { + AllowedCredentials = existingCredentials, + UserVerification = UserVerificationRequirement.Discouraged, + Extensions = exts + }); // 3. Temporarily store options, session/in-memory cache/redis/db var cookieOptions = new CookieOptions() @@ -226,7 +238,7 @@ public async Task GetAssertionOptions() catch (Exception e) { - return Json(new AssertionOptions { Status = "error", ErrorMessage = FormatException(e) }); + return Json(new { status = "error", errorMessage = FormatException(e) }); } } @@ -246,7 +258,7 @@ public async Task GetAttestationOptions([FromQuery] UsernamelessM // 2. Create options var authenticatorSelection = new AuthenticatorSelection { - RequireResidentKey = true, + ResidentKey = ResidentKeyRequirement.Required, UserVerification = UserVerificationRequirement.Preferred }; @@ -256,7 +268,14 @@ public async Task GetAttestationOptions([FromQuery] UsernamelessM UserVerificationMethod = true, }; - var options = _fido2.RequestNewCredential(fidoUser, existingKeys.ToList(), authenticatorSelection, AttestationConveyancePreference.None, exts); + var options = _fido2.RequestNewCredential(new RequestNewCredentialParams + { + User = fidoUser, + ExcludeCredentials = existingKeys.ToList(), + AuthenticatorSelection = authenticatorSelection, + AttestationPreference = AttestationConveyancePreference.None, + Extensions = exts + }); // 3. Temporarily store options, session/in-memory cache/redis/db var cookieOptions = new CookieOptions() diff --git a/demo/Fido2.Passwordless/Dockerfile b/demo/Fido2.Passwordless/Dockerfile index bc1df2a..cbe0532 100644 --- a/demo/Fido2.Passwordless/Dockerfile +++ b/demo/Fido2.Passwordless/Dockerfile @@ -1,16 +1,19 @@ -#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. +# Build context is the repository root (Directory.Build.props, Directory.Packages.props, global.json): +# docker build -f demo/Fido2.Passwordless/Dockerfile . -FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base WORKDIR /app -EXPOSE 80 -EXPOSE 443 +EXPOSE 8080 +EXPOSE 8081 -FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build -WORKDIR /src -COPY ["Fido2.Passwordless/Fido2.Passwordless.csproj", "Fido2.Passwordless/"] -RUN dotnet restore "Fido2.Passwordless/Fido2.Passwordless.csproj" -COPY . . -WORKDIR "/src/Fido2.Passwordless" +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +WORKDIR /repo +COPY ["Directory.Build.props", "Directory.Packages.props", "global.json", "README.MD", "./"] +COPY ["assets/", "assets/"] +COPY ["src/", "src/"] +COPY ["demo/", "demo/"] +RUN dotnet restore "demo/Fido2.Passwordless/Fido2.Passwordless.csproj" +WORKDIR "/repo/demo/Fido2.Passwordless" RUN dotnet build "Fido2.Passwordless.csproj" -c Release -o /app/build FROM build AS publish @@ -19,4 +22,4 @@ RUN dotnet publish "Fido2.Passwordless.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . -ENTRYPOINT ["dotnet", "Fido2.Passwordless.dll"] \ No newline at end of file +ENTRYPOINT ["dotnet", "Fido2.Passwordless.dll"] diff --git a/demo/Fido2.Passwordless/Fido2.Passwordless.csproj b/demo/Fido2.Passwordless/Fido2.Passwordless.csproj index 0e2b75c..f7640c1 100644 --- a/demo/Fido2.Passwordless/Fido2.Passwordless.csproj +++ b/demo/Fido2.Passwordless/Fido2.Passwordless.csproj @@ -1,44 +1,29 @@ - + - net8.0;net10.0 + net10.0 enable enable + false Linux + ..\.. - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - + + + + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + diff --git a/demo/Fido2.Passwordless/wwwroot/js/login.passwordless.js b/demo/Fido2.Passwordless/wwwroot/js/login.passwordless.js index 0cce1a6..7e1d40c 100644 --- a/demo/Fido2.Passwordless/wwwroot/js/login.passwordless.js +++ b/demo/Fido2.Passwordless/wwwroot/js/login.passwordless.js @@ -29,7 +29,7 @@ async function handleSignInSubmit(event) { console.log("Assertion Options Object", makeAssertionOptions); // show options error to user - if (makeAssertionOptions.status !== "ok") { + if (makeAssertionOptions.status === "error") { console.log("Error creating assertion options"); console.log(makeAssertionOptions.errorMessage); showErrorAlert(makeAssertionOptions.errorMessage); diff --git a/demo/Fido2.Passwordless/wwwroot/js/login.usernameless.js b/demo/Fido2.Passwordless/wwwroot/js/login.usernameless.js index d752418..3cfbc86 100644 --- a/demo/Fido2.Passwordless/wwwroot/js/login.usernameless.js +++ b/demo/Fido2.Passwordless/wwwroot/js/login.usernameless.js @@ -21,7 +21,7 @@ async function handleSignInSubmit(event) { console.log("Assertion Options Object", makeAssertionOptions); // show options error to user - if (makeAssertionOptions.status !== "ok") { + if (makeAssertionOptions.status === "error") { console.log("Error creating assertion options"); console.log(makeAssertionOptions.errorMessage); showErrorAlert(makeAssertionOptions.errorMessage); diff --git a/demo/Fido2.Passwordless/wwwroot/js/register.passwordless.js b/demo/Fido2.Passwordless/wwwroot/js/register.passwordless.js index 99322f9..4afd912 100644 --- a/demo/Fido2.Passwordless/wwwroot/js/register.passwordless.js +++ b/demo/Fido2.Passwordless/wwwroot/js/register.passwordless.js @@ -26,7 +26,7 @@ async function handleRegisterSubmit(event) { console.log("Credential Options Object", makeCredentialOptions); - if (makeCredentialOptions.status !== "ok") { + if (makeCredentialOptions.status === "error") { console.log("Error creating credential options"); console.log(makeCredentialOptions.errorMessage); showErrorAlert(makeCredentialOptions.errorMessage); diff --git a/demo/Fido2.Passwordless/wwwroot/js/register.usernameless.js b/demo/Fido2.Passwordless/wwwroot/js/register.usernameless.js index bfc5720..8dda9a9 100644 --- a/demo/Fido2.Passwordless/wwwroot/js/register.usernameless.js +++ b/demo/Fido2.Passwordless/wwwroot/js/register.usernameless.js @@ -24,7 +24,7 @@ async function handleRegisterSubmit(event) { console.log("Credential Options Object", makeCredentialOptions); - if (makeCredentialOptions.status !== "ok") { + if (makeCredentialOptions.status === "error") { console.log("Error creating credential options"); console.log(makeCredentialOptions.errorMessage); showErrorAlert(makeCredentialOptions.errorMessage); diff --git a/global.json b/global.json new file mode 100644 index 0000000..1d364c6 --- /dev/null +++ b/global.json @@ -0,0 +1,9 @@ +{ + "sdk": { + "version": "10.0.100", + "rollForward": "latestFeature" + }, + "test": { + "runner": "Microsoft.Testing.Platform" + } +} diff --git a/src/NetDevPack.Fido2.EntityFramework.Store/Mappers/PublicKeyCredentialDescriptorMapper.cs b/src/NetDevPack.Fido2.EntityFramework.Store/Mappers/PublicKeyCredentialDescriptorMapper.cs index f9ffdf5..605ab75 100644 --- a/src/NetDevPack.Fido2.EntityFramework.Store/Mappers/PublicKeyCredentialDescriptorMapper.cs +++ b/src/NetDevPack.Fido2.EntityFramework.Store/Mappers/PublicKeyCredentialDescriptorMapper.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using Fido2NetLib; +using Fido2NetLib; using Fido2NetLib.Objects; using NetDevPack.Fido2.EntityFramework.Store.Model; @@ -8,19 +6,42 @@ namespace NetDevPack.Fido2.EntityFramework.Store.Mappers; internal static class PublicKeyCredentialDescriptorMapper { - public static Fido2NetLib.Objects.PublicKeyCredentialDescriptor ToDomain(StoredCredentialDetail model) + public static PublicKeyCredentialDescriptor ToDomain(StoredCredentialDetail model) { - var transports = string.IsNullOrWhiteSpace(model.Transports) - ? null - : model.Transports.Split(';', StringSplitOptions.RemoveEmptyEntries) - .Select(s => s.ToEnum()) - .ToArray(); + return new PublicKeyCredentialDescriptor( + model.Type ?? PublicKeyCredentialType.PublicKey, + model.PublicKeyId, + ParseTransports(model.Transports)); + } + + /// + /// Transports are stored as a ';' separated list of enum names (e.g. "Usb;Internal"). + /// Accepts enum names (any case) and WebAuthn values (e.g. "usb", "smart-card"); unknown values are ignored. + /// + internal static AuthenticatorTransport[]? ParseTransports(string? transports) + { + if (string.IsNullOrWhiteSpace(transports)) + return null; - return new PublicKeyCredentialDescriptor + var result = new List(); + foreach (var value in transports.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { - Id = model.PublicKeyId, - Transports = transports, - Type = model.Type ?? PublicKeyCredentialType.PublicKey - }; + if (Enum.TryParse(value, ignoreCase: true, out var parsed) && Enum.IsDefined(parsed)) + { + result.Add(parsed); + continue; + } + + try + { + result.Add(value.ToEnum()); + } + catch (ArgumentException) + { + // Unknown transport (e.g. added by a newer authenticator): ignore it, it is only a hint for the client. + } + } + + return result.ToArray(); } } diff --git a/src/NetDevPack.Fido2.EntityFramework.Store/Mappers/StoredCredentialMapper.cs b/src/NetDevPack.Fido2.EntityFramework.Store/Mappers/StoredCredentialMapper.cs index da202c7..4431f97 100644 --- a/src/NetDevPack.Fido2.EntityFramework.Store/Mappers/StoredCredentialMapper.cs +++ b/src/NetDevPack.Fido2.EntityFramework.Store/Mappers/StoredCredentialMapper.cs @@ -4,10 +4,10 @@ namespace NetDevPack.Fido2.EntityFramework.Store.Mappers; internal static class StoredCredentialMapper { - public static StoredCredentialDetail ToModel(Fido2NetLib.Development.StoredCredential domain) + public static StoredCredentialDetail ToModel(StoredCredential domain) { - string transports = null; - if (domain.Descriptor.Transports != null) + string? transports = null; + if (domain.Descriptor.Transports is { Length: > 0 }) transports = string.Join(";", domain.Descriptor.Transports); return new StoredCredentialDetail { @@ -18,6 +18,8 @@ public static StoredCredentialDetail ToModel(Fido2NetLib.Development.StoredCrede CredType = domain.CredType, RegDate = domain.RegDate, AaGuid = domain.AaGuid, + IsBackupEligible = domain.IsBackupEligible, + IsBackedUp = domain.IsBackedUp, PublicKeyId = domain.Descriptor.Id, Type = domain.Descriptor.Type, @@ -25,17 +27,19 @@ public static StoredCredentialDetail ToModel(Fido2NetLib.Development.StoredCrede }; } - public static Fido2NetLib.Development.StoredCredential ToDomain(StoredCredentialDetail model) + public static StoredCredential ToDomain(StoredCredentialDetail model) { - return new Fido2NetLib.Development.StoredCredential + return new StoredCredential { - UserId = model.UserId, + UserId = model.UserId ?? [], PublicKey = model.PublicKey, UserHandle = model.UserHandle, SignatureCounter = model.SignatureCounter, CredType = model.CredType, RegDate = model.RegDate, AaGuid = model.AaGuid, + IsBackupEligible = model.IsBackupEligible, + IsBackedUp = model.IsBackedUp, Descriptor = PublicKeyCredentialDescriptorMapper.ToDomain(model) }; } diff --git a/src/NetDevPack.Fido2.EntityFramework.Store/Model/StoredCredential.cs b/src/NetDevPack.Fido2.EntityFramework.Store/Model/StoredCredential.cs new file mode 100644 index 0000000..315fba3 --- /dev/null +++ b/src/NetDevPack.Fido2.EntityFramework.Store/Model/StoredCredential.cs @@ -0,0 +1,85 @@ +using Fido2NetLib.Objects; + +namespace NetDevPack.Fido2.EntityFramework.Store.Model; + +/// +/// A registered WebAuthn credential. +/// Replaces Fido2NetLib.Development.StoredCredential, which Fido2 4 no longer ships. +/// Property names match the Fido2 3 type to make the upgrade easier. +/// +public class StoredCredential +{ + /// + /// The user id () that owns the credential. + /// + public byte[] UserId { get; set; } = []; + + /// + /// Credential id, type and transports. + /// + public PublicKeyCredentialDescriptor Descriptor { get; set; } = null!; + + /// + /// The credential public key (COSE encoded). + /// + public byte[] PublicKey { get; set; } = []; + + /// + /// The user handle returned by the authenticator. + /// + public byte[] UserHandle { get; set; } = []; + + /// + /// Last known signature counter. + /// + public uint SignatureCounter { get; set; } + + /// + /// Attestation statement format (e.g. none, packed). + /// + public string? CredType { get; set; } + + /// + /// Registration date. + /// + public DateTime RegDate { get; set; } + + /// + /// Authenticator AAGUID. + /// + public Guid AaGuid { get; set; } + + /// + /// Backup Eligibility (BE) flag: the credential can be synced (e.g. a passkey). + /// + public bool IsBackupEligible { get; set; } + + /// + /// Backup State (BS) flag: the credential is currently backed up/synced. + /// + public bool IsBackedUp { get; set; } + + /// + /// Creates a from the result of IFido2.MakeNewCredentialAsync. + /// + /// The verified credential. + /// Registration date. Defaults to . + public static StoredCredential FromRegisteredCredential(RegisteredPublicKeyCredential credential, DateTime? regDate = null) + { + ArgumentNullException.ThrowIfNull(credential); + + return new StoredCredential + { + UserId = credential.User.Id, + Descriptor = new PublicKeyCredentialDescriptor(credential.Type, credential.Id, credential.Transports), + PublicKey = credential.PublicKey, + UserHandle = credential.User.Id, + SignatureCounter = credential.SignCount, + CredType = credential.AttestationFormat, + RegDate = regDate ?? DateTime.UtcNow, + AaGuid = credential.AaGuid, + IsBackupEligible = credential.IsBackupEligible, + IsBackedUp = credential.IsBackedUp + }; + } +} diff --git a/src/NetDevPack.Fido2.EntityFramework.Store/Model/StoredCredentialDetail.cs b/src/NetDevPack.Fido2.EntityFramework.Store/Model/StoredCredentialDetail.cs index d097510..8769588 100644 --- a/src/NetDevPack.Fido2.EntityFramework.Store/Model/StoredCredentialDetail.cs +++ b/src/NetDevPack.Fido2.EntityFramework.Store/Model/StoredCredentialDetail.cs @@ -39,6 +39,16 @@ public class StoredCredentialDetail public PublicKeyCredentialType? Type { get; set; } public string? Transports { get; set; } + /// + /// Backup Eligibility (BE) flag. Added in 4.0 (Fido2 4). Rows created by older versions default to false. + /// + public bool IsBackupEligible { get; set; } + + /// + /// Backup State (BS) flag. Added in 4.0 (Fido2 4). Updated on every successful assertion. + /// + public bool IsBackedUp { get; set; } + public StoredCredentialDetail UpdateUserDetails(Fido2User user) { Username = user.Name; diff --git a/src/NetDevPack.Fido2.EntityFramework.Store/NetDevPack.Fido2.EntityFramework.Store.csproj b/src/NetDevPack.Fido2.EntityFramework.Store/NetDevPack.Fido2.EntityFramework.Store.csproj index 71543b0..8267a14 100644 --- a/src/NetDevPack.Fido2.EntityFramework.Store/NetDevPack.Fido2.EntityFramework.Store.csproj +++ b/src/NetDevPack.Fido2.EntityFramework.Store/NetDevPack.Fido2.EntityFramework.Store.csproj @@ -1,41 +1,47 @@ - + - net8.0;net9.0;net10.0 + net10.0 enable enable + NetDevPack.Fido2.EntityFramework.Store Bruno Brito - https://raw.githubusercontent.com/NetDevPack/NetDevPack/master/assets/IconNuget.png - Fido2 EntityFramework EF + NetDevPack + Fido2 WebAuthn Passkeys EntityFramework EF Fido2 EntityFramework Store - Thin wrapper around Fido2 + Entity Framework Core store for the Fido2 (WebAuthn / passkeys) library, integrated with ASP.NET Core Identity. en MIT + IconNuget.png + README.MD + https://github.com/NetDevPack/Fido2.EntityFramework.Store https://github.com/NetDevPack/Fido2.EntityFramework.Store git + main + true + $(NoWarn);CS1591 + true + snupkg - + + - - - - - - + + + - - + + - - + - <_CustomFiles Include="../../.github/hooks/commit-msg" /> + <_CustomFiles Include="$(MSBuildThisFileDirectory)../../.github/hooks/commit-msg" /> - + diff --git a/src/NetDevPack.Fido2.EntityFramework.Store/Store/Fido2Store.cs b/src/NetDevPack.Fido2.EntityFramework.Store/Store/Fido2Store.cs index 4cfa3c5..0d8404f 100644 --- a/src/NetDevPack.Fido2.EntityFramework.Store/Store/Fido2Store.cs +++ b/src/NetDevPack.Fido2.EntityFramework.Store/Store/Fido2Store.cs @@ -1,5 +1,4 @@ using Fido2NetLib; -using Fido2NetLib.Development; using Fido2NetLib.Objects; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -37,7 +36,7 @@ public async Task> ListCredentialsByPublicKeyIdAsy return users.Select(StoredCredentialMapper.ToDomain); } - public async Task GetCredentialByPublicKeyIdAsync(byte[] credentialId) + public async Task GetCredentialByPublicKeyIdAsync(byte[] credentialId) { var users = await _context.Fido2StoredCredential.AsNoTrackingWithIdentityResolution().FirstOrDefaultAsync(w => w.PublicKeyId == credentialId); if (users == null) @@ -60,13 +59,15 @@ public async Task> GetCredentialsByUserHandleAsync } - public async Task UpdateCounter(byte[] credentialId, uint counter) + public async Task UpdateCounter(byte[] credentialId, uint counter, bool? isBackedUp = null) { var cred = await _context.Fido2StoredCredential.FirstOrDefaultAsync(f => f.PublicKeyId == credentialId); if (cred != null) { cred.SignatureCounter = counter; - _context.SaveChanges(); + if (isBackedUp.HasValue) + cred.IsBackedUp = isBackedUp.Value; + await _context.SaveChangesAsync(); } } diff --git a/src/NetDevPack.Fido2.EntityFramework.Store/Store/IFido2Store.cs b/src/NetDevPack.Fido2.EntityFramework.Store/Store/IFido2Store.cs index 7c83c45..d62c66a 100644 --- a/src/NetDevPack.Fido2.EntityFramework.Store/Store/IFido2Store.cs +++ b/src/NetDevPack.Fido2.EntityFramework.Store/Store/IFido2Store.cs @@ -1,5 +1,4 @@ using Fido2NetLib; -using Fido2NetLib.Development; using Fido2NetLib.Objects; using NetDevPack.Fido2.EntityFramework.Store.Model; @@ -10,11 +9,15 @@ public interface IFido2Store Task> ListCredentialsByUser(string username); Task> ListPublicKeysByUser(string username); Task> ListCredentialsByPublicKeyIdAsync(byte[] credentialId); - Task GetCredentialByPublicKeyIdAsync(byte[] credentialId); + Task GetCredentialByPublicKeyIdAsync(byte[] credentialId); void Store(string securityKeyAlias, Fido2User user, StoredCredential storedCredential); //void Store(Model.FidoInfo info, StoredCredential storedCredential); Task> GetCredentialsByUserHandleAsync(byte[] userHandle); - Task UpdateCounter(byte[] credentialId, uint counter); + /// + /// Updates the signature counter after a successful assertion and, when provided, the Backup State (BS) flag + /// returned by Fido2 4 (VerifyAssertionResult.IsBackedUp). + /// + Task UpdateCounter(byte[] credentialId, uint counter, bool? isBackedUp = null); Task GetUsernameByIdAsync(byte[] userId); Task> ListCredentialDetailsByUser(byte[] userId); Task> ListCredentialDetailsByUser(string username); diff --git a/src/NetDevPack.Fido2.sln b/src/NetDevPack.Fido2.sln index a57074c..3e80a63 100644 --- a/src/NetDevPack.Fido2.sln +++ b/src/NetDevPack.Fido2.sln @@ -9,26 +9,63 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "demo", "demo", "{EFC298AE-D EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fido2.Passwordless", "..\demo\Fido2.Passwordless\Fido2.Passwordless.csproj", "{F43AD8A2-9D4F-44F9-BC08-A7D89D189612}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetDevPack.Fido2.EntityFramework.Store.Tests", "..\tests\NetDevPack.Fido2.EntityFramework.Store.Tests\NetDevPack.Fido2.EntityFramework.Store.Tests.csproj", "{4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {A33D492B-0A7A-4C36-9A0F-1160A321E625}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A33D492B-0A7A-4C36-9A0F-1160A321E625}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A33D492B-0A7A-4C36-9A0F-1160A321E625}.Debug|x64.ActiveCfg = Debug|Any CPU + {A33D492B-0A7A-4C36-9A0F-1160A321E625}.Debug|x64.Build.0 = Debug|Any CPU + {A33D492B-0A7A-4C36-9A0F-1160A321E625}.Debug|x86.ActiveCfg = Debug|Any CPU + {A33D492B-0A7A-4C36-9A0F-1160A321E625}.Debug|x86.Build.0 = Debug|Any CPU {A33D492B-0A7A-4C36-9A0F-1160A321E625}.Release|Any CPU.ActiveCfg = Release|Any CPU {A33D492B-0A7A-4C36-9A0F-1160A321E625}.Release|Any CPU.Build.0 = Release|Any CPU + {A33D492B-0A7A-4C36-9A0F-1160A321E625}.Release|x64.ActiveCfg = Release|Any CPU + {A33D492B-0A7A-4C36-9A0F-1160A321E625}.Release|x64.Build.0 = Release|Any CPU + {A33D492B-0A7A-4C36-9A0F-1160A321E625}.Release|x86.ActiveCfg = Release|Any CPU + {A33D492B-0A7A-4C36-9A0F-1160A321E625}.Release|x86.Build.0 = Release|Any CPU {F43AD8A2-9D4F-44F9-BC08-A7D89D189612}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F43AD8A2-9D4F-44F9-BC08-A7D89D189612}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F43AD8A2-9D4F-44F9-BC08-A7D89D189612}.Debug|x64.ActiveCfg = Debug|Any CPU + {F43AD8A2-9D4F-44F9-BC08-A7D89D189612}.Debug|x64.Build.0 = Debug|Any CPU + {F43AD8A2-9D4F-44F9-BC08-A7D89D189612}.Debug|x86.ActiveCfg = Debug|Any CPU + {F43AD8A2-9D4F-44F9-BC08-A7D89D189612}.Debug|x86.Build.0 = Debug|Any CPU {F43AD8A2-9D4F-44F9-BC08-A7D89D189612}.Release|Any CPU.ActiveCfg = Release|Any CPU {F43AD8A2-9D4F-44F9-BC08-A7D89D189612}.Release|Any CPU.Build.0 = Release|Any CPU + {F43AD8A2-9D4F-44F9-BC08-A7D89D189612}.Release|x64.ActiveCfg = Release|Any CPU + {F43AD8A2-9D4F-44F9-BC08-A7D89D189612}.Release|x64.Build.0 = Release|Any CPU + {F43AD8A2-9D4F-44F9-BC08-A7D89D189612}.Release|x86.ActiveCfg = Release|Any CPU + {F43AD8A2-9D4F-44F9-BC08-A7D89D189612}.Release|x86.Build.0 = Release|Any CPU + {4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED}.Debug|x64.ActiveCfg = Debug|Any CPU + {4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED}.Debug|x64.Build.0 = Debug|Any CPU + {4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED}.Debug|x86.ActiveCfg = Debug|Any CPU + {4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED}.Debug|x86.Build.0 = Debug|Any CPU + {4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED}.Release|Any CPU.Build.0 = Release|Any CPU + {4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED}.Release|x64.ActiveCfg = Release|Any CPU + {4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED}.Release|x64.Build.0 = Release|Any CPU + {4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED}.Release|x86.ActiveCfg = Release|Any CPU + {4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {F43AD8A2-9D4F-44F9-BC08-A7D89D189612} = {EFC298AE-D56F-4B48-AF44-C41BC6FD3EF7} + {4C2B5311-EE9A-4E7B-9BC3-7F11665FB7ED} = {0AB3BF05-4346-4AA6-1389-037BE0695223} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3FCAFD34-75EB-4818-9741-90E8ACCFD268} diff --git a/tests/NetDevPack.Fido2.EntityFramework.Store.Tests/Fido2StoreTests.cs b/tests/NetDevPack.Fido2.EntityFramework.Store.Tests/Fido2StoreTests.cs new file mode 100644 index 0000000..cbeeabe --- /dev/null +++ b/tests/NetDevPack.Fido2.EntityFramework.Store.Tests/Fido2StoreTests.cs @@ -0,0 +1,205 @@ +using System.Text; +using AwesomeAssertions; +using Fido2NetLib; +using Fido2NetLib.Objects; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using NetDevPack.Fido2.EntityFramework.Store.Model; +using NetDevPack.Fido2.EntityFramework.Store.Store; +using Xunit; + +namespace NetDevPack.Fido2.EntityFramework.Store.Tests; + +public sealed class TestDbContext(DbContextOptions options) : DbContext(options), IFido2Context +{ + public DbSet Fido2StoredCredential { get; set; } = null!; +} + +/// +/// Runs against a real relational provider (SQLite in-memory), +/// so byte[] comparisons and column mappings are translated to SQL. +/// +public sealed class Fido2StoreTests : IAsyncLifetime +{ + private readonly SqliteConnection _connection = new("DataSource=:memory:"); + private ServiceProvider _provider = null!; + private AsyncServiceScope _scope; + + private IFido2Store Store => _scope.ServiceProvider.GetRequiredService(); + private TestDbContext Context => _scope.ServiceProvider.GetRequiredService(); + + public async ValueTask InitializeAsync() + { + await _connection.OpenAsync(); + + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDbContext(o => o.UseSqlite(_connection)); + services.AddFido2Context(); + _provider = services.BuildServiceProvider(); + + _scope = _provider.CreateAsyncScope(); + await Context.Database.EnsureCreatedAsync(); + } + + public async ValueTask DisposeAsync() + { + await _scope.DisposeAsync(); + await _provider.DisposeAsync(); + await _connection.DisposeAsync(); + } + + private static Fido2User User(string name) => new() + { + Name = name, + DisplayName = name, + Id = Encoding.UTF8.GetBytes(name) + }; + + private static StoredCredential Credential(Fido2User user, byte[] credentialId, uint counter = 0, params AuthenticatorTransport[] transports) => + StoredCredential.FromRegisteredCredential(new RegisteredPublicKeyCredential + { + Type = PublicKeyCredentialType.PublicKey, + Id = credentialId, + PublicKey = [1, 2, 3, 4], + Transports = transports, + SignCount = counter, + IsBackupEligible = true, + IsBackedUp = false, + AaGuid = Guid.Parse("08987058-cadc-4b81-b6e1-30de50dcbe96"), + User = user, + AttestationFormat = "none" + }, new DateTime(2026, 11, 17, 0, 0, 0, DateTimeKind.Utc)); + + [Fact] + public async Task ShouldStoreAndGetCredentialByPublicKeyId() + { + var user = User("alice@netdevpack.net"); + byte[] credentialId = [10, 20, 30]; + + Store.Store("YubiKey", user, Credential(user, credentialId, 5, AuthenticatorTransport.Usb, AuthenticatorTransport.Nfc)); + + var stored = await Store.GetCredentialByPublicKeyIdAsync(credentialId); + + stored.Should().NotBeNull(); + stored!.Descriptor.Id.Should().Equal(credentialId); + stored.Descriptor.Type.Should().Be(PublicKeyCredentialType.PublicKey); + stored.Descriptor.Transports.Should().Equal(AuthenticatorTransport.Usb, AuthenticatorTransport.Nfc); + stored.PublicKey.Should().Equal(1, 2, 3, 4); + stored.UserId.Should().Equal(user.Id); + stored.UserHandle.Should().Equal(user.Id); + stored.SignatureCounter.Should().Be(5); + stored.CredType.Should().Be("none"); + stored.AaGuid.Should().Be(Guid.Parse("08987058-cadc-4b81-b6e1-30de50dcbe96")); + stored.IsBackupEligible.Should().BeTrue(); + stored.IsBackedUp.Should().BeFalse(); + + (await Store.HasSecurityKey("YubiKey")).Should().BeTrue(); + (await Store.GetUsernameByIdAsync(user.Id)).Should().Be(user.Name); + } + + [Fact] + public async Task ShouldReturnNullWhenCredentialDoesNotExist() + { + (await Store.GetCredentialByPublicKeyIdAsync([9, 9, 9])).Should().BeNull(); + } + + [Fact] + public async Task ShouldUpdateCounterAndBackupState() + { + var user = User("bob@netdevpack.net"); + byte[] credentialId = [1, 1, 1]; + Store.Store("Phone", user, Credential(user, credentialId, 1)); + + await Store.UpdateCounter(credentialId, 42, isBackedUp: true); + + var stored = await Store.GetCredentialByPublicKeyIdAsync(credentialId); + stored!.SignatureCounter.Should().Be(42); + stored.IsBackedUp.Should().BeTrue(); + } + + [Fact] + public async Task ShouldUpdateCounterWithoutChangingBackupStateWhenNotInformed() + { + var user = User("carol@netdevpack.net"); + byte[] credentialId = [2, 2, 2]; + var credential = Credential(user, credentialId, 1); + credential.IsBackedUp = true; + Store.Store("Laptop", user, credential); + + await Store.UpdateCounter(credentialId, 7); + + var stored = await Store.GetCredentialByPublicKeyIdAsync(credentialId); + stored!.SignatureCounter.Should().Be(7); + stored.IsBackedUp.Should().BeTrue(); + } + + [Fact] + public async Task ShouldListCredentialsByUser() + { + var alice = User("alice@netdevpack.net"); + var bob = User("bob@netdevpack.net"); + Store.Store("Key 1", alice, Credential(alice, [1])); + Store.Store("Key 2", alice, Credential(alice, [2], 0, AuthenticatorTransport.Internal)); + Store.Store("Key 3", bob, Credential(bob, [3])); + + var credentials = (await Store.ListCredentialsByUser("alice@netdevpack.net")).ToList(); + credentials.Should().HaveCount(2); + credentials.Select(c => c.Descriptor.Id[0]).Should().BeEquivalentTo(new byte[] { 1, 2 }); + + var publicKeys = (await Store.ListPublicKeysByUser("alice@netdevpack.net")).ToList(); + publicKeys.Should().HaveCount(2); + + (await Store.ListCredentialDetailsByUser(alice.Id)).Should().HaveCount(2); + (await Store.ListCredentialDetailsByUser("alice@netdevpack.net")).Select(d => d.SecurityKeyName) + .Should().BeEquivalentTo("Key 1", "Key 2"); + (await Store.GetCredentialsByUserHandleAsync(bob.Id)).Should().ContainSingle(); + (await Store.ListCredentialsByPublicKeyIdAsync([3])).Should().ContainSingle(); + } + + [Fact] + public async Task ShouldRemoveCredentials() + { + var user = User("dave@netdevpack.net"); + Store.Store("Key A", user, Credential(user, [5])); + Store.Store("Key B", user, Credential(user, [6])); + + (await Store.RemoveByPublicKeyId([5])).Should().BeTrue(); + (await Store.RemoveBySecretName("Key B")).Should().BeTrue(); + (await Store.RemoveByPublicKeyId([5])).Should().BeFalse(); + + (await Store.ListCredentialsByUser("dave@netdevpack.net")).Should().BeEmpty(); + } + + [Fact] + public async Task ShouldReadRowsWrittenByPreviousVersions() + { + // A row as written by 3.x (Fido2 3): transports stored as enum names, no backup flags + Context.Fido2StoredCredential.Add(new StoredCredentialDetail + { + Username = "legacy@netdevpack.net", + UserId = Encoding.UTF8.GetBytes("legacy"), + SecurityKeyName = "Legacy", + PublicKey = [7, 7], + PublicKeyId = [7], + UserHandle = Encoding.UTF8.GetBytes("legacy"), + SignatureCounter = 3, + CredType = "packed", + RegDate = DateTime.UtcNow, + AaGuid = Guid.Empty, + Type = null, + Transports = "Usb;Internal;unknown-transport" + }); + await Context.SaveChangesAsync(); + + var stored = await Store.GetCredentialByPublicKeyIdAsync([7]); + + stored.Should().NotBeNull(); + stored!.Descriptor.Type.Should().Be(PublicKeyCredentialType.PublicKey); + stored.Descriptor.Transports.Should().Equal(AuthenticatorTransport.Usb, AuthenticatorTransport.Internal); + stored.IsBackupEligible.Should().BeFalse(); + stored.IsBackedUp.Should().BeFalse(); + stored.SignatureCounter.Should().Be(3); + } +} diff --git a/tests/NetDevPack.Fido2.EntityFramework.Store.Tests/NetDevPack.Fido2.EntityFramework.Store.Tests.csproj b/tests/NetDevPack.Fido2.EntityFramework.Store.Tests/NetDevPack.Fido2.EntityFramework.Store.Tests.csproj new file mode 100644 index 0000000..5ad8730 --- /dev/null +++ b/tests/NetDevPack.Fido2.EntityFramework.Store.Tests/NetDevPack.Fido2.EntityFramework.Store.Tests.csproj @@ -0,0 +1,23 @@ + + + + net10.0 + Exe + enable + enable + false + true + + + + + + + + + + + + + +