Security Playbook

Agents paste API keys into appsettings.json. Make that fail the build, and make the app refuse to start without the real one

A 90-line xUnit scanner, a startup check and one user-secrets command that keep agent-written ASP.NET Core code from committing credentials. About 15 minutes to try, and it works with any agent.

A cracked glass vial in dark water with a thread of gold ink seeping out and spreading in soft plumes.

An agent is asked to wire up a payments client. The API key isn’t set anywhere on the machine yet, the app throws on startup, and the quickest way to a green run is to paste a key into appsettings.Development.json. The agent does exactly that. The diff is small, the tests pass, and the commit goes through. The file now sits in git history with a live credential in it.

Nothing in that sequence is malicious. The agent optimised for “the app runs”, and the config file was the nearest place a value could live. A line in an instructions file saying “never commit secrets” helps, but it’s a request, and a long session or a different agent can ignore it. A failing test can’t be ignored.

This Playbook builds three small pieces for an ASP.NET Core project on .NET 10. A scanner test fails the build when a committed appsettings*.json file holds something that looks like a credential. A startup check makes the app refuse to boot without the real key, so there’s never a reason to paste one in to “see it work”. And user-secrets plus environment variables give both the agent and the human a legitimate place for the value to live. Total setup is about 15 minutes, none of it depends on a particular agent, and the failure messages never print the secret they found.

The three pieces and what each one stops

Each piece covers a gap the others leave.

The startup check removes the motive. If the app fails with a clear message naming the missing key, the agent’s next step is to supply the key, and the question becomes where. The scanner closes the obvious answer. If the agent writes the value into a committed file, the build fails and the failure message says where it should have gone instead. User-secrets and environment variables are the places the message points to.

Order matters in practice. The scanner on its own gets “fixed” by an agent that deletes the test or loosens a pattern, which is why it should be paired with a rule in the project’s instructions file and a required CI check (more on that under the failure modes). The startup check on its own stops nothing, because it tells nobody where the value should go.

Step 1: bind the secret to an options class that validates on start

Start with the payments settings as a typed options class. [Required] and [MinLength] are what turn “the key is missing” into an error at boot instead of a 401 on the first customer request.

using System.ComponentModel.DataAnnotations;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddOptions<PaymentsOptions>()
    .BindConfiguration(PaymentsOptions.SectionName)
    .ValidateDataAnnotations()
    .ValidateOnStart();

var app = builder.Build();

app.MapGet("/payments/status", (Microsoft.Extensions.Options.IOptions<PaymentsOptions> options) =>
    new { configured = true, baseUrl = options.Value.BaseUrl });

app.Run();

public sealed class PaymentsOptions
{
    public const string SectionName = "Payments";

    [Required, Url]
    public string BaseUrl { get; set; } = "";

    [Required, MinLength(20)]
    public string ApiKey { get; set; } = "";
}

public partial class Program;

Two details matter here. ValidateOnStart is what moves validation to startup, because the Microsoft options documentation says validation otherwise happens at runtime. And the endpoint returns the base URL and a flag, never the key, so there’s no pattern for the agent to copy that echoes a secret back to a caller. The empty public partial class Program; at the bottom exposes the entry point to the test project.

The committed appsettings.json holds the non-secret half of the section and nothing else:

{
  "Logging": { "LogLevel": { "Default": "Information" } },
  "AllowedHosts": "*",
  "ConnectionStrings": { "Shop": "Server=(localdb)\\mssqllocaldb;Database=Shop;Trusted_Connection=True" },
  "Payments": { "BaseUrl": "https://api.payments.example/v2" }
}

The connection string is the LocalDB one from the template: no password, so nothing to hide. A connection string with a password in it is the case the scanner has to catch.

Step 2: the scanner

The scanner walks every string in a JSON file and flags three things: a value shaped like a vendor key, a password inside a connection string, and a literal value under a key whose name says it’s a secret. It reports the file, the configuration path and a masked value, never the full value, because test output ends up in CI logs that more people can read than the repo.

using System.Text.Json;
using System.Text.RegularExpressions;

namespace Shop.Api.Tests;

public sealed record Finding(string File, string Path, string Reason, string Masked);

public static partial class ConfigSecretScanner
{
    [GeneratedRegex("password|pwd|secret|apikey|api_key|accesskey|privatekey|token", RegexOptions.IgnoreCase)]
    private static partial Regex SecretKeyName();

