DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

Obfuscating FluentValidation without garbling error names

Here is a bug that passes every unit test and ships to production looking fine. You protect your ASP.NET Core API with an obfuscator, the build is green, the validators still reject bad input exactly as before — and then a customer reports that your form shows the error "'a' must not be empty" next to the email box. Nothing threw. The validation logic is intact. But FluentValidation is now reporting the failing field as a, because that is what your Email property is called after renaming.

The surprising part is that the rule still works. Most obfuscation-breaks-framework-X stories end in a null or an exception. This one does not: the validator keeps catching the empty value. What breaks is only the name FluentValidation attaches to the failure — and that name flows straight into your API's error contract. Understanding why requires looking at what RuleFor(x => x.Email) actually does with that lambda, because it does two separate things with it, and only one of them survives a rename.

What RuleFor does with the lambda

The signature is RuleFor<TProperty>(Expression<Func<T, TProperty>> expression). The argument is an expression tree, not a delegate — the compiler hands FluentValidation a data structure describing x => x.Email, specifically a LambdaExpression whose body is a MemberExpression pointing at the Email property. FluentValidation uses that one tree for two unrelated purposes:

  1. To read the value. It compiles the expression into a Func<T, TProperty> (cached per member in FluentValidation's AccessorCache) and invokes it at validation time to get the value to test. This is pure behaviour: the compiled delegate reads whatever member the expression references.
  2. To name the member. It walks the same MemberExpression chain and extracts member.Member.Name to produce the property name stored on the rule. This is the string that ends up on every ValidationFailure the rule produces.

The default name resolution lives in ValidatorOptions.Global.PropertyNameResolver, whose default implementation builds the name from the member chain — x => x.Address.Street becomes "Address.Street". Crucially, it reads MemberInfo.Name at runtime, from the metadata of the compiled assembly. It does not bake the literal "Email" into your code at compile time. So the resolved name is only ever as stable as the CLR member name — and the CLR member name is precisely what an obfuscator rewrites.

Seeing the break

Take an ordinary request model and validator:

public sealed class RegisterRequest
{
    public string Email { get; set; } = "";
    public string DisplayName { get; set; } = "";
}

public sealed class RegisterRequestValidator : AbstractValidator<RegisterRequest>
{
    public RegisterRequestValidator()
    {
        RuleFor(x => x.Email).NotEmpty().EmailAddress();
        RuleFor(x => x.DisplayName).NotEmpty().MaximumLength(50);
    }
}
Enter fullscreen mode Exit fullscreen mode

Run it against an empty request before obfuscation and the failures read exactly as you would expect:

var result = new RegisterRequestValidator().Validate(new RegisterRequest());
foreach (var f in result.Errors)
    Console.WriteLine($"{f.PropertyName}: {f.ErrorMessage}");

// Email: 'Email' must not be empty.
// DisplayName: 'Display Name' must not be empty.
Enter fullscreen mode Exit fullscreen mode

Note that FluentValidation has already split DisplayName into "Display Name" for the message — that is the DisplayNameResolver plus the PascalCase splitter working on the resolved member name. Now rename Email to a and DisplayName to b with an obfuscator and run the identical code against the identical input:

a: 'a' must not be empty.
b: 'b' must not be empty.
Enter fullscreen mode Exit fullscreen mode

The empty values are still caught — the predicates ran and failed exactly as before. But PropertyName is now a, and the message token {PropertyName} resolved to a as well. In a plain library this is ugly; in an ASP.NET Core API it is a contract break, because those PropertyName strings become your ModelState keys, and ModelState keys are what the framework serializes into the errors object of a ValidationProblemDetails response. Your front end keyed its field-level error display on email; the API now sends it a.

Why the value still validates

It is worth being precise about the asymmetry, because it is the whole reason this is a report-only bug rather than a crash. The compiled accessor is built from the expression's structure, not its member's name. x => x.Email and its renamed form x => x.a describe the same member access — a load of the same property getter — so the delegate FluentValidation compiles reads the correct value either way. The getter's new name get_a is irrelevant to the IL that calls it; the call site was rewritten to match during obfuscation. The predicate (NotEmpty, EmailAddress, MaximumLength) runs against the returned value and never looks at any name at all.

The reported name, by contrast, is derived from metadata — MemberInfo.Name — and metadata is exactly what renaming rewrites. Two things built from one expression, one keyed on structure and one keyed on a name, diverge the moment the name changes. That is why the rule keeps working while its label breaks.

The keep-list: pin the validated members

Nebula's rename pass is driven by nebula.config.json. The targeted fix is to turn renaming on globally and carve out the public members that validators reference and that surface as error names — which, for most APIs, is the same set of public properties your model binder already reads off the request body:

{
  "input": "bin/Release/net8.0/Acme.Api.dll",
  "rename": {
    "enabled": true,
    "keep": [
      {
        "namespace": "Acme.Api.Contracts",
        "kind": "type",
        "members": "public",
        "reason": "FluentValidation resolves RuleFor property names from these public members; they are also the client-facing error field names"
      }
    ]
  },
  "strings": { "encrypt": true },
  "controlFlow": { "enabled": true }
}
Enter fullscreen mode Exit fullscreen mode

The "members": "public" scope is the point: it preserves the public property names FluentValidation reads for its PropertyName, while still letting Nebula rename private backing fields, which no resolver ever touches. The AbstractValidator subclasses themselves — RegisterRequestValidator and everything in your validation plumbing — are not on the keep-list. Their type names and method names carry no runtime meaning to FluentValidation, so they are renamed, string-encrypted and control-flow-flattened like the rest of your code. You are pinning the data shapes, not the validators.

The escape hatch: name the rule explicitly

If you would rather rename even the DTO properties — perhaps their names are themselves revealing — FluentValidation lets you set the reported name explicitly so it no longer depends on the member at all. .WithName() overrides the display name used in messages; .OverridePropertyName() overrides the PropertyName on the failure (and thus the ModelState key):

RuleFor(x => x.Email)
    .NotEmpty().EmailAddress()
    .OverridePropertyName("email")
    .WithName("Email");

RuleFor(x => x.DisplayName)
    .NotEmpty().MaximumLength(50)
    .OverridePropertyName("displayName")
    .WithName("Display name");
Enter fullscreen mode Exit fullscreen mode

Those arguments are string literals. Nebula may encrypt them so they are not sitting in plaintext, but encryption is transparent at runtime — the decrypted value is byte-for-byte what you wrote. So the reported name is now driven by "email", not by the Email member, and the member underneath is free to be renamed to a. This is the same decoupling trick that a [JsonPropertyName] attribute gives System.Text.Json: move the wire name into a literal and the identifier becomes disposable. The cost is that you must remember to set it on every rule; a missed rule silently falls back to the member name and breaks again under obfuscation.

A middle path, if you have many validators, is to replace the global resolver once at startup so there is nothing to forget:

ValidatorOptions.Global.PropertyNameResolver =
    (type, member, expr) => member?.Name; // still member-name based — pin members
Enter fullscreen mode Exit fullscreen mode

That hook is useful for mapping names (for example, lowercasing to match a JSON convention), but note it still receives the MemberInfo, so a resolver that reads member.Name is just as rename-fragile as the default. The hook decouples you from obfuscation only if you drive it from something stable — an attribute value or a dictionary — rather than from member.Name.

Caveats and the honest limits

  • Nested and collection rules inherit the break. RuleFor(x => x.Address.Street) resolves to "Address.Street"; renaming either member rewrites that segment. RuleForEach(x => x.Items) with child validators produces names like Items[0].Sku. Pin every type in the chain, not just the root.
  • .WithName() and .OverridePropertyName() differ. WithName changes only the message display; OverridePropertyName changes the PropertyName that becomes the ModelState key. If your client keys off the field name, you need OverridePropertyName (or both). Setting only WithName fixes the message but still sends the obfuscated key.
  • Automatic model binding is a separate contract. If you rename the DTO properties and rely on .WithName/.OverridePropertyName for errors, the inbound JSON binding still needs the property to deserialize — either keep the public member names anyway or give them [JsonPropertyName]. Obfuscating the serializer contract is its own topic; the keep-list approach avoids the whole question by leaving the public members intact.

Verify before you ship

Confirm the rename did what the keep-list intended by opening the protected assembly in Glass, the free .NET decompiler. Your contract types — RegisterRequest and friends — should still show Email and DisplayName as public properties with their original names. Your validators — RegisterRequestValidator — should show up renamed to opaque identifiers, proving they were protected rather than swept into the keep-list. Then run one integration test that posts an empty body and asserts the response's errors object is keyed by email/displayName, not by a/b. That test is the cheapest possible substitute for the exception FluentValidation never throws.

The shape of the rule

FluentValidation's dependency on your code is narrow and name-based, but it is not where people expect it. The validation logic is rename-proof, because it is compiled from the expression's structure. The reported member name is rename-fragile, because it is read from metadata every time a rule fails — and that name flows into your messages, your ModelState and your API's error contract. Pin the public members of your validated models in nebula.config.json, or move the reported names into string literals with .OverridePropertyName(), verify the result in Glass, and you ship an API whose validators are opaque to a reverse engineer and whose error field names still say email. Protecting that API end to end is what Nebula.NET is for.

Top comments (0)