Building the Have I Been Pwned CLI, Part 2: From a C# command to a native executable

The C# definition of the latest command above a terminal where hibp breach latest --help prints the same description.

Suppose you run hibp breach latest and Have I Been Pwned tells you to try again in two seconds. Fair enough. The CLI can wait and ask again. Now suppose the command you ran was hibp domain verification send-email. Did the first attempt already send the email? Suddenly that same little retry loop looks like a questionable idea.

In Part 1 we used the CLI to turn a breach lookup into a report. This time let's follow that lookup through the C# code. Along the way we'll see where we make the retry decision and how the same project produces a native executable for six different targets.

Where did the HTTP call go?

We build the command tree with System.CommandLine. The root has a breach command, and under that sit list, get and latest. Each has its own Create method. Here's the whole method for latest.

public static Command Create(CliServices services)
{
    var command = new Command("latest", "Get the most recently added breach.");
    return ApiCommand.Bind(command, services, _ => new(ApiOperations.BreachLatest));
}

That description is the one you see when you run hibp breach latest --help. The underscore is a small clue about the command. It takes no arguments, so it can build the same request for every invocation. Its sibling get registers a name argument and passes result.GetValue(value) along with ApiOperations.BreachGet. That's the difference between asking for the latest breach and asking for Adobe.

The operation itself is a C# record. Here's the declaration for the latest breach, which gives the client the operation ID, HTTP method, relative API path and whether it needs an API key.

public static readonly ApiOperation BreachLatest =
    new("getLatestBreach", HttpMethod.Get, "latestbreach", false);

That last false means the HTTP client can go straight to the public API. An authenticated operation goes through the credential resolver first. The command never has to handle the key, and hibp breach latest works on a machine that's never had one.

One handler for the ordinary API commands

Program.cs creates an HttpClient, the credential resolver and a CliServices object with the output and error writers. We pass those dependencies into the tree explicitly. A test can give the CLI an HTTP handler that returns a particular response and two writers that capture what a script would see.

ApiCommand.Bind registers the common output options and attaches the action to the command. These four lines inside that action are the path from parsed arguments to an exit code.

var settings = output.Read(result);
var apiRequest = request(result);
using var response = await services.Api.SendAsync(apiRequest, cancellationToken);
return await ResultWriter.WriteAsync(response, apiRequest, settings, services.Output, cancellationToken);

The order matters. Try giving the command both output formats in PowerShell. You can reproduce this one with your network disconnected.

hibp breach latest --json --markdown
$LASTEXITCODE
Choose either --json or --markdown, not both.
2

output.Read catches the conflict before the HTTP call. The diagnostic goes to stderr and stdout stays empty. For a valid invocation, the default JSON path copies the API response through to the caller. If HIBP adds a field tomorrow, a script can read it immediately. Ask for Markdown and the writer parses the record so it can lay out the dates, account count and exposed data classes.

When do we try again?

Let's go back to the SendAsync line in the handler. What does it do if the service asks us to slow down? The HTTP client makes a fresh HttpRequestMessage for each attempt. For an ordinary GET, four response codes can trigger another attempt (429, 502, 503 and 504). Here's where the client decides whether to wait.

if (operation.Method == HttpMethod.Get && retryable && attempt < MaximumRetries && delay <= s_maximumDelay)
{
    response.Dispose();
    await Task.Delay(delay, cancellationToken);
    continue;
}

We allow two retries, so the service sees at most three requests. We use Retry-After when the service supplies it, accepting either a duration or an HTTP date. Without that header the waits are one second and then two. The 30-second limit in that condition is easy to misread. If HIBP says to come back in an hour, the CLI reports the rate limit and exits with code 5. Waking up after 30 seconds and sending the same request would just ignore what the server told us.

The method check answers the email question we started with. A verification POST can have a side effect even if the caller receives a 503. We give the caller the failure and leave the decision to send another email to them. The same policy applies to the DELETE that removes a monitored domain.

We test this without making anyone wait an hour or sending an email. One test makes the HTTP handler return 429 with Retry-After: 3600, then checks the exit code and counts exactly one request. Another returns 503 for the verification email command and checks that the handler saw a single POST. Counting calls catches a bug that an exit-code assertion alone would miss.

