DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

Obfuscating a JSON source-generated context

A [JsonSerializable] context is the serializer you reach for when you are about to obfuscate. The reflection-based path reads your live property names at runtime, so renaming CustomerRef to a turns your JSON into {"a":…}; the source-generated path resolves everything at compile time and reaches your members through typed delegates, so the rename is invisible on the wire. That much is well known.

What is less obvious is how the generated context stays intact — and where it does not. The generator writes the serialization contract down in two kinds of thing: tokens that the renamer follows, and literals that it leaves exactly where they are. A source-generated JsonSerializerContext is rename-safe precisely when those two halves stay in step, and it desyncs the moment a code path sidesteps the context. So the question worth answering concretely is: what does the generator actually emit, which parts move under renaming and which do not, and how do you prove the halves still line up after Nebula runs?

What the generator emits

Start with a DTO carrying one explicit wire name and a context for it:

public sealed class Order
{
    [JsonPropertyName("customer_ref")] public string CustomerRef { get; set; } = "";
    public decimal Total { get; set; }
}

[JsonSerializable(typeof(Order))]
internal partial class AppJsonContext : JsonSerializerContext { }
Enter fullscreen mode Exit fullscreen mode

Turn on <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> and read what the generator produced. Two pieces matter. First, the context resolves a type to its JsonTypeInfo by identity:

public override JsonTypeInfo? GetTypeInfo(Type type)
{
    if (type == typeof(global::Order))   return this.Order;
    if (type == typeof(string))          return this.String;
    if (type == typeof(decimal))         return this.Decimal;
    return null;
}
Enter fullscreen mode Exit fullscreen mode

There is no string anywhere in that method. typeof(global::Order) compiles to an ldtoken of the type's metadata handle, and type == is a reference comparison against the runtime Type the serializer already holds. When the renamer turns Order into a, it rewrites the ldtoken and the this.Order property reference together — GetTypeInfo(typeof(a)) still returns the right metadata. This is the whole reason the context survives: resolution is token-based end to end.

Second, the per-property metadata. In the default metadata mode the generator emits an initializer like this (trimmed):

private static JsonPropertyInfo[] OrderPropInit(JsonSerializerOptions options)
{
    var properties = new JsonPropertyInfo[2];

    var info0 = new JsonPropertyInfoValues<string>
    {
        IsProperty       = true,
        DeclaringType    = typeof(global::Order),
        Getter           = static obj => ((global::Order)obj).CustomerRef,
        Setter           = static (obj, value) => ((global::Order)obj).CustomerRef = value!,
        JsonPropertyName = "customer_ref",   // from [JsonPropertyName], captured as a literal
        PropertyName     = "CustomerRef",     // the CLR name, also captured
    };
    properties[0] = JsonMetadataServices.CreatePropertyInfo<string>(options, info0);
    // ... Total ...
    return properties;
}
Enter fullscreen mode Exit fullscreen mode

The getter and setter are lambdas that touch the member directly — in IL, ldftn on a compiler-generated method whose body is callvirt Order::get_CustomerRef(). The wire name is a ldstr "customer_ref". After Nebula renames Order to a and CustomerRef to b, the lambda body becomes callvirt a::get_b(), rewritten by token like every call site, while the ldstr still reads "customer_ref". Serialize an order and you get {"customer_ref":"…","total":…} exactly as before.

The reflection resolver binds the wire key to the live member name; the generated context binds the type by typeof identity and the wire name to a captured literal — both rename-safe.

In the fast-path serialization mode the shape is the same, just hand-written: a pre-encoded private static readonly JsonEncodedText PropName_customer_ref = JsonEncodedText.Encode("customer_ref"); and a writer.WriteString(PropName_customer_ref, value.CustomerRef). Literal plus direct member access, again. Whichever mode the generator picked, the rule is the inverse of the reflection rule: the member is safe to rename; the literal is what you reason about.

The constructor is bound positionally

An immutable DTO adds a wrinkle the reflection serializer handles by parameter name. The generator handles it differently — and better. Give Order a parameterized constructor and the generated object metadata carries a positional creator plus parameter info:

objectInfo.CreateObjectWithArgs =
    static args => new global::Order((string)args[0]!, (decimal)args[1]!);