    [GeneratedRegex(@"(^|;)\s*(password|pwd|accountkey|sharedaccesskey)\s*=\s*[^;\s]+", RegexOptions.IgnoreCase)]
    private static partial Regex PasswordInConnectionString();

    [GeneratedRegex(@"^(sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{30,}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,})$")]
    private static partial Regex KnownKeyShape();

    public static IReadOnlyList<Finding> Scan(string file, string json)
    {
        var findings = new List<Finding>();
        using var doc = JsonDocument.Parse(json, new JsonDocumentOptions
        {
            CommentHandling = JsonCommentHandling.Skip,
            AllowTrailingCommas = true
        });
        Walk(doc.RootElement, "", file, findings);
        return findings;
    }

    private static void Walk(JsonElement el, string path, string file, List<Finding> findings)
    {
        switch (el.ValueKind)
        {
            case JsonValueKind.Object:
                foreach (var p in el.EnumerateObject())
                    Walk(p.Value, path.Length == 0 ? p.Name : path + ":" + p.Name, file, findings);
                break;
            case JsonValueKind.Array:
                var i = 0;
                foreach (var item in el.EnumerateArray())
                    Walk(item, $"{path}:{i++}", file, findings);
                break;
            case JsonValueKind.String:
                Check(el.GetString() ?? "", path, file, findings);
                break;
        }
    }

    private static void Check(string value, string path, string file, List<Finding> findings)
    {
        if (value.Length == 0 || IsPlaceholder(value)) return;
        var leaf = path[(path.LastIndexOf(':') + 1)..];

        if (KnownKeyShape().IsMatch(value))
            findings.Add(new(file, path, "value has the shape of a vendor key", Mask(value)));
        else if (PasswordInConnectionString().IsMatch(value))
            findings.Add(new(file, path, "password inside a connection string", Mask(value)));
        else if (SecretKeyName().IsMatch(leaf))
            findings.Add(new(file, path, "secret-like key name has a literal value", Mask(value)));
    }

    private static bool IsPlaceholder(string v) =>
        v.StartsWith("<") || v.StartsWith("${") || v.StartsWith("#{")
        || v.Equals("set-by-user-secrets", StringComparison.Ordinal);

    private static string Mask(string v) => v.Length <= 4 ? "****" : $"{v[..2]}... ({v.Length} chars)";
}

A few choices are deliberate. Connection strings are checked only for an embedded Password=, Pwd=, AccountKey= or SharedAccessKey=, so a trusted-connection string passes. Placeholders such as <set me> and ${DB_PASSWORD} pass, because a template that documents where a value goes is the behaviour you want. The key-name rule is the weakest of the three, and it’s there for the case where an agent invents a key format the shape regex has never seen. It’s also the rule that produces false positives (a TokenLifetime string like "00:30:00" would trip it), which is why the placeholder escape exists.

Step 3: the tests that wire it into the build

Three tests. The first scans the committed config, the second proves the app won’t start without the key, and the third proves it starts when the key arrives from configuration and doesn’t echo it.

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Options;

namespace Shop.Api.Tests;

public class ConfigGateTests
{
    private static string RepoRoot()
    {
        var dir = new DirectoryInfo(AppContext.BaseDirectory);
        while (dir is not null && !Directory.Exists(Path.Combine(dir.FullName, ".git")))
            dir = dir.Parent;
        return dir?.FullName ?? throw new InvalidOperationException("No .git directory above the test binary.");
    }

    [Fact]
    public void Committed_appsettings_files_contain_no_secrets()
    {
        var root = RepoRoot();
        var files = Directory.EnumerateFiles(Path.Combine(root, "src"), "appsettings*.json", SearchOption.AllDirectories)
            .Where(f => !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}")
                     && !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}"));

        var findings = files
            .SelectMany(f => ConfigSecretScanner.Scan(Path.GetRelativePath(root, f), File.ReadAllText(f)))
            .ToList();

