# Security (/docs/security)



The runtime defaults to deny: [storage](/docs/storage) adapters are RLS-aware, the
[audit ledger](/docs/audit-ledger) is append-only, the [fingerprint](/docs/fingerprint)
isolates tenants, and the plugin contract stops a plugin from rewriting the
lattice or bypassing the synthesize seam. This page covers what the substrate
enforces and what you're still on the hook for.

## Reporting a vulnerability [#reporting-a-vulnerability]

Email `getpleach@protonmail.com` with subject `Security disclosure`
for anything you find in the runtime itself — not in an application
built on top of it. Acknowledgement lands within two business days;
confirmed reports get a fix-or-mitigation plan and, if a published
`@pleach/*` package needs one, a CVE. No paid bounty — reports get a
real response, not a payout. Full disclosure policy: [Community](/community).

## What the substrate enforces [#what-the-substrate-enforces]

| Property                                                       | Enforcement                                                                                          |
| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| Tenant isolation in the [cache](/docs/cache)                   | Cache keys include the tenant, so tenants never share a bucket                                       |
| Append-only audit                                              | The ledger interface has no update or delete call; the hash chain makes edits detectable             |
| RLS-bound storage (signed-in clients)                          | The schema bundle scopes every core table to its owner for signed-in clients; `anon` matches none    |
| Plugin can't rewrite the lattice                               | Plugins declare nodes, not edges; registration refuses a node that overrides a core stage            |
| Plugin can't bypass the final answer step                      | The runtime owns that step                                                                           |
| Plugin can't reach the modelfamily matrix                      | Plugins resolve models through the adapter; a lint rule in Pleach's own source enforces the boundary |
| [Sync](/docs/sync) conflicts surface, never silently overwrite | The merge is gated on a version comparison                                                           |
| Replay [determinism](/docs/determinism)                        | Deterministic reducers and fingerprinting                                                            |

Getting these wrong fails CI or throws at runtime. They're contracts, not posture.

## What you're on the hook for [#what-youre-on-the-hook-for]

| Concern                                    | Where it lives                                                            |
| ------------------------------------------ | ------------------------------------------------------------------------- |
| Auth (who the request is)                  | Your handler — `authToken` and `userId` come from there                   |
| Service-role key handling                  | Server-only code paths; never reach the browser bundle                    |
| RLS policy correctness for shared sessions | Extend the bundle's owner-scoped policies for membership                  |
| Tenant-scoped runtime construction         | `organizationId` passed on every `new SessionRuntime`                     |
| Tool execution sandboxing                  | Tools that touch the filesystem / shell / network are your responsibility |
| Plugin trust model                         | Plugins run in-process; vet what you install                              |
| Provider key handling                      | BYOK / gateway pattern keeps tenant credentials scoped                    |

## Auth: `authToken` and `userId` [#auth-authtoken-and-userid]

Two distinct fields on `SessionRuntimeConfig`:

* `userId` is the row owner. It drives RLS in storage and tenant
  attribution in the audit ledger.
* `authToken` is the bearer token forwarded to outbound API calls
  (provider, gateway, sync endpoints). It isn't exposed to plugin code.

Resolve both before runtime construction:

```typescript
const session = await auth.verifyRequest(req);
if (!session) return new Response("Unauthorized", { status: 401 });

const runtime = new SessionRuntime({
  storage,
  userId:         session.userId,
  organizationId: session.orgId,
  authToken:      session.bearerToken,
});
```

Never default `userId` to `"anonymous"` in production. The runtime accepts it
for tutorials and mock mode, but it leaks tenant attribution in a real deployment.

## Service-role keys [#service-role-keys]

The Supabase service-role key bypasses RLS, and the substrate uses it in
server-side adapters. &#x2A;*Service-role clients never belong in browser bundles.**

1. **Server-only imports.** Import service-role clients only in
   `app/api/*` (Next.js), `server/*` (Remix), or equivalent. Browsers reach
   the runtime over HTTP.
2. **Build-time check.** A bundler check can fail builds that pull
   server-only imports into client chunks.
3. **`@pleach/core/query` is server-only.** It bypasses RLS by design.
   Importing it from a client component is an anti-pattern; flag it in CI lint.

## RLS extensions for shared sessions [#rls-extensions-for-shared-sessions]

The default policies are owner-scoped: a user sees only rows they own. For
multi-user sessions within a tenant, replace the owner-only select policy on the
sessions table with one that also admits users in your session-membership
table, and keep the owner check in the same policy.