// parameter metadata the serializer matches JSON properties against:
new JsonParameterInfoValues { Name = "customerRef", Position = 0, ParameterType = typeof(string) };
new JsonParameterInfoValues { Name = "total",       Position = 1, ParameterType = typeof(decimal) };
Enter fullscreen mode Exit fullscreen mode

The object is constructed through a delegate that calls the constructor positionally — args[0], args[1] — so the constructor call is a token and renaming the constructor changes nothing. The Name = "customerRef" literal is what pairs a deserialized property to its slot, and it was captured at generation time, so renaming the constructor parameters to p0, p1 cannot desync it. This is a real improvement over the reflection path, where that pairing is read from live parameter-name metadata and a parameter renamer can break it. With the generated context, the parameter names are frozen into literals before Nebula runs.

Where the context and the wire still desync

The generated context is safe, but only for traffic that actually goes through it. Three paths leave it:

A reflection fallback. JsonSerializer.Serialize(order) with no context argument, or a resolver chain that ends in DefaultJsonTypeInfoResolver for a type the context does not cover, resolves names from live metadata — and emits the renamed names. You do not want to find that in the obfuscated build. Close the door at the project level so it throws in development:

<PropertyGroup>
  <JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
</PropertyGroup>
Enter fullscreen mode Exit fullscreen mode

A context resolved by name. Type.GetType("AppJsonContext") or any reflective construction of the context is a string dependency the renamer invalidates. Reach the context the generated way — AppJsonContext.Default and its per-type AppJsonContext.Default.Order — which are token references that rename with your call sites.

A missing [JsonPropertyName]. The generator always captures a wire name, but when you omit the attribute that literal is whatever the property was called in source. Two costs follow: a later source rename silently changes the wire (the captured literal moves with it at the next build), and the original member name sits in the assembly as a readable ldstr. Attribute the names that are contracts, and turn on encryptStrings so the captured literals — wire names and the PropertyName copies — are encrypted at rest and decrypted at runtime. The JSON is unaffected; the map of original names is gone from the file.

The rules for the context type

Do not exclude the JsonSerializerContext-derived type by reflex. The context, its Default property and the per-type JsonTypeInfo<T> properties are reached by token from your own code, so the renamer rewrites every reference consistently and nothing breaks — excluding it only hands an attacker a clean, named map of your serialized model. Preserve it in exactly two situations: the context is public API another assembly consumes across the obfuscation boundary (use preservePublicApi, or exclude that one type), or it is resolved by name somewhere (remove the reflective lookup instead). In both cases the DTOs behind it still rename freely.

Prove the halves line up

The assertion that matters runs against the obfuscated artifact, because the whole failure mode only appears after Nebula renames. A round-trip plus a resolver check catches every desync above:

[Fact]
public void Protected_build_round_trips_through_the_generated_context()
{
    var order = new Order("ACME-7", 42.50m);

    var json = JsonSerializer.Serialize(order, AppJsonContext.Default.Order);
    Assert.Contains("\"customer_ref\":\"ACME-7\"", json);  // the contract, literally
    Assert.DoesNotContain("\"b\":", json);                 // no renamed member leaked

    var back = JsonSerializer.Deserialize(json, AppJsonContext.Default.Order)!;
    Assert.Equal("ACME-7", back.CustomerRef);              // ctor matched positionally

    // the context still resolves the (renamed) type by identity
    Assert.NotNull(AppJsonContext.Default.GetTypeInfo(typeof(Order)));
}
Enter fullscreen mode Exit fullscreen mode

Wire that against the post-obfuscation build in CI and "serialization broke" becomes a red test instead of a customer email. The principle generalizes: a source-generated context is the easiest serializer in your assembly to obfuscate because it resolves by token and carries its contract as literals — your job is only to keep every serialization path inside it, and to encrypt the names it wrote down.

For the reflection-side version of this problem, see obfuscating System.Text.Json types without breaking JSON; for the broader generator picture, obfuscating source-generated code safely. Nebula.NET renames aggressively by design, and the rules above are how the one name that has to stay does. Download it free and run your round-trip against the protected build.

Top comments (0)