# Compliance · GDPR right-to-erasure (/docs/compliance/gdpr-erasure)



The GDPR right to erasure obliges the controller to erase personal data on a
qualifying request. An append-only hash chain resists row-level deletion.

This page covers the tension, the two production approaches, and the
primitive `@pleach/compliance` ships for one of them. It shipped in an earlier
release.

## The tension [#the-tension]

Each row's hash feeds the next row's hash. Erase a row in the middle and every
later row stops verifying. A plain `DELETE` on a PII row therefore looks like
tampering, so a deployment that pairs erasure with a chain has to pick a
strategy. Neither is free.

## Approach (a): crypto-shredding (recommended for production) [#approach-a-crypto-shredding-recommended-for-production]

PII fields are encrypted at write time with a per-subject key. Erasure deletes
the key. The ciphertext stays, the chain stays valid, and the data becomes
unreadable.

* **Pros:** the chain stays valid indefinitely, and pre-erasure attestations
  keep verifying.
* **Cons:** you need key-management infrastructure (a cloud KMS or Vault) and
  per-field envelope encryption at every write site. Onboarding costs more.

`executeErasureRequest` implements approach (a) and never rebuilds the chain.
You supply `subjectKeys` and the key custody behind it. The package stays
vendor-neutral.

## Approach (b): row deletion and chain rebuild (not the shipped primitive) [#approach-b-row-deletion-and-chain-rebuild-not-the-shipped-primitive]

PII rows are physically deleted and later rows are re-anchored against a fresh
genesis seed.

* **Pros:** no key infrastructure, and it works against any event store that
  can `DELETE`.
* **Cons:** pre-erasure attestations no longer verify against the rebuilt
  chain. The changed genesis root is itself the proof that erasure happened.

Accept that trade-off explicitly. If you need erasure and pre-erasure
attestations that stay verifiable, use crypto-shredding.

## `executeErasureRequest` — the structural primitive [#executeerasurerequest--the-structural-primitive]

```ts
import { executeErasureRequest } from "@pleach/compliance/hashchain";

const result = await executeErasureRequest({
  request: {
    tenantId: "tenant-acme",
    subjectId: "user@example.com",
    scope: "all",
    reason: "DSAR-2026-06-15 Art 17(1)(a)",
    operator: "support-engineer@example.com",
  },
  subjectKeys,          // your SubjectKeyRegistryLike — see below
  attestationKeyStore,  // any @pleach/core/attestation AttestationKeyStore
});

console.log(result);
// {
//   subjectId: "user@example.com",
//   tenantId: "tenant-acme",
//   shredded: true,
//   chainRebuilt: false,
//   attestation: { version: "pleach.erasure.v1", signature: "...", ... },
// }
```

It destroys the subject's key with `subjectKeys.shred(tenantId, subjectId)`,
which is irreversible and idempotent, then seals a signed shred proof with
`attestationKeyStore`. It doesn't touch the chain, so `chainRebuilt` is always
`false`. `rebuildChainFromGenesis` is deprecated, and the helper never calls it.

A repeat request for an already-shredded subject succeeds with a freshly
sealed attestation, never an error. A `shred` or signer failure throws. There
is no soft-fail path.

### `ErasureScope` [#erasurescope]

`request.scope` takes `"messages"`, `"calls"`, or `"all"`. It's an advisory
label only. Erasure shreds the subject's one key, so the scope doesn't narrow
what becomes unreadable.

## What the attestation proves [#what-the-attestation-proves]

The attestation records the tenant, the subject, the seal time, the reason,
the operator (when you set one), and a signature with the signing key's id
(`signaturePublicKeyId`), which you resolve out-of-band.
`verifyErasureAttestation(attestation, publicKey)` returns `{ valid: true }` or
`{ valid: false, reason }`. It doesn't throw on a bad signature.

The helper doesn't persist the attestation. Store it in your compliance ledger
next to the DSAR case.

