From 27b198a0edd9045d18bb43e26ad54d72f82ffff8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 21:40:44 +0000 Subject: [PATCH 1/4] feat(core,engine): ownerWrites collections, read by the scope, written by the owner (FIX-1793 P1) A second mode of the owner-key fence beside ownerPrivate. A collection declaring `ownerWrites: { param }` keys rows with ownerSegment(userId) at that parameter. Every read path (handle, seed cache, browser routes, /state, debug) serves the row to anyone the scope serves; a create, update or delete is refused unless the session's user is the key's owner, with its own message. A reader holds refs it could write through, so the scope resource registry judges the rule where every write it makes meets the store (state mutate and delete, content write and delete), not only on the handle. The browser update and delete routes ask the same predicate. The startup fence arms for either mode, and the predicate decides on the collection's mode, not on the key alone. Core refuses both modes on one collection, and an eviction policy on an owner-writes one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- .changeset/owner-writes-collections.md | 6 + .../architecture/resources-and-client-data.md | 10 + docs/contributing/architecture-reference.md | 2 +- .../core/src/types/collection-patterns.ts | 5 +- .../core/src/types/resource-collection.ts | 33 +- .../core/test/resource-collection.test.ts | 53 +++ .../src/context/createExecutionContext.ts | 8 +- .../engine/src/context/resource-registry.ts | 51 ++- packages/engine/src/registry/flow-registry.ts | 6 +- .../engine/src/resources/owner-private.ts | 175 +++++-- packages/engine/src/routes/resource-routes.ts | 27 +- .../engine/test/owner-writes-fence.test.ts | 430 ++++++++++++++++++ 12 files changed, 735 insertions(+), 71 deletions(-) create mode 100644 .changeset/owner-writes-collections.md create mode 100644 packages/engine/test/owner-writes-fence.test.ts diff --git a/.changeset/owner-writes-collections.md b/.changeset/owner-writes-collections.md new file mode 100644 index 0000000000..43dde470ed --- /dev/null +++ b/.changeset/owner-writes-collections.md @@ -0,0 +1,6 @@ +--- +"@flow-state-dev/core": minor +"@flow-state-dev/engine": minor +--- + +`defineResourceCollection` accepts `ownerWrites: { param }`: every reader the collection's scope serves reads each row, and only the user the row's owner segment names writes it. Key rows with `ownerSegment(userId)` at that parameter, as for `ownerPrivate`, and the same pattern rules apply (the parameter appears once, no `**`); a browser read is allowed. A create, update or delete by anyone else, through the collection handle, a ref obtained by reading, or the browser update and delete routes, throws `A row of an owner-writes collection is written only by the user it belongs to.` and changes nothing. The startup fence covers these collections too: a wider collection in the same scope that can reach their keys, or the same pattern declared `ownerPrivate`, stops the app from starting. A collection can't declare both modes, and an owner-writes collection can't declare an `eviction` policy other than `"none"`. diff --git a/docs/architecture/resources-and-client-data.md b/docs/architecture/resources-and-client-data.md index 56f7307890..11837727f0 100644 --- a/docs/architecture/resources-and-client-data.md +++ b/docs/architecture/resources-and-client-data.md @@ -269,6 +269,16 @@ A collection declaring `ownerPrivate: { param }` owns every key whose first segm Workforce's private roster collection is the first consumer. Engine knows it only as an owner-private collection. +#### Owner-writes collections + +A collection declaring `ownerWrites: { param }` takes the same key shape, the same definition checks except the browser-read one, and both fences. It differs in one rule: **every reader the scope serves reads the row, and only its owner writes it.** + +- **Reads.** The key fence admits the row to every read path listed above, for any caller, as long as its first `~` segment sits at the owner parameter. The request-start seed cache admits it too, judged against the run's declared collections, since those collections serve it from that cache. +- **Writes.** A create, update or delete is refused with its own message (`A row of an owner-writes collection is written only by the user it belongs to.`) unless the session's user is the one the key's owner segment encodes. A reader holds refs it could write through, so the scope resource registry judges this where every write it makes meets the store (state mutate, state delete, content write, content delete), whichever handle, ref or eviction asked. The browser update and delete routes ask the same question before writing. +- **The startup fence** arms for either mode. An owner-private and an owner-writes declaration of one pattern are two declarations, and the second is refused. + +It reads only the key and the declaring collection, so a second process declaring the same collection over one store refuses the same writes. A flow that declares the pattern without the mode gets the key fence's plain-collection answer: absent, and refused on write. + ### Block-Level Resource Declarations Blocks declare resource dependencies via a single `resources` field: diff --git a/docs/contributing/architecture-reference.md b/docs/contributing/architecture-reference.md index bb836f11e9..8b751468de 100644 --- a/docs/contributing/architecture-reference.md +++ b/docs/contributing/architecture-reference.md @@ -165,7 +165,7 @@ Purposes and default models live in the catalog — don't restate them here. - `defineFlow` merges block-declared resources into the flow's `resources` map; flow-level wins over block-level - Same `defineResource()` reference across blocks = no conflict; different references for same name = build-time error - Collection snapshots emit `count` always and `prefetched` when `prefetchWindow > 0`; per-item `clientData` is gated by `client.state.read`. Lazy reads via `GET /sessions/:id/resources/:ref` and a flow-static manifest at `GET /sessions/:id/manifest` (FIX-427). -- A key segment beginning `~` belongs to an owner-private collection (`ownerPrivate: { param }`), in every app: no other collection reads or writes it, and a key's first one names its owner. A registry that has held one refuses, for good, any flow whose collection in the same scope can reach its keys, and every registry refuses a single resource whose key has a segment beginning `~` → [Resources and client data](../architecture/resources-and-client-data.md#owner-private-collections) +- A key segment beginning `~` belongs to an owner-keyed collection, in every app: no other collection reads or writes it, and a key's first one names its owner. An owner-private collection (`ownerPrivate: { param }`) serves the row only to that owner; an owner-writes collection (`ownerWrites: { param }`) serves it to every reader the scope serves and lets only that owner write it, judged where the run's writes meet the store. A registry that has held either refuses, for good, any flow whose collection in the same scope can reach its keys, and every registry refuses a single resource whose key has a segment beginning `~` → [Resources and client data](../architecture/resources-and-client-data.md#owner-private-collections) → [Resources and Client Data](../architecture/resources-and-client-data.md) diff --git a/packages/core/src/types/collection-patterns.ts b/packages/core/src/types/collection-patterns.ts index 65fab2f85a..e5ec9e113b 100644 --- a/packages/core/src/types/collection-patterns.ts +++ b/packages/core/src/types/collection-patterns.ts @@ -176,8 +176,9 @@ export function encodeUserSegment(userId: string): string { * The key segment that marks a row as `userId`'s: `~` plus * {@link encodeUserSegment}. * - * An owner-private collection (`ownerPrivate: { param }`) keys each row with - * this at its owner parameter, and serves the row only to that user. A key's + * An owner-keyed collection (`ownerPrivate: { param }` or `ownerWrites: { param }`) + * keys each row with this at its owner parameter: an owner-private one serves + * the row only to that user, an owner-writes one lets only that user write it. A key's * first segment beginning `~` is its owner in every app, so no other * collection reads or writes a key carrying one. The escaped id holds no `~` * and no `/`, so the segment is one segment with one marker. diff --git a/packages/core/src/types/resource-collection.ts b/packages/core/src/types/resource-collection.ts index 99cc193885..275136691c 100644 --- a/packages/core/src/types/resource-collection.ts +++ b/packages/core/src/types/resource-collection.ts @@ -78,6 +78,17 @@ export type ResourceCollectionConfig = { * has no browser read. */ ownerPrivate?: { param: string }; + /** + * Make each row readable by everyone the scope serves and writable only by + * the user it belongs to. `param` names the pattern parameter that holds the + * owner; key it with `ownerSegment(userId)`. Every read path serves the row, + * the browser routes included. A create, update or delete is refused unless + * the session's user is the one the owner segment names, and no other + * collection in the app reads or writes the rows. The pattern must declare + * `param` exactly once and must not use `**`. Not with `ownerPrivate`, and + * not with an `eviction` policy other than `"none"`. + */ + ownerWrites?: { param: string }; /** * Intrinsic scope this collection lives in. Required for new collections — * mirrors `defineResource({ scope })`. @@ -336,7 +347,19 @@ export function defineResourceCollection< ProjectedClient>, TConfig["client"]> > { validatePattern(config.pattern); + if (config.ownerPrivate !== undefined && config.ownerWrites !== undefined) { + throw new Error(`Collection "${config.pattern}" declares both ownerPrivate and ownerWrites; choose one.`); + } if (config.ownerPrivate !== undefined) assertOwnerPrivateShape(config); + if (config.ownerWrites !== undefined) { + const named = `Owner-writes collection "${config.pattern}"`; + assertOwnerKeyShape(config.pattern, config.ownerWrites.param, named); + // Every user's create sees every owner's rows, so its eviction would pick + // a row its caller may not delete. + if (config.eviction !== undefined && config.eviction !== "none") { + throw new Error(`${named} must not evict: an eviction would delete another user's row.`); + } + } if (config.contentTemplate !== undefined && config.contentTemplateRef !== undefined) { throw new Error( @@ -458,7 +481,6 @@ function assertOwnerPrivateShape( } ): void { const { pattern, client } = config; - const param = config.ownerPrivate?.param; const named = `Owner-private collection "${pattern}"`; if ( client?.state?.read === true || @@ -467,6 +489,15 @@ function assertOwnerPrivateShape( ) { throw new Error(`${named} must not enable a browser read.`); } + assertOwnerKeyShape(pattern, config.ownerPrivate?.param, named); +} + +/** + * The key shape both owner modes (`ownerPrivate`, `ownerWrites`) need: the + * owner sits at one known segment, so the pattern names the parameter exactly + * once, as a whole segment, and has no `**`. `named` opens each refusal. + */ +function assertOwnerKeyShape(pattern: string, param: unknown, named: string): void { const segments = pattern.split("/"); if ( typeof param !== "string" || diff --git a/packages/core/test/resource-collection.test.ts b/packages/core/test/resource-collection.test.ts index 4e3690696a..f2cd8114d4 100644 --- a/packages/core/test/resource-collection.test.ts +++ b/packages/core/test/resource-collection.test.ts @@ -719,6 +719,59 @@ describe("defineResourceCollection · ownerPrivate", () => { }); }); +// --------------------------------------------------------------------------- +// Owner-writes collections: the scope reads every row, only its owner writes it +// --------------------------------------------------------------------------- + +describe("defineResourceCollection · ownerWrites", () => { + const entries = (overrides: Record = {}) => + defineResourceCollection({ + pattern: "entries/[project]/[owner]/[entry]", + ownerWrites: { param: "owner" }, + scope: "org", + stateSchema: z.object({}).passthrough(), + ...overrides, + } as Parameters[0]); + + it("defines a collection that names its owner parameter once", () => { + const collection = entries(); + expect(collection.ownerWrites).toEqual({ param: "owner" }); + expect({ ...collection }.ownerWrites).toEqual({ param: "owner" }); + }); + + it("allows a browser read, since every row is readable by the whole scope", () => { + expect(() => entries({ client: { state: { read: true }, content: { read: true, prefetch: true } } })).not.toThrow(); + }); + + it("refuses a parameter the pattern lacks, or declares more than once", () => { + expect(() => entries({ ownerWrites: { param: "author" } })).toThrow( + 'Owner-writes collection "entries/[project]/[owner]/[entry]" must declare parameter "author" exactly once.' + ); + expect(() => entries({ pattern: "entries/[owner]/[owner]" })).toThrow( + 'Owner-writes collection "entries/[owner]/[owner]" must declare parameter "owner" exactly once.' + ); + }); + + it('refuses "**", because the owner has to sit at one known segment', () => { + expect(() => entries({ pattern: "entries/[owner]/**" })).toThrow( + 'Owner-writes collection "entries/[owner]/**" must not use "**": its owner sits at one segment.' + ); + }); + + it("refuses an eviction policy, which would delete another user's row on a create", () => { + expect(() => entries({ maxInstances: 5, eviction: "lru" })).toThrow( + 'Owner-writes collection "entries/[project]/[owner]/[entry]" must not evict: an eviction would delete another user\'s row.' + ); + expect(() => entries({ maxInstances: 5, eviction: "none" })).not.toThrow(); + }); + + it("refuses ownerPrivate beside it: a row has one owner rule", () => { + expect(() => entries({ ownerPrivate: { param: "owner" } })).toThrow( + 'Collection "entries/[project]/[owner]/[entry]" declares both ownerPrivate and ownerWrites; choose one.' + ); + }); +}); + describe("ownerSegment", () => { it("is ~ plus the escaped user id, one segment whatever the id holds", () => { expect(ownerSegment("alice")).toBe("~alice"); diff --git a/packages/engine/src/context/createExecutionContext.ts b/packages/engine/src/context/createExecutionContext.ts index 579c47d0cb..ff49cfc591 100644 --- a/packages/engine/src/context/createExecutionContext.ts +++ b/packages/engine/src/context/createExecutionContext.ts @@ -1271,15 +1271,19 @@ export async function createExecutionContext< // copy depends on which collection was declared first. // // Every prefix load passes through here, so it is also where another user's - // owner-private row is kept out of the run's cache (`ownerKeyMaySeed`). + // owner-private row is kept out of the run's cache (`ownerKeyMaySeed`). An + // owner-writes row is everyone's to read, so the scope's collections decide. const retainOwnedKeys = ( scope: ContentScopeType, scopeId: string, rows: Record ): Record => { const owned = ownKeyRecord(); + const scopeConfigs = Object.values( + scope === "session" ? sessionResourceConfigs : scope === "user" ? userResourceConfigs : orgResourceConfigs + ); for (const [key, value] of Object.entries(rows)) { - if (!ownerKeyMaySeed(key, userId)) continue; + if (!ownerKeyMaySeed(key, userId, scopeConfigs)) continue; if (resolveResourceStorageScopeId(scope, key) === scopeId) owned[key] = value; } return owned; diff --git a/packages/engine/src/context/resource-registry.ts b/packages/engine/src/context/resource-registry.ts index d23d90ba2a..87809debc7 100644 --- a/packages/engine/src/context/resource-registry.ts +++ b/packages/engine/src/context/resource-registry.ts @@ -36,7 +36,7 @@ import { searchProjectedRecords, } from "@flow-state-dev/core/types"; import type { ResourceLoadRecord } from "@flow-state-dev/core/items"; -import { OWNER_ROW_REFUSAL, ownerKeyAdmits } from "../resources/owner-private"; +import { OWNER_ROW_REFUSAL, ownerKeyAdmits, ownerWritesRefusalForKey } from "../resources/owner-private"; import { cloneValue, resolveClientProjection } from "@flow-state-dev/core/helpers"; import { applyGetOrPatchState, isTraceObservabilityEnabled } from "@flow-state-dev/core"; import { createResourceEdgeApi } from "@flow-state-dev/core/graph"; @@ -754,13 +754,15 @@ export function filterFlowLevelEager( /** * Fence owner keys on a collection handle. * - * An owner-private collection sees only the session user's own rows. Every - * other collection sees none of any owner's rows, whatever this process - * registered. A fenced key is absent for list, count and `getOptional`, and - * refused for `get` and every write; the message does not say whether the row - * exists. The decision is {@link ownerKeyAdmits}. Every collection pattern has - * a wildcard or parameter segment, and so can resolve onto a key with a - * segment beginning `~`, so every handle is wrapped. + * An owner-private collection sees only the session user's own rows, and an + * owner-writes collection sees every owner's. Every other collection sees + * none of any owner's rows, whatever this process registered. A fenced key is + * absent for list, count and `getOptional`, and refused for `get` and every + * write; the message does not say whether the row exists. The decision is + * {@link ownerKeyAdmits}. Who may write an owner-writes row is judged where + * the registry's writes meet the store, since a reader holds refs to it. + * Every collection pattern has a wildcard or parameter segment, and so can + * resolve onto a key with a segment beginning `~`, so every handle is wrapped. */ function fenceOwnerKeys( handle: ResourceCollectionRef, @@ -810,7 +812,7 @@ function fenceOwnerKeys( } export function createScopeResourceRegistry>>( - options: { + unfencedOptions: { scope: ScopeType; /** * Identifier of the concrete scope instance — `userId` for `"user"`, @@ -939,11 +941,40 @@ export function createScopeResourceRegistry { + // An owner-writes row is readable by anyone the scope serves, so a reader + // can hold a ref to another user's row and write through it. Every write + // this registry makes meets the store through these four callbacks, so the + // owner rule is judged here, whichever handle, ref or eviction asked. + const declaredConfigs = Object.values(unfencedOptions.configs ?? {}); + const refuseOwnerWrite = (key: string): void => { + const refusal = ownerWritesRefusalForKey(declaredConfigs, key, unfencedOptions.actorUserId); + if (refusal !== undefined) throw new Error(refusal); + }; + const options: typeof unfencedOptions = { + ...unfencedOptions, + mutateResourceKey: async (key, mutator, opts) => { + refuseOwnerWrite(key); + return unfencedOptions.mutateResourceKey(key, mutator, opts); + }, + deleteResourceKey: async (key) => { + refuseOwnerWrite(key); + return unfencedOptions.deleteResourceKey(key); + }, + persistResourceContentKey: async (key, content) => { + refuseOwnerWrite(key); + return unfencedOptions.persistResourceContentKey(key, content); + }, + deleteResourceContentKey: async (key) => { + refuseOwnerWrite(key); + return unfencedOptions.deleteResourceContentKey(key); + }, + }; // Null-prototype: keyed by author-supplied accessor names, and this is the // map `get()` below reads. On a plain `{}` an accessor of `__proto__` would // replace the map's prototype rather than add a key, and an accessor sharing diff --git a/packages/engine/src/registry/flow-registry.ts b/packages/engine/src/registry/flow-registry.ts index 068a10ce9f..f8f635fe3b 100644 --- a/packages/engine/src/registry/flow-registry.ts +++ b/packages/engine/src/registry/flow-registry.ts @@ -34,9 +34,9 @@ * scope, so its `stateSchema` drops out under the flow-level flag, while each * resource carries its own `flowIsolation` override and drops out on that. * - * The registry also keeps the owner-private startup fence + * The registry also keeps the owner-key startup fence * (`admitOwnerPrivateCollections` in `resources/owner-private.ts`). It arms - * when a flow declaring an owner-private collection is admitted, checks every + * when a flow declaring an owner-keyed (owner-private or owner-writes) collection is admitted, checks every * held flow against each declaration as it arrives, checks every later flow, * and never disarms. A registry that never holds one refuses nothing on that * account. Every registry, armed or not, refuses a single resource whose @@ -157,7 +157,7 @@ export class InMemoryFlowRegistry implements FlowRegistry { }; /** - * Every owner-private declaration this registry has admitted. Never + * Every owner-keyed declaration this registry has admitted. Never * cleared, even across unregister, for the reason the participants map * above is kept: the rows outlive the registration, so the constraint has * to as well. Non-empty means the startup fence is armed. diff --git a/packages/engine/src/resources/owner-private.ts b/packages/engine/src/resources/owner-private.ts index b52a1b27b3..b6e70dd1d7 100644 --- a/packages/engine/src/resources/owner-private.ts +++ b/packages/engine/src/resources/owner-private.ts @@ -1,6 +1,6 @@ /** - * Owner-private collections: the one module that decides who reads a row - * keyed to an owner, and which collections may sit beside one. + * Owner-keyed collections: the one module that decides who reads and who + * writes a row keyed to an owner, and which collections may sit beside one. * * A collection declaring `ownerPrivate: { param }` keys each row with * `ownerSegment(userId)` (`~` plus the escaped user id) at that parameter. @@ -9,15 +9,15 @@ * **The key fence** ({@link ownerKeyAdmits}) is always on. A key's first * segment beginning `~` is its owner, read off the key alone, so every process * over the store agrees on it whatever it registered. A key with one is served - * only through an owner-private collection whose owner parameter sits at that - * segment, and only to the user the segment encodes. Every other collection + * only through an owner-keyed collection whose owner parameter sits at that + * segment (an owner-private one: only to the user it encodes). Every other collection * lists and counts without it, reads it as absent and is refused on write. * Every read path asks it: the resource handle, the request-start seed cache * ({@link ownerKeyMaySeed}), projected collections, the browser resource * routes, `/state` and the debug endpoints. * * **The startup fence** ({@link admitOwnerPrivateCollections}) arms once a - * registry holds a flow declaring an owner-private collection. From then on + * registry holds a flow declaring an owner-keyed collection. From then on * it refuses any flow declaring another collection in the same scope whose * pattern can reach those keys, checking the flows already held and every * later one, and it never disarms. A registry that never holds one refuses @@ -27,8 +27,16 @@ * key has a segment beginning `~` ({@link refuseOwnerMarkedSingleResources}). * A single resource's key is the same for every caller, so it can never be * the owner's own, and the key fence above only guards collections. + * + * **Owner-writes collections** (`ownerWrites: { param }`) share the key shape + * and both fences, with one difference: every read path admits their rows to + * anyone the scope serves, and only a write needs the owner + * ({@link ownerWriteRefusal}). Since a reader holds a ref it could write + * through, the write check also runs where every write of a run meets the + * store ({@link ownerWritesRefusalForKey}), and the seed cache admits other + * users' rows of such a collection ({@link ownerKeyMaySeed}). */ -import { ownerSegment } from "@flow-state-dev/core/types"; +import { matchesPattern, ownerSegment } from "@flow-state-dev/core/types"; import { isCollectionConfig } from "./is-collection-config"; import { resourceStorageKeys } from "./storage-keys"; @@ -38,15 +46,25 @@ import { resourceStorageKeys } from "./storage-keys"; */ export const OWNER_ROW_REFUSAL = "A row of an owner-private collection is readable only by the user it belongs to."; -/** An owner-private declaration as registration compares it. */ +/** + * The refusal another user's write to an owner-writes row gets. The row is + * readable, so naming the rule reveals nothing a read wouldn't. + */ +export const OWNER_WRITE_REFUSAL = "A row of an owner-writes collection is written only by the user it belongs to."; + +/** Which owner rule a collection declares. */ +type OwnerMode = "private" | "writes"; + +/** An owner-keyed declaration (either mode) as registration compares it. */ export interface OwnerPrivateDeclaration { pattern: string; param: string; scope: unknown; + mode: OwnerMode; } /** A collection entry as the fences read it: a pattern, a scope, maybe a declaration. */ -type CollectionEntry = { pattern: string; scope?: unknown; ownerPrivate?: unknown }; +type CollectionEntry = { pattern: string; scope?: unknown; ownerPrivate?: unknown; ownerWrites?: unknown }; /** The key's first segment beginning `~`, which names its owner, or `undefined`. */ function ownerSegmentOf(storageKey: string): { index: number; segment: string } | undefined { @@ -56,51 +74,119 @@ function ownerSegmentOf(storageKey: string): { index: number; segment: string } return index === -1 ? undefined : { index, segment: segments[index]! }; } -/** The declared owner parameter, or `undefined` when the collection is not owner-private. */ -function ownerParamOf(collection: object): string | undefined { - const declaration = (collection as { ownerPrivate?: unknown }).ownerPrivate; - if (declaration === undefined || declaration === null) return undefined; - const param = (declaration as { param?: unknown }).param; - // A declaration with no usable parameter still marks the collection - // owner-private; it matches no segment, so it serves nothing. - return typeof param === "string" ? param : ""; +/** + * The declared owner rule, or `undefined` when the collection declares none. + * A declaration with no usable parameter still marks the collection; it + * matches no segment, so it serves nothing. + */ +function ownerRuleOf(collection: object): { mode: OwnerMode; param: string } | undefined { + const declared = collection as { ownerPrivate?: unknown; ownerWrites?: unknown }; + const mode: OwnerMode | undefined = + declared.ownerPrivate !== undefined && declared.ownerPrivate !== null + ? "private" + : declared.ownerWrites !== undefined && declared.ownerWrites !== null + ? "writes" + : undefined; + if (mode === undefined) return undefined; + const param = (declared[mode === "private" ? "ownerPrivate" : "ownerWrites"] as { param?: unknown }).param; + return { mode, param: typeof param === "string" ? param : "" }; +} + +/** Whether the key's owner segment sits at the collection's owner parameter. */ +function ownerAtParam(collection: object, owner: { index: number }, param: string): boolean { + const pattern = (collection as { pattern?: unknown }).pattern; + if (typeof pattern !== "string") return false; + return owner.index === pattern.split("/").indexOf(`[${param}]`); } /** - * Whether `userId` may read or write the row at `storageKey` through - * `collection`. The one key predicate. + * Whether `userId` may read the row at `storageKey` through `collection`. The + * one read predicate; a write asks {@link ownerWriteRefusal}. * - * A collection that is not owner-private is admitted every key with no - * segment beginning `~`, and none with one. An owner-private collection is - * admitted a key only when its first `~` segment sits at the owner parameter - * and is `ownerSegment(userId)`; a later `~` segment is data. With no user, - * it is admitted nothing. + * A collection with no owner rule is admitted every key with no segment + * beginning `~`, and none with one. An owner-keyed collection is admitted a + * key only when its first `~` segment sits at the owner parameter; a later + * `~` segment is data. An owner-private one also needs that segment to be + * `ownerSegment(userId)`, so with no user it is admitted nothing. An + * owner-writes one serves the row to anyone the scope serves. */ export function ownerKeyAdmits(collection: object, storageKey: string, userId: string | undefined): boolean { const owner = ownerSegmentOf(storageKey); - const param = ownerParamOf(collection); - if (param === undefined) return owner === undefined; - if (owner === undefined || userId === undefined || userId.length === 0) return false; - const pattern = (collection as { pattern?: unknown }).pattern; - if (typeof pattern !== "string") return false; - return owner.index === pattern.split("/").indexOf(`[${param}]`) && owner.segment === ownerSegment(userId); + const rule = ownerRuleOf(collection); + if (rule === undefined) return owner === undefined; + if (owner === undefined || !ownerAtParam(collection, owner, rule.param)) return false; + if (rule.mode === "writes") return true; + if (userId === undefined || userId.length === 0) return false; + return owner.segment === ownerSegment(userId); +} + +/** + * Why `userId` may not write the row at `storageKey` through `collection`, or + * `undefined` when it may. A key the read predicate refuses gets + * {@link OWNER_ROW_REFUSAL}, which does not say whether the row exists. A + * readable owner-writes row whose owner segment is not `ownerSegment(userId)` + * gets {@link OWNER_WRITE_REFUSAL}. + */ +export function ownerWriteRefusal( + collection: object, + storageKey: string, + userId: string | undefined +): string | undefined { + if (!ownerKeyAdmits(collection, storageKey, userId)) return OWNER_ROW_REFUSAL; + if (ownerRuleOf(collection)?.mode !== "writes") return undefined; + if (userId === undefined || userId.length === 0) return OWNER_WRITE_REFUSAL; + return ownerSegmentOf(storageKey)!.segment === ownerSegment(userId) ? undefined : OWNER_WRITE_REFUSAL; +} + +/** The owner-writes collection among `collections` that reads `storageKey`, if any. */ +function ownerWritesCollectionFor(collections: Iterable, storageKey: string): object | undefined { + for (const collection of collections) { + if (!isCollectionConfig(collection)) continue; + if (ownerRuleOf(collection)?.mode !== "writes") continue; + if (!matchesPattern(collection.pattern, storageKey)) continue; + if (ownerKeyAdmits(collection, storageKey, undefined)) return collection; + } + return undefined; +} + +/** + * The refusal for a run's write at `storageKey`, judged against the + * collections the run declared, or `undefined`. Only owner-writes rows are + * judged here: a ref to one can be held by any reader, so the store write is + * the one place every write meets. Other owner keys never reach a ref the + * handle fence did not admit. + */ +export function ownerWritesRefusalForKey( + collections: Iterable, + storageKey: string, + userId: string | undefined +): string | undefined { + if (ownerSegmentOf(storageKey) === undefined) return undefined; + const collection = ownerWritesCollectionFor(collections, storageKey); + return collection === undefined ? undefined : ownerWriteRefusal(collection, storageKey, userId); } /** * Whether a row read from the store may enter a run's cache for `userId`: - * every key except one whose owner segment names another user. + * every key except one whose owner segment names another user, unless one of + * the run's owner-writes `collections` reads it. * * Collections load by prefix, so a wide collection's scan sweeps up every * owner's rows. The handles fence them again through {@link ownerKeyAdmits}, * but the cache has other readers (a `contentTemplateRef` resolves against it - * by storage key), so another user's row never enters it. The caller's own - * rows do: an owner-private collection serves them from the same cache. + * by storage key), so another user's owner-private row never enters it. The + * caller's own rows do, and so does any owner-writes row: those collections + * serve them from the same cache. */ -export function ownerKeyMaySeed(storageKey: string, userId: string | undefined): boolean { +export function ownerKeyMaySeed( + storageKey: string, + userId: string | undefined, + collections: Iterable = [] +): boolean { const owner = ownerSegmentOf(storageKey); if (owner === undefined) return true; - if (userId === undefined || userId.length === 0) return false; - return owner.segment === ownerSegment(userId); + if (userId !== undefined && userId.length > 0 && owner.segment === ownerSegment(userId)) return true; + return ownerWritesCollectionFor(collections, storageKey) !== undefined; } /** A segment the key matcher reads as one segment of anything: `*` or any bracketed segment. */ @@ -132,12 +218,17 @@ function collectionEntries(resources: Record | undefined): Coll } function declarationOf(entry: CollectionEntry): OwnerPrivateDeclaration | undefined { - const param = ownerParamOf(entry); - return param === undefined ? undefined : { pattern: entry.pattern, param, scope: entry.scope }; + const rule = ownerRuleOf(entry); + return rule === undefined ? undefined : { pattern: entry.pattern, param: rule.param, scope: entry.scope, mode: rule.mode }; } function sameDeclaration(left: OwnerPrivateDeclaration, right: OwnerPrivateDeclaration): boolean { - return left.pattern === right.pattern && left.param === right.param && left.scope === right.scope; + return ( + left.pattern === right.pattern && + left.param === right.param && + left.scope === right.scope && + left.mode === right.mode + ); } /** Throw when `entry` reaches one of `declarations` in its scope and is not that declaration. */ @@ -148,8 +239,10 @@ function refuseReach(entry: CollectionEntry, declarations: readonly OwnerPrivate if (own !== undefined && sameDeclaration(own, declaration)) continue; if (!patternsReach(entry.pattern, declaration.pattern)) continue; throw new Error( - `Collection pattern "${entry.pattern}" can reach the rows of owner-private collection "${declaration.pattern}". ` + - `Only that collection reads or writes them, each for the user it belongs to.` + + `Collection pattern "${entry.pattern}" can reach the rows of owner-${declaration.mode} collection "${declaration.pattern}". ` + + (declaration.mode === "private" + ? `Only that collection reads or writes them, each for the user it belongs to.` + : `Only that collection reads or writes them.`) + (heldBy === undefined ? "" : ` Flow "${heldBy}" declares it and is already registered.`) ); } @@ -184,7 +277,7 @@ export function refuseOwnerMarkedSingleResources(incoming: { resources?: Record< /** * The startup fence, for one registration. * - * `known` is every owner-private declaration the registry has admitted, kept + * `known` is every owner-keyed declaration the registry has admitted, kept * for good. When it is empty and the incoming flow declares none, nothing is * checked. Otherwise every collection of the incoming flow is checked against * every declaration, and every held flow is checked against each declaration diff --git a/packages/engine/src/routes/resource-routes.ts b/packages/engine/src/routes/resource-routes.ts index b8d42461e3..3a3f776105 100644 --- a/packages/engine/src/routes/resource-routes.ts +++ b/packages/engine/src/routes/resource-routes.ts @@ -5,11 +5,13 @@ * the `client` config declared on resource definitions. Only resources with * an explicit `client` configuration are accessible. * - * Every handler that lists, reads, writes or deletes a collection key asks - * {@link ownerKeyAdmits} for the session's user, the fence the resource - * handle applies to a run: a row keyed to an owner is absent from a read and + * Every handler that lists or reads a collection key asks + * {@link ownerKeyAdmits} for the session's user, and every handler that + * writes or deletes one asks {@link ownerWriteRefusal}: the fence the resource + * handle applies to a run. A row keyed to an owner is absent from a read and * refused on a write, except through its owner-private collection, to its - * owner. + * owner, or through its owner-writes collection, read by anyone and written + * by its owner. */ import type { CollectionClientConfig, @@ -36,7 +38,7 @@ import { } from "../resources/normalize-resource-state"; import { normalizeScopeResourceContent } from "../context/resource-registry"; import { ValidationError } from "../errors/flow-error"; -import { OWNER_ROW_REFUSAL, ownerKeyAdmits } from "../resources/owner-private"; +import { OWNER_ROW_REFUSAL, ownerKeyAdmits, ownerWriteRefusal } from "../resources/owner-private"; import type { ParsedFlowRoute } from "./parseFlowRoute"; import { isJsonObject } from "../utils/json-helpers"; import { @@ -262,8 +264,9 @@ export async function handleCreateCollectionItem( } const storageKey = resolveCollectionKey(config.pattern, topic.trim()); - if (!ownerKeyAdmits(config, storageKey, session.userId)) { - return jsonResponse(403, { error: OWNER_ROW_REFUSAL }); + const createRefusal = ownerWriteRefusal(config, storageKey, session.userId); + if (createRefusal !== undefined) { + return jsonResponse(403, { error: createRefusal }); } // Only session-scoped for now (Phase 1 simplification) @@ -388,8 +391,9 @@ export async function handleUpdateResourceContent( if (!matchesPattern(config.pattern, storageKey)) { storageKey = resolveCollectionKey(config.pattern, route.topic); } - if (!ownerKeyAdmits(config, storageKey, session.userId)) { - return jsonResponse(403, { error: OWNER_ROW_REFUSAL }); + const updateRefusal = ownerWriteRefusal(config, storageKey, session.userId); + if (updateRefusal !== undefined) { + return jsonResponse(403, { error: updateRefusal }); } // FIX-1068: addressed by the key's owner, so read and write land where a // block would rather than where the named route would. @@ -791,8 +795,9 @@ export async function handleDeleteCollectionItem( if (!matchesPattern(config.pattern, storageKey)) { storageKey = resolveCollectionKey(config.pattern, route.topic); } - if (!ownerKeyAdmits(config, storageKey, session.userId)) { - return jsonResponse(403, { error: OWNER_ROW_REFUSAL }); + const deleteRefusal = ownerWriteRefusal(config, storageKey, session.userId); + if (deleteRefusal !== undefined) { + return jsonResponse(403, { error: deleteRefusal }); } // Conflict before anything is deleted — the create route's rule, mirrored. // `undefined` means no live row, i.e. `expectedVersion: 0`, so an absent key diff --git a/packages/engine/test/owner-writes-fence.test.ts b/packages/engine/test/owner-writes-fence.test.ts new file mode 100644 index 0000000000..aebb8b6b07 --- /dev/null +++ b/packages/engine/test/owner-writes-fence.test.ts @@ -0,0 +1,430 @@ +/** + * The owner-writes key fence, through `createFlowState` and the HTTP router. + * + * A collection declaring `ownerWrites: { param }` keys each row with the + * owner's segment, like an owner-private one. Every read path serves the row + * to anyone the scope serves; a create, update or delete is refused unless the + * session's user is the one the key names. The rule holds at the store, so it + * holds through the handle, through a ref obtained by reading, through the + * browser routes and from a second process over the same store. + * + * The collections here are generic (`entries/…`). No package's key shape is + * Engine's contract. + */ +import { describe, expect, it } from "vitest"; +import { z } from "zod"; +import { defineFlow, defineResourceCollection, handler, ownerSegment } from "@flow-state-dev/core"; +import type { ResourceCollectionRef } from "@flow-state-dev/core/types"; +import { createFlowState, inMemoryStores } from "../src"; +import { ownerKeyAdmits, ownerKeyMaySeed, ownerWriteRefusal } from "../src/resources/owner-private"; +import { createMockModelResolver } from "@flow-state-dev/testing"; + +const WRITE_REFUSAL = "A row of an owner-writes collection is written only by the user it belongs to."; +const PRIVATE_REFUSAL = "A row of an owner-private collection is readable only by the user it belongs to."; +const ALICE_KEY = `entries/apollo/${ownerSegment("alice")}/checkout`; +const ALICE_STATE = { status: "ALICE-ON-TRACK" }; +const passthrough = z.object({}).passthrough(); +const tagInput = z.object({ tag: z.string() }); + +const verified = { + resolvePrincipal: (context: { request?: Request }) => { + const userId = context.request?.headers.get("x-verified-user"); + const orgId = context.request?.headers.get("x-verified-org"); + return userId && orgId ? { userId, orgId } : null; + }, +}; + +const attempt = async (run: () => Promise): Promise => { + try { + const value = await run(); + return `ok:${JSON.stringify(value ?? null)}`; + } catch (error) { + return `threw:${(error as Error).message}`; + } +}; + +type Router = Record Promise>; + +/** Boot one app over `stores`, and a caller that speaks for `user` in org acme. */ +async function bootApp(flows: Record, stores: ReturnType) { + const state = createFlowState({ + flows: flows as never, + resolvePrincipal: verified.resolvePrincipal, + stores: { default: { primary: stores } }, + modelResolver: createMockModelResolver({}), + debugEndpointsEnabled: true, + debugAllowAnonymousLocal: true, + }); + const router = (await state.getRouter()) as Router; + const runtime = await state.getRuntime(); + const call = async (user: string, method: string, path: string[], body?: unknown) => { + const response = await router[method]!( + new Request(`http://test/api/flows/${path.join("/")}`, { + method, + headers: { "content-type": "application/json", "x-verified-user": user, "x-verified-org": "acme" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }), + { params: { path } } + ); + const text = await response.text(); + let json: unknown; + try { + json = text.length > 0 ? JSON.parse(text) : undefined; + } catch { + json = undefined; + } + return { status: response.status, json: json as any, text }; + }; + const open = async (flow: string, user: string) => { + const opened = await call(user, "POST", [flow, "sessions"], { userId: user }); + expect(opened.status).toBe(201); + return opened.json.session.id as string; + }; + /** Run `action` as `user` and return the JSON the probe wrote at `probes/`. */ + const probe = async (flow: string, user: string, action: string, tag: string) => { + const sessionId = await open(flow, user); + const posted = await call(user, "POST", [flow, sessionId, "actions", action], { userId: user, input: { tag } }); + expect(posted.status).toBe(202); + let row: { state?: { seen?: string } } | undefined; + for (let i = 0; i < 400 && row === undefined; i++) { + row = await runtime.stores.resourceState.get("org", "acme", `probes/${tag}`); + if (row === undefined) await new Promise((resolve) => setTimeout(resolve, 5)); + } + return JSON.parse(row!.state!.seen!); + }; + const stored = async (key: string) => ({ + state: (await runtime.stores.resourceState.get("org", "acme", key))?.state, + content: await runtime.stores.content.get("org", "acme", key), + }); + return { state, runtime, call, open, probe, stored }; +} + +const probes = defineResourceCollection({ + pattern: "probes/*", + scope: "org", + stateSchema: z.object({ seen: z.string() }), +}); + +const entries = defineResourceCollection({ + pattern: "entries/[project]/[owner]/[entry]", + ownerWrites: { param: "owner" }, + scope: "org", + flowIsolation: false, + stateSchema: passthrough, + client: { state: { read: true }, content: { read: true } }, +}); + +const entryKey = (user: string, entry = "checkout") => ({ project: "apollo", owner: ownerSegment(user), entry }); + +/** Each user writes their own entry, then tries every write on Alice's. */ +const probeEntries = handler({ + name: "probe-entries", + inputSchema: tagInput, + outputSchema: z.object({ ok: z.boolean() }), + resources: { entries, probes }, + execute: async (input, ctx) => { + const me = ctx.session.identity.userId!; + const col = ctx.resources.entries as unknown as ResourceCollectionRef; + const alice = entryKey("alice"); + const seen = { + writeOwn: await attempt(async () => (await col.upsert(entryKey(me, "mine"), { status: `${me}-own` })).state), + list: (await col.list()).map((row) => row.path).sort(), + count: await col.count(), + getOptionalAlice: await attempt(async () => (await col.getOptional(alice))?.state), + getAlice: await attempt(async () => (await col.get(alice)).state), + listUnderProject: (await col.list("apollo/")).map((row) => row.path).sort(), + createUnderAlice: await attempt(async () => (await col.create(entryKey("alice", "forged"), { status: "F" })).state), + replaceAlice: await attempt(async () => (await col.create(alice, { status: "F" }, { replace: true })).state), + upsertAlice: await attempt(async () => (await col.upsert(alice, { status: "F" })).state), + getOrCreateAlice: await attempt(async () => (await col.getOrCreate(entryKey("alice", "other"), {})).state), + deleteAlice: await attempt(() => col.delete(alice)), + patchThroughRef: await attempt(async () => (await col.get(alice)).patchState({ status: "F" })), + setThroughRef: await attempt(async () => (await col.get(alice)).setState({ status: "F" })), + contentThroughRef: await attempt(async () => + ((await col.get(alice)) as unknown as { writeContent(c: string): Promise }).writeContent("FORGED") + ), + }; + await (ctx.resources.probes as unknown as ResourceCollectionRef).create(input.tag, { seen: JSON.stringify(seen) }); + return { ok: true }; + }, +}); + +/** The user writes their own entry and nothing else. */ +const seedOwn = handler({ + name: "seed-own", + inputSchema: tagInput, + outputSchema: z.object({ ok: z.boolean() }), + resources: { entries, probes }, + execute: async (input, ctx) => { + const me = ctx.session.identity.userId!; + const col = ctx.resources.entries as unknown as ResourceCollectionRef; + const seen = { + writeOwn: await attempt(async () => (await col.upsert(entryKey(me, "mine"), { status: `${me}-own` })).state), + }; + await (ctx.resources.probes as unknown as ResourceCollectionRef).create(input.tag, { seen: JSON.stringify(seen) }); + return { ok: true }; + }, +}); + +const entriesFlow = defineFlow({ + kind: "entries", + resources: { entries, probes }, + org: { + client: { + derived: { + entriesSeen: (ctx: { resources: Record }) => { + const col = ctx.resources.entries as { list(): Array<{ path: string }>; count(): number }; + return { list: col.list().map((row) => row.path).sort(), count: col.count() }; + }, + }, + }, + }, + actions: { + probe: { inputSchema: tagInput, block: probeEntries }, + seed: { inputSchema: tagInput, block: seedOwn }, + }, + authentication: verified, +}); + +async function bootEntries(stores = inMemoryStores()) { + const app = await bootApp({ entries: entriesFlow }, stores); + // Alice writes her own entry through the app: nothing is planted. + const alice = await app.probe("entries", "alice", "seed", "alice-seed"); + expect(alice.writeOwn).toBe(`ok:${JSON.stringify({ status: "alice-own" })}`); + return { ...app, stores }; +} + +describe("an owner-writes collection: the scope reads every row, only its owner writes it", () => { + it("the owner writes her rows, by every write", async () => { + const app = await bootEntries(); + const alice = await app.probe("entries", "alice", "probe", "alice-2"); + // Her own key, through each write the handle and a ref offer. + expect(alice.createUnderAlice).toBe(`ok:${JSON.stringify({ status: "F" })}`); + expect(alice.upsertAlice).not.toMatch(/^threw:/); + expect(alice.deleteAlice).toBe("ok:null"); + }); + + it("another user lists, counts and reads the owner's rows through the handle", async () => { + const app = await bootEntries(); + await app.runtime.stores.resourceState.set("org", "acme", ALICE_KEY, ALICE_STATE, "any"); + const bob = await app.probe("entries", "bob", "probe", "bob"); + const aliceMine = `entries/apollo/${ownerSegment("alice")}/mine`; + const bobMine = `entries/apollo/${ownerSegment("bob")}/mine`; + expect(bob.list).toEqual([ALICE_KEY, aliceMine, bobMine].sort()); + expect(bob.listUnderProject).toEqual([ALICE_KEY, aliceMine, bobMine].sort()); + expect(bob.count).toBe(3); + expect(bob.getOptionalAlice).toBe(`ok:${JSON.stringify(ALICE_STATE)}`); + expect(bob.getAlice).toBe(`ok:${JSON.stringify(ALICE_STATE)}`); + }); + + it("refuses another user's create, replace, upsert, getOrCreate and delete under the owner's key, and every write through a ref he read", async () => { + const app = await bootEntries(); + await app.runtime.stores.resourceState.set("org", "acme", ALICE_KEY, ALICE_STATE, "any"); + await app.runtime.stores.content.set("org", "acme", ALICE_KEY, "ALICE-REPORT"); + const bob = await app.probe("entries", "bob", "probe", "bob"); + const refused = `threw:${WRITE_REFUSAL}`; + expect(bob).toMatchObject({ + writeOwn: `ok:${JSON.stringify({ status: "bob-own" })}`, + createUnderAlice: refused, + replaceAlice: refused, + upsertAlice: refused, + getOrCreateAlice: refused, + deleteAlice: refused, + patchThroughRef: refused, + setThroughRef: refused, + contentThroughRef: refused, + }); + // Nothing changed, and nothing new landed under Alice's segment. + expect(await app.stored(ALICE_KEY)).toEqual({ state: ALICE_STATE, content: "ALICE-REPORT" }); + const rows = await app.runtime.stores.resourceState.getByPrefix("org", "acme", "entries/"); + expect(Object.keys(rows).sort()).toEqual( + [ALICE_KEY, `entries/apollo/${ownerSegment("alice")}/mine`, `entries/apollo/${ownerSegment("bob")}/mine`].sort() + ); + }); + + it("a second process over the same store refuses the same writes", async () => { + const first = await bootEntries(); + await first.runtime.stores.resourceState.set("org", "acme", ALICE_KEY, ALICE_STATE, "any"); + const second = await bootApp({ entries: entriesFlow }, first.stores); + const bob = await second.probe("entries", "bob", "probe", "bob-elsewhere"); + expect(bob.getAlice).toBe(`ok:${JSON.stringify(ALICE_STATE)}`); + expect(bob.upsertAlice).toBe(`threw:${WRITE_REFUSAL}`); + expect(bob.patchThroughRef).toBe(`threw:${WRITE_REFUSAL}`); + expect(bob.deleteAlice).toBe(`threw:${WRITE_REFUSAL}`); + expect(await first.stored(ALICE_KEY)).toMatchObject({ state: ALICE_STATE }); + }); + + it("the browser routes, the state snapshot and the debug endpoints read the owner's row", async () => { + const app = await bootEntries(); + await app.runtime.stores.resourceState.set("org", "acme", ALICE_KEY, ALICE_STATE, "any"); + await app.runtime.stores.content.set("org", "acme", ALICE_KEY, "ALICE-REPORT"); + const sessionId = await app.open("entries", "bob"); + const resources = ["sessions", sessionId, "resources", "entries"]; + + const listed = await app.call("bob", "GET", resources); + expect(listed.status).toBe(200); + expect(listed.json.items.map((item: { storageKey: string }) => item.storageKey)).toContain(ALICE_KEY); + const item = await app.call("bob", "GET", [...resources, ...ALICE_KEY.split("/")]); + expect(item.status).toBe(200); + expect(item.text).toContain("ALICE-ON-TRACK"); + const content = await app.call("bob", "GET", [...resources, ...ALICE_KEY.split("/"), "content"]); + expect(content.status).toBe(200); + expect(content.text).toContain("ALICE-REPORT"); + + const snapshot = await app.call("bob", "GET", ["sessions", sessionId, "state"]); + expect(snapshot.status).toBe(200); + expect(snapshot.json.resources.org.entries.count).toBe(2); + expect(snapshot.json.clientData.org.entriesSeen.list).toContain(ALICE_KEY); + + const debug = await app.call("bob", "GET", ["sessions", sessionId, "debug", "resources", "entries", "items"]); + expect(debug.status).toBe(200); + expect(JSON.stringify(debug.json)).toContain("ALICE-ON-TRACK"); + }); + + // The browser create route takes a bare topic, which a parameterized + // pattern refuses before any owner check, so only update and delete apply. + it("the browser update and delete routes refuse another user's key and take the owner's", async () => { + const drafts = defineResourceCollection({ + pattern: "drafts/[owner]/[id]", + ownerWrites: { param: "owner" }, + scope: "session", + stateSchema: passthrough, + client: { state: { read: true }, content: { read: true, update: true, delete: true } }, + }); + const draftsFlow = defineFlow({ + kind: "drafts", + resources: { drafts }, + actions: {}, + authentication: verified, + }); + const app = await bootApp({ drafts: draftsFlow }, inMemoryStores()); + const sessionId = await app.open("drafts", "bob"); + const resources = ["sessions", sessionId, "resources", "drafts"]; + const aliceDraft = `drafts/${ownerSegment("alice")}/d1`; + const bobDraft = `drafts/${ownerSegment("bob")}/d1`; + await app.runtime.stores.resourceState.set("session", sessionId, aliceDraft, { text: "A" }, "any"); + await app.runtime.stores.resourceState.set("session", sessionId, bobDraft, { text: "B" }, "any"); + + const patched = await app.call("bob", "PATCH", [...resources, ...aliceDraft.split("/"), "content"], { + content: "FORGED", + }); + expect(patched).toMatchObject({ status: 403, json: { error: WRITE_REFUSAL } }); + const deleted = await app.call("bob", "DELETE", [...resources, ...aliceDraft.split("/")]); + expect(deleted).toMatchObject({ status: 403, json: { error: WRITE_REFUSAL } }); + expect((await app.runtime.stores.resourceState.get("session", sessionId, aliceDraft))?.state).toEqual({ text: "A" }); + expect(await app.runtime.stores.content.get("session", sessionId, aliceDraft)).toBeUndefined(); + + const ownPatch = await app.call("bob", "PATCH", [...resources, ...bobDraft.split("/"), "content"], { content: "MINE" }); + expect(ownPatch.status).toBe(200); + const ownDelete = await app.call("bob", "DELETE", [...resources, ...bobDraft.split("/")]); + expect(ownDelete.status).toBe(200); + }); +}); + +describe("the owner-writes predicates", () => { + it("read with no caller, and write only as the owner", () => { + expect(ownerKeyAdmits(entries, ALICE_KEY, undefined)).toBe(true); + expect(ownerWriteRefusal(entries, ALICE_KEY, undefined)).toBe(WRITE_REFUSAL); + expect(ownerWriteRefusal(entries, ALICE_KEY, "")).toBe(WRITE_REFUSAL); + expect(ownerWriteRefusal(entries, ALICE_KEY, "bob")).toBe(WRITE_REFUSAL); + expect(ownerWriteRefusal(entries, ALICE_KEY, "alice")).toBeUndefined(); + }); + + it("serve no key whose first ~ segment is not at the owner parameter", () => { + const tildeBefore = `entries/~team/${ownerSegment("alice")}/checkout`; + expect(ownerKeyAdmits(entries, tildeBefore, "alice")).toBe(false); + expect(ownerWriteRefusal(entries, tildeBefore, "alice")).toBe(PRIVATE_REFUSAL); + expect(ownerKeyAdmits(entries, "entries/apollo/alice/checkout", "alice")).toBe(false); + }); + + it("let another user's row into the run's cache only beside a collection that reads it", () => { + expect(ownerKeyMaySeed(ALICE_KEY, "bob")).toBe(false); + expect(ownerKeyMaySeed(ALICE_KEY, "bob", [entries])).toBe(true); + expect(ownerKeyMaySeed(`notes/${ownerSegment("alice")}/n1`, "bob", [entries])).toBe(false); + }); +}); + +describe("the startup fence reaches owner-writes rows too", () => { + const ping = handler({ + name: "ping", + inputSchema: z.object({}), + outputSchema: z.object({ ok: z.boolean() }), + execute: () => ({ ok: true }), + }); + const flowWith = (kind: string, resources: Record) => + defineFlow({ kind, resources: resources as never, actions: { ping: { inputSchema: z.object({}), block: ping } }, authentication: verified }); + const wide = flowWith("wide", { + everything: defineResourceCollection({ pattern: "entries/**", scope: "org", stateSchema: passthrough }), + }); + const owned = flowWith("owned", { entries }); + const reach = 'Collection pattern "entries/**" can reach the rows of owner-writes collection "entries/[project]/[owner]/[entry]".'; + + it("refuses a wider collection registered after it", async () => { + await expect(bootApp({ owned, wide }, inMemoryStores())).rejects.toThrow(reach); + }); + + it("refuses a wider collection registered before it, naming the held flow", async () => { + await expect(bootApp({ wide, owned }, inMemoryStores())).rejects.toThrow( + `${reach} Only that collection reads or writes them. Flow "wide" declares it and is already registered.` + ); + }); + + it("refuses the same pattern declared owner-private beside it", async () => { + const privateCopy = flowWith("private-copy", { + entries: defineResourceCollection({ + pattern: "entries/[project]/[owner]/[entry]", + ownerPrivate: { param: "owner" }, + scope: "org", + stateSchema: passthrough, + }), + }); + await expect(bootApp({ owned, privateCopy }, inMemoryStores())).rejects.toThrow( + 'Collection pattern "entries/[project]/[owner]/[entry]" can reach the rows of owner-writes collection "entries/[project]/[owner]/[entry]".' + ); + }); + + it("admits the same declaration on several flows", async () => { + const again = flowWith("again", { entries }); + await expect(bootApp({ owned, again }, inMemoryStores())).resolves.toBeDefined(); + }); +}); + +describe("an owner-private collection keeps its refusal beside the new mode", () => { + it("still reads another user's row as absent and refuses its write with the read refusal", async () => { + const notes = defineResourceCollection({ + pattern: "notes/[owner]/[id]", + ownerPrivate: { param: "owner" }, + scope: "org", + flowIsolation: false, + stateSchema: passthrough, + }); + const probeNotes = handler({ + name: "probe-notes", + inputSchema: tagInput, + outputSchema: z.object({ ok: z.boolean() }), + resources: { notes, probes, entries }, + execute: async (input, ctx) => { + const col = ctx.resources.notes as unknown as ResourceCollectionRef; + const key = { owner: ownerSegment("alice"), id: "n1" }; + const seen = { + list: (await col.list()).map((row) => row.path), + write: await attempt(async () => (await col.upsert(key, { text: "F" })).state), + }; + await (ctx.resources.probes as unknown as ResourceCollectionRef).create(input.tag, { seen: JSON.stringify(seen) }); + return { ok: true }; + }, + }); + const flow = defineFlow({ + kind: "notes", + resources: { notes, probes, entries }, + actions: { probe: { inputSchema: tagInput, block: probeNotes } }, + authentication: verified, + }); + const stores = inMemoryStores(); + const primary = await stores.resolve(["primary"]); + await primary.resourceState!.set("org", "acme", `notes/${ownerSegment("alice")}/n1`, { text: "A" }, "any"); + const app = await bootApp({ notes: flow }, stores); + const bob = await app.probe("notes", "bob", "probe", "bob"); + expect(bob).toEqual({ list: [], write: `threw:${PRIVATE_REFUSAL}` }); + }); +}); From c24436395855cd52629038ae797c2c4a9e6b84aa Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 21:46:15 +0000 Subject: [PATCH 2/4] chore(changeset): reference FIX-1793 in the ownerWrites fragment Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- .changeset/owner-writes-collections.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/owner-writes-collections.md b/.changeset/owner-writes-collections.md index 43dde470ed..eec99f621c 100644 --- a/.changeset/owner-writes-collections.md +++ b/.changeset/owner-writes-collections.md @@ -3,4 +3,4 @@ "@flow-state-dev/engine": minor --- -`defineResourceCollection` accepts `ownerWrites: { param }`: every reader the collection's scope serves reads each row, and only the user the row's owner segment names writes it. Key rows with `ownerSegment(userId)` at that parameter, as for `ownerPrivate`, and the same pattern rules apply (the parameter appears once, no `**`); a browser read is allowed. A create, update or delete by anyone else, through the collection handle, a ref obtained by reading, or the browser update and delete routes, throws `A row of an owner-writes collection is written only by the user it belongs to.` and changes nothing. The startup fence covers these collections too: a wider collection in the same scope that can reach their keys, or the same pattern declared `ownerPrivate`, stops the app from starting. A collection can't declare both modes, and an owner-writes collection can't declare an `eviction` policy other than `"none"`. +`defineResourceCollection` accepts `ownerWrites: { param }`: every reader the collection's scope serves reads each row, and only the user the row's owner segment names writes it. Key rows with `ownerSegment(userId)` at that parameter, as for `ownerPrivate`, and the same pattern rules apply (the parameter appears once, no `**`); a browser read is allowed. A create, update or delete by anyone else, through the collection handle, a ref obtained by reading, or the browser update and delete routes, throws `A row of an owner-writes collection is written only by the user it belongs to.` and changes nothing. The startup fence covers these collections too: a wider collection in the same scope that can reach their keys, or the same pattern declared `ownerPrivate`, stops the app from starting. A collection can't declare both modes, and an owner-writes collection can't declare an `eviction` policy other than `"none"` (FIX-1793). From 57315de83a5cde8fd0d691a72a3d558a134c3ef6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 21:49:05 +0000 Subject: [PATCH 3/4] chore(changeset): ownerWrites is additive, so patch (pre-1.0 rule) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- .changeset/owner-writes-collections.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/owner-writes-collections.md b/.changeset/owner-writes-collections.md index eec99f621c..497cc1366e 100644 --- a/.changeset/owner-writes-collections.md +++ b/.changeset/owner-writes-collections.md @@ -1,6 +1,6 @@ --- -"@flow-state-dev/core": minor -"@flow-state-dev/engine": minor +"@flow-state-dev/core": patch +"@flow-state-dev/engine": patch --- `defineResourceCollection` accepts `ownerWrites: { param }`: every reader the collection's scope serves reads each row, and only the user the row's owner segment names writes it. Key rows with `ownerSegment(userId)` at that parameter, as for `ownerPrivate`, and the same pattern rules apply (the parameter appears once, no `**`); a browser read is allowed. A create, update or delete by anyone else, through the collection handle, a ref obtained by reading, or the browser update and delete routes, throws `A row of an owner-writes collection is written only by the user it belongs to.` and changes nothing. The startup fence covers these collections too: a wider collection in the same scope that can reach their keys, or the same pattern declared `ownerPrivate`, stops the app from starting. A collection can't declare both modes, and an owner-writes collection can't declare an `eviction` policy other than `"none"` (FIX-1793). From 4f3012775e8d415f1fe9167cdd3ab41abf57bbc0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 21:52:44 +0000 Subject: [PATCH 4/4] chore(engine): drop unused OWNER_ROW_REFUSAL import; tests use the refusal constants Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- packages/engine/src/routes/resource-routes.ts | 2 +- packages/engine/test/owner-writes-fence.test.ts | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/engine/src/routes/resource-routes.ts b/packages/engine/src/routes/resource-routes.ts index 3a3f776105..ff59883bd9 100644 --- a/packages/engine/src/routes/resource-routes.ts +++ b/packages/engine/src/routes/resource-routes.ts @@ -38,7 +38,7 @@ import { } from "../resources/normalize-resource-state"; import { normalizeScopeResourceContent } from "../context/resource-registry"; import { ValidationError } from "../errors/flow-error"; -import { OWNER_ROW_REFUSAL, ownerKeyAdmits, ownerWriteRefusal } from "../resources/owner-private"; +import { ownerKeyAdmits, ownerWriteRefusal } from "../resources/owner-private"; import type { ParsedFlowRoute } from "./parseFlowRoute"; import { isJsonObject } from "../utils/json-helpers"; import { diff --git a/packages/engine/test/owner-writes-fence.test.ts b/packages/engine/test/owner-writes-fence.test.ts index aebb8b6b07..05a67e8873 100644 --- a/packages/engine/test/owner-writes-fence.test.ts +++ b/packages/engine/test/owner-writes-fence.test.ts @@ -16,11 +16,17 @@ import { z } from "zod"; import { defineFlow, defineResourceCollection, handler, ownerSegment } from "@flow-state-dev/core"; import type { ResourceCollectionRef } from "@flow-state-dev/core/types"; import { createFlowState, inMemoryStores } from "../src"; -import { ownerKeyAdmits, ownerKeyMaySeed, ownerWriteRefusal } from "../src/resources/owner-private"; +import { + OWNER_ROW_REFUSAL, + OWNER_WRITE_REFUSAL, + ownerKeyAdmits, + ownerKeyMaySeed, + ownerWriteRefusal, +} from "../src/resources/owner-private"; import { createMockModelResolver } from "@flow-state-dev/testing"; -const WRITE_REFUSAL = "A row of an owner-writes collection is written only by the user it belongs to."; -const PRIVATE_REFUSAL = "A row of an owner-private collection is readable only by the user it belongs to."; +const WRITE_REFUSAL = OWNER_WRITE_REFUSAL; +const PRIVATE_REFUSAL = OWNER_ROW_REFUSAL; const ALICE_KEY = `entries/apollo/${ownerSegment("alice")}/checkout`; const ALICE_STATE = { status: "ALICE-ON-TRACK" }; const passthrough = z.object({}).passthrough();