        Assert.True(findings.Count == 0,
            "Secrets in committed config. Move each to user-secrets or an environment variable "
            + "(Section__Key) and leave the key out of the file:\n"
            + string.Join("\n", findings.Select(f => $"  {f.File} [{f.Path}] {f.Reason}, value {f.Masked}")));
    }

    [Fact]
    public void App_refuses_to_start_without_the_payments_api_key()
    {
        // Production: no appsettings.Development.json and no user-secrets, whatever is on this machine.
        using var factory = new WebApplicationFactory<Program>()
            .WithWebHostBuilder(b => b.UseEnvironment("Production"));
        var ex = Assert.Throws<OptionsValidationException>(() => factory.CreateClient());
        Assert.Contains(ex.Failures, f => f.Contains("ApiKey"));
    }

    [Fact]
    public async Task App_starts_when_the_key_comes_from_the_environment_shaped_config()
    {
        using var factory = new WebApplicationFactory<Program>().WithWebHostBuilder(b =>
            b.UseSetting("Payments:ApiKey", "test-key-0123456789-abcdef"));
        var body = await factory.CreateClient().GetStringAsync("/payments/status");
        Assert.DoesNotContain("test-key", body);
        Assert.Contains("\"configured\":true", body);
    }
}

The failure message is written for the agent as much as for the human. When the test fails inside an agent loop, the output is what the agent reads, so it names the fix (“user-secrets or an environment variable”) and the Section__Key naming that environment variables need.

The test project needs Microsoft.AspNetCore.Mvc.Testing, and the version has to match the SDK. A bare dotnet add package pulled a version the .NET 10 project rejected as incompatible with every framework, so pin it:

dotnet add tests/Shop.Api.Tests package Microsoft.AspNetCore.Mvc.Testing --version 10.0.0
dotnet test tests/Shop.Api.Tests

On a clean tree it prints:

Passed!  - Failed:     0, Passed:     3, Skipped:     0, Total:     3, Duration: 279 ms - Shop.Api.Tests.dll (net10.0)

Step 4: watch it catch the agent

Reproduce the scenario from the opening. This is what the agent leaves behind in appsettings.Development.json:

{
  "Logging": { "LogLevel": { "Default": "Debug" } },
  "Payments": { "ApiKey": "sk-live-9fA2kQ7xLm3VbN8cT1dW" },
  "ConnectionStrings": { "Shop": "Server=db.internal;Database=Shop;User Id=shop;Password=Hunter2!pw" }
}

Run dotnet test and the scanner fails the build:

Failed Shop.Api.Tests.ConfigGateTests.Committed_appsettings_files_contain_no_secrets [11 ms]
  Error Message:
   Secrets in committed config. Move each to user-secrets or an environment variable (Section__Key) and leave the key out of the file:
  src/Shop.Api/appsettings.Development.json [Payments:ApiKey] value has the shape of a vendor key, value sk... (28 chars)
  src/Shop.Api/appsettings.Development.json [ConnectionStrings:Shop] password inside a connection string, value Se... (65 chars)

The path, the reason and a masked value are enough to fix it without the secret ever reaching the log. (The mask keeps two characters, so for a connection string it shows the start of the string rather than the password. Shorten it to **** if even that is too much for your logs.)

Notice the other failure in the same run. App_refuses_to_start_without_the_payments_api_key also failed, with No exception was thrown. That’s the committed key doing its job in the wrong direction: the factory runs in the Development environment by default, loads appsettings.Development.json, finds the key and starts happily. A startup check that passes because a secret is sitting in the repo isn’t checking anything, which is the reason the test pins UseEnvironment("Production").

That pin matters for a second reason, and this one only shows up on a developer’s machine. After the fix below, user-secrets holds a real key, and a Development-environment test would pick it up and stop failing for the wrong reason. WebApplication’s builder calls AddUserSecrets when the environment is Development, per the Microsoft docs, so the test has to leave Development to be independent of whoever is running it. With the pin in place, all three tests pass on a machine that has the user secret set.

Step 5: give the value somewhere legitimate to live

Remove the key and the password from the file, then store the key where the app can read it in development:

cd src/Shop.Api
dotnet user-secrets init
dotnet user-secrets set "Payments:ApiKey" "sk-live-9fA2kQ7xLm3VbN8cT1dW"
dotnet user-secrets list

init adds a UserSecretsId element to Shop.Api.csproj. The value lands in a secrets.json under ~/.microsoft/usersecrets/<id>/ on Linux and macOS, outside the repository, so there’s nothing to commit. list prints each key with its value, so run it somewhere nobody is watching.

For anything that isn’t a developer’s machine, use an environment variable. The double underscore is the portable separator, and the docs note that Bash can’t use a colon in a variable name:

Payments__ApiKey=sk-live-9fA2kQ7xLm3VbN8cT1dW dotnet run --no-launch-profile --urls http://127.0.0.1:5077
curl http://127.0.0.1:5077/payments/status
{"configured":true,"baseUrl":"https://api.payments.example/v2"}

