← Back to Pull requests

Security: fix 6 pkg/dotc1z audit findings; harden SQLite .c1z ingestion #1160

Closed
unknown closed this pull request without merging on Oct 03, 2026 14:46 UTC
View on GitHub
unknown unknown commented on Oct 03, 2026 00:39 UTC
Author

Summary

A security audit of pkg/dotc1z (the .c1z sync-artifact layer) reported 7 issues. This PR fixes 6 of them, each with a TestSecurity_ regression test that fails before the fix and passes after it. The seventh, forged grant digests, is not a vulnerability; the reasoning is below.

It also hardens SQLite .c1z ingestion. A v1 catalog that carries file-authored triggers or views now fails to open before any file-authored SQL runs. Nothing is stripped, repaired, or rewritten in the source.

No new exported API. The protection is the default behavior of the functions callers already use (dotc1z.NewStore, NewC1ZFile, NewC1File, AttachFile, CopyIsolateSync); there is nothing to opt into or out of. pkg/sync, pkg/tasks/c1api, pkg/dotc1z/c1zstore, and the Pebble engine's open path are unchanged from main.

Fixes

| # | Finding | Severity | Fix |
|---|---------|----------|-----|
| 1 | Attacker-controlled SQLite index names were interpolated unescaped into DROP INDEX during bulk-load open (SQL injection; arbitrary file creation through ATTACH was demonstrated) | high | c1file.go: quoteIdentifier on index names read from the file's schema |
| 2 | The compactor interpolated an unvalidated SyncID into the working-artifact filename. That escaped the temp dir, and the fold path then O_TRUNC-wrote the hostile base .c1z to attacker-chosen paths that persisted after cleanup | high | compactor.go: non-empty SyncIDs must match a token charset, so separators are rejected |
| 3 | The SQLite engine's ListGrantsForEntitlements page-token decoder panicked on a uint64 length wrap (decodeBatchCursor lenU+4), crashing an exported Reader RPC | medium | grants_for_entitlements.go: per-term bound check (ports the Pebble twin's fix) |
| 4 | Indexed-zstd extraction bypassed its budget on entry count: raw_size==0 frames extracted about 1.1M files/dirs at zero budget cost | medium | indexed.go: charge 512 B per entry against the decoded budget (mirrors tar header accounting) |
| 6 | A hostile sync-run keyspace turned one ListSyncs RPC into K×O(N) full-keyspace stats scans | medium | adapter_reader.go: stats come only from the canonical fixed key, once per RPC |
| 7 | LicenseProfileTrait.license_name passed through the sanitizer verbatim, breaking the identity-stripping contract | low | handlers.go: HMAC it like every other human-readable field |

Finding 5 (forged grant digests): not a vulnerability

