diff --git a/specs/REQ-000017-prevent-overlapping-top-level-pools/contracts/doctor-root-pools.md b/specs/REQ-000017-prevent-overlapping-top-level-pools/contracts/doctor-root-pools.md new file mode 100644 index 0000000..41bcab4 --- /dev/null +++ b/specs/REQ-000017-prevent-overlapping-top-level-pools/contracts/doctor-root-pools.md @@ -0,0 +1,94 @@ +# Contract: Doctor root-pool diagnostics + +**Source**: [spec.md](../spec.md), FR-7 and AC-9, AC-10, NFR-3, NFR-4. +**Existing surfaces**: `cmd/ipam/doctor.go`, `cmd/ipam/output.go`, root `Client`. + +## Read-only public diagnostic seam + +Add a root-library diagnostic method rather than duplicating private document +codecs in the CLI: + +```go +type RootPoolDiagnostic struct { + Check string + PoolIDs []string + Detail string +} + +func (c *Client) DiagnoseRootPools(ctx context.Context) ([]RootPoolDiagnostic, error) +``` + +`Check` is `root-overlap` or `root-registry`; `PoolIDs` are sorted known valid +pool IDs, and `Detail` is static, operator-safe wording. The method performs no +create, put or delete. Storage/decoding failures return no partial-success claim; +doctor renders an explicit `root-registry` FAIL with an error class, not raw +registry bytes (FR-7, C-I.2, C-V.1; AC-9, AC-10). + +## Checks and severity + +| Input snapshot | Check | Status | Trace | +| --- | --- | --- | --- | +| Two usable same-family roots have an intersecting canonical CIDR | `root-overlap` | FAIL | FR-7, AC-9, NFR-3 | +| Usable roots are all same-family disjoint and registry membership matches | no negative row; one global PASS may summarize consistency | PASS | NFR-4 | +| Registry absent with one or more usable roots | `root-registry` | FAIL | FR-7, FR-11, AC-10 | +| Registry absent with no usable roots | `root-registry` | PASS (`not initialized; no roots`) | FR-9, AC-1 | +| Invalid/unsupported registry, duplicate entry, invalid state/family/CIDR | `root-registry` | FAIL | FR-7, AC-10 | +| Usable root absent from a present registry, or active entry does not match usable incarnation/family/CIDRs | `root-registry` | FAIL | FR-7, AC-10 | +| `pending` or `deleting` entry cannot yet be matched to the final usable/deleted shape | `root-registry` | WARN | FR-7, AC-10; no-auto-repair scope | + +Every confirmed overlap pair produces one row with both sorted IDs. WARN does +not mean the range is released: pending and deleting claims continue to reserve +it. Existing doctor aggregation remains any FAIL -> `fail`/exit 6, otherwise any +WARN -> `warn`/exit 0, otherwise `pass`/exit 0. + +## Example JSON subset + +Only fictional identifiers and ranges are allowed in examples. The following is +an illustrative subset, not a claim about the current store: + +```json +{ + "result": "fail", + "checks": [ + { + "check": "root-overlap", + "pool": "example-a,example-b", + "status": "FAIL", + "detail": "usable root pools example-a and example-b overlap in address family 4" + } + ] +} +``` + +Table mode uses the existing `CHECK POOL STATUS DETAIL` columns and `RESULT:` +footer. Check details identify affected pool IDs, state and schema/error class; +they do not contain raw keys, URL, endpoint, credential, backend message, or +untrusted document contents. + +## Snapshot rules + +1. List every direct usable root through existing pool-document consistency + rules. Child pools do not participate (FR-1, FR-6; AC-15). +2. Compare canonical ranges independently from registry entries so legacy + overlap is found even if the registry is missing or wrong (FR-7, AC-9). +3. Compare the same snapshot with registry membership, state, family, + incarnation and full CIDR list (AC-10). +4. Do not create, replace, delete or “repair” any object, including the registry + and pool documents. Do not retry a diagnostic by publishing (FR-7, + no-auto-repair scope). +5. A single read sequence cannot distinguish a legitimate in-flight `pending` + transition from interruption, so report it as WARN with explicit wording, + never FAIL-to-WARN default fallback and never automatic cleanup (ASM-6). + +## Verification + +- At least 10 deterministic overlap fixtures cover equal, contained, enclosing + and partial intersections for both families where useful; each reports all + affected pools (NFR-3). +- At least 10 deterministic disjoint or adjacent root sets produce no false + overlap row (NFR-4). +- Recording stores assert zero `CreateIfAbsent`, `PutIfMatch` and `DeleteIfMatch` + calls in root diagnostics (FR-7 and doctor read-only convention). +- Keep doctor permission, output, write-probe and fragmentation behavior under + the existing BASE-0015 and REQ-000070 tests; root diagnostics run only as + additional read-only rows (AC-10). diff --git a/specs/REQ-000017-prevent-overlapping-top-level-pools/contracts/root-pool-overlap.md b/specs/REQ-000017-prevent-overlapping-top-level-pools/contracts/root-pool-overlap.md new file mode 100644 index 0000000..cf278c1 --- /dev/null +++ b/specs/REQ-000017-prevent-overlapping-top-level-pools/contracts/root-pool-overlap.md @@ -0,0 +1,102 @@ +# Contract: Root-pool overlap coordination + +**Source**: [spec.md](../spec.md), FR-1..FR-6, FR-9..FR-11 and AC-1..AC-8, +AC-12..AC-16. +**Consumers**: Root `ipam.Client`, CLI callers and doctor diagnostics. + +## Existing public API + +Keep these signatures and semantics: + +```go +func (c *Client) CreatePool(ctx context.Context, spec PoolSpec) (Pool, error) +func (c *Client) DeletePool(ctx context.Context, poolID string) error +func (c *Client) ListPools(ctx context.Context) ([]Pool, error) +``` + +No new API is needed to create or configure the registry. The path is internal, +and ordinary reads continue to return `Pool` values without coordination +metadata (FR-2, FR-10; AC-1, AC-2, AC-15). + +## Root create outcomes + +| Condition | Result | Trace | +| --- | --- | --- | +| Valid disjoint root in a store with no registry/roots | Pool becomes usable; registry contains one `active` entry | AC-1 | +| Disjoint from all applicable roots | Pool becomes usable; its own reservation transitions to `active` | FR-2, AC-2 | +| Same-family canonical range intersects another registry reservation | No proposed pool/state document becomes usable; `*OpError`, `Reason == "overlap"`, `errors.Is(err, ErrConflict)` | FR-3, FR-4, AC-3, AC-4, AC-12, AC-13 | +| Equal/adjacent/mixed scenario | Equal ranges conflict; adjacent ranges succeed; another family succeeds | FR-1, FR-6, AC-3, AC-4, AC-7, AC-8 | +| Concurrent overlapping proposals with normal CAS | Exactly one reservation may become active; loser returns overlap or retries to the existing contention result; never two usable roots | FR-5, AC-5, NFR-1 | +| Identical exact root already usable and active | Existing idempotent success, zero replacement pool-doc writes | FR-10, AC-15 | +| Present registry cannot be decoded | No overwrite or adoption; return the existing unsupported/document error category | FR-7, AC-10 | + +The overlap category must not match `ErrInvalidCIDR` or the `pool_exists` +reason. Contention remains a separate result as defined by `client.go` and +BASE-0004. (AC-12.) + +## Registry protocol + +At every CAS transition, decode the complete current registry, validate the +entry invariants, mutate an isolated copy and encode deterministic JSON before +writing. Opaque `storage.Version` values are round-tripped, never parsed. + +Bootstrap and create reservation are one conditional creation when possible: + +1. `Get(rootRegistryKey)`. +2. If missing, list/decode all usable roots and build an active snapshot. +3. Check the proposal against every same-family reservation. +4. `CreateIfAbsent` a sorted document containing existing active roots plus the + proposed `pending` entry. +5. If creation loses, reread and repeat the check/`PutIfMatch` transition; never + overwrite an existing key without its exact version. + +For an existing registry, add or transition the claim with `PutIfMatch`. +On `ErrUnknownOutcome`, reread and treat the operation as success only if the +exact own entry and document version-independent fields prove this call's write +landed. This follows `CreatePool` and backend-contract patterns; it is not a +blind success fallback. (FR-5, AC-5, NFR-1.) + +## Lifecycle integration + +- A child pool never reserves a registry entry; its parent allocation remains + the overlap boundary (FR-6 and out of scope). +- A root pending claim precedes both pool document writes. The existing + state/pool `CreateIfAbsent` order and own-incarnation cleanup remain (FR-5, + FR-10; AC-1..AC-5). +- A failed root publication removes only a matching `pending` entry for this + call and only after its own pool documents are absent. Cleanup failure is + joined to the original error so it remains explicit (AC-10, AC-15). +- A root delete checks nonempty and incarnation rules first, CAS-writes + `active|pending -> deleting`, runs the existing document deletion, then + removes the matching `deleting` entry (FR-10; AC-15). +- `pending`, `active` and `deleting` all reserve their ranges. Only removal + after successful lifecycle completion releases a range (FR-3; AC-5). + +## Prefix matching + +Reuse `canonicalPool` before comparison. For same-family entries and every pair +of prefixes, overlap is `netip.Prefix.Overlaps`; equal, enclosing, contained and +partial intersections all match. Adjacent prefixes and an IPv4/IPv6 pair do +not match. Existing CIDR input acceptance and mapped IPv4 normalization are +unchanged. (FR-1, FR-6, FR-10; AC-3, AC-4, AC-7, AC-8, AC-14.) + +## Compatibility and storage permissions + +The reserved key starts below the existing `pools/` prefix, uses a leading-dot +basename invalid as a pool ID, and requires the same object capability already +needed to create/delete root pool definitions. Pool listing filters it through +the existing pool-ID parser. Doctor discovery must likewise ignore keys whose +basename is not a valid pool ID (C-I.1, FR-6; AC-6, AC-7). + +Pool and allocation-state documents retain existing schema bytes. Existing +stores bootstrap lazily on a root mutation. Mixed old/new writers are not safe +and are outside the concurrent-client guarantee; rollout must quiesce old +versions (ASM-4; FR-5, AC-5, NFR-1). + +## Public and documentation vocabulary + +Documentation identifies the rule as: “A root pool is rejected when any +canonical CIDR overlaps a root pool of the same address family in the same +store. Doctor reports legacy overlap and registry inconsistency.” It does not +claim cross-store, cross-family or child-pool coordination (FR-8, AC-11 and +out-of-scope set). diff --git a/specs/REQ-000017-prevent-overlapping-top-level-pools/data-model.md b/specs/REQ-000017-prevent-overlapping-top-level-pools/data-model.md new file mode 100644 index 0000000..0332771 --- /dev/null +++ b/specs/REQ-000017-prevent-overlapping-top-level-pools/data-model.md @@ -0,0 +1,89 @@ +# Data model: Root-pool overlap coordination + +**Source**: [spec.md](spec.md) +**Design**: [plan.md](plan.md), [root contract](contracts/root-pool-overlap.md) + +## Persisted entity: root registry + +| Field | Shape | Invariants and lifecycle | Trace | +| --- | --- | --- | --- | +| Storage key | `pools/.root-registry.json` | Reserved internal key, excluded from valid pool IDs. Shared by every root operation in one storage prefix. No new backend or credential key. | FR-1, FR-5, FR-6, AC-5, AC-6, AC-7 | +| `schema_version` | Integer, `1` | Unknown value returns `ErrUnsupportedSchema`; never reinterpret or overwrite automatically. | FR-10, AC-10 | +| `kind` | Literal `root_pool_registry` | Wrong value is an invalid document; codec returns a non-overlap error. | AC-10 | +| `roots` | Array of root entries sorted by `pool_id` | Exactly one entry per pool ID; no child pools. An absent key is bootstrap-capable, a present invalid document is not. | FR-1, FR-6, FR-11, AC-9, AC-10, AC-16 | + +## Root entry + +| Field | Shape | Invariants and lifecycle | Trace | +| --- | --- | --- | --- | +| `pool_id` | Valid pool ID | Unique. It is the lifecycle and diagnostic identity, never a customer identifier. | FR-10, AC-9, AC-10, AC-12 | +| `incarnation` | Existing 16-byte hex format | Must match both usable pool documents while `active`; retained through `deleting` to prevent adoption by a replacement. | FR-10, AC-15 | +| `family` | Integer `4` or `6` | Must equal the family inferred from every canonical CIDR. | FR-1, FR-6, AC-3, AC-4, AC-7 | +| `cidrs` | Sorted canonical strings | One or more; same-family and internally disjoint under existing `canonicalPool`; full membership is replaceable by a future CAS update. | FR-1, FR-10, AC-13, AC-14; future-prefix constraint | +| `state` | `pending`, `active`, `deleting` | Defines the only legal transitions below. Every state reserves its complete range. | FR-3, FR-5, FR-7, AC-5, AC-10, AC-15 | + +Example with fictional pool data: + +```json +{ + "schema_version": 1, + "kind": "root_pool_registry", + "roots": [ + { + "pool_id": "example-root", + "incarnation": "0123456789abcdef0123456789abcdef", + "family": 4, + "cidrs": ["192.0.2.0/24"], + "state": "active" + } + ] +} +``` + +## State transitions + +```text +absent --CreateIfAbsent with bootstrap + proposed claim--> pending +active --valid empty DeletePool--> deleting --documents absent + CAS--> absent +pending --own matching documents usable + CAS--> active +pending --owned publication failure, own documents absent + CAS--> absent +pending --valid delete of matching usable empty pool--> deleting +``` + +1. `pending` means the range is reserved but publication is not yet confirmed. + It can become `active` only after both pool documents match its incarnation + (FR-5, FR-10; AC-1, AC-5). +2. `active` means a usable root exists and registry fields exactly match its + definition. A future prefix update can replace this entry's `cidrs` under one + CAS while preserving the state and incarnation (future-prefix constraint; + AC-16). +3. `deleting` means the range remains reserved while matching pool documents + are removed. It can return to absent only after the current call observes + those documents absent (FR-3, FR-10; AC-15). +4. No path from `deleting` to `active` exists. A replacement root cannot reclaim + the range until the old entry is removed (FR-3, FR-5; AC-5). + +## Derived entities + +| Entity | Fields | Invariants | Trace | +| --- | --- | --- | --- | +| Canonical proposed root | Pool ID, family, CIDRs, incarnation generated by the call | Uses `canonicalPool`; no mixed family or internal overlap. It does not become usable before registry reservation. | FR-1, FR-10, AC-1..AC-4, AC-13, AC-14 | +| Overlap result | Proposed ID, conflicting ID, same-family matching canonical ranges | Produced only for range intersection; maps to `ErrConflict` reason `overlap`. | FR-4, AC-3, AC-4, AC-12 | +| Root diagnostic | Check name, status, affected pool IDs, static detail | A derivation, not persisted; contains no endpoint, raw registry bytes or credentials. | FR-7, AC-9, AC-10, C-I.2/C-V.1 | +| Bootstrap set | Sorted usable root entries from `ListPools`/matching document pairs | Formed only when the registry key is absent; preserves all usable roots, including legacy overlapping roots for doctor to report. | FR-11, AC-9, AC-16 | + +## Consistency rules + +- An `active` entry and usable root must match ID, incarnation, family and CIDRs. +- Every usable root must have an entry once a registry is present. +- `pending` and `deleting` may be observed without a usable root. They are a + warning because the read cannot distinguish active work from interruption; + they still reserve their ranges. +- A pending/deleting entry must never be automatically deleted by doctor or a + normal read. A create compensates only its own `pending` entry after proving + its own documents did not publish; a delete completes only a + matching `deleting` entry (FR-5, FR-7; AC-5, AC-10). +- Overlap is strict address intersection. Adjacent ranges do not overlap; + different stores and address families are independent (FR-6; AC-6..AC-8). +- Existing pool and allocation-state documents do not gain fields and retain + their current schema and migration behavior (FR-10; AC-15, AC-16). diff --git a/specs/REQ-000017-prevent-overlapping-top-level-pools/decisions/ADR-0001-stack.md b/specs/REQ-000017-prevent-overlapping-top-level-pools/decisions/ADR-0001-stack.md new file mode 100644 index 0000000..879d2af --- /dev/null +++ b/specs/REQ-000017-prevent-overlapping-top-level-pools/decisions/ADR-0001-stack.md @@ -0,0 +1,45 @@ +# ADR-0001: Retain the exact-pinned Go library and Cobra CLI stack + +**Status**: Proposed for G3 +**Trace**: AC-1..AC-16; FR-8; NFR-1..NFR-4; constitution III. + +## Context + +`go.mod` declares `github.com/appvia/ipam`, Go 1.27.3 and Cobra v1.10.2. +`pool.go`, `client.go`, `storage/storage.go` and `cmd/ipam/doctor.go` already +provide the lifecycle, CAS, retry, storage and diagnostic seams required by the +approved spec. `mise.toml` pins Go 1.27.3 and golangci-lint 2.14.0; CI retains +cross-platform tests, Linux race checks, lint and backend emulator coverage. + +The change is one persisted JSON coordination document and a local extension to +pool/doctor behavior. It needs no new service, runtime, SDK or dependency. + +## Decision + +Implement the design in the existing root Go library and Cobra CLI. Reuse +standard `net/netip`, `errors`, maps/slices and the existing internal document +codec patterns. Add no runtime dependency or tool. Use `make build`, `make test` +and `make lint`; preserve the current `go.mod`/`go.sum`, `mise.toml`, `mise.lock` +and CI workflows. + +Use the product's `ac-test-mapping` skill for later Story evidence. No separate +Go stack skill exists in the product checkout, so the commands above are the +explicit build, test and lint contract. + +## Alternatives considered + +- A separate registry service/database would add availability, deployment, + identity and data-synchronisation concerns without improving one-object CAS + atomicity required by AC-5. +- A new coordination dependency or language would duplicate existing retry, + document and storage behavior and create a toolchain migration outside scope. +- A CLI-only prevention check would not protect library callers and would fail + AC-1 through AC-5. + +## Consequences + +The feature is covered by the existing tests and release path in one repository. +No package/tool pin changes are needed, and all backends retain their storage +contract. Root registry tests must exercise memory, local and existing emulator +paths without changing provider implementations. Any future dependency or +toolchain need requires a separate design decision. diff --git a/specs/REQ-000017-prevent-overlapping-top-level-pools/decisions/ADR-0002-root-registry.md b/specs/REQ-000017-prevent-overlapping-top-level-pools/decisions/ADR-0002-root-registry.md new file mode 100644 index 0000000..f921c85 --- /dev/null +++ b/specs/REQ-000017-prevent-overlapping-top-level-pools/decisions/ADR-0002-root-registry.md @@ -0,0 +1,41 @@ +# ADR-0002: Serialize root overlap decisions in a CAS registry + +**Status**: Proposed for G3 +**Trace**: FR-1..FR-6, FR-9; AC-1..AC-8, AC-12..AC-14; NFR-1. + +## Context + +Each root pool is currently represented by an allocation-state document and a +pool definition. There is no shared object across roots. A creator can list +current pools and still race another creator that observed the same snapshot, +so sequential overlap checking is insufficient. The approved requirement +permits only storage conditional writes for correctness. + +## Decision + +Add one versioned document at `pools/.root-registry.json`. It lists every root +reservation with ID, incarnation, family, canonical CIDRs and lifecycle state. +Root creates read the registry, reject same-family `netip.Prefix.Overlaps` +matches and CAS-add a `pending` entry before publishing pool documents. A +successful reservation is unique by storage conditional semantics. The +document lives below the existing `pools/` capability and uses a basename that +cannot be a valid pool ID. + +## Alternatives considered + +- List-then-create was rejected because two creators can both observe no roots. +- One object per possible prefix was rejected because intersection spans + arbitrary, nested and partial ranges with no finite precomputed key set. +- A lock file or in-process mutex was rejected because it is not shared reliably + across processes and violates the CAS-only constraint. +- Creating the registry under a new top-level prefix was rejected to avoid + expanding the permissions needed for existing root writers. + +## Consequences + +All root operations share a small contention point. Disjoint roots may retry +when their registry versions race, bounded by existing client semantics. A +storage backend that ignores CAS cannot provide the invariant; the existing +backend qualification and doctor write probe remain mandatory. The registry's +full CIDR list supports a future CAS replacement when prefix add/remove is +introduced, without changing this design. diff --git a/specs/REQ-000017-prevent-overlapping-top-level-pools/decisions/ADR-0003-lifecycle-migration.md b/specs/REQ-000017-prevent-overlapping-top-level-pools/decisions/ADR-0003-lifecycle-migration.md new file mode 100644 index 0000000..af9cb5d --- /dev/null +++ b/specs/REQ-000017-prevent-overlapping-top-level-pools/decisions/ADR-0003-lifecycle-migration.md @@ -0,0 +1,51 @@ +# ADR-0003: Preserve safety through lifecycle states and lazy migration + +**Status**: Proposed for G3 +**Trace**: FR-3, FR-7, FR-9..FR-11; AC-5, AC-9, AC-10, AC-15, AC-16. + +## Context + +Registry reservation and pool publication cannot be one object-storage +transaction, and root deletion cannot atomically remove a claim and both pool +documents. Processes may stop between steps. An older store may contain usable +roots with no registry. Doctor cannot distinguish every in-flight creator from +an interrupted one using only a read snapshot. + +## Decision + +Use `pending`, `active` and `deleting` entries. A creator reserves `pending`, +publishes matching documents and advances to `active`; ordinary failure rolls +back only an owned pending claim after proving its own documents are absent. A +deleter transitions an empty matching root to `deleting`, removes documents and +then removes the entry. Every state reserves its ranges. + +When the registry key is absent during a root mutation, build the initial +document from all currently usable roots and atomically include the proposed +pending entry when applicable. Preserve pool documents and represent legacy +roots as `active`. A present malformed registry is never rebuilt or overwritten +automatically. + +Doctor reports stable mismatches and legacy overlap as FAIL, and pending or +deleting uncertainty as WARN. It never removes state. A later exact create or +delete can finish only a transition for which it can prove the matching own +incarnation and documents. + +## Alternatives considered + +- Active-only entries were rejected because an interrupted publication looks + complete and cannot safely be distinguished during recovery. +- Time-based claim expiry was rejected because clock skew and duration would add + a non-CAS correctness dependency and could release a live creator's range. +- Automatic doctor repair was rejected because a cleanup read can race a creator + that has not yet published. +- Mandatory store migration was rejected because FR-11 permits preserving + existing roots and the product has no external store migration command. + +## Consequences + +Crashes favor temporary false contention over duplicate address use. Operators +must inspect doctor warnings and apply a reviewed manual recovery process when +state is genuinely abandoned; automatic repair is outside this requirement. +Legacy bootstrap preserves existing overlapping roots, which remain diagnostic +failures. All concurrent writers must participate in registry behavior during +rollout because older clients cannot honour an object they do not read. diff --git a/specs/REQ-000017-prevent-overlapping-top-level-pools/plan.md b/specs/REQ-000017-prevent-overlapping-top-level-pools/plan.md new file mode 100644 index 0000000..3c7335b --- /dev/null +++ b/specs/REQ-000017-prevent-overlapping-top-level-pools/plan.md @@ -0,0 +1,202 @@ +# Technical Design: Prevent overlapping top-level pools + +**Spec**: `specs/REQ-000017-prevent-overlapping-top-level-pools/spec.md` +**Created**: 2026-12-01 +**Status**: Draft for G3 +**Risk rating**: See [threat-model.md](threat-model.md); the threat model is authoritative. + +## Summary + +Add one versioned root-registry document at `pools/.root-registry.json` and make +it the CAS serialisation point for root CIDR membership. `CreatePool` reserves +canonical ranges in `pending`, publishes the existing pool and allocation-state +documents, then marks the entry `active`; failed publication compensates only +its own pending reservation. `DeletePool` transitions a usable empty root to +`deleting` before removing documents, then removes the entry. `ipam doctor` +compares the registry with usable root pools and reports confirmed overlap or +coordination inconsistency without repair. This satisfies AC-1..AC-16 and the +CAS-only constraint while leaving child pools and storage backends unchanged. + +## Technical context + +**Languages and versions**: Go 1.27.3 and golangci-lint 2.14.0, exact-pinned in +`mise.toml` and locked; Cobra v1.10.2 and all runtime dependencies remain +exact-pinned in `go.mod`/`go.sum`. + +**Stack decision**: [ADR-0001-stack.md](decisions/ADR-0001-stack.md). Retain +the existing Go library, Cobra CLI and CAS-capable object-storage abstraction. +The product has an `ac-test-mapping` skill; no separate Go stack skill is +present. Build, test and lint are `make build`, `make test`, and `make lint`. + +**Repositories touched**: `appvia/ipam` only. + +**Storage**: Existing S3, Azure Blob, local and memory stores. Add one JSON +object below the already permitted `pools/` prefix; no new service, bucket, +region, endpoint, credential or permission model. + +**Testing**: Existing Go unit, race, cross-platform, backend-contract and CLI +test suites. Use deterministic synthetic prefixes and recording/fault stores. +Retain emulator integration tests for the unchanged backend behavior. + +**Constraints**: NFR-1..NFR-4; storage CAS only; preserve root lifecycle and +canonicalisation; future prefix updates must be representable; doctor remains +read-only; no automatic repair, backend or credential change (spec FR-5, FR-10, +FR-11 and out of scope). + +## Constitution check + +| Principle | How the design complies | Exception (needs approver sign-off) | +| --- | --- | --- | +| I. Security baseline | The registry is below existing `pools/*` capability, stored input is strictly decoded, overlap input reuses canonical validation, errors include no endpoint or secret, and storage CAS remains the trust boundary. No authentication, authorisation, dependency or external integration change. | None. | +| II. Test standards | The AC map below names proof for every AC. Concurrency proof uses deterministic barriers and at least 1,000 trials; classification uses at least 100 trials; doctor uses at least 10 positive and 10 negative fixtures. Existing suites remain enabled. | None. | +| III. Technology choice | Existing Go/Cobra stack and exact tool pins are retained. `go.mod`/`go.sum`, `mise.toml` and CI require no dependency change. | None. | +| IV. Accessibility | No new graphical interface. CLI/table diagnostics remain textual and machine-readable under the existing JSON contract, without colour-only status. | None. | +| V. Data handling | Registry and diagnostics contain only pool IDs, canonical CIDRs, families, incarnations and state. Tests use synthetic RFC-style address space. No personal data, customer identifiers, credentials or production values. | None. | + +## Existing code and patterns + +| Evidence | Pattern relied on | Trace | +| --- | --- | --- | +| `pool.go`: `CreatePool`, `createPoolAttempt`, `publishPool` | Preserve per-call incarnation and `CreateIfAbsent` publication; reserve the root range before either pool document can make the pool usable. | AC-1..AC-5, AC-13, AC-14 | +| `pool.go`: `DeletePool`, `deletePoolAttempt` | Pin one incarnation, refuse nonempty residue, delete state before definition, and conditionally finish interrupted work. Add registry `deleting` around this existing sequence. | AC-15, AC-16 | +| `canonical.go`: `canonicalPool`, `canonicalPrefix` | Canonicalize, normalize mapped IPv4 and sort ranges before checking any registry entry. Do not introduce a second CIDR grammar. | FR-1, FR-10, AC-3, AC-4, AC-8, AC-14 | +| `doc.go`, `document.go`, `internal/document/types.go` | Version and strictly decode every persisted object; leave pool and allocation-state wire schemas unchanged. | FR-10, AC-15, AC-16 | +| `client.go`: retry/backoff and `withoutPoolLocks` | Reuse opaque-version CAS retry and prove correctness with in-process locks disabled. | FR-5, AC-5, NFR-1 | +| `storage/storage.go` and `storagetest` | Use only `Get`, `CreateIfAbsent`, `PutIfMatch`, `DeleteIfMatch` and `List`; retain all backend contracts. | CAS-only constraint, AC-5 | +| `errors.go`, `pool.go` `poolExistsError` | Return wrapped sentinels with `OpError.Reason`; use `overlap` as the distinct public subtype. | FR-4, AC-3, AC-4, AC-12 | +| `cmd/ipam/doctor.go`, `output.go` | Reuse global/per-pool checks, table/JSON shapes and FAIL-over-WARN aggregation. | FR-7, AC-9, AC-10, NFR-3, NFR-4 | +| `README.md` Concepts, Storage layout and error list | Add root-overlap behavior next to the existing root-pool definition and stored-object layout. | FR-8, AC-11 | +| Baselines `BASE-0001`, `BASE-0004`, `BASE-0006`, `BASE-0007`, `BASE-0010`, `BASE-0015` | Preserve lifecycle, retry, error, document, storage and doctor contracts. | All ACs | + +## Components + +| Component | Repo | Responsibility | Acceptance criteria / constraint | +| --- | --- | --- | --- | +| Root registry codec | appvia/ipam | Strictly encode/decode the `root_pool_registry` v1 document under `pools/`; sort entries and CIDRs deterministically. | FR-1, FR-10, AC-10, AC-14, AC-15 | +| Root registry mutation | appvia/ipam | Bootstrap, read, overlap-check, reserve, activate and remove registry entries with CAS and unknown-outcome rereads. | FR-2..FR-6, FR-9, FR-11, AC-1..AC-8, AC-13..AC-16 | +| Root pool lifecycle integration | appvia/ipam | Reserve before `publishPool`; compensate only an owned pending claim; coordinate registry `deleting` with existing nonempty and incarnation rules. | FR-3, FR-5, FR-10, AC-3..AC-5, AC-15, AC-16 | +| Root diagnostics API | appvia/ipam | Read usable roots and registry, classify overlap/mismatch and return structured, redacted diagnostics. | FR-7, AC-9, AC-10, NFR-3, NFR-4 | +| Doctor reporting | appvia/ipam | Render root overlap/registry diagnostics through current table and JSON formats with no writes. | FR-7, AC-9, AC-10 | +| Pool documentation | appvia/ipam | Document the same-store/same-family create rule, registry layout and doctor role. | FR-8, AC-11 | + +## Root create protocol + +1. Validate and canonicalize the root spec using existing `validatePoolSpec` and + `canonicalPool` behavior. Child creates skip the registry (FR-1, FR-6; + AC-3, AC-4, AC-6, AC-7, AC-13, AC-14). +2. Read the target pool documents and, for a repeated usable exact root, retain + existing idempotent behavior only after confirming or bootstrapping matching + registry membership (FR-10; AC-15, AC-16). +3. Load the registry. If absent, list usable roots and seed `active` entries, + including their incarnations, families and canonical CIDRs. A proposed root + is added to this initial document as `pending` (FR-9, FR-11; AC-1, AC-16). +4. Reject if any entry other than the exact own incarnation has a CIDR with the + same family that overlaps the proposal. Return `Reason: "overlap"`, + `ErrConflict`; adjacency and another family do not match (FR-2, FR-4, + FR-6; AC-2..AC-4, AC-6..AC-8, AC-12). +5. CAS-write the new pending entry. On stale version or ambiguous outcome, + reread. Accept only an entry exactly matching this ID/incarnation and range + as this call's claim, otherwise retry through the existing backoff + (`FR-5`; AC-5; NFR-1). +6. Publish the existing authoritative-state document then pool definition. + The pool becomes usable only under the existing matching-incarnation rule + (FR-10; AC-1, AC-2, AC-14, AC-15). +7. Verify the own documents and CAS-transition the entry `pending -> active`. + If publication returns an ordinary error and both own documents are absent, + CAS-remove the owned pending entry. A crashed process may leave a pending + reservation; doctor reports it but never repairs it (FR-7; AC-9, AC-10). + +## Root delete protocol + +1. Perform the existing empty-pool and incarnation checks (FR-10; AC-15). +2. CAS-transition the matching `active` entry to `deleting`. If a matching + `pending` entry already backs usable documents, a delete may transition it + to `deleting`; creator activation then loses its CAS and cannot revert the + deletion (FR-5, FR-10; AC-5, AC-15). +3. Delete the authoritative state and pool definition with the existing + incarnation/version protections (FR-10; AC-15). +4. CAS-remove only the matching `deleting` entry. A crash keeps the range + reserved and a subsequent deletion can finish it; it never makes the pool + usable again (FR-3, FR-7; AC-10, AC-15). + +`pending` and `deleting` entries continue to participate in overlap decisions; +only their CAS removal releases a root range (FR-3, FR-5; AC-5, AC-10). + +## Doctor contract + +Doctor remains read-only. It reads the registry and usable roots, then emits: + +- `root-overlap` FAIL for each same-family pair of usable roots; detail names + both pool IDs (FR-7; AC-9; NFR-3, NFR-4). +- `root-registry` FAIL for missing registry with usable roots, invalid schema, + duplicate entry, usable root missing from an existing registry, or active + entry mismatch (FR-7; AC-10). +- `root-registry` WARN for a non-reconciled `pending` or `deleting` transition, + describing it as potentially in-progress or interrupted; ranges remain + reserved (FR-7; AC-10 and no-auto-repair scope). + +No raw document bytes, endpoint, credential or underlying error that can carry +private backend configuration enters a root diagnostic detail (C-I.2, C-V.1). +Existing doctor FAIL/WARN precedence and zero/exit-6 behavior remain. + +## Contracts + +- [contracts/root-pool-overlap.md](contracts/root-pool-overlap.md): registry + wire format, CAS protocol, conflict behavior and lifecycle integration. +- [contracts/doctor-root-pools.md](contracts/doctor-root-pools.md): read-only + diagnostics, row identities, statuses and report examples. + +## Data model + +See [data-model.md](data-model.md). The new persisted entity is only the root +registry; existing pool, allocation-state and storage versions are unchanged. + +## Decisions + +- [ADR-0001-stack.md](decisions/ADR-0001-stack.md): retain the exact-pinned Go/Cobra stack. +- [ADR-0002-root-registry.md](decisions/ADR-0002-root-registry.md): one CAS registry is the overlap serialisation point. +- [ADR-0003-lifecycle-migration.md](decisions/ADR-0003-lifecycle-migration.md): use explicit states, lazy legacy bootstrap and diagnostic-only recovery. + +Design assumptions and analysis findings are in [research.md](research.md). + +## Rollout + +1. Release the client/CLI with registry codec, create/delete integration, + doctor checks and documentation (FR-8; AC-1..AC-16). +2. Quiesce or upgrade every writer to a version that participates in the + registry before concurrent root mutation begins (ASM-4; FR-5; AC-5, NFR-1). +3. On first root mutation, bootstrap from all currently usable roots; no pool + document is rewritten or adopted. Existing overlapping legacy roots remain, + and doctor reports them (FR-11; AC-9, AC-16). +4. Run doctor after rollout and before enabling wider root creation. Review + failures manually; the design performs no automatic repair (FR-7, AC-10). +5. Rollback requires stopping new root mutations, then removing the code under + normal product release procedures. Do not delete or edit the registry while + any new client can create roots; it still protects addresses (FR-5, AC-5). + +## Validation and AC-to-test map + +These are proposed names for implementation; this design does not claim they +have run. + +| Acceptance criteria | Named proof and measurable assertion | +| --- | --- | +| AC-1, AC-2 | `TestCreateRootRegistryHappyPaths`: first create and a disjoint create become usable and registry entries are `active`. | +| AC-3, AC-4 | `TestCreateRootOverlapConflict`: table of equal, enclosing, contained and partial intersections for IPv4 and IPv6; `errors.Is(ErrConflict)`, reason `overlap`, zero rejected documents. | +| AC-5, NFR-1 | `TestConcurrentOverlappingRootCreates`: barrier-based pairs across 1,000 deterministic seeds, with `withoutPoolLocks`; exactly one success and no more than one usable pool in every trial. Run for migrated and legacy allocation-state modes. | +| AC-6, AC-7 | `TestRootOverlapScope`: separate stores and other address families remain successful. | +| AC-8 | `TestAdjacentRootsAllowed`: table of adjacent IPv4/IPv6 ranges succeeds. | +| AC-9, NFR-3 | `TestDoctorReportsRootOverlap`: at least 10 equal/nested/enclosing/partial fixtures, each reports both pool IDs. | +| AC-10 | `TestDoctorReportsRootRegistryInconsistency`: missing key with roots, corrupt/unsupported schema, duplicate, absent member and active mismatch. | +| AC-11 | G3 reviewer checks README content against the required root rule, registry location and doctor role. CI may check links/structure, but an automated test must not assert the documentation's wording. | +| AC-12, NFR-2 | `TestRootOverlapPublicClassification`: 100 deterministic rejections all match `ErrConflict` with reason `overlap` and not invalid-CIDR, `pool_exists` or contention. | +| AC-13 | `TestCreateRootMultiCIDROverlapIsAtomic`: one overlapping and otherwise disjoint list leaves no proposed documents or registry member. | +| AC-14 | `TestCreateRootOverlapCanonicalization`: accepted mapped/non-masked input is compared after canonicalization and rejected when it aliases an existing range. | +| AC-15 | `TestRootRegistryLifecycleIncarnations`: pending, active, deleting and mismatched incarnations cannot create an independently usable or adopted root. | +| AC-16 | `TestBootstrapLegacyRootRegistry`: usable legacy roots are preserved, all become active entries, and later overlap checks apply. | +| NFR-4 | `TestDoctorRootOverlapNoFalsePositives`: at least 10 disjoint/adjacent valid root sets produce zero `root-overlap` rows and no registry failure. | + +Additional regression proof: fault stores inject failures at registry create/put, +pool-state create, pool-definition create and activation; unknown outcomes are +reread before rollback. Keep all existing pool lifecycle, migration, child +allocation, delete, storage-contract and doctor suites. diff --git a/specs/REQ-000017-prevent-overlapping-top-level-pools/research.md b/specs/REQ-000017-prevent-overlapping-top-level-pools/research.md new file mode 100644 index 0000000..751dfbb --- /dev/null +++ b/specs/REQ-000017-prevent-overlapping-top-level-pools/research.md @@ -0,0 +1,109 @@ +# Research: Prevent overlapping top-level pools + +**Spec**: [spec.md](spec.md) +**Created**: 2026-12-01 + +## Codebase evidence + +| Evidence | Pattern and consequence | Trace | +| --- | --- | --- | +| `pool.go` `CreatePool`, `createPoolAttempt`, `publishPool`, `createOwnDocument` | Root creation already separates authoritative-state and pool-definition writes, retries CAS failures, and handles ambiguous write outcomes by rereading. Add the registry reservation before this publication sequence and compensate only the reservation owned by the call. | AC-1..AC-5, AC-13, AC-14 | +| `pool.go` `DeletePool`, `deletePoolAttempt`, `deletePoolDocument` | Pool deletion already pins an incarnation, removes state before definition, and retries conditional deletes. Add a registry `deleting` transition before document deletion and remove the claim after both documents are absent. | AC-10, AC-15, AC-16 | +| `pool.go` `ListPools`, `readPoolDocuments`; `doc.go` | Pool usability means matching pool and allocation-state incarnations. The registry must compare only usable roots and carry the same incarnation. | FR-10, AC-15, AC-16 | +| `canonical.go` `canonicalPool`, `canonicalPrefix` and `validate.go` | Preserve canonical masking, mapped-address normalization, same-family validation and disjointness inside one pool. Use `netip.Prefix.Overlaps` only after these validations. | FR-1, FR-10, AC-3, AC-4, AC-8, AC-14 | +| `client.go` `Client`, `waitRetry`, `withoutPoolLocks` | In-process pool locks are optimization only. Every registry transition must retry opaque storage versions and pass the existing lock-disabled model. | FR-5, CAS-only constraint, AC-5, NFR-1 | +| `storage/storage.go` | `Get`, `CreateIfAbsent`, `PutIfMatch`, `DeleteIfMatch` and `List` provide the complete coordination surface; no backend extension is needed. | FR-5, storage-CAS constraint, AC-1..AC-5 | +| `errors.go`, `pool.go` `poolExistsError`; `specs/BASE-0006-error-contract/spec.md` AC-24 | Preserve sentinel identity through `OpError`. Reuse `ErrConflict` plus stable `Reason: "overlap"` for a deterministic root-range conflict. | FR-4, AC-3, AC-4, AC-12 | +| `cmd/ipam/doctor.go` `diagnose`, `checkResult`, `finish`; `specs/BASE-0015-cli-doctor/spec.md` | Add read-only root-overlap/registry rows to the existing table/JSON report without changing status aggregation or exit codes. | FR-7, AC-9, AC-10, NFR-3, NFR-4 | +| `README.md` Concepts and Storage layout | Extend the existing root-pool and storage-layout sections; the current documentation describes only non-overlap within one pool. | FR-8, AC-11 | +| `specs/BASE-0007-document-format/spec.md` and `document.go` | Treat the registry as a separately versioned JSON document, decoded strictly and never silently reinterpreted. Existing pool and allocation-state schemas remain unchanged. | FR-10, AC-15, AC-16 | + +## Decisions + +### D1 - Reserve ranges in one CAS registry + +**Decision**: Store all root reservations in `pools/.root-registry.json`. A create reads the current registry, rejects same-family intersections, adds the proposed pool as `pending`, and writes the registry through `CreateIfAbsent` or `PutIfMatch`. Only then may it publish pool documents. The registry is the serialisation point. + +**Rationale**: A list-then-publish check cannot close the two-creator race because roots otherwise have no shared object. One shared versioned object turns concurrent overlapping decisions into one winner and one stale-version loser. Keeping it below `pools/` lets identities that already create root pools use existing object grants without adding an authentication or IAM scheme. (FR-1, FR-2, FR-3, FR-5; CAS-only constraint; AC-1..AC-5, AC-6, AC-7, AC-13, AC-14.) + +**Alternatives considered**: + +- List all root documents then create both pool documents: rejected; concurrent creators can both observe the same empty snapshot and become usable. (AC-5, NFR-1.) +- One object per root or prefix: rejected; no single conditional operation can prove absence across every overlapping prefix, especially variable IPv4/IPv6 prefix lengths. (FR-5; future prefix-update constraint.) +- Locks or leases: rejected; the approved constraint permits storage conditional writes only. (FR-5.) + +### D2 - Keep a lifecycle state machine, not a lock + +**Decision**: Each registry entry has `pending`, `active`, or `deleting` state and the full current prefix set. A creator writes `pending`, publishes its two documents, verifies their incarnation, and CAS-updates to `active`. A deleter CAS-transitions a usable, empty pool to `deleting`, removes pool documents, and removes the entry. `pending` and `deleting` ranges remain reserved. + +**Rationale**: The state exposes interrupted work without allowing another creator to use the same address range. A repeated compatible create can finish `pending -> active`; a repeated delete can finish `deleting -> absent`. Full per-pool prefix membership can later be replaced by one CAS for prefix additions/removals, rather than requiring a new coordination model. (FR-10, FR-11; brief future-prefix constraint; AC-10, AC-15, AC-16.) + +**Alternatives considered**: + +- Registry insertion after pool publication: rejected because both creators can publish before either updates the registry. (AC-5.) +- An active-only registry with no pending/deleting state: rejected because interrupted creation or deletion becomes indistinguishable from valid data during recovery and diagnostics. (AC-10, AC-15, AC-16.) +- Per-prefix lock objects: rejected because overlapping arbitrary CIDRs need a cross-prefix intersection check and the model is harder to evolve for prefix updates. (FR-1, FR-11; future-prefix constraint.) + +### D3 - Bootstrap legacy stores at the first root mutation + +**Decision**: If the registry key is absent, construct it from all currently usable roots. A first or later root mutation atomically creates the key while adding the proposed `pending` claim; an exact repeat may create a registry containing the already usable pool. No read-only operation creates the registry. + +**Rationale**: This preserves pre-existing roots and makes the migration lazy, without an external migration command or a new public write side effect. Missing registry plus zero roots and missing registry plus existing roots are distinct from a present malformed registry; only the absent case is bootstrapped. (FR-9, FR-11; AC-1, AC-16.) + +**Alternatives considered**: + +- Fail all legacy stores: rejected because FR-11 requires preserving and indexing existing roots. (AC-16.) +- Rewrite or adopt the registry during `ListPools`: rejected because reads should not mutate a store and doctor must remain read-only. (FR-7, AC-9, AC-10.) +- Rebuild a malformed present registry: rejected because overwriting it could erase reservations and undermine create safety. (FR-7, AC-10.) + +### D4 - Diagnose, do not repair, persisted uncertainty + +**Decision**: `ipam doctor` independently derives usable roots and compares them with registry entries. It emits `FAIL` for confirmed same-family overlap, unsupported/corrupt registry, usable roots absent from an existing registry, or `active` entry mismatch. It emits `WARN` for an expected transient `pending` or `deleting` entry that is not fully reconciled; the detail identifies it as either in progress or interrupted, without deleting it. + +**Rationale**: Doctor cannot prove whether a cross-process creator is still running after taking a single read snapshot. A conservative warning reports interruption while a false-success repair could let two overlapping creators publish. Stable active/deleted fixtures have an exact consistency result. (FR-7, AC-9, AC-10, NFR-3, NFR-4; out-of-scope automatic repair.) + +**Alternatives considered**: + +- Automatically clear orphaned entries: rejected because it can race an active creator and violates the central overlap invariant. (FR-5, AC-5.) +- A time-based expiry: rejected because wall-clock timestamps are not a CAS correctness mechanism and can be skewed between processes. (FR-5, CAS-only constraint.) +- Report only usable-root overlap: rejected because an active-entry mismatch must be visible under FR-7 and AC-10. + +### D5 - Keep the existing public conflict shape + +**Decision**: Root overlap returns `*OpError{Op: "create pool", Pool: proposed.ID, Reason: "overlap", Err: ErrConflict}`. CAS contention remains a contention outcome; malformed or unsupported registry data remains a separately classified read error. The exact public reason is not overloaded with unrelated failures. + +**Rationale**: This follows existing allocation overlap and error-contract patterns and lets callers distinguish overlap from `pool_exists`, invalid CIDR and retryable contention. (FR-4, AC-3, AC-4, AC-12.) + +**Alternatives considered**: + +- A new sentinel: rejected as unnecessary; `ErrConflict` already classifies the category and `OpError.Reason` supplies the stable subtype. (FR-4, AC-12.) +- One generic registry conflict: rejected because it makes AC-12 unobservable to callers. (AC-12.) + +## Assumptions + +- **ASM-1**: “Update a store” in FR-11 means the first successful root `CreatePool` or root `DeletePool` operation that changes state; read-only operations and `ipam doctor` never create the registry. Reason: the product has no store-level update command, so a mutating pool lifecycle operation is the smallest safe migration point. Trace: FR-9, FR-11, AC-1, AC-16. +- **ASM-2**: A current registry entry's full `cidrs` list is the coordination snapshot for a root; pool definition and registry CIDRs must match when the entry is `active`. Reason: this directly supports diagnostics and future prefix membership replacement. Trace: FR-1, FR-10, AC-10, brief future-prefix constraint. +- **ASM-3**: A root registry entry remains a reservation from `pending` through `deleting`; only removal of the CAS-owned entry releases its ranges for a later create. Reason: liveness failures are safer than allowing a second overlapping root. Trace: FR-3, FR-5, AC-5, AC-10. +- **ASM-4**: Normal correctness assumes every concurrent root-mutating writer uses this client version during cutover; older binaries cannot be made to honour a document they do not read. Reason: the storage interface cannot stop an unaware writer, and rollout quiescence is the safe operational default. Trace: FR-5, CAS-only constraint, AC-5, NFR-1. +- **ASM-5**: CAS contention from registry transitions uses the client's existing bounded retry/backoff outcome. A normal conflict with an overlapping range is returned as `overlap`; exhausting version races remains `contention`. Reason: this preserves established `client.go` retry semantics and AC-5's allowed outcomes. Trace: FR-4, FR-5, AC-5, AC-12. +- **ASM-6**: A `pending` or `deleting` snapshot is diagnostic uncertainty, not proof of corruption; confirmed stale `active` state, missing registry membership and root overlap are deterministic failures. Reason: doctor cannot atomically prove absence of an in-flight writer with the available read API. Trace: FR-7, AC-9, AC-10, NFR-3, NFR-4. +- **ASM-7**: The key `pools/.root-registry.json` is reserved internal storage even though it shares the root-pool object prefix. Reason: its leading dot cannot match the pool-ID grammar and existing root writers retain the same `pools/*` capability. Trace: FR-6, AC-6, AC-7, C-I.1 and no-auth-change scope. + +## Adapted `speckit-analyze` findings (passes A-D and F) + +The analysis was read-only across `spec.md`, the drafted `plan.md`, `data-model.md` and this file. Pass E (task coverage) was omitted by the pipeline rules. + +| Pass | Finding | Resolution | +| --- | --- | --- | +| A - Duplication | No contradictory or near-duplicate design requirements were found. | None. | +| B - Ambiguity | The spec does not name the operation that updates a legacy store and does not define which registry mismatches count as inconsistent. | ASM-1 and ASM-6 make both details explicit; no scope edit is needed. | +| C - Underspecification | The concurrency guarantee does not state behavior for an older client that predates registry reads. | ASM-4 records the rollout prerequisite; no spec scope is changed. | +| C - Underspecification | The accepted `pending` and `deleting` windows are not visible in the spec's overlap-state entity. | D2 and ASM-3 define them as reservation-preserving states. | +| D - Constitution | No conflict. The key stays under the existing `pools/*` capability, tests are named for every AC, no secrets/data are added, and stack choices remain exact-pinned. | Recorded in plan Constitution Check. | +| F - Inconsistency | The spec uses the generic term “overlap-protection state”; the design introduces “root registry”. | Plan and artifacts define them as the same concept; no terminology change in an approved AC. | + +No `(proposed)` spec edits are required. + +## Open blockers + +None. All choices above fit the approved outcome and existing product conventions, and have safe defaults recorded as assumptions. diff --git a/specs/REQ-000017-prevent-overlapping-top-level-pools/threat-model.md b/specs/REQ-000017-prevent-overlapping-top-level-pools/threat-model.md new file mode 100644 index 0000000..24111b5 --- /dev/null +++ b/specs/REQ-000017-prevent-overlapping-top-level-pools/threat-model.md @@ -0,0 +1,84 @@ +# Threat model: Root-pool overlap coordination + +**Reviewed**: 2026-12-01 +**Inputs**: [spec.md](spec.md), [plan.md](plan.md), +[data-model.md](data-model.md), both contracts, ADRs and +`.specify/memory/constitution.md`. + +This is a design threat assessment. It does not claim implementation or exploit +evidence. It does not change the architecture. Fixtures and examples are +synthetic. + +## Scope, assets and trust boundaries + +| Asset | Security property | Evidence and design owner | +| --- | --- | --- | +| Root range uniqueness | Integrity and exclusivity across concurrently mutated roots | `CreatePool`/registry CAS protocol; AC-1..AC-5, NFR-1 | +| Root pool and allocation-state documents | Incarnation integrity and existing lifecycle | `pool.go`, `doc.go`; FR-10, AC-15 | +| Root registry document | CAS integrity, schema validity, complete prefix membership and recoverable state | `pools/.root-registry.json`; AC-9, AC-10, AC-16 | +| Doctor report | Truthful, redacted and actionable diagnosis | `cmd/ipam/doctor.go`; FR-7, AC-9, AC-10 | +| Storage conditional semantics | Only trusted linearisation and failure boundary | `storage.Storage`; BASE-0010, existing backend qualification | + +Trust boundaries: + +1. Untrusted `PoolSpec` crosses canonical validation before any storage write. +2. Multiple processes cross the shared storage boundary through opaque CAS + versions; each process trusts the backend to enforce conditions. +3. A new or legacy store crosses the root-registry bootstrap boundary on its + first root mutation; old binaries that do not read the registry must be + quiesced before rollout. +4. Stored registry/pool bytes cross strict codecs before diagnostics or create + decisions; malformed and unsupported data fails rather than being adopted. +5. Doctor crosses the output boundary using valid IDs, lifecycle state and static + classifications, never raw registry bytes, endpoint configuration or + credentials. + +## Threats + +| ID / area | Asset | Entry point and threat | Impact | Likelihood | Mitigation the design or a Story carries | Trace | +| --- | --- | --- | --- | --- | --- | --- | +| T-1: concurrency | Root range uniqueness | Two same-family creators reserve overlapping ranges from the same registry version | High: duplicate address space becomes usable | Low after CAS enforcement; high without it | One `CreateIfAbsent`/`PutIfMatch` serialisation point; stale/unknown-outcome reread; 1,000 barrier trials with pool locks disabled and all normal backends | FR-5, AC-5, NFR-1 | +| T-2: storage enforcement | Registry and pool documents | A non-enforcing backend accepts stale CAS and lets losing creators publish | High: registry and documents no longer protect allocation uniqueness | Low on qualified backends; medium for a caller-managed unsupported store | Preserve full storage contract and existing doctor write probe; no support-policy change or claim that opening proves CAS enforcement | FR-5, C-I.6; AC-5 | +| T-3: mixed versions / authorisation boundary | Root range uniqueness | An old or un-upgraded writer creates a root without reading the registry | High: the newer client may later observe an unregistered overlapping usable root | Medium during an uncontrolled rollout | Drain old root-mutating clients before enabling new roots, run doctor, and document the boundary; no silent compatibility assertion | ASM-4, FR-11, AC-16 | +| T-4: interrupted creation | Registry liveness and root integrity | Process stops after `pending` reservation or pool document publication | Medium: range is conservatively blocked; safe overlap is preserved | Medium for process/storage failure | Keep all states reserving; record ID/incarnation/CIDRs; own-call rollback only after proving documents absent; compatible retry may finalize `active`; doctor WARN reports uncertainty | FR-7, AC-10, AC-15 | +| T-5: interrupted deletion / authorisation ordering | Registry integrity | Delete removes documents but stops before deleting claim, or creator activation wins after a delete read | Medium: stale claim blocks reuse; unsafe window could lead to recreation or revival if state is wrong | Low with transition ordering | CAS `active/pending -> deleting` before document deletion; `deleting` never returns to active; remove entry only after matching documents are absent; race/fault tests | FR-3, FR-5, AC-5, AC-15 | +| T-6: input handling | Registry and overlap decision | Non-canonical, mixed-family, mapped-address, malformed or oversized stored input reaches overlap comparison | High: false acceptance or parser denial if validation is inconsistent | Low with shared canonicalisation and strict codec | Reuse `canonicalPool`/`canonicalPrefix`; validate schema, kind, IDs, states, family and complete CIDR list before decisions; fail closed, do not rebuild a present invalid registry | FR-1, FR-10, AC-3, AC-4, AC-14 | +| T-7: data exposure and secrets | Doctor report and errors | Raw registry bytes or backend errors expose endpoint, credential or private configuration | High: diagnostic output can leak sensitive configuration | Low if static details are enforced | Diagnostic seam returns IDs/state/error class; no raw URL, object bytes or backend message in root checks; synthetic regression fixtures and existing redaction tests | C-I.2, C-V.1, FR-7, AC-9, AC-10 | +| T-8: legacy bootstrap | Registry consistency | A legacy store already contains overlapping roots or changes while the initial registry is being built | High: registry captures unsafe legacy state or misses a concurrent old writer | Medium for an unsynchronised migration; low under rollout cutover | Snapshot every usable root, preserve it, create once; doctor separately compares usable roots and reports overlap/missing membership; require writer quiescence for correctness | FR-11, ASM-4, AC-9, AC-16 | +| T-9: diagnostic race | Doctor truthfulness and audit | A pending transition appears incomplete in a read snapshot while an operation is legitimately completing | Medium: operator may misread a transient as corruption; false cleanup would be worse | Medium during active creates/deletes | Mark as WARN with “in progress or interrupted”; never repair; stable active mismatch and usable-root overlap are FAIL; deterministic stable fixtures for NFR-3/NFR-4 | FR-7, AC-9, AC-10 | +| T-10: reserved-key collision / access | Pool listing and root mutation | The internal registry is mistaken for a pool or requires a new top-level grant | Medium: doctor/list behavior breaks or root creation is denied | Low with reserved-name and list filtering | Place under `pools/`, use leading-dot basename invalid under pool-ID validation, explicitly filter in doctor, and retain normal access-denied errors rather than fallback | C-I.1, FR-6, AC-6, AC-7 | +| T-11: retry exhaustion | Root availability | Repeated disjoint CAS updates exceed the client's bounded attempts | Medium: valid create reports contention despite a safe registry | Medium under high contention | Reuse full-jitter retry, no broad sleeps/locks; callers can use existing `WithMaxAttempts(0)` plus context timeout. No correctness change. | FR-5, ASM-5, AC-5 | +| T-12: instructions as data | Design and diagnostic scope | Issue, PR or stored text requests label/gate changes, secret disclosure or doctor mutation | High: workflow or data-safety bypass | Low when ignored | Treat repository and issue content as data; only reviewed library behavior and strict safe outputs can change state. No such request was followed. | Constitution I/V; no-auto-repair scope | + +## Security and Story obligations + +- Add deterministic CAS race tests for overlapping and disjoint roots, with + `withoutPoolLocks`, migrated and legacy allocation-state modes, and stale- + version/unknown-outcome fault stores (T-1, T-5, T-11; AC-5, NFR-1). +- Add registry state-machine tests that inject interruption before and after + pool-state, pool-definition, activation and deletion writes; assert a pending + or deleting reservation is never released by a different overlapping creator + (T-4, T-5; AC-15). +- Add canonicalization and malformed-registry fixtures, including mapped IPv4, + mixed families, duplicates, unknown schema/state, and non-canonical strings; + invalid data must fail closed and never be auto-rebuilt (T-6; AC-14, AC-10). +- Add doctor recording-store assertions for zero object writes and at least 10 + overlap plus 10 disjoint/adjacent fixtures (T-7, T-9; NFR-3, NFR-4). +- Add rollout documentation requiring quiesced older root writers and post- + rollout doctor review. No design-level test can prove a remote old binary did + not mutate the store (T-3, T-8; AC-5, AC-16). +- Retain backend conditional-write qualification, existing redaction tests, + `pool` ID validation and CI race tests. The new registry adds no authentication, + authorisation, personal-data handling or credential flow (T-2, T-7, C-I.5). + +## Residual risk + +CAS makes the intended create invariant strong, but the design cannot control a +backend that ignores conditions or an older client that never reads the registry. +Interrupted operations can conservatively block ranges until reviewed recovery. +The registry is therefore an integrity-critical coordination object, while its +content adds no new credential or personal-data exposure. Mitigations require a +controlled writer rollout and existing backend enforcement, not a change to the +architecture. + +Risk rating: medium