Apply the same change to the checkpoints and call-ledger tables. The call
ledger also needs a tenant filter, because leaking audit rows across tenants is
a security event whatever the session membership.

<Callout type="warn">
  Per-**user** isolation on the event log is **chat ownership**, not
  per-event actor. One chat's log mixes actors (user, system, subagent), so
  filtering by actor would hide rows from the owner and break reconstruction,
  export, and cost projections. Check in the API route, *before* the
  event-log query, that the caller created the chat. The user gets the
  complete trail if and only if they own the chat.
</Callout>

## Tool sandboxing [#tool-sandboxing]

The substrate doesn't sandbox tool execution. A tool that reads the filesystem,
spawns a process, or makes outbound HTTP requests runs with the host
process's privileges.

Mitigations, in order of strength:

1. **Schema-validate every input.** `defineTool` validates with Zod before `execute` runs.
2. **Honor `ToolContext.signal`.** Tools that ignore it keep running after the
   user aborts, which is a DoS vector for expensive work.
3. **Require approval for destructive tools.** Set `InterruptConfig.perToolApproval`
   for tools that write or delete.
4. **Move untrusted code into [`@pleach/coding-agent`](/docs/coding-agent).**
   It runs guest-supplied code in a microVM (Vercel Sandbox or equivalent), not
   in the host process.

### Filesystem tools and a shared root [#filesystem-tools-and-a-shared-root]

The `fs_*` tools from `@pleach/core/base-tools` confine every path to their roots and refuse `denyPaths` (default: a built-in sensitive-path denylist). Two options tighten writes and shared roots:

* **`writeGuard`** is your write policy. Returning a message, or throwing, refuses an `fs_write` or `fs_edit` call.
* **`rootLock`** keeps the tools from racing code that has the same root mounted read-write. Without it, a directory swapped for a symlink between the tools' check and use goes unnoticed. With a registry set, the tools also refuse a call once a root resolves somewhere else.

Create one registry with `createRootLockRegistry()` and give the same instance to the fs tools and to your code runner. The runner holds the root `"exclusive"` while a cell runs; fs calls hold it `"shared"`.

```typescript
import { createRootLockRegistry } from "@pleach/core/base-tools";

const rootLock = createRootLockRegistry(); // waitTimeoutMs 180000, maxKeys 1024

// In your code runner, around one cell:
const release = await rootLock.acquire(realRootPath, "exclusive");
try {
  await runCell();
} finally {
  release();
}
```

A request that times out, is aborted, or exceeds `maxKeys` is refused with `RootLockRefusedError` (`code: "ROOT_LOCK_REFUSED"`), and the fs call returns a failed result. No published code runner takes the lock for you, so it only helps when your runner does.

## Plugin trust model [#plugin-trust-model]

`HarnessPlugin` is an in-process extension contract. Plugins run with the
runtime's privileges, like any in-process library, so you choose what to install:

* Install only plugins you'd accept as ordinary npm dependencies.
* Pin versions in `package.json` and review changelogs on upgrade.
* Isolate untrusted code in separate processes or containers, each with its own
  agent instance and plugin set.

## Provider key handling (BYOK) [#provider-key-handling-byok]

Two patterns, documented in [Multi-tenant](/docs/multi-tenant):

* **BYOK via runtime construction** threads the tenant key into the provider
  at runtime build. It works when one tenant uses one provider.
* **Gateway plugin**: `@pleach/gateway` reads tenant context off the runtime
  and routes with its own credentials store. Use it when tenants share a
  provider but have different rate limits or fallback chains.

Either way, provider keys stay out of the browser bundle, audit-ledger payloads
(the ledger records `family`, `model` and `transport`, never the credential),
and logs.

## Audit ledger as evidence [#audit-ledger-as-evidence]

The ledger API has no update or delete call, and the schema ships owner-scoped
RLS policies. Neither stops someone with direct database access from changing
rows. `@pleach/compliance` adds a [hash chain](/docs/hash-chain), so an edit,
deletion or reordering is detectable after the fact. Stamping is on by default.

For SOC 2, HIPAA and FDA Part 11 reviews, the chain is the foundation. A chain
is a mechanism, not compliance: the
[Part 11 and ALCOA+ page](/docs/compliance/part-11-alcoa) shows what Pleach
provides and what you still provide, and the
[SEC and FINRA page](/docs/compliance/sec-finra) does the same for
broker-dealer rules.

## Sync conflicts and confused-deputy [#sync-conflicts-and-confused-deputy]

