# Obfuscating a LiteDB app without losing data


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

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

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

```json
{ "_id": { "$oid": "..." }, "Name": "Acme", "Total": 4250.0, "SignedUp": { "$date": "..." } }
```

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:

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

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.

<figure class="my-8"><svg viewBox="0 0 700 320" role="img" aria-label="Diagram contrasting two LiteDB mappings after renaming. On the left, a bare property named Total with no attribute: the mapper reads the live CLR name, so after renaming to b the new build writes and reads the field b, while the document already on disk still holds the field Total, so the read misses and the value comes back zero. On the right, a property carrying the attribute BsonField total: the mapper reads the string literal from the attribute, so even after the property is renamed the field stays total and matches the document on disk. A note states that renaming rewrites member names and tokens consistently, but the mapper binds to the live name unless an attribute pins a literal." style="width:100%;height:auto"><defs><style>.ti{font:600 12px system-ui;fill:#6366f1}.h{font:600 11px system-ui;fill:#0f172a}.x{font:10px system-ui;fill:#64748b}.mono{font:10px ui-monospace,Consolas,monospace;fill:#0891b2}.src{fill:#eef2ff;stroke:#a5b4fc}.bad{fill:#fee2e2;stroke:#f87171}.good{fill:#dcfce7;stroke:#4ade80}.attr{fill:#fef3c7;stroke:#fbbf24}.ar{stroke:#64748b;stroke-width:1.3;fill:none;marker-end:url(#a)}</style><marker id="a" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 z" fill="#64748b"/></marker></defs><text class="ti" x="12" y="18">The mapper binds to a name — pin it with an attribute</text><rect class="src" x="12" y="34" width="210" height="64" rx="5"/><text class="h" x="20" y="52">bare property</text><text class="mono" x="20" y="72">public decimal Total</text><text class="x" x="20" y="90">no attribute → CLR name is the field</text><rect class="bad" x="12" y="124" width="210" height="96" rx="5"/><text class="h" x="20" y="144">after rename → b</text><text class="mono" x="20" y="166">new build writes/reads "b"</text><text class="x" x="20" y="186">disk already holds "Total"</text><text class="x" x="20" y="204">read misses → Total = 0  lost</text><rect class="attr" x="262" y="34" width="214" height="64" rx="5"/><text class="h" x="270" y="52">attributed property</text><text class="mono" x="270" y="72">[BsonField("total")]</text><text class="mono" x="270" y="90">public decimal Total</text><rect class="good" x="262" y="124" width="214" height="96" rx="5"/><text class="h" x="270" y="144">after rename → b</text><text class="mono" x="270" y="166">mapper reads literal "total"</text><text class="x" x="270" y="186">disk field "total" matches</text><text class="x" x="270" y="204">read hits → value restored</text><path class="ar" d="M117,98 L117,124"/><path class="ar" d="M369,98 L369,124"/><rect class="src" x="516" y="34" width="172" height="186" rx="5"/><text class="h" x="524" y="54">what renaming does</text><text class="x" x="524" y="76">Renaming rewrites the</text><text class="x" x="524" y="92">property name and every</text><text class="x" x="524" y="108">token that points at it —</text><text class="x" x="524" y="124">consistently. The mapper</text><text class="x" x="524" y="140">does not follow a token;</text><text class="x" x="524" y="156">it reads the live name</text><text class="x" x="524" y="172">and makes it the field.</text><text class="x" x="524" y="188">The attribute moves the</text><text class="x" x="524" y="204">field into a literal.</text></svg></figure>

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

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

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:

```csharp
BsonMapper.Global.Entity<Customer>()
    .Id(x => x.Id)
    .Field(x => x.Name,     "name")
    .Field(x => x.Total,    "total")
    .Field(x => x.SignedUp, "signedUp");
```

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:

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

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:

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

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:

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

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

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

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](https://delta1labs.com/products/nebula/) 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](https://delta1labs.com/blog/obfuscate-system-text-json-jsonpropertyname-contract/).