The audit reported that a .c1z can carry grant-digest state that does not match its grants, and that the engine trusts it as present-means-exact. That is true, and it is not a security issue:

  • The digest is derived from data the writer already controls. The SDK computes it at EndSync from the grants in the same file. Anyone who can write a forged digest (the connector, or anything that can rewrite the .c1z) can write any grants they like. A forged digest gives them nothing beyond lying about the grants directly.

  • Its only platform consumer is a skip optimization. C1 reads just the per-entitlement root (GetEntitlementGrantDigest), to skip reconciling an entitlement whose digest matches the last reconciled value. That skip is behind a feature flag and is re-proven against the real grants within a TTL. The worst case for a wrong root is that C1 reflects that entitlement's grants late, which the writer could equally cause by withholding the grants. The digest is not an authorization input.

  • Bugs and corruption are already covered. The digest ABI stamp drops or gates digests built by other hash code, an absent digest means "recalculate", and C1's TTL revalidation catches drift.

  • Validating it is expensive. An earlier revision of this PR recomputed every digest from the grants at open. Measured end-to-end with NewStore:
  • | Grants | main read-only | validating read-only | main writable | validating writable |
    |---|---|---|---|---|
    | 100k | 12 ms | 462 ms | 12 ms | 240 ms |
    | 1M | 74 ms | 5.86 s | 72 ms | 2.99 s |

    That cost lands on every open, including the platform's read-only reader paths. That revision also had to choose between rejecting the digest states the engine itself writes (invalidated partitions, failed repairs) and loosening the check case by case. It was removed.

    SQLite ingestion hardening

    A .c1z is untrusted when it is imported. For SQLite, the danger is executable schema: a file-authored trigger runs the moment the SDK's own migrations touch its table.

  • Schema guard (sqlite_schema_guard.go). Rejects any persistent trigger or view anywhere in the catalog, non-table objects under SDK table names, and hidden/virtual/generated columns or hostile column names on SDK tables. It reads only sqlite_schema and PRAGMA table_list/table_xinfo and never executes file-authored SQL. It runs in InitTables before migrations, in CopyIsolateSync before the raw-copy DELETEs, and in AttachFile (ATTACH, validate, and DETACH-on-reject on one leased connection; the host is closed if that DETACH fails). This closes the v1 open-time trigger finding: a read-only open ran a file-defined RAISE(ABORT) trigger during the grant-backfill migration, and trusted_schema=OFF does not disable triggers.

  • Hardened opener (sqlite_open.go). _pragma=trusted_schema(OFF) is set on every physical connection through the DSN. This is defense in depth; the schema guard is what blocks triggers. Callers are trusted: a trusted_schema setting passed through WithC1FPragma or the caller's own file: URI is applied, not refused.

  • Constructor fixes. NewC1File closes the raw DB on every init failure (a leaked handle per rejected file was a DoS vector). A failing SQLite OpenStore returns a nil c1zstore.Store interface instead of a typed nil. parseTimeoutSeconds clamps instead of overflowing to a negative duration.
  • The guard reads catalog metadata only: one sqlite_schema scan, one table_list, and one table_xinfo per SDK table present, independent of row count.

    Compatibility

  • Deliberate default-behavior changes (all SQLite):

  • - a catalog with triggers, views, view or virtual SDK tables, generated columns, or hostile column names fails to open;
    - AttachFile rejects such a catalog.
  • Still opens: ordinary historical schemas — old tables, indexes, partial indexes, sqlite_stat, ALTER-appended columns, and unrelated ordinary tables (see the legacy acceptance controls). Pebble artifacts open exactly as on main.

  • Rejection errors: plain errors, retryable in pkg/tasks/c1api like every other bad-input error on main (ErrEnvelopeTruncated, ErrMaxSizeExceeded, corrupt headers).

  • Version: no API or wire change, so no version bump.
  • Limits

  • This is not a CHECK/default/foreign-key/expression-index allowlist and not a resource sandbox.

  • Changes made to a raw SQLite file by another process after validation are outside the guard's guarantee.
  • Verification

  • Each regression test failed before its fix and passes after it:

  • - TestSecurity_HostileIndexNameExecutesDDLDuringBulkLoadOpen: before the fix, the marker file was created. After it, the marker is absent and the hostile index is still dropped.
    - TestSecurityCompactSyncIDFilenameEscapeFold/Overlay + the NewCompactor rejection matrix
    - TestSecurity_DecodeBatchCursorRejectsUint64WrapTokens
    - TestSecurity_IndexedExtractionBudgetBoundsEntryCardinality
    - TestSecurity_ListSyncsBoundedAgainstHostileSyncRunCardinality
    - TestSecurity_SanitizeRewritesLicenseName
    - TestSecurity_HostileTriggerRejectedOnEveryRoute and TestSecurity_HostileTriggerMarkerNeverExecutes: every public route rejects, the trigger's marker never executes, and the source envelope is byte-for-byte unchanged.
    - TestSecurity_InitTablesReentryRejectsPlantedTrigger, …CopyIsolateSyncRejectsBeforeRawCopyDelete, …AttachFileRejectsHostileAttachment, …ConversionRejectsHostileV1, TestSecurity_SchemaGuardRejectionAndAcceptance. With the guard disabled, the triggers planted in the InitTables and CopyIsolateSync cases fire.
  • Controls for behavior that must not change:

  • - TestSecurity_LegacyOldSchemaAcceptedAndReadsCorrectly and …ConvertsAndIsolates: an old schema opens read-only with correct sync metadata and grants and an unchanged envelope, and both ToPebble and CopyIsolateSync accept it.
    - TestSecurity_InvalidVerificationClaimReadsUnverified: ingest-invariant markers this SDK can't validate read as unverified on both engines, never as an error, as on main.
    - TestOptionalPreviousSyncC1ZPath_SoftFails now includes a spare that the schema guard rejects: the optional path still syncs without replay, and the strict path fails.
  • go test -short -tags=baton_lambda_support ./... and golangci-lint (CI-pinned v2.13.2) pass locally.
  • Notes for reviewers

  • The audit also recorded 3 needs_validation findings that depend on deployment facts outside this repo: the v1 zstd FCS fail-fast bypass with its flat 10 GiB budget, the v3 payload budget ×100 scaling, and manifest sync_runs heap amplification.

  • The compactor still accepts the empty-SyncID sentinel ("resolve latest").
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: pquerna Review duration: 847m
    All Vouch review confidence checks passed
    Residual risk 0.34 = Change Risk (0.75) × (1 − Review Confidence (0.54)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.75 · 650 lines diff across 8 files
    0.75
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    54%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Sensitive Paths sensitive_paths
    0.075
    Real PR Conversation Timeline
    1 comments
    "Review active on #1160"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 54.2% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 75.2% (HIGH) · Higher = larger blast radius
    75.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 54.2% · Lower = rushed or shallow review
    54.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 34.4% · Safe to merge
    34.4%