Select Page

A failed sign-in event needs enough information to count failures and identify their category. It does not need the submitted password, bearer token, email address, or raw exception message. Give that event its own small schema, then test both the fields and their values.

This tutorial builds a BCL-only JSON event writer and an executable regression check. It targets .NET 10 with the default C# 14 language version and uses no external packages. The test captures the writer’s output in memory; it does not test an authentication system or a production logging provider.

Choose what may leave the application

For this example, the event contains four fields: a fixed event ID, a fixed event name, an attempt number supplied by application code, and a reason chosen from a short list. None identifies a user. Keep that decision explicit when adapting the schema; even an identifier can become sensitive when joined with other data.

Serializing an entire request is risky because System.Text.Json includes public properties by default. A new password or token property can therefore become output without a logging change. Serialize a dedicated event instead. Microsoft’s serialization guide documents that default and the Serialize method.

The writer below accepts only an integer and an enum. It maps the enum to fixed text, including a fixed fallback for unexpected numeric values. A property named Reason is not inherently safe: putting an exception message into it would defeat the schema’s purpose.

Run the complete event check

Create a console project with the .NET 10 SDK and replace Program.cs with the complete listing below. The verification used a net10.0 executable project with nullable analysis, implicit usings, and warnings treated as errors. All input credentials are synthetic canaries.

dotnet new console --framework net10.0 --name SafeEvents
cd SafeEvents
# Replace Program.cs with the listing below.
dotnet run --project SafeEvents.csproj -p:TreatWarningsAsErrors=true
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.Json;

internal enum FailureReason { InvalidCredentials, ServiceUnavailable }
internal sealed record LoginAttempt(string UserName, string Password, string BearerToken);
internal sealed record AuthEvent(int EventId, string EventName, int Attempt, string Reason);

internal static class Program
{
    private static void Main()
    {
        // Synthetic canaries only: never put real credentials in test fixtures.
        var request = new LoginAttempt("person@example.invalid", "fake-password-120", "fake-token-120");
        var failure = new InvalidOperationException("Upstream rejected " + request.BearerToken);
        string[] forbidden = { request.UserName, request.Password, request.BearerToken, failure.Message };

        string first = Capture(FailureReason.InvalidCredentials);
        AssertEvent(first, "InvalidCredentials", forbidden);
        AssertEvent(Capture(FailureReason.ServiceUnavailable), "ServiceUnavailable", forbidden);
        AssertEvent(Capture((FailureReason)999), "Unknown", forbidden);

        // Negative control: dumping an input object must fail the schema check.
        ExpectRejection(JsonSerializer.Serialize(request), "InvalidCredentials", forbidden, "schema");
        // A permitted property name is insufficient if its value contains a secret.
        string unsafeReason = JsonSerializer.Serialize(
            new AuthEvent(1201, "AuthenticationRejected", 1, failure.Message));
        ExpectRejection(unsafeReason, "InvalidCredentials", forbidden, "value");

        Console.Write(first);
        Console.WriteLine("PASS: three allowed events");
        Console.WriteLine("PASS: request dump rejected");
        Console.WriteLine("PASS: exception message rejected");
    }

    private static void LogRejected(TextWriter sink, int attempt, FailureReason reason)
    {
        string category = reason switch
        {
            FailureReason.InvalidCredentials => "InvalidCredentials",
            FailureReason.ServiceUnavailable => "ServiceUnavailable",
            _ => "Unknown"
        };
        // The writer accepts a category, never the request or the exception.
        var entry = new AuthEvent(1201, "AuthenticationRejected", attempt, category);
        sink.WriteLine(JsonSerializer.Serialize(entry));
    }

    private static string Capture(FailureReason reason)
    {
        using var sink = new StringWriter(CultureInfo.InvariantCulture);
        sink.NewLine = "\n";
        LogRejected(sink, 1, reason);
        return sink.ToString();
    }

    private static void AssertEvent(string json, string reason, string[] forbidden)
    {
        using var document = JsonDocument.Parse(json);
        JsonElement root = document.RootElement;
        string[] names = root.EnumerateObject().Select(p => p.Name).OrderBy(n => n, StringComparer.Ordinal).ToArray();
        if (!names.SequenceEqual(new[] { "Attempt", "EventId", "EventName", "Reason" }))
            throw new InvalidDataException("schema");
        if (root.GetProperty("EventId").GetInt32() != 1201 ||
            root.GetProperty("EventName").GetString() != "AuthenticationRejected" ||
            root.GetProperty("Attempt").GetInt32() != 1 ||
            root.GetProperty("Reason").GetString() != reason)
            throw new InvalidDataException("value");

        // Inspect decoded strings so JSON escaping cannot conceal a canary.
        foreach (JsonProperty property in root.EnumerateObject())
            if (property.Value.ValueKind == JsonValueKind.String)
                foreach (string secret in forbidden)
                    if (property.Value.GetString()!.Contains(secret, StringComparison.Ordinal))
                        throw new InvalidDataException("canary");
    }

    private static void ExpectRejection(string json, string reason, string[] forbidden, string expected)
    {
        try { AssertEvent(json, reason, forbidden); }
        catch (InvalidDataException error) when (error.Message == expected) { return; }
        throw new InvalidOperationException("Negative control was not rejected as expected.");
    }
}

The verified run produced exactly:

{"EventId":1201,"EventName":"AuthenticationRejected","Attempt":1,"Reason":"InvalidCredentials"}
PASS: three allowed events
PASS: request dump rejected
PASS: exception message rejected

Why the check tests more than missing passwords

AssertEvent parses the JSON and compares the complete property-name set. An added field fails even if it does not contain one of today’s canary values. It also checks the expected event ID, name, attempt number, and reason. The three passing cases exercise both known reasons and the Unknown fallback.

The first negative control serializes the whole request. It must fail with the schema diagnostic. The second uses the right property names but inserts an exception message containing the synthetic token. It must fail with the value diagnostic. ExpectRejection accepts only the expected failure; a check that stops rejecting either defect makes the program fail.

The decoded-string scan provides an additional canary guard for this flat schema. Scanning decoded values avoids mistaking JSON escaping for removal of sensitive content. Exact value checks already reject the second negative control, so that control does not independently exercise the canary diagnostic. This is deliberate: the event contract is stronger than searching for known secret strings.

Each capture creates and disposes its own StringWriter, and each parse disposes its JsonDocument. No file, network service, shared logger state, timing assumption, or cleanup of external data is involved. The outer verification also asserted the complete standard output after compiling and running the listing in an offline container.

Carry the boundary into your logging setup

Use the same field and value policy wherever your application emits this event. Keep request bodies, authorization headers, and raw exception messages out of this path. If diagnosis needs more detail, define another reviewed category or field rather than feeding arbitrary text into Reason. An attempt counter should come from application state, not a numeric credential.

When a system genuinely needs classified values to pass through a redaction layer, Microsoft’s data redaction documentation describes masking and erasing sensitive output. This sample chooses omission and fixed categories; it does not implement or verify that package.

The passing check proves the behavior of this writer for these inputs. It does not prove that every application log is safe, that a remote sink received anything, or that scopes, exception enrichment, middleware, and exporters cannot add other data. Test the final captured event at each integration boundary you actually use. Repeat the schema review when fields change, and keep real credentials out of fixtures and their failure output.

For the language features behind the example, continue with classes in C# and exception handling. For choosing a logging library later, the C# package directory includes Serilog and its integration limits.

Share This