And with no key anywhere, the app stops at startup with an error that names the field:

Unhandled exception. Microsoft.Extensions.Options.OptionsValidationException: DataAnnotation validation failed for 'PaymentsOptions' members: 'ApiKey' with the error: 'The ApiKey field is required.'.

That message is what an agent sees the first time it runs the app after adding the feature. It names the class, the member and the problem, and the agent’s natural next move is to supply a value. Tell it where in the instructions file.

Step 6: tell the agent the rule, in terms it can act on

Put this in AGENTS.md, CLAUDE.md, a Cursor rule or whatever your agent reads. The wording is tool-neutral on purpose:

Credentials and connection-string passwords never go in any file under src/.
When a feature needs one: add a property to its options class with [Required],
read it through IOptions<T>, and stop. Tell the user the configuration key
(for example Payments:ApiKey) so they can set it with `dotnet user-secrets set`.
Do not invent a value. Do not add the key to appsettings*.json, launchSettings.json
or test fixtures. `dotnet test` includes a scanner that fails on committed secrets;
do not edit, skip or loosen it to get a green run.

The last sentence earns its place. When a gate fails, “make it pass” has two solutions, and the cheaper one is sometimes to change the gate. Naming that explicitly costs a line.

Make it yours

A few variations for different stacks.

Other files. launchSettings.json is the usual second hiding place, because environmentVariables in a launch profile are a convenient spot for a key and the file is usually committed. Widen the glob in the first test to launchSettings.json and walk it with the same scanner. Docker Compose and .env.example files need a different walker, so cover them with a secret scanner built for arbitrary text and keep this test for the JSON that .NET reads.

Production values. Environment variables are commonly stored as plain text, which the Microsoft docs call out, and Secret Manager is explicitly a development tool, not an encrypted store. For deployed environments the docs point at Azure Key Vault and its configuration provider. The options class and the startup check don’t change when the source does: the key still has to bind to Payments:ApiKey, and the app still refuses to boot without it. Key Vault wiring wasn’t run for this piece, so follow the provider’s documentation for the registration.

TypeScript. The same split works for a Node service: a zod schema parsed at process start that throws on a missing PAYMENTS_API_KEY, plus a Vitest test that walks committed .json and .env* files with a scanner like the one above. The pieces are the same, only the libraries change. The canary-secret test in this earlier piece covers the logging side of the same problem in TypeScript.

Beside GitHub. This gate runs on the developer’s machine and in CI, before a push. GitHub’s push protection runs at the remote and recognises provider-specific key formats, which this scanner can’t match. They catch different cases, and the push protection piece covers what an agent hits there. Run both.

What goes wrong

Names that match nothing. The scanner knows a few key-name fragments and a few vendor shapes. A credential under "Value" in a format nobody has taught it passes. Treat the scanner as a net for the common cases and add a pattern the first time something gets through.

False positives. Config keys like TokenValidityMinutes hold numbers, which the scanner ignores (it only reads strings), but a string-typed TokenLifetime trips the name rule. Use the placeholder escape or rename the key, and resist the urge to loosen the name regex until nothing fires.

History. The scanner stops a secret reaching the commit. It does nothing for one already in history, and a secret that was ever pushed needs rotating, not deleting. Removing the line in a follow-up commit leaves the old one in the log.

Agents editing the gate. The gate lives in the same repository the agent can write to. Mark the scanner and its test as protected paths in whatever required-review mechanism you have (CODEOWNERS and a required review on the test directory works with any agent), and make the CI job a required status check, so a local edit to the test can’t reach the main branch unreviewed.

User-secrets aren’t a vault. Anything on the developer’s machine, including the agent, can read secrets.json. The benefit is keeping the value out of the repo, not out of reach. If the agent shouldn’t see the key at all, don’t give it a shell on a machine that holds the key.

Don’t bother if a pre-commit secret scanner and push protection already run on every repo you work in and cover your config formats. The part worth keeping in that case is the startup check, because it removes the reason to paste a key in at all.

First 15 minutes

Add the three tests and the scanner to your existing test project, pin Microsoft.AspNetCore.Mvc.Testing to the major version of your SDK, and run dotnet test. Whatever the scanner finds in your current appsettings*.json files is the first thing to move into user-secrets. Then paste the rule from Step 6 into your agent’s instructions file and add ValidateOnStart to the next options class you write.