Skip to content

Commit

Permalink
Half-day of learning updates
Browse files Browse the repository at this point in the history
  • Loading branch information
IEvangelist committed Sep 1, 2021
1 parent 383f4b0 commit f52e1b0
Show file tree
Hide file tree
Showing 14 changed files with 301 additions and 50 deletions.
94 changes: 90 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,99 @@
# Have I Been Pwned? — .NET Client
# ![';-- have i been pwned? — .NET HTTP Client logo.](https://raw.githubusercontent.com/IEvangelist/pwned-client/main/assets/pwned-header.png)

[![build](https://github.com/IEvangelist/pwned-client/actions/workflows/build-validation.yml/badge.svg)](https://github.com/IEvangelist/pwned-client/actions/workflows/build-validation.yml) [![code analysis](https://github.com/IEvangelist/pwned-client/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/IEvangelist/pwned-client/actions/workflows/codeql-analysis.yml)
[![build](https://github.com/IEvangelist/pwned-client/actions/workflows/build-validation.yml/badge.svg)](https://github.com/IEvangelist/pwned-client/actions/workflows/build-validation.yml) [![code analysis](https://github.com/IEvangelist/pwned-client/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/IEvangelist/pwned-client/actions/workflows/codeql-analysis.yml) [![NuGet](https://img.shields.io/nuget/v/HaveIBeenPwned.Client.svg?style=flat)](https://www.nuget.org/packages/HaveIBeenPwned.Client)

A .NET HTTP client for the "Have I Been Pwned" API
A .NET HTTP client for the "Have I Been Pwned" API.

## Get started

Install from the .NET CLI:

```shell
dotnet add package HaveIBeenPwned.Client
```

Alternatively add manually to your consuming _.csproj_:

```xml
<PackageReference Include="HaveIBeenPwned.Client" Version="{VersionNumber}" />
```

Or, install using the NuGet Package Manager:

```powershell
Install-Package HaveIBeenPwned.Client
```

### Dependency injection

To add all of the services to the dependency injection container, call one of the `AddPwnedServices` overloads. From Minimal APIs for example, with using a named configuration section:

```csharp
builder.Services.AddPwnedServices(
builder.Configuration.GetSection(nameof(HibpOptions)));
```

From a `ConfigureServices` method, with an `IConfiguration` instance:

```csharp
services.AddPwnedServices(options =>
{
options.ApiKey = _configuration["HibpOptions:ApiKey"];
options.UserAgent = _configuration["HibpOptions:UserAgent"];
});
```

Then you can require any of the available DI-ready types:

- `IPwnedBreachesClient`: [Breaches API](https://haveibeenpwned.com/API/v3#BreachesForAccount).
- `IPwnedPastesClient`: [Pastes API](https://haveibeenpwned.com/API/v3#PastesForAccount).
- `IPwnedPasswordsClient`: [Pwned Passwords API](https://haveibeenpwned.com/API/v3#PwnedPasswords).
- `IPwnedClient`: Marker interface, for conveniently injecting all of the above clients into a single client.

### Example Minimal APIs

![Minimal APIs example code.](https://raw.githubusercontent.com/IEvangelist/pwned-client/main/assets/minimal-api.svg)

## Configuration

To configure the `HaveIBeenPwned.Client`, the following table identifies the well-known configuration object:

### Well-known keys

Depending on the [.NET configuration provider](https://docs.microsoft.com/dotnet/core/extensions/configuration-providers?WC.m_id=dapine) your app is using, there are several well-known keys that map to the `HibpOptions` that configure your usage of the HTTP client. When using environment variables, such as those in Azure App Service configuration or Azure Key Vault secrets, the following keys map to the `HibpOption` instance:

| Key | Data type | Default value |
|--------------------------|-----------|--------------------------|
| `HibpOptions__ApiKey` | `string` | `null` |
| `HibpOptions__UserAgent` | `string` | `".NET HIBP Client/1.0"` |

The `ApiKey` is required, to get one &mdash; sign up here: <https://haveibeenpwned.com/api/key>

### Example `appsettings.json`

```json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"HibpOptions": {
"ApiKey": "<YourApiKey>",
"UserAgent": "<YourUserAgent>"
}
}
```

For more information, see [JSON configuration provider](https://docs.microsoft.com/dotnet/core/extensions/configuration-providers?WC.m_id=dapine#json-configuration-provider).

<!--
Notes for tagging releases:
https://rehansaeed.com/the-easiest-way-to-version-nuget-packages/#minver
git tag -a 0.0.3 -m "Build version 0.0.3"
git push upstream --tags
-->
-->
Binary file added assets/logo.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
27 changes: 27 additions & 0 deletions assets/minimal-api.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/pwned-header.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/pwned-logo-small.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/pwned-logo.ico
Binary file not shown.
Binary file added assets/pwned-logo.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
27 changes: 27 additions & 0 deletions assets/pwned-logo.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions src/HaveIBeenPwned.Client/DefaultPwnedClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,8 +235,8 @@ async Task<PwnedPassword> IPwnedPasswordsClient.GetPwnedPasswordAsync(string pla
.Replace('\r', '\0')
.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
return pair?.Length != 2 || !int.TryParse(pair[1], out var count)
? (Hash: "", Count: 0, IsValid: false)
return pair?.Length != 2 || !long.TryParse(pair[1], out var count)
? (Hash: "", Count: 0L, IsValid: false)
: (Hash: pair[0], Count: count, IsValid: true);
})
.Where(t => t.IsValid)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright (c) David Pine. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Linq;
using System.Threading.Tasks;

namespace HaveIBeenPwned.Client.Extensions
{
/// <summary></summary>
public static class PwnedPasswordsClientExtensions
{
/// <summary>
/// An extension method that evaluates whether the <paramref name="plainTextPassword"/> is "pwned".
/// When <c>true</c>, the <c>Count</c> is at least <c>1</c>.
/// </summary>
/// <param name="pwnedPasswordsClient"></param>
/// <param name="plainTextPassword"></param>
/// <returns>
/// <list type="bullet">
/// <item>
/// When the given <paramref name="plainTextPassword"/> is "pwned", returns <c>(true, 3)</c> when "pwned" three times.
/// </item>
/// <item>
/// When the given <paramref name="plainTextPassword"/> <strong>isn't</strong> "pwned", this could return <c>(false, 0)</c>.
/// </item>
/// <item>
/// When unable to determine, returns <c>(null, null)</c>.
/// </item>
/// </list>
/// </returns>
public static async ValueTask<(bool? IsPwned, long? Count)> IsPasswordPwnedAsync(
this IPwnedPasswordsClient pwnedPasswordsClient, string plainTextPassword)
{
var pwnedPassword = await pwnedPasswordsClient.GetPwnedPasswordAsync(plainTextPassword);

return
(
IsPwned: pwnedPassword.IsPwned ?? false,
Count: pwnedPassword.PwnedCount
);
}

/// <summary>
/// An extension method that evaluates whether the <paramref name="account"/> is part of a breach.
/// When <c>true</c>, the <c>Breaches</c> has at least one breach name.
/// </summary>
/// <param name="pwnedBreachesClient"></param>
/// <param name="account"></param>
/// <returns>
/// <list type="bullet">
/// <item>
/// When the given <paramref name="account"/> is part of a breach, returns
/// <c>(true, ["Adobe", "LinkedIn"])</c> when the found in the Adobe and LinkedIn breaches.
/// </item>
/// <item>
/// When the given <paramref name="account"/> <strong>isn't</strong> part of a breach, returns <c>(false, [])</c>.
/// </item>
/// <item>
/// When unable to determine, returns <c>(null, null)</c>.
/// </item>
/// </list>
/// </returns>
public static async ValueTask<(bool? IsBreached, string[]? Breaches)> IsBreachedAccountAsync(
this IPwnedBreachesClient pwnedBreachesClient, string account)
{
if (string.IsNullOrWhiteSpace(account))
{
return (null, null);
}

var breaches = await pwnedBreachesClient.GetBreachHeadersForAccountAsync(account);

return
(
IsBreached: breaches is { Length: > 0 },
Breaches: breaches?.Select(breach => breach.Name)?.ToArray() ?? Array.Empty<string>()
);
}
}
}
57 changes: 31 additions & 26 deletions src/HaveIBeenPwned.Client/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
// Licensed under the MIT License.

using System;
using System.Net.Http;
using System.Net.Mime;
using HaveIBeenPwned.Client;
using HaveIBeenPwned.Client.Http;
using HaveIBeenPwned.Client.Options;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Polly;

namespace Microsoft.Extensions.DependencyInjection
{
Expand All @@ -21,12 +23,15 @@ public static class ServiceCollectionExtensions
/// </summary>
/// <param name="services">The service collection to add services to.</param>
/// <param name="namedConfigurationSection">The name configuration section to bind options from.</param>
/// <param name="configureRetryPolicy">The (optional) rety policy configuration function, when provided adds transient HTTP error policy.</param>
/// <returns>The same <paramref name="services"/> instance with other services added.</returns>
/// <exception cref="ArgumentNullException">
/// If either the <paramref name="services"/> or <paramref name="namedConfigurationSection"/> are <c>null</c>.
/// </exception>
public static IServiceCollection AddPwnedServices(
this IServiceCollection services, IConfiguration namedConfigurationSection)
this IServiceCollection services,
IConfiguration namedConfigurationSection,
Func<PolicyBuilder<HttpResponseMessage>, IAsyncPolicy<HttpResponseMessage>>? configureRetryPolicy = default)
{
if (services is null)
{
Expand All @@ -40,27 +45,9 @@ public static class ServiceCollectionExtensions
nameof(namedConfigurationSection), "The IConfiguration cannot be null.");
}

services.AddLogging();
services.AddOptions<HibpOptions>();
services.Configure<HibpOptions>(namedConfigurationSection);

AddPwnedHttpClient(
services,
HttpClientNames.HibpClient,
HttpClientUrls.HibpApiUrl);

AddPwnedHttpClient(
services,
HttpClientNames.PasswordsClient,
HttpClientUrls.PasswordsApiUrl,
isPlainText: true);

services.AddSingleton<IPwnedBreachesClient, DefaultPwnedClient>();
services.AddSingleton<IPwnedPasswordsClient, DefaultPwnedClient>();
services.AddSingleton<IPwnedPastesClient, DefaultPwnedClient>();
services.AddSingleton<IPwnedClient, DefaultPwnedClient>();

return services;
return AddPwnedServices(services, configureRetryPolicy);
}

/// <summary>
Expand All @@ -69,12 +56,15 @@ public static class ServiceCollectionExtensions
/// </summary>
/// <param name="services">The service collection to add services to.</param>
/// <param name="configureOptions">The action used to configure options.</param>
/// <param name="configureRetryPolicy">The (optional) retry policy configuration function, when provided adds transient HTTP error policy.</param>
/// <returns>The same <paramref name="services"/> instance with other services added.</returns>
/// <exception cref="ArgumentNullException">
/// If either the <paramref name="services"/> or <paramref name="configureOptions"/> are <c>null</c>.
/// </exception>
public static IServiceCollection AddPwnedServices(
this IServiceCollection services, Action<HibpOptions> configureOptions)
this IServiceCollection services,
Action<HibpOptions> configureOptions,
Func<PolicyBuilder<HttpResponseMessage>, IAsyncPolicy<HttpResponseMessage>>? configureRetryPolicy = default)
{
if (services is null)
{
Expand All @@ -88,20 +78,28 @@ public static class ServiceCollectionExtensions
nameof(configureOptions), "The Action<HibpOptions> cannot be null.");
}

services.Configure(configureOptions);

return AddPwnedServices(services, configureRetryPolicy);
}

static IServiceCollection AddPwnedServices(
IServiceCollection services,
Func<PolicyBuilder<HttpResponseMessage>, IAsyncPolicy<HttpResponseMessage>>? configureRetryPolicy)
{
services.AddLogging();
services.AddOptions<HibpOptions>();
services.Configure(configureOptions);

AddPwnedHttpClient(
_ = AddPwnedHttpClient(
services,
HttpClientNames.HibpClient,
HttpClientUrls.HibpApiUrl);
HttpClientUrls.HibpApiUrl).TryAddTransientHttpErrorPolicy(configureRetryPolicy);

AddPwnedHttpClient(
_ = AddPwnedHttpClient(
services,
HttpClientNames.PasswordsClient,
HttpClientUrls.PasswordsApiUrl,
isPlainText: true);
isPlainText: true).TryAddTransientHttpErrorPolicy(configureRetryPolicy);

services.AddSingleton<IPwnedBreachesClient, DefaultPwnedClient>();
services.AddSingleton<IPwnedPasswordsClient, DefaultPwnedClient>();
Expand Down Expand Up @@ -135,5 +133,12 @@ public static class ServiceCollectionExtensions
new(MediaTypeNames.Text.Plain));
}
});

static IHttpClientBuilder TryAddTransientHttpErrorPolicy(
this IHttpClientBuilder httpClientBuilder,
Func<PolicyBuilder<HttpResponseMessage>, IAsyncPolicy<HttpResponseMessage>>? configureRetryPolicy = default) =>
configureRetryPolicy is not null
? httpClientBuilder.AddTransientHttpErrorPolicy(configureRetryPolicy)
: httpClientBuilder;
}
}
29 changes: 17 additions & 12 deletions src/HaveIBeenPwned.Client/HaveIBeenPwned.Client.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<Version Condition=" '$(VersionSuffix)' == '' ">$(ClientVersion)</Version>
<Version Condition=" '$(VersionSuffix)' != '' ">$(ClientVersion)-$(VersionSuffix)</Version>
<FileVersion>$(ClientVersion)</FileVersion>
<Authors>IEvangelist</Authors>
<Authors>David Pine</Authors>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AssemblyName>HaveIBeenPwned.Client</AssemblyName>
<Title>Have I Been Pwned .NET HTTP client library</Title>
Expand All @@ -30,23 +30,33 @@
<PlatformTarget>AnyCPU</PlatformTarget>
<ShippingScope>External</ShippingScope>
<SigningType>Product</SigningType>
<DebugType>portable</DebugType>
<DebugType>embedded</DebugType>
<IncludeSymbols>false</IncludeSymbols>
<IncludeSource>false</IncludeSource>
<RootNamespace>HaveIBeenPwned.Client</RootNamespace>
<NoWarn>NU5125</NoWarn>
<NoWarn>NU5125;NU5039</NoWarn>
<Optimize Condition="'$(Configuration)'=='Release'">true</Optimize>
<RepositoryUrl>https://github.com/IEvangelist/pwned-client</RepositoryUrl>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<RepositoryType>git</RepositoryType>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
<PackageReadmeFile>README.md</PackageReadmeFile>
<IsPackable>true</IsPackable>
<PackageIcon>logo.png</PackageIcon>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="MinVer" Version="2.5.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand All @@ -59,14 +69,9 @@
</ItemGroup>

<ItemGroup>
<None Include="..\..\LICENSE">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
<None Include="..\..\README.md">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
<None Include="..\..\LICENSE" Pack="true" PackagePath="" />
<None Include="..\..\README.md" Pack="true" PackagePath="" />
<None Include="..\..\assets\logo.png" Pack="true" PackagePath="" />
</ItemGroup>

</Project>
4 changes: 2 additions & 2 deletions src/HaveIBeenPwned.Client/Models/PwnedPassword.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ namespace HaveIBeenPwned.Client.Models
/// <summary></summary>
public record PwnedPassword(
string? PlainTextPassword,
bool IsPwned = false,
int PwnedCount = -1,
bool? IsPwned = default,
long PwnedCount = -1,
string? HashedPassword = default)
{
internal bool IsInvalid() =>
Expand Down

0 comments on commit f52e1b0

Please sign in to comment.