Sync detects conflicts at write time. The default merger picks `merged` when
fields don't overlap and `local` when they do. If `local` is the wrong default
for a field (say, a server-side compliance flag the client shouldn't override),
pass a custom merger in `SyncCoordinatorConfig.merger` that picks `remote` for it.

A misconfigured default merger is the closest the substrate comes to a
confused-deputy issue, so review it.

## Secrets in environment variables [#secrets-in-environment-variables]

The [Env vars](/docs/env-vars) page lists what the runtime reads at startup.
To keep secrets in memory no longer than needed:

* Read `process.env.X` once at runtime construction and pass the resolved
  value as config.
* For per-request secrets (a BYOK key resolved from a session), build the
  runtime per request, as in [Multi-tenant](/docs/multi-tenant).

## Logging and PII [#logging-and-pii]

The default loggers write event types and ids, not payloads. Plugins can log
anything, so vet them.

The durable audit ledgers scrub free-text fields by default
(`createScrubberChainRedactor()`): emails, API keys, JWTs and phone numbers in
interrupt decisions, plan intents and envelope text. They don't scrub
`pluginPayloads` or `modelCall`. For regulated identifiers, add the
`@pleach/compliance` scrubbers; see [scrubbers](/docs/scrubbers). Passing
`null` or `piiRedactorNoop()` stores those fields raw.

Error text, logs and probes are redacted separately, for credentials and private
host names; see [redaction](/docs/redaction).

## Production checklist [#production-checklist]

* [ ] Service-role keys server-only; CI enforces no import in client bundles
* [ ] `userId` and `organizationId` always passed; never defaulted
* [ ] Schema bundle applied; RLS extended for membership if needed
* [ ] Default ledger redactor left on; `@pleach/compliance` scrubbers added for regulated deployments
* [ ] `TamperEvidence` wired for evidence-required deployments
* [ ] Plugin set audited; versions pinned
* [ ] Tool inputs Zod-validated (automatic; verify no `as any` escapes)
* [ ] `InterruptConfig.perToolApproval` configured for destructive tools
* [ ] Sync merger reviewed for confused-deputy-safe defaults
* [ ] DevTools (`useHarnessDevTools`) gated behind `NODE_ENV !== "production"`

## Security-shaped substrate features [#security-shaped-substrate-features]

Several features ship security-relevant behavior by default. They reduce where
your own discipline can slip; they don't replace it.

* **Scrubber gate at write time.** Every event log row passes through registered
  `Scrubber` instances before it is stored. `@pleach/compliance` ships four
  (`SSN-US`, `Luhn`, `US-DL`, `KeyedRegex`); hosts add more via
  `contributeScrubbers`. See [Scrubbers](/docs/scrubbers) and [Compliance](/docs/compliance).
* **Tamper-evident hash chain.** Each event log row carries a hash that makes
  silent backfills, reorders and removals detectable. Writer-side stamping is on
  by default. See [Hash chain](/docs/hash-chain).
* **Multi-tenant scoping.** `runtime.tenant` stamps the tenant on every event
  log row, audit ledger row and OTel span, and (via `withTenantHeader`) on every
  outbound HTTP request. RLS at the database layer enforces it. Core's base
  schema ships owner and service-role policies; the tenant policies come with
  `@pleach/compliance`, so apply its
  [tenant RLS schema tier](/docs/compliance#the-tenant-rls-schema-tier) and verify
  it with `auditRlsPolicies()`. See [Tenant facet](/docs/tenant-facet).
* **Audit-record version log.** Lists which fields changed in which release, so
  you can pin alert thresholds to a version. See [Typed records](/docs/typed-records).
* **OTel `pleach.tenant_id` attribute.** Set on every span when `runtime.tenant`
  is configured, for per-tenant trace queries. See [OTel observability](/docs/otel-observability).

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

<Cards>
  <Card title="Multi-tenant" href="/docs/multi-tenant" description="Tenant-isolation patterns and the production checklist." />

  <Card title="Schema" href="/docs/schema" description="The RLS template and how to extend it." />

  <Card title="Audit ledger" href="/docs/audit-ledger" description="The compliance plug-points (`TamperEvidence`, `PIIRedactor`, `GDPRSoftDelete`)." />

  <Card title="Env vars" href="/docs/env-vars" description="What the runtime reads from the environment." />

  <Card title="Scrubbers" href="/docs/scrubbers" description="Write-time PII gate with four shipped detectors and host extension." />

  <Card title="Hash chain" href="/docs/hash-chain" description="Tamper-evident chaining over event log rows." />
</Cards>
