From 408da550b1431df0a96475e8a295efc2bb191976 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sun, 6 Dec 2026 09:07:53 +0000 Subject: [PATCH 1/7] An administrator assigns a shared namespace's document source to a service account's worker knowledge.source.worker_assign took only an agent's subject, in that agent's own namespace, so a team's shared index had no worker that could sync it. The worker subject's kind now decides where the source lives. An agent's subject keeps its rule: its own namespace, and not while it has lent it. Any other subject is assigned only in a namespace no workload trust made for an agent, and one that takes a shared source: not a person's own and active. A blank subject is refused. knowledge.source.worker.claim offers an agent's subject the sources of its own namespace, as before. A subject with no namespace of its own is offered the sources that name it across its org: one statement over the registry on the key prefix org that returns the key, version and registration of the rows naming the caller, 2,000 at most, and one read of their sync states. The row a turn starts on is read whole before its lease and is offered only at the version and subject the poll read. Such a poll draws the namespace tier of its rate limit on a slot per subject. The dashboard offers Retire on an assigned source to the subject that assigned it, and says that its copies go with it. No op, field, migration or setting is added. A replica one build behind lists, retires and expires such a source as it does an agent's, refuses to make one and answers its subject's claim with none. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/document-sources.md | 90 ++++++-- docs/architecture/rolling-upgrades.md | 10 + docs/features/knowledge.md | 42 +++- docs/reference/cli.md | 2 +- docs/reference/http-api.md | 5 +- docs/reference/operations/knowledge.md | 4 +- .../src/flows/KnowledgeSourceDialog.test.tsx | 33 +++ frontend/src/flows/KnowledgeSourceDialog.tsx | 22 +- frontend/src/lib/knowledgeSources.ts | 7 + frontend/src/views/SourcesList.test.tsx | 66 ++++++ frontend/src/views/SourcesList.tsx | 14 +- sdk/typescript/src/generated/ops.ts | 4 +- server/cli/knowledge_source.py | 11 +- server/knowledge/api/models_source_worker.py | 4 +- server/knowledge/api/models_sources.py | 35 +-- server/knowledge/app/assigned_sources.py | 74 ++++--- server/knowledge/app/source_worker_turns.py | 156 ++++++++++---- server/knowledge/domain/assigned_source.py | 41 +++- server/knowledge/store/sources.py | 80 +++++++ tests/analyzer/cases/workers.py | 6 + tests/analyzer/shapes.txt | 3 + .../test_cross_principal_leakage.py | 135 +++++++++++- .../integration/test_source_worker_turn_ch.py | 129 +++++++++++ tests/unit/snapshots/cli_help.json | 4 +- tests/unit/snapshots/cli_tree.json | 6 +- tests/unit/test_assigned_source.py | 57 ++++- tests/unit/test_source_worker_ops.py | 204 +++++++++++++++++- 27 files changed, 1098 insertions(+), 146 deletions(-) diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 8d0221cc45..8dec432574 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -137,7 +137,9 @@ An agent that runs beside an account host has no person to own a source and no credential Loom may hold: the host's tool channel adds the credential to each call. So a namespace administrator assigns the source instead, with `knowledge.source.worker_assign`: the row names the worker subject whose own token syncs -the source (`worker_subject`, an agent's subject `sa::`), the reader that +the source (`worker_subject`: an agent's subject `sa::`, or a service +account's that is no agent's, for +[a shared namespace](#where-an-assigned-source-lives)), the reader that subject runs (`reader`), the host's id of the connection (`ref`) with its `generation`, the digest of the reader profile the administrator approved (`profile_digest`), and the documents: 1 to 1,000 ids (`selection: selected`) or one container the worker lists on @@ -160,7 +162,10 @@ audience is the namespace's, the assignment fixes it where it is made: | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | | The caller is not the namespace's administrator | 403, the op's role refusal | | The caller is the worker subject | 403 `SOURCE_WORKER_SELF_ASSIGNED` | -| `worker_subject` is not an agent's subject, or the namespace is not its own | 422 `SOURCE_WORKER_NAMESPACE` | +| An agent's `worker_subject`, and the namespace is not that agent's own | 422 `SOURCE_WORKER_NAMESPACE` | +| Any other `worker_subject`, and the namespace is an agent's own | 422 `SOURCE_WORKER_NAMESPACE` | +| Any other `worker_subject`, and the namespace takes no shared source | 422 `PERSONAL_NAMESPACE` or `NAMESPACE_INACTIVE`, as for `add` | +| No `worker_subject` | 422 `SOURCE_WORKER_NAMESPACE` | | The agent has lent the namespace to another agent (`grants.share_agent`) | 409 `SOURCE_WORKER_NAMESPACE_SHARED` | | A live process reports a schema below the migration that adds `worker_subject` | 503 `OVERLOADED`, retry after 30 s | | No source of that name | the name and quota checks of `add`, then one row; `created: true` | @@ -173,14 +178,42 @@ audience is the namespace's, the assignment fixes it where it is made: | Another `generation`, `profile_digest`, `selection`, items, bound or pause | one version row, same `source_id`; `changed: true`; the copies stay | | Another `worker_subject`, `reader` or `ref` | 409 `SOURCE_REPLACED`: remove the source, then assign the new one | -The namespace's own is the directory row the agent's trust made: active, tagged for the -trust and owned by the agent. A share is a live grant the agent made to another subject: -the admin grant the agent's namespace starts with is none, and a grant an administrator -made on the namespace is that administrator's decision and refuses nothing. The other -way round, `grants.share_agent` answers 409 `NAMESPACE_HOLDS_ASSIGNED_SOURCE` while the -namespace holds an active assignment, and both run under the namespace's source lease, -so neither lands beside the other. An assigned source counts against the namespace's -source quota (`LOOM_KNOWLEDGE_SOURCES_MAX_PER_NAMESPACE`), not a person's. +An assigned source counts against the namespace's source quota +(`LOOM_KNOWLEDGE_SOURCES_MAX_PER_NAMESPACE`), not a person's. + +### Where an assigned source lives + +The worker subject's kind decides the namespace, and the subject's form decides the +kind: `sa::` is an agent's subject, and any other subject is not. + +| Worker subject | Namespace | Who reads the copies | What its claim reads | +| ---------------------------------------------------------- | ------------------------ | --------------------------------------------------------------- | ------------------------------------ | +| An agent's | That agent's own, only | The agent, and whoever an administrator granted the namespace | The agent's own namespace | +| Any other: a service account that runs a worker for a team | A shared namespace, only | Every reader of the namespace, as for a source `add` registered | The org's rows that name the subject | + +**An agent's own namespace** is the directory row the agent's trust made: active, tagged +for the trust and owned by the agent. A share is a live grant the agent made to another +subject: the admin grant the agent's namespace starts with is none, and a grant an +administrator made on the namespace is that administrator's decision and refuses +nothing. The other way round, `grants.share_agent` answers 409 +`NAMESPACE_HOLDS_ASSIGNED_SOURCE` while the namespace holds an active assignment, and +both run under the namespace's source lease, so neither lands beside the other. + +**A shared namespace** is one no workload trust made for an agent, which takes a shared +source. Its directory row carries no trust's tag, the mark a trust sets on each agent's +namespace and no caller can set; a released agent's namespace keeps the tag and is +refused too. It passes the checks of `knowledge.source.add`: never a person's own place, +never an inactive namespace. A namespace with no directory row is shared. The share rule +does not apply: the namespace's readers are the audience, whoever granted them. So a +source whose upstream not every reader of the namespace may read is not assigned to a +shared namespace: it stays a source a person owns. + +The assignment does not prove what a subject string names. Only a service account +calling as itself is answered a turn ([who is answered](#a-worker-subjects-turn)), so a +source that names a person is stored, shown, and never synced. No row names a subject +that is no agent's in an agent's namespace: the assignment refuses it, and a trust +never makes an agent's namespace over a name that holds an active source, which counts +as a namespace in use. Only the subject that assigned a source changes it, an org administrator included: the source is managed where it was turned on. `knowledge.source.list` and `inspect` show it @@ -203,10 +236,19 @@ Loom runs no reader and holds no credential: the worker lists and fetches. **Who is answered.** A claim is answered by assignment alone, not by a namespace role; a commit needs the writer role on the source's namespace and then the assignment. The caller is a worker subject when its verified token is a service account's own token, -carries no impersonation and no read narrowing, and belongs to the body's `org`. A claim reads -only the caller's home namespace, with one bounded statement over the registry on the -sorting key prefix `(org, namespace)` and one over the sync states of that namespace, -and keeps the active rows whose `worker_subject` is the caller. A caller that is no +carries no impersonation and no read narrowing, and belongs to the body's `org`. An +agent's claim reads only the agent's own namespace, with one bounded statement over the +registry on the sorting key prefix `(org, namespace)` and one over the sync states of +that namespace, and keeps the active rows whose `worker_subject` is the caller: a row +that names the agent in another namespace is never offered. A subject that is no +agent's has no namespace of its own, so its claim reads the org: one statement over the +registry on the sorting key prefix `org` that answers only the active rows whose +`worker_subject` is the caller, by namespace and name, 2,000 at most and without their +items, and one statement over the sync states of those rows. Neither is repeated per +namespace. Before a turn starts, that claim reads the due source's whole row and offers +it only at the version the first read answered and while it still names the caller. A +worker subject is offered at most 2,000 sources: a team with more runs another worker +under another subject. A caller that is no worker subject, or one with no source, is answered `status: none` exactly as a worker with nothing due, so the answer never says whether a source exists. A commit names its namespace, so the transport first requires the writer role there and refuses a caller @@ -537,9 +579,11 @@ Three bounds decide how an org with thousands of assigned sources behaves: requests of `source.worker.write`: 200 at once and 20 a second for the org at the defaults, however many workers send them. A turn's polls, one `claim` and its `stored` pages of up to 500 copies, draw `source.worker.poll`: 200 at once and 40 a second. A - fleet that sends under those rates is never refused by the org. Every read of a - `claim` names its caller's home namespace; it still reads the whole index granule - those rows are in, which the org's other sources share. + fleet that sends under those rates is never refused by the org. Every read of an + agent's `claim` names its caller's home namespace; it still reads the whole index + granule those rows are in, which the org's other sources share. The `claim` of a + subject that is no agent's reads the org's registry rows once and draws the + namespace tier on a slot of its own per subject. - **Sources that expire together are retired a page of the queue a pass.** The scan queues what it reaches in its 15 seconds, each expiry under its namespace's source lease, and the queue then retires 40 entries. An entry queued behind the queue's @@ -2095,6 +2139,10 @@ The redirect URI to register with each store is ([a worker subject's turn](#a-worker-subjects-turn)). - No copy of an assigned source is retired on the evidence of a listing that was partial, failed or empty. +- An agent's token claims no source outside the agent's own namespace, and a subject + that is no agent's is assigned no source inside one + ([where an assigned source lives](#where-an-assigned-source-lives)). A claim that + reads the org answers only rows that name the caller's own subject. ## Source entry points @@ -2362,6 +2410,14 @@ Each implementing pull request lists its own; these pin the model: and a disconnect stop the person's sources and retire their mirrored documents; `namespace.delete` and `collection.delete` retire the namespace's sources and clear their credentials. +- Unit and integration: `tests/unit/test_assigned_source.py`, + `tests/unit/test_source_worker_ops.py`, `tests/integration/test_source_worker_turn_ch.py` + and `tests/integration/test_cross_principal_leakage.py`: a subject that is no agent's + is assigned a source only outside agents' namespaces and an agent's subject only in + its own; a service account claims its sources in two namespaces with one registry + read and one state read, and never another subject's; a person named as worker + subject claims nothing; a reader of the shared namespace finds the copy, and a + principal of another namespace or org sees neither the source nor the copy. - Integration: `tests/integration/test_document_worker_load.py`: 200 assigned sources of one org import, expire together, are retired by the queue and import again with no request refused by an org bucket; an org whose write bucket is empty does not refuse diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 3076c199a5..035e6ce5c0 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1297,6 +1297,16 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline never reads it and it waits for a retirement pass of N, and `copies_expired_at` is a key of the state row N-1 never reads for a worker row. The scan's position in the worker's resume cursor is an exception to rule 4, described there. + N assigns a source to a subject that is no agent's, in a shared namespace + ([where an assigned source lives](document-sources.md#where-an-assigned-source-lives)), + and offers that subject its sources across the org. The row has the shape of every + assigned row, so N-1 lists it, retires it on `remove` and expires its copies as it + does an agent's. N-1 refuses to make or change one with 422 + `SOURCE_WORKER_NAMESPACE` and answers that subject's claim `none`, since it reads + only an agent's own namespace; a worker routed to N-1 polls again, and its `stored`, + `put` and `commit` on a turn N opened are served by both builds. No gate holds the + rollout. After a rollback below N such a source is never claimed: its copies are + served until the copy age bound retires them, or until its registrant removes it. The mixed-version gate does not check this rule. 82. **The `primer`, `pin` and `unpin` sections of `curator.status`** (no migration): N diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index ef72588c34..8fcf617fde 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -524,8 +524,11 @@ A probe's error names the HTTP status (`http_403`), never the store's response t An agent that runs beside an account host reads its documents through the host's own tool channel, which holds the credential. A namespace administrator assigns such a source to the agent's worker subject with `knowledge.source.worker_assign` -(experimental; `loom knowledge source assign`). The assignment names who syncs -(`worker_subject`, the agent's subject `sa::`), the reader that subject +(experimental; `loom knowledge source assign`). A team's shared index is assigned the +same way to a service account that runs the worker +([a team's shared namespace](#a-service-accounts-source-in-a-shared-namespace)). The +assignment names who syncs (`worker_subject`: an agent's subject `sa::`, +or a service account's), the reader that subject runs, the host's id of the connection (`ref`) and its `generation`, the digest of the approved reader profile, and what to read: 1 to 1,000 document ids with `selection: selected`, or one container id with `selection: listed`. Its own fields take @@ -545,9 +548,10 @@ likes; a changed `generation`, `profile_digest`, `selection`, item list, `max_documents` (2,000 by default, at most `LOOM_KNOWLEDGE_SOURCE_MAX_DOCUMENTS`) or `paused` writes one version of the same source. -- The source lives only in the worker subject's own namespace, and every reader of that - namespace reads its copies (`access_rule` answers `collection_wide`). Any other - namespace answers `SOURCE_WORKER_NAMESPACE` (422). +- An agent's source lives only in that agent's own namespace, and a source of any + other worker subject only in a shared namespace; every reader of the namespace reads + its copies (`access_rule` answers `collection_wide`). Any other pairing answers + `SOURCE_WORKER_NAMESPACE` (422). - The worker subject does not assign a source to itself (`SOURCE_WORKER_SELF_ASSIGNED`, 403), and only the subject that assigned a source changes it (`SOURCE_MANAGED_BY_REGISTRANT`, 403). @@ -571,6 +575,34 @@ the worker subject's next turn runs at once. The other source operations refuse source with `SOURCE_WORKER_OWNED`. The design is in [document sources](../architecture/document-sources.md#a-source-a-worker-syncs-for-an-agent). +#### A service account's source in a shared namespace + +A team's shared index, such as public documentation, has no agent: an operator runs the +worker under a service account, and every reader of the shared namespace reads the +copies. Assign the source in that namespace to the service account's subject: + +```bash +loom knowledge source assign --namespace team-docs --name handbook \ + --worker-subject sa:docs-sync --reader pages --ref docs-1 --generation 1 \ + --profile-digest <64 hex digits> --selection listed --item space-1 +``` + +- The namespace is a shared one: not an agent's own (`SOURCE_WORKER_NAMESPACE`, 422), + not a person's own (`PERSONAL_NAMESPACE`, 422) and active (`NAMESPACE_INACTIVE`, 422). +- Every reader of the namespace reads every copy. Assign a source there only when all + of them may read all of its upstream; otherwise keep it a source a person owns. +- Give the service account's token the `writer` role on each namespace it syncs: the + turn's `put`, `stored` and `commit` name the namespace. +- Name a service account. Only a service account calling as itself is answered a turn, + and `worker_assign` cannot tell what a subject string names, so a source that names a + person is stored and never synced. +- One claim offers the service account its sources in every namespace of the org, 2,000 + at most. Run a second worker under another subject for more. +- The subject that assigned the source removes it, with `loom knowledge source remove` + or the dashboard's Retire, and its copies go with it. + +#### Turns + The worker subject syncs the source in turns: `knowledge.source.worker.claim` (experimental) answers the next due source assigned to the caller, with a claim that is the bearer secret of that turn, and `knowledge.source.worker.commit` (experimental) diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 816a0920be..3957154c27 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -263,7 +263,7 @@ python scripts/codegen/docs_reference.py | `loom knowledge source list` | List the namespace's sources, items and sync state. | `--namespace`, `--org`, `--server-url`, `--token` | | `loom knowledge source add` | Register a source from links or items, probed with the credential before anything is stored; a source added with a credential file is read by every reader of the namespace (knowledge.source.add). | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--kind`, `--link`, `--item-json`, `--include`, `--credential-file`, `--dry-run` | | `loom knowledge source update` | Add and remove a source's items or change its file kinds, the added items probed with the stored credential (knowledge.source.update). | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--link`, `--item-json`, `--include`, `--remove-link`, `--remove-item-json` | -| `loom knowledge source assign` | Assign a source to a worker subject, or change that assignment; the namespace is that subject's own, and every reader of it reads the copies (knowledge.source.worker_assign, experimental). | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--worker-subject`, `--reader`, `--ref`, `--generation`, `--profile-digest`, `--selection`, `--item`, `--changed-since`, `--max-documents`, `--paused` | +| `loom knowledge source assign` | Assign a source to a worker subject, or change that assignment; the namespace is an agent's own for that agent's subject and a shared one for any other, and every reader of it reads the copies… | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--worker-subject`, `--reader`, `--ref`, `--generation`, `--profile-digest`, `--selection`, `--item`, `--changed-since`, `--max-documents`, `--paused` | | `loom knowledge source remove` | Retire a source: its row goes inactive and its credential is cleared. | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--confirm`, `--delete-documents` | | `loom knowledge source worker-profiles` | List the provisioned source worker profiles and the collection's approval of each (knowledge.source.worker_profiles; experimental, answered denied until the CLI declares session protection). | `--namespace`, `--org`, `--server-url`, `--token`, `--limit`, `--after-json` | | `loom knowledge source worker-approve` | Set or revoke the collection's approval of one worker profile (knowledge.source.worker_approve; experimental, answered denied until the CLI declares session protection). | `--namespace`, `--org`, `--server-url`, `--token`, `--worker-id`, `--profile-digest`, `--mode`, `--revoke`, `--team-access`, `--expected-generation` | diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 34862895bf..3c04d829fa 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -528,8 +528,9 @@ and **op class**: `memory`, `memory.read` (exact-key reads such as `X-RateLimit-*` headers and `detail.retry_after_s`. Both SDKs pace on these headers and wait out a 429 for up to 15 s per call by default. - `knowledge.source.worker.claim` names no namespace: it draws its buckets on the - calling agent's own namespace, and its 429 carries `Retry-After` and - `detail.retry_after_s` without the `X-RateLimit-*` headers. + calling agent's own namespace, or for a subject that is no agent's on a slot of its + own per subject, and its 429 carries `Retry-After` and `detail.retry_after_s` without + the `X-RateLimit-*` headers. Rate-limit tuning for a deployment is in [Performance tuning](../guides/performance-tuning.md). diff --git a/docs/reference/operations/knowledge.md b/docs/reference/operations/knowledge.md index 4f1a5a570f..790c2f3351 100644 --- a/docs/reference/operations/knowledge.md +++ b/docs/reference/operations/knowledge.md @@ -1203,9 +1203,9 @@ Assign a document source to a worker subject, or change that assignment: the sub | Input field | Type | Default | Meaning | | --- | --- | --- | --- | | `org` | `str` | required | The org. | -| `namespace` | `str` | required | The worker subject's own namespace. | +| `namespace` | `str` | required | The namespace the copies live in: the agent's own, or a shared one for a subject that is no agent's. | | `name` | `str` | required | The source name, unique in the namespace. | -| `worker_subject` | `str` | required | The agent's subject (sa::) whose token syncs the source. | +| `worker_subject` | `str` | required | The subject whose token syncs the source: an agent's (sa::), or a service account's that is no agent's. | | `reader` | `str` | required | The reader the worker runs: a lower-case letter, then letters, digits or _. | | `ref` | `str` | required | The host's id of the connection: lower-case letters, digits and -. | | `generation` | `int` | required | The connection's generation at the host, from 1. | diff --git a/frontend/src/flows/KnowledgeSourceDialog.test.tsx b/frontend/src/flows/KnowledgeSourceDialog.test.tsx index 51cef0c1c1..c111c5ef62 100644 --- a/frontend/src/flows/KnowledgeSourceDialog.test.tsx +++ b/frontend/src/flows/KnowledgeSourceDialog.test.tsx @@ -639,6 +639,39 @@ describe("RetireSourceDialog", () => { return onRetired; } + it.each([ + { pending: 0, said: "Retired design-docs; its copies are removed" }, + { pending: 1, said: "Retired design-docs; 1 copy is still being removed" }, + { pending: 40, said: "Retired design-docs; 40 copies are still being removed" }, + ])("retires an assigned source with its copies, $pending left", async ({ pending, said }) => { + vi.mocked(removeKnowledgeSource).mockResolvedValue({ name: "design-docs", documents_pending: pending }); + const onRetired = vi.fn(); + render( + {}} + {...NS} + name="design-docs" + enabled + access="namespace" + assigned + onRetired={onRetired} + />, + ); + expect( + screen.getByText( + "Loom stops syncing this source and removes the copies it wrote. Every reader of the namespace reads them until then.", + ), + ).toBeInTheDocument(); + // The copies always go: there is nothing to choose. + expect(screen.queryByRole("checkbox")).not.toBeInTheDocument(); + fireEvent.change(screen.getByLabelText(/to confirm/), { target: { value: "design-docs" } }); + fireEvent.click(screen.getByRole("button", { name: "Retire source" })); + await waitFor(() => expect(onRetired).toHaveBeenCalled()); + expect(removeKnowledgeSource).toHaveBeenCalledWith(NS, "design-docs", "design-docs", true); + expect(vi.mocked(toast).mock.calls[0]?.[0]).toBe(said); + }); + it.each([true, false])("explains mandatory mirrored-copy retirement with sync enabled=%s", async (enabled) => { vi.mocked(removeKnowledgeSource).mockResolvedValue({ name: "design-docs", documents_pending: 0 }); const onRetired = renderRetire(enabled, vi.fn(), "mirrored"); diff --git a/frontend/src/flows/KnowledgeSourceDialog.tsx b/frontend/src/flows/KnowledgeSourceDialog.tsx index 1b3d7b209a..7f3df40e80 100644 --- a/frontend/src/flows/KnowledgeSourceDialog.tsx +++ b/frontend/src/flows/KnowledgeSourceDialog.tsx @@ -657,15 +657,25 @@ export function RetireSourceDialog({ name, enabled, access, + assigned = false, onRetired, -}: DialogProps & { name: string; enabled: boolean; access: KnowledgeSource["access"]; onRetired: () => void }) { +}: DialogProps & { + name: string; + enabled: boolean; + access: KnowledgeSource["access"]; + /** A source assigned to a worker subject: its copies always go with it. */ + assigned?: boolean; + onRetired: () => void; +}) { const [typed, setTyped] = useState(""); const [deleteDocuments, setDeleteDocuments] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); - const retireDocuments = access === "mirrored" || deleteDocuments; - const description = - access === "mirrored" + const always = access === "mirrored" || assigned; + const retireDocuments = always || deleteDocuments; + const description = assigned + ? "Loom stops syncing this source and removes the copies it wrote. Every reader of the namespace reads them until then." + : access === "mirrored" ? `Loom stops pulling from this source. Mirrored copies are always queued for retirement. Only this source's imported copies are retired over future sync passes${enabled ? "." : "; retirement waits until sync is on."}` : access === "namespace" ? "Loom stops pulling from the source and clears any credential it stored. The documents it wrote stay unless you ask for them to go too." @@ -675,7 +685,7 @@ export function RetireSourceDialog({ setError(null); try { const out = await removeKnowledgeSource({ org, namespace }, name, typed.trim(), retireDocuments); - toast(retiredMessage(name, retireDocuments, out.documents_pending, enabled, access), "ok"); + toast(retiredMessage(name, retireDocuments, out.documents_pending, enabled, access, assigned), "ok"); onRetired(); onOpenChange(false); } catch (e) { @@ -706,7 +716,7 @@ export function RetireSourceDialog({ } > - {access !== "mirrored" && ( + {!always && ( { expect(items[0]).not.toHaveAttribute("aria-disabled"); }); + it("offers Retire on a service account's source to the subject that assigned it", async () => { + useStore.setState({ whoami: { authenticated: true, subject: "alice", org: "acme", roles: ["admin"] } }); + const assigned = { + ...LISTED.sources[0]!, + kind: "mcp", + credential_mode: "worker", + items: [{ id: "space-1" }], + worker_subject: "sa:docs-sync", + }; + sources.listKnowledgeSources.mockResolvedValue({ + enabled: true, + sources: [ + { ...assigned, name: "handbook", managed_by: "alice" }, + { ...assigned, name: "wiki", managed_by: "bob" }, + ], + }); + render(); + // One sentence, whoever syncs and whoever manages: a service account and a person here. + const row = (await screen.findByRole("button", { name: "handbook" })).closest("li")!; + expect(row).toHaveTextContent("Synced by sa:docs-sync. Managed by alice."); + // The server takes its removal only from the subject that assigned it. + await userEvent.click(screen.getByRole("button", { name: "Actions for wiki" })); + const theirs = await screen.findByRole("menu", { name: "Actions for wiki" }); + expect( + within(theirs) + .getAllByRole("menuitem") + .map((item) => item.textContent), + ).toEqual(["Sync now"]); + await userEvent.keyboard("{Escape}"); + await userEvent.click(screen.getByRole("button", { name: "Actions for handbook" })); + const mine = await screen.findByRole("menu", { name: "Actions for handbook" }); + expect( + within(mine) + .getAllByRole("menuitem") + .map((item) => item.textContent), + ).toEqual(["Sync now", "Retire"]); + // Its copies always go with it: the dialog says so and offers no choice. + await userEvent.click(within(mine).getByRole("menuitem", { name: "Retire" })); + expect(await screen.findByText(/removes the copies it wrote/)).toBeInTheDocument(); + expect(screen.queryByRole("checkbox")).not.toBeInTheDocument(); + }); + + it("offers the subject that assigned a source its Retire where it cannot ask for a sync", async () => { + useStore.setState({ whoami: { authenticated: true, subject: "alice", org: "acme", roles: ["viewer"] } }); + sources.listKnowledgeSources.mockResolvedValue({ + enabled: true, + sources: [ + { + ...LISTED.sources[0]!, + kind: "mcp", + credential_mode: "worker", + worker_subject: "sa:docs-sync", + managed_by: "alice", + }, + ], + }); + render(); + await userEvent.click(await screen.findByRole("button", { name: "Actions for design-docs" })); + const menu = await screen.findByRole("menu", { name: "Actions for design-docs" }); + expect( + within(menu) + .getAllByRole("menuitem") + .map((item) => item.textContent), + ).toEqual(["Retire"]); + }); + it("says what a blocked assigned source waits for, and why a withdrawn one cannot be synced", async () => { useStore.setState({ whoami: { authenticated: true, subject: "alice", org: "acme", roles: ["admin"] } }); const assigned = { diff --git a/frontend/src/views/SourcesList.tsx b/frontend/src/views/SourcesList.tsx index c449527b49..2707c96636 100644 --- a/frontend/src/views/SourcesList.tsx +++ b/frontend/src/views/SourcesList.tsx @@ -293,8 +293,8 @@ function ScopedSourcesList({ const menu = (s: KnowledgeSource): RowMenuItem[] => { // The server serves only removal for a worker source; the dashboard offers none. An - // assigned one is changed and removed where it was assigned, never here: a writer of - // its namespace may only ask for its next turn. + // assigned one is changed where it was assigned, never here: a writer of its + // namespace may ask for its next turn, and the subject that assigned it may retire it. const assigned = isAssignedSource(s); if (isWorkerSource(s) && !assigned) return []; const connected = s.credential_mode === "connected"; @@ -315,10 +315,15 @@ function ScopedSourcesList({ reason: item.reason ?? (expired ? "Sign in again to use this." : null), })); if (assigned) { - if (closed || !(manageable || connectedManageable)) return []; // A request starts no turn on a source whose access the provider withdrew. const withdrawn = "Access was withdrawn at the provider. Assign the source again to sync it."; - return disable([{ ...sync, reason: s.sync.status === "revoked" ? withdrawn : null }]); + const asks = !closed && (manageable || connectedManageable); + // The server takes an assigned source's removal only from the subject that assigned it. + const removes = !!subject && s.managed_by === subject; + return disable([ + ...(asks ? [{ ...sync, reason: s.sync.status === "revoked" ? withdrawn : null }] : []), + ...(removes ? [retire] : []), + ]); } // The namespace's admin may check, sync or retire another person's connected source; only // its owner edits its items or manages its connection. @@ -563,6 +568,7 @@ function ScopedSourcesList({ name={acting.source.name} enabled={state.kind === "ready" && state.enabled} access={acting.source.access} + assigned={isAssignedSource(acting.source)} onOpenChange={close} onRetired={reload} /> diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 9bddc58b6e..89e42a5efc 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -5462,11 +5462,11 @@ export interface KnowledgeSourceAssignedItem { export interface KnowledgeSourceWorkerAssignInput { /** The org. */ org: string; - /** The worker subject's own namespace. */ + /** The namespace the copies live in: the agent's own, or a shared one for a subject that is no agent's. */ namespace: string; /** The source name, unique in the namespace. */ name: string; - /** The agent's subject (sa::) whose token syncs the source. */ + /** The subject whose token syncs the source: an agent's (sa::), or a service account's that is no agent's. */ worker_subject: string; /** The reader the worker runs: a lower-case letter, then letters, digits or _. */ reader: string; diff --git a/server/cli/knowledge_source.py b/server/cli/knowledge_source.py index c22c13bde9..cc7fdefd79 100644 --- a/server/cli/knowledge_source.py +++ b/server/cli/knowledge_source.py @@ -65,13 +65,16 @@ def register_knowledge_source_cli(ksub: Any) -> None: p_assign = ssub.add_parser( "assign", help="Assign a source to a worker subject, or change that assignment; the namespace " - "is that subject's own, and every reader of it reads the copies " - "(knowledge.source.worker_assign, experimental).", + "is an agent's own for that agent's subject and a shared one for any other, and " + "every reader of it reads the copies (knowledge.source.worker_assign, experimental).", ) - _common(p_assign, "The worker subject's own namespace") + _common(p_assign, "The namespace the copies live in") p_assign.add_argument("--name", required=True, help="The source's name in the namespace") p_assign.add_argument( - "--worker-subject", required=True, help="The agent's subject, sa::" + "--worker-subject", + required=True, + help="The subject whose token syncs the source: an agent's, sa::, " + "or a service account's", ) p_assign.add_argument("--reader", required=True, help="The reader the worker runs") p_assign.add_argument("--ref", required=True, help="The host's id of the connection") diff --git a/server/knowledge/api/models_source_worker.py b/server/knowledge/api/models_source_worker.py index ad7e701f04..c16a974e52 100644 --- a/server/knowledge/api/models_source_worker.py +++ b/server/knowledge/api/models_source_worker.py @@ -20,7 +20,9 @@ class KnowledgeSourceWorkerClaimInput(BaseModel): """Ask for one turn of one document source assigned to the calling worker subject. Only a service account calling as itself is answered with a turn; any other caller, - and a subject no source is assigned to, is answered `none`. The answer names the + and a subject no source is assigned to, is answered `none`. An agent's subject is + offered the sources of its own namespace; any other subject is offered the sources + that name it in every namespace of the org, 2,000 at most. The answer names the source due longest whose reader and profile digest the call lists, with a `claim` that proves the turn to `knowledge.source.worker.commit` until the turn ends: by its last commit, by its age, or by any rewrite of the source's registration.""" diff --git a/server/knowledge/api/models_sources.py b/server/knowledge/api/models_sources.py index 33268f6fd5..29127c7336 100644 --- a/server/knowledge/api/models_sources.py +++ b/server/knowledge/api/models_sources.py @@ -759,26 +759,35 @@ class KnowledgeSourceAssignedItem(BaseModel): class KnowledgeSourceWorkerAssignInput(BaseModel): """Assign a document source to a worker subject, or change that assignment: the subject's own token then syncs the source into this namespace, where every reader of - the namespace reads its copies. The namespace must be the worker subject's own (an - agent's namespace), and a namespace administrator other than that subject assigns. - The assignment names a reader, the host's id of a connection and the documents; its - own fields hold no address, tool name or credential, which the host's tool channel - adds, and an item id is the host's opaque id, shown to every reader of the - namespace. A call that changes nothing writes nothing. Only the subject that - assigned the source changes it (SOURCE_MANAGED_BY_REGISTRANT); another worker - subject, reader or connection is a remove and a new assignment (SOURCE_REPLACED), - under another name or, once the removed source's copies are retired, the same one: - until then the name answers SOURCE_RETIRING. - Refused while the agent has lent the namespace to another agent + the namespace reads its copies. A namespace administrator other than the worker + subject assigns, and the subject's kind decides the namespace + (SOURCE_WORKER_NAMESPACE): an agent's subject syncs only the agent's own namespace; + any other subject, a service account that runs a worker for a team, syncs only a + shared namespace, one that is no agent's own and takes a shared source. Only a + service account calling as itself is ever answered a turn, so a source that names a + person is accepted and never synced. The assignment names a reader, the host's id + of a connection and the documents; its own fields hold no address, tool name or + credential, which the host's tool channel adds, and an item id is the host's opaque + id, shown to every reader of the namespace. A call that changes nothing writes + nothing. Only the subject that assigned the source changes it + (SOURCE_MANAGED_BY_REGISTRANT); another worker subject, reader or connection is a + remove and a new assignment (SOURCE_REPLACED), under another name or, once the + removed source's copies are retired, the same one: until then the name answers + SOURCE_RETIRING. Refused while the agent has lent its namespace to another agent (SOURCE_WORKER_NAMESPACE_SHARED).""" org: str = Field(..., description="The org.") - namespace: str = Field(..., description="The worker subject's own namespace.") + namespace: str = Field( + ..., + description="The namespace the copies live in: the agent's own, or a shared one " + "for a subject that is no agent's.", + ) name: str = Field(..., max_length=64, description="The source name, unique in the namespace.") worker_subject: str = Field( ..., max_length=256, - description="The agent's subject (sa::) whose token syncs the source.", + description="The subject whose token syncs the source: an agent's " + "(sa::), or a service account's that is no agent's.", ) reader: str = Field( ..., diff --git a/server/knowledge/app/assigned_sources.py b/server/knowledge/app/assigned_sources.py index e0b80eb9f4..91bc86373a 100644 --- a/server/knowledge/app/assigned_sources.py +++ b/server/knowledge/app/assigned_sources.py @@ -1,16 +1,20 @@ """knowledge.source.worker_assign: a namespace administrator names the worker subject -that may sync one document source into that subject's own namespace. +that may sync one document source into a namespace. -An agent beside an account host has no person to own a source and no credential Loom may -hold: the host's tool channel adds the credential. So the assignment names only who syncs -(an agent's subject), through which reader and which of the host's connections, and the -documents. It writes no document and starts no turn. +A worker has no person to own a source and no credential Loom may hold: the host's tool +channel adds the credential. So the assignment names only who syncs (the worker +subject), through which reader and which of the host's connections, and the documents. +It writes no document and starts no turn. The copies will live in the namespace itself, read by every reader of it, so the audience -is fixed where the source is assigned: only in the worker subject's own namespace, never by -that subject, and not while the agent has lent the namespace to another agent -(`grants.share_agent` refuses the other way round). Add and change are one op, since a host -applies its wanted state repeatedly: a call that changes nothing writes nothing. +is fixed where the source is assigned, never by the worker subject itself. The subject's +kind decides the place (`_require_place`). An agent's subject syncs only the agent's own +namespace, and not while the agent has lent it to another agent (`grants.share_agent` +refuses the other way round). Any other subject, a service account that runs a worker +for a team, syncs only a namespace no workload trust made for an agent and that takes a +shared source: its readers are the audience, as for a source added to the namespace. +Add and change are one op, since a host applies its wanted state repeatedly: a call +that changes nothing writes nothing. """ from __future__ import annotations @@ -91,26 +95,53 @@ def _registration( def _not_home(namespace: str) -> ValidationError: return ValidationError( - f"{namespace!r} is not the own namespace of the agent worker_subject names; a " - "source is assigned only there", + f"{namespace!r} is not the own namespace of the agent worker_subject names; an " + "agent's source is assigned only there", code="SOURCE_WORKER_NAMESPACE", ) def _trust_of(namespace: str, worker_subject: str) -> str: """The trust of the agent `worker_subject` names, when `namespace` is that agent's - own by name; any other subject, an empty one included, is refused.""" + own by name; '' for a subject that is no agent's, whose place the directory decides + (`_require_place`). An agent's subject anywhere else is refused, and so is no + subject: an assigned row is the one that names its worker.""" found = agents.parse(worker_subject) - if found is None or agents.home_of(worker_subject) != namespace: + if found is None: + if not worker_subject.strip(): + raise ValidationError( + "worker_subject names the subject whose token syncs the source", + code="SOURCE_WORKER_NAMESPACE", + ) + return "" + if agents.home_of(worker_subject) != namespace: raise _not_home(namespace) return found[0] -async def _require_home(org: str, namespace: str, worker_subject: str, trust: str) -> None: - """An assigned source lives only in its worker subject's own namespace: the - directory row the agent's trust made.""" - if not await store.is_agent_home(org, namespace, tag=agents.tag(trust), agent=worker_subject): - raise _not_home(namespace) +async def _require_place(org: str, namespace: str, worker_subject: str, trust: str) -> None: + """Where an assigned source may live, by its worker subject's kind. An agent's + (`trust` is its trust): the directory row that trust made for it, while the agent + has lent the namespace to nobody. Any other subject's: a namespace no trust made, + released ones included, that takes a shared source (`_require_source_namespace`).""" + if trust: + if not await store.is_agent_home( + org, namespace, tag=agents.tag(trust), agent=worker_subject + ): + raise _not_home(namespace) + if await store.lent_by(org, namespace, worker_subject): + raise SourceWorkerNamespaceSharedError( + f"the agent of {namespace!r} has lent it to another agent; a source " + "is assigned once it has taken its shares back" + ) + return + if await store.trust_made(org, namespace, prefix=agents.TAG_PREFIX): + raise ValidationError( + f"{namespace!r} is an agent's own namespace; only that agent's subject syncs " + "a source there", + code="SOURCE_WORKER_NAMESPACE", + ) + await source_ops._require_source_namespace(org, namespace) async def _require_fleet() -> None: @@ -194,12 +225,7 @@ async def handle_knowledge_source_worker_assign( # Under the lease nothing else writes this namespace's sources, and an agent's # share waits for it, so the checks hold until the insert. with sequential_reads(): - await _require_home(input.org, input.namespace, input.worker_subject, trust) - if await store.lent_by(input.org, input.namespace, input.worker_subject): - raise SourceWorkerNamespaceSharedError( - f"the agent of {input.namespace!r} has lent it to another agent; a source " - "is assigned once it has taken its shares back" - ) + await _require_place(input.org, input.namespace, input.worker_subject, trust) await _require_fleet() held = await store.get_source(input.org, input.namespace, name) if held is not None and domain.is_assigned(held): diff --git a/server/knowledge/app/source_worker_turns.py b/server/knowledge/app/source_worker_turns.py index a718a75be4..517e257296 100644 --- a/server/knowledge/app/source_worker_turns.py +++ b/server/knowledge/app/source_worker_turns.py @@ -2,11 +2,13 @@ turn of one document source assigned to it, reads what the source holds, uploads its documents and closes the turn. -A worker beside an account host has no listener, and the server holds no credential for -it, so the worker asks for work. `claim` answers the caller's source that has been due -longest and takes the source's turn lease, the one a native sync turn of the name would -hold, for the turn's whole bound; `commit` records progress and, with `done`, the outcome -that schedules the next turn (`domain.source_worker_schedule`). +A worker has no listener, and the server holds no credential for it, so the worker asks +for work. `claim` answers the caller's source that has been due longest and takes the +source's turn lease, the one a native sync turn of the name would hold, for the turn's +whole bound; `commit` records progress and, with `done`, the outcome that schedules the +next turn (`domain.source_worker_schedule`). An agent's subject is offered the sources of +its own namespace and no other; a subject that is no agent's has no namespace of its +own and is offered the sources that name it across its org (`_offers_across`). Inside the turn `stored` lists the source's copies (ids, revisions and hashes, never text), `put` writes one document as the source's copy at the source's own address @@ -86,6 +88,7 @@ AssignedItem, AssignedSourceConfig, AssignedSourceRefused, + assigned_config, assigned_prefix, assigned_uri, decode_assigned_source, @@ -156,77 +159,154 @@ def _lost() -> ClaimLostError: return ClaimLostError("the claim is not current; claim the source's next turn") +class _Offer(NamedTuple): + """One of the caller's sources as a poll weighs it: its key, the row version read, + its registration and its turn state. It holds no item.""" + + namespace: str + name: str + version: int + config: AssignedSourceConfig + state: schedule.TurnState + + class _Due(NamedTuple): src: KnowledgeSource config: AssignedSourceConfig items: tuple[AssignedItem, ...] state: schedule.TurnState + def offer(self) -> _Offer: + src = self.src + return _Offer(src.namespace, src.name, src.version, self.config, self.state) + + +def _poll_slot(subject: str) -> str: + """Where the poll of a subject with no namespace of its own draws its namespace + bucket: a slot per subject, a name no namespace can have, so one worker's polls + spend no other's.""" + return f"source-worker:{subject}" + + +async def _rows_at_home(org: str, home: str, subject: str) -> dict[tuple[str, str], _Due]: + """The caller's sources in its own namespace, by key: one read of that namespace's + key range and one of its sync states.""" + rows = await store.assigned_to( + org, home, subject, limit=int(settings.knowledge_sources_max_per_namespace) + ) + states = await store.read_states(org, home, [row.name for row in rows]) + found: dict[tuple[str, str], _Due] = {} + for src in rows: + try: + config, items = decode_assigned_source(src) + except AssignedSourceRefused: + continue + detail = domain.json_object((states.get(src.name) or {}).get("detail", "")) + found[(src.namespace, src.name)] = _Due(src, config, items, schedule.turn_state(detail)) + return found + + +async def _offers_across(org: str, subject: str) -> list[_Offer]: + """The sources that name `subject` as their worker, whichever namespace of the org + holds them: one statement over the registry that answers only such rows, and one + over their sync states, never a read per namespace. The rows come without their + items; `_row_of` reads the one a turn is about to start on.""" + rows = await store.assigned_across(org, subject) + states = await store.read_states_of(org, [(row.namespace, row.name) for row in rows]) + offers: list[_Offer] = [] + for row in rows: + try: + config = assigned_config(row.config_json) + except AssignedSourceRefused: + continue + stored = states.get((row.namespace, row.name)) or {} + state = schedule.turn_state(domain.json_object(stored.get("detail", ""))) + offers.append(_Offer(row.namespace, row.name, row.version, config, state)) + return offers + + +async def _row_of(org: str, subject: str, offer: _Offer) -> _Due | None: + """The whole row of a due `offer`, read fresh; None when it is no longer the + assignment the poll read: rewritten, removed, or handed to another subject.""" + with sequential_reads(): + src = await store.get_source(org, offer.namespace, offer.name) + if src is None or src.version != offer.version or src.worker_subject != subject: + return None + try: + config, items = decode_assigned_source(src) + except AssignedSourceRefused: + return None + return _Due(src, config, items, offer.state) + async def handle_knowledge_source_worker_claim( input: KnowledgeSourceWorkerClaimInput, ) -> KnowledgeSourceWorkerClaimOutput: idle = int(settings.knowledge_source_sync_interval_seconds) subject = _worker_subject(input.org) - home = agents.home_of(subject) if subject else "" - if not home: + if not subject: return KnowledgeSourceWorkerClaimOutput(status="none", retry_after_s=idle) + # An agent's subject reads its own namespace and nothing else, whatever names it. + home = agents.home_of(subject) # A claim names no namespace, so the transport draws no bucket for it: the poll's - # buckets are drawn here, on the caller's home, before the first read. + # buckets are drawn here, on the caller's home or its own slot, before the first read. admit_route( "knowledge.source.worker.claim", - home, + home or _poll_slot(subject), org=input.org, actor=subject, traffic_class=current_traffic_class(), ) + rows: dict[tuple[str, str], _Due] = {} with sequential_reads(): # a registration another replica just wrote is the current one - rows = await store.assigned_to( - input.org, home, subject, limit=int(settings.knowledge_sources_max_per_namespace) - ) - states = await store.read_states(input.org, home, [row.name for row in rows]) + if home: + rows = await _rows_at_home(input.org, home, subject) + offers = [found.offer() for found in rows.values()] + else: + offers = await _offers_across(input.org, subject) now = utc_now() - due: list[_Due] = [] waiting: list[KnowledgeSourceWorkerAttention] = [] next_due: datetime | None = None - def claimable(found: _Due) -> bool: - """Whether `found` may start a turn now; one that may not is counted among the + def claimable(offer: _Offer) -> bool: + """Whether `offer` may start a turn now; one that may not is counted among the sources that wait for a person, or towards the earliest due time.""" nonlocal next_due - src, config, _items, state = found - if schedule.needs_person(state, src.version): + if schedule.needs_person(offer.state, offer.version): waiting.append( KnowledgeSourceWorkerAttention( - namespace=src.namespace, name=src.name, status=state.status, reason=state.reason + namespace=offer.namespace, + name=offer.name, + status=offer.state.status, + reason=offer.state.reason, ) ) return False at = schedule.due_at( - state, version=src.version, interval=source_ops.assigned_interval(config), now=now + offer.state, + version=offer.version, + interval=source_ops.assigned_interval(offer.config), + now=now, ) if at > now: next_due = at if next_due is None else min(next_due, at) return False return True - for src in rows: - try: - config, items = decode_assigned_source(src) - except AssignedSourceRefused: - continue - if ( - config.paused - or config.reader not in input.readers - or config.profile_digest not in input.profile_digests - ): - continue - detail = domain.json_object((states.get(src.name) or {}).get("detail", "")) - found = _Due(src, config, items, schedule.turn_state(detail)) - if claimable(found): - due.append(found) + due = [ + offer + for offer in offers + if not offer.config.paused + and offer.config.reader in input.readers + and offer.config.profile_digest in input.profile_digests + and claimable(offer) + ] # The turn that ended longest ago first, so a busy source hides no other. - for found in sorted(due, key=lambda d: d.state.turn_ended_at): + for offer in sorted(due, key=lambda o: o.state.turn_ended_at): + key = (offer.namespace, offer.name) + found = rows.get(key) or await _row_of(input.org, subject, offer) + if found is None: + continue src = found.src claim = await _take(src) if not claim: @@ -252,7 +332,7 @@ def claimable(found: _Due) -> bool: async def _under_lease( - found: _Due, claim: str, claimable: Callable[[_Due], bool] + found: _Due, claim: str, claimable: Callable[[_Offer], bool] ) -> tuple[_Due, int] | None: """What the turn `claim` just took the lease of starts from: `found` with the sync state read under that lease, and how many copies the source holds; None when that @@ -264,7 +344,7 @@ async def _under_lease( fresh = found._replace( state=schedule.turn_state(domain.json_object(stored.get("detail", ""))) ) - if not claimable(fresh): + if not claimable(fresh.offer()): return None with sequential_reads(): # a replica behind the last turn's uploads return fresh, await store.count_assigned_copies(src.org, src.namespace, src.source_id) diff --git a/server/knowledge/domain/assigned_source.py b/server/knowledge/domain/assigned_source.py index 0b857878fd..0c44be6d80 100644 --- a/server/knowledge/domain/assigned_source.py +++ b/server/knowledge/domain/assigned_source.py @@ -2,11 +2,12 @@ registration of `knowledge.source.worker_assign`, kept in the source registry beside the sealed worker registration (`mcp_worker_source`). Pure: no I/O. -The row names who syncs (`worker_subject`, an agent's own subject), through which reader -(`reader`, a name the worker resolves) and which of the host's connections (`ref`, the -host's own id for it). It holds no endpoint, tool name or credential: the host's tool -channel adds those, and Loom never sees them. The copies live in the namespace itself, so -every reader of the namespace reads them. +The row names who syncs (`worker_subject`: an agent's own subject, or a service +account's that is no agent's), through which reader (`reader`, a name the worker +resolves) and which of the host's connections (`ref`, the host's own id for it). It +holds no endpoint, tool name or credential: the host's tool channel adds those, and Loom +never sees them. The copies live in the namespace itself, so every reader of the +namespace reads them. """ from __future__ import annotations @@ -130,6 +131,29 @@ def _checked_items(config: AssignedSourceConfig, raw: Any) -> tuple[AssignedItem return items +def _config(raw_config: dict[str, Any]) -> AssignedSourceConfig: + """The assignment a row's parsed `config_json` holds; a ValueError for anything else.""" + payload = raw_config.get(ASSIGNMENT) + if ( + set(raw_config) != {ASSIGNMENT} + or not isinstance(payload, str) + or len(payload.encode("utf-8")) > _MAX_CONFIG_BYTES + ): + raise AssignedSourceRefused("assigned source unavailable") + return AssignedSourceConfig.model_validate_json(payload) + + +def assigned_config(config_json: str) -> AssignedSourceConfig: + """The config of a stored assignment from its `config_json` column alone, for a read + that leaves the items out; AssignedSourceRefused for anything else. It says what the + registration asks for, never that the row is a current assignment: only + `decode_assigned_source` says that, from the whole row.""" + try: + return _config(json_object(config_json)) + except (ValueError, TypeError, AttributeError, RecursionError): + raise AssignedSourceRefused("assigned source unavailable") from None + + def decode_assigned_source( source: KnowledgeSource, ) -> tuple[AssignedSourceConfig, tuple[AssignedItem, ...]]: @@ -152,16 +176,12 @@ def decode_assigned_source( or source.crawl_generation or source.crawl_customer_id or source.crawl_credential_hash - or set(raw_config) != {ASSIGNMENT} ): raise AssignedSourceRefused("assigned source unavailable") try: if str(UUID(source.source_id)) != source.source_id or UUID(source.source_id).int == 0: raise AssignedSourceRefused("assigned source unavailable") - payload = raw_config[ASSIGNMENT] - if not isinstance(payload, str) or len(payload.encode("utf-8")) > _MAX_CONFIG_BYTES: - raise AssignedSourceRefused("assigned source unavailable") - config = AssignedSourceConfig.model_validate_json(payload) + config = _config(raw_config) items = _checked_items(config, tuple(stored_items(history.items_json))) if source.connection_id != config.ref: raise AssignedSourceRefused("assigned source unavailable") @@ -220,6 +240,7 @@ def encode_assigned_source( "AssignedItem", "AssignedSourceConfig", "AssignedSourceRefused", + "assigned_config", "assigned_prefix", "assigned_uri", "decode_assigned_source", diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index 5fe73da913..b60851e1d4 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -587,6 +587,19 @@ async def is_agent_home( return row is not None +async def trust_made(org: str, namespace: str, *, prefix: str, ch: _CHClient | None = None) -> bool: + """Whether the namespace's directory row, active or released, carries a tag that + starts with `prefix`: the mark a workload trust leaves on each agent's own + namespace (`auth.agents.tag`), which no caller can set.""" + row = await (ch or _default_client()).query_one( + "SELECT 1 AS x FROM loom.namespaces FINAL " + "WHERE org = {org:String} AND namespace = {ns:String} " + "AND arrayExists(t -> startsWith(t, {prefix:String}), tags) LIMIT 1", + params={"org": org, "ns": namespace, "prefix": prefix}, + ) + return row is not None + + async def lent_by(org: str, namespace: str, subject: str, *, ch: _CHClient | None = None) -> bool: """Whether the namespace holds a live grant `subject` made to another subject (`grants.share_agent` writes the lending agent as `granted_by`). The admin grant an @@ -628,6 +641,44 @@ async def assigned_to( return [_source(r) for r in rows] +# Sources one worker subject is offered across an org: a subject serves no more, and +# further sources take another subject. +SUBJECT_SOURCES_MAX = 2000 # not a setting: a bound on one statement + + +class SubjectSource(NamedTuple): + """An active source assigned to a worker subject as that subject's poll reads it: + its key, its row version and its registration, without its items.""" + + namespace: str + name: str + version: int + config_json: str + + +async def assigned_across( + org: str, subject: str, *, ch: _CHClient | None = None +) -> list[SubjectSource]: + """The org's active sources assigned to the worker subject `subject`, whichever + namespace holds them, by namespace and name, SUBJECT_SOURCES_MAX at most: the poll of + a subject with no namespace of its own. One read on the sorting key prefix `org` + that answers only rows naming `subject`, and never their items.""" + rows = await (ch or _default_client()).query_all( + f"SELECT namespace, name, version, config_json FROM {TABLE} FINAL " + "WHERE org = {org:String} AND active " + f"AND credential_mode = 'worker' AND access = '{NAMESPACE_ACCESS}' " + "AND worker_subject = {subject:String} AND worker_subject != '' " + f"ORDER BY namespace, name LIMIT {SUBJECT_SOURCES_MAX}", + params={"org": org, "subject": subject}, + ) + return [ + SubjectSource( + str(r["namespace"]), str(r["name"]), int(r["version"]), str(r["config_json"] or "") + ) + for r in rows + ] + + # Rows one scan of the assigned sources returns; the scan resumes past the last. ASSIGNED_PAGE_SIZE = 1000 # not a setting: a bound on one statement @@ -748,6 +799,30 @@ async def read_states( } +async def read_states_of( + org: str, sources: list[tuple[str, str]], *, ch: _CHClient | None = None +) -> dict[tuple[str, str], dict[str, str]]: + """{(namespace, name): {state_value, detail}} of the `(namespace, name)` sources of + `org` that have a sync state: one statement for sources that span namespaces, on + the sorting key `(org, namespace, state_key)`.""" + if not sources: + return {} + keys = {(namespace, state_key(name)): (namespace, name) for namespace, name in sources} + rows = await (ch or _default_client()).query_all( + f"SELECT namespace, state_key, state_value, detail FROM {STATE_TABLE} FINAL " + "WHERE org = {org:String} " + "AND (namespace, state_key) IN {keys:Array(Tuple(String, String))}", + params={"org": org, "keys": list(keys)}, + ) + return { + keys[(str(r["namespace"]), str(r["state_key"]))]: { + "state_value": str(r.get("state_value") or ""), + "detail": str(r.get("detail") or ""), + } + for r in rows + } + + # The org's sources shown to every reader of their namespace (`domain.served`) whose last # turn failed, newest failure first, each row with how many there are. The state of a # removed source stays, so the registry's active row is joined in; a mirror's own state @@ -1218,9 +1293,12 @@ async def count_assigned_copies( "DOCUMENTS_LIMIT", "DirectoryRow", "REVISIONS_PAGE", + "SUBJECT_SOURCES_MAX", + "SubjectSource", "TABLE", "active_count", "all_active_sources", + "assigned_across", "assigned_copies", "assigned_held", "assigned_sources_page", @@ -1243,9 +1321,11 @@ async def count_assigned_copies( "list_sources", "pending_delete_sources", "read_states", + "read_states_of", "source_documents", "source_revisions", "sources_in", + "trust_made", "uploaded_copies", "worker_history_exists", "worker_history_owners", diff --git a/tests/analyzer/cases/workers.py b/tests/analyzer/cases/workers.py index e9c0ead356..8e0d3772bb 100644 --- a/tests/analyzer/cases/workers.py +++ b/tests/analyzer/cases/workers.py @@ -466,6 +466,12 @@ async def _source_retirements(ch: RecordingCH, c: dict[str, Any]) -> None: # cursor. await sources.assigned_sources_page(("", "", ""), ch=ch) await sources.assigned_sources_page(("AB" * 32, NS, "decks"), ch=ch) + # A worker subject with no home of its own: the sources that name it in every + # namespace of its org, then the sync state of each in one read. + await sources.assigned_across(ORG, "sa:docs-sync", ch=ch) + await sources.read_states_of(ORG, [(NS, "decks"), ("team-ops", "runbooks")], ch=ch) + # Whether a namespace was made as an agent's home, by its directory tag. + await sources.trust_made(ORG, NS, prefix="machine:", ch=ch) # The copies behind a page of search hits, by their addresses. await sources.uploaded_copies(ORG, [(NS, f"source-doc:{item.source_id}:" + "a" * 64)], ch=ch) diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 6ab1d02024..046184ea7e 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -987,6 +987,7 @@ 675a57195847 SELECT memory_id, version, agent, user_id, session_id, memory_key, created_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory_key IN {keys:Array(String)} AND tom 6765755688ca SELECT kind, name, status, description, cardinality, created_by, updated_at FROM loom.namespace_ontology FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status = {status:String} ORDER B 679aaca08b74 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows +67aff120d5cd SELECT ? AS x FROM loom.namespaces FINAL WHERE org = {org:String} AND namespace = {ns:String} AND arrayExists(t -> startsWith(t, {prefix:String}), tags) LIMIT ? 67b04af64852 SELECT DISTINCT namespace FROM loom.documents WHERE org = {org:String} AND user_id = {uid:String} ORDER BY namespace 67b658495a69 SELECT count() AS n FROM loom.read_receipts WHERE org = {org:String} AND (namespace = {ns:String} AND ts < {verified_at:DateTime}) 67dfbb3578cb SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this @@ -1816,6 +1817,7 @@ b91605c34026 SELECT DISTINCT toString(memory_id) AS mid FROM loom.memory FINAL W b97612337078 SELECT count() AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} b97cf55bd0f6 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status != ? AND tombstoned_at IS NULL AND status != ? AND user_id = {uid:String} AND session_id = {s b98c5b9096ba SELECT count() AS n FROM loom.session_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL +b9ac3c50a3dd SELECT namespace, name, version, config_json FROM loom.knowledge_sources FINAL WHERE org = {org:String} AND active AND credential_mode = ? AND access = ? AND worker_subject = {subject:String} AND work b9bc47ece20e SELECT count() AS n FROM loom.entity_triple_rows WHERE org = {org:String} AND namespace = {ns:String} AND ? b9f6cfd45b7f SELECT count() AS n FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND thread_id = {tid:String} AND tombstoned_at IS NOT NULL ba2554cad547 SELECT source_uri, count() AS n FROM loom.chunks WHERE org = {org:String} AND namespace = {ns:String} AND source_uri IN {uris:Array(String)} AND doc_superseded_at IS NULL AND (org, namespace, embeddin @@ -2353,6 +2355,7 @@ ec567ce8ec8a SELECT count() AS n FROM loom.datasets WHERE org = {org:String} AND ec8349287ea0 SELECT sum(upstream_cost_usd) AS spent, countDistinct(namespace) AS ns_count FROM (SELECT ts, org, namespace, agent, user_id, session_id, run_id, operation, request_id, trace_id, memory_key, impersona ecad23572860 SELECT count() AS n FROM loom.entity_triple_rows WHERE org = {org:String} AND namespace = {ns:String} ecbcf4ca3679 SELECT ts, event_type, org, namespace, actor, subject, request_id, row_hash FROM loom.audit_log WHERE org = {org:String} AND namespace IN {ns_list:Array(String)} ORDER BY ts DESC, request_id DESC, row +ecc4ad5f336b SELECT namespace, state_key, state_value, detail FROM loom.code_index_state FINAL WHERE org = {org:String} AND (namespace, state_key) IN {keys:Array(Tuple(String, String))} ed30af4d157c SELECT term, df, avgdl FROM loom.code_term_df WHERE org = {org:String} AND namespace = {ns:String} AND term IN {terms:Array(String)} ed3dcc0014f8 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user ed4fa5b45c9d WITH (SELECT (toFloat64(count()), sumMap(arrayFilter(s -> has({stems:Array(String)}, s), arrayDistinct(arrayMap( t -> stem(t, ?), splitByChar(?, translate(lower(memory_key), ?, ?))))) AS ks, arrayResi diff --git a/tests/integration/test_cross_principal_leakage.py b/tests/integration/test_cross_principal_leakage.py index 775d3fe2ee..1e54dfb2ef 100644 --- a/tests/integration/test_cross_principal_leakage.py +++ b/tests/integration/test_cross_principal_leakage.py @@ -108,12 +108,13 @@ "knowledge.source.rotate", "knowledge.source.remove", "knowledge.source.sync_now", - # ADMIN on the worker subject's own namespace; its gate is driven as tenant B in - # test_a_viewer_of_another_namespace_sees_no_assigned_source. + # ADMIN on the namespace the source is assigned in; its gate is driven as tenant B + # in test_a_viewer_of_another_namespace_sees_no_assigned_source. "knowledge.source.worker_assign", # Writes: a claim is answered by assignment alone, a commit needs the writer role # and then the assignment; their gates are driven in - # tests/integration/test_source_worker_turn_ch.py. + # tests/integration/test_source_worker_turn_ch.py, and as tenant B in + # test_a_viewer_of_another_namespace_sees_no_service_workers_source_or_copy. "knowledge.source.worker.claim", "knowledge.source.worker.commit", "knowledge.source.worker.put", @@ -2955,6 +2956,134 @@ def test_a_viewer_of_another_namespace_sees_no_assigned_source( assert after.status_code == 200 and after.json()["managed_by"] == f"host-{nonce}" +def test_a_viewer_of_another_namespace_sees_no_service_workers_source_or_copy( + control_plane_url, seed, tokens, mint_test_token, worker_source_org +) -> None: + """A source a service account syncs into a shared namespace, and the copy its turn + uploaded, are shown to the readers of that namespace and to nobody else. Tenant B's + viewer, writer and admin and a principal of another org get the gate's refusal for + `list`, `inspect`, a search, a read and the turn's ops on namespace A, find nothing + of it in their own namespace, and are answered a claim as a subject with no source + is: the org-wide claim answers only rows that name the caller's own subject.""" + import hashlib + + worker_source_org(seed.org) + nonce = _canary() + service, name = f"sa:leak-sync-{nonce[-6:]}", f"s{nonce[-12:]}" + at = {"org": seed.org, "namespace": seed.ns_a} + named = {**at, "name": name} + host = mint_test_token( + org=seed.org, namespaces=[seed.ns_a], roles=["admin"], subject=f"host-{nonce}" + ) + made = _post( + control_plane_url, + host, + "knowledge.source.worker_assign", + { + **named, + "worker_subject": service, + "reader": "pages", + "ref": "docs-1", + "generation": 1, + "profile_digest": "ab" * 32, + "selection": "selected", + "items": [{"id": f"page-{nonce}"}], + }, + ) + assert made.status_code == 200, made.text[:300] + worker = mint_test_token( + org=seed.org, namespaces=[seed.ns_a], roles=["writer"], subject=service + ) + poll = {"org": seed.org, "readers": ["pages"], "profile_digests": ["ab" * 32]} + turn = _post(control_plane_url, worker, "knowledge.source.worker.claim", poll) + assert turn.status_code == 200 and turn.json()["status"] == "claimed", turn.text[:300] + mine = {**named, "claim": turn.json()["claim"]} + text = f"The {nonce} ledger is kept in the north vault." + put = _post( + control_plane_url, + worker, + "knowledge.source.worker.put", + { + **mine, + "document_id": f"page-{nonce}", + "revision": "r1", + "text_sha256": hashlib.sha256(text.encode()).hexdigest(), + "title": f"Ledger {nonce}", + "mime_type": "text/plain", + "payload": text, + }, + ) + assert put.status_code == 200 and put.json()["status"] == "stored", put.text[:300] + uri = put.json()["source_uri"] + done = _post( + control_plane_url, + worker, + "knowledge.source.worker.commit", + {**mine, "seq": 1, "done": True, "listing": "complete", "counts": {"listed": 1}}, + ) + assert done.status_code == 200, done.text[:300] + + # Positive control: a reader of the namespace is shown the source and finds the copy. + reader = mint_test_token(org=seed.org, namespaces=[seed.ns_a], roles=["viewer"], subject="rita") + search = {"query": f"{nonce} ledger north vault", "top_k": 5} + shown = _post(control_plane_url, reader, "knowledge.source.list", at) + assert shown.status_code == 200 and nonce in shown.text, shown.text[:300] + found = _post(control_plane_url, reader, "knowledge.search", {**at, **search}) + assert found.status_code == 200, found.text[:300] + assert uri in [h["source_uri"] for h in found.json()["results"]] + + secrets = (nonce, name, service, uri) + none = _post( + control_plane_url, + mint_test_token(org=seed.org, namespaces=[seed.ns_b], roles=["writer"], subject="sa:x"), + "knowledge.source.worker.claim", + poll, + ) + assert none.status_code == 200 and none.json()["status"] == "none", none.text[:300] + for who in ("b_viewer", "b_writer", "b_admin", "other_org"): + for op, body in ( + ("knowledge.source.list", at), + ("knowledge.source.inspect", named), + ("knowledge.search", {**at, **search}), + ("knowledge.get", {**at, "source_uri": uri}), + ("knowledge.source.worker.stored", mine), + ("knowledge.source.worker.commit", {**mine, "seq": 2}), + ): + r = _post(control_plane_url, tokens[who], op, body) + assert r.status_code == 403, f"{who} {op}: {r.status_code} {r.text[:200]}" + # The body echoes the namespace the caller named; nothing of the row. + assert not any(s in r.text for s in secrets), f"{who} {op}" + # A claim names no namespace: the caller's own subject names no source, and the + # answer is the one any subject with no source gets. + org = seed.org if who != "other_org" else f"{seed.org}-other" + r = _post( + control_plane_url, tokens[who], "knowledge.source.worker.claim", {**poll, "org": org} + ) + if who == "b_viewer": + assert r.status_code == 403, r.text[:200] # the op's role + else: + assert (r.status_code, r.json()) == (none.status_code, none.json()), who + assert not any(s in r.text for s in secrets), who + # Its own namespace lists and finds nothing of it. + if who != "other_org": + own = {"org": seed.org, "namespace": seed.ns_b} + for op, body in ( + ("knowledge.source.list", own), + ("knowledge.search", {**own, **search}), + ): + r = _post(control_plane_url, tokens[who], op, body) + assert r.status_code == 200, f"{who} {op}: {r.text[:200]}" + assert not any(s in r.text for s in secrets), f"{who} {op}" + # A writer of namespace A who is not the worker subject is offered nothing either: + # the assignment is the grant, never the role. + r = _post(control_plane_url, tokens["a_writer"], "knowledge.source.worker.claim", poll) + assert (r.status_code, r.json()) == (none.status_code, none.json()) + # The source and its copy are as they were. + after = _post(control_plane_url, reader, "knowledge.source.inspect", named) + assert after.status_code == 200 and after.json()["managed_by"] == f"host-{nonce}" + assert after.json()["sync"]["status"] == "ok" + + def test_a_draft_skill_is_read_only_by_the_writers_of_its_namespace( control_plane_url, mint_test_token ) -> None: diff --git a/tests/integration/test_source_worker_turn_ch.py b/tests/integration/test_source_worker_turn_ch.py index a73a6a7991..4cce29377d 100644 --- a/tests/integration/test_source_worker_turn_ch.py +++ b/tests/integration/test_source_worker_turn_ch.py @@ -481,6 +481,135 @@ def test_an_uploaded_document_is_found_by_search_and_read_by_get( assert _claimed(control_plane_url, worker, org)["source"]["remaining_documents"] == 1997 +def test_a_reader_of_the_shared_namespace_finds_a_service_workers_copy( + control_plane_url: str, mint_test_token: Any, ch_client: Any, worker_source_org: Any +) -> None: + """Fails when a service account that is no agent's is not offered its sources in two + shared namespaces, is offered another subject's, or is accepted in an agent's own + namespace; when a reader of the shared namespace does not find the copy, or a + reader of the other one does; or when the copy outlives the source's removal.""" + service, other, docs, ops = "sa:docs-sync", "sa:wiki-sync", "team-docs", "team-ops" + org = worker_source_org(unique_org("worker-service")) + # A registered shared namespace with a tag of its own, one with no directory row, + # and an agent's home as its trust leaves it. + ch_client.insert( + "loom.namespaces", + [[org, docs, "lead@example.com", ["team"]], [org, HOME, WORKER, ["machine:fleet"]]], + column_names=["org", "namespace", "owner_email", "tags"], + ) + host = mint_test_token(org=org, namespaces=[docs, ops, HOME], roles=["admin"], subject=HOST) + op = "knowledge.source.worker_assign" + + def assignment(namespace: str, name: str, subject: str) -> dict[str, Any]: + return { + "org": org, + "namespace": namespace, + "name": name, + "worker_subject": subject, + "reader": "pages", + "ref": "docs-1", + "generation": 1, + "profile_digest": DIGEST, + "selection": "listed", + "items": [{"id": "space-1"}], + } + + # Neither kind of subject is accepted in the other's place. + for refused in (assignment(HOME, "guide", service), assignment(docs, "guide", WORKER)): + answer = _post(control_plane_url, host, op, refused) + assert answer.status_code == 422, answer.text[:300] + assert answer.json()["detail"]["code"] == "SOURCE_WORKER_NAMESPACE" + for namespace, name, subject in ( + (docs, "guide", service), + (ops, "manual", service), + (docs, "theirs", other), + ): + made = _post(control_plane_url, host, op, assignment(namespace, name, subject)) + assert made.status_code == 200 and made.json()["created"], made.text[:300] + + worker = mint_test_token(org=org, namespaces=[docs, ops], roles=["writer"], subject=service) + poll = {"org": org, **POLL} + text = "# Harbour rules\n\nThe quillfen lock is closed to barges after the dusk bell." + stored: dict[str, str] = {} + for _ in range(2): + turn = _post(control_plane_url, worker, "knowledge.source.worker.claim", poll).json() + assert turn["status"] == "claimed", turn + source = turn["source"] + mine = { + "org": org, + "namespace": source["namespace"], + "name": source["name"], + "claim": turn["claim"], + } + put = _post( + control_plane_url, + worker, + "knowledge.source.worker.put", + {**mine, **_upload("page-1", text, title="Harbour rules")}, + ) + assert put.status_code == 200 and put.json()["status"] == "stored", put.text[:300] + stored[f"{source['namespace']}/{source['name']}"] = put.json()["source_uri"] + done = _post( + control_plane_url, + worker, + "knowledge.source.worker.commit", + {**mine, "seq": 1, "done": True, "listing": "complete", "counts": {"listed": 1}}, + ) + assert done.status_code == 200, done.text[:300] + # Both of its sources, one in each namespace, and never the other subject's. + assert sorted(stored) == [f"{docs}/guide", f"{ops}/manual"] + waits = _post(control_plane_url, worker, "knowledge.source.worker.claim", poll).json() + assert (waits["status"], waits["attention"]) == ("none", []) + # The other subject is offered its own source, and an agent's token nothing here. + theirs = _post( + control_plane_url, + mint_test_token(org=org, namespaces=[docs], roles=["writer"], subject=other), + "knowledge.source.worker.claim", + poll, + ).json() + assert (theirs["source"]["namespace"], theirs["source"]["name"]) == (docs, "theirs") + agent = mint_test_token(org=org, namespaces=[HOME, docs], roles=["writer"], subject=WORKER) + assert ( + _post(control_plane_url, agent, "knowledge.source.worker.claim", poll).json()["status"] + == "none" + ) + + # A reader of the shared namespace finds the copy and is shown who syncs the source. + reader = mint_test_token(org=org, namespaces=[docs], roles=["viewer"], subject="vera") + query = {"org": org, "query": "quillfen lock dusk bell", "top_k": 5} + found = _post(control_plane_url, reader, "knowledge.search", {**query, "namespace": docs}) + assert found.status_code == 200, found.text[:300] + (hit,) = [h for h in found.json()["results"] if h["source_uri"] == stored[f"{docs}/guide"]] + assert (hit["synced_from"]["name"], hit["synced_from"]["uploaded_by"]) == ("guide", service) + listed = _post( + control_plane_url, reader, "knowledge.source.list", {"org": org, "namespace": docs} + ).json()["sources"] + shown = {row["name"]: (row["worker_subject"], row["managed_by"]) for row in listed} + assert shown == {"guide": (service, HOST), "theirs": (other, HOST)} + # A reader of the other namespace reads that namespace's copy and not this one. + elsewhere = _post(control_plane_url, reader, "knowledge.search", {**query, "namespace": ops}) + assert elsewhere.status_code == 403, elsewhere.text[:300] + + # The subject that assigned it removes it, and its copy goes with it. + removed = _post( + control_plane_url, + host, + "knowledge.source.remove", + {"org": org, "namespace": docs, "name": "guide", "confirm": "guide"}, + ) + assert removed.status_code == 200 and removed.json()["documents_pending"] == 0, removed.text + after = _post(control_plane_url, reader, "knowledge.search", {**query, "namespace": docs}) + assert after.status_code == 200, after.text[:300] + assert stored[f"{docs}/guide"] not in [h["source_uri"] for h in after.json()["results"]] + left = _post( + control_plane_url, + mint_test_token(org=org, namespaces=[ops], roles=["viewer"], subject="otto"), + "knowledge.search", + {**query, "namespace": ops}, + ) + assert stored[f"{ops}/manual"] in [h["source_uri"] for h in left.json()["results"]] + + def _hit(base: str, token: str, org: str, query: str, uri: str) -> dict[str, Any]: """The hit of the document at `uri` in a member's search of the namespace.""" found = _post( diff --git a/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index 8fe14e3ac5..882c7a246e 100644 --- a/tests/unit/snapshots/cli_help.json +++ b/tests/unit/snapshots/cli_help.json @@ -137,7 +137,7 @@ ], "loom knowledge source": [ "usage: loom knowledge source [-h] {list,add,update,assign,remove,worker-profiles,worker-approve,worker-accounts,worker-enroll,worker-preview,worker-register,worker-link,worker-unlink} ...", - "positional arguments: {list,add,update,assign,remove,worker-profiles,worker-approve,worker-accounts,worker-enroll,worker-preview,worker-register,worker-link,worker-unlink} list List the namespace's sources, items and sync state. add Register a source from links or items, probed with the credential before anything is stored; a source added with a credential file is read by every reader of the namespace (knowledge.source.add). update Add and remove a source's items or change its file kinds, the added items probed with the stored credential (knowledge.source.update). assign Assign a source to a worker subject, or change that assignment; the namespace is that subject's own, and every reader of it reads the copies (knowledge.source.worker_assign, experimental). remove Retire a source: its row goes inactive and its credential is cleared. The copies of a mirrored source and of one assigned to a worker subject always go; for an assigned source the answer's documents_pending counts those still live (knowledge.source.remove). worker-profiles List the provisioned source worker profiles and the collection's approval of each (knowledge.source.worker_profiles; experimental, answered denied until the CLI declares session protection). worker-approve Set or revoke the collection's approval of one worker profile (knowledge.source.worker_approve; experimental, answered denied until the CLI declares session protection). worker-accounts List the worker profiles the collection approves, with your own account on each (knowledge.source.worker_accounts; experimental, answered denied until the CLI declares session protection). worker-enroll Link your own worker account to an approved profile (knowledge.source.worker_enroll; experimental, answered denied until the CLI declares session protection). worker-preview Check a worker source's selection through your linked account; nothing is written (knowledge.source.worker_preview; experimental, answered denied until the CLI declares session protection). worker-register Register the worker source a preview showed (knowledge.source.worker_register; experimental, answered denied until the CLI declares session protection). worker-link Link your own enrolled worker account to a team worker source, to read it live (knowledge.source.worker_link; experimental, answered denied until the CLI declares session protection). worker-unlink Unlink your own worker account from a worker source, or, as an administrator, a reader's (knowledge.source.worker_unlink; experimental, answered denied until the CLI declares session protection).", + "positional arguments: {list,add,update,assign,remove,worker-profiles,worker-approve,worker-accounts,worker-enroll,worker-preview,worker-register,worker-link,worker-unlink} list List the namespace's sources, items and sync state. add Register a source from links or items, probed with the credential before anything is stored; a source added with a credential file is read by every reader of the namespace (knowledge.source.add). update Add and remove a source's items or change its file kinds, the added items probed with the stored credential (knowledge.source.update). assign Assign a source to a worker subject, or change that assignment; the namespace is an agent's own for that agent's subject and a shared one for any other, and every reader of it reads the copies (knowledge.source.worker_assign, experimental). remove Retire a source: its row goes inactive and its credential is cleared. The copies of a mirrored source and of one assigned to a worker subject always go; for an assigned source the answer's documents_pending counts those still live (knowledge.source.remove). worker-profiles List the provisioned source worker profiles and the collection's approval of each (knowledge.source.worker_profiles; experimental, answered denied until the CLI declares session protection). worker-approve Set or revoke the collection's approval of one worker profile (knowledge.source.worker_approve; experimental, answered denied until the CLI declares session protection). worker-accounts List the worker profiles the collection approves, with your own account on each (knowledge.source.worker_accounts; experimental, answered denied until the CLI declares session protection). worker-enroll Link your own worker account to an approved profile (knowledge.source.worker_enroll; experimental, answered denied until the CLI declares session protection). worker-preview Check a worker source's selection through your linked account; nothing is written (knowledge.source.worker_preview; experimental, answered denied until the CLI declares session protection). worker-register Register the worker source a preview showed (knowledge.source.worker_register; experimental, answered denied until the CLI declares session protection). worker-link Link your own enrolled worker account to a team worker source, to read it live (knowledge.source.worker_link; experimental, answered denied until the CLI declares session protection). worker-unlink Unlink your own worker account from a worker source, or, as an administrator, a reader's (knowledge.source.worker_unlink; experimental, answered denied until the CLI declares session protection).", "options: -h, --help show this help message and exit" ], "loom knowledge source list": [ @@ -154,7 +154,7 @@ ], "loom knowledge source assign": [ "usage: loom knowledge source assign [-h] --namespace NAMESPACE [--org ORG] [--server-url SERVER_URL] [--token TOKEN] --name NAME --worker-subject WORKER_SUBJECT --reader READER --ref REF --generation GENERATION --profile-digest PROFILE_DIGEST --selection {selected,listed} --item ITEM [--changed-since] [--max-documents MAX_DOCUMENTS] [--paused]", - "options: -h, --help show this help message and exit --namespace NAMESPACE The worker subject's own namespace --org ORG Default: the token's org --server-url SERVER_URL Server URL (default: $LOOM_BASE_URL, ~/.loom/config.json url, http://localhost:7777) --token TOKEN JWT (default: $LOOM_API_KEY, ~/.loom/token) --name NAME The source's name in the namespace --worker-subject WORKER_SUBJECT The agent's subject, sa:: --reader READER The reader the worker runs --ref REF The host's id of the connection --generation GENERATION The connection's generation, from 1 --profile-digest PROFILE_DIGEST The approved reader profile's SHA-256 --selection {selected,listed} selected: each --item is a document; listed: the one --item is a container --item ITEM An id to read; repeatable --changed-since listed: ask the container only for what changed since the last pass --max-documents MAX_DOCUMENTS The documents kept, at most; default 2000 --paused Keep the assignment and stop its sync" + "options: -h, --help show this help message and exit --namespace NAMESPACE The namespace the copies live in --org ORG Default: the token's org --server-url SERVER_URL Server URL (default: $LOOM_BASE_URL, ~/.loom/config.json url, http://localhost:7777) --token TOKEN JWT (default: $LOOM_API_KEY, ~/.loom/token) --name NAME The source's name in the namespace --worker-subject WORKER_SUBJECT The subject whose token syncs the source: an agent's, sa::, or a service account's --reader READER The reader the worker runs --ref REF The host's id of the connection --generation GENERATION The connection's generation, from 1 --profile-digest PROFILE_DIGEST The approved reader profile's SHA-256 --selection {selected,listed} selected: each --item is a document; listed: the one --item is a container --item ITEM An id to read; repeatable --changed-since listed: ask the container only for what changed since the last pass --max-documents MAX_DOCUMENTS The documents kept, at most; default 2000 --paused Keep the assignment and stop its sync" ], "loom knowledge source remove": [ "usage: loom knowledge source remove [-h] --namespace NAMESPACE [--org ORG] [--server-url SERVER_URL] [--token TOKEN] --name NAME --confirm CONFIRM [--delete-documents]", diff --git a/tests/unit/snapshots/cli_tree.json b/tests/unit/snapshots/cli_tree.json index 4371fc4b76..d47691f988 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -4508,7 +4508,7 @@ "nargs": null, "type": null, "required": true, - "help": "The worker subject's own namespace", + "help": "The namespace the copies live in", "metavar": null }, { @@ -4583,7 +4583,7 @@ "nargs": null, "type": null, "required": true, - "help": "The agent's subject, sa::", + "help": "The subject whose token syncs the source: an agent's, sa::, or a service account's", "metavar": null }, { @@ -6357,7 +6357,7 @@ }, { "dest": "assign", - "help": "Assign a source to a worker subject, or change that assignment; the namespace is that subject's own, and every reader of it reads the copies (knowledge.source.worker_assign, experimental).", + "help": "Assign a source to a worker subject, or change that assignment; the namespace is an agent's own for that agent's subject and a shared one for any other, and every reader of it reads the copies (knowledge.source.worker_assign, experimental).", "metavar": "assign" }, { diff --git a/tests/unit/test_assigned_source.py b/tests/unit/test_assigned_source.py index 54ebb869e7..461feb526c 100644 --- a/tests/unit/test_assigned_source.py +++ b/tests/unit/test_assigned_source.py @@ -65,6 +65,9 @@ WORKER = "sa:fleet:scout" HOME = "fleet-scout" HOST = "sa:host-control" +# A service account that is no agent's, and a namespace no trust made. +SERVICE = "sa:docs-sync" +SHARED = "team-docs" DIGEST = "ab" * 32 _MIGRATIONS = Path(__file__).resolve().parents[2] / "schemas" / "migrations" @@ -159,6 +162,9 @@ async def count_assigned_copies(self, org: str, namespace: str, source_id: str) async def is_agent_home(self, org: str, namespace: str, *, tag: str, agent: str) -> bool: return (namespace, tag, agent) in self.homes + async def trust_made(self, org: str, namespace: str, *, prefix: str) -> bool: + return any(home == namespace and tag.startswith(prefix) for home, tag, _ in self.homes) + async def lent_by(self, org: str, namespace: str, subject: str) -> bool: return (namespace, subject) in self.lent @@ -383,13 +389,12 @@ def test_a_worker_subject_cannot_assign_itself(registry: _Registry) -> None: [ ("team-docs", WORKER), # a shared namespace ("fleet-other", WORKER), # another agent's home - ("fleet-scout", "sa:fleet"), # a trust's own subject, no agent - ("fleet-scout", "pat@example.com"), # a person ("fleet-scout", "sa:fleet:other"), # an agent, but not this namespace's ("fleet-scout", ""), # no subject + ("team-docs", " "), # a blank one ], ) -def test_an_assigned_source_lives_only_in_its_subjects_home( +def test_an_agents_source_lives_only_in_its_own_home( registry: _Registry, namespace: str, worker: str ) -> None: refused = _refusal(namespace=namespace, worker_subject=worker) @@ -398,6 +403,52 @@ def test_an_assigned_source_lives_only_in_its_subjects_home( assert registry.written == [] and registry.leases == [] +def test_a_service_subject_is_assigned_only_outside_agent_homes(registry: _Registry) -> None: + """Fails when a subject that is no agent's is accepted in an agent's namespace, or an + agent's subject in a shared one.""" + # A trust's own subject, a service account and a person: none is an agent's subject, + # and the namespace is the one a trust made for its agent. + for subject in ("sa:fleet", SERVICE, "pat@example.com"): + assert _refusal(worker_subject=subject) == (422, "SOURCE_WORKER_NAMESPACE"), subject + # The directory row says whose the namespace is, read under the lease the row would + # be written under; an agent's subject is refused by its name alone. + assert registry.leases == [HOME] * 3 + assert _refusal(namespace=SHARED) == (422, "SOURCE_WORKER_NAMESPACE") + # A namespace a trust made and released keeps the trust's tag. + registry.homes.add(("fleet-retired", agents.tag("fleet"), "sa:fleet:retired")) + refused = _refusal(namespace="fleet-retired", worker_subject=SERVICE) + assert refused == (422, "SOURCE_WORKER_NAMESPACE") + # A person's own place takes no source, as for `knowledge.source.add`. + refused = _refusal(namespace="personal-pat", worker_subject=SERVICE) + assert refused == (422, "PERSONAL_NAMESPACE") + assert registry.written == [] + + made = _assign(namespace=SHARED, worker_subject=SERVICE) + assert (made.created, made.changed) == (True, True) + (row,) = registry.written + assert (row.namespace, row.worker_subject, row.access) == (SHARED, SERVICE, "namespace") + assert (row.owner_subject, row.registrant_subject) == ("", HOST) + assert domain.is_assigned(row) + # The service subject cannot assign itself either. + assert _refusal(SERVICE, namespace=SHARED, worker_subject=SERVICE) == ( + 403, + "SOURCE_WORKER_SELF_ASSIGNED", + ) + + +def test_a_shared_namespace_takes_a_service_subjects_source_whoever_holds_grants( + registry: _Registry, +) -> None: + """Fails when the share rule of an agent's own namespace refuses a shared one, whose + readers are the audience by design.""" + registry.lent.add((SHARED, SERVICE)) + assert _assign(namespace=SHARED, worker_subject=SERVICE).created is True + # The subject string does not prove its kind: a person named as worker subject is + # stored, and no token of that person is ever answered a turn. + registry.rows.clear() + assert _assign(namespace=SHARED, worker_subject="pat@example.com").created is True + + def test_a_namespace_another_trust_made_is_not_the_subjects_home(registry: _Registry) -> None: # The name matches, but the directory row is not the one the agent's trust wrote # (inactive, another trust's tag or another owner). diff --git a/tests/unit/test_source_worker_ops.py b/tests/unit/test_source_worker_ops.py index 273cafd14e..039080d160 100644 --- a/tests/unit/test_source_worker_ops.py +++ b/tests/unit/test_source_worker_ops.py @@ -59,7 +59,8 @@ from server.knowledge.store import chunks as knowledge_repo from server.knowledge.store import documents as documents_repo from server.knowledge.store import source_retirements as retirement_queue -from server.knowledge.store.sources import TurnHolder +from server.knowledge.store import sources as source_store +from server.knowledge.store.sources import SUBJECT_SOURCES_MAX, SubjectSource, TurnHolder from server.memory.domain import trust from server.observability.budget_shape import current_budget_shape from server.operations.registry import OPERATIONS_BY_NAME @@ -70,6 +71,10 @@ WORKER = "sa:fleet:scout" HOME = "fleet-scout" HOST = "sa:host-control" +# A service account that is no agent's, and two namespaces no trust made. +SERVICE = "sa:docs-sync" +DOCS = "team-docs" +OPS = "team-ops" DIGEST = "ab" * 32 START = datetime(2026, 3, 1, 12, 0, tzinfo=UTC) BOUND = 600 @@ -88,13 +93,24 @@ def __init__(self) -> None: self.retiring: set[str] = set() # The retirement entries a commit queued, each with its `pending`. self.queued: list[tuple[Any, bool]] = [] + # Each read of the registry (org, namespace or '' for the whole org, subject), + # and the sources each cross-namespace state read named. self.reads: list[tuple[str, str, str]] = [] + self.state_reads: list[list[tuple[str, str]]] = [] # The buckets a poll draws, refilled by the same clock. self.limiter = Limiter(clock=lambda: (self.now - START).total_seconds()) self._version = 100 - def assign(self, name: str = "notes", **changes: Any) -> KnowledgeSource: - """Write the assignment `name`, as `worker_assign` would: a new row version.""" + def assign( + self, + name: str = "notes", + *, + namespace: str = HOME, + worker_subject: str = WORKER, + **changes: Any, + ) -> KnowledgeSource: + """Write the assignment `name`, as `worker_assign` would: a new row version. The + rows are kept by name, so a test names each source once across namespaces.""" fields: dict[str, Any] = { "version": 1, "reader": "pages", @@ -109,10 +125,10 @@ def assign(self, name: str = "notes", **changes: Any) -> KnowledgeSource: items = changes.pop("items", (AssignedItem(id="page-1"), AssignedItem(id="page-2"))) row = encode_assigned_source( org=ORG, - namespace=HOME, + namespace=namespace, name=name, source_id=f"11111111-2222-4333-8444-{len(name):012d}", - worker_subject=WORKER, + worker_subject=worker_subject, registrant=HOST, config=AssignedSourceConfig(**{**fields, **changes}), items=items, @@ -144,6 +160,24 @@ async def assigned_to( ] return sorted(found, key=lambda row: row.name)[:limit] + async def assigned_across(self, org: str, subject: str) -> list[SubjectSource]: + self.reads.append((org, "", subject)) + found = [ + row + for row in self.rows.values() + if (row.org, row.worker_subject) == (org, subject) and row.active + ] + return [ + SubjectSource(row.namespace, row.name, row.version, row.worker_history.config_json) + for row in sorted(found, key=lambda row: (row.namespace, row.name)) + ][:SUBJECT_SOURCES_MAX] + + async def read_states_of( + self, org: str, sources: list[tuple[str, str]] + ) -> dict[tuple[str, str], Any]: + self.state_reads.append(sources) + return {key: self.states[key[1]] for key in sources if key[1] in self.states} + async def get_source(self, org: str, namespace: str, name: str) -> KnowledgeSource | None: row = self.rows.get(name) return row if row and (row.org, row.namespace) == (org, namespace) and row.active else None @@ -310,6 +344,155 @@ def test_another_subject_sees_no_source(world: _World) -> None: assert world.state_writes == writes and world.detail()["checkpoint"] == "" +def _service(subject: str = SERVICE, **fields: Any) -> Any: + """A service account that is no agent's, a writer of the two shared namespaces.""" + return principal("writer", subject=subject, namespaces=(DOCS, OPS), **fields) + + +def test_a_service_worker_claims_across_namespaces(world: _World) -> None: + """Fails when a source in a second namespace is never claimed, another subject's + source is, an agent's token claims outside its home, or a subject that is no + agent's is offered a source by a namespace's key range.""" + world.assign("guide", namespace=DOCS, worker_subject=SERVICE) + world.assign("manual", namespace=OPS, worker_subject=SERVICE) + world.assign("theirs", namespace=DOCS, worker_subject="sa:wiki-sync") + world.assign("notes") # the agent's own, in its home + # A row that names the agent outside its home: the op never writes one. + world.assign("stray", namespace=DOCS) + world.states["manual"] = { + "state_value": "", + "detail": json.dumps({"turn_ended_at": "2026-02-27T09:00:00+00:00"}), + } + world.states["guide"] = { + "state_value": "", + "detail": json.dumps({"turn_ended_at": "2026-02-28T09:00:00+00:00"}), + } + + first, second = _claim(_service()), _claim(_service()) + # The turn that ended longest ago first, whichever namespace holds it. + assert [(t.source.namespace, t.source.name) for t in (first, second)] == [ + (OPS, "manual"), + (DOCS, "guide"), + ] + assert [item.id for item in first.source.items] == ["page-1", "page-2"] + assert (first.source.reader, first.source.remaining_documents) == ("pages", 2000) + assert _claim(_service()).status == "none" + # Each poll read the org once by the caller's subject, and no namespace's range. + assert world.reads == [(ORG, "", SERVICE)] * 3 + # The turn is the service worker's: its commit lands, and nobody else's does. + at = {"namespace": OPS, "name": "manual"} + assert _commit(first.claim, auth=_service(), **at).status == "ok" + for stranger in (_worker(), _service("sa:wiki-sync")): + with pytest.raises(LoomServerError) as refused: + _commit(first.claim, 2, auth=stranger, **at) + assert refused.value.to_detail()["code"] == "CLAIM_LOST" + assert _done(first.claim, 2, auth=_service(), **at).next_due_s == INTERVAL + + # The agent reads its home and is offered its own source there, never the stray row. + world.reads.clear() + assert _claim().source.name == "notes" + assert _claim().status == "none" + assert world.reads == [(ORG, HOME, WORKER)] * 2 + # Another service subject is offered its own source and nothing else. + theirs = _claim(_service("sa:wiki-sync")) + assert (theirs.source.namespace, theirs.source.name) == (DOCS, "theirs") + assert _claim(_service("sa:wiki-sync")).status == "none" + + +def test_a_source_rewritten_since_the_poll_read_it_starts_no_turn( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """Fails when a turn starts on the registration the org-wide read answered although + the row was changed, handed to another subject or removed before its turn lease.""" + row = world.assign("guide", namespace=DOCS, worker_subject=SERVICE) + read = world.assigned_across + + def then(change: Any) -> None: + async def stale(org: str, subject: str) -> list[SubjectSource]: + found = await read(org, subject) + change() + return found + + monkeypatch.setattr(world, "assigned_across", stale) + + then(lambda: world.assign("guide", namespace=DOCS, worker_subject=SERVICE, generation=2)) + assert _claim(_service()).status == "none" and world.leases == {} + then(lambda: world.assign("guide", namespace=DOCS, worker_subject="sa:wiki-sync")) + assert _claim(_service()).status == "none" and world.leases == {} + then(lambda: world.rows.update(guide=dataclasses.replace(world.rows["guide"], active=False))) + assert _claim(_service()).status == "none" and world.leases == {} + # The sentinel: the row as the read answered it starts its turn. + world.write(row) + monkeypatch.setattr(world, "assigned_across", read) + assert _claim(_service()).source.name == "guide" + + +def test_a_person_named_as_worker_subject_claims_nothing(world: _World) -> None: + """Fails when a token that is not a service account's own is answered a turn of a + source that names its subject, or can commit to one.""" + pat = "pat@example.com" + world.assign("guide", namespace=DOCS, worker_subject=pat) + person = principal("admin", subject=pat, namespaces=(DOCS,), service_account=False) + answer = _claim(person) + assert (answer.status, answer.claim, answer.source) == ("none", "", None) + # The answer is the one a subject with no source gets, and nothing was read for it. + assert answer == _claim(_service("sa:nobody")) + assert world.reads == [(ORG, "", "sa:nobody")] and world.leases == {} + # A service account of the same name is the worker subject the row names. + claim = _claim(_service(pat)).claim + assert claim + writes = world.state_writes + with pytest.raises(LoomServerError) as refused: + _commit(claim, auth=person, namespace=DOCS, name="guide") + assert refused.value.to_detail()["code"] == "CLAIM_LOST" + assert world.state_writes == writes + + +class _Statements: + """A client that records each statement and answers no row.""" + + def __init__(self) -> None: + self.sent: list[tuple[str, dict[str, Any]]] = [] + + async def query_all(self, sql: str, params: dict[str, Any] | None = None) -> list[Any]: + self.sent.append((sql, params or {})) + return [] + + +def test_the_org_wide_claim_is_one_statement_and_one_state_read(world: _World) -> None: + """Fails when the poll of a subject with no namespace of its own reads a namespace + at a time, reads a source's items, or is not bound to the caller's subject.""" + names = [f"s{n:02d}" for n in range(12)] + for n, name in enumerate(names): + world.assign(name, namespace=f"team-{n % 4}", worker_subject=SERVICE, paused=True) + assert _claim(_service()).status == "none" + # Twelve sources in four namespaces: one registry read and one state read. + assert world.reads == [(ORG, "", SERVICE)] + assert [sorted(name for _ns, name in asked) for asked in world.state_reads] == [names] + + # The statements themselves: each is one read on the org's key prefix. + ch = _Statements() + asyncio.run(source_store.assigned_across(ORG, SERVICE, ch=ch)) + asyncio.run(source_store.read_states_of(ORG, [(DOCS, "guide"), (OPS, "manual")], ch=ch)) + (registry, bound), (states, keys) = ch.sent + assert " FROM loom.knowledge_sources FINAL WHERE org = {org:String} AND active " in registry + assert "worker_subject = {subject:String} AND worker_subject != ''" in registry + assert registry.endswith(f"ORDER BY namespace, name LIMIT {SUBJECT_SOURCES_MAX}") + assert bound == {"org": ORG, "subject": SERVICE} and SUBJECT_SOURCES_MAX == 2000 + # Narrow: the key, the version and the registration, never the items or a credential. + selected = registry.split(" FROM ")[0].removeprefix("SELECT ").split(", ") + assert selected == ["namespace", "name", "version", "config_json"] + assert " FROM loom.code_index_state FINAL WHERE org = {org:String} " in states + assert "(namespace, state_key) IN {keys:Array(Tuple(String, String))}" in states + assert keys == { + "org": ORG, + "keys": [(DOCS, "knowledge_source:guide"), (OPS, "knowledge_source:manual")], + } + # No source, no state read. + asyncio.run(source_store.read_states_of(ORG, [], ch=ch)) + assert len(ch.sent) == 2 + + def test_an_empty_worker_subject_claims_nothing(world: _World) -> None: """Fails when a row whose `worker_subject` a build without the column emptied is offered to a caller with no subject, or takes that caller's commit.""" @@ -1072,8 +1255,17 @@ def test_a_poll_past_the_burst_is_refused(world: _World, monkeypatch: pytest.Mon # A caller that is no worker subject reads nothing and draws nothing: no bucket is # made for it, and each one holds the tokens it held. held = _tokens(limiter) - assert _claim(principal("writer", subject="wes", namespaces=(HOME,))).status == "none" + person = principal("writer", subject="wes", namespaces=(HOME,), service_account=False) + assert _claim(person).status == "none" assert len(world.reads) == 20 and _tokens(limiter) == held + # A subject with no namespace of its own draws a slot of its own, which no namespace + # is named, and the org's bucket: the agent's empty bucket does not refuse it. + assert _claim(_service()).status == "none" + drawn = {key: tokens for key, tokens in _tokens(limiter).items() if key not in held} + assert [ + (key[0], f"source-worker:{SERVICE}" in key, tokens) for key, tokens in drawn.items() + ] == [("namespace", True, 19.0)] + assert world.reads[20:] == [(ORG, "", SERVICE)] # The bucket refills at two polls a second. world.tick(1) assert [_claim().status, _claim().status] == ["none", "none"] From ebb97c09fff6f1240bd4e30495f9d459d0ca36e5 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sun, 6 Dec 2026 09:59:39 +0000 Subject: [PATCH 2/7] A service account's source in a namespace claimed at sign-up answers PERSONAL_NAMESPACE An agent claim's mark, machine:agent-signup:claimed, starts as a workload trust's tag does and names no trust. trust_made matched it, so knowledge.source.worker_assign answered SOURCE_WORKER_NAMESPACE with "is an agent's own namespace; only that agent's subject syncs a source there" for a namespace no agent's subject can be assigned in. The statement leaves the claim's mark out, and the namespace reaches the shared-source check, which refuses a person's own place as knowledge.source.add does. Both answers are 422. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- server/knowledge/app/assigned_sources.py | 8 +++- server/knowledge/store/sources.py | 14 ++++--- tests/analyzer/cases/workers.py | 4 +- tests/analyzer/shapes.txt | 2 +- tests/integration/test_assigned_source_ch.py | 41 ++++++++++++++++++++ tests/unit/test_assigned_source.py | 18 +++++++-- 6 files changed, 74 insertions(+), 13 deletions(-) diff --git a/server/knowledge/app/assigned_sources.py b/server/knowledge/app/assigned_sources.py index 91bc86373a..761c39f625 100644 --- a/server/knowledge/app/assigned_sources.py +++ b/server/knowledge/app/assigned_sources.py @@ -25,7 +25,7 @@ import pydantic -from server.auth import agents, machines +from server.auth import agents, claim_codes, machines from server.auth.context import current_caller from server.core import ch from server.core.ch import sequential_reads @@ -135,7 +135,11 @@ async def _require_place(org: str, namespace: str, worker_subject: str, trust: s "is assigned once it has taken its shares back" ) return - if await store.trust_made(org, namespace, prefix=agents.TAG_PREFIX): + # A namespace claimed at sign-up carries the claim's mark, not a trust's: it is a + # person's own place, which the shared-source check refuses. + if await store.trust_made( + org, namespace, prefix=agents.TAG_PREFIX, claim_tag=claim_codes.CLAIMED_TAG + ): raise ValidationError( f"{namespace!r} is an agent's own namespace; only that agent's subject syncs " "a source there", diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index b60851e1d4..fad7f12e9c 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -587,15 +587,19 @@ async def is_agent_home( return row is not None -async def trust_made(org: str, namespace: str, *, prefix: str, ch: _CHClient | None = None) -> bool: +async def trust_made( + org: str, namespace: str, *, prefix: str, claim_tag: str, ch: _CHClient | None = None +) -> bool: """Whether the namespace's directory row, active or released, carries a tag that - starts with `prefix`: the mark a workload trust leaves on each agent's own - namespace (`auth.agents.tag`), which no caller can set.""" + starts with `prefix` and is not `claim_tag`: the mark a workload trust leaves on + each agent's own namespace (`auth.agents.tag`), which no caller can set. An agent + claim's mark starts the same way and names no trust.""" row = await (ch or _default_client()).query_one( "SELECT 1 AS x FROM loom.namespaces FINAL " "WHERE org = {org:String} AND namespace = {ns:String} " - "AND arrayExists(t -> startsWith(t, {prefix:String}), tags) LIMIT 1", - params={"org": org, "ns": namespace, "prefix": prefix}, + "AND arrayExists(t -> startsWith(t, {prefix:String}) AND t != {claim:String}, tags) " + "LIMIT 1", + params={"org": org, "ns": namespace, "prefix": prefix, "claim": claim_tag}, ) return row is not None diff --git a/tests/analyzer/cases/workers.py b/tests/analyzer/cases/workers.py index 8e0d3772bb..b0d25f8bef 100644 --- a/tests/analyzer/cases/workers.py +++ b/tests/analyzer/cases/workers.py @@ -471,7 +471,9 @@ async def _source_retirements(ch: RecordingCH, c: dict[str, Any]) -> None: await sources.assigned_across(ORG, "sa:docs-sync", ch=ch) await sources.read_states_of(ORG, [(NS, "decks"), ("team-ops", "runbooks")], ch=ch) # Whether a namespace was made as an agent's home, by its directory tag. - await sources.trust_made(ORG, NS, prefix="machine:", ch=ch) + await sources.trust_made( + ORG, NS, prefix="machine:", claim_tag="machine:agent-signup:claimed", ch=ch + ) # The copies behind a page of search hits, by their addresses. await sources.uploaded_copies(ORG, [(NS, f"source-doc:{item.source_id}:" + "a" * 64)], ch=ch) diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 13cfa28786..890cc6d565 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -984,7 +984,6 @@ 675a57195847 SELECT memory_id, version, agent, user_id, session_id, memory_key, created_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory_key IN {keys:Array(String)} AND tom 6765755688ca SELECT kind, name, status, description, cardinality, created_by, updated_at FROM loom.namespace_ontology FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status = {status:String} ORDER B 679aaca08b74 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows -67aff120d5cd SELECT ? AS x FROM loom.namespaces FINAL WHERE org = {org:String} AND namespace = {ns:String} AND arrayExists(t -> startsWith(t, {prefix:String}), tags) LIMIT ? 67b04af64852 SELECT DISTINCT namespace FROM loom.documents WHERE org = {org:String} AND user_id = {uid:String} ORDER BY namespace 67b658495a69 SELECT count() AS n FROM loom.read_receipts WHERE org = {org:String} AND (namespace = {ns:String} AND ts < {verified_at:DateTime}) 67dfbb3578cb SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this @@ -2438,6 +2437,7 @@ f4fbd5666c4e SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e. f516a9cc81d3 SELECT * FROM loom.entity_vectors FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory_key IN {keys:Array(String)} AND tombstoned_at IS NULL f51d6af32512 SELECT e.org AS org, e.namespace AS namespace, e.agent AS agent, e.user_id AS user_id, e.session_id AS session_id, e.memory_key AS memory_key FROM (SELECT org, namespace, agent, user_id, session_id, m f51e0ce42dcd SELECT count() OVER () AS total, memory_key, toString(memory_id) AS memory_id, expires_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND (emp +f5587aa13109 SELECT ? AS x FROM loom.namespaces FINAL WHERE org = {org:String} AND namespace = {ns:String} AND arrayExists(t -> startsWith(t, {prefix:String}) AND t != {claim:String}, tags) LIMIT ? f5c829aa506f SELECT memory_key, toString(memory_id) AS mid, version, content_sha256, agent, actor, memory_type, sensitivity, tags, toString(created_at) AS created, conflict_with, cross_promoted_from_namespace AS c f5ddaf977ab5 SELECT state_key, state_value AS value FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} AND state_key IN {keys:Array(String)} f5f447871253 SELECT count() AS n FROM loom.knowledge_suite_drafts WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? diff --git a/tests/integration/test_assigned_source_ch.py b/tests/integration/test_assigned_source_ch.py index 7d8c587ef1..27ee0c1ac0 100644 --- a/tests/integration/test_assigned_source_ch.py +++ b/tests/integration/test_assigned_source_ch.py @@ -249,6 +249,47 @@ def test_an_administrator_assigns_a_source_and_a_reader_is_shown_it( assert after["items"] == [{"id": "page-1"}, {"id": "page-2"}] +def test_a_namespace_claimed_at_sign_up_is_refused_as_a_persons_own_place( + control_plane_url: str, mint_test_token: Any, ch_client: Any, worker_source_org: Any +) -> None: + """Fails when the mark an agent's claim leaves, which starts as a trust's tag does + and names no trust, makes the namespace read as an agent's own: the refusal would + send the administrator to an agent's subject, and no agent's subject is accepted + there.""" + from server.auth.claim_codes import CLAIMED_TAG + + org = worker_source_org(unique_org("assigned-claimed")) + claimed = "agent-quill" + # An agent's home as its trust leaves it, and a namespace as agent sign-up and its + # claim leave it: its own owner, carrying the claim's mark. + ch_client.insert( + "loom.namespaces", + [[org, HOME, WORKER, ["machine:fleet"]], [org, claimed, claimed, [CLAIMED_TAG]]], + column_names=["org", "namespace", "owner_email", "tags"], + ) + host = mint_test_token(org=org, namespaces=[HOME, claimed], roles=["admin"], subject=HOST) + body = { + "org": org, + "name": "guide", + "worker_subject": "sa:docs-sync", + "reader": "pages", + "ref": "docs-1", + "generation": 1, + "profile_digest": DIGEST, + "selection": "listed", + "items": [{"id": "space-1"}], + } + for namespace, code in ((HOME, "SOURCE_WORKER_NAMESPACE"), (claimed, "PERSONAL_NAMESPACE")): + refused = _post( + control_plane_url, + host, + "knowledge.source.worker_assign", + {**body, "namespace": namespace}, + ) + assert refused.status_code == 422, refused.text[:300] + assert refused.json()["detail"]["code"] == code, namespace + + def _agent_home(ch_client: Any, org: str) -> None: """The agent's home as its first exchange leaves it: the directory row and the agent's own admin grant.""" diff --git a/tests/unit/test_assigned_source.py b/tests/unit/test_assigned_source.py index 461feb526c..39eb5f90fa 100644 --- a/tests/unit/test_assigned_source.py +++ b/tests/unit/test_assigned_source.py @@ -17,7 +17,7 @@ import pydantic import pytest -from server.auth import agents, machines +from server.auth import agents, claim_codes, machines from server.core.errors import LoomServerError from server.core.naming import is_mirror_name from server.identity.api.models_grants import GrantsCreateOutput, GrantsShareAgentInput @@ -162,8 +162,11 @@ async def count_assigned_copies(self, org: str, namespace: str, source_id: str) async def is_agent_home(self, org: str, namespace: str, *, tag: str, agent: str) -> bool: return (namespace, tag, agent) in self.homes - async def trust_made(self, org: str, namespace: str, *, prefix: str) -> bool: - return any(home == namespace and tag.startswith(prefix) for home, tag, _ in self.homes) + async def trust_made(self, org: str, namespace: str, *, prefix: str, claim_tag: str) -> bool: + return any( + home == namespace and tag.startswith(prefix) and tag != claim_tag + for home, tag, _ in self.homes + ) async def lent_by(self, org: str, namespace: str, subject: str) -> bool: return (namespace, subject) in self.lent @@ -202,7 +205,9 @@ async def write_state(self, *args: Any, **kwargs: Any) -> None: async def directory_row(self, org: str, namespace: str) -> Any: from server.knowledge.store.sources import DirectoryRow - return DirectoryRow(inactive=False, claimed_at_signup=False) + # Sign-up writes the namespace itself as its owner. + claimed = any(home == namespace == owner for home, _, owner in self.homes) + return DirectoryRow(inactive=False, claimed_at_signup=claimed) async def insert_assigned_source(self, src: KnowledgeSource) -> None: # The real writer decodes before it writes; a row it would refuse fails here too. @@ -421,6 +426,11 @@ def test_a_service_subject_is_assigned_only_outside_agent_homes(registry: _Regis # A person's own place takes no source, as for `knowledge.source.add`. refused = _refusal(namespace="personal-pat", worker_subject=SERVICE) assert refused == (422, "PERSONAL_NAMESPACE") + # So is a namespace claimed at sign-up: the claim's mark starts as a trust's tag + # does and names no trust. + registry.homes.add(("agent-quill", claim_codes.CLAIMED_TAG, "agent-quill")) + refused = _refusal(namespace="agent-quill", worker_subject=SERVICE) + assert refused == (422, "PERSONAL_NAMESPACE") assert registry.written == [] made = _assign(namespace=SHARED, worker_subject=SERVICE) From 37be59b4afaac218fb1345f5e4b935688c83aa65 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sun, 6 Dec 2026 09:59:46 +0000 Subject: [PATCH 3/7] The CLI reference row of loom knowledge source assign names its op and maturity The reference cuts a command's help at 200 characters, and the help was 240, so the row ended before "(knowledge.source.worker_assign, experimental)". The help is 158 characters, and the rule for the namespace is in the help of --namespace. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/reference/cli.md | 2 +- server/cli/knowledge_source.py | 11 +++++++---- tests/unit/snapshots/cli_help.json | 4 ++-- tests/unit/snapshots/cli_tree.json | 4 ++-- 4 files changed, 12 insertions(+), 9 deletions(-) diff --git a/docs/reference/cli.md b/docs/reference/cli.md index b4dd41ec84..e05e38c064 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -263,7 +263,7 @@ python scripts/codegen/docs_reference.py | `loom knowledge source list` | List the namespace's sources, items and sync state. | `--namespace`, `--org`, `--server-url`, `--token` | | `loom knowledge source add` | Register a source from links or items, probed with the credential before anything is stored; a source added with a credential file is read by every reader of the namespace (knowledge.source.add). | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--kind`, `--link`, `--item-json`, `--include`, `--credential-file`, `--dry-run` | | `loom knowledge source update` | Add and remove a source's items or change its file kinds, the added items probed with the stored credential (knowledge.source.update). | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--link`, `--item-json`, `--include`, `--remove-link`, `--remove-item-json` | -| `loom knowledge source assign` | Assign a source to a worker subject, or change that assignment; the namespace is an agent's own for that agent's subject and a shared one for any other, and every reader of it reads the copies… | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--worker-subject`, `--reader`, `--ref`, `--generation`, `--profile-digest`, `--selection`, `--item`, `--changed-since`, `--max-documents`, `--paused` | +| `loom knowledge source assign` | Assign a source to a worker subject, or change that assignment; every reader of the namespace reads the copies (knowledge.source.worker_assign, experimental). | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--worker-subject`, `--reader`, `--ref`, `--generation`, `--profile-digest`, `--selection`, `--item`, `--changed-since`, `--max-documents`, `--paused` | | `loom knowledge source remove` | Retire a source: its row goes inactive and its credential is cleared. | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--confirm`, `--delete-documents` | | `loom knowledge source worker-profiles` | List the provisioned source worker profiles and the collection's approval of each (knowledge.source.worker_profiles; experimental, answered denied until the CLI declares session protection). | `--namespace`, `--org`, `--server-url`, `--token`, `--limit`, `--after-json` | | `loom knowledge source worker-approve` | Set or revoke the collection's approval of one worker profile (knowledge.source.worker_approve; experimental, answered denied until the CLI declares session protection). | `--namespace`, `--org`, `--server-url`, `--token`, `--worker-id`, `--profile-digest`, `--mode`, `--revoke`, `--team-access`, `--expected-generation` | diff --git a/server/cli/knowledge_source.py b/server/cli/knowledge_source.py index cc7fdefd79..361b2a319d 100644 --- a/server/cli/knowledge_source.py +++ b/server/cli/knowledge_source.py @@ -64,11 +64,14 @@ def register_knowledge_source_cli(ksub: Any) -> None: p_update.set_defaults(func=_cmd_update) p_assign = ssub.add_parser( "assign", - help="Assign a source to a worker subject, or change that assignment; the namespace " - "is an agent's own for that agent's subject and a shared one for any other, and " - "every reader of it reads the copies (knowledge.source.worker_assign, experimental).", + help="Assign a source to a worker subject, or change that assignment; every reader " + "of the namespace reads the copies (knowledge.source.worker_assign, experimental).", + ) + _common( + p_assign, + "The namespace the copies live in: the agent's own for an agent's subject, a " + "shared one for any other", ) - _common(p_assign, "The namespace the copies live in") p_assign.add_argument("--name", required=True, help="The source's name in the namespace") p_assign.add_argument( "--worker-subject", diff --git a/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index f3f9a0d8f1..fd09f1600f 100644 --- a/tests/unit/snapshots/cli_help.json +++ b/tests/unit/snapshots/cli_help.json @@ -137,7 +137,7 @@ ], "loom knowledge source": [ "usage: loom knowledge source [-h] {list,add,update,assign,remove,worker-profiles,worker-approve,worker-accounts,worker-enroll,worker-preview,worker-register,worker-link,worker-unlink} ...", - "positional arguments: {list,add,update,assign,remove,worker-profiles,worker-approve,worker-accounts,worker-enroll,worker-preview,worker-register,worker-link,worker-unlink} list List the namespace's sources, items and sync state. add Register a source from links or items, probed with the credential before anything is stored; a source added with a credential file is read by every reader of the namespace (knowledge.source.add). update Add and remove a source's items or change its file kinds, the added items probed with the stored credential (knowledge.source.update). assign Assign a source to a worker subject, or change that assignment; the namespace is an agent's own for that agent's subject and a shared one for any other, and every reader of it reads the copies (knowledge.source.worker_assign, experimental). remove Retire a source: its row goes inactive and its credential is cleared. The copies of a mirrored source and of one assigned to a worker subject always go; for an assigned source the answer's documents_pending counts those still live (knowledge.source.remove). worker-profiles List the provisioned source worker profiles and the collection's approval of each (knowledge.source.worker_profiles; experimental, answered denied until the CLI declares session protection). worker-approve Set or revoke the collection's approval of one worker profile (knowledge.source.worker_approve; experimental, answered denied until the CLI declares session protection). worker-accounts List the worker profiles the collection approves, with your own account on each (knowledge.source.worker_accounts; experimental, answered denied until the CLI declares session protection). worker-enroll Link your own worker account to an approved profile (knowledge.source.worker_enroll; experimental, answered denied until the CLI declares session protection). worker-preview Check a worker source's selection through your linked account; nothing is written (knowledge.source.worker_preview; experimental, answered denied until the CLI declares session protection). worker-register Register the worker source a preview showed (knowledge.source.worker_register; experimental, answered denied until the CLI declares session protection). worker-link Link your own enrolled worker account to a team worker source, to read it live (knowledge.source.worker_link; experimental, answered denied until the CLI declares session protection). worker-unlink Unlink your own worker account from a worker source, or, as an administrator, a reader's (knowledge.source.worker_unlink; experimental, answered denied until the CLI declares session protection).", + "positional arguments: {list,add,update,assign,remove,worker-profiles,worker-approve,worker-accounts,worker-enroll,worker-preview,worker-register,worker-link,worker-unlink} list List the namespace's sources, items and sync state. add Register a source from links or items, probed with the credential before anything is stored; a source added with a credential file is read by every reader of the namespace (knowledge.source.add). update Add and remove a source's items or change its file kinds, the added items probed with the stored credential (knowledge.source.update). assign Assign a source to a worker subject, or change that assignment; every reader of the namespace reads the copies (knowledge.source.worker_assign, experimental). remove Retire a source: its row goes inactive and its credential is cleared. The copies of a mirrored source and of one assigned to a worker subject always go; for an assigned source the answer's documents_pending counts those still live (knowledge.source.remove). worker-profiles List the provisioned source worker profiles and the collection's approval of each (knowledge.source.worker_profiles; experimental, answered denied until the CLI declares session protection). worker-approve Set or revoke the collection's approval of one worker profile (knowledge.source.worker_approve; experimental, answered denied until the CLI declares session protection). worker-accounts List the worker profiles the collection approves, with your own account on each (knowledge.source.worker_accounts; experimental, answered denied until the CLI declares session protection). worker-enroll Link your own worker account to an approved profile (knowledge.source.worker_enroll; experimental, answered denied until the CLI declares session protection). worker-preview Check a worker source's selection through your linked account; nothing is written (knowledge.source.worker_preview; experimental, answered denied until the CLI declares session protection). worker-register Register the worker source a preview showed (knowledge.source.worker_register; experimental, answered denied until the CLI declares session protection). worker-link Link your own enrolled worker account to a team worker source, to read it live (knowledge.source.worker_link; experimental, answered denied until the CLI declares session protection). worker-unlink Unlink your own worker account from a worker source, or, as an administrator, a reader's (knowledge.source.worker_unlink; experimental, answered denied until the CLI declares session protection).", "options: -h, --help show this help message and exit" ], "loom knowledge source list": [ @@ -154,7 +154,7 @@ ], "loom knowledge source assign": [ "usage: loom knowledge source assign [-h] --namespace NAMESPACE [--org ORG] [--server-url SERVER_URL] [--token TOKEN] --name NAME --worker-subject WORKER_SUBJECT --reader READER --ref REF --generation GENERATION --profile-digest PROFILE_DIGEST --selection {selected,listed} --item ITEM [--changed-since] [--max-documents MAX_DOCUMENTS] [--paused]", - "options: -h, --help show this help message and exit --namespace NAMESPACE The namespace the copies live in --org ORG Default: the token's org --server-url SERVER_URL Server URL (default: $LOOM_BASE_URL, ~/.loom/config.json url, http://localhost:7777) --token TOKEN JWT (default: $LOOM_API_KEY, ~/.loom/token) --name NAME The source's name in the namespace --worker-subject WORKER_SUBJECT The subject whose token syncs the source: an agent's, sa::, or a service account's --reader READER The reader the worker runs --ref REF The host's id of the connection --generation GENERATION The connection's generation, from 1 --profile-digest PROFILE_DIGEST The approved reader profile's SHA-256 --selection {selected,listed} selected: each --item is a document; listed: the one --item is a container --item ITEM An id to read; repeatable --changed-since listed: ask the container only for what changed since the last pass --max-documents MAX_DOCUMENTS The documents kept, at most; default 2000 --paused Keep the assignment and stop its sync" + "options: -h, --help show this help message and exit --namespace NAMESPACE The namespace the copies live in: the agent's own for an agent's subject, a shared one for any other --org ORG Default: the token's org --server-url SERVER_URL Server URL (default: $LOOM_BASE_URL, ~/.loom/config.json url, http://localhost:7777) --token TOKEN JWT (default: $LOOM_API_KEY, ~/.loom/token) --name NAME The source's name in the namespace --worker-subject WORKER_SUBJECT The subject whose token syncs the source: an agent's, sa::, or a service account's --reader READER The reader the worker runs --ref REF The host's id of the connection --generation GENERATION The connection's generation, from 1 --profile-digest PROFILE_DIGEST The approved reader profile's SHA-256 --selection {selected,listed} selected: each --item is a document; listed: the one --item is a container --item ITEM An id to read; repeatable --changed-since listed: ask the container only for what changed since the last pass --max-documents MAX_DOCUMENTS The documents kept, at most; default 2000 --paused Keep the assignment and stop its sync" ], "loom knowledge source remove": [ "usage: loom knowledge source remove [-h] --namespace NAMESPACE [--org ORG] [--server-url SERVER_URL] [--token TOKEN] --name NAME --confirm CONFIRM [--delete-documents]", diff --git a/tests/unit/snapshots/cli_tree.json b/tests/unit/snapshots/cli_tree.json index 062de44117..054fd545fc 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -4508,7 +4508,7 @@ "nargs": null, "type": null, "required": true, - "help": "The namespace the copies live in", + "help": "The namespace the copies live in: the agent's own for an agent's subject, a shared one for any other", "metavar": null }, { @@ -6357,7 +6357,7 @@ }, { "dest": "assign", - "help": "Assign a source to a worker subject, or change that assignment; the namespace is an agent's own for that agent's subject and a shared one for any other, and every reader of it reads the copies (knowledge.source.worker_assign, experimental).", + "help": "Assign a source to a worker subject, or change that assignment; every reader of the namespace reads the copies (knowledge.source.worker_assign, experimental).", "metavar": "assign" }, { From 83478469c2a41de43d30d10e2c0871737fb796a2 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sun, 6 Dec 2026 09:59:54 +0000 Subject: [PATCH 4/7] The comments and pages on a worker's claim state the rule for both kinds of subject Five statements said a claim reads only the caller's home namespace, or that a host connection serves only an agent's own namespace. An agent's claim reads its own namespace and draws the namespace bucket there. Any other service account's claim reads the org's rows that name it, where the assignment is the grant, and draws the bucket on a slot per subject. A host connection gives authority where an administrator assigned the source: the agent's own namespace, or a shared one for a subject that is no agent's. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/document-sources.md | 8 +++++--- docs/architecture/mcp-source-worker-boundary.md | 9 +++++---- server/core/ratelimit.py | 10 +++++----- server/knowledge/api/ops_source_worker.py | 10 ++++++---- tests/unit/test_by_id_ops_scoped_tokens.py | 5 +++-- 5 files changed, 24 insertions(+), 18 deletions(-) diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 8dec432574..b81bec7a5d 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -419,9 +419,11 @@ draws from: `source.worker.poll` for `claim` and `stored` (20 burst, 2 per secon namespace; 200 and 40 per org) and `source.worker.write` for `commit` and `put` (40 burst, one per two seconds per namespace; 200 and 20 per org), so a fleet of agents that each poll one namespace is bounded by the org and never by one agent's readers. A claim -names no namespace, so its handler draws the poll's buckets on the caller's home -namespace before it reads anything; the other three are drawn by the transport, as for -any op that names a namespace. +names no namespace, so its handler draws the poll's buckets before it reads anything. +An agent's claim draws the namespace bucket on the agent's own namespace. The claim of +a subject that is no agent's draws it on a slot per subject, `source-worker:`, +a name no namespace can have, so one worker's polls spend no other's. The other three +ops are drawn by the transport, as for any op that names a namespace. ### Removing an assigned source diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index c737793340..4a31f78527 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -211,10 +211,11 @@ server descriptions cannot expand the accepted operations or outbound addresses. Returned data is evidence for the requested resource only. An account host can implement this worker contract locally if it can resolve the exact requester and connection for the requested operation without an active agent session or -credential export. A host connection gives authority for the host identity's own -namespace only, and only when an administrator of that namespace, not the agent, -assigned the source -([assigned sources](document-sources.md#a-source-a-worker-syncs-for-an-agent)). +credential export. A host connection gives authority only where an administrator of the +namespace, not the worker subject, assigned the source: in the agent's own namespace +for an agent's subject, or in a shared namespace for a service account that is no +agent's +([where an assigned source lives](document-sources.md#where-an-assigned-source-lives)). ## Live read statuses diff --git a/server/core/ratelimit.py b/server/core/ratelimit.py index a3c3cb63ed..94273e1681 100644 --- a/server/core/ratelimit.py +++ b/server/core/ratelimit.py @@ -182,9 +182,9 @@ class Limit: # One mutation per delete. The burst covers an administrator who removes several # revisions in a row; the sustained rate keeps queued rewrites of the table apart. "skill.delete": Limit(capacity=10, rate=1 / 60), # 1/min - # One worker subject polls its own home namespace. A claim names no namespace, so - # its handler draws these buckets, not the transport; a fleet shares the org's - # (`DEFAULT_ORG_LIMITS`). + # One worker subject's polls: an agent's draw on its own namespace, any other + # subject's on a slot of its own. A claim names no namespace, so its handler draws + # these buckets, not the transport; a fleet shares the org's (`DEFAULT_ORG_LIMITS`). "source.worker.poll": Limit(capacity=20, rate=2), # A turn commits a checkpoint every few seconds at most and ends within its bound. "source.worker.write": Limit(capacity=40, rate=0.5), @@ -197,8 +197,8 @@ class Limit: op_class: Limit(capacity=lim.capacity * 3, rate=lim.rate * 3) for op_class, lim in DEFAULT_LIMITS.items() } -# One org is a fleet of worker subjects, each in its own namespace: its buckets are -# sized by the fleet, not by three namespaces. 40 polls a second serve 24,000 workers +# One org is a fleet of worker subjects, each on a namespace bucket of its own: its +# buckets are sized by the fleet, not by three namespaces. 40 polls a second serve 24,000 workers # that each poll every ten minutes. DEFAULT_ORG_LIMITS["source.worker.poll"] = Limit(capacity=200, rate=40) DEFAULT_ORG_LIMITS["source.worker.write"] = Limit(capacity=200, rate=20) diff --git a/server/knowledge/api/ops_source_worker.py b/server/knowledge/api/ops_source_worker.py index bbe33c190b..4383c52b63 100644 --- a/server/knowledge/api/ops_source_worker.py +++ b/server/knowledge/api/ops_source_worker.py @@ -3,10 +3,12 @@ source's copies inside it. Their wire models are in `models_source_worker`. A claim is answered by assignment alone: it names no namespace, so the gate admits a -scoped token on its best role in the org (`row_scoped`), and the handler reads only the -caller's home namespace and keeps the rows whose `worker_subject` is the caller. A -commit names its namespace, so the gate requires the writer role there first, and the -handler then requires the assignment; `stored` and `put` are gated as a commit is. +scoped token on its best role in the org (`row_scoped`), and the handler keeps only the +rows whose `worker_subject` is the caller. An agent's claim reads the agent's own +namespace; any other service account's reads the org's rows that name it, where the +assignment is the grant. A commit names its namespace, so the gate requires the writer +role there first, and the handler then requires the assignment; `stored` and `put` are +gated as a commit is. Anyone else is answered as for a source that does not exist. Only `stored`, a read, is idempotent: a cached answer of another would keep a claim or repeat a write.""" diff --git a/tests/unit/test_by_id_ops_scoped_tokens.py b/tests/unit/test_by_id_ops_scoped_tokens.py index b5aaa4b7ad..cbdc6bc2cf 100644 --- a/tests/unit/test_by_id_ops_scoped_tokens.py +++ b/tests/unit/test_by_id_ops_scoped_tokens.py @@ -128,8 +128,9 @@ def test_every_row_scoped_handler_authorizes_the_rows_namespace() -> None: """The flag moves the namespace check from the transport into the handler; a handler that forgot it would serve any namespace's row. `namespace_for_id` keeps only the namespaces `row_in_scope` admits.""" - # A worker subject's claim names no row: it reads only the caller's own home - # namespace, and only as a service account calling as itself (`_worker_subject`). + # A worker subject's claim names no row: it reads only the sources assigned to the + # caller, an agent's in its own namespace and any other subject's across the org, + # and only as a service account calling as itself (`_worker_subject`). gates = ("row_in_scope", "_authorize_status_read", "namespace_for_id", "_worker_subject") for name in _ROW_SCOPED: src = inspect.getsource(_op(name).handler) From f1cb4bd2a5ca49142f4df83e8f326040673a01cd Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sun, 6 Dec 2026 10:30:29 +0000 Subject: [PATCH 5/7] The boundary page states one namespace rule for a worker beside a host, for both kinds of subject The host backend section said a claim reads the home namespace alone, which holds for an agent's subject only. The claim of a service account that is no agent's reads the org's rows that name it. The page says what each claim reads, and that the backend syncs the one namespace it is given: a source claimed from another shared namespace is refused `tool_not_allowed`. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- .../architecture/mcp-source-worker-boundary.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index 16b67e9fb7..947a1de027 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -216,6 +216,9 @@ namespace, not the worker subject, assigned the source: in the agent's own names for an agent's subject, or in a shared namespace for a service account that is no agent's ([where an assigned source lives](document-sources.md#where-an-assigned-source-lives)). +An agent's claim reads the agent's own namespace alone. The claim of a service account +that is no agent's reads the org's rows that name it, in whichever shared namespace each +was assigned. ### The host backend @@ -231,7 +234,7 @@ calls it and gives it: | `list_tools(ref)` | The tool definitions the connection advertises. The reader checks them against the mapping's pinned digests before it calls a tool. | | The mappings | A directory of [read mappings](source-mapping.md), one a JSON file. The worker claims only a source whose `profile_digest` is the digest of one of them. | | The allow-list | The ids of the connections the host allowed for indexing. | -| The home namespace | The host identity's own namespace, the only one whose sources the worker syncs. | +| The home namespace | The one namespace whose sources the worker syncs: the host identity's own for an agent's subject, one shared namespace for a service account that is no agent's. | Both functions raise `ReaderError` with one of the reader's [failure codes](source-mapping.md#failure-codes) and nothing else. Turning the host's own @@ -272,11 +275,14 @@ registrant removes the source or the [copy age bound](document-sources.md#copies-of-a-connection-nobody-verified) passes. The trust of a host connection: anything that holds the host identity's token can upload -a copy under a source assigned to that identity. Four things bound it. A claim reads the -home namespace alone, and the backend refuses any other. Only the subject that assigned -a source changes its registration, and the worker subject never assigns one to itself. A -turn writes inside its source's key range (`source-doc::`) and nowhere else. -Every hit of a copy names the uploader as `uploaded_by` in its `synced_from`. +a copy under a source assigned to that identity. Four things bound it. The backend syncs +the home namespace alone: an agent's claim reads no other, and a source that the claim +of a service account that is no agent's answers from another shared namespace is +refused `tool_not_allowed`, so such an account run beside a host is assigned sources in +that one namespace. Only the subject that assigned a source changes its registration, +and the worker subject never assigns one to itself. A turn writes inside its source's +key range (`source-doc::`) and nowhere else. Every hit of a copy names the +uploader as `uploaded_by` in its `synced_from`. The host never puts a server its platform runs for itself in the allow-list: the list holds what a person turned on for indexing. The worker drops its own route to Loom, the From d01e672cfab33bf47b15d461a2ecbbf6dd4bcdda Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sun, 6 Dec 2026 10:30:36 +0000 Subject: [PATCH 6/7] The comment on an org's worker limits says its subjects are spread over many namespace buckets The comment sits above the org's poll and write limits. Only a claim by a subject that is no agent's draws a namespace bucket of its own; `stored`, `put` and `commit` draw the bucket of the source's namespace, which the workers assigned there share. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- server/core/ratelimit.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/server/core/ratelimit.py b/server/core/ratelimit.py index 94273e1681..e4a4014800 100644 --- a/server/core/ratelimit.py +++ b/server/core/ratelimit.py @@ -197,9 +197,9 @@ class Limit: op_class: Limit(capacity=lim.capacity * 3, rate=lim.rate * 3) for op_class, lim in DEFAULT_LIMITS.items() } -# One org is a fleet of worker subjects, each on a namespace bucket of its own: its -# buckets are sized by the fleet, not by three namespaces. 40 polls a second serve 24,000 workers -# that each poll every ten minutes. +# One org is a fleet of worker subjects spread over many namespace buckets: its buckets +# are sized by the fleet, not by three namespaces. 40 polls a second serve 24,000 +# workers that each poll every ten minutes. DEFAULT_ORG_LIMITS["source.worker.poll"] = Limit(capacity=200, rate=40) DEFAULT_ORG_LIMITS["source.worker.write"] = Limit(capacity=200, rate=20) From 64044026962de6ce801372d5c85c4a120337e2a4 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sun, 6 Dec 2026 11:26:36 +0000 Subject: [PATCH 7/7] A service account's claim starts a turn only where its token writes A claim across the org offered every source that names the caller, and the commit that ends a turn needs the writer role on the source's namespace at the transport. A source assigned in a namespace the token cannot write was offered first on every poll, took its turn lease and ended the worker's run at a commit the transport refused, with no state written. The claim now passes over a due source in a namespace where the caller does not hold the writer role, before its row is read and with no lease taken, and goes on to the caller's next due source. The gate a commit passes decides the role from the caller's grants, read once a claim and not once a source. Grants that cannot be read refuse the claim with 503. An agent's claim reads the agent's own namespace and is unchanged. The source worker boundary page states the server's bound on a host token first, for each kind of subject, and the backend's own rule after the four bounds. The document sources page says what an administrator sees for a source assigned where the service account's token cannot write: its row shows no turn. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/document-sources.md | 27 ++++-- .../mcp-source-worker-boundary.md | 24 ++--- docs/features/knowledge.md | 9 +- server/knowledge/api/models_source_worker.py | 9 +- server/knowledge/api/ops_source_worker.py | 14 +-- server/knowledge/app/source_worker_turns.py | 47 ++++++++-- .../test_cross_principal_leakage.py | 85 +++++++++++++++++- tests/unit/test_by_id_ops_scoped_tokens.py | 4 +- tests/unit/test_source_worker_ops.py | 87 ++++++++++++++++++- 9 files changed, 263 insertions(+), 43 deletions(-) diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index b81bec7a5d..c51b36b0d0 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -210,7 +210,10 @@ shared namespace: it stays a source a person owns. The assignment does not prove what a subject string names. Only a service account calling as itself is answered a turn ([who is answered](#a-worker-subjects-turn)), so a -source that names a person is stored, shown, and never synced. No row names a subject +source that names a person is stored, shown, and never synced. So is a source assigned to +a service account whose token does not hold the writer role on the source's namespace: +its row shows no turn, and a copy it holds is served until the +[copy age bound](#copies-of-a-connection-nobody-verified) passes. No row names a subject that is no agent's in an agent's namespace: the assignment refuses it, and a trust never makes an agent's namespace over a name that holds an active source, which counts as a namespace in use. @@ -233,8 +236,9 @@ ended. Inside a turn `knowledge.source.worker.put` (experimental) uploads one do and `knowledge.source.worker.stored` (experimental) lists what Loom holds of the source. Loom runs no reader and holds no credential: the worker lists and fetches. -**Who is answered.** A claim is answered by assignment alone, not by a namespace role; a -commit needs the writer role on the source's namespace and then the assignment. The +**Who is answered.** A claim is answered by assignment, and across the org only where +the caller's token holds the writer role on the source's namespace; a commit needs the +writer role on the source's namespace and then the assignment. The caller is a worker subject when its verified token is a service account's own token, carries no impersonation and no read narrowing, and belongs to the body's `org`. An agent's claim reads only the agent's own namespace, with one bounded statement over the @@ -246,7 +250,14 @@ registry on the sorting key prefix `org` that answers only the active rows whose `worker_subject` is the caller, by namespace and name, 2,000 at most and without their items, and one statement over the sync states of those rows. Neither is repeated per namespace. Before a turn starts, that claim reads the due source's whole row and offers -it only at the version the first read answered and while it still names the caller. A +it only at the version the first read answered and while it still names the caller. It +starts no turn its caller could not commit: a due source in a namespace where the +caller's token does not hold the writer role is passed over before its row is read, with +no lease taken, and the claim goes on to the caller's next due source. The gate that +admits a commit decides the role, from the caller's grants read once a claim and not +once a source, and grants that cannot be read refuse the claim with 503. An agent's +claim is not checked so: it reads the agent's own namespace, where the agent holds its +role. A worker subject is offered at most 2,000 sources: a team with more runs another worker under another subject. A caller that is no worker subject, or one with no source, is answered `status: none` exactly as a worker @@ -2417,9 +2428,11 @@ Each implementing pull request lists its own; these pin the model: and `tests/integration/test_cross_principal_leakage.py`: a subject that is no agent's is assigned a source only outside agents' namespaces and an agent's subject only in its own; a service account claims its sources in two namespaces with one registry - read and one state read, and never another subject's; a person named as worker - subject claims nothing; a reader of the shared namespace finds the copy, and a - principal of another namespace or org sees neither the source nor the copy. + read and one state read, and never another subject's; it is offered no source in a + namespace its token cannot write, takes no lease there and is offered its next due + source; a person named as worker subject claims nothing; a reader of the shared + namespace finds the copy, and a principal of another namespace or org sees neither + the source nor the copy. - Integration: `tests/integration/test_document_worker_load.py`: 200 assigned sources of one org import, expire together, are retired by the queue and import again with no request refused by an org bucket; an org whose write bucket is empty does not refuse diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index 947a1de027..e1ca53302d 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -218,7 +218,7 @@ agent's ([where an assigned source lives](document-sources.md#where-an-assigned-source-lives)). An agent's claim reads the agent's own namespace alone. The claim of a service account that is no agent's reads the org's rows that name it, in whichever shared namespace each -was assigned. +was assigned, and offers a source only in a namespace its token writes. ### The host backend @@ -260,7 +260,8 @@ channel's request cap: a `put` whose arguments are longer than the cap less 4,09 is counted `too_large` and not sent. The backend refuses a claimed source before a tool is listed or called, and the refusal -is the turn's last commit: +is the turn's last commit. A claim offers a source only in a namespace the caller's token +writes, so the server takes that commit. The refusal is one of: - `tool_not_allowed`: a `ref` outside the allow-list, a `ref` that is not a lower-case letter or digit followed by at most 31 lower-case letters, digits or `-` (the stricter @@ -275,14 +276,17 @@ registrant removes the source or the [copy age bound](document-sources.md#copies-of-a-connection-nobody-verified) passes. The trust of a host connection: anything that holds the host identity's token can upload -a copy under a source assigned to that identity. Four things bound it. The backend syncs -the home namespace alone: an agent's claim reads no other, and a source that the claim -of a service account that is no agent's answers from another shared namespace is -refused `tool_not_allowed`, so such an account run beside a host is assigned sources in -that one namespace. Only the subject that assigned a source changes its registration, -and the worker subject never assigns one to itself. A turn writes inside its source's -key range (`source-doc::`) and nowhere else. Every hit of a copy names the -uploader as `uploaded_by` in its `synced_from`. +a copy under a source assigned to that identity. Four things bound it. A claim answers +only the sources an administrator assigned to the caller: an agent's in its own +namespace alone, and those of a service account that is no agent's in every shared +namespace that names it and that its token writes. Only the subject that assigned a +source changes its registration, and the worker subject never assigns one to itself. A +turn writes inside its source's key range (`source-doc::`) and nowhere else. +Every hit of a copy names the uploader as `uploaded_by` in its `synced_from`. + +The backend itself syncs the home namespace alone: a source of another namespace is +refused `tool_not_allowed`, so a service account run beside a host is assigned sources +in that one namespace. The host never puts a server its platform runs for itself in the allow-list: the list holds what a person turned on for indexing. The worker drops its own route to Loom, the diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 4732dd1efd..0495ce3ffd 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -592,12 +592,15 @@ loom knowledge source assign --namespace team-docs --name handbook \ - Every reader of the namespace reads every copy. Assign a source there only when all of them may read all of its upstream; otherwise keep it a source a person owns. - Give the service account's token the `writer` role on each namespace it syncs: the - turn's `put`, `stored` and `commit` name the namespace. + turn's `put`, `stored` and `commit` name the namespace. A claim offers no source in a + namespace the token does not write, so a source assigned there is never synced: its + row shows no turn. - Name a service account. Only a service account calling as itself is answered a turn, and `worker_assign` cannot tell what a subject string names, so a source that names a person is stored and never synced. -- One claim offers the service account its sources in every namespace of the org, 2,000 - at most. Run a second worker under another subject for more. +- One claim offers the service account its sources in every namespace of the org that + its token writes, of 2,000 at most that name it. Run a second worker under another + subject for more. - The subject that assigned the source removes it, with `loom knowledge source remove` or the dashboard's Retire, and its copies go with it. diff --git a/server/knowledge/api/models_source_worker.py b/server/knowledge/api/models_source_worker.py index c16a974e52..0c2a648aad 100644 --- a/server/knowledge/api/models_source_worker.py +++ b/server/knowledge/api/models_source_worker.py @@ -22,10 +22,11 @@ class KnowledgeSourceWorkerClaimInput(BaseModel): Only a service account calling as itself is answered with a turn; any other caller, and a subject no source is assigned to, is answered `none`. An agent's subject is offered the sources of its own namespace; any other subject is offered the sources - that name it in every namespace of the org, 2,000 at most. The answer names the - source due longest whose reader and profile digest the call lists, with a `claim` - that proves the turn to `knowledge.source.worker.commit` until the turn ends: by its - last commit, by its age, or by any rewrite of the source's registration.""" + that name it across the org, 2,000 at most, in the namespaces where its token holds + the writer role. The answer names the source due longest whose reader and profile + digest the call lists, with a `claim` that proves the turn to + `knowledge.source.worker.commit` until the turn ends: by its last commit, by its age, + or by any rewrite of the source's registration.""" model_config = _PRIVATE diff --git a/server/knowledge/api/ops_source_worker.py b/server/knowledge/api/ops_source_worker.py index 4383c52b63..ca17aa078a 100644 --- a/server/knowledge/api/ops_source_worker.py +++ b/server/knowledge/api/ops_source_worker.py @@ -2,13 +2,13 @@ opens and closes a turn of an assigned document source with, and reads and uploads the source's copies inside it. Their wire models are in `models_source_worker`. -A claim is answered by assignment alone: it names no namespace, so the gate admits a -scoped token on its best role in the org (`row_scoped`), and the handler keeps only the -rows whose `worker_subject` is the caller. An agent's claim reads the agent's own -namespace; any other service account's reads the org's rows that name it, where the -assignment is the grant. A commit names its namespace, so the gate requires the writer -role there first, and the handler then requires the assignment; `stored` and `put` are -gated as a commit is. +A claim names no namespace, so the gate admits a scoped token on its best role in the +org (`row_scoped`), and the handler keeps only the rows whose `worker_subject` is the +caller. An agent's claim reads the agent's own namespace; any other service account's +reads the org's rows that name it and starts a turn only in a namespace where the caller +holds the writer role, the role the turn's commit needs. A commit names its namespace, +so the gate requires the writer role there first, and the handler then requires the +assignment; `stored` and `put` are gated as a commit is. Anyone else is answered as for a source that does not exist. Only `stored`, a read, is idempotent: a cached answer of another would keep a claim or repeat a write.""" diff --git a/server/knowledge/app/source_worker_turns.py b/server/knowledge/app/source_worker_turns.py index 517e257296..1227dbfbb9 100644 --- a/server/knowledge/app/source_worker_turns.py +++ b/server/knowledge/app/source_worker_turns.py @@ -8,7 +8,8 @@ whole bound; `commit` records progress and, with `done`, the outcome that schedules the next turn (`domain.source_worker_schedule`). An agent's subject is offered the sources of its own namespace and no other; a subject that is no agent's has no namespace of its -own and is offered the sources that name it across its org (`_offers_across`). +own and is offered the sources that name it across its org (`_offers_across`), in the +namespaces where its token holds the writer role (`_row_of`). Inside the turn `stored` lists the source's copies (ids, revisions and hashes, never text), `put` writes one document as the source's copy at the source's own address @@ -19,8 +20,10 @@ Every op requires the assignment: the caller is a service account calling as itself whose subject is the row's `worker_subject`. Anyone else is answered as for a source that does -not exist: `none` by claim, CLAIM_LOST by the others. A claim needs nothing more; the -others name their namespace, so the transport requires the writer role there first. +not exist: `none` by claim, CLAIM_LOST by the others. The others name their namespace, +so the transport requires the writer role there first. A claim names none: across the +org it starts a turn only where the caller holds that role, so it hands out no turn +its caller cannot commit. A claim is `w1..<32 random bytes>`. Only its SHA-256 is kept, as the holder of the lease row and, beside the row version, as the state's `turn`. A turn ends by its @@ -40,11 +43,11 @@ import re import secrets import time -from collections.abc import AsyncIterator, Callable +from collections.abc import AsyncIterator, Awaitable, Callable from datetime import datetime from typing import Any, NamedTuple -from server.auth import agents +from server.auth import agents, authz from server.auth.context import current_auth, current_caller from server.core import leases from server.core.ch import sequential_reads @@ -98,6 +101,7 @@ from server.knowledge.store import sources as store from server.observability.budget_shape import note_budget_shape from server.observability.traffic_class import current_traffic_class +from server.operations.base import Role from server.settings import settings log = logging.getLogger(__name__) @@ -225,9 +229,33 @@ async def _offers_across(org: str, subject: str) -> list[_Offer]: return offers -async def _row_of(org: str, subject: str, offer: _Offer) -> _Due | None: - """The whole row of a due `offer`, read fresh; None when it is no longer the - assignment the poll read: rewritten, removed, or handed to another subject.""" +def _writer_gate(org: str) -> Callable[[str], Awaitable[bool]]: + """Whether the calling token holds the writer role on a namespace of `org`, the role + the transport requires of a turn's commit there. One gate answers for a claim + (`authz.CachedGate`): it reads the caller's grants once, and each namespace is + decided once, however many of the caller's sources it holds. A role the gate cannot + confirm is not held, and grants that cannot be read refuse the claim (503).""" + auth = current_auth() + gate = authz.CachedGate(auth, org) if auth is not None else None + verdicts: dict[str, bool] = {} + + async def writes(namespace: str) -> bool: + if namespace not in verdicts: + verdicts[namespace] = gate is not None and await gate.admits(namespace, Role.WRITER) + return verdicts[namespace] + + return writes + + +async def _row_of( + org: str, subject: str, offer: _Offer, writes: Callable[[str], Awaitable[bool]] +) -> _Due | None: + """The whole row of a due `offer`, read fresh; None where the caller could not + commit the turn (`writes`), so no claim starts one it cannot end, and when the row + is no longer the assignment the poll read: rewritten, removed, or handed to another + subject.""" + if not await writes(offer.namespace): + return None with sequential_reads(): src = await store.get_source(org, offer.namespace, offer.name) if src is None or src.version != offer.version or src.worker_subject != subject: @@ -301,10 +329,11 @@ def claimable(offer: _Offer) -> bool: and offer.config.profile_digest in input.profile_digests and claimable(offer) ] + writes = _writer_gate(input.org) # The turn that ended longest ago first, so a busy source hides no other. for offer in sorted(due, key=lambda o: o.state.turn_ended_at): key = (offer.namespace, offer.name) - found = rows.get(key) or await _row_of(input.org, subject, offer) + found = rows.get(key) or await _row_of(input.org, subject, offer, writes) if found is None: continue src = found.src diff --git a/tests/integration/test_cross_principal_leakage.py b/tests/integration/test_cross_principal_leakage.py index 493d1f65f4..93ab746f58 100644 --- a/tests/integration/test_cross_principal_leakage.py +++ b/tests/integration/test_cross_principal_leakage.py @@ -3075,7 +3075,7 @@ def test_a_viewer_of_another_namespace_sees_no_service_workers_source_or_copy( assert r.status_code == 200, f"{who} {op}: {r.text[:200]}" assert not any(s in r.text for s in secrets), f"{who} {op}" # A writer of namespace A who is not the worker subject is offered nothing either: - # the assignment is the grant, never the role. + # the role offers nothing without the assignment. r = _post(control_plane_url, tokens["a_writer"], "knowledge.source.worker.claim", poll) assert (r.status_code, r.json()) == (none.status_code, none.json()) # The source and its copy are as they were. @@ -3084,6 +3084,89 @@ def test_a_viewer_of_another_namespace_sees_no_service_workers_source_or_copy( assert after.json()["sync"]["status"] == "ok" +def test_a_service_worker_is_offered_no_source_its_token_cannot_write( + control_plane_url, mint_test_token, worker_source_org +) -> None: + """A service account's claim starts a turn only in a namespace where its token holds + the writer role, the role the turn's commit is gated on. A source an administrator + of another namespace assigned to the subject is not offered and takes no turn lease, + and it hides no other: the claim offers the source the token can sync, and a later + claim offers it again.""" + org = worker_source_org(unique_org("leak-claim")) + tag = uuid.uuid4().hex[:6] + service = f"sa:leak-sync-{tag}" + # The namespace the token cannot write sorts first, so its source is due first. + closed, written = f"a-ops-{tag}", f"b-docs-{tag}" + host = mint_test_token( + org=org, namespaces=[closed, written], roles=["admin"], subject=f"host-{tag}" + ) + for namespace, name in ((closed, "manual"), (written, "guide")): + made = _post( + control_plane_url, + host, + "knowledge.source.worker_assign", + { + "org": org, + "namespace": namespace, + "name": name, + "worker_subject": service, + "reader": "pages", + "ref": "docs-1", + "generation": 1, + "profile_digest": "ab" * 32, + "selection": "selected", + "items": [{"id": "page-1"}], + }, + ) + assert made.status_code == 200, made.text[:300] + worker = mint_test_token(org=org, namespaces=[written], roles=["writer"], subject=service) + poll = {"org": org, "readers": ["pages"], "profile_digests": ["ab" * 32]} + guide = {"org": org, "namespace": written, "name": "guide"} + + def offered(token: str) -> dict[str, Any]: + r = _post(control_plane_url, token, "knowledge.source.worker.claim", poll) + assert r.status_code == 200, r.text[:300] + return dict(r.json()) + + def ended(turn: dict[str, Any]) -> None: + body = {**guide, "claim": turn["claim"], "seq": 1, "done": True, "listing": "complete"} + done = _post(control_plane_url, worker, "knowledge.source.worker.commit", body) + assert done.status_code == 200, done.text[:300] + + first = offered(worker) + assert first["status"] == "claimed", first + assert (first["source"]["namespace"], first["source"]["name"]) == (written, "guide") + # While that turn runs the caller has nothing else to sync, and is told of no other. + waits = offered(worker) + assert (waits["status"], waits["attention"]) == ("none", []) + ended(first) + # A request makes `guide` due again: the later claim offers it, not the other source. + asked = _post(control_plane_url, host, "knowledge.source.sync_now", guide) + assert asked.status_code == 200, asked.text[:300] + again = offered(worker) + assert (again["status"], again["source"]["name"]) == ("claimed", "guide"), again + ended(again) + # The commit that would end a turn of the other source is the gate's refusal, and + # the source ran no turn. + manual = {"org": org, "namespace": closed, "name": "manual"} + refused = _post( + control_plane_url, + worker, + "knowledge.source.worker.commit", + {**manual, "claim": first["claim"], "seq": 1, "done": True}, + ) + assert refused.status_code == 403, refused.text[:300] + shown = _post(control_plane_url, host, "knowledge.source.inspect", manual) + assert shown.status_code == 200, shown.text[:300] + assert (shown.json()["sync"]["status"], shown.json()["sync"]["last_synced_at"]) == ("", "") + # Positive control: the subject's token that writes both namespaces is offered the + # other source at once, so the role alone withheld it and no claim took its lease. + both = mint_test_token(org=org, namespaces=[closed, written], roles=["writer"], subject=service) + control = offered(both) + assert control["status"] == "claimed", control + assert (control["source"]["namespace"], control["source"]["name"]) == (closed, "manual") + + def test_a_draft_skill_is_read_only_by_the_writers_of_its_namespace( control_plane_url, mint_test_token ) -> None: diff --git a/tests/unit/test_by_id_ops_scoped_tokens.py b/tests/unit/test_by_id_ops_scoped_tokens.py index cbdc6bc2cf..b5576e0d68 100644 --- a/tests/unit/test_by_id_ops_scoped_tokens.py +++ b/tests/unit/test_by_id_ops_scoped_tokens.py @@ -130,7 +130,9 @@ def test_every_row_scoped_handler_authorizes_the_rows_namespace() -> None: `namespace_for_id` keeps only the namespaces `row_in_scope` admits.""" # A worker subject's claim names no row: it reads only the sources assigned to the # caller, an agent's in its own namespace and any other subject's across the org, - # and only as a service account calling as itself (`_worker_subject`). + # where a turn starts only in a namespace the caller's token writes + # (`_writer_gate`), and only as a service account calling as itself + # (`_worker_subject`). gates = ("row_in_scope", "_authorize_status_read", "namespace_for_id", "_worker_subject") for name in _ROW_SCOPED: src = inspect.getsource(_op(name).handler) diff --git a/tests/unit/test_source_worker_ops.py b/tests/unit/test_source_worker_ops.py index 039080d160..c6389d6e9c 100644 --- a/tests/unit/test_source_worker_ops.py +++ b/tests/unit/test_source_worker_ops.py @@ -25,7 +25,8 @@ import pytest -from server.core import ratelimit, shielded +from server.auth import authz, service_accounts +from server.core import grant_cache, ratelimit, shielded from server.core.errors import LoomServerError from server.core.ratelimit import DEFAULT_LIMITS, DEFAULT_ORG_LIMITS, Limit, Limiter, op_class_for from server.knowledge.api.models_source_worker import ( @@ -252,6 +253,10 @@ async def held_by(name: str, holder: str, **_: Any) -> bool: held = await fake.turn_holder(name) return held is not None and not held.stale and held.holder == holder + async def no_creator(org: str, subject: str, **_: Any) -> None: + """No service account here reads through its creator's grants.""" + + monkeypatch.setattr(service_accounts, "inheriting_creator", no_creator) monkeypatch.setattr(ratelimit, "get_limiter", lambda: fake.limiter) monkeypatch.setattr(turns, "store", fake) monkeypatch.setattr(source_ops, "store", fake) @@ -399,6 +404,86 @@ def test_a_service_worker_claims_across_namespaces(world: _World) -> None: assert _claim(_service("sa:wiki-sync")).status == "none" +def test_a_service_worker_is_offered_no_source_its_token_cannot_write( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """Fails when a claim starts a turn, or takes a turn lease, on a source in a + namespace where the calling token does not hold the writer role, when such a source + hides the caller's next due one, or when the role costs a read for each source.""" + world.assign("guide", namespace=DOCS, worker_subject=SERVICE) + for name in ("manual", "runbook"): + world.assign(name, namespace=OPS, worker_subject=SERVICE) + world.assign("handbook", namespace="team-hr", worker_subject=SERVICE) + # Only `guide` ran a turn, so every other source has been due longer. + world.states["guide"] = { + "state_value": "", + "detail": json.dumps({"turn_ended_at": "2026-02-28T09:00:00+00:00"}), + } + rows: list[str] = [] + grant_reads: list[str] = [] + read_row = world.get_source + + async def get_source(org: str, namespace: str, name: str) -> KnowledgeSource | None: + rows.append(name) + return await read_row(org, namespace, name) + + async def grants_of(org: str, subject: str) -> grant_cache.GrantMap: + grant_reads.append("every namespace") + return grant_cache.GrantMap(ranks={}) + + async def grant_on(org: str, namespace: str, subject: str) -> None: + grant_reads.append(namespace) + + monkeypatch.setattr(world, "get_source", get_source) + monkeypatch.setattr(grant_cache, "_read", grants_of) + monkeypatch.setattr(authz, "grant_role_for", grant_on) + at = {"namespace": DOCS, "name": "guide"} + # A writer of one namespace, and one that only reads the others. + writes_docs = principal("writer", subject=SERVICE, namespaces=(DOCS,)) + reads_the_rest = principal( + subject=SERVICE, + namespaces=(DOCS, OPS, "team-hr"), + ns_roles=((DOCS, "writer"), (OPS, "viewer"), ("team-hr", "viewer")), + ) + for token in (writes_docs, reads_the_rest): + grant_cache.clear() + turn = _claim(token) + assert (turn.source.namespace, turn.source.name) == (DOCS, "guide") + # No lease and no row read where the turn could not be committed, and the + # caller's grants read once for the three sources passed over. + assert list(world.leases) == [domain.turn_lease_name(ORG, DOCS, "guide")] + assert (rows, grant_reads) == (["guide"], ["every namespace"]) + assert _done(turn.claim, auth=token, **at).next_due_s == INTERVAL + # A later poll is answered the same: nothing until `guide` is due again. + waiting = _claim(token) + assert (waiting.status, waiting.retry_after_s, world.leases) == ("none", INTERVAL, {}) + world.tick(INTERVAL) + rows.clear() + grant_reads.clear() + # The sentinel: a token that writes every namespace is offered the others first. + everywhere = principal("writer", subject=SERVICE, namespaces=(DOCS, OPS, "team-hr")) + assert [_claim(everywhere).source.name for _ in range(3)] == ["handbook", "manual", "runbook"] + + +def test_a_claim_offers_nothing_while_the_callers_role_cannot_be_resolved( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """Fails when a claim across the org starts a turn or keeps a lease although the + caller's grants could not be read, or when an agent's claim, which reads its own + namespace, starts to depend on that read.""" + world.assign("guide", namespace=DOCS, worker_subject=SERVICE) + world.assign("notes") + + async def unread(org: str, subject: str) -> grant_cache.GrantMap: + raise ConnectionError("no grant row was read") + + monkeypatch.setattr(grant_cache, "_read", unread) + with pytest.raises(LoomServerError) as refused: + _claim(_service()) + assert refused.value.status_code == 503 and world.leases == {} + assert _claim().source.name == "notes" + + def test_a_source_rewritten_since_the_poll_read_it_starts_no_turn( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: