# 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](https://docs.fluentvalidation.net/) 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.

<figure class="my-8"><svg viewBox="0 0 720 320" role="img" aria-label="RuleFor receives the expression x arrow x.Email and uses it two ways: it compiles an accessor that reads the value (behaviour, rename-safe) and it extracts MemberExpression.Member.Name to build the reported property name (rename-fragile). After obfuscation renames Email to a, the accessor still reads the value correctly, but the resolved name becomes a, so ValidationFailure.PropertyName, the ModelState key and the {PropertyName} message token all report a instead of Email." style="width:100%;height:auto"><defs><style>.ti{font:600 13px system-ui;fill:#6366f1}.lbl{font:11px system-ui;fill:#64748b}.mono{font:600 11px ui-monospace,monospace;fill:#0f172a}.okbox{fill:#10b98120;stroke:#10b981}.srcbox{fill:#6366f120;stroke:#6366f1}.badbox{fill:#f8717120;stroke:#f87171}</style><marker id="a1" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto"><path d="M0 0l6 3-6 3z" fill="#64748b"/></marker><marker id="a2" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto"><path d="M0 0l6 3-6 3z" fill="#f87171"/></marker><text class="ti" x="16" y="22">RuleFor(x =&gt; x.Email) — one expression, two uses</text><rect class="srcbox" x="16" y="34" width="210" height="30" rx="4"/><text class="mono" x="26" y="53">Expression&lt;Func&lt;T,string&gt;&gt;</text><path d="M226 49 h70" stroke="#64748b" stroke-width="2" fill="none" marker-end="url(#a1)"/><rect class="okbox" x="300" y="20" width="230" height="26" rx="4"/><text class="mono" x="310" y="37">Compile → Func&lt;T,string&gt; (value)</text><text class="lbl" x="536" y="37">rename-safe</text><rect class="badbox" x="300" y="56" width="230" height="26" rx="4"/><text class="mono" x="310" y="73">Member.Name → "Email" (name)</text><text class="lbl" x="536" y="73">rename-fragile</text><text class="ti" x="16" y="128">After obfuscation: Email renamed to a</text><rect class="srcbox" x="16" y="140" width="210" height="30" rx="4"/><text class="mono" x="26" y="159">x =&gt; x.a  (same tree)</text><path d="M226 155 h70" stroke="#64748b" stroke-width="2" fill="none" marker-end="url(#a1)"/><rect class="okbox" x="300" y="126" width="230" height="26" rx="4"/><text class="mono" x="310" y="143">reads the value ✓</text><rect class="badbox" x="300" y="162" width="230" height="26" rx="4"/><text class="mono" x="310" y="179">Member.Name → "a" ✗</text><text class="ti" x="16" y="226">Where the name "a" surfaces</text><rect class="badbox" x="16" y="238" width="220" height="26" rx="4"/><text class="mono" x="26" y="255">ValidationFailure.PropertyName</text><path d="M236 251 h24" stroke="#f87171" stroke-width="2" fill="none" marker-end="url(#a2)"/><rect class="badbox" x="264" y="238" width="190" height="26" rx="4"/><text class="mono" x="274" y="255">ModelState["a"]</text><path d="M454 251 h24" stroke="#f87171" stroke-width="2" fill="none" marker-end="url(#a2)"/><rect class="badbox" x="482" y="238" width="220" height="26" rx="4"/><text class="mono" x="492" y="255">"'a' must not be empty."</text><text class="lbl" x="16" y="296">The predicate (NotEmpty, EmailAddress) is unaffected — only the reported member name moves.</text></svg></figure>

## Seeing the break

Take an ordinary request model and validator:

```csharp
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);
    }
}
```

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

```csharp
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.
```

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.
```

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:

```json
{
  "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 }
}
```

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):

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

RuleFor(x => x.DisplayName)
    .NotEmpty().MaximumLength(50)
    .OverridePropertyName("displayName")
    .WithName("Display name");
```

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:

```csharp
ValidatorOptions.Global.PropertyNameResolver =
    (type, member, expr) => member?.Name; // still member-name based — pin members
```

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](https://delta1labs.com/products/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](https://delta1labs.com/products/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](https://delta1labs.com/products/nebula) is for.