The cancellation token also goes into the delay, the HTTP call and the result writer. Ordinary API commands get a 120-second deadline for the whole operation. A retry doesn't restart the clock. Ctrl+C exits with 130, while a timeout exits with 6. The bulk password downloader has its own retry policy because a full corpus download can legitimately take much longer.

Getting the JSON code ready for Native AOT

So far we've been able to exercise the command with a test HTTP handler and a couple of text writers. What happens when we put that same C# program on someone's machine? One reason we chose .NET is that we can publish a native executable for a particular operating system and processor. Once it's there, you can run hibp without first installing a .NET runtime. If you're weighing that choice for your own CLI, Microsoft's Native AOT deployment guide explains what gets compiled ahead of time and which runtime features that choice rules out.

For our CLI, one place that choice shows up is the JSON we write to stdout. Take a look at the trimming settings and the last line in this excerpt from the project file.

<TargetFramework>net11.0</TargetFramework>
<PublishAot>true</PublishAot>
<PublishTrimmed Condition="'$(PublishAot)' == 'true'">true</PublishTrimmed>
<TrimMode Condition="'$(PublishAot)' == 'true'">full</TrimMode>
<IsAotCompatible>true</IsAotCompatible>
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>

For our native builds we use full trimming. At publish time the toolchain follows the calls the program can make and removes unused code, including code in our dependencies. The awkward case is a library that looks up a property by name at runtime. How does the trimmer know that a getter nobody calls directly still needs to end up in the executable? If you hit a warning like that, Microsoft's guidance on fixing trim warnings walks through how to find the reflection call and decide what the trimmer needs to know.

For hibp password check, we already know the answer at build time. The CLI creates a PasswordCheckResult with a Found flag and a Count. We register that type on our JsonSerializerContext using [JsonSerializable(typeof(PasswordCheckResult))]. The source generator then produces the metadata we pass to the serializer here.

public string ExportJson() =>
    JsonSerializer.Serialize(this, CliJsonContext.Default.PasswordCheckResult);

The second argument is the important bit. We tell the serializer exactly which generated metadata to use. Disabling its reflection fallback also exercises that decision during ordinary development. If you add a new result type, you can discover a missing registration well before someone installs the native package.

We control that serialization code ourselves. Bring in a package and the trimmer also has to follow the calls we make into someone else's code, including any dependencies the package brings along. That's why we try to keep the package list short. Think back to the retry loop. HttpClient gives us the response, Retry-After tells us how long to wait, and Task.Delay already accepts our cancellation token. What would another package need to add there?

There are two explicit package references in the CLI project. System.CommandLine gives us the parser and help output you saw earlier. NuGet.Versioning earns its place in the update check. Given preview.2 and preview.10 of the same version, a plain string comparison puts them in the wrong order. Using NuGet's own comparison rules means we can tell you which release is newer without maintaining our own version parser.

How does NuGet know which executable to install?

Now let's look at NuGet from the other end. Someone installing the CLI shouldn't have to work out which of our six native builds to download. We set PackAsTool to true and ToolCommandName to hibp, so everyone with .NET SDK 10 or later can use the same two commands to install the preview and see the help text we started with.

dotnet tool install --global HaveIBeenPwned.Cli --prerelease
hibp breach latest --help

Behind that one install command is a small pointer package and a set of implementation packages. The SDK selects the package for the machine doing the installation. We build x64 and Arm64 executables for Windows, glibc-based Linux and macOS. There's also an any package with a managed build that runs on .NET 11. The SDK handles installation. Once installed, the native build carries what it needs from .NET.

There's one practical limit to that install command. The native hibp executable can run on its own, but you still need an SDK to run dotnet tool install. If we want to reach someone who doesn't have the SDK, we could distribute those same binaries another way. A WinGet manifest could point Windows users at a versioned release, and macOS and Linux users could download an archive with a published checksum.

For the NuGet packages we ship today, we can check the whole trip in CI. We install the freshly built tool into a temporary directory and invoke hibp password download --help. Seeing that nested command's help text tells us NuGet selected a package the runner could actually execute and System.CommandLine found the command inside it. That's a handy check without having to download a million hash ranges.

Of course, printing the help for password download is the easy part. What happens when we actually ask it to write those ranges to disk? That's where we'll pick up in Part 3, with the C# buffers, the allocations we could get rid of, and the measurements that tell us whether we're waiting on the CPU, the network or the disk. Hope this helps!

Mastodon