DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Edited on Originally published at delta1labs.com

Obfuscating a LiteDB app without losing data

Here is a document model that works perfectly until the day you obfuscate the update:

public sealed class Customer
{
    public ObjectId Id { get; set; } = ObjectId.NewObjectId();
    public string Name { get; set; } = "";
    public decimal Total { get; set; }
    public DateTime SignedUp { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Store one with LiteDB and the document written to the .db file on the customer's disk is, literally:

{ "_id": { "$oid": "..." }, "Name": "Acme", "Total": 4250.0, "SignedUp": { "$date": "..." } }
Enter fullscreen mode Exit fullscreen mode

Ship version 1.0, then build 1.1 through a renamer and ship that. The new build's LiteDB now writes { "a": "Acme", "b": 4250.0, … } — and when it opens the customer's existing file, it looks for a field called "a" in every document, finds "Name" instead, and hands back a Customer whose Name is empty and whose Total is zero. Nothing threw. The build was green. The data is intact on disk; the application just can't read its own past.

This is the embedded-store version of the "obfuscation broke serialization" incident, and it is worse than the wire-contract version, because the broken contract is not a live consumer you can redeploy — it is bytes already written to someone else's machine.

Why the rename reaches the disk

Internal calls survive renaming because they are joined by metadata token: the compiler emits call against a token, and a renamer that rewrites the callee rewrites every token pointing at it, so the graph stays connected. LiteDB's mapper does not use a token. When it first sees a type it walks it with reflection, reads each public property's actual CLR Name, and uses that string as the BSON field name:

// BsonMapper, in effect, for each mapped property p:
//   fieldName = p.Name;                 // "Total"  — the live CLR name
//   doc[fieldName] = Serialize(value);  // => { "Total": 4250.0 }
Enter fullscreen mode Exit fullscreen mode

The field "Total" exists only because the property is named Total. There is no token joining the string in the file to the member in the assembly — the join is the name. Reading runs the same machinery in reverse: LiteDB pulls each field by its string name and assigns it to the property of that name. So when the renamer turns Total into b, the mapper does exactly what it is told — it writes "b" and reads "b" — and every document written under the old name is now unreachable.

The fix is an attribute, not a keep rule

The instinct is to exclude Customer from renaming. Don't — that hands an attacker the whole domain model, and it is unnecessary. The field name should be a constant, not a side effect of the member name, and [BsonField] makes it one:

public sealed class Customer
{
    [BsonId]                          public ObjectId Id { get; set; } = ObjectId.NewObjectId();
    [BsonField("name")]               public string Name { get; set; } = "";
    [BsonField("total")]              public decimal Total { get; set; }
    [BsonField("signedUp")]           public DateTime SignedUp { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Now the mapper reads the attribute's string literal — "total" — not the property name. The renamer is free to turn Total into b; the attribute still says "total", the stored field is still "total", and every document ever written under that literal still reads back. The member does get renamed, which is the point; only the string LiteDB reads is pinned. If you prefer to keep attributes out of the model, the fluent mapper pins the same literals from one place:

BsonMapper.Global.Entity<Customer>()
    .Id(x => x.Id)
    .Field(x => x.Name,     "name")
    .Field(x => x.Total,    "total")
    .Field(x => x.SignedUp, "signedUp");
Enter fullscreen mode Exit fullscreen mode

The rule is simple and total: every stored field gets an explicit name. One un-pinned property falls back to its CLR name and becomes the single field that vanishes on the next build.

_id is already pinned — the trap is everything else

The identifier is the one field LiteDB does not bind by your member name. A property called Id (any case), or one marked [BsonId], is always stored as the literal _id, so the primary key survives renaming for free. That is also the trap: it lulls you into thinking the document round-trips, because FindById keeps working and the record is clearly there — while every other field has quietly gone to its default. Test the whole document, not the lookup.

A string query is a second name binding

Field names leak into queries, too, and the two query styles behave differently under a rename. A string BSON expression hard-codes the field name as a literal the mapper never rewrites:

// The "$.Total" literal is NOT a member reference — the renamer never touches it.
var vips = col.Query().Where("$.Total > @0", 1000m).ToList();   // breaks after rename
col.EnsureIndex("Total");                                       // indexes a dead field name
Enter fullscreen mode Exit fullscreen mode

After renaming, "$.Total" queries a field the current build no longer writes, and returns nothing. An expression query is different — LiteDB runs the lambda through the same mapper, so it resolves the field name from the (renamed) property and stays self-consistent with its own build's data:

var vips = col.Find(x => x.Total > 1000m).ToList();   // resolves to the renamed field
col.EnsureIndex(x => x.Total);                         // indexes whatever Total maps to now
Enter fullscreen mode Exit fullscreen mode

Once you have pinned the field names with [BsonField("total")], both forms resolve to the stable literal "total" and agree — which is the real reason to prefer attributed names over bare ones even when all your queries are expression-based: the attribute is what makes the string query and the on-disk data meet.

Caveats and when it still breaks

Two honest limits. First, LiteDB has to construct your type on read. By default it uses a public parameterless constructor and then assigns fields; if you deserialize through a parameterized constructor, LiteDB matches each parameter to a field by parameter name, so confirm your obfuscator leaves constructor parameter names alone (Nebula does by default — but when a model deserializes through a constructor, that default is load-bearing, so verify it rather than assume it). Second, [BsonField] fixes future writes and reads; data already written by an un-pinned build still carries the raw member name in its documents. If you ship obfuscation after data already exists, run a one-time migration that reads each old field and rewrites it under the pinned name — there is no way to recover a field whose stored name was a member name the next build no longer produces.

The Nebula configuration

With the stored names pinned by attribute or fluent map, the configuration keeps nothing — the model renames like everything else:

<Nebula>
  <Assembly file="MyApp.dll">
    <Rename enabled="true" />          <!-- document models rename; [BsonField] holds the wire -->
    <ControlFlow enabled="true" />
    <StringEncryption enabled="true" />
  </Assembly>
</Nebula>
Enter fullscreen mode Exit fullscreen mode

StringEncryption is safe to leave on across the whole assembly: the "total" literal inside [BsonField] is decrypted at the point the mapper reads it, so LiteDB sees the same field name it always did. No Preserve block is needed, because nothing in the model is resolved by member name any more — that was the entire goal.

Prove it against an old database

The test that matters does not round-trip a fresh object in memory; it opens a database file written by the previous build with the obfuscated assembly, because the whole failure mode is that the names only move between builds. Commit a small v1.0-seed.db to the repo and assert against it in CI:

[Fact]
public void Obfuscated_build_reads_the_previous_versions_database()
{
    File.Copy("fixtures/v1.0-seed.db", "test.db", overwrite: true);
    using var db = new LiteDatabase("test.db");
    var col = db.GetCollection<Customer>("customers");

    var acme = col.FindOne(x => x.Name == "Acme");
    Assert.NotNull(acme);
    Assert.Equal(4250.0m, acme!.Total);      // the field that silently goes to 0 if unpinned
    Assert.NotEqual(default, acme.SignedUp);
}
Enter fullscreen mode Exit fullscreen mode

Run this against the post-obfuscation artifact and the "update wiped everyone's data" incident becomes a failed test instead of a support queue. The principle underneath it is the one worth carrying to every store that maps by reflection: a name a framework reads at runtime is a contract, and a persisted contract belongs in a string literal the obfuscator cannot move — not in a member name it is paid to rename.

Nebula.NET renames aggressively by design; [BsonField] is how you keep the one name that has to survive on disk while losing every name that should disappear from the binary. For the same pattern on the wire, see obfuscating System.Text.Json types.

Top comments (0)