## What you must supply [#what-you-must-supply]

`executeErasureRequest` takes **two injected dependencies**. Both are required.

| dependency            | type you implement       | import from                                                            | reference impl                                                          |
| --------------------- | ------------------------ | ---------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `subjectKeys`         | `SubjectKeyRegistryLike` | `@pleach/compliance/hashchain`                                         | `SubjectKeyRegistry` from `@pleach/core/crypto` (Postgres), or your own |
| `attestationKeyStore` | `AttestationKeyStore`    | `@pleach/core/attestation` (`@pleach/compliance` doesn't re-export it) | `FileBackedAttestationKeyStore` from `@pleach/core/attestation/testing` |

**`subjectKeys` needs key custody you choose.** `@pleach/core/crypto` ships
`SubjectKeyRegistry`, which keeps per-subject keys in Postgres wrapped by a
key-encryption key. `createAesGcmKekProvider` is the reference provider. In
production, back it with your KMS. If you keep keys elsewhere, implement the
small surface inline:

```ts
import type { SubjectKeyRegistryLike } from "@pleach/compliance/hashchain";

const subjectKeys: SubjectKeyRegistryLike = {
  // MUST be idempotent — a repeated DSAR for the same subject must not throw.
  async shred(tenantId, subjectId) {
    await kms.scheduleKeyDeletion(`${tenantId}/${subjectId}`);
  },
};
```

**Per-scope keys.** `createEnvelopeKekProvider` from `@pleach/core/crypto`
wraps each subject key under a key-encryption key owned by a subject, a
shared scope or a customer. A KEK is generated and stored wrapped by a root
you inject, supplied as raw material, or a reference to the customer's own
KMS key through a client you inject. Core imports no KMS SDK.
`createLocalSubjectKekRoot` is a root that needs no external service, for
development. Wrapped keys name the KEK that sealed them, so a scope can
change keys and older keys still open. The provider's `rewrapStoredKek` moves a stored KEK
to the current root and proves the new bytes open before it commits. The
provider is experimental, and its wrapped-key format freezes at the first
durable write.

**Call-ledger rows.** A row in the call ledger is sealed under its
`principal.userId` whenever one is set, for every actor kind: `user`,
`scheduled`, `system` and `guest`. Before, a scheduled, system or guest row
with a user id was sealed under its session, so shredding that user's key
left those rows readable. A user id in a reserved subject namespace
(`session:`, `tenant:`, `shadow:`) is refused, and the row falls back to its
session subject. Because the user id now picks the sealing key for every
actor kind, it must come from a validated credential on every write path.

Rows sealed before this change don't record their subject. The reader tries
the current subject first, then the session subject the old rule used. A
legacy row is erased only by shredding its session subject.

**For local development and tests**, `@pleach/core/attestation/testing` ships a
file-backed signer. It expects a raw 32-byte ed25519 seed on disk, not a PEM file.

```ts
import { FileBackedAttestationKeyStore } from "@pleach/core/attestation/testing";
const attestationKeyStore = new FileBackedAttestationKeyStore({ privateKeyPath });
```

Use a KMS-backed `AttestationKeyStore` in production — the file-backed one is a
development affordance, and the shred proof is only as trustworthy as the key that
signed it.

## End-to-end example [#end-to-end-example]

```ts
import { executeErasureRequest } from "@pleach/compliance/hashchain";

/**
 * `subjectKeys` is the plug-point for your own key custody (cloud KMS,
 * HSM, Vault). The package ships no concrete registry.
 */
const subjectKeys = {
  async shred(tenantId: string, subjectId: string): Promise<void> {
    await kms.destroyKey(`${tenantId}/${subjectId}`); // idempotent
  },
};

async function handleDsarRequest(
  tenantId: string,
  subjectEmail: string,
  caseId: string,
  operatorEmail: string,
) {
  const result = await executeErasureRequest({
    request: {
      tenantId,
      subjectId: subjectEmail,
      reason: `${caseId} Art 17(1)(a)`,
      operator: operatorEmail,
    },
    subjectKeys,
    attestationKeyStore, // your KMS-backed AttestationKeyStore
  });

  // result.shredded     === true   — the subject's key is destroyed
  // result.chainRebuilt === false  — the chain was not touched
  // result.attestation             — signed shred proof; check with verifyErasureAttestation()

  await persistAttestation(pool, { caseId, erasureResult: result });
  return result;
}
```

## Example: an erasure request during a litigation hold [#example-an-erasure-request-during-a-litigation-hold]

**Example: a former employee asks for erasure while their sessions are under
hold.** Acme runs the [WORM tier](/docs/worm) on Postgres with a KMS-backed
subject-key registry. Legal has placed a `chat` hold on the former employee's
sessions. The data-protection officer is asked what happened to the request and
whether the record still verifies.

1. The scheduled `runChainRetentionPass` reaches those chats. The destroy
   function returns `held` with the hold id and deletes nothing.
2. The disposal record gets a `held` row naming the target, reason, actor and
   outcome ([Disposal records](/docs/worm#disposal-records)).
3. Legal releases the hold through the attributed release function. The next
   retention pass destroys the chats and records `destroyed` with a row count.
4. `executeErasureRequest` shreds the subject's key and returns a signed
   attestation. Store it with the case.
5. `verifyChainForChat` still passes, because crypto-shredding never rewrote a
   row. `verifyErasureAttestation` checks the proof.

The officer can show the `held` row, the release, the `destroyed` row and the
attestation. Backups, replicas and copies outside the event log aren't covered;
see [Erasure limits](/docs/compliance/erasure-limits). A registry with no hold
checker wired shreds regardless of holds, so order the steps yourself.

## Erasing a permission approver [#erasing-a-permission-approver]

Permission rows name who approved them by a reference, not by id (see
[Approver references](/docs/audit-ledger#approver-references)). The id
mapping isn't chained. `eraseApprover` deletes that mapping and leaves every
event-log row untouched, so each signed row still verifies.

```typescript
import {
  createPgApproverIdentityStore,
  createPgPermissionLedgerClient,
  eraseApprover,
} from "@pleach/core/audit/permission-ledger";

const result = await eraseApprover(
  {
    identities: createPgApproverIdentityStore(pool, { tenantId }),
    client: createPgPermissionLedgerClient(pool),
    dialect: "postgres",
    tenantId,
  },
  approverId, // the id, or an hmac-sha256: reference
);
```

* **Given a reference**, it erases every reference to the id that reference
  named.
* **`erased`** is how many identity rows were deleted.
* **`plaintextRows`** counts the tenant's earlier rows that name the id in
  clear. Those rows are never rewritten. It is `null`, with a `reason`, when
  the count could not run; the erase has still happened.
* **`lowercasedRevokeRows`** is set when the id has capitals and older revoke
  rows name it lowercased. Those may belong to another approver, so check them
  by hand.

## Public surface [#public-surface]

* `executeErasureRequest` factory, from `@pleach/compliance/hashchain`.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="HashChainMiddleware (deprecated)" href="/docs/compliance/hashchain-middleware" description="Deprecated helper whose pre-write anchors nothing verifies. EventLogWriter stamps the chain; verify with verifyChainForChat." />

  <Card title="Erasure limits" href="/docs/compliance/erasure-limits" description="What a crypto-shred does not erase: backups, plaintext written outside encryption, copies outside the event log." />

  <Card title="Hash chain" href="/docs/hash-chain" description="Substrate-level walkthrough of @pleach/core's chain primitives." />

  <Card title="Compliance" href="/docs/compliance" description="The full @pleach/compliance surface — redaction, scrubbers, audit query, PDF export." />

  <Card title="Regulated domain agent" href="/docs/regulated-domain-agent" description="End-to-end recipe composing compliance + hash chain + erasure." />
</Cards>
