diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md
index 2ea5d856b5c..389eb864537 100644
--- a/docs/architecture/rolling-upgrades.md
+++ b/docs/architecture/rolling-upgrades.md
@@ -1710,6 +1710,23 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline
`tests/unit/test_code_review_brief_mirror.py` checks N's side, and the mixed-version
gate does not check this rule.
+104. **Namespace invitations** (`loom.namespace_invites`, migration
+ `139_namespace_invites.sql`): N-1 serves none of `grants.invite`,
+ `grants.list_invites`, `grants.cancel_invite` and `grants.accept_invite`, and
+ answers one routed to it as an unknown operation. N's dashboard sends a person's
+ add to `grants.invite`, so while N-1 serves, an add or an acceptance can fail on an
+ N-1 replica and succeed on a retry that reaches N. N-1's in-use check of a new name
+ does not count an open invitation: a name retired with one outstanding can be
+ registered as new on an N-1 replica, and the link would then grant on the new
+ owner's namespace; cancel open invitations before retiring a name during the
+ rollout. N-1's user erasure does not take the user off the invitations they made:
+ one an N-1 replica runs leaves their `user:` as an invitation's `created_by`
+ until the TTL drops the row, a week after the link expires. Those links admit
+ nobody, since the erasure revoked the user's grants, and the erasure's residue
+ check does not count the table. After a rollback the table stays, its rows dropped
+ by TTL a week after they expire. No gate holds the rollout, and the mixed-version
+ gate does not check this rule.
+
## What checks them
`scripts/gates/mixed_version.py` (`make test-mixed-version`, the `mixed-version` CI job,
diff --git a/docs/architecture/security.md b/docs/architecture/security.md
index 33e979c9985..c6e89f81052 100644
--- a/docs/architecture/security.md
+++ b/docs/architecture/security.md
@@ -989,38 +989,39 @@ which says only that a change is running. In use means a `loom.namespaces` row,
configured code-plane repository or tracker namespace, any row in a table the erasure
census counts by namespace (`census.namespace_tables`), tombstoned or not, a live row in
a table whose rows a later owner would inherit (`namespace_census.STATE_TABLES`: grants,
-webhooks, task inboxes, sources and the like), or, on the Postgres authority, a memory
-there (`steps_pg.pg_holds_namespace`). Every other table keyed by namespace is exempt
-with a reason (`tests/unit/test_in_use_coverage.py`), which a new table cannot skip. A
-namespace can hold such rows without a registry row when auto-registration failed or was
-off, for data older than it, and for a grant made before the first write. The ClickHouse
-read is one statement that stops at the first row in each table
-(`server/identity/store/namespace_census.py`, `in_use`), read under the name's claim and
-the account's (`account_change`, which `namespace.register` and `namespace.restore` hold
-too) with sequential consistency; when it cannot be read the sign-up fails and nothing
-is provisioned. The personal-namespace auto-claim passes over a name in use to its
-fallback name, a workload trust's exchange refuses an agent name in use, and a first
-write's auto-registration names no owner on a name in use (rows a read or a run leaves
-aside, `namespace_autoregister.READ_TRACES`, which a fresh `namespace.register` still
-counts), so only an admin of the name completes the registration, a writer that is one
-included. It names none either for a token of another org (a platform administrator's,
-`namespace_autoregister.maybe_autoregister`): a name in a tenant org is that org's to
-own. The exchange sets aside the rows a request writes about itself under the name it
-names (`namespace_census.REQUEST_TRACES`: a latency reading, an exposure, a search
-trace), so a lookup of an agent's name before its first exchange does not take the name
-from the agent; a run's ledger row counts there. Every other path that registers a name
-as new and makes its caller admin (`namespace.register`, `namespace.restore` into a
-fresh target, `collection.create`, a self-service code repository or tracker source,
-which checks again under the account's claim after its remote probe) refuses a name in
-use unless the caller passes the gate's ADMIN check on it, within its token's limit on
-the name (`registration.refused_as_in_use`; for a collection name outside the tree, a
-platform admin). The refusal is the one a registered name's non-admin gets; the time it
-takes may still differ, as a registered name is answered before the in-use read. With
-auth off nobody is refused. An operator gives such a namespace an owner: `loom
-namespaces-adopt` registers the ones holding live memory, and an admin grant covers the
-rest, an ownerless auto-registered row (`owner_email = ''`, tagged `auto-registered`)
-included. An auto-registered row written before first writes checked for use may name an
-owner of a name that held another identity's data; an operator reviews rows tagged
+open invitations, webhooks, task inboxes, sources and the like), or, on the Postgres
+authority, a memory there (`steps_pg.pg_holds_namespace`). Every other table keyed by
+namespace is exempt with a reason (`tests/unit/test_in_use_coverage.py`), which a new
+table cannot skip. A namespace can hold such rows without a registry row when
+auto-registration failed or was off, for data older than it, and for a grant made before
+the first write. The ClickHouse read is one statement that stops at the first row in
+each table (`server/identity/store/namespace_census.py`, `in_use`), read under the
+name's claim and the account's (`account_change`, which `namespace.register` and
+`namespace.restore` hold too) with sequential consistency; when it cannot be read the
+sign-up fails and nothing is provisioned. The personal-namespace auto-claim passes over
+a name in use to its fallback name, a workload trust's exchange refuses an agent name in
+use, and a first write's auto-registration names no owner on a name in use (rows a read
+or a run leaves aside, `namespace_autoregister.READ_TRACES`, which a fresh
+`namespace.register` still counts), so only an admin of the name completes the
+registration, a writer that is one included. It names none either for a token of another
+org (a platform administrator's, `namespace_autoregister.maybe_autoregister`): a name in
+a tenant org is that org's to own. The exchange sets aside the rows a request writes
+about itself under the name it names (`namespace_census.REQUEST_TRACES`: a latency
+reading, an exposure, a search trace), so a lookup of an agent's name before its first
+exchange does not take the name from the agent; a run's ledger row counts there. Every
+other path that registers a name as new and makes its caller admin
+(`namespace.register`, `namespace.restore` into a fresh target, `collection.create`, a
+self-service code repository or tracker source, which checks again under the account's
+claim after its remote probe) refuses a name in use unless the caller passes the gate's
+ADMIN check on it, within its token's limit on the name
+(`registration.refused_as_in_use`; for a collection name outside the tree, a platform
+admin). The refusal is the one a registered name's non-admin gets; the time it takes may
+still differ, as a registered name is answered before the in-use read. With auth off
+nobody is refused. An operator gives such a namespace an owner: `loom namespaces-adopt`
+registers the ones holding live memory, and an admin grant covers the rest, an ownerless
+auto-registered row (`owner_email = ''`, tagged `auto-registered`) included. An
+auto-registered row written before first writes checked for use may name an owner of a
+name that held another identity's data; an operator reviews rows tagged
`auto-registered` and not `adopted`, with an owner, and re-registers one as its admin.
Two kinds of use leave nothing to find. A flat token minted for a name
diff --git a/docs/architecture/sharing.md b/docs/architecture/sharing.md
index 7654d0af723..d014a53209e 100644
--- a/docs/architecture/sharing.md
+++ b/docs/architecture/sharing.md
@@ -200,6 +200,103 @@ admin. The group lands in that org; a member is a user id, held as `user:`.
Membership is read by Loom on every request, never claimed by a token, so removing a
member takes effect within the consistency window below.
+## Invitations
+
+`grants.invite` gives a person a role by what an admin knows of them. An email verified
+for an account (an SSO account or an `sso_links` row) is granted at once through
+`grants.create`, under that account's handle. So is a login handle an account's row is
+owned under, or a live grant in the org is stored under (a person whose tokens Loom did
+not mint at sign-in has no account row), under the spelling stored for it. The answer
+names the subject as `grants.create` writes it: a handle that is itself another
+account's verified email moves onto that account's handle. Only a verified tie counts
+for an email: a row's `owner_email` and a grant's subject are whatever their writer
+typed, and `namespace.register` takes any owner. A request with no token, which only a
+server with auth off serves, grants any other person as typed: no one signs in there to
+accept a link. Any other email, one plain address as sign-up checks it (a dot-atom local
+part and a domain IDNA encodes, so no list, display name or comment), gets an
+invitation: a `loom.namespace_invites` row and the link
+`/spaces#invite=&org=…&namespace=…`. The link is the credential. Only the
+secret's SHA-256 is stored, as the row's `invite_id`, and the link works once, for seven
+days by default (`invite_ttl_seconds`). The server emails it when `smtp_url`,
+`mail_from` and `public_base_url` are set; otherwise, or when the send fails, the answer
+carries the link for the admin to pass on. An invitation is made only on an active
+namespace, where its link can be accepted. With a token, a handle no account or live
+grant holds is refused with 404, so a typo is never kept as a grant for whoever signs up
+under that handle later.
+
+Where sign-in is single sign-on only (`oauth_login_provider = "oidc"`), the identity
+provider verifies every account's email, so an email no account holds is granted as typed
+through `grants.create` instead, and reaches that person at their first sign-in. There is
+no link to pass on. The address is checked as for a link: a list, a display name or a
+domain without a dot is refused, since no identity provider signs anyone in as it.
+
+For a person whose tokens Loom does not mint at sign-in (an upstream gateway's,
+`loom mint-token`'s, or a trusted caller's on their behalf), a handle Loom has not seen
+yet is refused, and an email gets a link too, accepted by whoever opens it signed in.
+Only an admin through a grant makes one: an admin whose role there is only a token's
+claim is refused, as below. `grants.create` grants either as typed, for a subject the
+token's minter names. The `gateway` identity provider does not mark such a server: a
+password server with sign-up off infers it too, and there a grant by email would reach
+nobody.
+
+The server's mail is no relay for a namespace admin, whom any sign-up can make: it emails
+at most 100 invitations an hour per org, which more sign-ups do not multiply, 20 an hour
+per inviter and 3 a day per mailbox (an address with its `+tag` and the dots of its local
+part dropped and its domain in IDNA's ASCII form, since a provider may ignore them; two
+people whose addresses differ only so share one limit), counted in `loom.auth_attempts`
+across the deployment (`server.auth.attempts`). Past any limit the invitation is still
+made, and its link is the inviter's to pass on.
+
+`grants.accept_invite` gives the invitation's role to the signed-in caller, under the
+handle they sign in with, stamped `granted_by` the invitation's maker. Only a person's
+token accepts: a service account, a grant principal, a trusted caller acting for someone
+(the person opens the link signed in themselves) or a token of another org is refused. A
+namespace-scoped token (one with `ns_roles`) is answered 400 `IDENTITY_INCOMPLETE` at the
+gate, as for every op that checks no namespace role there: the person accepts signed in,
+or with a token that carries no namespace roles. Under a lease per invitation
+(`grant_claims.invite_change`) it checks that the link is open, the namespace active and
+the maker still an admin, and marks the invitation accepted. It grants after leaving the
+lease, so the grant's own claims, and an admin grant's fan-out to a repository's branches,
+are never taken under it. One link never admits two people: after a failed grant the link
+opens again only when no grant at or above its role stands, so a failure after the grant
+row landed (a lost reply, a step after the write) leaves it used. A higher role the
+caller holds already stands. Its accepter opening the link again, as after a reply that
+was lost, is answered the role they hold now and writes nothing, while that role is at
+least the invitation's, even after an admin cancelled the used link. A lower role or
+none is answered as used: the grant failed and the link could not be reopened, or it was
+lowered or revoked since. So is a retry that lands while the first accept's grant is
+still being written, as the grant runs in that request right after the spend: the server
+has no request deadline to tell a grant still running from one that is gone. The
+dashboard sends one accept per link at a time, so its own second press never lands
+there.
+
+An invitation never outlasts its maker's admin. Its maker is the account the admin
+rests on: the caller, or a delegated token's creator, whose live grant holds the token to
+it. `grants.invite` and `grants.accept_invite` both read that account's grants as the gate
+reads them (`authz.subject_grant_role`): on a collection its own, its groups' and
+everyone's, there or on a collection above; elsewhere its grant, or an inheriting service
+account's creator's. The maker's account must also be active and their subject not
+revoked, as for a token they delegated (`delegation.creator_account_active`,
+`revocation.is_revoked` at the time the link was made). Short of any of these, the link is
+not made, or admits nobody; a failed read answers 503, so the dashboard keeps the link. An
+admin whose token alone makes them one (a platform admin, an operator's token) holds no
+grant that a later read could tell from a revoked one, so they cannot make a link: an
+admin through a grant invites the person. The open invitations name each maker, and
+`grants.list_invites` marks a link whose maker does not stand now `stopped`: it admits
+nobody while they do not, and again if they come to stand again, as a delegated token
+does; only a cutoff of the maker's tokens after the link was made ends it. It holds the
+name until it is cancelled or expires.
+
+Self sign-up makes accounts in `self_signup_org` only. On a password server, a link to a
+namespace of another org is accepted by an account an operator made there.
+
+A password account's email is never verified, which is why an email reaches one only
+through an invitation: the link went to that address, and opening it proves the reader
+got it. The whole link is a fragment, which a browser never sends to a server or puts in a
+Referer. Namespaces in your org moves it out of the address into the tab's session
+storage, where it waits until the person accepts it or closes the card, or the server
+refuses it; where the browser refuses that storage, the page holds it until it reloads.
+
## Consistency
Every change to a grant, a group or the tree writes a row to `loom.acl_versions` for its
@@ -288,22 +385,25 @@ replaced, so none reads as live again. It deletes their uploaded originals that
writer's live document shares (each upload by an end user is recorded in
`loom.blob_uploads`, because the document version that named it may have been replaced and
merged away since), revokes and then deletes every grant naming `user:`, blanks their
-id as the issuer of the grants they gave others (those grants stay), removes them from
-every group, blanks their id as the creator of the collections they made (the collections
-stay), and retires their personal collection's directory row (`namespace.delete` and
-`collection.delete` refuse a personal collection: it goes only with its user's erasure).
-The request ledger keeps the user's calls for cost with their `user:` subject
-scrubbed, and the user's newest-call row is deleted. Deleting a SCIM group revokes the
-grants that named it, so a group made later under the same id starts with none.
-Collections that hold other writers' documents stay: Loom deletes only what its writer
-asked to delete. `collection.delete` purges what its collection held (a namespace erasure
-that takes the rows off disk) before the collection leaves the tree. A user-scope
-`erasure.export` returns the chunks and the conversation rows (transcript turns, saved
-messages and threads) that user owns in the collections its caller may read, and in the
-user's own personal collection. An org admin may erase a collection's rows without
-reading them; a platform admin sees every collection. Each section's read leaves out what
-the caller may not see before its limit, so a hidden row never takes a visible row's place
-on the page.
+id as the issuer of the grants they gave others (those grants stay) and as the maker of
+their invitations, closing the open ones, removes them from every group, blanks their id
+as the creator of the collections they made (the collections stay), and retires their
+personal collection's directory row (`namespace.delete` and `collection.delete` refuse a
+personal collection: it goes only with its user's erasure). An accept or an invitation
+already past its maker check as that step runs can still write their id, as a grant's
+issuer or an invitation's maker, as a `grants.create` in flight can; such a link admits
+nobody, since the step revokes the user's grants first. The request ledger keeps the
+user's calls for cost with their `user:` subject scrubbed, and the user's newest-call
+row is deleted. Deleting a SCIM group revokes the grants that named it, so a group made
+later under the same id starts with none. Collections that hold other writers' documents
+stay: Loom deletes only what its writer asked to delete. `collection.delete` purges what
+its collection held (a namespace erasure that takes the rows off disk) before the
+collection leaves the tree. A user-scope `erasure.export` returns the chunks and the
+conversation rows (transcript turns, saved messages and threads) that user owns in the
+collections its caller may read, and in the user's own personal collection. An org admin
+may erase a collection's rows without reading them; a platform admin sees every
+collection. Each section's read leaves out what the caller may not see before its limit,
+so a hidden row never takes a visible row's place on the page.
## Namespace guides
@@ -376,6 +476,18 @@ One text serves agents and people, so there is no second copy to drift.
principals and differs per user; no one sort order clusters every user's union.
- **Group membership in a token claim.** A claim is fixed until the token expires, so a
removed member keeps access for the token's life.
+- **A confirmation email for every password account.** Verified emails would let a grant
+ by email bind at sign-in, but every server would need mail to sign anyone up; an
+ invitation works with or without mail.
+- **A pending grant by email, bound at the first sign-in under that email.** A password
+ sign-up names any email it likes, so whoever registered the address first would take
+ the grant.
+- **The invitation's secret in the query string.** It would reach access logs and Referer
+ headers.
+- **Binding acceptance to the invited address.** A password account has no verified email
+ to compare, so only the link can prove the address was reached.
+- **Cancelling a maker's invitations when their grant is revoked.** A best-effort cascade
+ would leave a link open when it fails; reading the grant at acceptance fails closed.
- **Inheritance resolved at write time.** Moving a collection would rewrite the grants of
every descendant; resolving at check time from a cached tree costs a walk of at most
eight parents.
diff --git a/docs/architecture/storage-layout.md b/docs/architecture/storage-layout.md
index 628337734a0..435b93ced8f 100644
--- a/docs/architecture/storage-layout.md
+++ b/docs/architecture/storage-layout.md
@@ -944,6 +944,7 @@ copies of tables listed here, owned and removed by that run, and erasure reaches
| `oauth_signin_state` | KeeperMap `claim_key` | Postgres `oauth_signin_state` | SoR | no content | 1 | strict compare-and-set per key with an expiry and optional verified sign-in email metadata: an `UPDATE … WHERE value = $old`; the KeeperMap expiry becomes `expires_at`, read by a sweep; named in `server/auth/claims.py`, `server/cli/secrets.py` |
| `grant_claims` | KeeperMap `claim_key` | delete | Coord | no content | 1 | no code path writes it (its census entry says so); no module outside the census names the table (`server/auth/grant_claims.py` is the claim module, whose keys are in `_migration_lock`) |
| `namespace_grants` | RMT(version) `(org, namespace, subject)`, by `org` | Postgres `namespace_grants` | SoR | step `grants.revoke` | 1 | every request's role check; a revoke takes effect within the grant cache's invalidation bound; named in `server/identity/store/grants.py`, `server/auth/self_signup.py` |
+| `namespace_invites` | RMT(version) `(org, namespace, invite_id)`, TTL | Postgres `namespace_invites` | SoR | step `grants.revoke` | 1 | an invitation read by `(org, namespace, invite_id)` when its link is accepted or cancelled, the open ones when a namespace's members are shown, the open, unexpired ones by a new name's in-use check, and the ones a user made by that user's erasure; named in `server/identity/store/invites.py` |
| `namespaces` | RMT(updated_at) `(org, namespace)`, by `org` | Postgres `namespaces` + ClickHouse mirror | SoR (head) | step `personal.retire`; step `collections.forget_owner` | 1 | the registry with its per-namespace settings, read by grants, sign-in and request paths through a cache; the mirror serves ClickHouse worker scans and the SQL surface views; named in `server/auth/self_signup.py`, `server/cli/hygiene.py` |
| `collections` | RMT(version) `(org, namespace)` | Postgres `collections` | SoR | step `collections.forget_owner` | 1 | the collection tree grants inherit through; named in `server/identity/store/collections.py`, `server/identity/store/namespace_census.py` |
| `acl_versions` | SMT(changes) `(org, kind)` | merge into Postgres `cache_generations` (kinds `grants`, `groups`, `collections`) | Coord | no content | 1 | a change counter caches poll; a generation row plus `NOTIFY` replaces it; named in `server/core/grant_cache.py` |
@@ -1211,63 +1212,63 @@ a row names a step today's ClickHouse census owns, the `pg:` census row is owned
Postgres step the flip splits off it, which joins `PG_ONLY_STEPS`
([restores](#restores)).
-| Table | Key | Kind | Erasure |
-| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| `authority` | [storage authority](storage-authority.md#the-tables); paired with ClickHouse's `storage_authority` | SoR | no content |
-| `pg_migrations` | the migration file | SoR | no content |
-| `scope_generations` | [storage authority](storage-authority.md#the-tables) | SoR (a namespace's row allocates its revision `seq`) | no content |
-| `cache_generations` | `(org, kind)` | Coord | no content |
-| `memory_current` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.memory_current` |
-| `memory_revisions` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.memory_revisions` |
-| `memory_refusals` | `(org, scope_kind, scope_value, user_id, kind, units, digest)` | SoR, hash-only consent policy committed beside memory; no TTL | no content; retained across erasure |
-| `memory_deliveries` | [storage authority](storage-authority.md#the-tables) | SoR | cascades with its revision |
-| `idempotency`, `idempotency_fences` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.idempotency`; `idempotency_fences` holds no content (the census's bound) |
-| `erased_memories`, `erased_documents` | [storage authority](storage-authority.md#the-tables) | SoR | evidence, no content |
-| `audit_outbox` | [storage authority](storage-authority.md#the-tables) | SoR | keys and ids, no values |
-| `document_catalog`, `document_uploaders` | `(org, namespace, sha256)`, `(org, user_id, namespace, sha256)` | SoR | a `pg:` census row each, owned by the Postgres step the flip splits off the steps that own the census rows of `document_blobs` and `blob_uploads` today, which joins `PG_ONLY_STEPS` (`documents.tombstone`, and the user step through `document_uploaders`) |
-| `knowledge_datasets` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_datasets`, step `pg_knowledge.delete` |
-| `knowledge_jobs` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_jobs`, step `pg_knowledge.delete` |
-| `mcp_worker_enrollment_challenges` | `(org, nonce)` | SoR | one-time account enrollment challenges of a canonical sign-in owner (`subject`; `user_id` is `-`), erased with the collection or by the owner's deletion (`pg_mcp_worker_enrollment.erase_subject`), never by a user erasure; census `pg:loom.mcp_worker_enrollment_challenges`, namespace step `pg_knowledge.delete` |
-| `mcp_worker_accounts` | `(org, connection_id)` | SoR | opaque connection bindings and revocation generations of a canonical sign-in owner (`subject`; `user_id` is `-`), one collection per connection, erased with the collection or by the owner's deletion (`pg_mcp_worker_enrollment.erase_subject`), never by a user erasure; census `pg:loom.mcp_worker_accounts`, namespace step `pg_knowledge.delete` |
-| `mcp_worker_approvals` | `(org, namespace, worker_id, profile_digest)` | SoR | a collection's allowed modes and approval generations, naming no subject (`user_id` is `-`), erased with the collection; census `pg:loom.mcp_worker_approvals`, namespace step `pg_knowledge.delete` |
-| `mcp_worker_source_readers` | `(org, namespace, source_id, subject)` | SoR | explicit team reader bindings of a canonical sign-in reader (`subject`; `user_id` is `-`), erased with the collection or by the reader's deletion (`pg_mcp_worker_enrollment.erase_subject`), never by a user erasure; census `pg:loom.mcp_worker_source_readers`, namespace step `pg_knowledge.delete` |
-| `knowledge_heads`, `knowledge_deliveries` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_heads`, `pg:loom.knowledge_deliveries` |
-| `jobs`, `job_users`, `job_memories` | `(org, id)`, `(org, user_id, job_id)`, `(org, namespace, memory_id, job_id)` | SoR | a census row, a step by namespace and user, a redaction step |
-| `leases`, `write_marks`, `graph_inflight` | `(org, name)`, `(org, namespace, surface)`, `(org, namespace, token)` | Coord | no content |
-| `cursors` | `(org, consumer, scope)` | SoR | no content |
-| `carry_acks` | `process` | Coord | no content |
-| `analysis_secrets` | `id` | SoR | no content |
-| `sql_access` | `(org, namespace, user_name)` | SoR | no content |
-| `cell_self` | singleton | SoR until attach writes its fingerprint to the directory row, then Derived (rewritten from the directory on a restore, [cells](cells.md)) | no content |
-| `tenancy` | `org` | SoR until attach places its org (the first cell's `recording` rows), then Derived (written back from the directory's placements on a restore, never deleted, [cells](cells.md)) | no content; an erasure leaves the org's row |
-| `tenancy_mode` | singleton | Derived (the mode raised only upward from the directory's recorded mode on a restore, [cells](cells.md)) | no content |
-| `cell_first` | singleton | Derived (written when absent and refused when it differs on a restore; written once, its update, delete and truncate refused by triggers, [cells](cells.md)) | no content |
-| `cell_probe` (the probe nonce the `loom cell` commands write, [cells](cells.md)) | `name` | Coord | no content; deleted once the probe has read it |
-| `job_parts` | `(org, job_id, seq)` | SoR | cascades with its job; `code_index.purge` reaches it through the job |
-| `idempotency_revisions` | `(org, key_hash, namespace, seq)` | SoR | cascades with its record; redaction reaches replay answers through it |
-| `revision_relations` | `(org, namespace, seq, ord)` | SoR | census `pg:loom.revision_relations`, step `pg_memory.delete`; cascades with its revision; redaction reaches it through its revision |
-| `revision_sources` | `(org, user_id, namespace, seq)` | SoR | cascades with its revision; the user step deletes the user's rows; the user step and the census reach shared revisions through it |
-| `table_moves`, `move_acks` | `move`, `(move, process)` | SoR, Coord | no content; `table_moves` also holds the registry of kept tables (each kept table's name and scope predicates) |
-| `backfill_steps` | the column, index or check it sets | SoR | no content; the backfill step's completion record, which boots read ([schema rules](#postgres)) |
-| `working_memory`, `records`, `operator_edges`, `context_offloads`, `session_briefs`, `session_brief_revisions`, `namespace_guides`, `skills`, `knowledge_suites`, `learning_candidates`, `learning_supporters`, `conflict_allowlist` | led by `(org, namespace, …)`, the ClickHouse sort key today | SoR | a census row and a saga step each |
-| `knowledge_suite_results` | `(org, namespace, memory_key, suite, recorded_at, id)`: the ClickHouse sort key and an added id per set, as two can share a `recorded_at` | SoR | a census row and the `knowledge_suites.delete` step |
-| `knowledge_suite_drafts` | `(org, namespace, suite, case_id, drafted_at, id)`: the ClickHouse sort key and an added id per row, as a draft and its dismissal can share a `drafted_at` | SoR | a census row and the `knowledge_suites.delete` step |
-| `conversation_states` | `(org, namespace, agent, thread_id, msg_id)` | SoR | a census row and the `conversations.tombstone` step, by namespace and by the saver's `user_id` |
-| `offload_bytes` | `(org, namespace, offload_id, part)`, its head's id and a part number | SoR | deleted with its head by the `context_offloads` step, and counted by its census row |
-| `shared_current` | `(org, namespace, memory_key)` | SoR | a `pg:` census row and the provenance step `shared` has today, through `revision_sources` |
-| `tasks`, `agent_runs` | `(org, inbox, task_id)`, `(org, namespace, run_id)` | SoR | a `pg:` census row each, owned by the Postgres step the flip splits off the step that owns its ClickHouse table's census row today, which joins `PG_ONLY_STEPS` (`tasks` in the namespace scope, `agent_runs` in both) |
-| `task_inboxes`, `task_poster_policies` | `(org, inbox)`, `(org, inbox, poster, kind)` | SoR | no content |
-| `erased_messages` | `(org, erasure_id, namespace, agent, thread_id, msg_id)` | SoR | evidence, no content; the messages a conversation erasure matched by their saver, which its ClickHouse replay reads, swept with its `erasure_ledger` row |
-| `erasure_ledger` | [storage authority](storage-authority.md#the-tables) | SoR | evidence, no content; Postgres's erasure record, which `loom reconcile` runs again after a ClickHouse restore, swept after `erasure_ledger_days` |
-| `record_schemas`, `namespace_visits`, `extraction_policies`, `namespace_policies`, `namespace_types`, `namespace_ontology`, `profile_schemas`, `user_state`, `webhooks`, `knowledge_sources`, `knowledge_mirrors`, `code_repos`, `qa_sources` | led by `org`, as the ClickHouse key | SoR | no memory content |
-| `knowledge_uploads` | led by `org`, as the ClickHouse key | SoR | a `pg:` census row owned by the Postgres step split off `documents.tombstone` ([restores](#restores)) |
-| `code_coverage_watches` | led by `org`, as the ClickHouse key | SoR | no memory content; reached by the Postgres part of `code_index.purge` ([restores](#restores)) |
-| `revoked_tokens` | `(kind, key)`, kind `subject_or_jti` (the bare key, which holds both today), `cutoff` or `scim` | SoR | no content |
-| `signing_keys`, `service_accounts`, `machine_identities`, `scim_users`, `sso_links`, `principal_groups`, `oauth_state`, `oauth_signin_state`, `namespace_grants`, `namespaces`, `collections`, `blacklist`, `org_model_calls` | as the ClickHouse key, `org` first where the table is per org, except the tables of the cell that [keys lead with `org`](#postgres) names | SoR | no memory content; the identity steps (`grants.revoke`, `groups.remove_member`, `personal.retire`, `collections.forget_owner`) rewrite `namespace_grants`, `principal_groups`, `namespaces` and `collections` |
-| `auth_attempts` | kind, hashed key and window | Coord | no content |
-| `deployment_config`, `runtime_overrides`, `provider_configuration`, `assistant_service` | as the ClickHouse key | SoR | no content |
-| `instances` | process | Coord | no content |
-| `embedder_calibration`, `namespace_calibration` | as the ClickHouse key, `org` first for `namespace_calibration` | Derived (rebuilt by a recalibration, at embedding cost) | no content |
+| Table | Key | Kind | Erasure |
+| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `authority` | [storage authority](storage-authority.md#the-tables); paired with ClickHouse's `storage_authority` | SoR | no content |
+| `pg_migrations` | the migration file | SoR | no content |
+| `scope_generations` | [storage authority](storage-authority.md#the-tables) | SoR (a namespace's row allocates its revision `seq`) | no content |
+| `cache_generations` | `(org, kind)` | Coord | no content |
+| `memory_current` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.memory_current` |
+| `memory_revisions` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.memory_revisions` |
+| `memory_refusals` | `(org, scope_kind, scope_value, user_id, kind, units, digest)` | SoR, hash-only consent policy committed beside memory; no TTL | no content; retained across erasure |
+| `memory_deliveries` | [storage authority](storage-authority.md#the-tables) | SoR | cascades with its revision |
+| `idempotency`, `idempotency_fences` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.idempotency`; `idempotency_fences` holds no content (the census's bound) |
+| `erased_memories`, `erased_documents` | [storage authority](storage-authority.md#the-tables) | SoR | evidence, no content |
+| `audit_outbox` | [storage authority](storage-authority.md#the-tables) | SoR | keys and ids, no values |
+| `document_catalog`, `document_uploaders` | `(org, namespace, sha256)`, `(org, user_id, namespace, sha256)` | SoR | a `pg:` census row each, owned by the Postgres step the flip splits off the steps that own the census rows of `document_blobs` and `blob_uploads` today, which joins `PG_ONLY_STEPS` (`documents.tombstone`, and the user step through `document_uploaders`) |
+| `knowledge_datasets` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_datasets`, step `pg_knowledge.delete` |
+| `knowledge_jobs` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_jobs`, step `pg_knowledge.delete` |
+| `mcp_worker_enrollment_challenges` | `(org, nonce)` | SoR | one-time account enrollment challenges of a canonical sign-in owner (`subject`; `user_id` is `-`), erased with the collection or by the owner's deletion (`pg_mcp_worker_enrollment.erase_subject`), never by a user erasure; census `pg:loom.mcp_worker_enrollment_challenges`, namespace step `pg_knowledge.delete` |
+| `mcp_worker_accounts` | `(org, connection_id)` | SoR | opaque connection bindings and revocation generations of a canonical sign-in owner (`subject`; `user_id` is `-`), one collection per connection, erased with the collection or by the owner's deletion (`pg_mcp_worker_enrollment.erase_subject`), never by a user erasure; census `pg:loom.mcp_worker_accounts`, namespace step `pg_knowledge.delete` |
+| `mcp_worker_approvals` | `(org, namespace, worker_id, profile_digest)` | SoR | a collection's allowed modes and approval generations, naming no subject (`user_id` is `-`), erased with the collection; census `pg:loom.mcp_worker_approvals`, namespace step `pg_knowledge.delete` |
+| `mcp_worker_source_readers` | `(org, namespace, source_id, subject)` | SoR | explicit team reader bindings of a canonical sign-in reader (`subject`; `user_id` is `-`), erased with the collection or by the reader's deletion (`pg_mcp_worker_enrollment.erase_subject`), never by a user erasure; census `pg:loom.mcp_worker_source_readers`, namespace step `pg_knowledge.delete` |
+| `knowledge_heads`, `knowledge_deliveries` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_heads`, `pg:loom.knowledge_deliveries` |
+| `jobs`, `job_users`, `job_memories` | `(org, id)`, `(org, user_id, job_id)`, `(org, namespace, memory_id, job_id)` | SoR | a census row, a step by namespace and user, a redaction step |
+| `leases`, `write_marks`, `graph_inflight` | `(org, name)`, `(org, namespace, surface)`, `(org, namespace, token)` | Coord | no content |
+| `cursors` | `(org, consumer, scope)` | SoR | no content |
+| `carry_acks` | `process` | Coord | no content |
+| `analysis_secrets` | `id` | SoR | no content |
+| `sql_access` | `(org, namespace, user_name)` | SoR | no content |
+| `cell_self` | singleton | SoR until attach writes its fingerprint to the directory row, then Derived (rewritten from the directory on a restore, [cells](cells.md)) | no content |
+| `tenancy` | `org` | SoR until attach places its org (the first cell's `recording` rows), then Derived (written back from the directory's placements on a restore, never deleted, [cells](cells.md)) | no content; an erasure leaves the org's row |
+| `tenancy_mode` | singleton | Derived (the mode raised only upward from the directory's recorded mode on a restore, [cells](cells.md)) | no content |
+| `cell_first` | singleton | Derived (written when absent and refused when it differs on a restore; written once, its update, delete and truncate refused by triggers, [cells](cells.md)) | no content |
+| `cell_probe` (the probe nonce the `loom cell` commands write, [cells](cells.md)) | `name` | Coord | no content; deleted once the probe has read it |
+| `job_parts` | `(org, job_id, seq)` | SoR | cascades with its job; `code_index.purge` reaches it through the job |
+| `idempotency_revisions` | `(org, key_hash, namespace, seq)` | SoR | cascades with its record; redaction reaches replay answers through it |
+| `revision_relations` | `(org, namespace, seq, ord)` | SoR | census `pg:loom.revision_relations`, step `pg_memory.delete`; cascades with its revision; redaction reaches it through its revision |
+| `revision_sources` | `(org, user_id, namespace, seq)` | SoR | cascades with its revision; the user step deletes the user's rows; the user step and the census reach shared revisions through it |
+| `table_moves`, `move_acks` | `move`, `(move, process)` | SoR, Coord | no content; `table_moves` also holds the registry of kept tables (each kept table's name and scope predicates) |
+| `backfill_steps` | the column, index or check it sets | SoR | no content; the backfill step's completion record, which boots read ([schema rules](#postgres)) |
+| `working_memory`, `records`, `operator_edges`, `context_offloads`, `session_briefs`, `session_brief_revisions`, `namespace_guides`, `skills`, `knowledge_suites`, `learning_candidates`, `learning_supporters`, `conflict_allowlist` | led by `(org, namespace, …)`, the ClickHouse sort key today | SoR | a census row and a saga step each |
+| `knowledge_suite_results` | `(org, namespace, memory_key, suite, recorded_at, id)`: the ClickHouse sort key and an added id per set, as two can share a `recorded_at` | SoR | a census row and the `knowledge_suites.delete` step |
+| `knowledge_suite_drafts` | `(org, namespace, suite, case_id, drafted_at, id)`: the ClickHouse sort key and an added id per row, as a draft and its dismissal can share a `drafted_at` | SoR | a census row and the `knowledge_suites.delete` step |
+| `conversation_states` | `(org, namespace, agent, thread_id, msg_id)` | SoR | a census row and the `conversations.tombstone` step, by namespace and by the saver's `user_id` |
+| `offload_bytes` | `(org, namespace, offload_id, part)`, its head's id and a part number | SoR | deleted with its head by the `context_offloads` step, and counted by its census row |
+| `shared_current` | `(org, namespace, memory_key)` | SoR | a `pg:` census row and the provenance step `shared` has today, through `revision_sources` |
+| `tasks`, `agent_runs` | `(org, inbox, task_id)`, `(org, namespace, run_id)` | SoR | a `pg:` census row each, owned by the Postgres step the flip splits off the step that owns its ClickHouse table's census row today, which joins `PG_ONLY_STEPS` (`tasks` in the namespace scope, `agent_runs` in both) |
+| `task_inboxes`, `task_poster_policies` | `(org, inbox)`, `(org, inbox, poster, kind)` | SoR | no content |
+| `erased_messages` | `(org, erasure_id, namespace, agent, thread_id, msg_id)` | SoR | evidence, no content; the messages a conversation erasure matched by their saver, which its ClickHouse replay reads, swept with its `erasure_ledger` row |
+| `erasure_ledger` | [storage authority](storage-authority.md#the-tables) | SoR | evidence, no content; Postgres's erasure record, which `loom reconcile` runs again after a ClickHouse restore, swept after `erasure_ledger_days` |
+| `record_schemas`, `namespace_visits`, `extraction_policies`, `namespace_policies`, `namespace_types`, `namespace_ontology`, `profile_schemas`, `user_state`, `webhooks`, `knowledge_sources`, `knowledge_mirrors`, `code_repos`, `qa_sources` | led by `org`, as the ClickHouse key | SoR | no memory content |
+| `knowledge_uploads` | led by `org`, as the ClickHouse key | SoR | a `pg:` census row owned by the Postgres step split off `documents.tombstone` ([restores](#restores)) |
+| `code_coverage_watches` | led by `org`, as the ClickHouse key | SoR | no memory content; reached by the Postgres part of `code_index.purge` ([restores](#restores)) |
+| `revoked_tokens` | `(kind, key)`, kind `subject_or_jti` (the bare key, which holds both today), `cutoff` or `scim` | SoR | no content |
+| `signing_keys`, `service_accounts`, `machine_identities`, `scim_users`, `sso_links`, `principal_groups`, `oauth_state`, `oauth_signin_state`, `namespace_grants`, `namespace_invites`, `namespaces`, `collections`, `blacklist`, `org_model_calls` | as the ClickHouse key, `org` first where the table is per org, except the tables of the cell that [keys lead with `org`](#postgres) names | SoR | no memory content; the identity steps (`grants.revoke`, `groups.remove_member`, `personal.retire`, `collections.forget_owner`) rewrite `namespace_grants`, `namespace_invites`, `principal_groups`, `namespaces` and `collections` |
+| `auth_attempts` | kind, hashed key and window | Coord | no content |
+| `deployment_config`, `runtime_overrides`, `provider_configuration`, `assistant_service` | as the ClickHouse key | SoR | no content |
+| `instances` | process | Coord | no content |
+| `embedder_calibration`, `namespace_calibration` | as the ClickHouse key, `org` first for `namespace_calibration` | Derived (rebuilt by a recalibration, at embedding cost) | no content |
A sweep deletes a `revoked_tokens` row ten days past its stored `expires_at`, as the
ClickHouse TTL does today; a token without `exp`, an operator cutoff and every SCIM
diff --git a/docs/features/dashboard.md b/docs/features/dashboard.md
index 37c43e07419..4cd9f0903f8 100644
--- a/docs/features/dashboard.md
+++ b/docs/features/dashboard.md
@@ -158,15 +158,25 @@ site describes the latest `main`, which can be ahead of the running release.
On Namespaces in your org, a search for the exact name of a namespace the list does not
show offers **Request access**, which is how a private namespace is asked for by name; a
-repository's or collection's name points to Repositories or the Library instead. **Invite**
-on a namespace you manage opens its members on the add field. The field takes a person's
-login handle, which their account menu shows under **Signed in as** and which may be an
+repository's or collection's name points to Repositories or the Library instead.
+**Invite** on a namespace you manage opens its members on the add field. The field takes
+a person's login handle, which their account menu shows under **Signed in as**, an
email, or a service account `sa:`. A collection's **Share** also takes a group
-`group:`, an agent `agent:` or `everyone`. An email that is not a login handle reaches its owner only
-once they sign in with it through single sign-on, or an operator links it to their account.
-Until then the grant is kept as typed and reaches nobody. With sign-in on, **Settings** ›
-**Tokens** links to Namespaces in your org for giving a person access: a token is for a tool,
-agent or script.
+`group:`, an agent `agent:` or `everyone`. A login handle no account or live
+grant holds is refused. An email is granted at once only when it is verified for an
+account; any other email gets an
+[invitation](namespaces-and-sharing.md#membership-and-grants). The add shows its link to
+copy, and the server emails it when it sends mail. The members dialog and a repository's
+Access tab list it under **Invited**, with who made it and **Cancel**, until it is
+accepted, cancelled or expired. One whose maker's admin, account or tokens no longer
+stand behind it admits nobody now, is marked stopped, and holds the name until it is
+cancelled or expires. Where sign-in is single sign-on only, the email is granted instead
+and reaches that person at their first sign-in. With auth off, a handle no account or
+live grant holds, or an email no account has verified, is granted as typed instead.
+Whoever opens the link signed in accepts it on Namespaces in your org, which then
+switches to the namespace; a collection opens in the Library. With sign-in on,
+**Settings** › **Tokens** links to Namespaces in your org for giving a person access: a
+token is for a tool, agent or script.
A collection's **Share**, and the members of a namespace or a repository, tell whoever can
change the members what a change does to the documents imported there, one sentence per
diff --git a/docs/features/namespaces-and-sharing.md b/docs/features/namespaces-and-sharing.md
index 6397b394a2d..bca2e2c967e 100644
--- a/docs/features/namespaces-and-sharing.md
+++ b/docs/features/namespaces-and-sharing.md
@@ -74,18 +74,34 @@ account, or a service account `sa:`) a role on one namespace: `viewer` rea
namespaces it may reach; the grant table decides the role. A platform admin reaches
every standard namespace without either ([the gate](../architecture/security.md#the-gate)).
-| Operation | Role | Does |
-| -------------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| `grants.create` | admin | Grant a role. A create below the subject's current role is refused with 409 `GRANT_WOULD_DOWNGRADE` unless `replace=true`. |
-| `grants.list` | viewer | Who has access, at which role, and any `pending_role`. |
-| `grants.revoke` | admin | Remove a grant. |
-| `grants.approve` | admin | Approve or reject a pending request, optionally with a different role. |
-| `grants.pending_for_me` | viewer | Every pending request in the namespaces the caller administers, org-wide. |
-| `namespace.browse` | viewer | Public namespaces in the org, never a collection (`closed` ones only with `include_closed`). |
-| `namespace.join` | viewer | Self-join a public namespace. `viewer` is granted at once; a `writer` or `admin` request always lands pending, with no access until an admin approves. |
-| `namespace.leave`, `namespace.cancel_request`, `namespace.mark_seen` | viewer | Drop one's own grant, withdraw a pending request, acknowledge an invitation. |
-| `namespace.list_mine` | viewer | The namespaces the caller belongs to, each with its `kind` (`collection` for a collection) and `title`. |
-| `namespace.list` | org admin | Every namespace in the org. |
+| Operation | Role | Does |
+| -------------------------------------------------------------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `grants.create` | admin | Grant a role. A create below the subject's current role is refused with 409 `GRANT_WOULD_DOWNGRADE` unless `replace=true`. |
+| `grants.invite` | admin | Give a person a role by login handle or email. A handle an account or live grant holds, or an email verified for one, is granted at once; any other email gets a single-use invitation link, emailed when the server has mail settings, or, under single sign-on only, a grant as typed. Any other handle is refused. A request with no token, which only auth off serves, grants any other handle or email as typed. |
+| `grants.list_invites`, `grants.cancel_invite` | admin | The open invitations, and withdraw one. |
+| `grants.accept_invite` | a signed-in person | Accept an invitation link: its role goes to the account the caller signs in as. |
+| `grants.list` | viewer | Who has access, at which role, and any `pending_role`. |
+| `grants.revoke` | admin | Remove a grant. |
+| `grants.approve` | admin | Approve or reject a pending request, optionally with a different role. |
+| `grants.pending_for_me` | viewer | Every pending request in the namespaces the caller administers, org-wide. |
+| `namespace.browse` | viewer | Public namespaces in the org, never a collection (`closed` ones only with `include_closed`). |
+| `namespace.join` | viewer | Self-join a public namespace. `viewer` is granted at once; a `writer` or `admin` request always lands pending, with no access until an admin approves. |
+| `namespace.leave`, `namespace.cancel_request`, `namespace.mark_seen` | viewer | Drop one's own grant, withdraw a pending request, record a visit (clears the namespace's new mark). |
+| `namespace.list_mine` | viewer | The namespaces the caller belongs to, each with its `kind` (`collection` for a collection) and `title`. |
+| `namespace.list` | org admin | Every namespace in the org. |
+
+A password account's email is never verified, so a grant by email reaches such an
+account only through an invitation. The link is `/spaces#invite=…` on the dashboard,
+works once, within seven days by default (`LOOM_INVITE_TTL_SECONDS`), and gives its role
+to whoever opens it signed in, under their own login handle, as granted by the admin who
+made it, while they still stand behind it: their grants make them admin there, their
+account is active, and neither their subject nor their tokens as old as the link are
+revoked. An admin only by token (a platform admin, or an operator's token) makes no
+link: on a password server, `grants.invite` refuses them an email no account has
+verified. To have the server email it, set `LOOM_SMTP_URL`
+(`smtps://user:password@host:465`, or `smtp://…:587` with STARTTLS), `LOOM_MAIL_FROM`
+and `LOOM_PUBLIC_BASE_URL`; without them, or when a send fails, the dashboard shows the
+link to copy. The design is in [sharing](../architecture/sharing.md#invitations).
Minting tokens, service accounts, read scopes and restricted namespaces are covered in
the [tokens and grants guide](../guides/tokens-and-grants.md).
diff --git a/docs/getting-started/connect-a-coding-agent.md b/docs/getting-started/connect-a-coding-agent.md
index fe3312e5439..b21eb91036d 100644
--- a/docs/getting-started/connect-a-coding-agent.md
+++ b/docs/getting-started/connect-a-coding-agent.md
@@ -9,8 +9,11 @@ Loom gives Claude Code, Codex and Cursor shared long-term memory through plugins
tools connected to the same self-hosted server. Invite each teammate to the team's
namespace: **Invite people to this namespace** in the namespace picker, with that namespace
picked, or **Invite** on Namespaces in your org. Each teammate makes their own token, and
-their agents find the facts others save. A teammate without a dashboard account gets a token
-from an operator (`loom mint-token`). Install the plugin or MCP entry below; the next
+their agents find the facts others save. A teammate without an account is invited by email
+and accepts once signed up; where sign-in is single sign-on only, the email is granted and
+reaches them at their first sign-in. Self sign-up makes accounts in `LOOM_SELF_SIGNUP_ORG`
+only, so for a namespace of another org, or where nobody can sign up, an operator makes
+their token (`loom mint-token`). Install the plugin or MCP entry below; the next
session can recall what an agent saved. What the Claude Code and Codex plugins send to
Loom is in [data handling](../features/integrations/claude-code.md#data-handling). Conversation recording
is off by default; the namespace owner turns it on with the **Record conversations**
diff --git a/docs/guides/tokens-and-grants.md b/docs/guides/tokens-and-grants.md
index fa0c2e27068..36f04b98d4b 100644
--- a/docs/guides/tokens-and-grants.md
+++ b/docs/guides/tokens-and-grants.md
@@ -232,13 +232,17 @@ answer to the user (the entity graph, conversation reads, exports, admin ops) is
namespace above what the token carries. Grants add; where the subject holds one, a
token's claim goes no further than it.
-| Op | Role | Does |
-| ----------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------ |
-| `grants.create` | admin | Give `subject` a `role`. Below the subject's current role it answers 409 `GRANT_WOULD_DOWNGRADE` unless `replace: true`. |
-| `grants.revoke` | admin | Remove it; on a restricted namespace the grants of tokens the subject minted there go too. |
-| `grants.list` | viewer | The namespace's grants. |
-| `grants.approve` | admin | Activate a pending join request. Below the subject's current grant it answers 409: an approval never asks to lower one. |
-| `grants.pending_for_me` | viewer | Requests waiting on the caller's approval. |
+| Op | Role | Does |
+| ----------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `grants.create` | admin | Give `subject` a `role`. Below the subject's current role it answers 409 `GRANT_WOULD_DOWNGRADE` unless `replace: true`. |
+| `grants.invite` | admin | Give a person a `role` by login handle or email: a handle an account or live grant holds, or a verified email, is granted at once; any other email gets a single-use invitation link, or, under single sign-on only, a grant as typed. Any other handle is refused (404). A request with no token, which only auth off serves, grants any other handle or email as typed. |
+| `grants.accept_invite` | a signed-in person | Accept an invitation link; its role goes to the account the caller signs in as. |
+| `grants.list_invites` | admin | The open invitations, each marked `stopped` when its maker's grants, account or tokens no longer stand behind it, so it admits nobody now; it keeps the name in use until it is cancelled or expires. |
+| `grants.cancel_invite` | admin | Withdraw an open invitation. |
+| `grants.revoke` | admin | Remove a grant; on a restricted namespace the grants of tokens the subject minted there go too. |
+| `grants.list` | viewer | The namespace's grants. |
+| `grants.approve` | admin | Activate a pending join request. Below the subject's current grant it answers 409: an approval never asks to lower one. |
+| `grants.pending_for_me` | viewer | Requests waiting on the caller's approval. |
```bash
curl -s "$LOOM_BASE_URL/v1/grants.create" -H "Authorization: Bearer $ADMIN_TOKEN" \
@@ -261,7 +265,8 @@ curl -s "$LOOM_BASE_URL/v1/grants.create" -H "Authorization: Bearer $ADMIN_TOKEN
owner proving the password from an SSO sign-in). A self-signup email is not: whoever
typed the address first does not hold the grants written under it, which still cap
that account's claims. Grant a self-signup account under its login handle, the namespace
- it signed up with. A `grants.revoke` of an address no verified account holds, and that
+ it signed up with, or invite its email with `grants.invite`, whose link the person
+ accepts signed in. A `grants.revoke` of an address no verified account holds, and that
never held a row of its own on the namespace, takes the rows stored under each
unverified account naming it, and the grants there of the tokens those accounts made.
When the address held a row of its own there, its revoke also takes the grants of the
diff --git a/docs/guides/without-the-dashboard.md b/docs/guides/without-the-dashboard.md
index f55d5c8b7c6..cf9eb066412 100644
--- a/docs/guides/without-the-dashboard.md
+++ b/docs/guides/without-the-dashboard.md
@@ -77,7 +77,8 @@ are on `agent.account` and `agent.deployment`.
| Namespaces: create, settings | `namespace.register`, `namespace.get`, `namespace.list_mine`, `policy.set`, `blacklist.add` | `agent.namespaces.*`, `agent.policy.*`, `agent.blacklist.*` |
| Join a namespace | `namespace.browse`, `namespace.join`, `namespace.leave` | `agent.client.namespace.join(...)` |
| Approve join requests | `grants.pending_for_me`, then `grants.approve namespace=… subject=… decision=approve` (or `reject`) | `agent.client.grants.pending_for_me()`, `agent.client.grants.approve(...)` |
-| Members and grants | `grants.list`, `grants.create`, `grants.revoke` | `agent.grants.*` |
+| Members and grants | `grants.list`, `grants.invite` (a person), `grants.create` (anyone else), `grants.revoke` | `agent.grants.*`, `agent.client.grants.invite(...)` |
+| Invitations | `grants.list_invites`, `grants.cancel_invite`; the person opens the link and `grants.accept_invite` runs signed in | `agent.client.grants.list_invites(...)`, `.cancel_invite(...)` |
| Who maintains what | `stewardship.list namespace=`, `stewardship.assign`, `stewardship.get` ([stewardship](../features/memory/history-and-provenance.md#stewardship)) | `agent.client.stewardship.list(...)`, `.assign(...)`, `.get(...)` |
| Review what you answer for | `stewardship.list mine:=true`, `memory.get`, `stewardship.review` ([a review](../features/memory/history-and-provenance.md#recording-a-review)) | `agent.client.stewardship.review(...)`, as a signed-in person |
| Review a document you answer for | `stewardship.list mine:=true`, `knowledge.get`, `stewardship.review` ([a review](../features/memory/history-and-provenance.md#recording-a-review)) | `agent.client.stewardship.review(...)`, as a signed-in person |
diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md
index a290e255e05..0dc4a220fff 100644
--- a/docs/operations/consolidation.md
+++ b/docs/operations/consolidation.md
@@ -12,7 +12,7 @@ run, with their settings. To move a whole deployment onto new hosts, see
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Memory namespaces, with their settings, per-type settings, policies and guide | Code-index and mirror namespaces, and collections: the target indexes the repositories again |
| Password accounts, with their argon2id hash, so the person signs in with their old password, and single sign-on accounts with their links under `sso_same_issuer` | Tokens, signing keys and the service accounts', bots' and connected accounts' credentials: the receipt lists each for its owner to set up again |
-| Live grants, under the mapped subjects, with the import as `granted_by` | Pending join requests, revoked grants, groups and the grants of groups, agents and `everyone`, which collections hold |
+| Live grants, under the mapped subjects, with the import as `granted_by` | Pending join requests, open invitations (`grants.invite` links: an admin invites again on the target), revoked grants, groups and the grants of groups, agents and `everyone`, which collections hold |
| Blacklist entries, before any content, each on the created namespaces it reaches | Conversations, session briefs, tasks, promoted shared memories, records, memory evidence, working memory blocks, memory links and category assignments: the manifest counts them per namespace |
| Deletion refusals, after the content, so the target refuses what the source deleted | Extraction policies (the org's own too), the conflict allowlist, ontology entries, profile schemas, memory webhooks, categories, record schemas and dataset approvals: the manifest counts them per namespace for the owners to set up again |
| Live memories with their validity, plus `created_at` and attestation in a created namespace | Documents an end user wrote, which the target could not erase as theirs: the manifest counts them |
diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md
index a2d9b5d4393..359858fdeb6 100644
--- a/docs/reference/configuration.md
+++ b/docs/reference/configuration.md
@@ -138,6 +138,10 @@ Authentication, tokens and identity providers.
| `LOOM_WORKLOAD_EXCHANGES_PER_AGENT` | `int` | `300` | | Workload-token exchanges one agent of a trust (a token with an agent claim) may make in 10 minutes, so one agent's loop cannot spend the trust's. A trust without agents has only `workload_exchanges_per_trust`. |
| `LOOM_SELF_SIGNUP` | `'off' \| 'open'` | `'off'` | | Browser self-signup: "off" (endpoint 404s) or "open" (/v1/auth/self-signup mints JWTs scoped to the requested namespace). A non-loopback bind refuses "open" unless identity_provider is "trust-network", allow_insecure is set, or oauth_login_provider is "oidc" (which closes sign-up). |
| `LOOM_SELF_SIGNUP_ORG` | `str` | `'dev'` | | Default org for self-signed tokens. |
+| `LOOM_SMTP_URL` | `str` | *(unset)* | | The mail server invitations go through: `smtps://user:password@host:465`, or `smtp://` on 587, which must offer STARTTLS. Empty: no email, and the inviter passes the link on. |
+| `LOOM_MAIL_FROM` | `str` | `''` | | The From address of an invitation email, e.g. `Loom `: one ASCII address (quote a display name with `,` or `;`), else refused at load. Empty sends none. |
+| `LOOM_SMTP_TIMEOUT_SECONDS` | `float` | `10.0` | | Seconds an invitation email's whole send may take, at most 30; past it the email is reported not sent and the link is shown to pass on, inside the dashboard's 60 s request. |
+| `LOOM_INVITE_TTL_SECONDS` | `int` | `604800` | | Seconds an invitation link stays valid, from one hour to 30 days: it admits whoever opens it. |
| `LOOM_IDENTITY_PROVIDER` | `'' \| 'single-user' \| 'trust-network' \| 'gateway'` | `''` | | How callers authenticate: "single-user" (no auth, one anonymous identity), "trust-network" (self-signup, first claim wins) or "gateway" (an upstream proxy mints short-lived Loom JWTs with the shared HS256 secret; Loom only validates). Empty = inferred from auth_required and self_signup at boot. |
| `LOOM_DASHBOARD_REDIRECT_URL` | `str` | `''` | | When set, a dashboard page load redirects (302) here instead of serving the SPA (Loom behind an aggregator). Deployment-specific; never hardcode. |
| `LOOM_TRUSTED_CALLERS` | `str` | `''` | | Comma-separated subjects allowed to send `X-Loom-On-Behalf-Of` (a trusted aggregator passing each end-user's identity under one service token). Empty disables the header. |
diff --git a/docs/reference/operations.md b/docs/reference/operations.md
index eb7738996a1..598349013bc 100644
--- a/docs/reference/operations.md
+++ b/docs/reference/operations.md
@@ -125,7 +125,7 @@ python scripts/codegen/docs_reference.py --check # exit 1 when a region is stal
-427 operations in 46 groups. Every op is served at `POST /v1/` and, unless its line says otherwise, as the MCP tool `loom_` (dots become underscores).
+431 operations in 46 groups. Every op is served at `POST /v1/` and, unless its line says otherwise, as the MCP tool `loom_` (dots become underscores).
Columns: **Role** is the minimum role (`viewer` < `writer` < `admin` < `org_admin` < `platform_admin`); **Kind** is `read` (idempotent, viewer, unaudited, writes nothing — MCP `readOnlyHint`), `idempotent` (safe to retry) or `write`; **Listed under `all`** says whether an MCP connection on the `all` toolset lists the op in `tools/list` (`code.*` ops only with `LOOM_MCP_CODE_TOOLS=true`); an op marked `no` is still callable by name or through `loom_op`; an op marked `hidden` is not served over MCP, except where its line on its group's page names the one place that serves it; **Audit** marks ops that leave an `audit_log` row.
@@ -385,9 +385,13 @@ Fields for every `grants` op: [operations/grants.md](operations/grants.md).
| Operation | Summary | Role | Kind | Listed under `all` | Audit |
| --- | --- | --- | --- | --- | --- |
+| [`grants.accept_invite`](operations/grants.md#grantsaccept_invite) | Accept an invitation link as the signed-in person. | viewer | write | no | yes |
| [`grants.approve`](operations/grants.md#grantsapprove) | Approve (or reject) a pending grant request. | admin | idempotent | no | yes |
+| [`grants.cancel_invite`](operations/grants.md#grantscancel_invite) | Cancel an open invitation, so its link admits nobody. | admin | idempotent | no | yes |
| [`grants.create`](operations/grants.md#grantscreate) | Grant another subject (user or service-account) viewer / writer / admin role on a namespace. | admin | idempotent | yes | yes |
+| [`grants.invite`](operations/grants.md#grantsinvite) | Give a person a role on a namespace by login handle or email. | admin | write | no | yes |
| [`grants.list`](operations/grants.md#grantslist) | List active grants on a namespace — who has access, at which role. | viewer | read | yes | |
+| [`grants.list_invites`](operations/grants.md#grantslist_invites) | List a namespace's open invitations. | admin | idempotent | no | |
| [`grants.pending_for_me`](operations/grants.md#grantspending_for_me) | Every pending request in the namespaces the caller administers, in one statement. | viewer | read | no | |
| [`grants.revoke`](operations/grants.md#grantsrevoke) | Remove a subject's grant on a namespace. | admin | idempotent | no | yes |
| [`grants.share_agent`](operations/grants.md#grantsshare_agent) | Let another agent of the caller's trust read, or write, the caller's own namespace. | writer | idempotent | no | yes |
@@ -641,7 +645,7 @@ Fields for every `namespace` op: [operations/namespace.md](operations/namespace.
| [`namespace.list_categories`](operations/namespace.md#namespacelist_categories) | Enumerate registered categories with item counts. | viewer | read | no | |
| [`namespace.list_mine`](operations/namespace.md#namespacelist_mine) | List namespaces the caller is a member of (own + granted). | viewer | read | yes | |
| [`namespace.list_ontology`](operations/namespace.md#namespacelist_ontology) | List the ontology terms (entity and relation kinds) registered for a namespace. | viewer | read | no | |
-| [`namespace.mark_seen`](operations/namespace.md#namespacemark_seen) | Acknowledge a new-invitation indicator on a namespace. | viewer | idempotent | no | |
+| [`namespace.mark_seen`](operations/namespace.md#namespacemark_seen) | Record a visit to a namespace, clearing its new mark. | viewer | idempotent | no | |
| [`namespace.register`](operations/namespace.md#namespaceregister) | Create a shared memory workspace within an org; caller becomes admin. | viewer | idempotent | yes | yes |
| [`namespace.register_category`](operations/namespace.md#namespaceregister_category) | Register a category in a namespace. | writer | write | no | yes |
| [`namespace.register_ontology`](operations/namespace.md#namespaceregister_ontology) | Register an entity type or relation verb for a namespace. | admin | idempotent | yes | yes |
diff --git a/docs/reference/operations/grants.md b/docs/reference/operations/grants.md
index 7018756c8d4..05c4e30a6b0 100644
--- a/docs/reference/operations/grants.md
+++ b/docs/reference/operations/grants.md
@@ -8,6 +8,23 @@ Every op is served at `POST /v1/` over HTTP and, unless its line says otherw
+## `grants.accept_invite`
+
+Accept an invitation link as the signed-in person.
+
+`POST /v1/grants.accept_invite` · MCP `loom_grants_accept_invite` · role `viewer` · write · audited · not listed under the MCP `all` toolset
+
+| Input field | Type | Default | Meaning |
+| --- | --- | --- | --- |
+| `org` | `str` | required | The tenant (first element of the identity tuple). |
+| `namespace` | `str` | required | The namespace the link names. |
+| `secret` | `str` | required | The secret from the link's fragment. |
+
+| Output field | Type | Meaning |
+| --- | --- | --- |
+| `namespace` | `str` | The namespace the op reads or writes. |
+| `role` | `Literal['viewer', 'writer', 'admin']` | The caller's role on the namespace now: the invitation's or a higher one they held; to its accepter opening the link again, the role they hold. |
+
## `grants.approve`
Approve (or reject) a pending grant request.
@@ -30,6 +47,22 @@ Approve (or reject) a pending grant request.
| `role` | `Literal['viewer', 'writer', 'admin'] \| None` | The role approved (for `reject`, the role the request would have had); None when no grant row existed for the subject. |
| `decided_at` | `datetime` | When the decision was written (UTC). |
+## `grants.cancel_invite`
+
+Cancel an open invitation, so its link admits nobody.
+
+`POST /v1/grants.cancel_invite` · MCP `loom_grants_cancel_invite` · role `admin` · idempotent · audited · not listed under the MCP `all` toolset
+
+| Input field | Type | Default | Meaning |
+| --- | --- | --- | --- |
+| `org` | `str` | required | The tenant (first element of the identity tuple). |
+| `namespace` | `str` | required | The namespace the op reads or writes. |
+| `invite_id` | `str` | required | The invitation, as grants.invite and grants.list_invites return it. |
+
+| Output field | Type | Meaning |
+| --- | --- | --- |
+| `cancelled` | `bool` | True when an open invitation was cancelled; false when none was open under the id. |
+
## `grants.create`
Grant another subject (user or service-account) viewer / writer / admin role on a namespace.
@@ -53,6 +86,30 @@ Grant another subject (user or service-account) viewer / writer / admin role on
| `role` | `Literal['viewer', 'writer', 'admin']` | The role now active for the subject. |
| `granted_at` | `datetime` | When the grant row was written (UTC). |
+## `grants.invite`
+
+Give a person a role on a namespace by login handle or email.
+
+`POST /v1/grants.invite` · MCP `loom_grants_invite` · role `admin` · write · audited · not listed under the MCP `all` toolset
+
+| Input field | Type | Default | Meaning |
+| --- | --- | --- | --- |
+| `org` | `str` | required | The tenant (first element of the identity tuple). |
+| `namespace` | `str` | required | The namespace the op reads or writes. |
+| `to` | `str` | required | The person to give `role`: a handle an account or live grant holds, or an email verified for one, is granted at once; any other email gets a link, or a grant under single sign-on only; with no token, any other person is granted as typed. |
+| `role` | `Literal['viewer', 'writer', 'admin']` | required | `viewer`, `writer` or `admin`; a code namespace takes only `viewer` and `admin`. |
+
+| Output field | Type | Meaning |
+| --- | --- | --- |
+| `outcome` | `Literal['granted', 'invited']` | "granted": the grant is written under `subject`; "invited": no account holds the email, and `link_path` opens the invitation. |
+| `role` | `Literal['viewer', 'writer', 'admin']` | The role given, as asked. |
+| `subject` | `str` | On "granted", the subject the grant is written under: the person's handle as stored (an account's, or a grant's), or, when none holds it and sign-in is single sign-on only or the request has no token, `to` as typed. |
+| `invite_id` | `str` | On "invited": the invitation, for grants.cancel_invite. |
+| `link_path` | `str` | On "invited": the dashboard path that accepts it, its secret in the fragment. |
+| `url` | `str` | On "invited": `link_path` on the server's public_base_url; "" when that is unset. |
+| `expires_at` | `datetime \| None` | On "invited": when the link stops working (UTC), `invite_ttl_seconds` after it was made. |
+| `emailed` | `bool` | On "invited": true when the mail server took the email to `to`; false when the server sends no mail, a mail limit was reached or the send failed. |
+
## `grants.list`
List active grants on a namespace — who has access, at which role.
@@ -73,6 +130,22 @@ List active grants on a namespace — who has access, at which role.
| `next_cursor` | `str \| None` | Pass as `cursor` for the next page; None when this page is the last. |
| `truncated` | `bool` | True when more people follow this page (`next_cursor` is set). |
+## `grants.list_invites`
+
+List a namespace's open invitations.
+
+`POST /v1/grants.list_invites` · MCP `loom_grants_list_invites` · role `admin` · idempotent · not listed under the MCP `all` toolset
+
+| Input field | Type | Default | Meaning |
+| --- | --- | --- | --- |
+| `org` | `str` | required | The tenant (first element of the identity tuple). |
+| `namespace` | `str` | required | The namespace the op reads or writes. |
+
+| Output field | Type | Meaning |
+| --- | --- | --- |
+| `rows` | `list[_InviteEntry]` | The namespace's open links (not accepted, cancelled or expired), newest first, from the newest 200 read. |
+| `truncated` | `bool` | True when more than 200 links are open: the older ones were not read. |
+
## `grants.pending_for_me`
Every pending request in the namespaces the caller administers, in one statement.
diff --git a/docs/reference/operations/namespace.md b/docs/reference/operations/namespace.md
index 0967567d924..0fa133fe805 100644
--- a/docs/reference/operations/namespace.md
+++ b/docs/reference/operations/namespace.md
@@ -331,7 +331,7 @@ List the ontology terms (entity and relation kinds) registered for a namespace.
## `namespace.mark_seen`
-Acknowledge a new-invitation indicator on a namespace.
+Record a visit to a namespace, clearing its new mark.
`POST /v1/namespace.mark_seen` · MCP `loom_namespace_mark_seen` · role `viewer` · idempotent · not listed under the MCP `all` toolset
diff --git a/docs/reference/schema.md b/docs/reference/schema.md
index e67931db79a..77352f6e9c0 100644
--- a/docs/reference/schema.md
+++ b/docs/reference/schema.md
@@ -142,7 +142,7 @@ the `loom` tables each view reads, and, for each materialized view, its target,
-205 tables, 5 views and 19 materialized views in the `loom` and `loom_telemetry` databases; a `loom_telemetry` object keeps its database prefix.
+206 tables, 5 views and 19 materialized views in the `loom` and `loom_telemetry` databases; a `loom_telemetry` object keeps its database prefix.
#### Tables
@@ -296,6 +296,7 @@ the `loom` tables each view reads, and, for each materialized view, its target,
| `namespace_calibration_result` | `ReplacingMergeTree(version)` | `(org, namespace)` | | | |
| `namespace_grants` | `ReplacingMergeTree(version)` | `(org, namespace, subject)` | `org` | | |
| `namespace_guides` | `MergeTree` | `(org, namespace, revision)` | | | |
+| `namespace_invites` | `ReplacingMergeTree(version)` | `(org, namespace, invite_id)` | | `toDateTime(expires_at) + toIntervalDay(7)` | |
| `namespace_ontology` | `ReplacingMergeTree(version)` | `(org, namespace, kind, name)` | `org` | | |
| `namespace_policies` | `ReplacingMergeTree(version)` | `(org, namespace, policy_id)` | | | |
| `namespace_snapshots` | `MergeTree` | `(org, source_namespace, created_at)` | `org` | | |
diff --git a/docs/reference/status.md b/docs/reference/status.md
index 6968966a916..84a1d0ef79c 100644
--- a/docs/reference/status.md
+++ b/docs/reference/status.md
@@ -25,7 +25,7 @@ serves is in the [MCP reference](./mcp.md#toolsets).
-427 operations, 313 of them experimental.
+431 operations, 317 of them experimental.
| Group | Stable | Experimental |
| --- | --- | --- |
@@ -48,7 +48,7 @@ serves is in the [MCP reference](./mcp.md#toolsets).
| `erasure` | 2 | [`erasure.list`](operations/erasure.md#erasurelist), [`erasure.status`](operations/erasure.md#erasurestatus) |
| `extraction_policy` | 0 | [`extraction_policy.clear`](operations/extraction_policy.md#extraction_policyclear), [`extraction_policy.get`](operations/extraction_policy.md#extraction_policyget), [`extraction_policy.set`](operations/extraction_policy.md#extraction_policyset) |
| `facts` | 2 | [`facts.expire_by_adapter`](operations/facts.md#factsexpire_by_adapter), [`facts.path`](operations/facts.md#factspath), [`facts.related`](operations/facts.md#factsrelated) |
-| `grants` | 2 | [`grants.approve`](operations/grants.md#grantsapprove), [`grants.pending_for_me`](operations/grants.md#grantspending_for_me), [`grants.revoke`](operations/grants.md#grantsrevoke), [`grants.share_agent`](operations/grants.md#grantsshare_agent), [`grants.unshare_agent`](operations/grants.md#grantsunshare_agent) |
+| `grants` | 2 | [`grants.accept_invite`](operations/grants.md#grantsaccept_invite), [`grants.approve`](operations/grants.md#grantsapprove), [`grants.cancel_invite`](operations/grants.md#grantscancel_invite), [`grants.invite`](operations/grants.md#grantsinvite), [`grants.list_invites`](operations/grants.md#grantslist_invites), [`grants.pending_for_me`](operations/grants.md#grantspending_for_me), [`grants.revoke`](operations/grants.md#grantsrevoke), [`grants.share_agent`](operations/grants.md#grantsshare_agent), [`grants.unshare_agent`](operations/grants.md#grantsunshare_agent) |
| `help` | 0 | [`help.get`](operations/help.md#helpget), [`help.search`](operations/help.md#helpsearch) |
| `inbox` | 0 | [`inbox.list`](operations/inbox.md#inboxlist), [`inbox.policy_list`](operations/inbox.md#inboxpolicy_list), [`inbox.policy_set`](operations/inbox.md#inboxpolicy_set), [`inbox.principals`](operations/inbox.md#inboxprincipals), [`inbox.register`](operations/inbox.md#inboxregister) |
| `insights` | 0 | [`insights.catalog`](operations/insights.md#insightscatalog), [`insights.query`](operations/insights.md#insightsquery) |
diff --git a/frontend/src/api/invites.ts b/frontend/src/api/invites.ts
new file mode 100644
index 00000000000..db298713cc4
--- /dev/null
+++ b/frontend/src/api/invites.ts
@@ -0,0 +1,70 @@
+// Inviting a person to a namespace: a login handle an account or live grant holds, or a
+// verified email, is granted at once; any other email gets a single-use link, emailed when the
+// server can send mail, or a grant as typed where sign-in is single sign-on only. With auth
+// off, any other person is granted as typed.
+// Wire shapes mirror server/identity/api/models_grants.py.
+import { post } from "../api";
+import type { GrantRole, Identity } from "../api";
+
+type Scope = Pick;
+
+export interface InviteResult {
+ outcome: "granted" | "invited";
+ role: GrantRole;
+ /** The subject granted, for `granted`. */
+ subject: string;
+ invite_id: string;
+ /** `/spaces#invite=&org=…&namespace=…`, for `invited`: the link without the server's address. */
+ link_path: string;
+ /** The whole link, when the server knows its public address. */
+ url: string;
+ expires_at: string | null;
+ emailed: boolean;
+}
+
+export interface OpenInvite {
+ invite_id: string;
+ email: string;
+ role: GrantRole;
+ created_by: string;
+ created_at: string;
+ expires_at: string;
+ // Its maker does not stand behind it now, so it admits nobody: their grants no longer make
+ // them admin here, their account is disabled, or their subject or tokens as old as the
+ // link are revoked. It holds the name until it is cancelled or expires.
+ stopped: boolean;
+}
+
+export function invite(id: Scope, to: string, role: GrantRole): Promise {
+ return post("/v1/grants.invite", { org: id.org, namespace: id.namespace, to, role });
+}
+
+/** How many open invitations the server reads, newest first. */
+export const INVITES_READ = 200;
+
+export function listInvites(id: Scope): Promise<{ rows: OpenInvite[]; truncated: boolean }> {
+ return post("/v1/grants.list_invites", { org: id.org, namespace: id.namespace });
+}
+
+export function cancelInvite(id: Scope, inviteId: string): Promise<{ cancelled: boolean }> {
+ return post("/v1/grants.cancel_invite", { org: id.org, namespace: id.namespace, invite_id: inviteId });
+}
+
+export function acceptInvite(id: Scope, secret: string): Promise<{ namespace: string; role: GrantRole }> {
+ return post("/v1/grants.accept_invite", { org: id.org, namespace: id.namespace, secret });
+}
+
+/** The link to hand over: the server's own address when it knows it, else this page's. */
+export function inviteLink(r: Pick): string {
+ return r.url || `${window.location.origin}${r.link_path}`;
+}
+
+/** A person's spelling, which `grants.invite` takes; a service account, a grant principal or
+ * everyone goes to `grants.create`, as the server's `has_aliases` and `is_reserved_subject` say. */
+export function isPersonSpelling(subject: string): boolean {
+ const lowered = subject.toLowerCase();
+ const last = lowered.split("/").pop() ?? "";
+ // has_aliases reads the whole spelling, is_reserved_subject the part after the last `/`.
+ const aliased = !["", "*", "everyone"].includes(lowered) && !/^(sa|user|group|agent):/.test(lowered);
+ return aliased && last !== "everyone" && !/^(user|group|agent):/.test(last);
+}
diff --git a/frontend/src/components/ErrorBoundary.test.tsx b/frontend/src/components/ErrorBoundary.test.tsx
index bdf10dc0e4c..717c57dd254 100644
--- a/frontend/src/components/ErrorBoundary.test.tsx
+++ b/frontend/src/components/ErrorBoundary.test.tsx
@@ -71,6 +71,17 @@ describe("ErrorBoundary", () => {
expect(await screen.findByRole("button", { name: "Copied" })).toBeInTheDocument();
});
+ it("leaves an invitation link's secret out of the route it copies", async () => {
+ history.replaceState(null, "", "/spaces?x=1#invite=s3cret&org=o&namespace=n");
+ try {
+ const text = await buildDiagnostics(new Error("card exploded"), null);
+ expect(text).toContain("route: /spaces?x=1\n");
+ expect(text).not.toContain("s3cret");
+ } finally {
+ history.replaceState(null, "", "/");
+ }
+ });
+
it("reads health with no token when the stored one names someone other than the page's person", async () => {
const part = (o: object) => btoa(JSON.stringify(o)).replace(/=+$/, "");
setPageOwner({ authenticated: true, subject: "alice", org: "o" });
diff --git a/frontend/src/components/ErrorBoundary.tsx b/frontend/src/components/ErrorBoundary.tsx
index 77cc74527f5..3fcb0bff014 100644
--- a/frontend/src/components/ErrorBoundary.tsx
+++ b/frontend/src/components/ErrorBoundary.tsx
@@ -82,7 +82,8 @@ export class ErrorBoundary extends Component {
export async function buildDiagnostics(error: Error | null, info: ErrorInfo | null): Promise {
const lines = [
`Loom dashboard error — ${new Date().toISOString()}`,
- `route: ${location.pathname}${location.search}${location.hash}`,
+ // Not the fragment: an invitation link's secret rides there until the page takes it.
+ `route: ${location.pathname}${location.search}`,
`build: ${await buildCommit()}`,
`user agent: ${navigator.userAgent}`,
"",
diff --git a/frontend/src/components/Invitations.test.tsx b/frontend/src/components/Invitations.test.tsx
new file mode 100644
index 00000000000..923a15a4c30
--- /dev/null
+++ b/frontend/src/components/Invitations.test.tsx
@@ -0,0 +1,172 @@
+import { cleanup, render, screen, waitFor } from "../test/rtl";
+import userEvent from "@testing-library/user-event";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cancelInvite, isPersonSpelling, listInvites } from "../api/invites";
+import { ApiError } from "../lib/errors";
+import { InviteSent, OpenInvitations } from "./Invitations";
+import { toast } from "./Toast";
+
+vi.mock("../api/invites", async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, listInvites: vi.fn(), cancelInvite: vi.fn(async () => ({ cancelled: true })) };
+});
+vi.mock("./Toast", () => ({ toast: vi.fn(), toastError: vi.fn() }));
+afterEach(() => cleanup());
+
+const sent = {
+ outcome: "invited" as const,
+ role: "writer" as const,
+ subject: "",
+ invite_id: "abc",
+ link_path: "/spaces#invite=s3cret&org=dev&namespace=team",
+ url: "",
+ expires_at: "2026-12-11T12:00:00Z",
+ emailed: false,
+};
+
+describe("InviteSent", () => {
+ it("hands over the link on this page's address when the server knows none", () => {
+ render();
+ expect(screen.getByRole("status")).toHaveTextContent("No account in this org has verified pat@example.com.");
+ expect(
+ screen.getByText(`${window.location.origin}/spaces#invite=s3cret&org=dev&namespace=team`),
+ ).toBeInTheDocument();
+ });
+
+ it("says it was emailed, and still shows the server's link", () => {
+ render(
+ ,
+ );
+ expect(screen.getByRole("status")).toHaveTextContent("Emailed an invitation to pat@example.com.");
+ expect(screen.getByText("https://loom.example.com/spaces#x")).toBeInTheDocument();
+ });
+
+ it("keeps Copy link in the link's row, not placed over the dialog", () => {
+ render();
+ expect(screen.getByRole("button", { name: /Copy link/ })).not.toHaveClass("absolute");
+ });
+});
+
+const open = {
+ invite_id: "abc",
+ email: "pat@example.com",
+ role: "writer" as const,
+ created_by: "ann",
+ created_at: "2026-12-04T12:00:00Z",
+ expires_at: "2026-12-11T12:00:00Z",
+ stopped: false,
+};
+
+describe("OpenInvitations", () => {
+ it("marks a link that admits nobody now, and still cancels it", async () => {
+ vi.mocked(listInvites).mockResolvedValue({ rows: [{ ...open, stopped: true }], truncated: false });
+ render(
+ {}} scope={{ org: "dev", namespace: "team" }} version={0} onJoined={() => {}} />,
+ );
+ expect(await screen.findByText("stopped: made by ann, and admits nobody now")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Cancel the invitation to pat@example.com" })).toBeEnabled();
+ });
+
+ it("lists the open invitations and cancels one", async () => {
+ vi.mocked(listInvites).mockResolvedValue({ rows: [open], truncated: false });
+ const user = userEvent.setup();
+ render(
+ {}} scope={{ org: "dev", namespace: "team" }} version={0} onJoined={() => {}} />,
+ );
+ await user.click(await screen.findByRole("button", { name: "Cancel the invitation to pat@example.com" }));
+ expect(cancelInvite).toHaveBeenCalledWith({ org: "dev", namespace: "team" }, "abc");
+ await waitFor(() => expect(screen.queryByRole("region", { name: "Open invitations" })).toBeNull());
+ });
+
+ it("keeps a cancelled invitation off the list when a read begun before the cancel lands after it", async () => {
+ let answer: (v: { rows: (typeof open)[]; truncated: boolean }) => void = () => {};
+ vi.mocked(listInvites)
+ .mockResolvedValueOnce({ rows: [open], truncated: false })
+ .mockImplementationOnce(() => new Promise((r) => (answer = r)));
+ const scope = { org: "dev", namespace: "team" };
+ const user = userEvent.setup();
+ const { rerender } = render( {}} scope={scope} version={0} onJoined={() => {}} />);
+ const cancel = await screen.findByRole("button", { name: "Cancel the invitation to pat@example.com" });
+ rerender( {}} scope={scope} version={1} onJoined={() => {}} />);
+ await user.click(cancel);
+ await waitFor(() => expect(screen.queryByRole("region", { name: "Open invitations" })).toBeNull());
+ answer({ rows: [open, { ...open, invite_id: "def", email: "lee@example.com" }], truncated: false });
+ expect(await screen.findByText("lee@example.com")).toBeInTheDocument();
+ expect(screen.queryByText("pat@example.com")).toBeNull();
+ });
+
+ it("says a link used meanwhile was not cancelled, and reads the members again", async () => {
+ vi.mocked(listInvites).mockResolvedValue({ rows: [{ ...open, created_by: "user:42" }], truncated: false });
+ vi.mocked(cancelInvite).mockResolvedValueOnce({ cancelled: false });
+ const onJoined = vi.fn();
+ const user = userEvent.setup();
+ render(
+ {}} scope={{ org: "dev", namespace: "team" }} version={0} onJoined={onJoined} />,
+ );
+ expect(await screen.findByText(/by user 42,/)).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "Cancel the invitation to pat@example.com" }));
+ await waitFor(() => expect(onJoined).toHaveBeenCalledTimes(1));
+ expect(toast).toHaveBeenCalledWith(
+ "The invitation to pat@example.com was already used, cancelled or expired",
+ "info",
+ );
+ });
+
+ it("says a failed read failed, not that there are none, and reads again on Retry", async () => {
+ vi.mocked(listInvites)
+ .mockRejectedValueOnce(new ApiError({ status: 503, code: "BACKEND_UNAVAILABLE", message: "grants unreadable" }))
+ .mockResolvedValueOnce({ rows: [{ ...open, email: "lee@example.com" }], truncated: false });
+ const user = userEvent.setup();
+ render(
+ {}} scope={{ org: "dev", namespace: "team" }} version={0} onJoined={() => {}} />,
+ );
+ expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't load the invitations: grants unreadable");
+ await user.click(screen.getByRole("button", { name: "Retry loading the invitations" }));
+ expect(await screen.findByText("lee@example.com")).toBeInTheDocument();
+ });
+
+ it("says a failed re-read failed while it still lists the last read", async () => {
+ vi.mocked(listInvites)
+ .mockResolvedValueOnce({ rows: [open], truncated: false })
+ .mockRejectedValueOnce(new ApiError({ status: 503, code: "BACKEND_UNAVAILABLE", message: "grants unreadable" }));
+ const scope = { org: "dev", namespace: "team" };
+ const { rerender } = render( {}} scope={scope} version={0} onJoined={() => {}} />);
+ expect(await screen.findByText("pat@example.com")).toBeInTheDocument();
+ rerender( {}} scope={scope} version={1} onJoined={() => {}} />);
+ expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't refresh the invitations: grants unreadable");
+ expect(screen.getByText("pat@example.com")).toBeInTheDocument();
+ });
+
+ it.each([
+ ["some", [open]],
+ ["none", []],
+ ])("says when the server read only the newest invitations, with %s left to show", async (_, rows) => {
+ vi.mocked(listInvites).mockResolvedValue({ rows, truncated: true });
+ render(
+ {}} scope={{ org: "dev", namespace: "team" }} version={0} onJoined={() => {}} />,
+ );
+ expect(await screen.findByText("Only the newest 200 invitations were read.")).toBeInTheDocument();
+ });
+});
+
+describe("isPersonSpelling", () => {
+ it("tells a person from a principal", () => {
+ // As the server's has_aliases (the whole spelling) and is_reserved_subject (after the last `/`).
+ for (const s of ["robin", "pat@example.com", "Pat", "acme/sa:bot"]) expect(isPersonSpelling(s)).toBe(true);
+ for (const s of [
+ "sa:bot",
+ "group:eng",
+ "user:42",
+ "agent:x",
+ "everyone",
+ "Everyone",
+ "*",
+ "acme/user:1",
+ "user:4/x",
+ ])
+ expect(isPersonSpelling(s)).toBe(false);
+ });
+});
diff --git a/frontend/src/components/Invitations.tsx b/frontend/src/components/Invitations.tsx
new file mode 100644
index 00000000000..d1be0912d70
--- /dev/null
+++ b/frontend/src/components/Invitations.tsx
@@ -0,0 +1,149 @@
+import { useEffect, useState } from "react";
+import { Button } from "@clickhouse/click-ui/Button";
+import {
+ cancelInvite,
+ INVITES_READ,
+ inviteLink,
+ listInvites,
+ type InviteResult,
+ type OpenInvite,
+} from "../api/invites";
+import { errorLine } from "../lib/errorWords";
+import { absoluteTime, fmtInt } from "../lib/format";
+import { CopyButton } from "./CopyButton";
+import { subjectLabel } from "../lib/grantSubject";
+import { toast, toastError } from "./Toast";
+
+type Scope = { org: string; namespace: string };
+
+/** What an invitation by email did: the link, and whether the server emailed it. */
+export function InviteSent({ email, result }: { email: string; result: InviteResult }) {
+ const link = inviteLink(result);
+ return (
+
+
+ {result.emailed
+ ? `Emailed an invitation to ${email}. You can also send them this link:`
+ : `No account in this org has verified ${email}. Send them this link:`}
+
+
+ {link}
+
+
+
+ It works once, until {absoluteTime(result.expires_at)}: whoever opens it signed in gets the role, under the
+ account they sign in with.
+
+
+ );
+}
+
+/** The namespace's open invitations, each with Cancel; nothing while there are none, and a
+ * failed read with Retry. `version` changes to read them again after an invitation is made.
+ * `onJoined` reads the members again when a link turns out to have been used meanwhile;
+ * `onClosed` names each link closed here, so a card showing it can come down. */
+export function OpenInvitations({
+ scope,
+ version,
+ onJoined,
+ onClosed,
+}: {
+ scope: Scope;
+ version: number;
+ onJoined: () => void;
+ onClosed: (inviteId: string) => void;
+}) {
+ const [read, setRead] = useState([]);
+ // Links closed from here: a read begun before the cancel can still list them, and a closed
+ // link never opens again.
+ const [closed, setClosed] = useState>(new Set());
+ const rows = read.filter((r) => !closed.has(r.invite_id));
+ const [cut, setCut] = useState(false);
+ const [error, setError] = useState(null);
+ const [reads, setReads] = useState(0);
+ const [busy, setBusy] = useState(null);
+ useEffect(() => {
+ let live = true;
+ listInvites(scope)
+ .then((r) => {
+ if (!live) return;
+ setRead(r.rows);
+ setCut(r.truncated);
+ setError(null);
+ })
+ .catch((e: unknown) => live && setError(errorLine(e, { read: true })));
+ return () => {
+ live = false;
+ };
+ }, [scope.org, scope.namespace, version, reads]);
+ // A line, not a second error state: the dialog's own list says it failed too in an outage.
+ const failed = error !== null && (
+
+ );
+ if (rows.length === 0 && !failed && !cut) return null;
+
+ const cancel = async (row: OpenInvite) => {
+ setBusy(row.invite_id);
+ try {
+ const out = await cancelInvite(scope, row.invite_id);
+ setClosed((ids) => new Set(ids).add(row.invite_id));
+ onClosed(row.invite_id);
+ if (!out.cancelled) {
+ // Accepted, cancelled elsewhere or expired between the read and the click: the
+ // person may be in.
+ toast(`The invitation to ${row.email} was already used, cancelled or expired`, "info");
+ onJoined();
+ }
+ } catch (e) {
+ toastError("Couldn't cancel the invitation", e);
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ return (
+
+ {failed}
+ {rows.length > 0 && (
+ <>
+
{`Invited (${fmtInt(rows.length)})`}
+
+ {rows.map((r) => (
+
+ {r.email}
+
+ {r.stopped
+ ? `stopped: made by ${subjectLabel(r.created_by, scope.org)}, and admits nobody now`
+ : `${r.role}, by ${subjectLabel(r.created_by, scope.org)}, until ${absoluteTime(r.expires_at)}`}
+
+
+
+ ))}
+
+ >
+ )}
+ {/* Even with no row shown: the newest read can all hold roles this build does not know. */}
+ {cut && (
+
{`Only the newest ${fmtInt(INVITES_READ)} invitations were read.`}
+ )}
+
+ );
+}
diff --git a/frontend/src/components/SubjectHelp.test.tsx b/frontend/src/components/SubjectHelp.test.tsx
new file mode 100644
index 00000000000..7dd68486a41
--- /dev/null
+++ b/frontend/src/components/SubjectHelp.test.tsx
@@ -0,0 +1,27 @@
+import { render, screen } from "../test/rtl";
+import { describe, expect, it, vi } from "vitest";
+import { SubjectHelp } from "./SubjectHelp";
+
+const auth = vi.hoisted(() => ({ off: false }));
+vi.mock("../api", async (importOriginal) => ({
+ ...(await importOriginal()),
+ isAuthDisabled: () => auth.off,
+}));
+
+// The add field's help says what a person's handle or email gets on this server.
+describe("SubjectHelp", () => {
+ it("offers an invitation link for an email where sign-in is on", () => {
+ auth.off = false;
+ render();
+ expect(screen.getByText(/any other email gets an invitation link/)).toBeInTheDocument();
+ });
+
+ it("says a person nothing holds is granted as typed where sign-in is off", () => {
+ auth.off = true;
+ render();
+ expect(
+ screen.getByText(/granted under its stored spelling, .* and any other handle or email as typed/),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(/invitation link/)).toBeNull();
+ });
+});
diff --git a/frontend/src/components/SubjectHelp.tsx b/frontend/src/components/SubjectHelp.tsx
index ba0e03d98ad..fcdaaf0d244 100644
--- a/frontend/src/components/SubjectHelp.tsx
+++ b/frontend/src/components/SubjectHelp.tsx
@@ -1,12 +1,14 @@
-/** What a spelling in an add field reaches: a namespace's members and a repository's readers
- * take the same subjects through `grants.create`, and a collection also takes a group, an agent
- * and everyone. */
+import { isAuthDisabled } from "../api";
+
+/** What a spelling in an add field reaches: a person through `grants.invite`, the others
+ * through `grants.create`; a collection also takes a group, an agent and everyone. */
export function SubjectHelp({ id, collection = false }: { id: string; collection?: boolean }) {
return (
- A login handle is the name a person signs in with, shown in their account menu under Signed in as; it may be an
- email. Any other email reaches them only once they sign in with it through single sign-on, or an operator links it
- to their account. A service account is sa:<name>
+ {isAuthDisabled()
+ ? "Sign-in is off on this server, so a login handle an account or a grant holds is granted under its stored spelling, an email verified for an account under that account's handle, and any other handle or email as typed."
+ : "A login handle is the name a person signs in with, shown in their account menu under Signed in as. An email is granted at once only when it is verified for an account; any other email gets an invitation link, emailed too when this server sends mail, and whoever opens it signed in joins. Where sign-in is single sign-on only, the email is granted instead."}{" "}
+ A service account is sa:<name>
{collection ? (
<>
, a group group:<id>, an agent{" "}
diff --git a/frontend/src/flows/MembersDialog.fanout.test.tsx b/frontend/src/flows/MembersDialog.fanout.test.tsx
index ddee88f32b5..c31172f0e93 100644
--- a/frontend/src/flows/MembersDialog.fanout.test.tsx
+++ b/frontend/src/flows/MembersDialog.fanout.test.tsx
@@ -6,9 +6,23 @@ import { render, screen, fireEvent, waitFor } from "../test/rtl";
import { MembersDialog } from "./MembersDialog";
import { useStore } from "../lib/state";
import * as api from "../api";
+import * as invites from "../api/invites";
import { ApiError } from "../lib/errors";
import { ToastViewport } from "../components/Toast";
+vi.mock("../api/invites", async (importOriginal) => ({
+ ...(await importOriginal()),
+ invite: vi.fn(async (_id: unknown, subject: string, role: string) => ({
+ outcome: "granted" as const,
+ role,
+ subject,
+ invite_id: "",
+ link_path: "",
+ url: "",
+ expires_at: null,
+ emailed: false,
+ })),
+}));
vi.mock("../api", async (importOriginal) => {
const actual = await importOriginal();
return {
@@ -41,6 +55,7 @@ const elsewhere = {
beforeEach(() => {
vi.mocked(api.approveGrant).mockClear();
vi.mocked(api.createGrant).mockClear();
+ vi.mocked(invites.invite).mockClear();
useStore.setState({
whoami: { authenticated: true, subject: "alice", org: "clickhouse", roles: ["ADMIN"] },
});
@@ -113,9 +128,9 @@ describe("MembersDialog approves a requester on every waiting branch at once", (
expect(screen.getByRole("button", { name: "Role for the new reader" })).toHaveTextContent("Reader");
fireEvent.change(screen.getByRole("textbox", { name: /reader to add/ }), { target: { value: subject } });
fireEvent.click(screen.getByRole("button", { name: /^Add$/ }));
- await waitFor(() => expect(api.createGrant).toHaveBeenCalledTimes(n));
+ await waitFor(() => expect(invites.invite).toHaveBeenCalledTimes(n));
}
- expect(vi.mocked(api.createGrant).mock.calls.map((c) => [c[1], c[2]])).toEqual([
+ expect(vi.mocked(invites.invite).mock.calls.map((c) => [c[1], c[2]])).toEqual([
["reader-a", "viewer"],
["reader-b", "viewer"],
]);
diff --git a/frontend/src/flows/MembersDialog.invite.test.tsx b/frontend/src/flows/MembersDialog.invite.test.tsx
new file mode 100644
index 00000000000..c4e2810b773
--- /dev/null
+++ b/frontend/src/flows/MembersDialog.invite.test.tsx
@@ -0,0 +1,181 @@
+import { cleanup, render, screen, waitFor, within } from "../test/rtl";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import * as api from "../api";
+import * as invites from "../api/invites";
+import { toast } from "../components/Toast";
+import { useStore } from "../lib/state";
+import { MembersDialog } from "./MembersDialog";
+
+// A person is added through grants.invite: an account is granted at once; any other email
+// gets a link the dialog shows to copy and lists as open. A service account goes through
+// grants.create as typed.
+
+vi.mock("../api", async (importOriginal) => ({
+ ...(await importOriginal()),
+ listGrants: vi.fn(async () => ({ rows: [] })),
+ createGrant: vi.fn(async () => ({})),
+}));
+vi.mock("../components/Toast", async (importOriginal) => ({
+ ...(await importOriginal()),
+ toast: vi.fn(),
+}));
+vi.mock("../api/invites", async (importOriginal) => ({
+ ...(await importOriginal()),
+ invite: vi.fn(),
+ listInvites: vi.fn(async () => ({ rows: [], truncated: false })),
+ cancelInvite: vi.fn(async () => ({ cancelled: true })),
+}));
+
+const invited = {
+ outcome: "invited" as const,
+ role: "writer" as const,
+ subject: "",
+ invite_id: "abc",
+ link_path: "/spaces#invite=s3cret&org=dev&namespace=team",
+ url: "https://loom.example.com/spaces#invite=s3cret&org=dev&namespace=team",
+ expires_at: "2026-12-11T12:00:00Z",
+ emailed: true,
+};
+
+beforeEach(() => {
+ vi.mocked(api.createGrant).mockClear();
+ vi.mocked(invites.invite).mockReset();
+ vi.mocked(invites.listInvites).mockReset().mockResolvedValue({ rows: [], truncated: false });
+ useStore.setState({ whoami: { authenticated: true, subject: "ann", org: "dev", roles: ["ADMIN"] } });
+});
+afterEach(() => cleanup());
+
+async function add(subject: string) {
+ const user = userEvent.setup();
+ render( {}} org="dev" namespace="team" kind="memory" />);
+ await user.click((await screen.findAllByRole("button", { name: /Add member/ }))[0]);
+ await user.type(await screen.findByRole("textbox", { name: /member to add/ }), `${subject}{Enter}`);
+}
+
+describe("MembersDialog invites a person", () => {
+ it("shows an email's invitation link and lists it as open", async () => {
+ vi.mocked(invites.invite).mockResolvedValue(invited);
+ vi.mocked(invites.listInvites)
+ .mockResolvedValueOnce({ rows: [], truncated: false })
+ .mockResolvedValue({
+ rows: [
+ {
+ invite_id: "abc",
+ email: "pat@example.com",
+ role: "writer",
+ created_by: "ann",
+ created_at: "2026-12-04T12:00:00Z",
+ expires_at: "2026-12-11T12:00:00Z",
+ stopped: false,
+ },
+ ],
+ truncated: false,
+ });
+ await add("pat@example.com");
+ expect(invites.invite).toHaveBeenCalledWith({ org: "dev", namespace: "team" }, "pat@example.com", "writer");
+ const notice = await screen.findByText(/Emailed an invitation to pat@example\.com\./);
+ const status = notice.closest('[role="status"]') as HTMLElement;
+ expect(within(status).getByText(invited.url)).toBeInTheDocument();
+ const open = await screen.findByRole("region", { name: "Open invitations" });
+ expect(open).toHaveTextContent("pat@example.com");
+ expect(api.createGrant).not.toHaveBeenCalled();
+ });
+
+ it("takes the link down once its invitation is cancelled from the list", async () => {
+ vi.mocked(invites.invite).mockResolvedValue(invited);
+ vi.mocked(invites.listInvites).mockResolvedValue({
+ rows: [
+ {
+ invite_id: "abc",
+ email: "pat@example.com",
+ role: "writer" as const,
+ created_by: "ann",
+ created_at: "2026-12-04T12:00:00Z",
+ expires_at: "2026-12-11T12:00:00Z",
+ stopped: false,
+ },
+ ],
+ truncated: false,
+ });
+ await add("pat@example.com");
+ await screen.findByText(/Emailed an invitation to pat@example\.com/);
+ await userEvent
+ .setup()
+ .click(await screen.findByRole("button", { name: "Cancel the invitation to pat@example.com" }));
+ await waitFor(() => expect(screen.queryByText(/send them this link/)).toBeNull());
+ });
+
+ it("grants an account's handle at once, under the subject the server names", async () => {
+ vi.mocked(invites.invite).mockResolvedValue({ ...invited, outcome: "granted", subject: "robin", invite_id: "" });
+ await add("Robin");
+ await waitFor(() => expect(toast).toHaveBeenCalledWith("Added robin as writer", "ok"));
+ expect(invites.invite).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText(/send them this link/)).toBeNull();
+ expect(screen.queryByRole("textbox", { name: /member to add/ })).toBeNull();
+ });
+
+ it("makes one invitation for an Enter pressed again while it is in flight", async () => {
+ let answer: (v: typeof invited) => void = () => {};
+ vi.mocked(invites.invite).mockImplementation(() => new Promise((r) => (answer = r)));
+ const user = userEvent.setup();
+ render( {}} org="dev" namespace="team" kind="memory" />);
+ await user.click((await screen.findAllByRole("button", { name: /Add member/ }))[0]);
+ const field = await screen.findByRole("textbox", { name: /member to add/ });
+ await user.type(field, "pat@example.com{Enter}");
+ await user.type(field, "{Enter}");
+ answer(invited);
+ await screen.findByText(/Emailed an invitation/);
+ expect(invites.invite).toHaveBeenCalledTimes(1);
+ });
+
+ it("shows a link only on the namespace it was made for, and not after Cancel", async () => {
+ vi.mocked(invites.invite).mockResolvedValue(invited);
+ const user = userEvent.setup();
+ const dialog = (namespace: string) => (
+ {}} org="dev" namespace={namespace} kind="memory" />
+ );
+ const { rerender } = render(dialog("team"));
+ await user.click((await screen.findAllByRole("button", { name: /Add member/ }))[0]);
+ await user.type(await screen.findByRole("textbox", { name: /member to add/ }), "pat@example.com{Enter}");
+ const link = /Emailed an invitation to pat@example\.com/;
+ await screen.findByText(link);
+ rerender(dialog("other"));
+ expect(screen.queryByText(link)).toBeNull();
+ rerender(dialog("team"));
+ expect(screen.getByText(link)).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "Cancel" }));
+ await user.click((await screen.findAllByRole("button", { name: /Add member/ }))[0]);
+ expect(screen.queryByText(link)).toBeNull();
+ });
+
+ it("lists no other namespace's open invitations while its own are read", async () => {
+ const row = {
+ invite_id: "abc",
+ email: "pat@example.com",
+ role: "writer" as const,
+ created_by: "ann",
+ created_at: "2026-12-04T12:00:00Z",
+ expires_at: "2026-12-11T12:00:00Z",
+ stopped: false,
+ };
+ vi.mocked(invites.listInvites).mockImplementation((scope) =>
+ scope.namespace === "team" ? Promise.resolve({ rows: [row], truncated: false }) : new Promise(() => {}),
+ );
+ const dialog = (namespace: string) => (
+ {}} org="dev" namespace={namespace} kind="memory" />
+ );
+ const { rerender } = render(dialog("team"));
+ expect(await screen.findByRole("region", { name: "Open invitations" })).toHaveTextContent("pat@example.com");
+ rerender(dialog("other"));
+ expect(screen.queryByText("pat@example.com")).toBeNull();
+ });
+
+ it("grants a service account through grants.create, as typed", async () => {
+ await add("sa:triage");
+ await waitFor(() =>
+ expect(api.createGrant).toHaveBeenCalledWith({ org: "dev", namespace: "team" }, "sa:triage", "writer"),
+ );
+ expect(invites.invite).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/flows/MembersDialog.loading.test.tsx b/frontend/src/flows/MembersDialog.loading.test.tsx
index 5e13d4074f7..97e24c354d5 100644
--- a/frontend/src/flows/MembersDialog.loading.test.tsx
+++ b/frontend/src/flows/MembersDialog.loading.test.tsx
@@ -6,11 +6,16 @@ import { act, render, screen, fireEvent, waitFor } from "../test/rtl";
import { MembersDialog } from "./MembersDialog";
import { useStore } from "../lib/state";
import * as api from "../api";
+import { invite } from "../api/invites";
vi.mock("../api", async (importOriginal) => {
const actual = await importOriginal();
- return { ...actual, listGrants: vi.fn(), approveGrant: vi.fn(async () => ({})), createGrant: vi.fn() };
+ return { ...actual, listGrants: vi.fn(), approveGrant: vi.fn(async () => ({})) };
});
+vi.mock("../api/invites", async (importOriginal) => ({
+ ...(await importOriginal()),
+ invite: vi.fn(),
+}));
// The namespace here holds no document source.
vi.mock("../api/knowledgeSources", () => ({
@@ -96,13 +101,15 @@ describe("MembersDialog opened on the add field", () => {
it("describes the field by a refused add's error, then the help", async () => {
vi.mocked(api.listGrants).mockResolvedValue({ rows: [] } as never);
- vi.mocked(api.createGrant).mockRejectedValueOnce(new Error("That subject is not allowed here"));
+ vi.mocked(invite).mockRejectedValueOnce(new Error("No account in clickhouse signs in as pat"));
render( {}} org="clickhouse" namespace="team" startAdding />);
const field = await screen.findByRole("textbox", { name: /member to add/ });
fireEvent.change(field, { target: { value: "pat" } });
fireEvent.keyDown(field, { key: "Enter" });
await waitFor(() =>
- expect(field).toHaveAccessibleDescription(/^That subject is not allowed here.*A login handle is the name/),
+ expect(field).toHaveAccessibleDescription(
+ /^No account in clickhouse signs in as pat.*A login handle is the name/,
+ ),
);
});
diff --git a/frontend/src/flows/MembersDialog.tsx b/frontend/src/flows/MembersDialog.tsx
index 227cdf22104..1bdba23eacd 100644
--- a/frontend/src/flows/MembersDialog.tsx
+++ b/frontend/src/flows/MembersDialog.tsx
@@ -33,6 +33,8 @@ import { andList, fmtInt } from "../lib/format";
import { MORE_SHOWN, type ShowMoreRows, useShowMore } from "../lib/useShowMore";
import { grantSpellings, isAgentSubject, mySpellings, namesMe, subjectLabel } from "../lib/grantSubject";
import { PlaceLink } from "../components/ui/PlaceLink";
+import { invite, isPersonSpelling, type InviteResult } from "../api/invites";
+import { InviteSent, OpenInvitations } from "../components/Invitations";
import { connectedSourceMayStop, ImportedCopiesNote, useImportedCopies } from "./ImportedCopiesNote";
/** What Remove's confirm says: who still gets in once the grant here goes. Sign-in off serves
@@ -242,6 +244,11 @@ export function MembersDialog({
const [cut, setCut] = useState(false);
const [adding, setAdding] = useState(startAdding);
const [newSubject, setNewSubject] = useState("");
+ // The invitation an add just made, with its link to copy, shown only on the namespace
+ // it was made for (`key`).
+ const [sent, setSent] = useState<{ key: string; email: string; result: InviteResult } | null>(null);
+ // Invitations made here; a change reads the open ones again.
+ const [invited, setInvited] = useState(0);
// A code index has no writer role, so its default must be one the select offers.
const defaultRole: GrantRole = isCode ? "viewer" : "writer";
const [newRole, setNewRole] = useState(defaultRole);
@@ -321,12 +328,28 @@ export function MembersDialog({
const onAdd = async () => {
const subj = newSubject.trim();
- if (!subj) return;
+ // Enter while an add is in flight would make a second invitation and email.
+ if (!subj || busy === "__add__") return;
setBusy("__add__");
setErr(null);
try {
- await createGrant({ org, namespace }, subj, newRole);
- toast(`Added ${subjectLabel(subj, org)} as ${newRole}`, "ok");
+ // A person by handle or email goes through grants.invite, which grants at once or
+ // answers a link. Any other principal is granted as typed.
+ if (isPersonSpelling(subj)) {
+ const out = await invite({ org, namespace }, subj, newRole);
+ if (out.outcome === "invited") {
+ // The link stays on screen to copy, and the add field open for the next person.
+ setSent({ key: rowsKey, email: subj, result: out });
+ setInvited((n) => n + 1);
+ setNewSubject("");
+ return;
+ }
+ toast(`Added ${subjectLabel(out.subject, org)} as ${newRole}`, "ok");
+ } else {
+ await createGrant({ org, namespace }, subj, newRole);
+ toast(`Added ${subjectLabel(subj, org)} as ${newRole}`, "ok");
+ }
+ setSent(null);
setNewSubject("");
setNewRole(defaultRole);
setAdding(false);
@@ -466,6 +489,7 @@ export function MembersDialog({
// The next open, if the caller keeps the dialog mounted, starts where this one did.
setAdding(startAdding);
setErr(null);
+ setSent(null);
}
onOpenChange(v);
}}
@@ -504,6 +528,15 @@ export function MembersDialog({
{cut && (
{`Only the first ${fmtInt(GRANTS_READ)} grants were read.`}
@@ -723,9 +756,8 @@ export function MembersDialog({
{roles.find((r) => r.value === newRole)?.desc}
- {/* An email no verified account holds is stored as typed and reaches nobody: say so
- before the add, not after. */}
+ {sent?.key === rowsKey && }
)}
@@ -749,6 +781,7 @@ export function MembersDialog({
setAdding(false);
setNewSubject("");
setErr(null);
+ setSent(null);
}}
>
Cancel
diff --git a/frontend/src/flows/fieldErrors.test.tsx b/frontend/src/flows/fieldErrors.test.tsx
index 9aa6f8850e8..eeeda238f33 100644
--- a/frontend/src/flows/fieldErrors.test.tsx
+++ b/frontend/src/flows/fieldErrors.test.tsx
@@ -23,6 +23,13 @@ vi.mock("../api", async (importOriginal) => {
}),
};
});
+// A person's handle or email is added through grants.invite, which refuses an unknown one.
+vi.mock("../api/invites", async (importOriginal) => ({
+ ...(await importOriginal()),
+ invite: vi.fn(async () => {
+ throw new Error("No such subject");
+ }),
+}));
vi.mock("../api/tasks", async (importOriginal) => {
const actual = await importOriginal();
return {
diff --git a/frontend/src/lib/inviteLink.ts b/frontend/src/lib/inviteLink.ts
new file mode 100644
index 00000000000..914a630ef29
--- /dev/null
+++ b/frontend/src/lib/inviteLink.ts
@@ -0,0 +1,59 @@
+// An invitation link (`/spaces#invite=&org=…&namespace=…`), taken out of the address
+// into this tab's session by Namespaces in your org, which offers to accept it. A password
+// sign-in reloads the page, fragment and all; single sign-on makes no link.
+
+/** The session key for an invitation link's `{ secret, org, namespace }`. */
+export const INVITE_LINK = "loom_invite_v1";
+
+export interface InviteLink {
+ secret: string;
+ org: string;
+ namespace: string;
+}
+
+// Where session storage refuses the link, the page holds it until it reloads.
+let held: InviteLink | null = null;
+
+/** Take an invitation link out of the address into this tab's session, and return it. */
+export function takeInviteLink(): InviteLink | null {
+ const { hash, pathname, search } = window.location;
+ if (!hash.startsWith("#invite=")) return null;
+ history.replaceState(history.state, "", pathname + search);
+ const p = new URLSearchParams(hash.slice(1));
+ const [secret, org, namespace] = [p.get("invite"), p.get("org"), p.get("namespace")];
+ if (!secret || !org || !namespace) return null;
+ const link = { secret, org, namespace };
+ try {
+ sessionStorage.setItem(INVITE_LINK, JSON.stringify(link));
+ held = null;
+ } catch {
+ held = link;
+ }
+ return link;
+}
+
+/** The link this tab keeps for a later visit, if any. */
+export function keptInviteLink(): InviteLink | null {
+ if (held) return held;
+ try {
+ const v = JSON.parse(sessionStorage.getItem(INVITE_LINK) ?? "null") as Partial | null;
+ if (v && typeof v.secret === "string" && typeof v.org === "string" && typeof v.namespace === "string") {
+ return { secret: v.secret, org: v.org, namespace: v.namespace };
+ }
+ } catch {
+ /* unreadable or no session storage */
+ }
+ return null;
+}
+
+/** Forget `secret`'s link, and not one opened since; with a held link, also the older one
+ * storage kept, which it replaced. */
+export function dropInviteLink(secret: string): void {
+ if (keptInviteLink()?.secret !== secret) return;
+ held = null;
+ try {
+ sessionStorage.removeItem(INVITE_LINK);
+ } catch {
+ /* no session storage: nothing was kept */
+ }
+}
diff --git a/frontend/src/views/Browse.tsx b/frontend/src/views/Browse.tsx
index 7db9aaa851e..60fa2c3d4c4 100644
--- a/frontend/src/views/Browse.tsx
+++ b/frontend/src/views/Browse.tsx
@@ -22,6 +22,7 @@ import { COLLECTION_PREFIX, NAMESPACE_NAME, isCollectionName, isPersonalCollecti
import { canEditGuide, roleOnNamespace } from "../lib/namespaceRole";
import { callReason } from "../lib/callReason";
import { CreateNamespaceDialog } from "../flows/CreateNamespaceDialog";
+import { InvitationCard } from "./InvitationCard";
import { useStore, useIdentity } from "../lib/state";
import { RowSkeleton } from "../components/Skeleton";
import { Alert, ListRow, LoadingSkeleton, PageHeader, Panel, SectionHeading, Tip } from "../components/ui";
@@ -440,6 +441,7 @@ export function Browse() {
A namespace is a project's or an agent's memory. Join public namespaces in your org, or invite people into the
ones you manage.
+
{/* The Repositories hint: under the description, or inside the folded code section when there is one. */}
{managedCode.length === 0 && repoHint &&
{repoHint}
}
diff --git a/frontend/src/views/Code.accessInvite.test.tsx b/frontend/src/views/Code.accessInvite.test.tsx
new file mode 100644
index 00000000000..605059bafc0
--- /dev/null
+++ b/frontend/src/views/Code.accessInvite.test.tsx
@@ -0,0 +1,122 @@
+/**
+ * The Access tab adds a person through grants.invite, and names the subject the server
+ * granted, which may be another spelling than the one typed; any other principal goes
+ * through grants.create.
+ */
+import userEvent from "@testing-library/user-event";
+import { cleanup, render, screen, waitFor } from "../test/rtl";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { toast } from "../components/Toast";
+import * as api from "../api";
+import * as invites from "../api/invites";
+import { useStore } from "../lib/state";
+import { AccessTab } from "./Code";
+
+vi.mock("../api", async (importOriginal) => ({
+ ...(await importOriginal()),
+ listGrants: vi.fn(async () => ({ rows: [{ subject: "alice", role: "admin", status: "active" }] })),
+ getNamespace: async () => ({ namespace: "code-app", join_policy: "approval" }),
+ createGrant: vi.fn(async () => ({})),
+}));
+vi.mock("../api/invites", async (importOriginal) => ({
+ ...(await importOriginal()),
+ invite: vi.fn(),
+ listInvites: vi.fn(async () => ({ rows: [], truncated: false })),
+ cancelInvite: vi.fn(async () => ({ cancelled: true })),
+}));
+vi.mock("../lib/sharedReads", async (importOriginal) => ({
+ ...(await importOriginal()),
+ sharedIndexStatus: async () => ({ org_readable: false }),
+}));
+vi.mock("../components/Toast", async (importOriginal) => ({
+ ...(await importOriginal()),
+ toast: vi.fn(),
+}));
+
+beforeEach(() => {
+ vi.mocked(invites.invite).mockReset();
+ useStore.setState({ whoami: { authenticated: true, subject: "alice", org: "dev", roles: ["ADMIN"] } });
+});
+afterEach(() => cleanup());
+
+it("names the handle the server granted, not what was typed", async () => {
+ vi.mocked(invites.invite).mockResolvedValue({
+ outcome: "granted",
+ role: "viewer",
+ subject: "robin",
+ invite_id: "",
+ link_path: "",
+ url: "",
+ expires_at: null,
+ emailed: false,
+ });
+ const user = userEvent.setup();
+ render();
+ const field = await screen.findByRole("textbox", { name: "Login handle or email of the reader to add" });
+ await waitFor(() => expect(field).toBeEnabled());
+ await user.type(field, "Robin{Enter}");
+ await waitFor(() => expect(toast).toHaveBeenCalledWith(expect.stringMatching(/^robin is now a /), "ok"));
+ expect(invites.invite).toHaveBeenCalledWith({ org: "dev", namespace: "code-app" }, "Robin", expect.any(String));
+});
+
+it("adds a service account through grants.create, not grants.invite", async () => {
+ const user = userEvent.setup();
+ render();
+ const field = await screen.findByRole("textbox", { name: "Login handle or email of the reader to add" });
+ await waitFor(() => expect(field).toBeEnabled());
+ await user.type(field, "sa:ci-bot{Enter}");
+ await waitFor(() => expect(toast).toHaveBeenCalledWith(expect.stringMatching(/^sa:ci-bot is now a /), "ok"));
+ expect(api.createGrant).toHaveBeenCalledWith({ org: "dev", namespace: "code-app" }, "sa:ci-bot", expect.any(String));
+ expect(invites.invite).not.toHaveBeenCalled();
+});
+
+const invited = {
+ outcome: "invited" as const,
+ role: "viewer" as const,
+ subject: "",
+ invite_id: "abc",
+ link_path: "/spaces#invite=s3cret&org=dev&namespace=code-app",
+ url: "",
+ expires_at: "2026-12-11T12:00:00Z",
+ emailed: false,
+};
+
+it("makes one invitation for a submit while one is in flight", async () => {
+ let answer: (v: typeof invited) => void = () => {};
+ vi.mocked(invites.invite).mockImplementation(() => new Promise((r) => (answer = r)));
+ const user = userEvent.setup();
+ render();
+ const field = await screen.findByRole("textbox", { name: "Login handle or email of the reader to add" });
+ await waitFor(() => expect(field).toBeEnabled());
+ await user.type(field, "pat@example.com{Enter}");
+ await user.type(field, "{Enter}");
+ answer(invited);
+ await screen.findByRole("status");
+ expect(invites.invite).toHaveBeenCalledTimes(1);
+});
+
+it("takes the link down once its invitation is cancelled from the list", async () => {
+ vi.mocked(invites.invite).mockResolvedValue(invited);
+ vi.mocked(invites.listInvites).mockResolvedValue({
+ rows: [
+ {
+ invite_id: "abc",
+ email: "pat@example.com",
+ role: "viewer" as const,
+ created_by: "ann",
+ created_at: "2026-12-04T12:00:00Z",
+ expires_at: "2026-12-11T12:00:00Z",
+ stopped: false,
+ },
+ ],
+ truncated: false,
+ });
+ const user = userEvent.setup();
+ render();
+ const field = await screen.findByRole("textbox", { name: "Login handle or email of the reader to add" });
+ await waitFor(() => expect(field).toBeEnabled());
+ await user.type(field, "pat@example.com{Enter}");
+ await screen.findByText(/No account in this org has verified pat@example\.com/);
+ await user.click(await screen.findByRole("button", { name: "Cancel the invitation to pat@example.com" }));
+ await waitFor(() => expect(screen.queryByText(/No account in this org has verified/)).toBeNull());
+});
diff --git a/frontend/src/views/Code.tsx b/frontend/src/views/Code.tsx
index b79747f4663..ff2011d5ac2 100644
--- a/frontend/src/views/Code.tsx
+++ b/frontend/src/views/Code.tsx
@@ -34,6 +34,8 @@ import { useAbortableEffect, useVisiblePoll } from "../lib/hooks";
import { EmptyState } from "../components/EmptyState";
import { ScopeBadge } from "../components/ScopeBadge";
import { SubjectHelp } from "../components/SubjectHelp";
+import { invite, isPersonSpelling, type InviteResult } from "../api/invites";
+import { InviteSent, OpenInvitations } from "../components/Invitations";
import { IconButton } from "../components/IconButton";
import { ChoiceGroup } from "../components/ui/ChoiceGroup";
import { Modal, ModalFooter } from "../components/ui/Modal";
@@ -3043,6 +3045,10 @@ export function AccessTab({
// grants.list refused the caller (a viewer read): not a reader, so not a maintainer.
const [refused, setRefused] = useState(false);
const [subject, setSubject] = useState("");
+ // The invitation an add just made, with its link to copy; and how many, which reads the
+ // open invitations again.
+ const [sent, setSent] = useState<{ email: string; result: InviteResult } | null>(null);
+ const [invited, setInvited] = useState(0);
const [role, setRole] = useState("viewer");
const [busy, setBusy] = useState(null);
const [settingsOpen, setSettingsOpen] = useState(false);
@@ -3188,8 +3194,21 @@ export function AccessTab({
if (!s || !canManage) return;
setBusy("add");
try {
- await createGrant(id, s, role);
- toast(`${s} is now a ${roleWord(role)}`, "ok");
+ // A person by handle or email goes through grants.invite, which grants at once or
+ // answers a link to copy. Any other principal goes to grants.create as typed.
+ let granted = s;
+ if (isPersonSpelling(s)) {
+ const out = await invite(id, s, role);
+ if (out.outcome === "invited") {
+ setSent({ email: s, result: out });
+ setInvited((n) => n + 1);
+ setSubject("");
+ return;
+ }
+ granted = out.subject; // the handle the server granted, which may differ from what was typed
+ } else await createGrant(id, s, role);
+ toast(`${granted} is now a ${roleWord(role)}`, "ok");
+ setSent(null);
setSubject("");
load();
} catch (err) {
@@ -3592,8 +3611,21 @@ export function AccessTab({
Adding someone by name works under every rule. Agents read with a token that names this repository.
+ {sent && (
+
+
+
+ )}
)}
+ {canManage && (
+ load()}
+ onClosed={(inviteId) => setSent((s) => (s?.result.invite_id === inviteId ? null : s))}
+ />
+ )}
)}
diff --git a/frontend/src/views/CollectionSharing.test.tsx b/frontend/src/views/CollectionSharing.test.tsx
index ed5ec173e86..f8e6eaec703 100644
--- a/frontend/src/views/CollectionSharing.test.tsx
+++ b/frontend/src/views/CollectionSharing.test.tsx
@@ -22,6 +22,23 @@ const api = vi.hoisted(() => ({
isAuthDisabled: vi.fn(() => false),
}));
vi.mock("../api", async (importOriginal) => ({ ...(await importOriginal()), ...api }));
+// A person is added through grants.invite; a principal through grants.create.
+const invites = vi.hoisted(() => ({
+ invite: vi.fn(async (_id: unknown, subject: string, role: string) => ({
+ outcome: "granted" as const,
+ role,
+ subject,
+ invite_id: "",
+ link_path: "",
+ url: "",
+ expires_at: null,
+ emailed: false,
+ })),
+}));
+vi.mock("../api/invites", async (importOriginal) => ({
+ ...(await importOriginal()),
+ ...invites,
+}));
vi.mock("../components/ConfirmDialog", async (importOriginal) => ({
...(await importOriginal()),
confirmAction: async () => true,
@@ -629,7 +646,7 @@ describe("the collection header", () => {
fireEvent.click(within(dialog).getByRole("button", { name: "Add member" }));
fireEvent.change(within(dialog).getByRole("textbox"), { target: { value: "bob" } });
fireEvent.click(within(dialog).getByRole("button", { name: "Add" }));
- await waitFor(() => expect(api.createGrant).toHaveBeenCalled());
+ await waitFor(() => expect(invites.invite).toHaveBeenCalled());
let answer: (v: unknown) => void = () => {};
api.listGrants.mockReturnValue(new Promise((r) => (answer = r)));
fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));
@@ -712,7 +729,7 @@ describe("the collection header", () => {
fireEvent.click(await within(dialog).findByRole("button", { name: "Add member" }));
fireEvent.change(within(dialog).getByRole("textbox"), { target: { value: "bob" } });
fireEvent.click(within(dialog).getByRole("button", { name: "Add" }));
- await waitFor(() => expect(api.createGrant).toHaveBeenCalled());
+ await waitFor(() => expect(invites.invite).toHaveBeenCalled());
const through = await within(dialog).findByRole("region", { name: "Also can see it, through Engineering" });
fireEvent.click(within(through).getByRole("link", { name: "Engineering" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
diff --git a/frontend/src/views/InvitationCard.test.tsx b/frontend/src/views/InvitationCard.test.tsx
new file mode 100644
index 00000000000..ad398a7c6fe
--- /dev/null
+++ b/frontend/src/views/InvitationCard.test.tsx
@@ -0,0 +1,368 @@
+import { act, cleanup, render, screen, waitFor } from "../test/rtl";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { listMine } from "../api";
+import { acceptInvite } from "../api/invites";
+import { dropInviteLink, INVITE_LINK, keptInviteLink, takeInviteLink } from "../lib/inviteLink";
+import { ApiError } from "../lib/errors";
+import { invalidateShared, sharedMine } from "../lib/sharedReads";
+import { useStore } from "../lib/state";
+import { InvitationCard } from "./InvitationCard";
+
+// An invitation link's secret rides in the fragment; the card moves it into the tab's session
+// and accepts it as the signed-in person.
+
+vi.mock("../api/invites", () => ({ acceptInvite: vi.fn() }));
+vi.mock("../api", async (importOriginal) => ({
+ ...(await importOriginal()),
+ listMine: vi.fn(async () => []),
+}));
+
+beforeEach(() => {
+ sessionStorage.clear();
+ vi.mocked(acceptInvite).mockReset();
+ vi.mocked(listMine).mockClear();
+ invalidateShared();
+ useStore.setState({ identity: { org: "dev", namespace: "home", agent: "loom-ui" } });
+});
+afterEach(() => cleanup());
+
+describe("takeInviteLink", () => {
+ it("does not bring back an older link storage held once one it refused is dropped", () => {
+ sessionStorage.setItem(INVITE_LINK, JSON.stringify({ secret: "old", org: "dev", namespace: "stale" }));
+ const refuse = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new DOMException("full", "QuotaExceededError");
+ });
+ try {
+ history.replaceState(null, "", "/spaces#invite=s3cret&org=dev&namespace=alerts");
+ takeInviteLink();
+ dropInviteLink("s3cret");
+ expect(keptInviteLink()).toBeNull();
+ } finally {
+ refuse.mockRestore();
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it("moves the link out of the address into the session", () => {
+ history.replaceState(null, "", "/spaces#invite=s3cret&org=dev&namespace=team-alerts");
+ takeInviteLink();
+ expect(window.location.pathname + window.location.hash).toBe("/spaces");
+ expect(JSON.parse(sessionStorage.getItem(INVITE_LINK) ?? "null")).toEqual({
+ secret: "s3cret",
+ org: "dev",
+ namespace: "team-alerts",
+ });
+ });
+
+ it.each(["team_alpha", "TeamAlpha", "proj.v2", "data team"])(
+ "keeps a link to %s, a name the server registers though the create dialog refuses it",
+ (namespace) => {
+ history.replaceState(null, "", `/spaces#invite=s3cret&org=dev&namespace=${namespace}`);
+ expect(takeInviteLink()).toEqual({ secret: "s3cret", org: "dev", namespace });
+ expect(keptInviteLink()).toEqual({ secret: "s3cret", org: "dev", namespace });
+ },
+ );
+
+ it("leaves any other fragment alone", () => {
+ history.replaceState(null, "", "/spaces#token=x");
+ takeInviteLink();
+ expect(window.location.hash).toBe("#token=x");
+ expect(sessionStorage.getItem(INVITE_LINK)).toBeNull();
+ });
+});
+
+function opened(): void {
+ sessionStorage.setItem(INVITE_LINK, JSON.stringify({ secret: "s3cret", org: "dev", namespace: "alerts" }));
+ render();
+}
+
+describe("InvitationCard", () => {
+ it.each([
+ ["namespace", "dev", "Call the help desk", "You're invited to a namespace."],
+ ["org", "Call the help desk", "alerts", "in another org. Sign in to that org to accept it."],
+ ])("opens a link whose %s is a sentence without printing it", (_, org, namespace, said) => {
+ sessionStorage.setItem(INVITE_LINK, JSON.stringify({ secret: "s3cret", org, namespace }));
+ render();
+ expect(screen.getByRole("region", { name: "Invitation" })).toHaveTextContent(said);
+ expect(screen.queryByText(/help desk/)).toBeNull();
+ });
+
+ it("accepts as the signed-in person and switches to the namespace", async () => {
+ vi.mocked(acceptInvite).mockResolvedValue({ namespace: "alerts", role: "writer" });
+ await sharedMine("dev");
+ const user = userEvent.setup();
+ opened();
+ expect(screen.getByRole("region", { name: "Invitation" })).toHaveTextContent("You're invited to alerts.");
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(acceptInvite).toHaveBeenCalledWith(expect.objectContaining({ org: "dev", namespace: "alerts" }), "s3cret");
+ expect(useStore.getState().identity?.namespace).toBe("alerts");
+ expect(sessionStorage.getItem(INVITE_LINK)).toBeNull();
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ // The new grant is read at once, not after the shared list_mine read's 30 s.
+ await sharedMine("dev");
+ expect(listMine).toHaveBeenCalledTimes(2);
+ });
+
+ it("opens an accepted collection in the Library, keeping the namespace in use", async () => {
+ vi.mocked(acceptInvite).mockResolvedValue({ namespace: "col-runbooks", role: "viewer" });
+ const real = useStore.getState().navigate;
+ const navigate = vi.fn();
+ useStore.setState({ navigate });
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(navigate).toHaveBeenCalledWith("knowledge", { query: { collection: "col-runbooks" } });
+ expect(useStore.getState().identity?.namespace).toBe("home");
+ useStore.setState({ navigate: real });
+ });
+
+ it.each([
+ [
+ 404,
+ "RESOURCE_NOT_FOUND",
+ "this invitation link admits nobody now: it is used, cancelled or expired, its namespace is deleted, or its maker no longer stands behind it; ask for a new one",
+ ],
+ [422, "VALIDATION_FAILED", "an invitation is accepted by a person, signed in as themselves"],
+ ])("says why a refused link is refused and offers only Close (%i %s)", async (status, code, message) => {
+ vi.mocked(acceptInvite).mockRejectedValue(new ApiError({ status, code, message }));
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(await screen.findByText(message, { exact: false })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Accept invitation" })).toBeNull();
+ expect(sessionStorage.getItem(INVITE_LINK)).toBeNull();
+ expect(useStore.getState().identity?.namespace).toBe("home");
+ });
+
+ it("sends one accept for a link however often Accept is pressed while it is in flight", async () => {
+ let answer: (v: Awaited>) => void = () => {};
+ vi.mocked(acceptInvite).mockReturnValue(new Promise((r) => (answer = r)));
+ opened();
+ const button = screen.getByRole("button", { name: "Accept invitation" });
+ act(() => {
+ button.click();
+ button.click();
+ });
+ expect(acceptInvite).toHaveBeenCalledTimes(1);
+ await act(async () => answer({ namespace: "alerts", role: "writer" }));
+ });
+
+ it("keeps the link when the 404 is not the server's refusal of it", async () => {
+ // A replica of the previous build answers an op it does not serve with a bare 404.
+ vi.mocked(acceptInvite).mockRejectedValueOnce(new ApiError({ status: 404, message: "Not Found" }));
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ await waitFor(() => expect(screen.getByRole("button", { name: "Accept invitation" })).toBeEnabled());
+ expect(acceptInvite).toHaveBeenCalledTimes(1);
+ expect(sessionStorage.getItem(INVITE_LINK)).not.toBeNull();
+ });
+
+ it("shows a link pasted into a tab already on the page", async () => {
+ render();
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ history.replaceState(null, "", "/spaces#invite=s3cret&org=dev&namespace=alerts");
+ act(() => {
+ window.dispatchEvent(new HashChangeEvent("hashchange"));
+ });
+ try {
+ expect(await screen.findByRole("button", { name: "Accept invitation" })).toBeEnabled();
+ } finally {
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it("offers Accept again for a refused link opened again", async () => {
+ // Refused while its maker did not stand; they may since, so it is the server's to say.
+ vi.mocked(acceptInvite).mockRejectedValueOnce(
+ new ApiError({ status: 404, code: "RESOURCE_NOT_FOUND", message: "admits nobody now" }),
+ );
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(await screen.findByText("admits nobody now", { exact: false })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Accept invitation" })).toBeNull();
+ history.replaceState(null, "", "/spaces#invite=s3cret&org=dev&namespace=alerts");
+ act(() => {
+ window.dispatchEvent(new HashChangeEvent("hashchange"));
+ });
+ try {
+ expect(await screen.findByRole("button", { name: "Accept invitation" })).toBeEnabled();
+ expect(screen.queryByText("admits nobody now", { exact: false })).toBeNull();
+ } finally {
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it("offers Accept for a link pasted after one was accepted", async () => {
+ vi.mocked(acceptInvite).mockResolvedValue({ namespace: "alerts", role: "writer" });
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ history.replaceState(null, "", "/spaces#invite=other&org=dev&namespace=ops");
+ act(() => {
+ window.dispatchEvent(new HashChangeEvent("hashchange"));
+ });
+ try {
+ expect(await screen.findByRole("button", { name: "Accept invitation" })).toBeEnabled();
+ } finally {
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it.each([
+ ["accepted", () => Promise.resolve({ namespace: "alerts", role: "writer" as const })],
+ ["refused", () => Promise.reject(new ApiError({ status: 404, code: "RESOURCE_NOT_FOUND", message: "used" }))],
+ ])("keeps a link pasted while another's accept is in flight, once that one is %s", async (_, answer) => {
+ let settle: () => void = () => {};
+ vi.mocked(acceptInvite).mockReturnValueOnce(
+ new Promise((resolve, reject) => {
+ settle = () => void answer().then(resolve, reject);
+ }),
+ );
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ history.replaceState(null, "", "/spaces#invite=other&org=dev&namespace=ops");
+ act(() => {
+ window.dispatchEvent(new HashChangeEvent("hashchange"));
+ });
+ try {
+ // The new link's own Accept, not the one still waiting on the other link's answer.
+ expect(screen.getByRole("button", { name: "Accept invitation" })).toBeEnabled();
+ await act(async () => settle());
+ expect(screen.getByRole("region", { name: "Invitation" })).toHaveTextContent("You're invited to ops.");
+ await waitFor(() => expect(screen.getByRole("button", { name: "Accept invitation" })).toBeEnabled());
+ expect(screen.queryByText(/used/)).toBeNull();
+ expect(JSON.parse(sessionStorage.getItem(INVITE_LINK) ?? "null")?.secret).toBe("other");
+ } finally {
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it("leaves a link set aside by Not now aside when the fragment changes", async () => {
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Not now" }));
+ history.replaceState(null, "", "/spaces#token=x");
+ act(() => {
+ window.dispatchEvent(new HashChangeEvent("hashchange"));
+ });
+ try {
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ } finally {
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it("shows the link the address carries over an older one storage still holds", () => {
+ sessionStorage.setItem(INVITE_LINK, JSON.stringify({ secret: "old", org: "dev", namespace: "stale" }));
+ const refuse = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new DOMException("full", "QuotaExceededError");
+ });
+ try {
+ history.replaceState(null, "", "/spaces#invite=s3cret&org=dev&namespace=alerts");
+ render();
+ expect(screen.getByRole("region", { name: "Invitation" })).toHaveTextContent("You're invited to alerts.");
+ } finally {
+ refuse.mockRestore();
+ dropInviteLink("s3cret");
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it("keeps a link set aside with Not now for the next visit where session storage is refused", async () => {
+ const refuse = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new DOMException("blocked", "SecurityError");
+ });
+ try {
+ history.replaceState(null, "", "/spaces#invite=s3cret&org=dev&namespace=alerts");
+ const user = userEvent.setup();
+ const first = render();
+ await user.click(screen.getByRole("button", { name: "Not now" }));
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ first.unmount();
+ render();
+ expect(screen.getByRole("region", { name: "Invitation" })).toHaveTextContent("You're invited to alerts.");
+ } finally {
+ refuse.mockRestore();
+ dropInviteLink("s3cret");
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it("holds the link itself where session storage is refused", () => {
+ const refuse = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new DOMException("blocked", "SecurityError");
+ });
+ try {
+ history.replaceState(null, "", "/spaces#invite=s3cret&org=dev&namespace=alerts");
+ render();
+ expect(screen.getByRole("button", { name: "Accept invitation" })).toBeEnabled();
+ expect(window.location.hash).toBe("");
+ } finally {
+ refuse.mockRestore();
+ dropInviteLink("s3cret");
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it("keeps the link and Accept through an outage", async () => {
+ vi.mocked(acceptInvite).mockRejectedValueOnce(
+ new ApiError({ status: 503, code: "BACKEND_UNAVAILABLE", message: "grants could not be read" }),
+ );
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(await screen.findByText(/could not be read/)).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Accept invitation" })).toBeEnabled();
+ expect(sessionStorage.getItem(INVITE_LINK)).not.toBeNull();
+ });
+
+ it("keeps the link through a sign-in the session ended for", async () => {
+ vi.mocked(acceptInvite).mockRejectedValueOnce(
+ new ApiError({ status: 401, code: "AUTH_REQUIRED", message: "sign in again" }),
+ );
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(await screen.findByText(/sign in again/i)).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Accept invitation" })).toBeEnabled();
+ expect(sessionStorage.getItem(INVITE_LINK)).not.toBeNull();
+ });
+
+ it("keeps the link for the next visit on Not now", async () => {
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Not now" }));
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ expect(sessionStorage.getItem(INVITE_LINK)).not.toBeNull();
+ cleanup();
+ render();
+ expect(screen.getByRole("region", { name: "Invitation" })).toBeInTheDocument();
+ });
+
+ it("asks for a sign-in to another org's link instead of offering Accept", () => {
+ useStore.setState({ identity: { org: "acme", namespace: "home", agent: "loom-ui" } });
+ opened();
+ expect(screen.getByRole("region", { name: "Invitation" })).toHaveTextContent("Sign in to dev to accept it.");
+ expect(screen.queryByRole("button", { name: "Accept invitation" })).toBeNull();
+ expect(screen.getByRole("button", { name: "Close" })).toBeInTheDocument();
+ });
+
+ it("shows nothing without an invitation", () => {
+ render();
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ });
+});
+
+describe("InvitationCard on an address that still carries the link", () => {
+ it("takes the link from the address itself", () => {
+ history.replaceState(null, "", "/spaces#invite=s3cret&org=dev&namespace=alerts");
+ render();
+ expect(screen.getByRole("region", { name: "Invitation" })).toHaveTextContent("You're invited to alerts.");
+ expect(window.location.hash).toBe("");
+ });
+});
diff --git a/frontend/src/views/InvitationCard.tsx b/frontend/src/views/InvitationCard.tsx
new file mode 100644
index 00000000000..3c2be0a62f9
--- /dev/null
+++ b/frontend/src/views/InvitationCard.tsx
@@ -0,0 +1,116 @@
+import { useEffect, useRef, useState } from "react";
+import { Button } from "@clickhouse/click-ui/Button";
+import { setSavedNamespace } from "../api";
+import { acceptInvite } from "../api/invites";
+import { Alert } from "../components/ui";
+import { toast } from "../components/Toast";
+import { dropInviteLink as drop, keptInviteLink, type InviteLink, takeInviteLink } from "../lib/inviteLink";
+import { humanizeError } from "../lib/errorWords";
+import { ApiError } from "../lib/errors";
+import { isCollectionName } from "../lib/namespace";
+import { invalidateShared } from "../lib/sharedReads";
+import { useStore } from "../lib/state";
+
+function stashed(): InviteLink | null {
+ // An address opened signed in, or after a password sign-in, still carries it.
+ return takeInviteLink() ?? keptInviteLink();
+}
+
+/** The invitation link this tab opened, for the signed-in person to accept. */
+export function InvitationCard() {
+ const [link, setLink] = useState(stashed);
+ // Each keyed by the link's secret: an answer about one link says nothing of one pasted since.
+ const [error, setError] = useState<{ secret: string; text: string } | null>(null);
+ // The server refused the link: RESOURCE_NOT_FOUND when it admits nobody now (used,
+ // cancelled, expired, its namespace deleted or its maker no longer behind it),
+ // VALIDATION_FAILED when this account cannot accept it. Only Close is left, until the link
+ // is opened again: one that admits again later gets Accept back.
+ const [refusedSecret, setRefusedSecret] = useState(null);
+ const [busySecret, setBusySecret] = useState(null);
+ // Links with an accept in flight, read before a render: a second press of Accept sends
+ // nothing, since the server answers it before the first's grant is in place.
+ const inFlight = useRef(new Set());
+ const identity = useStore((s) => s.identity);
+ const setIdentity = useStore((s) => s.setIdentity);
+ const navigate = useStore((s) => s.navigate);
+ // A link pasted into a tab already on this page changes only the fragment. Only a link
+ // the address carries now: one Not now set aside stays aside.
+ useEffect(() => {
+ const opened = () => {
+ const next = takeInviteLink();
+ if (!next) return;
+ setLink(next);
+ setRefusedSecret(null);
+ setError(null);
+ };
+ window.addEventListener("hashchange", opened);
+ return () => window.removeEventListener("hashchange", opened);
+ }, []);
+ if (!link) return null;
+
+ const refused = refusedSecret === link.secret;
+ const shownError = error?.secret === link.secret ? error.text : null;
+ // A link to another org is accepted only signed in there: the server refuses it here.
+ const elsewhere = Boolean(identity && identity.org !== link.org);
+ // Printed before the server reads the link, so a value that holds whitespace (a sentence
+ // a link made up, though the server may register such a name) is not: the link still opens.
+ const [namespace, org] = [link.namespace, link.org].map((v) => (/\s/.test(v) ? null : v));
+ const close = () => {
+ drop(link.secret);
+ setLink(null);
+ };
+ const accept = async () => {
+ const current = link;
+ if (inFlight.current.has(current.secret)) return;
+ inFlight.current.add(current.secret);
+ setBusySecret(current.secret);
+ setError(null);
+ try {
+ const out = await acceptInvite(current, current.secret);
+ drop(current.secret);
+ setLink((shown) => (shown?.secret === current.secret ? null : shown));
+ toast(`Joined ${out.namespace} as ${out.role}`, "ok");
+ invalidateShared("mine:");
+ // A collection opens in the Library; a namespace becomes the one in use.
+ if (isCollectionName(out.namespace)) navigate("knowledge", { query: { collection: out.namespace } });
+ else if (identity && identity.org === current.org) {
+ setIdentity({ ...identity, namespace: out.namespace });
+ setSavedNamespace(out.namespace);
+ }
+ } catch (e) {
+ // Only the server's refusal of the link drops it: an ended session, a rate limit or a
+ // replica that does not serve the op yet keeps it for a retry.
+ if (e instanceof ApiError && (e.code === "RESOURCE_NOT_FOUND" || e.code === "VALIDATION_FAILED")) {
+ drop(current.secret);
+ setRefusedSecret(current.secret);
+ }
+ setError({ secret: current.secret, text: humanizeError(e) });
+ } finally {
+ // The card stays mounted after an accept, and the next pasted link reuses it.
+ inFlight.current.delete(current.secret);
+ setBusySecret((s) => (s === current.secret ? null : s));
+ }
+ };
+
+ return (
+
+
+ You're invited to {namespace ? {namespace} : "a namespace"}
+ {elsewhere ? ` in ${org ?? "another org"}. Sign in to ${org ?? "that org"} to accept it.` : "."}
+ {elsewhere ? "" : " Accepting gives the account you're signed in as the role the invitation names."}
+
+ {shownError && }
+
+ {/* Not now keeps the link in this tab, so the card is back on the next visit. */}
+
+ {!refused && !elsewhere && (
+
+ )}
+
+
+ );
+}
diff --git a/loom.example.yaml b/loom.example.yaml
index dd28acaef10..73dc833cbc2 100644
--- a/loom.example.yaml
+++ b/loom.example.yaml
@@ -891,6 +891,20 @@ settings:
# Default org for self-signed tokens. [restart]
# self_signup_org: "dev"
+ # The From address of an invitation email, e.g. `Loom `: one ASCII
+ # address (quote a display name with `,` or `;`), else refused at load. Empty sends
+ # none. [restart]
+ # mail_from: ""
+
+ # Seconds an invitation email's whole send may take, at most 30; past it the email is
+ # reported not sent and the link is shown to pass on, inside the dashboard's 60 s
+ # request. [restart]
+ # smtp_timeout_seconds: 10.0
+
+ # Seconds an invitation link stays valid, from one hour to 30 days: it admits whoever
+ # opens it. [restart]
+ # invite_ttl_seconds: 604800
+
# How callers authenticate: "single-user" (no auth, one anonymous identity),
# "trust-network" (self-signup, first claim wins) or "gateway" (an upstream proxy
# mints short-lived Loom JWTs with the shared HS256 secret; Loom only validates).
diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json
index fadb74518aa..23420d3cef6 100644
--- a/schemas/loom-settings.schema.json
+++ b/schemas/loom-settings.schema.json
@@ -3318,6 +3318,13 @@
"type": "number",
"description": "Seconds between this process's loom.instances heartbeats, each of which also compares it with the deployment's published configuration. A row not renewed for three intervals is not live."
},
+ "invite_ttl_seconds": {
+ "default": 604800,
+ "maximum": 2592000,
+ "minimum": 3600,
+ "type": "integer",
+ "description": "Seconds an invitation link stays valid, from one hour to 30 days: it admits whoever opens it."
+ },
"jwt_audience": {
"default": "loom-platform",
"type": "string",
@@ -4128,6 +4135,11 @@
"type": "string",
"description": "Root log level. (Bind host/port are flags of `loom serve`, not settings.)"
},
+ "mail_from": {
+ "default": "",
+ "type": "string",
+ "description": "The From address of an invitation email, e.g. `Loom `: one ASCII address (quote a display name with `,` or `;`), else refused at load. Empty sends none."
+ },
"max_request_bytes": {
"default": 33554432,
"type": "integer",
@@ -6962,6 +6974,13 @@
"type": "number",
"description": "Seconds a process keeps serving after SIGTERM while /v1/health/ready answers 503, so the load balancer stops routing to it before its port closes. Size it to the LB's probe interval × failure threshold. 0 = stop at once."
},
+ "smtp_timeout_seconds": {
+ "default": 10.0,
+ "exclusiveMinimum": 0,
+ "maximum": 30,
+ "type": "number",
+ "description": "Seconds an invitation email's whole send may take, at most 30; past it the email is reported not sent and the link is shown to pass on, inside the dashboard's 60 s request."
+ },
"storage_authority": {
"default": "clickhouse",
"enum": [
diff --git a/schemas/migrations/139_namespace_invites.sql b/schemas/migrations/139_namespace_invites.sql
new file mode 100644
index 00000000000..08285728c73
--- /dev/null
+++ b/schemas/migrations/139_namespace_invites.sql
@@ -0,0 +1,30 @@
+-- Invitations to a namespace, for a person no account signs in as yet.
+--
+-- grants.invite writes one row per invitation: the role it gives, the email it was made
+-- for and who made it, whose grants grants.accept_invite reads again: an invitation never
+-- outlasts its maker's admin. The link it hands out carries a random secret; the row
+-- is keyed by the secret's SHA-256 (`invite_id`), so a row read out of storage admits nobody.
+-- grants.accept_invite writes the row again with `state = 'accepted'` and who accepted
+-- it, and, when the grant then fails, as it was (naming no accepter if it was closed
+-- meanwhile); grants.cancel_invite with `state = 'cancelled'`, over an open or an
+-- accepted one; and a user's erasure with `created_by = ''`, cancelled if it was open.
+-- An invitation lives for `expires_at` (Unix seconds); the TTL drops the rows a week
+-- after that. A build before this one never reads the table.
+CREATE TABLE IF NOT EXISTS loom.namespace_invites
+(
+ org LowCardinality(String),
+ namespace LowCardinality(String),
+ invite_id String,
+ email String DEFAULT '',
+ role LowCardinality(String),
+ created_by String,
+ created_at DateTime64(3, 'UTC'),
+ expires_at UInt32,
+ state LowCardinality(String) DEFAULT 'open',
+ accepted_by String DEFAULT '',
+ version UInt64 DEFAULT toUInt64(toUnixTimestamp64Nano(now64(9)))
+)
+ENGINE = ReplacingMergeTree(version)
+ORDER BY (org, namespace, invite_id)
+TTL toDateTime(expires_at) + INTERVAL 7 DAY
+SETTINGS non_replicated_deduplication_window = 1000;
diff --git a/schemas/schema.sql b/schemas/schema.sql
index f91ef39d870..3a3b3af2782 100644
--- a/schemas/schema.sql
+++ b/schemas/schema.sql
@@ -16,13 +16,13 @@
-- Do NOT hand-edit. Edit schemas/migrations/*.sql and re-dump.
-- CI verifies this file matches what migrations would produce.
--
--- Counts: 205 tables + 5 views + 19 materialized views.
+-- Counts: 206 tables + 5 views + 19 materialized views.
CREATE DATABASE IF NOT EXISTS `loom`;
CREATE DATABASE IF NOT EXISTS `loom_telemetry`;
-- ======================================================================
--- Tables (205)
+-- Tables (206)
-- ======================================================================
-- loom.acl_versions
@@ -3506,6 +3506,26 @@ ENGINE = MergeTree
ORDER BY (org, namespace, revision)
SETTINGS non_replicated_deduplication_window = 1000, index_granularity = 8192;
+-- loom.namespace_invites
+CREATE TABLE IF NOT EXISTS loom.namespace_invites
+(
+ `org` LowCardinality(String),
+ `namespace` LowCardinality(String),
+ `invite_id` String,
+ `email` String DEFAULT '',
+ `role` LowCardinality(String),
+ `created_by` String,
+ `created_at` DateTime64(3, 'UTC'),
+ `expires_at` UInt32,
+ `state` LowCardinality(String) DEFAULT 'open',
+ `accepted_by` String DEFAULT '',
+ `version` UInt64 DEFAULT toUInt64(toUnixTimestamp64Nano(now64(9)))
+)
+ENGINE = ReplacingMergeTree(version)
+ORDER BY (org, namespace, invite_id)
+TTL toDateTime(expires_at) + toIntervalDay(7)
+SETTINGS non_replicated_deduplication_window = 1000, index_granularity = 8192;
+
-- loom.namespace_ontology
CREATE TABLE IF NOT EXISTS loom.namespace_ontology
(
diff --git a/sdk/go/client.gen.go b/sdk/go/client.gen.go
index 74cc015dd85..9e06437ab99 100644
--- a/sdk/go/client.gen.go
+++ b/sdk/go/client.gen.go
@@ -1103,21 +1103,45 @@ type FindingEvidence = wire.FindingEvidence
// GrantEntry is a model used by Loom operations.
type GrantEntry = wire.GrantEntry
+// GrantsAcceptInviteInput is the request to grants.accept_invite.
+type GrantsAcceptInviteInput = wire.GrantsAcceptInviteInput
+
+// GrantsAcceptInviteOutput is the response from grants.accept_invite.
+type GrantsAcceptInviteOutput = wire.GrantsAcceptInviteOutput
+
// GrantsApproveInput is the request to grants.approve.
type GrantsApproveInput = wire.GrantsApproveInput
// GrantsApproveOutput is the response from grants.approve.
type GrantsApproveOutput = wire.GrantsApproveOutput
+// GrantsCancelInviteInput is the request to grants.cancel_invite.
+type GrantsCancelInviteInput = wire.GrantsCancelInviteInput
+
+// GrantsCancelInviteOutput is the response from grants.cancel_invite.
+type GrantsCancelInviteOutput = wire.GrantsCancelInviteOutput
+
// GrantsCreateInput is the request to grants.create.
type GrantsCreateInput = wire.GrantsCreateInput
// GrantsCreateOutput is the response from grants.create.
type GrantsCreateOutput = wire.GrantsCreateOutput
+// GrantsInviteInput is the request to grants.invite.
+type GrantsInviteInput = wire.GrantsInviteInput
+
+// GrantsInviteOutput is the response from grants.invite.
+type GrantsInviteOutput = wire.GrantsInviteOutput
+
// GrantsListInput is the request to grants.list.
type GrantsListInput = wire.GrantsListInput
+// GrantsListInvitesInput is the request to grants.list_invites.
+type GrantsListInvitesInput = wire.GrantsListInvitesInput
+
+// GrantsListInvitesOutput is the response from grants.list_invites.
+type GrantsListInvitesOutput = wire.GrantsListInvitesOutput
+
// GrantsListOutput is the response from grants.list.
type GrantsListOutput = wire.GrantsListOutput
@@ -1262,6 +1286,9 @@ type InventoryScope = wire.InventoryScope
// InventorySection is a model used by Loom operations.
type InventorySection = wire.InventorySection
+// InviteEntry is a model used by Loom operations.
+type InviteEntry = wire.InviteEntry
+
// KnowledgeAddInput is the request to knowledge.add.
type KnowledgeAddInput = wire.KnowledgeAddInput
@@ -5700,6 +5727,20 @@ func (s FactsService) Traverse(ctx context.Context, seedEntity string, opts ...O
return callOperation[FactsTraverseOutput](s.client, ctx, "facts.traverse", in)
}
+// AcceptInvite calls grants.accept_invite.
+// Use WithInput to supply additional request fields.
+func (s GrantsService) AcceptInvite(ctx context.Context, secret string, opts ...Option[GrantsAcceptInviteInput]) (*GrantsAcceptInviteOutput, error) {
+ in := applyOptions(opts)
+ in.Secret = secret
+ if in.Namespace == "" {
+ in.Namespace = s.client.identity.Namespace
+ }
+ if in.Org == "" {
+ in.Org = s.client.identity.Org
+ }
+ return callOperation[GrantsAcceptInviteOutput](s.client, ctx, "grants.accept_invite", in)
+}
+
// Approve calls grants.approve.
// Use WithInput to supply additional request fields.
func (s GrantsService) Approve(ctx context.Context, subject string, opts ...Option[GrantsApproveInput]) (*GrantsApproveOutput, error) {
@@ -5714,6 +5755,20 @@ func (s GrantsService) Approve(ctx context.Context, subject string, opts ...Opti
return callOperation[GrantsApproveOutput](s.client, ctx, "grants.approve", in)
}
+// CancelInvite calls grants.cancel_invite.
+// Use WithInput to supply additional request fields.
+func (s GrantsService) CancelInvite(ctx context.Context, inviteID string, opts ...Option[GrantsCancelInviteInput]) (*GrantsCancelInviteOutput, error) {
+ in := applyOptions(opts)
+ in.InviteID = inviteID
+ if in.Namespace == "" {
+ in.Namespace = s.client.identity.Namespace
+ }
+ if in.Org == "" {
+ in.Org = s.client.identity.Org
+ }
+ return callOperation[GrantsCancelInviteOutput](s.client, ctx, "grants.cancel_invite", in)
+}
+
// Create calls grants.create.
func (s GrantsService) Create(ctx context.Context, in GrantsCreateInput) (*GrantsCreateOutput, error) {
if in.Namespace == "" {
@@ -5725,6 +5780,17 @@ func (s GrantsService) Create(ctx context.Context, in GrantsCreateInput) (*Grant
return callOperation[GrantsCreateOutput](s.client, ctx, "grants.create", in)
}
+// Invite calls grants.invite.
+func (s GrantsService) Invite(ctx context.Context, in GrantsInviteInput) (*GrantsInviteOutput, error) {
+ if in.Namespace == "" {
+ in.Namespace = s.client.identity.Namespace
+ }
+ if in.Org == "" {
+ in.Org = s.client.identity.Org
+ }
+ return callOperation[GrantsInviteOutput](s.client, ctx, "grants.invite", in)
+}
+
// List calls grants.list.
// Use WithInput to supply additional request fields.
func (s GrantsService) List(ctx context.Context, opts ...Option[GrantsListInput]) (*GrantsListOutput, error) {
@@ -5738,6 +5804,19 @@ func (s GrantsService) List(ctx context.Context, opts ...Option[GrantsListInput]
return callOperation[GrantsListOutput](s.client, ctx, "grants.list", in)
}
+// ListInvites calls grants.list_invites.
+// Use WithInput to supply additional request fields.
+func (s GrantsService) ListInvites(ctx context.Context, opts ...Option[GrantsListInvitesInput]) (*GrantsListInvitesOutput, error) {
+ in := applyOptions(opts)
+ if in.Namespace == "" {
+ in.Namespace = s.client.identity.Namespace
+ }
+ if in.Org == "" {
+ in.Org = s.client.identity.Org
+ }
+ return callOperation[GrantsListInvitesOutput](s.client, ctx, "grants.list_invites", in)
+}
+
// PendingForMe calls grants.pending_for_me.
// Use WithInput to supply additional request fields.
func (s GrantsService) PendingForMe(ctx context.Context, opts ...Option[GrantsPendingForMeInput]) (*GrantsPendingForMeOutput, error) {
diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go
index 41aa37cea8d..0aca22f37cd 100644
--- a/sdk/go/wire/models.gen.go
+++ b/sdk/go/wire/models.gen.go
@@ -4693,6 +4693,23 @@ type GrantEntry struct {
Also *[]string `json:"also,omitempty"`
}
+// GrantsAcceptInviteInput is the request to grants.accept_invite.
+type GrantsAcceptInviteInput struct {
+ Org string `json:"org"`
+ Namespace string `json:"namespace"`
+ Secret string `json:"secret"`
+}
+
+// GrantsAcceptInviteOutput is the response from grants.accept_invite.
+type GrantsAcceptInviteOutput struct {
+ IgnoredArgs *[]string `json:"ignored_args,omitempty"`
+ DidYouMean *map[string]string `json:"did_you_mean,omitempty"`
+ Mirrored *bool `json:"mirrored,omitempty"`
+ Degraded *[]string `json:"degraded,omitempty"`
+ Namespace string `json:"namespace"`
+ Role string `json:"role"`
+}
+
// GrantsApproveInput is the request to grants.approve.
type GrantsApproveInput struct {
Org string `json:"org"`
@@ -4715,6 +4732,22 @@ type GrantsApproveOutput struct {
DecidedAt string `json:"decided_at"`
}
+// GrantsCancelInviteInput is the request to grants.cancel_invite.
+type GrantsCancelInviteInput struct {
+ Org string `json:"org"`
+ Namespace string `json:"namespace"`
+ InviteID string `json:"invite_id"`
+}
+
+// GrantsCancelInviteOutput is the response from grants.cancel_invite.
+type GrantsCancelInviteOutput struct {
+ IgnoredArgs *[]string `json:"ignored_args,omitempty"`
+ DidYouMean *map[string]string `json:"did_you_mean,omitempty"`
+ Mirrored *bool `json:"mirrored,omitempty"`
+ Degraded *[]string `json:"degraded,omitempty"`
+ Cancelled bool `json:"cancelled"`
+}
+
// GrantsCreateInput is the request to grants.create.
type GrantsCreateInput struct {
Org string `json:"org"`
@@ -4738,6 +4771,30 @@ type GrantsCreateOutput struct {
GrantedAt string `json:"granted_at"`
}
+// GrantsInviteInput is the request to grants.invite.
+type GrantsInviteInput struct {
+ Org string `json:"org"`
+ Namespace string `json:"namespace"`
+ To string `json:"to"`
+ Role string `json:"role"`
+}
+
+// GrantsInviteOutput is the response from grants.invite.
+type GrantsInviteOutput struct {
+ IgnoredArgs *[]string `json:"ignored_args,omitempty"`
+ DidYouMean *map[string]string `json:"did_you_mean,omitempty"`
+ Mirrored *bool `json:"mirrored,omitempty"`
+ Degraded *[]string `json:"degraded,omitempty"`
+ Outcome string `json:"outcome"`
+ Role string `json:"role"`
+ Subject *string `json:"subject,omitempty"`
+ InviteID *string `json:"invite_id,omitempty"`
+ LinkPath *string `json:"link_path,omitempty"`
+ URL *string `json:"url,omitempty"`
+ ExpiresAt Optional[string] `json:"expires_at,omitempty"`
+ Emailed *bool `json:"emailed,omitempty"`
+}
+
// GrantsListInput is the request to grants.list.
type GrantsListInput struct {
Org string `json:"org"`
@@ -4747,6 +4804,22 @@ type GrantsListInput struct {
Fields Optional[[]string] `json:"fields,omitempty"`
}
+// GrantsListInvitesInput is the request to grants.list_invites.
+type GrantsListInvitesInput struct {
+ Org string `json:"org"`
+ Namespace string `json:"namespace"`
+}
+
+// GrantsListInvitesOutput is the response from grants.list_invites.
+type GrantsListInvitesOutput struct {
+ IgnoredArgs *[]string `json:"ignored_args,omitempty"`
+ DidYouMean *map[string]string `json:"did_you_mean,omitempty"`
+ Mirrored *bool `json:"mirrored,omitempty"`
+ Degraded *[]string `json:"degraded,omitempty"`
+ Rows []InviteEntry `json:"rows"`
+ Truncated *bool `json:"truncated,omitempty"`
+}
+
// GrantsListOutput is the response from grants.list.
type GrantsListOutput struct {
IgnoredArgs *[]string `json:"ignored_args,omitempty"`
@@ -5266,6 +5339,17 @@ type InventorySection struct {
Reason *string `json:"reason,omitempty"`
}
+// InviteEntry is a model used by Loom operations.
+type InviteEntry struct {
+ InviteID string `json:"invite_id"`
+ Email string `json:"email"`
+ Role string `json:"role"`
+ CreatedBy string `json:"created_by"`
+ CreatedAt string `json:"created_at"`
+ ExpiresAt string `json:"expires_at"`
+ Stopped *bool `json:"stopped,omitempty"`
+}
+
// KnowledgeAddInput is the request to knowledge.add.
type KnowledgeAddInput struct {
Org string `json:"org"`
diff --git a/sdk/python/loom/client.py b/sdk/python/loom/client.py
index f8e58fabf6b..93361c199c8 100644
--- a/sdk/python/loom/client.py
+++ b/sdk/python/loom/client.py
@@ -1167,6 +1167,15 @@ class GrantsOps:
def __init__(self, agent: Agent) -> None:
self._agent = agent
+ async def accept_invite(
+ self, body: _ops.GrantsAcceptInviteBody | None = None, /, **options: Any
+ ) -> _ops.GrantsAcceptInviteOutput:
+ """`grants.accept_invite`."""
+ return cast(
+ "_ops.GrantsAcceptInviteOutput",
+ await self._agent.call("grants.accept_invite", body, **options),
+ )
+
async def approve(
self, body: _ops.GrantsApproveBody | None = None, /, **options: Any
) -> _ops.GrantsApproveOutput:
@@ -1175,6 +1184,15 @@ async def approve(
"_ops.GrantsApproveOutput", await self._agent.call("grants.approve", body, **options)
)
+ async def cancel_invite(
+ self, body: _ops.GrantsCancelInviteBody | None = None, /, **options: Any
+ ) -> _ops.GrantsCancelInviteOutput:
+ """`grants.cancel_invite`."""
+ return cast(
+ "_ops.GrantsCancelInviteOutput",
+ await self._agent.call("grants.cancel_invite", body, **options),
+ )
+
async def create(
self, body: _ops.GrantsCreateBody | None = None, /, **options: Any
) -> _ops.GrantsCreateOutput:
@@ -1183,12 +1201,29 @@ async def create(
"_ops.GrantsCreateOutput", await self._agent.call("grants.create", body, **options)
)
+ async def invite(
+ self, body: _ops.GrantsInviteBody | None = None, /, **options: Any
+ ) -> _ops.GrantsInviteOutput:
+ """`grants.invite`."""
+ return cast(
+ "_ops.GrantsInviteOutput", await self._agent.call("grants.invite", body, **options)
+ )
+
async def list(
self, body: _ops.GrantsListBody | None = None, /, **options: Any
) -> _ops.GrantsListOutput:
"""`grants.list`."""
return cast("_ops.GrantsListOutput", await self._agent.call("grants.list", body, **options))
+ async def list_invites(
+ self, body: _ops.GrantsListInvitesBody | None = None, /, **options: Any
+ ) -> _ops.GrantsListInvitesOutput:
+ """`grants.list_invites`."""
+ return cast(
+ "_ops.GrantsListInvitesOutput",
+ await self._agent.call("grants.list_invites", body, **options),
+ )
+
async def pending_for_me(
self, body: _ops.GrantsPendingForMeBody | None = None, /, **options: Any
) -> _ops.GrantsPendingForMeOutput:
diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py
index e305ab9b56f..7236be8ba09 100644
--- a/sdk/python/loom/ops.py
+++ b/sdk/python/loom/ops.py
@@ -154,9 +154,13 @@ class OpSpec:
"facts.path",
"facts.related",
"facts.traverse",
+ "grants.accept_invite",
"grants.approve",
+ "grants.cancel_invite",
"grants.create",
+ "grants.invite",
"grants.list",
+ "grants.list_invites",
"grants.pending_for_me",
"grants.revoke",
"grants.share_agent",
@@ -584,9 +588,13 @@ class OpSpec:
"facts.path",
"facts.related",
"facts.traverse",
+ "grants.accept_invite",
"grants.approve",
+ "grants.cancel_invite",
"grants.create",
+ "grants.invite",
"grants.list",
+ "grants.list_invites",
"grants.pending_for_me",
"grants.revoke",
"grants.share_agent",
@@ -2279,6 +2287,18 @@ class OpSpec:
False,
True,
),
+ "grants.accept_invite": OpSpec(
+ "grants.accept_invite",
+ "GrantsAcceptInviteInput",
+ "GrantsAcceptInviteBody",
+ "GrantsAcceptInviteOutput",
+ False,
+ "viewer",
+ "experimental",
+ 150,
+ True,
+ False,
+ ),
"grants.approve": OpSpec(
"grants.approve",
"GrantsApproveInput",
@@ -2291,6 +2311,18 @@ class OpSpec:
True,
False,
),
+ "grants.cancel_invite": OpSpec(
+ "grants.cancel_invite",
+ "GrantsCancelInviteInput",
+ "GrantsCancelInviteBody",
+ "GrantsCancelInviteOutput",
+ True,
+ "admin",
+ "experimental",
+ 80,
+ True,
+ False,
+ ),
"grants.create": OpSpec(
"grants.create",
"GrantsCreateInput",
@@ -2303,6 +2335,18 @@ class OpSpec:
True,
False,
),
+ "grants.invite": OpSpec(
+ "grants.invite",
+ "GrantsInviteInput",
+ "GrantsInviteBody",
+ "GrantsInviteOutput",
+ False,
+ "admin",
+ "experimental",
+ 3000,
+ True,
+ False,
+ ),
"grants.list": OpSpec(
"grants.list",
"GrantsListInput",
@@ -2315,6 +2359,18 @@ class OpSpec:
False,
True,
),
+ "grants.list_invites": OpSpec(
+ "grants.list_invites",
+ "GrantsListInvitesInput",
+ "GrantsListInvitesBody",
+ "GrantsListInvitesOutput",
+ True,
+ "admin",
+ "experimental",
+ 80,
+ False,
+ False,
+ ),
"grants.pending_for_me": OpSpec(
"grants.pending_for_me",
"GrantsPendingForMeInput",
@@ -11116,6 +11172,27 @@ class TraversalNode(TypedDict, total=False):
path: NotRequired[list[str]]
+class GrantsAcceptInviteInput(TypedDict, total=False):
+ "Accept an invitation link as the signed-in person."
+
+ org: Required[str]
+ namespace: Required[str]
+ secret: Required[str]
+
+
+class GrantsAcceptInviteBody(TypedDict, total=False):
+ "Accept an invitation link as the signed-in person."
+
+ org: NotRequired[str]
+ namespace: NotRequired[str]
+ secret: Required[str]
+
+
+class GrantsAcceptInviteOutput(TypedDict, total=False):
+ namespace: Required[str]
+ role: Required[Literal["viewer", "writer", "admin"]]
+
+
class GrantsApproveInput(TypedDict, total=False):
"Approve (or reject) a pending grant request."
@@ -11144,6 +11221,26 @@ class GrantsApproveOutput(TypedDict, total=False):
decided_at: Required[str] # date-time as ISO-8601 text
+class GrantsCancelInviteInput(TypedDict, total=False):
+ "Cancel an open invitation, so its link admits nobody."
+
+ org: Required[str]
+ namespace: Required[str]
+ invite_id: Required[str]
+
+
+class GrantsCancelInviteBody(TypedDict, total=False):
+ "Cancel an open invitation, so its link admits nobody."
+
+ org: NotRequired[str]
+ namespace: NotRequired[str]
+ invite_id: Required[str]
+
+
+class GrantsCancelInviteOutput(TypedDict, total=False):
+ cancelled: Required[bool]
+
+
class GrantsCreateInput(TypedDict, total=False):
org: Required[str]
namespace: Required[str]
@@ -11170,6 +11267,35 @@ class GrantsCreateOutput(TypedDict, total=False):
granted_at: Required[str] # date-time as ISO-8601 text
+class GrantsInviteInput(TypedDict, total=False):
+ "Give a person a role on a namespace by login handle or email."
+
+ org: Required[str]
+ namespace: Required[str]
+ to: Required[str]
+ role: Required[Literal["viewer", "writer", "admin"]]
+
+
+class GrantsInviteBody(TypedDict, total=False):
+ "Give a person a role on a namespace by login handle or email."
+
+ org: NotRequired[str]
+ namespace: NotRequired[str]
+ to: Required[str]
+ role: Required[Literal["viewer", "writer", "admin"]]
+
+
+class GrantsInviteOutput(TypedDict, total=False):
+ outcome: Required[Literal["granted", "invited"]]
+ role: Required[Literal["viewer", "writer", "admin"]]
+ subject: NotRequired[str]
+ invite_id: NotRequired[str]
+ link_path: NotRequired[str]
+ url: NotRequired[str]
+ expires_at: NotRequired[Optional[str]]
+ emailed: NotRequired[bool]
+
+
class GrantsListInput(TypedDict, total=False):
org: Required[str]
namespace: Required[str]
@@ -11203,6 +11329,35 @@ class GrantEntry(TypedDict, total=False):
also: NotRequired[list[str]]
+class GrantsListInvitesInput(TypedDict, total=False):
+ "List a namespace's open invitations."
+
+ org: Required[str]
+ namespace: Required[str]
+
+
+class GrantsListInvitesBody(TypedDict, total=False):
+ "List a namespace's open invitations."
+
+ org: NotRequired[str]
+ namespace: NotRequired[str]
+
+
+class GrantsListInvitesOutput(TypedDict, total=False):
+ rows: Required[list["InviteEntry"]]
+ truncated: NotRequired[bool]
+
+
+class InviteEntry(TypedDict, total=False):
+ invite_id: Required[str]
+ email: Required[str]
+ role: Required[Literal["viewer", "writer", "admin"]]
+ created_by: Required[str]
+ created_at: Required[str] # date-time as ISO-8601 text
+ expires_at: Required[str] # date-time as ISO-8601 text
+ stopped: NotRequired[bool]
+
+
class GrantsPendingForMeInput(TypedDict, total=False):
org: Required[str]
limit: NotRequired[int]
diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb
index 1e92b4ece06..dc568007708 100644
--- a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb
+++ b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb
@@ -8,7 +8,7 @@ module Loom
# Every served operation: its spec in OPS, and one method per op on the class
# of its group (`client.memory.set(...)` is `memory.set`).
module Generated
- OP_COUNT = 427
+ OP_COUNT = 431
# The declared spec of every served op, by name; the HTTP path is /v1/.
OPS = {
@@ -127,9 +127,13 @@ module Generated
"facts.path" => OpSpec.new("facts.path", "facts", "path", true, true, "viewer", "experimental", %w[org namespace entity_a entity_b max_hops top_k_per_hop min_co_occur as_of relations labeled].freeze, %w[org namespace entity_a entity_b].freeze),
"facts.related" => OpSpec.new("facts.related", "facts", "related", true, true, "viewer", "experimental", %w[org namespace entity top_k as_of].freeze, %w[org namespace entity].freeze),
"facts.traverse" => OpSpec.new("facts.traverse", "facts", "traverse", true, true, "viewer", "stable", %w[org namespace seed_entity max_hops top_k_per_hop min_co_occur max_nodes as_of relations labeled hub_degree hub_share rank_by].freeze, %w[org namespace seed_entity].freeze),
+ "grants.accept_invite" => OpSpec.new("grants.accept_invite", "grants", "accept_invite", false, false, "viewer", "experimental", %w[org namespace secret].freeze, %w[org namespace secret].freeze),
"grants.approve" => OpSpec.new("grants.approve", "grants", "approve", true, false, "admin", "experimental", %w[org namespace subject decision role].freeze, %w[org namespace subject].freeze),
+ "grants.cancel_invite" => OpSpec.new("grants.cancel_invite", "grants", "cancel_invite", true, false, "admin", "experimental", %w[org namespace invite_id].freeze, %w[org namespace invite_id].freeze),
"grants.create" => OpSpec.new("grants.create", "grants", "create", true, false, "admin", "stable", %w[org namespace subject role granted_by replace].freeze, %w[org namespace subject role].freeze),
+ "grants.invite" => OpSpec.new("grants.invite", "grants", "invite", false, false, "admin", "experimental", %w[org namespace to role].freeze, %w[org namespace to role].freeze),
"grants.list" => OpSpec.new("grants.list", "grants", "list", true, true, "viewer", "stable", %w[org namespace limit cursor fields].freeze, %w[org namespace].freeze),
+ "grants.list_invites" => OpSpec.new("grants.list_invites", "grants", "list_invites", true, false, "admin", "experimental", %w[org namespace].freeze, %w[org namespace].freeze),
"grants.pending_for_me" => OpSpec.new("grants.pending_for_me", "grants", "pending_for_me", true, true, "viewer", "experimental", %w[org limit].freeze, %w[org].freeze),
"grants.revoke" => OpSpec.new("grants.revoke", "grants", "revoke", true, false, "admin", "experimental", %w[org namespace subject].freeze, %w[org namespace subject].freeze),
"grants.share_agent" => OpSpec.new("grants.share_agent", "grants", "share_agent", true, false, "writer", "experimental", %w[org namespace grantee role].freeze, %w[org namespace grantee].freeze),
@@ -1220,6 +1224,13 @@ def traverse(body = nil, request_options: nil, **fields)
# The `grants.*` operations.
class GrantsOps < OpGroup
+ # `grants.accept_invite` (viewer, writes, experimental).
+ # Accept an invitation link as the signed-in person.
+ # Required: org, namespace, secret.
+ def accept_invite(body = nil, request_options: nil, **fields)
+ call_op("grants.accept_invite", body, fields, request_options)
+ end
+
# `grants.approve` (admin, writes, Idempotency-Key, experimental).
# Approve (or reject) a pending grant request.
# Required: org, namespace, subject.
@@ -1227,18 +1238,39 @@ def approve(body = nil, request_options: nil, **fields)
call_op("grants.approve", body, fields, request_options)
end
+ # `grants.cancel_invite` (admin, writes, Idempotency-Key, experimental).
+ # Cancel an open invitation, so its link admits nobody.
+ # Required: org, namespace, invite_id.
+ def cancel_invite(body = nil, request_options: nil, **fields)
+ call_op("grants.cancel_invite", body, fields, request_options)
+ end
+
# `grants.create` (admin, writes, Idempotency-Key).
# Required: org, namespace, subject, role.
def create(body = nil, request_options: nil, **fields)
call_op("grants.create", body, fields, request_options)
end
+ # `grants.invite` (admin, writes, experimental).
+ # Give a person a role on a namespace by login handle or email.
+ # Required: org, namespace, to, role.
+ def invite(body = nil, request_options: nil, **fields)
+ call_op("grants.invite", body, fields, request_options)
+ end
+
# `grants.list` (viewer, read-only).
# Required: org, namespace.
def list(body = nil, request_options: nil, **fields)
call_op("grants.list", body, fields, request_options)
end
+ # `grants.list_invites` (admin, writes, Idempotency-Key, experimental).
+ # List a namespace's open invitations.
+ # Required: org, namespace.
+ def list_invites(body = nil, request_options: nil, **fields)
+ call_op("grants.list_invites", body, fields, request_options)
+ end
+
# `grants.pending_for_me` (viewer, read-only, experimental).
# Required: org.
def pending_for_me(body = nil, request_options: nil, **fields)
diff --git a/sdk/rust/src/blocking_operations.rs b/sdk/rust/src/blocking_operations.rs
index 8ce51ce9b61..986b8c5961a 100644
--- a/sdk/rust/src/blocking_operations.rs
+++ b/sdk/rust/src/blocking_operations.rs
@@ -4275,6 +4275,74 @@ impl crate::blocking::Client {
) -> Result, crate::CallFailure> {
self.call("grants.unshare_agent", &request, options)
}
+ /// Call `grants.invite`.
+ pub fn grants_invite(
+ &self,
+ request: crate::GrantsInviteInput,
+ ) -> Result {
+ self.grants_invite_with_options(request, crate::CallOptions::default())
+ .map(|result| result.data)
+ .map_err(|failure| failure.error)
+ }
+ /// Call `grants.invite` with per-request options and metadata.
+ pub fn grants_invite_with_options(
+ &self,
+ request: crate::GrantsInviteInput,
+ options: crate::CallOptions,
+ ) -> Result, crate::CallFailure> {
+ self.call("grants.invite", &request, options)
+ }
+ /// Call `grants.list_invites`.
+ pub fn grants_list_invites(
+ &self,
+ request: crate::GrantsListInvitesInput,
+ ) -> Result {
+ self.grants_list_invites_with_options(request, crate::CallOptions::default())
+ .map(|result| result.data)
+ .map_err(|failure| failure.error)
+ }
+ /// Call `grants.list_invites` with per-request options and metadata.
+ pub fn grants_list_invites_with_options(
+ &self,
+ request: crate::GrantsListInvitesInput,
+ options: crate::CallOptions,
+ ) -> Result, crate::CallFailure> {
+ self.call("grants.list_invites", &request, options)
+ }
+ /// Call `grants.cancel_invite`.
+ pub fn grants_cancel_invite(
+ &self,
+ request: crate::GrantsCancelInviteInput,
+ ) -> Result {
+ self.grants_cancel_invite_with_options(request, crate::CallOptions::default())
+ .map(|result| result.data)
+ .map_err(|failure| failure.error)
+ }
+ /// Call `grants.cancel_invite` with per-request options and metadata.
+ pub fn grants_cancel_invite_with_options(
+ &self,
+ request: crate::GrantsCancelInviteInput,
+ options: crate::CallOptions,
+ ) -> Result, crate::CallFailure> {
+ self.call("grants.cancel_invite", &request, options)
+ }
+ /// Call `grants.accept_invite`.
+ pub fn grants_accept_invite(
+ &self,
+ request: crate::GrantsAcceptInviteInput,
+ ) -> Result {
+ self.grants_accept_invite_with_options(request, crate::CallOptions::default())
+ .map(|result| result.data)
+ .map_err(|failure| failure.error)
+ }
+ /// Call `grants.accept_invite` with per-request options and metadata.
+ pub fn grants_accept_invite_with_options(
+ &self,
+ request: crate::GrantsAcceptInviteInput,
+ options: crate::CallOptions,
+ ) -> Result, crate::CallFailure> {
+ self.call("grants.accept_invite", &request, options)
+ }
/// Call `collection.budget_set`.
pub fn collection_budget_set(
&self,
diff --git a/sdk/rust/src/operations.rs b/sdk/rust/src/operations.rs
index 6818208891b..0ac1a9bd3f1 100644
--- a/sdk/rust/src/operations.rs
+++ b/sdk/rust/src/operations.rs
@@ -4592,6 +4592,78 @@ impl crate::Client {
) -> Result, crate::CallFailure> {
self.call("grants.unshare_agent", &request, options).await
}
+ /// Call `grants.invite`.
+ pub async fn grants_invite(
+ &self,
+ request: crate::GrantsInviteInput,
+ ) -> Result {
+ self.grants_invite_with_options(request, crate::CallOptions::default())
+ .await
+ .map(|result| result.data)
+ .map_err(|failure| failure.error)
+ }
+ /// Call `grants.invite` with per-request options and metadata.
+ pub async fn grants_invite_with_options(
+ &self,
+ request: crate::GrantsInviteInput,
+ options: crate::CallOptions,
+ ) -> Result, crate::CallFailure> {
+ self.call("grants.invite", &request, options).await
+ }
+ /// Call `grants.list_invites`.
+ pub async fn grants_list_invites(
+ &self,
+ request: crate::GrantsListInvitesInput,
+ ) -> Result {
+ self.grants_list_invites_with_options(request, crate::CallOptions::default())
+ .await
+ .map(|result| result.data)
+ .map_err(|failure| failure.error)
+ }
+ /// Call `grants.list_invites` with per-request options and metadata.
+ pub async fn grants_list_invites_with_options(
+ &self,
+ request: crate::GrantsListInvitesInput,
+ options: crate::CallOptions,
+ ) -> Result, crate::CallFailure> {
+ self.call("grants.list_invites", &request, options).await
+ }
+ /// Call `grants.cancel_invite`.
+ pub async fn grants_cancel_invite(
+ &self,
+ request: crate::GrantsCancelInviteInput,
+ ) -> Result {
+ self.grants_cancel_invite_with_options(request, crate::CallOptions::default())
+ .await
+ .map(|result| result.data)
+ .map_err(|failure| failure.error)
+ }
+ /// Call `grants.cancel_invite` with per-request options and metadata.
+ pub async fn grants_cancel_invite_with_options(
+ &self,
+ request: crate::GrantsCancelInviteInput,
+ options: crate::CallOptions,
+ ) -> Result, crate::CallFailure> {
+ self.call("grants.cancel_invite", &request, options).await
+ }
+ /// Call `grants.accept_invite`.
+ pub async fn grants_accept_invite(
+ &self,
+ request: crate::GrantsAcceptInviteInput,
+ ) -> Result {
+ self.grants_accept_invite_with_options(request, crate::CallOptions::default())
+ .await
+ .map(|result| result.data)
+ .map_err(|failure| failure.error)
+ }
+ /// Call `grants.accept_invite` with per-request options and metadata.
+ pub async fn grants_accept_invite_with_options(
+ &self,
+ request: crate::GrantsAcceptInviteInput,
+ options: crate::CallOptions,
+ ) -> Result, crate::CallFailure> {
+ self.call("grants.accept_invite", &request, options).await
+ }
/// Call `collection.budget_set`.
pub async fn collection_budget_set(
&self,
diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs
index 531428ebbe1..3c44539de3c 100644
--- a/sdk/rust/src/wire_models.rs
+++ b/sdk/rust/src/wire_models.rs
@@ -1325,6 +1325,28 @@ pub(crate) const OP_POLICIES: &[OperationPolicy] = &[
&["namespace", "org"],
&[],
),
+ ("grants.invite", false, false, &["namespace", "org"], &[]),
+ (
+ "grants.list_invites",
+ true,
+ false,
+ &["namespace", "org"],
+ &[],
+ ),
+ (
+ "grants.cancel_invite",
+ true,
+ false,
+ &["namespace", "org"],
+ &[],
+ ),
+ (
+ "grants.accept_invite",
+ false,
+ false,
+ &["namespace", "org"],
+ &[],
+ ),
("collection.budget_set", true, false, &["org"], &[]),
("collection.create", true, false, &["org"], &[]),
("collection.move", true, false, &["org"], &[]),
@@ -2226,6 +2248,7 @@ pub(crate) const NAMESPACE_HINT_EXCLUSIONS: &[&str] = &[
"extraction_policy.clear",
"extraction_policy.get",
"extraction_policy.set",
+ "grants.accept_invite",
"memory.verify",
];
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -22967,6 +22990,74 @@ impl FactsTraverseInput {
}
}
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub enum GrantsAcceptInviteOutputRole {
+ #[serde(rename = "viewer")]
+ Viewer,
+ #[serde(rename = "writer")]
+ Writer,
+ #[serde(rename = "admin")]
+ Admin,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub struct GrantsAcceptInviteOutput {
+ pub namespace: String,
+ pub role: GrantsAcceptInviteOutputRole,
+}
+
+#[derive(Clone, PartialEq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub struct GrantsAcceptInviteInput {
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present_value"
+ )]
+ pub org: Option,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present_value"
+ )]
+ pub namespace: Option,
+ pub secret: String,
+}
+impl std::fmt::Debug for GrantsAcceptInviteInput {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("GrantsAcceptInviteInput")
+ .field("org", &self.org)
+ .field("namespace", &self.namespace)
+ .finish_non_exhaustive()
+ }
+}
+impl GrantsAcceptInviteInput {
+ pub fn new(secret: impl Into) -> Self {
+ Self {
+ org: None,
+ namespace: None,
+ secret: secret.into(),
+ }
+ }
+ pub fn org(mut self, org: impl Into) -> Self {
+ self.org = Some(org.into());
+ self
+ }
+ pub fn namespace(mut self, namespace: impl Into) -> Self {
+ self.namespace = Some(namespace.into());
+ self
+ }
+ pub async fn send(
+ self,
+ client: &crate::Client,
+ options: crate::CallOptions,
+ ) -> Result, crate::CallFailure> {
+ client.call("grants.accept_invite", &self, options).await
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum GrantsApproveOutputDecision {
@@ -23086,6 +23177,54 @@ impl GrantsApproveInput {
}
}
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub struct GrantsCancelInviteOutput {
+ pub cancelled: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub struct GrantsCancelInviteInput {
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present_value"
+ )]
+ pub org: Option,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present_value"
+ )]
+ pub namespace: Option,
+ pub invite_id: String,
+}
+impl GrantsCancelInviteInput {
+ pub fn new(invite_id: impl Into) -> Self {
+ Self {
+ org: None,
+ namespace: None,
+ invite_id: invite_id.into(),
+ }
+ }
+ pub fn org(mut self, org: impl Into) -> Self {
+ self.org = Some(org.into());
+ self
+ }
+ pub fn namespace(mut self, namespace: impl Into) -> Self {
+ self.namespace = Some(namespace.into());
+ self
+ }
+ pub async fn send(
+ self,
+ client: &crate::Client,
+ options: crate::CallOptions,
+ ) -> Result, crate::CallFailure> {
+ client.call("grants.cancel_invite", &self, options).await
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum GrantsCreateOutputRole {
@@ -23184,6 +23323,112 @@ impl GrantsCreateInput {
}
}
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub enum GrantsInviteOutputOutcome {
+ #[serde(rename = "granted")]
+ Granted,
+ #[serde(rename = "invited")]
+ Invited,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub enum GrantsInviteOutputRole {
+ #[serde(rename = "viewer")]
+ Viewer,
+ #[serde(rename = "writer")]
+ Writer,
+ #[serde(rename = "admin")]
+ Admin,
+}
+
+#[derive(Clone, PartialEq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub struct GrantsInviteOutput {
+ pub outcome: GrantsInviteOutputOutcome,
+ pub role: GrantsInviteOutputRole,
+ #[serde(default = "default_grants_invite_output_subject")]
+ pub subject: String,
+ #[serde(default = "default_grants_invite_output_invite_id")]
+ pub invite_id: String,
+ #[serde(default = "default_grants_invite_output_link_path")]
+ pub link_path: String,
+ #[serde(default = "default_grants_invite_output_url")]
+ pub url: String,
+ #[serde(default = "default_grants_invite_output_expires_at")]
+ pub expires_at: Option,
+ #[serde(default = "default_grants_invite_output_emailed")]
+ pub emailed: bool,
+}
+impl std::fmt::Debug for GrantsInviteOutput {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("GrantsInviteOutput")
+ .field("outcome", &self.outcome)
+ .field("role", &self.role)
+ .field("subject", &self.subject)
+ .field("invite_id", &self.invite_id)
+ .field("expires_at", &self.expires_at)
+ .field("emailed", &self.emailed)
+ .finish_non_exhaustive()
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub enum GrantsInviteInputRole {
+ #[serde(rename = "viewer")]
+ Viewer,
+ #[serde(rename = "writer")]
+ Writer,
+ #[serde(rename = "admin")]
+ Admin,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub struct GrantsInviteInput {
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present_value"
+ )]
+ pub org: Option,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present_value"
+ )]
+ pub namespace: Option,
+ pub to: String,
+ pub role: GrantsInviteInputRole,
+}
+impl GrantsInviteInput {
+ pub fn new(to: impl Into, role: GrantsInviteInputRole) -> Self {
+ Self {
+ org: None,
+ namespace: None,
+ to: to.into(),
+ role,
+ }
+ }
+ pub fn org(mut self, org: impl Into) -> Self {
+ self.org = Some(org.into());
+ self
+ }
+ pub fn namespace(mut self, namespace: impl Into) -> Self {
+ self.namespace = Some(namespace.into());
+ self
+ }
+ pub async fn send(
+ self,
+ client: &crate::Client,
+ options: crate::CallOptions,
+ ) -> Result, crate::CallFailure> {
+ client.call("grants.invite", &self, options).await
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum GrantEntryRole {
@@ -23364,6 +23609,83 @@ impl GrantsListInput {
}
}
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub enum InviteEntryRole {
+ #[serde(rename = "viewer")]
+ Viewer,
+ #[serde(rename = "writer")]
+ Writer,
+ #[serde(rename = "admin")]
+ Admin,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub struct InviteEntry {
+ pub invite_id: String,
+ pub email: String,
+ pub role: InviteEntryRole,
+ pub created_by: String,
+ pub created_at: String,
+ pub expires_at: String,
+ #[serde(default = "default_invite_entry_stopped")]
+ pub stopped: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub struct GrantsListInvitesOutput {
+ pub rows: Vec,
+ #[serde(default = "default_grants_list_invites_output_truncated")]
+ pub truncated: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub struct GrantsListInvitesInput {
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present_value"
+ )]
+ pub org: Option,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present_value"
+ )]
+ pub namespace: Option,
+}
+impl Default for GrantsListInvitesInput {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+impl GrantsListInvitesInput {
+ pub fn new() -> Self {
+ Self {
+ org: None,
+ namespace: None,
+ }
+ }
+ pub fn org(mut self, org: impl Into) -> Self {
+ self.org = Some(org.into());
+ self
+ }
+ pub fn namespace(mut self, namespace: impl Into) -> Self {
+ self.namespace = Some(namespace.into());
+ self
+ }
+ pub async fn send(
+ self,
+ client: &crate::Client,
+ options: crate::CallOptions,
+ ) -> Result, crate::CallFailure> {
+ client.call("grants.list_invites", &self, options).await
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum PendingForMeEntryCurrentRole {
@@ -71323,12 +71645,36 @@ fn default_facts_traverse_output_hubs() -> Vec {
fn default_grants_approve_output_role() -> Option {
serde_json::from_str("null").expect("schema default")
}
+fn default_grants_invite_output_subject() -> String {
+ serde_json::from_str("\"\"").expect("schema default")
+}
+fn default_grants_invite_output_invite_id() -> String {
+ serde_json::from_str("\"\"").expect("schema default")
+}
+fn default_grants_invite_output_link_path() -> String {
+ serde_json::from_str("\"\"").expect("schema default")
+}
+fn default_grants_invite_output_url() -> String {
+ serde_json::from_str("\"\"").expect("schema default")
+}
+fn default_grants_invite_output_expires_at() -> Option {
+ serde_json::from_str("null").expect("schema default")
+}
+fn default_grants_invite_output_emailed() -> bool {
+ serde_json::from_str("false").expect("schema default")
+}
fn default_grants_list_output_next_cursor() -> Option {
serde_json::from_str("null").expect("schema default")
}
fn default_grants_list_output_truncated() -> bool {
serde_json::from_str("false").expect("schema default")
}
+fn default_invite_entry_stopped() -> bool {
+ serde_json::from_str("false").expect("schema default")
+}
+fn default_grants_list_invites_output_truncated() -> bool {
+ serde_json::from_str("false").expect("schema default")
+}
fn default_pending_for_me_entry_kind() -> String {
serde_json::from_str("\"memory\"").expect("schema default")
}
diff --git a/sdk/rust/tests/registry_contracts.rs b/sdk/rust/tests/registry_contracts.rs
index b1d2eb88946..334a13cb58b 100644
--- a/sdk/rust/tests/registry_contracts.rs
+++ b/sdk/rust/tests/registry_contracts.rs
@@ -7532,6 +7532,90 @@ fn grants_unshare_agent() {
);
}
#[test]
+fn grants_invite() {
+ let value: clickhouse_loom::GrantsInviteInput = serde_json::from_str(
+ "{\"org\":\"sample\",\"namespace\":\"sample\",\"to\":\"sample\",\"role\":\"viewer\"}",
+ )
+ .unwrap();
+ let encoded = serde_json::to_value(value).unwrap();
+ assert!(encoded.is_object());
+ let value: clickhouse_loom::GrantsInviteOutput =
+ serde_json::from_str("{\"outcome\":\"granted\",\"role\":\"viewer\"}").unwrap();
+ let encoded = serde_json::to_value(value).unwrap();
+ assert!(encoded.is_object());
+ assert_eq!(
+ encoded["subject"],
+ serde_json::from_str::("\"\"").unwrap(),
+ "grants.invite:subject"
+ );
+ assert_eq!(
+ encoded["invite_id"],
+ serde_json::from_str::("\"\"").unwrap(),
+ "grants.invite:invite_id"
+ );
+ assert_eq!(
+ encoded["link_path"],
+ serde_json::from_str::("\"\"").unwrap(),
+ "grants.invite:link_path"
+ );
+ assert_eq!(
+ encoded["url"],
+ serde_json::from_str::("\"\"").unwrap(),
+ "grants.invite:url"
+ );
+ assert_eq!(
+ encoded["expires_at"],
+ serde_json::from_str::("null").unwrap(),
+ "grants.invite:expires_at"
+ );
+ assert_eq!(
+ encoded["emailed"],
+ serde_json::from_str::("false").unwrap(),
+ "grants.invite:emailed"
+ );
+}
+#[test]
+fn grants_list_invites() {
+ let value: clickhouse_loom::GrantsListInvitesInput =
+ serde_json::from_str("{\"org\":\"sample\",\"namespace\":\"sample\"}").unwrap();
+ let encoded = serde_json::to_value(value).unwrap();
+ assert!(encoded.is_object());
+ let value: clickhouse_loom::GrantsListInvitesOutput =
+ serde_json::from_str("{\"rows\":[]}").unwrap();
+ let encoded = serde_json::to_value(value).unwrap();
+ assert!(encoded.is_object());
+ assert_eq!(
+ encoded["truncated"],
+ serde_json::from_str::("false").unwrap(),
+ "grants.list_invites:truncated"
+ );
+}
+#[test]
+fn grants_cancel_invite() {
+ let value: clickhouse_loom::GrantsCancelInviteInput = serde_json::from_str(
+ "{\"org\":\"sample\",\"namespace\":\"sample\",\"invite_id\":\"sample\"}",
+ )
+ .unwrap();
+ let encoded = serde_json::to_value(value).unwrap();
+ assert!(encoded.is_object());
+ let value: clickhouse_loom::GrantsCancelInviteOutput =
+ serde_json::from_str("{\"cancelled\":false}").unwrap();
+ let encoded = serde_json::to_value(value).unwrap();
+ assert!(encoded.is_object());
+}
+#[test]
+fn grants_accept_invite() {
+ let value: clickhouse_loom::GrantsAcceptInviteInput =
+ serde_json::from_str("{\"org\":\"sample\",\"namespace\":\"sample\",\"secret\":\"sample\"}")
+ .unwrap();
+ let encoded = serde_json::to_value(value).unwrap();
+ assert!(encoded.is_object());
+ let value: clickhouse_loom::GrantsAcceptInviteOutput =
+ serde_json::from_str("{\"namespace\":\"sample\",\"role\":\"viewer\"}").unwrap();
+ let encoded = serde_json::to_value(value).unwrap();
+ assert!(encoded.is_object());
+}
+#[test]
fn collection_budget_set() {
let value: clickhouse_loom::CollectionBudgetSetInput =
serde_json::from_str("{\"org\":\"sample\",\"namespace\":\"sample\"}").unwrap();
diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts
index 92c0ffb1088..d13c88aa1e6 100644
--- a/sdk/typescript/src/generated/ops.ts
+++ b/sdk/typescript/src/generated/ops.ts
@@ -3414,6 +3414,17 @@ export interface FactsTraverseOutput {
hubs?: string[];
}
+export interface GrantsAcceptInviteInput {
+ org: string;
+ namespace: string;
+ secret: string;
+}
+
+export interface GrantsAcceptInviteOutput {
+ namespace: string;
+ role: "viewer" | "writer" | "admin";
+}
+
export interface GrantsApproveInput {
org: string;
namespace: string;
@@ -3430,6 +3441,16 @@ export interface GrantsApproveOutput {
decided_at: string; // date-time
}
+export interface GrantsCancelInviteInput {
+ org: string;
+ namespace: string;
+ invite_id: string;
+}
+
+export interface GrantsCancelInviteOutput {
+ cancelled: boolean;
+}
+
export interface GrantsCreateInput {
org: string;
namespace: string;
@@ -3447,6 +3468,24 @@ export interface GrantsCreateOutput {
granted_at: string; // date-time
}
+export interface GrantsInviteInput {
+ org: string;
+ namespace: string;
+ to: string;
+ role: "viewer" | "writer" | "admin";
+}
+
+export interface GrantsInviteOutput {
+ outcome: "granted" | "invited";
+ role: "viewer" | "writer" | "admin";
+ subject?: string;
+ invite_id?: string;
+ link_path?: string;
+ url?: string;
+ expires_at?: string | null;
+ emailed?: boolean;
+}
+
export interface GrantsListInput {
org: string;
namespace: string;
@@ -3472,6 +3511,26 @@ export interface GrantsListOutput {
truncated?: boolean;
}
+export interface GrantsListInvitesInput {
+ org: string;
+ namespace: string;
+}
+
+export interface InviteEntry {
+ invite_id: string;
+ email: string;
+ role: "viewer" | "writer" | "admin";
+ created_by: string;
+ created_at: string; // date-time
+ expires_at: string; // date-time
+ stopped?: boolean;
+}
+
+export interface GrantsListInvitesOutput {
+ rows: InviteEntry[];
+ truncated?: boolean;
+}
+
export interface GrantsPendingForMeInput {
org: string;
limit?: number;
@@ -12566,9 +12625,13 @@ export type OpName =
| "facts.path"
| "facts.related"
| "facts.traverse"
+ | "grants.accept_invite"
| "grants.approve"
+ | "grants.cancel_invite"
| "grants.create"
+ | "grants.invite"
| "grants.list"
+ | "grants.list_invites"
| "grants.pending_for_me"
| "grants.revoke"
| "grants.share_agent"
@@ -12996,9 +13059,13 @@ export interface OpMap {
"facts.path": { input: FactsPathInput; output: FactsPathOutput };
"facts.related": { input: FactsRelatedInput; output: FactsRelatedOutput };
"facts.traverse": { input: FactsTraverseInput; output: FactsTraverseOutput };
+ "grants.accept_invite": { input: GrantsAcceptInviteInput; output: GrantsAcceptInviteOutput };
"grants.approve": { input: GrantsApproveInput; output: GrantsApproveOutput };
+ "grants.cancel_invite": { input: GrantsCancelInviteInput; output: GrantsCancelInviteOutput };
"grants.create": { input: GrantsCreateInput; output: GrantsCreateOutput };
+ "grants.invite": { input: GrantsInviteInput; output: GrantsInviteOutput };
"grants.list": { input: GrantsListInput; output: GrantsListOutput };
+ "grants.list_invites": { input: GrantsListInvitesInput; output: GrantsListInvitesOutput };
"grants.pending_for_me": { input: GrantsPendingForMeInput; output: GrantsPendingForMeOutput };
"grants.revoke": { input: GrantsRevokeInput; output: GrantsRevokeOutput };
"grants.share_agent": { input: GrantsShareAgentInput; output: GrantsShareAgentOutput };
@@ -13426,9 +13493,13 @@ export const OPS: readonly OpSpec[] = [
{ name: "facts.path", group: "facts", method: "path", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 250, audit: false, readOnly: true },
{ name: "facts.related", group: "facts", method: "related", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 60, audit: false, readOnly: true },
{ name: "facts.traverse", group: "facts", method: "traverse", idempotent: true, role: "viewer", maturity: "stable", budgetP99Ms: 200, audit: false, readOnly: true },
+ { name: "grants.accept_invite", group: "grants", method: "acceptInvite", idempotent: false, role: "viewer", maturity: "experimental", budgetP99Ms: 150, audit: true, readOnly: false },
{ name: "grants.approve", group: "grants", method: "approve", idempotent: true, role: "admin", maturity: "experimental", budgetP99Ms: 80, audit: true, readOnly: false },
+ { name: "grants.cancel_invite", group: "grants", method: "cancelInvite", idempotent: true, role: "admin", maturity: "experimental", budgetP99Ms: 80, audit: true, readOnly: false },
{ name: "grants.create", group: "grants", method: "create", idempotent: true, role: "admin", maturity: "stable", budgetP99Ms: 50, audit: true, readOnly: false },
+ { name: "grants.invite", group: "grants", method: "invite", idempotent: false, role: "admin", maturity: "experimental", budgetP99Ms: 3000, audit: true, readOnly: false },
{ name: "grants.list", group: "grants", method: "list", idempotent: true, role: "viewer", maturity: "stable", budgetP99Ms: 80, audit: false, readOnly: true },
+ { name: "grants.list_invites", group: "grants", method: "listInvites", idempotent: true, role: "admin", maturity: "experimental", budgetP99Ms: 80, audit: false, readOnly: false },
{ name: "grants.pending_for_me", group: "grants", method: "pendingForMe", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 150, audit: false, readOnly: true },
{ name: "grants.revoke", group: "grants", method: "revoke", idempotent: true, role: "admin", maturity: "experimental", budgetP99Ms: 80, audit: true, readOnly: false },
{ name: "grants.share_agent", group: "grants", method: "shareAgent", idempotent: true, role: "writer", maturity: "experimental", budgetP99Ms: 80, audit: true, readOnly: false },
@@ -13744,4 +13815,4 @@ export const OP_BY_NAME: Readonly> = Object.fromEntries(
OPS.map((o) => [o.name, o]),
) as Readonly>;
-export const GENERATED_OP_COUNT = 427;
+export const GENERATED_OP_COUNT = 431;
diff --git a/server/auth/aliases.py b/server/auth/aliases.py
index 0e9fe57c0bd..d8f8a1bd197 100644
--- a/server/auth/aliases.py
+++ b/server/auth/aliases.py
@@ -207,6 +207,19 @@ async def verified_spellings(org: str, subject: str, *, ch: object | None = None
return (await verified_tie(org, subject, ch=ch))[0]
+async def verified_owner(org: str, subject: str, *, ch: object | None = None) -> str | None:
+ """The login handle (`owner_email`), as stored, of the active account `subject` is by
+ its handle or its verified email: one that is no email first, as `canonical_subject`
+ picks, then the first in sort order; None when none is. Read past a link another
+ process just made; raises when the directory cannot be read."""
+ from server.core.ch import own_write_reads
+
+ with own_write_reads():
+ rows = await _rows(org, subject, ch)
+ owners = (str(r["owner_email"]) for r in rows if r.get("owner_email"))
+ return min(owners, key=lambda o: ("@" in o, o), default=None)
+
+
async def verified_tie(
org: str, subject: str, *, ch: object | None = None
) -> tuple[list[str], bool]:
@@ -230,6 +243,7 @@ async def verified_tie(
"read_aliases",
"spellings",
"subject_aliases",
+ "verified_owner",
"verified_spellings",
"verified_tie",
]
diff --git a/server/auth/attempts.py b/server/auth/attempts.py
index 257c6ea3994..9acedf62864 100644
--- a/server/auth/attempts.py
+++ b/server/auth/attempts.py
@@ -1,6 +1,7 @@
"""Attempt limits for the auth routes that run before a token exists to
-rate-limit by: sign-up, sign-in, OIDC sign-in starts and workload-token
-exchanges.
+rate-limit by (sign-up, sign-in, OIDC sign-in starts and workload-token
+exchanges), and for the invitation emails `grants.invite` sends, whose limits
+more sign-ups must not multiply.
The attempts are rows of `loom.auth_attempts`, so every Loom process of the
deployment counts the same ones. A key is stored as an HMAC keyed by the root
@@ -68,9 +69,11 @@ async def allow(self, key: str) -> bool:
return False
async def blocked(self, key: str) -> bool:
- """Whether `key` is at its limit, for a limit that counts failures only
- (a wrong device code, a refused callback): checked before the attempt,
- `record`ed after one that failed. A process too busy to check refuses."""
+ """Whether `key` is at its limit, recording nothing: for a limit that
+ counts failures only (a wrong device code, a refused callback), checked
+ before the attempt and `record`ed after one that failed; or to check a
+ limit `allow` counts before another limit spends its room. A process too
+ busy to check refuses."""
known = (self.kind, _digest(key))
if _known_over.get(known, 0.0) > _clock():
return True
diff --git a/server/auth/authz.py b/server/auth/authz.py
index b4cdbf3d7c6..dddc887b3f4 100644
--- a/server/auth/authz.py
+++ b/server/auth/authz.py
@@ -962,6 +962,15 @@ async def _lookup_grant(org: str, namespace: str, subject: str) -> Role | None:
return role
+async def subject_grant_role(org: str, namespace: str, subject: str) -> Role | None:
+ """The role `subject` holds on `namespace` through grants alone, no token's claim
+ counted: on a collection as `sharing.roles` reads it, elsewhere `_lookup_grant`.
+ A read that fails raises, or answers None and notes it (`fail_closed.unreadable`)."""
+ if sharing.is_collection(namespace):
+ return await sharing.granted_role(org, subject, namespace)
+ return await _lookup_grant(org, namespace, subject)
+
+
class CachedGate:
"""`check_authorized` for one token in one org, for the listings and the
default that must agree with the gate: the gate itself, handed the grant
diff --git a/server/auth/grant_claims.py b/server/auth/grant_claims.py
index 7092f532bdd..e48b2405f1f 100644
--- a/server/auth/grant_claims.py
+++ b/server/auth/grant_claims.py
@@ -19,7 +19,8 @@
(`maintainers.repo_change`), the repository's admins and the namespaces'
admins, or the trusts; then a bot or a grant (several sorted by namespace).
Taken the other way round, two changes wait each other out and both answer
-503.
+503. An invitation's claim (`invite_change`) is held alone: accepting spends the
+link under it and grants after leaving it.
"""
from __future__ import annotations
@@ -56,6 +57,14 @@ def grant_change(org: str, namespace: str, subject: str) -> AbstractAsyncContext
)
+def invite_change(org: str, namespace: str, invite_id: str) -> AbstractAsyncContextManager[None]:
+ """Hold one invitation from the read that finds it open to the write that accepts or
+ cancels it: two people opening one link at once must not both be let in."""
+ return _claimed(
+ "invite:" + json.dumps([org, namespace, invite_id]), f"an invitation to {org}/{namespace}"
+ )
+
+
def admins_change(org: str, namespace: str) -> AbstractAsyncContextManager[None]:
"""Hold the set of admins of `namespace` (or of a repository's branches, as
`repo:`). A change that may take admin from someone takes it before the
diff --git a/server/auth/self_signup.py b/server/auth/self_signup.py
index 867953dfcb4..b1a95446295 100644
--- a/server/auth/self_signup.py
+++ b/server/auth/self_signup.py
@@ -209,7 +209,8 @@ async def _claim_account(input: SelfSignupInput, org: str, namespace: str) -> Se
return await _claim_checked(input, org, namespace, subject, ch)
-def _valid_signup_email(email: str) -> bool:
+def valid_signup_email(email: str) -> bool:
+ """One plain address: a dot-atom local part and a domain IDNA encodes."""
local, _, domain = email.rpartition("@")
if not local.isprintable() or not domain.isprintable():
return False
@@ -248,7 +249,7 @@ async def _claim_checked(
await refuse_empowered(ch, org, namespace)
contact_email = input.email.strip().lower()
- if not _valid_signup_email(contact_email):
+ if not valid_signup_email(contact_email):
raise HTTPException(
status_code=400,
detail={
diff --git a/server/auth/sharing.py b/server/auth/sharing.py
index c40453621ed..d21a5acf314 100644
--- a/server/auth/sharing.py
+++ b/server/auth/sharing.py
@@ -237,6 +237,17 @@ def _capped(
return min(ceilings, key=lambda r: r.value) # type: ignore[union-attr]
+async def granted_role(org: str, subject: str, namespace: str) -> Role | None:
+ """The role `subject`'s grants give it on the shared collection `namespace`, read as
+ `roles` reads them (its own, its groups' and everyone's, there or on a collection
+ above), with no token to cap it. A failed read raises."""
+ collections = await tree(org)
+ if namespace not in collections.parent:
+ return None
+ maps = await _grant_maps(org, [subject, *await groups_of(org, subject), EVERYONE])
+ return _best(maps, collections.lineage(namespace))
+
+
async def role(auth: AuthorizationClaims, org: str, namespace: str) -> Role | None:
"""The request's role on the collection `namespace`."""
return (await roles(auth, org, [namespace]))[namespace]
diff --git a/server/erasure/app/saga_steps.py b/server/erasure/app/saga_steps.py
index d13931968e3..8184a48bb57 100644
--- a/server/erasure/app/saga_steps.py
+++ b/server/erasure/app/saga_steps.py
@@ -205,13 +205,15 @@ async def _step_scrub_stewardship_by_user(org: str, user_id: str) -> int:
async def _step_revoke_grants_by_user(org: str, user_id: str) -> int:
"""Every grant naming the user as a principal, `user:`, revoked
(which moves the watermark) and then deleted; then the user's id off the
- grants they gave others. Returns the grants revoked."""
+ grants they gave others and the invitations they made. Returns the grants revoked."""
from server.identity.app.grants import forget_granter, revoke_subject
+ from server.identity.app.invites import forget_maker
from server.memory.app.provenance import writer_actor
principal = "user:" + user_id
revoked = await revoke_subject(org, principal, actor=writer_actor("-"))
await forget_granter(org, principal)
+ await forget_maker(org, principal)
await principal_steps.delete_grant_rows_of_user(org, user_id)
return revoked
diff --git a/server/erasure/store/census.py b/server/erasure/store/census.py
index 85c7d001de5..1137c136ffd 100644
--- a/server/erasure/store/census.py
+++ b/server/erasure/store/census.py
@@ -622,9 +622,9 @@ def owner(self, scope_type: str) -> str | None:
# Who began each still-open run (KeeperMap: ids and user ids, no run text);
# dropped beside the runs, not counted.
"agent_runs.delete": ("loom.agent_run_claims",),
- # What a grant, a group and the collection tree say about a user as a
- # principal: identifiers, no memory content; rewritten, not counted.
- "grants.revoke": ("loom.namespace_grants",),
+ # What a grant, an invitation, a group and the collection tree say about a user
+ # as a principal: identifiers, no memory content; rewritten, not counted.
+ "grants.revoke": ("loom.namespace_grants", "loom.namespace_invites"),
"groups.remove_member": ("loom.principal_groups",),
"personal.retire": ("loom.namespaces",),
# Deactivates the namespace's sources and clears their credentials, and a crawl's
diff --git a/server/identity/api/models_grants.py b/server/identity/api/models_grants.py
index c91c2d480d5..4e420f820f6 100644
--- a/server/identity/api/models_grants.py
+++ b/server/identity/api/models_grants.py
@@ -2,18 +2,8 @@
The auth path consults `loom.namespace_grants` as a fallback when a
JWT's blanket role can't satisfy an op's `required_role`. This module
-models the wire ops for managing the grants themselves:
-
- - `grants.create` — issue a grant
- - `grants.list` — show grants in a namespace
- - `grants.revoke` — drop a grant
- - `grants.approve` — approve a pending elevation request
- - `grants.share_agent` / `grants.unshare_agent` — an agent lends its own
- namespace to another agent of its trust, or takes it back
-
-The first four are ADMIN-role + audited — only existing admins on an org
-can elevate other principals. The agent ops are WRITER-role + audited, and
-reach only the caller's own namespace and its trust's agents.
+models the wire ops that manage the grants themselves and the invitations
+that lead to one; `ops_grants.py` declares each op and the role it needs.
"""
from __future__ import annotations
@@ -210,3 +200,101 @@ class GrantsUnshareAgentOutput(BaseModel):
revoked: bool
# When the revoke was written (UTC); None when nothing was revoked.
revoked_at: datetime | None = None
+
+
+class GrantsInviteInput(BaseModel):
+ """Give a person a role on a namespace by login handle or email."""
+
+ org: str
+ namespace: str
+ # The person to give `role`: a handle an account or live grant holds, or an email
+ # verified for one, is granted at once; any other email gets a link, or a grant under
+ # single sign-on only; with no token, any other person is granted as typed.
+ to: str = Field(min_length=1, max_length=320)
+ # `viewer`, `writer` or `admin`; a code namespace takes only `viewer` and `admin`.
+ role: GrantRoleStr
+
+
+class GrantsInviteOutput(BaseModel):
+ # "granted": the grant is written under `subject`; "invited": no account holds the
+ # email, and `link_path` opens the invitation.
+ outcome: Literal["granted", "invited"]
+ # The role given, as asked.
+ role: GrantRoleStr
+ # On "granted", the subject the grant is written under: the person's handle as stored
+ # (an account's, or a grant's), or, when none holds it and sign-in is single sign-on
+ # only or the request has no token, `to` as typed.
+ subject: str = ""
+ # On "invited": the invitation, for grants.cancel_invite.
+ invite_id: str = ""
+ # On "invited": the dashboard path that accepts it, its secret in the fragment. Returned
+ # this once; Loom keeps only the secret's hash.
+ link_path: str = Field(default="", repr=False)
+ # On "invited": `link_path` on the server's public_base_url; "" when that is unset.
+ url: str = Field(default="", repr=False)
+ # On "invited": when the link stops working (UTC), `invite_ttl_seconds` after it was made.
+ expires_at: datetime | None = None
+ # On "invited": true when the mail server took the email to `to`; false when the server
+ # sends no mail, a mail limit was reached or the send failed.
+ emailed: bool = False
+
+
+class GrantsListInvitesInput(BaseModel):
+ """List a namespace's open invitations."""
+
+ org: str
+ namespace: str
+
+
+class _InviteEntry(BaseModel):
+ invite_id: str
+ # The address the invitation was made for.
+ email: str
+ role: GrantRoleStr
+ created_by: str
+ created_at: datetime
+ expires_at: datetime
+ # True when its maker does not stand behind the link now, so it admits nobody: their
+ # grants no longer make them admin there, their account is disabled, or their subject
+ # or tokens as old as the link are revoked. It holds the name until it is cancelled or
+ # expires.
+ stopped: bool = False
+
+
+class GrantsListInvitesOutput(BaseModel):
+ # The namespace's open links (not accepted, cancelled or expired), newest first, from
+ # the newest 200 read.
+ rows: list[_InviteEntry]
+ # True when more than 200 links are open: the older ones were not read.
+ truncated: bool = False
+
+
+class GrantsCancelInviteInput(BaseModel):
+ """Cancel an open invitation, so its link admits nobody."""
+
+ org: str
+ namespace: str
+ # The invitation, as grants.invite and grants.list_invites return it.
+ invite_id: str = Field(min_length=1, max_length=64)
+
+
+class GrantsCancelInviteOutput(BaseModel):
+ # True when an open invitation was cancelled; false when none was open under the id.
+ cancelled: bool
+
+
+class GrantsAcceptInviteInput(BaseModel):
+ """Accept an invitation link as the signed-in person."""
+
+ org: str
+ # The namespace the link names.
+ namespace: str
+ # The secret from the link's fragment.
+ secret: str = Field(min_length=1, max_length=128, repr=False)
+
+
+class GrantsAcceptInviteOutput(BaseModel):
+ namespace: str
+ # The caller's role on the namespace now: the invitation's or a higher one they held;
+ # to its accepter opening the link again, the role they hold.
+ role: GrantRoleStr
diff --git a/server/identity/api/ops_grants.py b/server/identity/api/ops_grants.py
index 002ec3400f9..74e16db7f0c 100644
--- a/server/identity/api/ops_grants.py
+++ b/server/identity/api/ops_grants.py
@@ -3,11 +3,19 @@
from __future__ import annotations
from server.identity.api.models_grants import (
+ GrantsAcceptInviteInput,
+ GrantsAcceptInviteOutput,
GrantsApproveInput,
GrantsApproveOutput,
+ GrantsCancelInviteInput,
+ GrantsCancelInviteOutput,
GrantsCreateInput,
GrantsCreateOutput,
+ GrantsInviteInput,
+ GrantsInviteOutput,
GrantsListInput,
+ GrantsListInvitesInput,
+ GrantsListInvitesOutput,
GrantsListOutput,
GrantsPendingForMeInput,
GrantsPendingForMeOutput,
@@ -29,6 +37,14 @@
handle_grants_pending_for_me,
handle_grants_revoke,
)
+from server.identity.app.invites import (
+ accept_audit_subject,
+ handle_grants_accept_invite,
+ handle_grants_cancel_invite,
+ handle_grants_invite,
+ handle_grants_list_invites,
+ invite_audit_subject,
+)
from server.operations.base import Operation, Role
grants_create = Operation(
@@ -116,6 +132,60 @@
audit=True,
)
+grants_invite = Operation(
+ name="grants.invite",
+ maturity="experimental",
+ input_model=GrantsInviteInput,
+ output_model=GrantsInviteOutput,
+ handler=handle_grants_invite,
+ # A retry after a lost reply makes a second link; the first stays listed to cancel.
+ idempotent=False,
+ required_role=Role.ADMIN,
+ audit=True,
+ audit_subject=invite_audit_subject,
+)
+
+grants_list_invites = Operation(
+ name="grants.list_invites",
+ maturity="experimental",
+ input_model=GrantsListInvitesInput,
+ output_model=GrantsListInvitesOutput,
+ handler=handle_grants_list_invites,
+ idempotent=True,
+ # The addresses invited are the admins' to see, as the people to approve are.
+ required_role=Role.ADMIN,
+ audit=False,
+)
+
+grants_cancel_invite = Operation(
+ name="grants.cancel_invite",
+ maturity="experimental",
+ input_model=GrantsCancelInviteInput,
+ output_model=GrantsCancelInviteOutput,
+ handler=handle_grants_cancel_invite,
+ idempotent=True,
+ required_role=Role.ADMIN,
+ audit=True,
+)
+
+# The person accepting holds no grant on the namespace yet: the link's secret is what
+# admits them, and the handler checks it, the person and the org.
+grants_accept_invite = Operation(
+ name="grants.accept_invite",
+ maturity="experimental",
+ input_model=GrantsAcceptInviteInput,
+ output_model=GrantsAcceptInviteOutput,
+ handler=handle_grants_accept_invite,
+ # A second call by its accepter is answered the role they hold, writing nothing,
+ # while it is at least the link's, else 404; anyone else's finds the link used and
+ # answers 404, so no reply is replayed.
+ idempotent=False,
+ required_role=Role.VIEWER,
+ audit=True,
+ audit_subject=accept_audit_subject,
+ skip_namespace_authz=True,
+)
+
OPERATIONS: list[Operation] = [
grants_create,
@@ -125,4 +195,8 @@
grants_approve,
grants_share_agent,
grants_unshare_agent,
+ grants_invite,
+ grants_list_invites,
+ grants_cancel_invite,
+ grants_accept_invite,
]
diff --git a/server/identity/app/grants.py b/server/identity/app/grants.py
index 9c5101a54ba..1b7f0f96e51 100644
--- a/server/identity/app/grants.py
+++ b/server/identity/app/grants.py
@@ -78,7 +78,7 @@ async def adopt_namespace(
return now
-async def _enforce_code_ceiling(org: str, namespace: str, role: str) -> None:
+async def enforce_code_ceiling(org: str, namespace: str, role: str) -> None:
"""On a code namespace `writer` does not exist; a reader (viewer) or maintainer (admin)
may be granted or approved by anyone the transport's ADMIN gate let through: an org
admin or a current maintainer of that repository."""
@@ -147,7 +147,7 @@ def _refuse_approval_below(current: str, target: str, input: GrantsApproveInput)
)
-def _enforce_principal_target(namespace: str, subject: str) -> None:
+def enforce_principal_target(namespace: str, subject: str) -> None:
"""A personal collection keeps its one grant; a group, an agent or
`everyone` holds grants only on collections; a `user:`/`group:`/`agent:`
subject needs a well-formed id."""
@@ -194,10 +194,7 @@ async def create_grant(
) -> GrantsCreateOutput:
"""`grants.create`; `may_replace` raises for a live row this caller must
not write over, checked on the row read under the grant's claim."""
- await _enforce_code_ceiling(input.org, input.namespace, input.role)
- _enforce_principal_target(input.namespace, input.subject)
- async with _group_held(input.org, input.subject):
- now = await _create_grant(input, may_replace)
+ now, _ = await store_grant(input, may_replace)
return GrantsCreateOutput(
org=input.org,
namespace=input.namespace,
@@ -207,42 +204,65 @@ async def create_grant(
)
+async def store_grant(
+ input: GrantsCreateInput,
+ may_replace: Callable[[GrantState], None] | None = None,
+ *,
+ issuer: str | None = None,
+) -> tuple[datetime, str]:
+ """`grants.create`'s checks and write: the code-namespace role ceiling, the principal
+ target and a group's claim, then the row under the subject's canonical spelling.
+ Returns when it was granted and the subject the row is stored under, which
+ `grants.create` does not answer. `issuer` is stamped as `granted_by` in place of the
+ caller: the maker of an invitation the caller accepts."""
+ await enforce_code_ceiling(input.org, input.namespace, input.role)
+ enforce_principal_target(input.namespace, input.subject)
+ async with _group_held(input.org, input.subject):
+ return await _create_grant(input, may_replace, issuer)
+
+
async def _create_grant(
- input: GrantsCreateInput, may_replace: Callable[[GrantState], None] | None
-) -> datetime:
- """`grants.create`'s write and what follows it; returns when it was granted."""
+ input: GrantsCreateInput,
+ may_replace: Callable[[GrantState], None] | None,
+ issuer: str | None = None,
+) -> tuple[datetime, str]:
+ """`grants.create`'s write and what follows it; returns when it was granted and the
+ subject it was written under."""
# A grant to a verified email is written under its account's login handle, so the
# person keeps one row; any other spelling is written as typed. The downgrade
# guard reads that same row.
from server.auth.aliases import canonical_subject
subject = await canonical_subject(input.org, input.subject)
- now = await _write_or_lower(input, subject, may_replace)
+ now = await _write_or_lower(input, subject, may_replace, issuer)
if input.role == "admin":
# Admin flows to the repository's other branches: from an operator entry to
# all of them, from a page-added branch to standard page-added ones.
from server.code.app.index import maintainers
await maintainers.sync_quietly(input.org, input.namespace)
- return now
+ return now, subject
async def _write_or_lower(
- input: GrantsCreateInput, subject: str, may_replace: Callable[[GrantState], None] | None
+ input: GrantsCreateInput,
+ subject: str,
+ may_replace: Callable[[GrantState], None] | None,
+ issuer: str | None = None,
) -> datetime:
"""Write the grant under its own claim, unless it lowers an active admin:
only `replace=true` lowers a grant (else 409), and that goes through
`_taking_admin`."""
async def _write(_row: GrantState | None) -> datetime:
- return await _write_grant(input, subject, may_replace)
+ return await _write_grant(input, subject, may_replace, issuer)
async with grant_change(input.org, input.namespace, subject):
row = None
if input.replace and input.role != "admin":
row = await grants_repo.find_any_grant(input.org, input.namespace, subject)
if row is None or not _active_admin(row):
- return await _write_grant(input, subject, may_replace)
+ return await _write_grant(input, subject, may_replace, issuer)
return await _taking_admin(input, subject, _write, lowered_to=input.role)
@@ -250,6 +270,7 @@ async def _write_grant(
input: GrantsCreateInput,
subject: str,
may_replace: Callable[[GrantState], None] | None = None,
+ issuer: str | None = None,
) -> datetime:
"""`grants.create`'s read of the current grant and its write, under the
grant's claim."""
@@ -261,13 +282,16 @@ async def _write_grant(
if pending_role is not None and grant_rank(input.role) >= grant_rank(str(pending_role)):
pending_role, pending_since = None, None
now = datetime.now(UTC).replace(tzinfo=None)
- # granted_by is who issued the grant — the authenticated caller, as
- # grants.approve records the approver. The body's value is honoured only
- # with auth off, where there is no caller to stamp.
+ # granted_by is who issued the grant: the maker of an invitation being accepted
+ # (`issuer`), else the authenticated caller, as grants.approve records the
+ # approver. The body's value is honoured only with auth off, where there is no
+ # caller to stamp.
from server.auth.context import current_auth
auth = current_auth()
- granted_by = auth.subject if auth is not None and auth.subject else input.granted_by or "admin"
+ granted_by = issuer or (
+ auth.subject if auth is not None and auth.subject else input.granted_by or "admin"
+ )
await grants_repo.insert_row(
{
"org": input.org,
@@ -600,7 +624,7 @@ async def _write_revoke(
async def handle_grants_approve(input: GrantsApproveInput) -> GrantsApproveOutput:
"""Approve or reject a pending grant. No-op if it doesn't exist."""
- _enforce_principal_target(input.namespace, input.subject)
+ enforce_principal_target(input.namespace, input.subject)
async with grant_change(input.org, input.namespace, input.subject):
out = await _decide_request(input)
if out.decision == "approve" and out.role == "admin":
@@ -646,7 +670,7 @@ async def _decide_request(input: GrantsApproveInput) -> GrantsApproveOutput:
target_role = input.role or pending_role or row.role
if input.decision == "approve" and not no_base_access:
_refuse_approval_below(row.role, str(target_role), input)
- await _enforce_code_ceiling(input.org, input.namespace, str(target_role))
+ await enforce_code_ceiling(input.org, input.namespace, str(target_role))
# granted_by on the new row is the approver, not the requester — the
# audit trail and the "approved by …" notification need the right person.
from server.auth.context import current_auth
diff --git a/server/identity/app/invite_mail.py b/server/identity/app/invite_mail.py
new file mode 100644
index 00000000000..2d840ce69e9
--- /dev/null
+++ b/server/identity/app/invite_mail.py
@@ -0,0 +1,109 @@
+"""The invitation email, sent over SMTP when `smtp_url`, `mail_from` and
+`public_base_url` are set. A failed send is logged and reported as not sent: the
+invitation stands, and whoever made it copies the link instead."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import smtplib
+import ssl
+from concurrent.futures import ThreadPoolExecutor
+from datetime import UTC, datetime
+from email.message import EmailMessage
+from email.utils import formatdate, make_msgid, parseaddr
+from urllib.parse import unquote, urlsplit
+
+import idna
+
+from server.core.naming import validate_namespace_name
+from server.settings import settings
+
+log = logging.getLogger(__name__)
+
+
+def can_send() -> bool:
+ return bool(settings.smtp_url and settings.mail_from and settings.public_base_url)
+
+
+def _message(
+ to: str, *, inviter: str, namespace: str, role: str, url: str, expires_at: int
+) -> EmailMessage:
+ until = datetime.fromtimestamp(expires_at, UTC).strftime("%d %B %Y, %H:%M UTC")
+ msg = EmailMessage()
+ msg["From"] = settings.mail_from
+ # The domain in IDNA's ASCII form, so a relay without SMTPUTF8 takes the address; only
+ # a non-ASCII local part still needs it.
+ local, _, domain = to.rpartition("@")
+ msg["To"] = f"{local}@{idna.encode(domain).decode('ascii')}"
+ lead = f"{inviter} invited you" if inviter else "You are invited"
+ # The email goes out as the operator's address, and any viewer can register a namespace
+ # under free text, so it names one only in the shape the server gives names.
+ try:
+ named = validate_namespace_name(namespace) == namespace
+ except ValueError:
+ named = False
+ msg["Subject"] = f"{lead} to {namespace if named else 'a namespace'} on Loom"
+ # Required of every message (RFC 5322); a relay passes a client's message on as sent.
+ msg["Date"] = formatdate(usegmt=True)
+ msg["Message-ID"] = make_msgid(domain=parseaddr(settings.mail_from)[1].rpartition("@")[2])
+ msg.set_content(
+ f"{lead} to {f'the Loom namespace {namespace}' if named else 'a Loom namespace'}, "
+ f"with the role {role}.\n\n"
+ f"Open this link, sign in, and accept:\n{url}\n\n"
+ f"The link works once, until {until}. If you did not expect it, ignore this email.\n"
+ )
+ return msg
+
+
+def _send(msg: EmailMessage) -> None:
+ u = urlsplit(settings.smtp_url)
+ host = u.hostname or ""
+ tls = ssl.create_default_context()
+ client: smtplib.SMTP
+ if u.scheme == "smtps":
+ client = smtplib.SMTP_SSL(
+ host, u.port or 465, context=tls, timeout=settings.smtp_timeout_seconds
+ )
+ else: # smtp://, the only other scheme the setting takes
+ client = smtplib.SMTP(host, u.port or 587, timeout=settings.smtp_timeout_seconds)
+ with client:
+ if u.scheme == "smtp":
+ client.ehlo()
+ # The link admits whoever reads it, and a login's password goes with it: neither
+ # is sent in the clear.
+ if not client.has_extn("starttls"):
+ raise smtplib.SMTPNotSupportedError("the server offers no STARTTLS")
+ client.starttls(context=tls)
+ client.ehlo()
+ if u.username:
+ client.login(unquote(u.username), unquote(u.password or ""))
+ client.send_message(msg)
+
+
+# Sends run on threads of their own: one past the timeout keeps its thread until each socket
+# step times out, so a stalled relay holds these, not the threads every other
+# `asyncio.to_thread` caller (name resolution among them) shares.
+_THREADS = 4 # not a setting: a bound on blocked threads; the mail limits bound the rate
+_EXECUTOR = ThreadPoolExecutor(max_workers=_THREADS, thread_name_prefix="loom-invite-mail")
+
+
+async def send_invite(
+ to: str, *, inviter: str, namespace: str, role: str, url: str, expires_at: int
+) -> bool:
+ """Email the link to `to`, which the caller has checked may be mailed; True when the
+ mail server took it."""
+ try:
+ # Inside: the email library refuses a header with a line break in it.
+ msg = _message(
+ to, inviter=inviter, namespace=namespace, role=role, url=url, expires_at=expires_at
+ )
+ # The whole exchange, not each step: the invite answers only after it. A send past
+ # it may still arrive, beside the link the inviter is shown.
+ sent = asyncio.get_running_loop().run_in_executor(_EXECUTOR, _send, msg)
+ await asyncio.wait_for(sent, settings.smtp_timeout_seconds)
+ except Exception as e: # noqa: BLE001 — a failed email leaves the link to copy
+ # Not the address: the audit row leaves it out, and no erasure reaches the log.
+ log.warning("invite mail: not sent: %s", type(e).__name__)
+ return False
+ return True
diff --git a/server/identity/app/invites.py b/server/identity/app/invites.py
new file mode 100644
index 00000000000..3fcf4605488
--- /dev/null
+++ b/server/identity/app/invites.py
@@ -0,0 +1,495 @@
+"""grants.{invite,list_invites,cancel_invite,accept_invite} handlers.
+
+`grants.invite` gives a person a role by what an admin knows of them. A handle an
+account or a live grant holds, or an email verified for an account, is granted at once.
+An email no account holds gets an invitation link, of which Loom keeps only the
+secret's hash. It is emailed when the server has mail settings, and gives its role
+once, to whoever opens it, under the account they sign in with. A password account's
+email is never verified, so this is how a person is reached by email on a server
+without single sign-on. Where sign-in is single sign-on only (`oauth_login_provider =
+"oidc"`), every account's email is verified by the identity provider, so the email is
+granted as typed and reaches that person at their first sign-in, with no link to pass
+on. A handle no account or live grant holds is refused, so a typo is never kept as a
+grant for whoever signs up under it later. A request with no token, which only auth off
+serves, grants such a handle or email as typed.
+
+An invitation stands on its maker as a delegated token stands on its creator
+(`_maker_stands`): grants that make them admin there, read as the gate reads them, an
+active account and no revocation of their subject or of tokens as old as the link,
+checked when the link is made and again when it is accepted. An admin only a token's
+claim makes cannot make one.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from datetime import UTC, datetime
+from typing import Any
+
+import idna
+
+from server.auth.attempts import Attempts
+from server.auth.authz import subject_grant_role
+from server.auth.delegation import creator_account_active
+from server.auth.fail_closed import reset, unreadable
+from server.auth.grant_claims import invite_change
+from server.auth.revocation import is_revoked
+from server.auth.self_signup import valid_signup_email
+from server.core.ch import own_write_reads
+from server.core.errors import (
+ BackendUnavailableError,
+ GrantWouldDowngradeError,
+ NotFoundError,
+ ValidationError,
+)
+from server.core.logging_config import log_value
+from server.core.principals import (
+ USER,
+ end_user_revocation_subject,
+ has_aliases,
+ is_reserved_subject,
+ principal_id,
+)
+from server.core.shielded import finish_cleanup
+from server.identity.api.models_grants import (
+ GrantsAcceptInviteInput,
+ GrantsAcceptInviteOutput,
+ GrantsCancelInviteInput,
+ GrantsCancelInviteOutput,
+ GrantsCreateInput,
+ GrantsInviteInput,
+ GrantsInviteOutput,
+ GrantsListInvitesInput,
+ GrantsListInvitesOutput,
+ _InviteEntry,
+)
+from server.identity.app import invite_mail
+from server.identity.app.grants import (
+ enforce_code_ceiling,
+ enforce_principal_target,
+ store_grant,
+)
+from server.identity.domain import invites as domain
+from server.identity.domain.grants import GrantState
+from server.identity.store import grants as grants_repo
+from server.identity.store import invites as invites_repo
+from server.identity.store import namespaces as namespaces_repo
+from server.operations.base import GRANT_ROLES, GrantRoleStr, Role, grant_rank
+from server.settings import settings
+
+log = logging.getLogger(__name__)
+
+# The open invitations a namespace lists.
+_LISTED = 200
+# Invitation emails, so that the server's mail is no relay for a namespace admin (whom any
+# sign-up can make): per org, which more sign-ups do not multiply, per inviter, and per
+# mailbox invited. Past any of them the invitation is still made, and its link is the
+# inviter's to pass on.
+_mail_by_org = Attempts("invite.mail.org", 100, 3600)
+_mail_by_inviter = Attempts("invite.mail.inviter", 20, 3600)
+_mail_by_address = Attempts("invite.mail.address", 3, 86400)
+_GONE = (
+ "this invitation link admits nobody now: it is used, cancelled or expired, its "
+ "namespace is deleted, or its maker no longer stands behind it; ask for a new one"
+)
+
+
+def _role(value: str) -> GrantRoleStr | None:
+ """A role read back from a row; None for one this build does not know."""
+ return next((r for r in GRANT_ROLES if r == value), None)
+
+
+def _maker() -> str:
+ """Whose admin an invitation stands on: a delegated token's creator, else the caller."""
+ from server.auth.context import current_auth
+
+ auth = current_auth()
+ return str(auth.creator or auth.subject) if auth is not None else ""
+
+
+def _inviter(maker: str) -> str:
+ """The maker as the email names them: a person's handle, else "" for a service
+ account acting as itself or an end user's `user:`, who name nobody the reader
+ knows. A delegated token's creator, or the subject an on-behalf request acts for, is
+ a person."""
+ from server.auth.context import current_auth
+
+ auth = current_auth()
+ as_itself = (
+ auth is not None and auth.is_service_account and not (auth.creator or auth.impersonated_by)
+ )
+ return maker if has_aliases(maker) and not as_itself else ""
+
+
+def _person(to: str) -> str:
+ """`to` as a person's spelling, or a refusal that names the op for the others."""
+ person = to.strip()
+ if not has_aliases(person.lower()) or is_reserved_subject(person):
+ raise ValidationError(
+ "invite a person by login handle or email; grants.create grants a service account, "
+ "a group or everyone"
+ )
+ return person
+
+
+async def _held(org: str, person: str) -> str | None:
+ """The subject an account signs in as for `person`, as stored; None when there is
+ none. An email counts only through the account it is verified for: a row's
+ `owner_email` and a grant's subject are whatever their writer typed. A handle counts
+ when an active row is owned under it or a live grant in the org is stored under it
+ (a person whose tokens Loom did not mint at sign-in has no account row): sign-up
+ refuses such a name (`self_signup.refuse_empowered`), so no later account takes
+ a grant meant for it."""
+ from server.auth.aliases import verified_owner
+
+ if "@" in person:
+ return await verified_owner(org, person)
+ handle = await namespaces_repo.account_handle(org, person)
+ return handle or await grants_repo.granted_spelling(org, person)
+
+
+async def handle_grants_invite(input: GrantsInviteInput) -> GrantsInviteOutput:
+ person = _person(input.to)
+ enforce_principal_target(input.namespace, person)
+ subject = await _held(input.org, person)
+ if subject is not None:
+ return await _granted(input, subject)
+ maker = _maker()
+ if not maker:
+ # A request with no token, which only auth off serves: no one signs in to accept.
+ return await _granted(input, person)
+ if "@" not in person:
+ raise NotFoundError(
+ f"no account in {input.org} signs in as {person!r}: check the login handle, "
+ "or invite them by email"
+ )
+ if not valid_signup_email(person.lower()):
+ # One plain address, so it names one recipient and keys its own mail limit.
+ raise ValidationError(f"{person!r} is not an email address")
+ if settings.oauth_login_provider == "oidc":
+ return await _granted(input, person)
+ # Read as the active check reads, past a repository's namespace just registered: a
+ # lagging read takes it for a memory one and stores a writer link no accept can grant.
+ with own_write_reads():
+ await enforce_code_ceiling(input.org, input.namespace, input.role)
+ if not await namespaces_repo.is_active(input.org, input.namespace):
+ raise NotFoundError(
+ f"{input.org}/{input.namespace} is not an active namespace: register or restore it "
+ "before inviting anyone"
+ )
+ return await _invite(input, person.lower(), maker)
+
+
+async def _granted(input: GrantsInviteInput, subject: str) -> GrantsInviteOutput:
+ # The answer names the subject the row is stored under: an email-shaped handle another
+ # account verified moves onto that account's handle.
+ _, stored = await store_grant(
+ GrantsCreateInput(
+ org=input.org, namespace=input.namespace, subject=subject, role=input.role
+ )
+ )
+ return GrantsInviteOutput(outcome="granted", role=input.role, subject=stored)
+
+
+async def _maker_stands(org: str, namespace: str, maker: str, made_at: int) -> bool:
+ """Whether `maker` still stands behind a link made at `made_at` (Unix seconds), as a
+ delegated token's creator stands behind it: `_maker_admin`, and neither they nor
+ tokens of theirs that old are revoked."""
+ return await _maker_admin(org, namespace, maker) and not _revoked(org, maker, made_at)
+
+
+def _revoked(org: str, maker: str, made_at: int) -> bool:
+ """Whether `maker`'s tokens as old as `made_at` are revoked, under the subject the
+ token check reads: an end user's is `/user:`."""
+ key = end_user_revocation_subject(org, maker) if principal_id(maker, USER) else maker
+ return is_revoked(key, issued_at=made_at)
+
+
+async def _maker_admin(org: str, namespace: str, maker: str) -> bool:
+ """Whether `maker`'s grants make them admin there (`authz.subject_grant_role`) and
+ their account is active. A read that fails answers 503, so a link is not given up
+ for an outage."""
+ reset() # this decision's own reads, not an earlier one's in the request
+ role = await subject_grant_role(org, namespace, maker)
+ active = await creator_account_active(org, maker)
+ if unreadable():
+ raise BackendUnavailableError("the inviter's grants could not be read: try again")
+ return role is not None and role.value >= Role.ADMIN.value and active
+
+
+async def _invite(input: GrantsInviteInput, email: str, maker: str) -> GrantsInviteOutput:
+ if not await _maker_stands(input.org, input.namespace, maker, int(time.time())):
+ raise ValidationError(
+ f"an invitation link stands on its maker's grants on {input.org}/{input.namespace}, "
+ f"and those of {maker!r} do not make them admin there with an active account: an "
+ "admin there through a grant invites them"
+ )
+ secret = domain.new_secret()
+ now = datetime.now(UTC)
+ invite = domain.Invite(
+ org=input.org,
+ namespace=input.namespace,
+ invite_id=domain.invite_id(secret),
+ email=email,
+ role=input.role,
+ created_by=maker,
+ created_at=now,
+ expires_at=int(now.timestamp()) + settings.invite_ttl_seconds,
+ )
+ # Asked before the row: a limit that cannot be read fails the invitation, not a link
+ # left listed that nobody was given.
+ may_mail = await _may_mail(input.org, maker, email)
+ await invites_repo.put(invite)
+ path = domain.link_path(input.org, input.namespace, secret)
+ base = settings.public_base_url.strip().rstrip("/")
+ url = f"{base}{path}" if base else ""
+ emailed = may_mail and await invite_mail.send_invite(
+ email,
+ inviter=_inviter(invite.created_by),
+ namespace=input.namespace,
+ role=input.role,
+ url=url,
+ expires_at=invite.expires_at,
+ )
+ return GrantsInviteOutput(
+ outcome="invited",
+ role=input.role,
+ invite_id=invite.invite_id,
+ link_path=path,
+ url=url,
+ expires_at=datetime.fromtimestamp(invite.expires_at, UTC),
+ emailed=emailed,
+ )
+
+
+def _mailbox(email: str) -> str:
+ """The key of an address's mail limit: its local part without a `+tag` or dots, which
+ a provider may ignore, and its domain in IDNA's ASCII form, as the email is sent. Two
+ people folded together share a limit, past which the link is still made."""
+ local, _, host = email.lower().rpartition("@")
+ box = local.split("+", 1)[0].replace(".", "")
+ return f"{box}@{idna.encode(host).decode('ascii')}"
+
+
+async def _may_mail(org: str, maker: str, email: str) -> bool:
+ """Whether this invitation may be emailed: the server sends mail, and neither the org,
+ the maker (keyed by subject, not by the name the mail shows) nor the mailbox is past
+ its limit."""
+ if not invite_mail.can_send():
+ return False
+ mailbox = _mailbox(email)
+ # A mailbox or org at its limit is refused before the inviter's attempt is counted,
+ # and each limit before the next one's is.
+ if await _mail_by_address.blocked(mailbox) or await _mail_by_org.blocked(org):
+ return False
+ return (
+ await _mail_by_inviter.allow(f"{org}/{maker}")
+ and await _mail_by_org.allow(org)
+ and await _mail_by_address.allow(mailbox)
+ )
+
+
+async def handle_grants_list_invites(input: GrantsListInvitesInput) -> GrantsListInvitesOutput:
+ read = await invites_repo.open_on(input.org, input.namespace, int(time.time()), _LISTED + 1)
+ rows = read[:_LISTED]
+ # A link whose maker does not stand now admits nobody but still holds the name, so it
+ # is listed, marked, for an admin to cancel.
+ admin = {
+ m: await _maker_admin(input.org, input.namespace, m) for m in {r.created_by for r in rows}
+ }
+ return GrantsListInvitesOutput(
+ rows=[
+ _InviteEntry(
+ invite_id=r.invite_id,
+ email=r.email,
+ role=role,
+ created_by=r.created_by,
+ created_at=r.created_at,
+ expires_at=datetime.fromtimestamp(r.expires_at, UTC),
+ stopped=not admin[r.created_by]
+ or _revoked(input.org, r.created_by, int(r.created_at.timestamp())),
+ )
+ for r in rows
+ if (role := _role(r.role)) is not None
+ ],
+ truncated=len(read) > _LISTED,
+ )
+
+
+async def handle_grants_cancel_invite(input: GrantsCancelInviteInput) -> GrantsCancelInviteOutput:
+ async with invite_change(input.org, input.namespace, input.invite_id):
+ invite = await invites_repo.get(input.org, input.namespace, input.invite_id)
+ if invite is None:
+ return GrantsCancelInviteOutput(cancelled=False)
+ was_open = invite.is_open(int(time.time()))
+ # An accepted one is closed too, so an accept whose grant then fails leaves it
+ # closed rather than open again after the cancel.
+ if was_open or invite.state == "accepted":
+ await invites_repo.put(invite.cancelled())
+ return GrantsCancelInviteOutput(cancelled=was_open)
+
+
+def _accepter(org: str) -> str:
+ """The signed-in person accepting: a service account, a principal, a trusted caller
+ acting for someone or a token of another org is refused."""
+ from server.auth.context import current_auth
+
+ auth = current_auth()
+ if auth is None or not auth.subject:
+ raise ValidationError("sign in to accept an invitation")
+ subject = str(auth.subject)
+ if (
+ auth.is_service_account
+ # An on-behalf request carries its bearer's flag, not the person's: refused either way.
+ or auth.impersonated_by
+ or not has_aliases(subject)
+ or is_reserved_subject(subject)
+ ):
+ raise ValidationError("an invitation is accepted by a person, signed in as themselves")
+ if auth.org != org:
+ raise ValidationError(f"this invitation is to {org}: sign in to {org} to accept it")
+ return subject
+
+
+async def handle_grants_accept_invite(input: GrantsAcceptInviteInput) -> GrantsAcceptInviteOutput:
+ subject = _accepter(input.org)
+ invite_id = domain.invite_id(input.secret)
+ # Read before the claim, so a secret no invitation holds costs no lease: a row is keyed
+ # by its secret's hash, so none can appear for it meanwhile.
+ if await invites_repo.get(input.org, input.namespace, invite_id) is None:
+ raise NotFoundError(_GONE)
+ spent: domain.Invite | None = None
+ try:
+ async with invite_change(input.org, input.namespace, invite_id):
+ invite = await invites_repo.get(input.org, input.namespace, invite_id)
+ role = None if invite is None else _role(invite.role)
+ if invite is None or role is None:
+ raise NotFoundError(_GONE)
+ if invite.accepted_by == subject:
+ # The accepter again, after a reply that was lost (and maybe a cancel since):
+ # the role they hold now, writing nothing, while it is at least the link's.
+ # A lower one is not the invitation done: its grant failed with the link not
+ # reopened, or was lowered or revoked since; either way the link is used.
+ current = await _grant_now(invite, subject)
+ if current is None or grant_rank(current.role) < grant_rank(role):
+ raise NotFoundError(_GONE)
+ return GrantsAcceptInviteOutput(namespace=input.namespace, role=current.role)
+ if not invite.is_open(int(time.time())):
+ raise NotFoundError(_GONE)
+ if not await namespaces_repo.is_active(input.org, input.namespace):
+ raise NotFoundError(_GONE)
+ made_at = int(invite.created_at.timestamp())
+ if not await _maker_stands(invite.org, invite.namespace, invite.created_by, made_at):
+ raise NotFoundError(_GONE)
+ # Spent under the claim, before the grant: a link never lets two people in. The
+ # grant takes its own claims after this one, as `grant_claims` orders them.
+ spent = invite
+ await invites_repo.put(invite.accepted(subject))
+ held = await _grant(invite, role, subject)
+ except BaseException:
+ if spent is not None:
+ await _reopen_after_failure(spent, subject)
+ raise
+ return GrantsAcceptInviteOutput(namespace=input.namespace, role=held)
+
+
+async def _reopen_after_failure(invite: domain.Invite, subject: str) -> None:
+ """`_reopen_unless_granted`, run to its end through a cancellation (anyio repeats one
+ at every await); a reopen that fails leaves the link used."""
+ try:
+ await finish_cleanup(_reopen_unless_granted(invite, subject), name="invite.reopen")
+ except Exception as e: # noqa: BLE001 — the failure's error is the answer; link stays used
+ log.warning(
+ "invitation %s on %s/%s stays used after a failed accept: %s",
+ log_value(invite.invite_id[:12]),
+ log_value(invite.org),
+ log_value(invite.namespace),
+ type(e).__name__,
+ )
+
+
+async def _grant_now(invite: domain.Invite, subject: str) -> GrantState | None:
+ """The accepter's active grant on the invitation's namespace, read under the subject
+ `store_grant` writes it under. Called under the claim, so it reads with sequential
+ consistency: right after the grant's own write, another replica may not have it yet."""
+ from server.auth.aliases import canonical_subject
+
+ granted_to = await canonical_subject(invite.org, subject)
+ return await grants_repo.find_active_grant(invite.org, invite.namespace, granted_to)
+
+
+async def _reopen_unless_granted(invite: domain.Invite, subject: str) -> None:
+ """Open the link again after a failed grant, unless the grant landed before the
+ failure (a lost reply, a step after the write): then it stays used. A read that fails
+ raises, and the link stays used."""
+ async with invite_change(invite.org, invite.namespace, invite.invite_id):
+ held = await _grant_now(invite, subject)
+ if held is not None and grant_rank(held.role) >= grant_rank(invite.role):
+ return
+ current = await invites_repo.get(invite.org, invite.namespace, invite.invite_id)
+ if current is None or current.accepted_by != subject:
+ return
+ if (current.state, current.created_by) == ("accepted", invite.created_by):
+ await invites_repo.put(invite) # unchanged since the accept, but for it
+ else:
+ # Closed meanwhile (a cancel, or an erasure that took the maker off): it stays
+ # closed, and names no accepter, since no grant landed.
+ await invites_repo.put(current.unclaimed())
+
+
+def invite_audit_subject(input: GrantsInviteInput, response: dict[str, Any]) -> dict[str, Any]:
+ """What an invitation's audit row records: who got the role, or the invitation by the
+ hash it is stored under, never the address it was made for."""
+ out = {
+ "org": input.org,
+ "namespace": input.namespace,
+ "role": response["role"],
+ "outcome": response["outcome"],
+ }
+ if response["outcome"] == "granted":
+ out["subject"] = response["subject"]
+ else:
+ out["invite_id"] = response["invite_id"]
+ return out
+
+
+def accept_audit_subject(
+ input: GrantsAcceptInviteInput, response: dict[str, Any]
+) -> dict[str, Any]:
+ """What an acceptance's audit row records, never the link's secret: the invitation
+ spent, by the hash it is stored under, and the role the caller holds now."""
+ return {
+ "org": input.org,
+ "namespace": input.namespace,
+ "invite_id": domain.invite_id(input.secret),
+ "role": response["role"],
+ }
+
+
+async def _grant(invite: domain.Invite, role: GrantRoleStr, subject: str) -> GrantRoleStr:
+ """The invitation's role for `subject`, stamped as granted by its maker; a higher
+ role they hold already stands."""
+ try:
+ await store_grant(
+ GrantsCreateInput(
+ org=invite.org, namespace=invite.namespace, subject=subject, role=role
+ ),
+ issuer=invite.created_by,
+ )
+ except GrantWouldDowngradeError as e:
+ return _role(e.extra["current_role"]) or role
+ return role
+
+
+async def forget_maker(org: str, maker: str) -> int:
+ """`maker` taken off every invitation they made in `org`, and each open one closed,
+ for an erasure: no link stands on an erased admin. Returns the invitations changed."""
+ changed = 0
+ for found in await invites_repo.made_by(org, maker):
+ async with invite_change(org, found.namespace, found.invite_id):
+ invite = await invites_repo.get(org, found.namespace, found.invite_id)
+ if invite is not None and invite.created_by == maker:
+ await invites_repo.put(invite.forgotten())
+ changed += 1
+ return changed
diff --git a/server/identity/domain/invites.py b/server/identity/domain/invites.py
new file mode 100644
index 00000000000..aa21ac17cff
--- /dev/null
+++ b/server/identity/domain/invites.py
@@ -0,0 +1,81 @@
+"""An invitation to a namespace: a link that gives whoever opens it, once, a role there.
+
+The link carries a random secret; Loom keeps only its SHA-256 (`invite_id`), so a row
+read out of storage is not a working link. An invitation is open until it is
+accepted, cancelled or `expires_at` passes; a state this build does not know is closed.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import secrets
+from dataclasses import asdict, dataclass, replace
+from datetime import datetime
+from typing import Any
+from urllib.parse import urlencode
+
+from server.core.datetimes import as_aware_utc
+
+
+def new_secret() -> str:
+ return secrets.token_urlsafe(32)
+
+
+def invite_id(secret: str) -> str:
+ return hashlib.sha256(secret.encode()).hexdigest()
+
+
+def link_path(org: str, namespace: str, secret: str) -> str:
+ """The dashboard page that accepts it, Namespaces in your org. All of it is the
+ fragment, which a browser never sends to a server or puts in a Referer."""
+ return "/spaces#" + urlencode({"invite": secret, "org": org, "namespace": namespace})
+
+
+@dataclass(frozen=True)
+class Invite:
+ org: str
+ namespace: str
+ invite_id: str
+ email: str
+ role: str
+ created_by: str
+ created_at: datetime
+ expires_at: int
+ state: str = "open"
+ accepted_by: str = ""
+
+ def is_open(self, now: int) -> bool:
+ return self.state == "open" and now < self.expires_at
+
+ def accepted(self, by: str) -> Invite:
+ return replace(self, state="accepted", accepted_by=by)
+
+ def cancelled(self) -> Invite:
+ return replace(self, state="cancelled")
+
+ def unclaimed(self) -> Invite:
+ """Naming no accepter: one whose grant never landed, on a link closed meanwhile."""
+ return replace(self, accepted_by="")
+
+ def forgotten(self) -> Invite:
+ """Its maker's name taken off, and closed if it was open."""
+ state = "cancelled" if self.state == "open" else self.state
+ return replace(self, created_by="", state=state)
+
+ def row(self) -> dict[str, Any]:
+ return asdict(self)
+
+ @classmethod
+ def from_row(cls, r: dict[str, Any]) -> Invite:
+ return cls(
+ org=str(r["org"]),
+ namespace=str(r["namespace"]),
+ invite_id=str(r["invite_id"]),
+ email=str(r["email"]),
+ role=str(r["role"]),
+ created_by=str(r["created_by"]),
+ created_at=as_aware_utc(r["created_at"]),
+ expires_at=int(r["expires_at"]),
+ state=str(r["state"]),
+ accepted_by=str(r["accepted_by"]),
+ )
diff --git a/server/identity/store/grants.py b/server/identity/store/grants.py
index 686d48a51cf..7bea8334540 100644
--- a/server/identity/store/grants.py
+++ b/server/identity/store/grants.py
@@ -329,6 +329,24 @@ async def find_active_grant(
return None if row is None else GrantState.from_row(row)
+async def granted_spelling(org: str, subject: str, *, ch: _CHClient | None = None) -> str | None:
+ """The subject, as stored, of a live grant in `org` that matches `subject` in any
+ case; None when there is none. Read past a grant another replica just wrote."""
+ from server.core.ch import own_write_reads
+
+ with own_write_reads():
+ row = await (ch or _default_client()).query_one(
+ """
+ SELECT subject FROM loom.namespace_grants FINAL
+ WHERE org = {org:String} AND lower(subject) = lower({sub:String}) AND {live}
+ ORDER BY subject
+ LIMIT 1
+ """.replace("{live}", LIVE_GRANT),
+ params={"org": org, "sub": subject},
+ )
+ return None if row is None else str(row["subject"])
+
+
async def live_rows_of(
org: str, subject: str, *, ch: _CHClient | None = None
) -> list[dict[str, Any]]:
diff --git a/server/identity/store/invites.py b/server/identity/store/invites.py
new file mode 100644
index 00000000000..6bfa5c5b302
--- /dev/null
+++ b/server/identity/store/invites.py
@@ -0,0 +1,72 @@
+"""Repository for loom.namespace_invites.
+
+One row per invitation, keyed by (org, namespace, invite_id); `invite_id` is the
+SHA-256 of the link's secret. ReplacingMergeTree(version) keeps the newest
+state, so an acceptance or a cancellation is a new row with a version past the
+last (`next_version`). The caller holds the invitation's claim
+(`grant_claims.invite_change`) from its read to that write.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from server.core.ch import own_write_reads
+from server.core.repo_base import _CHClient, _default_client
+from server.core.versions import next_version
+from server.identity.domain.invites import Invite
+
+TABLE = "loom.namespace_invites"
+_COLUMNS = (
+ "org, namespace, invite_id, email, role, created_by, created_at, expires_at, state, accepted_by"
+)
+
+
+async def put(invite: Invite, *, ch: _CHClient | None = None) -> None:
+ client = ch or _default_client()
+ row = invite.row()
+ row["version"] = await next_version(
+ client,
+ TABLE,
+ {"org": invite.org, "namespace": invite.namespace, "invite_id": invite.invite_id},
+ )
+ await client.insert(TABLE, [row], settings={"async_insert": 0, "wait_for_async_insert": 1})
+
+
+async def get(
+ org: str, namespace: str, invite_id: str, *, ch: _CHClient | None = None
+) -> Invite | None:
+ """The invitation's newest state, read past a write another replica just took."""
+ with own_write_reads():
+ row = await (ch or _default_client()).query_one(
+ f"SELECT {_COLUMNS} FROM {TABLE} FINAL WHERE org = {{org:String}} "
+ "AND namespace = {ns:String} AND invite_id = {id:String} LIMIT 1",
+ params={"org": org, "ns": namespace, "id": invite_id},
+ )
+ return Invite.from_row(dict(row)) if row else None
+
+
+async def open_on(
+ org: str, namespace: str, now: int, limit: int, *, ch: _CHClient | None = None
+) -> list[Invite]:
+ """The namespace's invitations still open at `now` (Unix seconds), newest first."""
+ with own_write_reads():
+ rows: list[dict[str, Any]] = await (ch or _default_client()).query_all(
+ f"SELECT {_COLUMNS} FROM {TABLE} FINAL WHERE org = {{org:String}} "
+ "AND namespace = {ns:String} AND state = 'open' AND expires_at > {now:UInt32} "
+ "ORDER BY created_at DESC LIMIT {limit:UInt32}",
+ params={"org": org, "ns": namespace, "now": now, "limit": limit},
+ )
+ return [Invite.from_row(dict(r)) for r in rows]
+
+
+async def made_by(org: str, maker: str, *, ch: _CHClient | None = None) -> list[Invite]:
+ """Every invitation in `org` that `maker` made, read past a write another replica
+ just took."""
+ with own_write_reads():
+ rows: list[dict[str, Any]] = await (ch or _default_client()).query_all(
+ f"SELECT {_COLUMNS} FROM {TABLE} FINAL WHERE org = {{org:String}} "
+ "AND created_by = {maker:String}",
+ params={"org": org, "maker": maker},
+ )
+ return [Invite.from_row(dict(r)) for r in rows]
diff --git a/server/identity/store/namespace_census.py b/server/identity/store/namespace_census.py
index bdf5e7bf4b0..f759257f500 100644
--- a/server/identity/store/namespace_census.py
+++ b/server/identity/store/namespace_census.py
@@ -74,12 +74,15 @@ async def unregistered_live(
_AT = "org = {org:String} AND namespace = {ns:String}"
# Tables outside the erasure census whose live rows a later owner of the name would
-# inherit (a grant, an outside target, a source, a mirror, a tree node, an identity
-# link, an open erasure), each with the condition that makes its row live. Every other
-# table keyed by namespace is counted by the census or exempt with a reason
-# (tests/unit/test_in_use_coverage.py).
+# inherit (a grant, an open invitation, an outside target, a source, a mirror, a tree
+# node, an identity link, an open erasure), each with the condition that makes its row
+# live. Every other table keyed by namespace is counted by the census or exempt with a
+# reason (tests/unit/test_in_use_coverage.py).
STATE_TABLES: dict[str, str] = {
"loom.namespace_grants": f"FINAL WHERE {_AT} AND {LIVE_GRANT}",
+ # Accepting one grants its role on whatever the name then holds.
+ "loom.namespace_invites": f"FINAL WHERE {_AT} AND state = 'open'"
+ " AND expires_at > toUInt32(now())",
"loom.memory_webhooks": f"FINAL WHERE {_AT} AND is_deleted = 0",
"loom.task_inboxes": "FINAL WHERE org = {org:String} AND owner_namespace = {ns:String}"
" AND is_deleted = 0",
diff --git a/server/identity/store/namespaces.py b/server/identity/store/namespaces.py
index aae3c35355d..f8b59c0ea66 100644
--- a/server/identity/store/namespaces.py
+++ b/server/identity/store/namespaces.py
@@ -9,6 +9,7 @@
from datetime import datetime
from typing import Any
+from server.core.ch import own_write_reads
from server.core.repo_base import _CHClient, _default_client
@@ -79,19 +80,37 @@ def claimed_row(
async def is_active(org: str, namespace: str, *, ch: _CHClient | None = None) -> bool:
- """Is (org, namespace) a registered, active namespace? A soft-deleted one is not."""
- ch = ch or _default_client()
- row = await ch.query_one(
- """
- SELECT 1 AS one FROM loom.namespaces FINAL
- WHERE org = {org:String} AND namespace = {ns:String} AND active
- LIMIT 1
- """,
- params={"org": org, "ns": namespace},
- )
+ """Is (org, namespace) a registered, active namespace? A soft-deleted one is not.
+ Read past a namespace another replica just registered."""
+ with own_write_reads():
+ row = await (ch or _default_client()).query_one(
+ """
+ SELECT 1 AS one FROM loom.namespaces FINAL
+ WHERE org = {org:String} AND namespace = {ns:String} AND active
+ LIMIT 1
+ """,
+ params={"org": org, "ns": namespace},
+ )
return row is not None
+async def account_handle(org: str, subject: str, *, ch: _CHClient | None = None) -> str | None:
+ """The owner, as stored, of an active row of `org` owned under `subject` in any case
+ (an account's own row, or a namespace registered for that owner); None when none is.
+ Read past a row another replica just made."""
+ with own_write_reads():
+ row = await (ch or _default_client()).query_one(
+ """
+ SELECT owner_email FROM loom.namespaces FINAL
+ WHERE org = {org:String} AND active AND lower(owner_email) = lower({sub:String})
+ ORDER BY owner_email
+ LIMIT 1
+ """,
+ params={"org": org, "sub": subject},
+ )
+ return None if row is None else str(row["owner_email"])
+
+
async def labels(
org: str, namespaces: list[str], *, ch: _CHClient | None = None
) -> dict[str, dict[str, str]]:
diff --git a/server/operations/reach_manifest.py b/server/operations/reach_manifest.py
index cce706e718e..97f86137fff 100644
--- a/server/operations/reach_manifest.py
+++ b/server/operations/reach_manifest.py
@@ -367,18 +367,34 @@
"sdk_method",
"dashboard",
),
+ "grants.accept_invite": (
+ "sdk_method",
+ "dashboard",
+ ),
"grants.approve": (
"sdk_method",
"dashboard",
),
+ "grants.cancel_invite": (
+ "sdk_method",
+ "dashboard",
+ ),
"grants.create": (
"sdk_method",
"dashboard",
),
+ "grants.invite": (
+ "sdk_method",
+ "dashboard",
+ ),
"grants.list": (
"sdk_method",
"dashboard",
),
+ "grants.list_invites": (
+ "sdk_method",
+ "dashboard",
+ ),
"grants.pending_for_me": (
"sdk_method",
"dashboard",
diff --git a/server/settings/_env.py b/server/settings/_env.py
index c68d526cdef..a56237d0cb3 100644
--- a/server/settings/_env.py
+++ b/server/settings/_env.py
@@ -149,6 +149,8 @@ def unknown_env_keys(fields: Iterable[str], env_file: str | None) -> list[str]:
r"(?:^|_)otlp_headers$",
# A Postgres DSN carries the password: the memory authority's and the router's.
r"(?:^|_)pg_dsn$",
+ # Its userinfo is the mail server's login.
+ r"^smtp_url$",
)
)
)
diff --git a/server/settings/catalog.py b/server/settings/catalog.py
index 099641de52f..aca8c235255 100644
--- a/server/settings/catalog.py
+++ b/server/settings/catalog.py
@@ -21,6 +21,8 @@
from collections.abc import Mapping
from dataclasses import dataclass
from dataclasses import field as dataclass_field
+from email.message import EmailMessage
+from email.utils import getaddresses
from typing import Annotated, Any, Literal
from urllib.parse import urlsplit
@@ -147,6 +149,42 @@ def signs_for(self, org: str) -> bool:
return any(org_patterns.matches(o, org) for o in self.orgs)
+def _one_mailbox(raw: str) -> str:
+ """`raw` when an email's From header and its SMTP envelope both read it as the same
+ one address with a domain: an unquoted `,` or `;` in a display name makes two. The
+ address in ASCII, which a relay without SMTPUTF8 takes."""
+ if raw:
+ header = EmailMessage()
+ header["From"] = raw # refuses a line break
+ boxes = [a.addr_spec for a in header["From"].addresses]
+ if (
+ len(boxes) != 1
+ or "@" not in boxes[0]
+ or not boxes[0].isascii()
+ or [a for _, a in getaddresses([raw])] != boxes
+ ):
+ raise ValueError(
+ "name one ASCII address, as `Loom ` (an international "
+ "domain in its xn-- form); quote a display name that holds `,` or `;`"
+ )
+ return raw
+
+
+def _mail_server(raw: str) -> str:
+ """`raw` when a send can connect to it: `smtps://` or `smtp://`, a host and, if one is
+ given, a port from 1 to 65535."""
+ if raw:
+ try:
+ u = urlsplit(raw)
+ port_ok = u.port is None or u.port > 0
+ ok = u.scheme in ("smtp", "smtps") and bool(u.hostname) and port_ok
+ except ValueError:
+ ok = False # urllib's message quotes the netloc, which can hold the password
+ if not ok:
+ raise ValueError("name a mail server, as `smtps://user:password@host:465`")
+ return raw
+
+
class AuthSettings(BaseModel):
"""Authentication, tokens and identity providers."""
@@ -468,6 +506,19 @@ def trusted_issuers(self) -> set[str]:
# Default org for self-signed tokens.
self_signup_org: str = "dev"
+ # The mail server invitations go through: `smtps://user:password@host:465`, or `smtp://`
+ # on 587, which must offer STARTTLS. Empty: no email, and the inviter passes the link on.
+ smtp_url: Annotated[str, AfterValidator(_mail_server)] = ""
+ # The From address of an invitation email, e.g. `Loom `: one ASCII address
+ # (quote a display name with `,` or `;`), else refused at load. Empty sends none.
+ mail_from: Annotated[str, AfterValidator(_one_mailbox)] = ""
+ # Seconds an invitation email's whole send may take, at most 30; past it the email is
+ # reported not sent and the link is shown to pass on, inside the dashboard's 60 s request.
+ smtp_timeout_seconds: float = Field(default=10.0, gt=0, le=30)
+ # Seconds an invitation link stays valid, from one hour to 30 days: it admits whoever
+ # opens it.
+ invite_ttl_seconds: int = Field(default=7 * 86400, ge=3600, le=30 * 86400)
+
# How callers authenticate: "single-user" (no auth, one anonymous identity),
# "trust-network" (self-signup, first claim wins) or "gateway" (an upstream proxy
# mints short-lived Loom JWTs with the shared HS256 secret; Loom only validates).
@@ -6650,9 +6701,14 @@ class TrackerSettings(BaseModel):
"facts.related": 60,
# One frontier query per hop, up to max_hops.
"facts.traverse": 200,
+ "grants.accept_invite": 150,
"grants.approve": 80,
+ "grants.cancel_invite": 80,
"grants.create": 50,
+ # A mail server's round trip when the invitation is emailed.
+ "grants.invite": 3000,
"grants.list": 80,
+ "grants.list_invites": 80,
"grants.pending_for_me": 150,
"grants.revoke": 80,
"grants.share_agent": 80,
diff --git a/server/transport/mcp_descriptions.py b/server/transport/mcp_descriptions.py
index 5067e2482bc..0be237d7dab 100644
--- a/server/transport/mcp_descriptions.py
+++ b/server/transport/mcp_descriptions.py
@@ -408,10 +408,10 @@ def revision_policy(update: str) -> str:
"default answer to 'what are my workspaces' / 'where can I save "
"this'. Each row has an `is_new` flag — true when someone "
"granted access and the caller hasn't visited yet; surface "
- "those as fresh invitations."
+ "those as newly shared."
),
"namespace.mark_seen": (
- "Acknowledge a new-invitation indicator on a namespace. Call "
+ "Record a visit to a namespace, clearing its new mark. Call "
"after surfacing rows from namespace.list_mine that had "
"is_new=true, so the badge clears on the next list."
),
@@ -468,11 +468,37 @@ def revision_policy(update: str) -> str:
# ---- Grants (per-namespace access control) ----
"grants.create": (
"Grant another subject (user or service-account) viewer / writer "
- "/ admin role on a namespace. Call when an admin wants to invite "
- 'someone or change their role — "add Bob as writer on X", '
- '"give Carol admin on Y". The caller must already be admin on '
- "the target namespace. Lowering someone's current role is refused "
- "(409 GRANT_WOULD_DOWNGRADE) unless replace=true is passed."
+ "/ admin role on a namespace. Call to grant a service account, a group "
+ 'or everyone, or to change the role of a member — "make Carol an admin of Y"; to add a '
+ "person by login handle or email, call grants.invite. The caller must "
+ "already be admin on the target namespace. Lowering someone's current "
+ "role is refused (409 GRANT_WOULD_DOWNGRADE) unless replace=true is passed."
+ ),
+ "grants.invite": (
+ "Give a person a role on a namespace by login handle or email. Call when "
+ 'an admin wants to add someone — "add bob@example.com as writer on X". '
+ "A handle an account or a live grant holds, or an email verified for an "
+ "account, is granted at once; any other email gets "
+ "a single-use invitation link (emailed when the server sends mail) to pass "
+ "on, or, where sign-in is single sign-on only, a grant as typed; any other "
+ "handle is refused. A request with no token, which only auth off serves, "
+ "grants any other handle or email as typed."
+ ),
+ "grants.list_invites": (
+ "List a namespace's open invitations: the address, role, maker and expiry "
+ "of each open link, marked stopped when its maker's grants, account or "
+ "tokens no longer stand behind it, so it admits nobody now; a stopped link "
+ "keeps the name in use until it is cancelled or expires. Caller must be admin."
+ ),
+ "grants.cancel_invite": (
+ "Cancel an open invitation by its invite_id, so its link admits nobody. "
+ "Caller must be admin on the namespace."
+ ),
+ "grants.accept_invite": (
+ "Accept an invitation link as the signed-in person: it grants its role on "
+ "the namespace it names; opened again by its accepter, it answers the role "
+ "they hold while that is at least the invitation's, and 404 as used "
+ "otherwise. Call with the secret from the link's fragment."
),
"grants.list": (
"List active grants on a namespace — who has access, at which "
diff --git a/tests/analyzer/cases/planes.py b/tests/analyzer/cases/planes.py
index c2c8d1ce82c..aed89a10204 100644
--- a/tests/analyzer/cases/planes.py
+++ b/tests/analyzer/cases/planes.py
@@ -178,6 +178,7 @@
{
"namespace_validate",
"grants",
+ "_grants_invites",
"context_offload",
"knowledge",
"_memory_consolidate",
@@ -243,6 +244,7 @@
("_knowledge_reads", "server.knowledge.app.document_reads"),
("_knowledge_dedup", "server.knowledge.app.dedup"),
("grants", "server.identity.app.grants"),
+ ("_grants_invites", "server.identity.app.invites"),
("policy", "server.identity.app.history_policy_ops"),
("learnings", "server.memory.app.learnings"),
("blacklist", "server.memory.app.blacklist"),
@@ -1119,6 +1121,28 @@ async def _grants_repo(ch: RecordingCH, c: dict[str, Any]) -> None:
await grants_repo.member_count(ORG, ["col-a", "col-b"], ch=ch)
+async def _invites_repo(ch: RecordingCH, c: dict[str, Any]) -> None:
+ """The version read every invitation write takes (`grants.invite`, an accept, a cancel)
+ and the maker read a user erasure's grant step takes; the handlers read the rest."""
+ from datetime import UTC, datetime
+
+ from server.identity.domain.invites import Invite
+ from server.identity.store import invites as invites_repo
+
+ made = Invite(
+ org=ORG,
+ namespace=NS,
+ invite_id="0" * 64,
+ email="a@example.com",
+ role="writer",
+ created_by="user:1",
+ created_at=datetime(2026, 1, 1, tzinfo=UTC),
+ expires_at=1_800_000_000,
+ )
+ await invites_repo.put(made, ch=ch)
+ await invites_repo.made_by(ORG, "user:1", ch=ch)
+
+
async def _mentor_evidence(ch: RecordingCH, c: dict[str, Any]) -> None:
"""The evidence ladder `mentor.brief` reads at each brief."""
from server.insights.app import mentor_rules
@@ -1506,6 +1530,15 @@ def cases() -> list[Case]:
)
out.append(Case("profiles", "server.memory.store.profile_sources", _profiles, {}))
out.append(Case("grants_repo", "server.identity.store.grants", _grants_repo, {}))
+ out.append(
+ Case(
+ "invites_repo",
+ "server.identity.store.invites",
+ _invites_repo,
+ {},
+ rows=lambda sql, _p: [{"v": 1}] if "max(version)" in sql else [],
+ )
+ )
out.append(
Case("namespace_in_use", "server.identity.store.namespace_census", _namespace_in_use, {})
)
diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt
index 57b1b6202ff..14a748e4dd2 100644
--- a/tests/analyzer/shapes.txt
+++ b/tests/analyzer/shapes.txt
@@ -580,7 +580,6 @@
3e00482285b2 SELECT count() AS n FROM loom.entity_vectors WHERE org = {org:String} AND namespace = {ns:String}
3e18758b5b32 ALTER TABLE loom.session_outcomes_by_user DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_s
3e2075d7a93f SELECT count() AS n FROM loom.memory_record_fields FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL
-3e2b5291eea1 SELECT ? AS in_use FROM ((SELECT ? FROM loom.namespace_grants FINAL WHERE org = {org:String} AND namespace = {ns:String} AND revoked_at IS NULL AND status = ? LIMIT ?) UNION ALL (SELECT ? FROM loom.me
3e750c517754 SELECT count() AS n FROM loom.memory_chunk_sources FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL
3ea44fb37980 ALTER TABLE loom.session_briefs DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ?
3eb6ce41ac13 SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = {
@@ -641,6 +640,7 @@
447df57d704d SELECT memory_key, toString(memory_id) AS id, version, memory_type, toString(status) AS status, source_class, agent, user_id, session_id, actor, updated_at, sensitivity, org, namespace, redacted_at FR
449f9de84bb3 SELECT * FROM loom.memory_embeddings FINAL PREWHERE org = {org:String} AND namespace = {ns:String} AND agent = {a:String} AND user_id = {u:String} AND session_id = {s:String} AND memory_key = {k:Strin
44a0f92f53ee SELECT pr_number, title, author, files, merged_at, linked_issues, arraySum( arrayMap( (tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {tokens:Array(String)}, {idfs:Array
+44a930ee83bd -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou
44b352c793fc SELECT DISTINCT start_line, end_line, content, kind, scope, symbol_ids, toString(indexed_commit) AS indexed_commit FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND
44be9faca8dd SELECT pr_number, title, author, merged_at, files, linked_issues, (match(title, {revert_re:String}) OR positionCaseInsensitive(body_excerpt, ?) > ? ) AS is_revert FROM loom.code_pr_history FINAL WHERE
44fe95e059ce ALTER TABLE loom.blob_uploads DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ?
@@ -704,7 +704,6 @@
4a4a4fc0989b ALTER TABLE loom.knowledge_ingest_cancels DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_s
4a536b32504b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_
4aeabb5d4edf SELECT count() AS n FROM loom.namespace_guides WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ?
-4b1fc95c4fbf -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou
4b25bd59f082 SELECT DISTINCT org, namespace, name, source_id, source_kind, owner_subject, connection_id FROM loom.knowledge_sources WHERE credential_mode = ? AND NOT (source_kind = ? OR kind = ? OR credential_mode
4b65a7bc66f1 SELECT count() AS n FROM loom.memory_records FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String}
4ba366a556c0 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
@@ -922,6 +921,7 @@
60db158b1832 SELECT count() AS n FROM loom.knowledge_source_listings WHERE org = {org:String} AND namespace = {ns:String} AND ?
60e599ddc650 SELECT source AS consumer_key, count() AS outcome_rows, countIf(action IN (?, ?)) AS outcome_positive, countIf(action IN (?, ?)) AS outcome_negative, countIf(action IN (?, ?)) AS shunt_rows, sum(token
60fbc5932a73 SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory WHERE tombstoned_at IS NULL AND sensitivity = ? AND (expires_at IS NULL OR expires_at > now()) AND (match(value,
+6110e05506bd SELECT org, namespace, invite_id, email, role, created_by, created_at, expires_at, state, accepted_by FROM loom.namespace_invites FINAL WHERE org = {org:String} AND namespace = {ns:String} AND invite_
611a33ab3983 ALTER TABLE loom.llm_response_cache DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ?
612ce0b0b345 SELECT c.category_id AS category_id, count() AS rows FROM (SELECT memory_key, category_id FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NU
61589fe302c8 SELECT count() AS n FROM loom.memory_exposures WHERE org = {org:String} AND user_id = {uid:String} AND ?
@@ -950,6 +950,7 @@
63c18bd2b0f9 SELECT count() AS n FROM loom.task_events WHERE org = {org:String} AND user_id = {uid:String}
63cdeebcb8df SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to
63fb69659b81 SELECT pr_number, merge_commit_sha, pack, pack_tokens, created_at FROM loom.code_context_packs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND pr_number = {pr:UInt32} AND tombstoned_at
+640e8c5c2a21 SELECT org, namespace, invite_id, email, role, created_by, created_at, expires_at, state, accepted_by FROM loom.namespace_invites FINAL WHERE org = {org:String} AND namespace = {ns:String} AND state =
641af70c0e23 ALTER TABLE loom.task_events DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ?
64280912c4ea SELECT memory_key, toString(memory_id) AS id, version, memory_type, toString(status) AS status, source_class, agent, user_id, session_id, actor, updated_at, sensitivity, org, namespace, redacted_at FR
642df47c9bb7 SELECT count() AS n FROM loom.memory_reinforcement WHERE org = {org:String} AND namespace IN {ns:Array(String)}
@@ -967,6 +968,7 @@
64c84281ac98 SELECT count() AS n FROM loom.datasets WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ?
64dc469b5155 SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER
6534ce8bc70f SELECT count() AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND has(tags, ?) AND hasAny(tags, {src:Array(String)}) AND hasAny(arrayMap(t -> (namespace, t), tags), {pairs:Array(Tuple
+657c5b6c5b97 SELECT greatest(toUInt64(toUnixTimestamp64Nano(now64(?))), max(version) + ?) AS v FROM loom.namespace_invites WHERE org = {k0:String} AND namespace = {k1:String} AND invite_id = {k2:String}
658d1794d1b8 ALTER TABLE loom.knowledge_ingestions DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ?
659e2ff307fc SELECT f.indexed_commit AS commit, count() AS files, max(f.created_at) AS ingested_at, any(ifNull(p.pr_number, ?)) AS pr_number FROM ( SELECT indexed_commit, created_at FROM loom.code_files FINAL WHER
65aa1f17328b SELECT count() AS n FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)}
@@ -1153,6 +1155,7 @@
79af77cb3b0b ALTER TABLE loom.derived_facts DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ?
79b7b807206a SELECT count() AS n, max(computed_at) AS newest_at FROM loom.code_unit_risk FINAL WHERE org = {org:String} AND namespace = {ns:String}
79ccf3419673 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND status = ? AND startsWith(memory_key, {p:String}) AND hasAny(tags, {tags:A
+79eb1c4cc46e SELECT org, namespace, invite_id, email, role, created_by, created_at, expires_at, state, accepted_by FROM loom.namespace_invites FINAL WHERE org = {org:String} AND created_by = {maker:String}
79ec8e98cd5d SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER
7a102674981e SELECT count() AS n FROM loom.query_history_sources WHERE org = {org:String} AND namespace IN {ns:Array(String)}
7a4159a961af SELECT id, org, scope_type, scope_value, requester, actor, urgency, purge, mirror_marked, attempts, steps_completed, requested_at, failure_reason, residue_count, residue, verified_at, census FROM loom
@@ -1401,6 +1404,7 @@
90779505e93e SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_
9121adbb70ab ALTER TABLE loom.memory_embeddings UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_m
914e48c84bc1 SELECT count() AS n FROM loom.connected_accounts WHERE ?
+918e152d9ce9 SELECT owner_email FROM loom.namespaces FINAL WHERE org = {org:String} AND active AND lower(owner_email) = lower({sub:String}) ORDER BY owner_email LIMIT ?
919b26f50c2c SELECT count() AS n FROM loom.delete_version_checks WHERE org = {org:String} AND namespace = {ns:String}
91a5c9a0b15e ALTER TABLE loom.memory_versions UPDATE value = ?, value_json = ?, evidence = ?, entities = [], concepts = [], redacted_at = {ts:DateTime}, redaction_reason = {rb:String} WHERE org = {org:String} AND
91c2100096c0 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
@@ -1431,6 +1435,7 @@
93c2557ad9b9 ALTER TABLE loom.stewardship_events DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync =
93ec8d6c0770 SELECT run_id, toString(memory_id) AS mid, event_type, credited_at, actor, agent, consumer, sum(event_count) AS net, count() AS n FROM loom.memory_usage_events WHERE org = {org:String} AND namespace =
93fb8239f3f5 SELECT count() AS n FROM loom.memory_record_fields FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}
+9454d42e8f4e SELECT ? AS in_use FROM ((SELECT ? FROM loom.namespace_grants FINAL WHERE org = {org:String} AND namespace = {ns:String} AND revoked_at IS NULL AND status = ? LIMIT ?) UNION ALL (SELECT ? FROM loom.na
945db02b838d SELECT count() AS n FROM loom.session_brief_revisions WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ?
946786a56b8c SELECT agent, user_id, session_id, memory_key FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND startsWith(source_trace, {trace:String}) AND (ag
9476186d6a8c SELECT c.category_id AS category_id, count() AS rows FROM (SELECT memory_key, category_id FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NU
@@ -2231,6 +2236,7 @@ df5c577c685a SELECT sid, argMin(content_hash, start_line) AS h FROM ( SELECT arr
df62986ef9b7 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
df875c426404 SELECT count() AS n FROM loom.memory_ask_precedents WHERE org = {org:String} AND namespace IN {ns:Array(String)}
df886269fbb5 SELECT org, namespace FROM loom.namespace_grants FINAL WHERE role = ? AND revoked_at IS NULL AND status = ? AND (org, namespace) IN {keys:Array(Tuple(String, String))} GROUP BY org, namespace
+df95e8727da8 SELECT subject FROM loom.namespace_grants FINAL WHERE org = {org:String} AND lower(subject) = lower({sub:String}) AND revoked_at IS NULL AND status = ? ORDER BY subject LIMIT ?
df9a592b3176 SELECT min(version) AS v FROM loom.memory_versions WHERE org = {org:String} AND namespace = {ns:String}
dfab46389b75 SELECT count() AS n FROM loom.memory_record_versions WHERE org = {org:String} AND namespace = {ns:String} AND ?
dfb389c3eaaa SELECT count() AS n FROM loom.memory_records FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL
diff --git a/tests/conftest.py b/tests/conftest.py
index c74aba61ab6..e21099f07b7 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -225,8 +225,9 @@ def pytest_sessionstart(session: pytest.Session) -> None:
@pytest.fixture
def mint_test_token():
- """A callable minting a service-account JWT for the test's own org, for
- tests that construct `Agent(...)` with their own identity:
+ """A callable minting a JWT for the test's own org (a service account's unless
+ `is_service_account=False`, a person's), for tests that construct `Agent(...)`
+ with their own identity:
tok = mint_test_token(org="my-test-org", namespaces=["*"])
async with Agent(org="my-test-org", ..., api_key=tok) as a: ...
@@ -242,6 +243,7 @@ def _mint(
subject: str = "test-suite",
read_user_id: str | None = None,
read_scope: str | None = None,
+ is_service_account: bool = True,
) -> str:
return mint_token(
subject=subject,
@@ -249,7 +251,7 @@ def _mint(
namespaces=namespaces or ["*"],
roles=roles or ["writer"],
ttl_seconds=ttl_seconds,
- is_service_account=True,
+ is_service_account=is_service_account,
read_user_id=read_user_id,
read_scope=read_scope,
)
diff --git a/tests/integration/test_grants_invite.py b/tests/integration/test_grants_invite.py
new file mode 100644
index 00000000000..c86ff8020b7
--- /dev/null
+++ b/tests/integration/test_grants_invite.py
@@ -0,0 +1,237 @@
+"""An admin invites a person by an email no account holds; the person, signed in under
+another login handle, accepts the link once and holds the role under that handle,
+granted by the admin. Runs against a real Control Plane + ClickHouse (LOOM_BASE_URL,
+LOOM_CH_*)."""
+
+from __future__ import annotations
+
+import uuid
+from typing import Any
+from urllib.parse import parse_qs, urlsplit
+
+import httpx
+
+from tests.integration._resources import unique_org
+
+
+def _post(base: str, token: str, op: str, payload: dict) -> httpx.Response:
+ with httpx.Client(base_url=base, timeout=30.0) as c:
+ return c.post(f"/v1/{op}", json=payload, headers={"Authorization": f"Bearer {token}"})
+
+
+def _register(base: str, token: str, org: str, namespace: str, owner: str) -> None:
+ body = {"org": org, "namespace": namespace, "owner_email": owner}
+ r = _post(base, token, "namespace.register", body)
+ assert r.status_code == 200, r.text
+
+
+def test_an_invited_email_is_accepted_once_under_the_accepters_handle(
+ control_plane_url: str, mint_test_token: Any
+) -> None:
+ org = unique_org("invite")
+ ns = f"ns-{uuid.uuid4().hex[:8]}"
+ admin = mint_test_token(
+ is_service_account=False, org=org, subject="ann-admin", namespaces=[ns], roles=["admin"]
+ )
+ _register(control_plane_url, admin, org, ns, "ann-admin")
+
+ r = _post(
+ control_plane_url,
+ admin,
+ "grants.invite",
+ {"org": org, "namespace": ns, "to": "robin@example.com", "role": "writer"},
+ )
+ assert r.status_code == 200, r.text
+ made = r.json()
+ assert made["outcome"] == "invited"
+ secret = parse_qs(urlsplit(made["link_path"]).fragment)["invite"][0]
+ listed = _post(control_plane_url, admin, "grants.list_invites", {"org": org, "namespace": ns})
+ assert [row["email"] for row in listed.json()["rows"]] == ["robin@example.com"]
+
+ # The person signs in under a handle that is not the email.
+ person = mint_test_token(
+ is_service_account=False,
+ org=org,
+ subject="robin",
+ namespaces=[f"home-{ns}"],
+ roles=["viewer"],
+ )
+ body = {"org": org, "namespace": ns, "secret": secret}
+ r = _post(control_plane_url, person, "grants.accept_invite", body)
+ assert r.status_code == 200, r.text
+ assert r.json() == {"namespace": ns, "role": "writer"}
+
+ grants = _post(control_plane_url, admin, "grants.list", {"org": org, "namespace": ns})
+ mine = [g for g in grants.json()["rows"] if g["subject"] == "robin"]
+ assert [(g["role"], g["granted_by"]) for g in mine] == [("writer", "ann-admin")]
+
+ # Its accepter opening it again (a lost reply) is answered the role held.
+ r = _post(control_plane_url, person, "grants.accept_invite", body)
+ assert (r.status_code, r.json()) == (200, {"namespace": ns, "role": "writer"}), r.text
+
+ # Spent: a second open of the link admits nobody, and it is no longer listed.
+ other = mint_test_token(
+ is_service_account=False,
+ org=org,
+ subject="someone",
+ namespaces=[f"x-{ns}"],
+ roles=["viewer"],
+ )
+ again = _post(control_plane_url, other, "grants.accept_invite", body)
+ assert again.status_code == 404, again.text
+ listed = _post(control_plane_url, admin, "grants.list_invites", {"org": org, "namespace": ns})
+ assert listed.json()["rows"] == []
+
+
+def test_a_handle_no_account_holds_is_refused(control_plane_url: str, mint_test_token: Any) -> None:
+ org = unique_org("invite")
+ ns = f"ns-{uuid.uuid4().hex[:8]}"
+ admin = mint_test_token(
+ is_service_account=False, org=org, subject="ann-admin", namespaces=[ns], roles=["admin"]
+ )
+ _register(control_plane_url, admin, org, ns, "ann-admin")
+ r = _post(
+ control_plane_url,
+ admin,
+ "grants.invite",
+ {"org": org, "namespace": ns, "to": "no-such-handle", "role": "viewer"},
+ )
+ assert r.status_code == 404, r.text
+ grants = _post(control_plane_url, admin, "grants.list", {"org": org, "namespace": ns})
+ assert all(g["subject"] != "no-such-handle" for g in grants.json()["rows"])
+
+
+def test_a_handle_an_account_signs_in_as_is_granted_at_once(
+ control_plane_url: str, mint_test_token: Any
+) -> None:
+ org = unique_org("invite")
+ ns = f"ns-{uuid.uuid4().hex[:8]}"
+ home = f"home-{ns}"
+ person = mint_test_token(
+ is_service_account=False, org=org, subject="robin", namespaces=[home], roles=["admin"]
+ )
+ _register(control_plane_url, person, org, home, "robin")
+ admin = mint_test_token(
+ is_service_account=False, org=org, subject="ann-admin", namespaces=[ns], roles=["admin"]
+ )
+ _register(control_plane_url, admin, org, ns, "ann-admin")
+ r = _post(
+ control_plane_url,
+ admin,
+ "grants.invite",
+ {"org": org, "namespace": ns, "to": "Robin", "role": "viewer"},
+ )
+ assert r.status_code == 200, r.text
+ assert (r.json()["outcome"], r.json()["subject"], r.json()["link_path"]) == (
+ "granted",
+ "robin",
+ "",
+ )
+
+
+def test_a_handle_a_grant_names_is_held_and_an_email_a_row_names_is_not(
+ control_plane_url: str, mint_test_token: Any
+) -> None:
+ """A grant under a handle is a person the org knows; an email a row's owner or a
+ grant names is whatever its writer typed, so it still gets a link."""
+ org = unique_org("invite")
+ ns, other = f"ns-{uuid.uuid4().hex[:8]}", f"ops-{uuid.uuid4().hex[:8]}"
+ admin = mint_test_token(
+ is_service_account=False,
+ org=org,
+ subject="ann-admin",
+ namespaces=[ns, other],
+ roles=["admin"],
+ )
+ _register(control_plane_url, admin, org, ns, "ann-admin")
+ _register(control_plane_url, admin, org, other, "platform@acme.example")
+ body = {"org": org, "namespace": other, "subject": "Dana-Ext", "role": "viewer"}
+ assert _post(control_plane_url, admin, "grants.create", body).status_code == 200
+
+ def _to(to: str) -> dict:
+ body = {"org": org, "namespace": ns, "to": to, "role": "viewer"}
+ r = _post(control_plane_url, admin, "grants.invite", body)
+ assert r.status_code == 200, r.text
+ return r.json()
+
+ held = _to("dana-ext")
+ assert (held["outcome"], held["subject"]) == ("granted", "Dana-Ext")
+ assert _to("platform@acme.example")["outcome"] == "invited"
+
+
+def _invite(base: str, token: str, org: str, ns: str, to: str) -> tuple[str, str]:
+ r = _post(
+ base, token, "grants.invite", {"org": org, "namespace": ns, "to": to, "role": "writer"}
+ )
+ assert r.status_code == 200, r.text
+ made = r.json()
+ return made["invite_id"], parse_qs(urlsplit(made["link_path"]).fragment)["invite"][0]
+
+
+def test_a_cancelled_link_is_unlisted_and_admits_nobody(
+ control_plane_url: str, mint_test_token: Any
+) -> None:
+ org = unique_org("invite")
+ ns = f"ns-{uuid.uuid4().hex[:8]}"
+ admin = mint_test_token(
+ is_service_account=False, org=org, subject="ann-admin", namespaces=[ns], roles=["admin"]
+ )
+ _register(control_plane_url, admin, org, ns, "ann-admin")
+ invite_id, secret = _invite(control_plane_url, admin, org, ns, "robin@example.com")
+
+ body = {"org": org, "namespace": ns, "invite_id": invite_id}
+ r = _post(control_plane_url, admin, "grants.cancel_invite", body)
+ assert (r.status_code, r.json()) == (200, {"cancelled": True}), r.text
+ listed = _post(control_plane_url, admin, "grants.list_invites", {"org": org, "namespace": ns})
+ assert listed.json()["rows"] == []
+ person = mint_test_token(
+ is_service_account=False,
+ org=org,
+ subject="robin",
+ namespaces=[f"home-{ns}"],
+ roles=["viewer"],
+ )
+ accept = {"org": org, "namespace": ns, "secret": secret}
+ assert _post(control_plane_url, person, "grants.accept_invite", accept).status_code == 404
+
+
+def test_a_link_stops_when_its_maker_loses_admin(
+ control_plane_url: str, mint_test_token: Any
+) -> None:
+ org = unique_org("invite")
+ ns = f"ns-{uuid.uuid4().hex[:8]}"
+ ann = mint_test_token(
+ is_service_account=False, org=org, subject="ann-admin", namespaces=[ns], roles=["admin"]
+ )
+ _register(control_plane_url, ann, org, ns, "ann-admin") # ann's admin role is a grant
+ invite_id, secret = _invite(control_plane_url, ann, org, ns, "robin@example.com")
+
+ # Another admin stays, so ann's grant can go.
+ grant = {"org": org, "namespace": ns, "subject": "bea-admin", "role": "admin"}
+ assert _post(control_plane_url, ann, "grants.create", grant).status_code == 200
+ bea = mint_test_token(
+ is_service_account=False, org=org, subject="bea-admin", namespaces=[ns], roles=["admin"]
+ )
+ revoke = {"org": org, "namespace": ns, "subject": "ann-admin"}
+ r = _post(control_plane_url, bea, "grants.revoke", revoke)
+ assert r.status_code == 200 and r.json()["revoked"] is True, r.text
+
+ person = mint_test_token(
+ is_service_account=False,
+ org=org,
+ subject="robin",
+ namespaces=[f"home-{ns}"],
+ roles=["viewer"],
+ )
+ accept = {"org": org, "namespace": ns, "secret": secret}
+ r = _post(control_plane_url, person, "grants.accept_invite", accept)
+ assert r.status_code == 404, r.text
+
+ # Stopped by its maker, not used or expired: listed as stopped, for another admin to
+ # cancel.
+ scope = {"org": org, "namespace": ns}
+ r = _post(control_plane_url, bea, "grants.list_invites", scope)
+ assert r.status_code == 200, r.text
+ assert [(x["invite_id"], x["stopped"]) for x in r.json()["rows"]] == [(invite_id, True)]
+ r = _post(control_plane_url, bea, "grants.cancel_invite", {**scope, "invite_id": invite_id})
+ assert r.status_code == 200 and r.json()["cancelled"] is True, r.text
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
index 2d0aecdb695..5b7d746c0d7 100644
--- a/tests/unit/conftest.py
+++ b/tests/unit/conftest.py
@@ -314,8 +314,15 @@ def _settings_left_as_found() -> Iterator[None]:
# pytest rewrites this for every phase; it is not a test's state.
_PYTEST_ENV = frozenset({"PYTEST_CURRENT_TEST"})
# The session loop's default executor threads and the process-wide pools (the document
-# bucket's, the blacklist matchers', the PR overlay's parses) outlive every test by design.
-_SHARED_THREAD_PREFIXES = ("asyncio_", "loom-object-store", "loom-blacklist", "loom-overlay-parse")
+# bucket's, the blacklist matchers', the PR overlay's parses, the invitation mail's sends)
+# outlive every test by design.
+_SHARED_THREAD_PREFIXES = (
+ "asyncio_",
+ "loom-object-store",
+ "loom-blacklist",
+ "loom-overlay-parse",
+ "loom-invite-mail",
+)
_THREAD_JOIN_SECONDS = 2.0
diff --git a/tests/unit/snapshots/sdk_public_api.json b/tests/unit/snapshots/sdk_public_api.json
index 2d2cf3ffae0..07b1d05224d 100644
--- a/tests/unit/snapshots/sdk_public_api.json
+++ b/tests/unit/snapshots/sdk_public_api.json
@@ -792,18 +792,34 @@
"grants": {
"class": "GrantsOps",
"methods": {
+ "accept_invite": [
+ "body",
+ "options"
+ ],
"approve": [
"body",
"options"
],
+ "cancel_invite": [
+ "body",
+ "options"
+ ],
"create": [
"body",
"options"
],
+ "invite": [
+ "body",
+ "options"
+ ],
"list": [
"body",
"options"
],
+ "list_invites": [
+ "body",
+ "options"
+ ],
"pending_for_me": [
"body",
"options"
diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json
index 197e5ab9e5b..1ee55f35520 100644
--- a/tests/unit/snapshots/settings_defaults.json
+++ b/tests/unit/snapshots/settings_defaults.json
@@ -590,6 +590,7 @@
"inference_workload_token_mode": "exchange",
"insights_agents_connected_ttl_s": 60.0,
"instance_heartbeat_seconds": 10.0,
+ "invite_ttl_seconds": 604800,
"jwt_audience": "loom-platform",
"jwt_end_user_issuers_json": "",
"jwt_end_user_jwks_refresh_seconds": 300.0,
@@ -725,6 +726,7 @@
"local_llm_base_url": "http://localhost:11434/v1",
"log_format": "text",
"log_level": "info",
+ "mail_from": "",
"max_request_bytes": 33554432,
"mcp_always_load_tools": "code.search,code.symbol",
"mcp_auth_mode": "required",
@@ -1221,6 +1223,7 @@
"session_brief_max_windows": 4,
"session_brief_window_chars": 24000,
"shutdown_ready_delay_s": 15.0,
+ "smtp_timeout_seconds": 10.0,
"storage_authority": "clickhouse",
"storage_frontend_assets_retry_max_s": 60.0,
"storage_frontend_assets_retry_s": 2.0,
diff --git a/tests/unit/test_agent_shares.py b/tests/unit/test_agent_shares.py
index 3b463ae6424..2f8fe050471 100644
--- a/tests/unit/test_agent_shares.py
+++ b/tests/unit/test_agent_shares.py
@@ -380,7 +380,7 @@ async def insert_row(row: Any, **kw: Any) -> None:
monkeypatch.setattr(grants_app.grants_repo, "find_active_grant", find_active_grant)
monkeypatch.setattr(grants_app.grants_repo, "insert_row", insert_row)
monkeypatch.setattr(grants_app, "grant_change", lambda *a: _Claim())
- monkeypatch.setattr(grants_app, "_enforce_code_ceiling", no_ceiling)
+ monkeypatch.setattr(grants_app, "enforce_code_ceiling", no_ceiling)
monkeypatch.setattr(aliases, "canonical_subject", canonical)
check = agent_shares._made_by("sa:fleet:a", "sa:fleet:b", "fleet-a")
body = GrantsCreateInput(org="acme", namespace="fleet-a", subject="sa:fleet:b", role=role)
diff --git a/tests/unit/test_aliases_verified_email_sql.py b/tests/unit/test_aliases_verified_email_sql.py
index 136423636a2..d35aede59ae 100644
--- a/tests/unit/test_aliases_verified_email_sql.py
+++ b/tests/unit/test_aliases_verified_email_sql.py
@@ -267,6 +267,30 @@ async def test_an_address_is_held_by_a_verified_account_or_a_handle_that_is_it(
assert (await aliases.verified_tie(ORG, address))[1] is held
+@pytest.mark.asyncio
+async def test_the_verified_owner_is_the_accounts_handle_as_stored(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # An SSO account signing in as an address, its verified contact another; a
+ # namespace registered naming that contact as its owner holds no verified email.
+ client = _CH(
+ *SETUP,
+ "INSERT INTO loom.namespaces (org, namespace, owner_email, contact_email,"
+ " password_hash, active, created_at, updated_at) VALUES"
+ f" ('{ORG}', 'hana', 'Hana@Corp.Example', 'hana.home@x.example', '', 1, now(), now()),"
+ f" ('{ORG}', 'hana-home', 'hana.home@x.example', '', '', 1, now(), now()),"
+ # A second SSO account for carol's address, its handle an email.
+ f" ('{ORG}', 'a-carol', 'a.carol@corp.example', 'carol@corp.example', '', 1, now(),"
+ " now())",
+ )
+ monkeypatch.setattr("server.core.ch.get_client", lambda: client)
+ for typed in ("Hana.Home@X.Example", "hana@corp.example"):
+ assert await aliases.verified_owner(ORG, typed) == "Hana@Corp.Example"
+ # A handle that is no email first, as canonical_subject picks.
+ assert await aliases.verified_owner(ORG, "carol@corp.example") == "u-carol"
+ assert await aliases.verified_owner(ORG, "bob@corp.example") is None # unverified
+
+
@pytest.mark.asyncio
async def test_revoking_an_address_whose_handle_is_it_leaves_a_squatters_row_and_tokens(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
diff --git a/tests/unit/test_audit_subject_credentials.py b/tests/unit/test_audit_subject_credentials.py
index 9d3bc2d607d..cc60a3e25d1 100644
--- a/tests/unit/test_audit_subject_credentials.py
+++ b/tests/unit/test_audit_subject_credentials.py
@@ -131,6 +131,38 @@ def test_code_repo_add_audits_what_was_registered_not_what_was_asked() -> None:
assert subject["authenticated"] is False
+def test_grants_accept_invite_audits_the_invitation_by_its_hash() -> None:
+ from server.identity.api.models_grants import GrantsAcceptInviteInput
+ from server.identity.domain.invites import invite_id
+
+ accept = GrantsAcceptInviteInput(org="acme", namespace="team", secret=SECRET)
+ subject = _subject("grants.accept_invite", accept, {"namespace": "team", "role": "writer"})
+ _assert_no_credential(subject)
+ assert subject == {
+ "org": "acme",
+ "namespace": "team",
+ "invite_id": invite_id(SECRET),
+ "role": "writer",
+ }
+
+
+def test_grants_invite_audits_who_got_the_role_never_the_address() -> None:
+ from server.identity.api.models_grants import GrantsInviteInput
+
+ asked = GrantsInviteInput(org="acme", namespace="team", to="m@example.com", role="writer")
+ granted = {"outcome": "granted", "role": "writer", "subject": "robin"}
+ assert _subject("grants.invite", asked, granted) == {
+ "org": "acme",
+ "namespace": "team",
+ "role": "writer",
+ "outcome": "granted",
+ "subject": "robin",
+ }
+ invited = {"outcome": "invited", "role": "writer", "subject": "", "invite_id": "h"}
+ subject = _subject("grants.invite", asked, invited)
+ assert subject["invite_id"] == "h" and "m@example.com" not in json.dumps(subject)
+
+
def test_the_matcher_tells_credentials_from_lookalikes() -> None:
for name in (
"password",
diff --git a/tests/unit/test_auth_aliases.py b/tests/unit/test_auth_aliases.py
index b3eaa4f7bde..383f2d94474 100644
--- a/tests/unit/test_auth_aliases.py
+++ b/tests/unit/test_auth_aliases.py
@@ -93,7 +93,7 @@ async def _insert(row: dict, **_k) -> None:
monkeypatch.setattr(grants_repo, "find_active_grant", _none)
monkeypatch.setattr(grants_repo, "insert_row", _insert)
- monkeypatch.setattr(grants_mod, "_enforce_code_ceiling", _none)
+ monkeypatch.setattr(grants_mod, "enforce_code_ceiling", _none)
monkeypatch.setattr("server.core.ch.get_client", lambda: _ch([])) # released: nothing tied
al._CACHE[("acme", "alice@acme.io")] = (time.monotonic(), ("alice@acme.io", "alice"))
await grants_mod.handle_grants_create(
diff --git a/tests/unit/test_auth_models_hide_credentials.py b/tests/unit/test_auth_models_hide_credentials.py
index f424e8f708c..39fe342e853 100644
--- a/tests/unit/test_auth_models_hide_credentials.py
+++ b/tests/unit/test_auth_models_hide_credentials.py
@@ -1,6 +1,6 @@
-"""The sign-in and sign-up models keep their credentials out of `repr`, so a
-model that reaches a log line or a traceback never prints a password, a
-token or a claim code; the wire shape is unchanged."""
+"""The sign-in, sign-up and invitation models keep their credentials out of `repr`, so
+a model that reaches a log line or a traceback never prints a password, a token, a claim
+code or an invitation's secret; the wire shape is unchanged."""
from __future__ import annotations
@@ -8,6 +8,7 @@
from server.auth.login import LoginInput, LoginOutput
from server.auth.self_signup import AgentSignupOutput, SelfSignupInput, SelfSignupOutput
+from server.identity.api.models_grants import GrantsAcceptInviteInput, GrantsInviteOutput
_CANARY = "canary-credential-0123456789"
@@ -28,6 +29,10 @@ def test_credentials_stay_out_of_repr_and_in_the_payload() -> None:
claim_code=_CANARY + "-code",
claim_url="https://loom.example/",
),
+ # An invitation's secret admits whoever holds it, and the link carries it.
+ GrantsAcceptInviteInput(org="o", namespace="n", secret=_CANARY),
+ GrantsInviteOutput(outcome="invited", role="writer", link_path=_CANARY),
+ GrantsInviteOutput(outcome="invited", role="writer", url=_CANARY),
]
for m in models:
assert _CANARY not in repr(m) and _CANARY not in str(m), type(m).__name__
diff --git a/tests/unit/test_cell_scan_tables.py b/tests/unit/test_cell_scan_tables.py
index 66a90d79c5a..e55608ccf4c 100644
--- a/tests/unit/test_cell_scan_tables.py
+++ b/tests/unit/test_cell_scan_tables.py
@@ -142,6 +142,7 @@
"loom.memory_webhooks",
"loom.namespace_calibration_result",
"loom.namespace_grants",
+ "loom.namespace_invites",
"loom.namespace_guides",
"loom.namespace_ontology",
"loom.namespace_policies",
diff --git a/tests/unit/test_erasure_audit_actor.py b/tests/unit/test_erasure_audit_actor.py
index 966895508a8..ff622a3fab3 100644
--- a/tests/unit/test_erasure_audit_actor.py
+++ b/tests/unit/test_erasure_audit_actor.py
@@ -137,7 +137,7 @@ async def test_a_tokenless_resume_of_a_user_saga_names_the_ledgers_actor(
"""The real user saga resumed without a token: `erasure.completed` names the
ledger's actor, else the resuming process (the CLI's pipeline actor, or the
worker)."""
- from server.identity.app import grants
+ from server.identity.app import grants, invites
_, audits, _ = recorded
@@ -149,6 +149,7 @@ async def _none(*a: Any, **kw: Any) -> None:
monkeypatch.setattr(grants, "revoke_subject", _revoke)
monkeypatch.setattr(grants, "forget_granter", _none)
+ monkeypatch.setattr(invites, "forget_maker", _none)
set_current_auth(None)
with pipeline_actor(outer):
await saga.run_saga(**_resume_args(stored))
diff --git a/tests/unit/test_grant_claims.py b/tests/unit/test_grant_claims.py
index d24e3c90ecf..6512c955dab 100644
--- a/tests/unit/test_grant_claims.py
+++ b/tests/unit/test_grant_claims.py
@@ -180,7 +180,7 @@ async def _nothing(*_a: Any, **_k: Any) -> None:
monkeypatch.setattr(grants_repo, "find_active_grant", _active)
monkeypatch.setattr(grants_repo, "insert_row", _insert)
monkeypatch.setattr("server.auth.aliases.canonical_subject", _same)
- monkeypatch.setattr(grants_app, "_enforce_code_ceiling", _nothing)
+ monkeypatch.setattr(grants_app, "enforce_code_ceiling", _nothing)
monkeypatch.setattr("server.code.app.index.maintainers.sync_quietly", _nothing)
async def _promote() -> None:
@@ -280,7 +280,7 @@ async def _nothing(*_a: Any, **_k: Any) -> None:
):
monkeypatch.setattr(grants_repo, name, fake)
monkeypatch.setattr("server.auth.aliases.canonical_subject", _same)
- monkeypatch.setattr(grants_app, "_enforce_code_ceiling", _nothing)
+ monkeypatch.setattr(grants_app, "enforce_code_ceiling", _nothing)
return gone
diff --git a/tests/unit/test_grants_create_downgrade.py b/tests/unit/test_grants_create_downgrade.py
index 541a8e64db2..dee8287b3d6 100644
--- a/tests/unit/test_grants_create_downgrade.py
+++ b/tests/unit/test_grants_create_downgrade.py
@@ -44,7 +44,7 @@ async def _no_ceiling(*_a: Any, **_k: Any) -> None:
monkeypatch.setattr(grants_repo, "find_active_grant", _find)
monkeypatch.setattr(grants_repo, "find_any_grant", _find)
monkeypatch.setattr(grants_repo, "insert_row", _insert)
- monkeypatch.setattr(grants_mod, "_enforce_code_ceiling", _no_ceiling)
+ monkeypatch.setattr(grants_mod, "enforce_code_ceiling", _no_ceiling)
return inserted, looked_up
diff --git a/tests/unit/test_grants_create_stamps_granter.py b/tests/unit/test_grants_create_stamps_granter.py
index d04fda0da41..ef9864495e8 100644
--- a/tests/unit/test_grants_create_stamps_granter.py
+++ b/tests/unit/test_grants_create_stamps_granter.py
@@ -32,11 +32,12 @@ async def _no_ceiling(*_a: Any, **_k: Any) -> None:
return None
async def _canonical(org: str, subject: str) -> str:
- return subject
+ # As an account that verified bob@x.example.
+ return "bob" if subject == "bob@x.example" else subject
monkeypatch.setattr(grants_repo, "find_active_grant", _find)
monkeypatch.setattr(grants_repo, "insert_row", _insert)
- monkeypatch.setattr(grants_mod, "_enforce_code_ceiling", _no_ceiling)
+ monkeypatch.setattr(grants_mod, "enforce_code_ceiling", _no_ceiling)
monkeypatch.setattr("server.auth.aliases.canonical_subject", _canonical)
yield rows
set_current_auth(None)
@@ -64,6 +65,33 @@ async def test_the_authenticated_caller_is_the_granter(inserted: list[dict[str,
assert [r["granted_by"] for r in inserted] == ["carol", "carol"]
+@pytest.mark.asyncio
+async def test_an_accepted_invitation_is_granted_by_its_maker(
+ inserted: list[dict[str, Any]],
+) -> None:
+ """The accepter signs in and calls; the row names the invitation's maker."""
+ set_current_auth(
+ AuthInfo(
+ subject="bob",
+ org="o",
+ namespaces=("home",),
+ roles=(Role.VIEWER,),
+ is_service_account=False,
+ )
+ )
+ await grants_mod.store_grant(_create(granted_by="the-ceo"), issuer="ann")
+ assert [(r["subject"], r["granted_by"]) for r in inserted] == [("bob", "ann")]
+
+
+@pytest.mark.asyncio
+async def test_store_grant_answers_the_subject_it_wrote(inserted: list[dict[str, Any]]) -> None:
+ """A verified email is written under its account's handle, and named so."""
+ _, stored = await grants_mod.store_grant(_create(subject="bob@x.example"))
+ assert stored == inserted[0]["subject"] == "bob"
+ out = await grants_mod.create_grant(_create(subject="bob@x.example"))
+ assert out.subject == "bob@x.example" # `grants.create` answers as typed
+
+
@pytest.mark.asyncio
async def test_auth_off_keeps_the_body_value(inserted: list[dict[str, Any]]) -> None:
set_current_auth(None)
diff --git a/tests/unit/test_grants_invite.py b/tests/unit/test_grants_invite.py
new file mode 100644
index 00000000000..2074c2a6651
--- /dev/null
+++ b/tests/unit/test_grants_invite.py
@@ -0,0 +1,1401 @@
+"""grants.invite gives a person a role by their handle or email: a grant when an account
+or a live grant holds it, an invitation link for an email no account holds, and a refusal
+for a handle neither holds; with no token, as auth off serves, those are granted as typed.
+grants.accept_invite spends a link once, for the signed-in person, stamped as granted by
+the invitation's maker; a failed grant leaves it open."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import smtplib
+import threading
+import time
+from collections import Counter
+from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
+from dataclasses import replace
+from datetime import UTC, datetime
+from typing import Any, ClassVar
+from urllib.parse import parse_qs, urlsplit
+
+import anyio
+import pytest
+
+from server.auth import aliases, fail_closed, revocation
+from server.auth.context import set_current_auth
+from server.auth.jwt import AuthInfo
+from server.core.ch import own_write_reads, sequential_reads_active
+from server.core.errors import (
+ BackendUnavailableError,
+ GrantWouldDowngradeError,
+ IdentityIncompleteError,
+ NotFoundError,
+ ValidationError,
+)
+from server.identity.api.models_grants import (
+ GrantsAcceptInviteInput,
+ GrantsCancelInviteInput,
+ GrantsCreateInput,
+ GrantsInviteInput,
+ GrantsListInvitesInput,
+)
+from server.identity.app import invite_mail
+from server.identity.app import invites as mod
+from server.identity.domain import invites as domain
+from server.identity.domain.grants import GrantState
+from server.identity.store import invites as invites_repo
+from server.operations.base import Role
+from server.settings import settings
+from tests.unit.schema_ddl import column_names
+
+
+class World:
+ """The rows the handlers read and write, in memory."""
+
+ def __init__(self) -> None:
+ self.invites: dict[str, domain.Invite] = {}
+ self.writes: list[domain.Invite] = []
+ # Rows' owners: an account's handle, or whatever `namespace.register` was given.
+ self.accounts = {"robin", "platform@acme.example", "Robin@Corp.Example"}
+ # Handles a live grant in the org is stored under, as stored.
+ self.granted = {"Carol", "bob@example.com"}
+ self.verified = {"sso@example.com": "sso-handle"}
+ # Verified emails, in lower case, that are themselves an account's login handle.
+ self.email_handles = {"robin@corp.example"}
+ self.grants: list[tuple[GrantsCreateInput, str | None]] = []
+ self.grant_error: BaseException | None = None
+ # The grant row lands before `grant_error` is raised (a lost reply).
+ self.grant_lands = False
+ # What each maker's grants make them on the namespace.
+ self.maker_roles: dict[str, Role | None] = {"admin-ann": Role.ADMIN}
+ # Makers whose account is disabled, and subjects revoked outright.
+ self.disabled: set[str] = set()
+ self.revoked: set[str] = set()
+ self.active = True
+ self.mail: list[dict[str, Any]] = []
+ self.may_mail = True
+ self.mail_asked: list[tuple[Any, ...]] = []
+ self.mail_error: BaseException | None = None
+ # Raised by the write that spends a link, after it lands (a lost reply).
+ self.put_error: BaseException | None = None
+ # Cancelled from inside the grant, as a client gone mid-request cancels it.
+ self.cancel: anyio.CancelScope | None = None
+ # Run while the grant is in flight, before it lands or fails.
+ self.during_grant: Callable[[], Awaitable[Any]] | None = None
+
+
+@pytest.fixture
+def world(monkeypatch: pytest.MonkeyPatch) -> Iterator[World]:
+ w = World()
+
+ async def put(invite: domain.Invite, **_: Any) -> None:
+ w.invites[invite.invite_id] = invite
+ w.writes.append(invite)
+ if w.put_error is not None and invite.state == "accepted":
+ raise w.put_error
+
+ async def get(org: str, namespace: str, invite_id: str, **_: Any) -> domain.Invite | None:
+ found = w.invites.get(invite_id)
+ await anyio.lowlevel.checkpoint() # answered as of the read, before another write
+ return found if found and (found.org, found.namespace) == (org, namespace) else None
+
+ async def open_on(
+ org: str, namespace: str, now: int, limit: int, **_: Any
+ ) -> list[domain.Invite]:
+ return [i for i in w.invites.values() if i.is_open(now)][:limit]
+
+ async def account_handle(org: str, subject: str, **_: Any) -> str | None:
+ return next((a for a in w.accounts if a.lower() == subject.lower()), None)
+
+ async def granted_spelling(org: str, subject: str, **_: Any) -> str | None:
+ return next((g for g in w.granted if g.lower() == subject.lower()), None)
+
+ async def made_by(org: str, maker: str, **_: Any) -> list[domain.Invite]:
+ return [i for i in w.invites.values() if (i.org, i.created_by) == (org, maker)]
+
+ async def is_active(org: str, namespace: str, **_: Any) -> bool:
+ return w.active
+
+ def canonical_of(subject: str) -> str:
+ # As canonical_subject: an email moves only onto a handle that is no email.
+ alias = w.verified.get(subject.lower())
+ return alias if alias and "@" in subject and "@" not in alias else subject
+
+ async def canonical(org: str, subject: str, **_: Any) -> str:
+ return canonical_of(subject)
+
+ async def verified_owner(org: str, subject: str, **_: Any) -> str | None:
+ if alias := w.verified.get(subject.lower()):
+ return alias
+ if subject.lower() not in w.email_handles:
+ return None
+ return next(a for a in w.accounts if a.lower() == subject.lower())
+
+ async def store_grant(
+ input: GrantsCreateInput, *_a: Any, issuer: str | None = None
+ ) -> tuple[None, str]:
+ # Written under the handle a verified email ties to, as the real one writes it.
+ input = input.model_copy(update={"subject": canonical_of(input.subject)})
+ if w.cancel is not None:
+ w.cancel.cancel()
+ await anyio.lowlevel.checkpoint()
+ if w.during_grant is not None:
+ await w.during_grant()
+ if w.grant_lands:
+ w.grants.append((input, issuer))
+ if w.grant_error is not None:
+ raise w.grant_error
+ if not w.grant_lands:
+ w.grants.append((input, issuer))
+ return None, input.subject
+
+ async def subject_grant_role(org: str, namespace: str, subject: str) -> Role | None:
+ return w.maker_roles.get(subject)
+
+ async def account_active(org: str, creator: str) -> bool:
+ return creator not in w.disabled
+
+ async def find_active_grant(org: str, namespace: str, subject: str, **_: Any) -> Any:
+ if not sequential_reads_active():
+ return None # a replica that has not seen the grant just written
+ held = [
+ g for g, _ in w.grants if (g.org, g.namespace, g.subject) == (org, namespace, subject)
+ ]
+ if not held:
+ return None
+ return GrantState(
+ role=held[-1].role,
+ granted_by="",
+ status="active",
+ pending_role=None,
+ pending_since=None,
+ )
+
+ async def no_ceiling(*_a: Any, **_k: Any) -> None:
+ return None
+
+ @contextlib.asynccontextmanager
+ async def claimed(*_a: Any) -> AsyncIterator[None]:
+ await anyio.lowlevel.checkpoint() # the lease's own round trip, where a cancel lands
+ with own_write_reads(): # as the real claim reads under it
+ yield
+
+ async def send(to: str, **kw: Any) -> bool:
+ w.mail.append({"to": to, **kw})
+ return True
+
+ monkeypatch.setattr(mod.invites_repo, "put", put)
+ monkeypatch.setattr(mod.invites_repo, "get", get)
+ monkeypatch.setattr(mod.invites_repo, "open_on", open_on)
+ monkeypatch.setattr(mod.invites_repo, "made_by", made_by)
+ monkeypatch.setattr(mod.namespaces_repo, "account_handle", account_handle)
+ monkeypatch.setattr(mod.grants_repo, "granted_spelling", granted_spelling)
+ monkeypatch.setattr(mod.namespaces_repo, "is_active", is_active)
+ monkeypatch.setattr("server.auth.aliases.canonical_subject", canonical)
+ monkeypatch.setattr("server.auth.aliases.verified_owner", verified_owner)
+ monkeypatch.setattr(mod, "store_grant", store_grant)
+ monkeypatch.setattr(mod, "subject_grant_role", subject_grant_role)
+ monkeypatch.setattr(mod, "creator_account_active", account_active)
+ monkeypatch.setattr(mod, "is_revoked", lambda subject, **_: subject in w.revoked)
+ monkeypatch.setattr(mod.grants_repo, "find_active_grant", find_active_grant)
+ monkeypatch.setattr(mod, "enforce_code_ceiling", no_ceiling)
+ monkeypatch.setattr(mod, "invite_change", claimed)
+ monkeypatch.setattr(mod.invite_mail, "send_invite", send)
+
+ async def may_mail(*a: Any) -> bool:
+ if w.mail_error is not None:
+ raise w.mail_error
+ w.mail_asked.append(a)
+ return w.may_mail
+
+ monkeypatch.setattr(mod, "_may_mail", may_mail)
+ signed_in("admin-ann")
+ yield w
+ set_current_auth(None)
+ fail_closed.reset()
+
+
+def signed_in(
+ subject: str,
+ *,
+ org: str = "o",
+ service: bool = False,
+ creator: str = "",
+ impersonated_by: str = "",
+) -> None:
+ set_current_auth(
+ AuthInfo(
+ subject=subject,
+ org=org,
+ namespaces=("ns",),
+ roles=(Role.WRITER,),
+ is_service_account=service,
+ creator=creator,
+ impersonated_by=impersonated_by,
+ )
+ )
+
+
+async def invite(to: str, role: str = "writer") -> Any:
+ return await mod.handle_grants_invite(
+ GrantsInviteInput(org="o", namespace="ns", to=to, role=role) # type: ignore[arg-type]
+ )
+
+
+def secret_of(link_path: str) -> str:
+ parts = urlsplit(link_path)
+ assert (parts.path, parts.query) == ("/spaces", "")
+ fragment = parse_qs(parts.fragment)
+ assert (fragment["org"], fragment["namespace"]) == (["o"], ["ns"])
+ return fragment["invite"][0]
+
+
+async def accept(secret: str) -> Any:
+ return await mod.handle_grants_accept_invite(
+ GrantsAcceptInviteInput(org="o", namespace="ns", secret=secret)
+ )
+
+
+@pytest.mark.asyncio
+async def test_a_handle_an_account_signs_in_as_is_granted_at_once(world: World) -> None:
+ out = await invite("Robin")
+ assert (out.outcome, out.subject, out.link_path) == ("granted", "robin", "")
+ assert [(g.subject, g.role) for g, _ in world.grants] == [("robin", "writer")]
+ assert world.invites == {}
+
+
+@pytest.mark.asyncio
+async def test_a_handle_a_live_grant_is_stored_under_is_granted_under_that_spelling(
+ world: World,
+) -> None:
+ """A person whose tokens Loom did not mint at sign-in has no account row."""
+ out = await invite("carol")
+ assert (out.outcome, out.subject) == ("granted", "Carol")
+ assert [g.subject for g, _ in world.grants] == ["Carol"]
+
+
+@pytest.mark.parametrize("to", ["bob@example.com", "platform@acme.example"])
+@pytest.mark.asyncio
+async def test_an_email_only_a_grant_or_a_rows_owner_names_still_gets_a_link(
+ world: World, to: str
+) -> None:
+ """`grants.create` stores an email as typed and `namespace.register` takes any owner,
+ so neither is an account that signs in."""
+ out = await invite(to)
+ assert out.outcome == "invited" and world.grants == []
+
+
+@pytest.mark.asyncio
+async def test_a_verified_email_is_granted_under_its_handle(world: World) -> None:
+ out = await invite("sso@example.com", "viewer")
+ assert (out.outcome, out.subject) == ("granted", "sso-handle")
+ assert world.invites == {}
+
+
+@pytest.mark.asyncio
+async def test_a_handle_no_account_holds_is_refused_and_writes_nothing(world: World) -> None:
+ with pytest.raises(NotFoundError, match="no account in o signs in as 'robinn'"):
+ await invite("robinn")
+ assert world.grants == [] and world.invites == {}
+
+
+@pytest.mark.parametrize("to", ["sa:bot", "SA:bot", "group:eng", "everyone", "user:42", "agent:x"])
+@pytest.mark.asyncio
+async def test_a_principal_is_left_to_grants_create(world: World, to: str) -> None:
+ with pytest.raises(ValidationError, match="grants.create"):
+ await invite(to)
+
+
+@pytest.mark.parametrize(
+ "to",
+ [
+ "victim@example.com,x1",
+ "victim@example.com;x1",
+ "Victim ",
+ "victim@example.com (x)",
+ '"v x"@example.com',
+ "victim@localhost",
+ ".a..b.@example.com",
+ ],
+)
+@pytest.mark.asyncio
+async def test_only_one_plain_address_gets_a_link(world: World, to: str) -> None:
+ """A list, a display name or a comment would name other recipients, or key the
+ address's mail limit by a string that is not the address."""
+ with pytest.raises(ValidationError):
+ await invite(to)
+ assert world.invites == {} and world.grants == [] and world.mail == []
+
+
+@pytest.mark.asyncio
+async def test_an_address_sign_up_takes_gets_a_link(world: World) -> None:
+ out = await invite("jörg@bücher.example")
+ assert out.outcome == "invited"
+ assert world.invites[out.invite_id].email == "jörg@bücher.example"
+
+
+@pytest.mark.asyncio
+async def test_a_request_with_no_token_grants_a_person_nothing_holds_as_typed(world: World) -> None:
+ """Only auth off serves one, and no one signs in there to accept a link."""
+ set_current_auth(None)
+ out = await invite("new@example.com")
+ assert (out.outcome, out.subject) == ("granted", "new@example.com")
+ # Answered under the subject the grant is written under.
+ assert (await invite("sso@example.com")).subject == "sso-handle"
+ # A handle no account or grant holds is granted, not refused; a held one keeps its
+ # stored spelling.
+ assert (await invite("robinn")).subject == "robinn"
+ assert (await invite("carol")).subject == "Carol"
+ assert world.invites == {}
+
+
+@pytest.mark.asyncio
+async def test_a_mail_limit_that_cannot_be_read_leaves_no_link_listed(world: World) -> None:
+ world.mail_error = BackendUnavailableError("down")
+ with pytest.raises(BackendUnavailableError):
+ await invite("robin@example.com")
+ assert world.writes == []
+
+
+@pytest.mark.asyncio
+async def test_a_verified_contact_email_is_granted_under_the_email_its_account_signs_in_as(
+ world: World,
+) -> None:
+ world.verified["robin.home@x.example"] = "Robin@Corp.Example"
+ # A namespace someone registered naming that contact address as its owner.
+ world.accounts.add("Robin.Home@X.Example")
+ out = await invite("Robin.Home@X.Example")
+ assert (out.outcome, out.subject, out.link_path) == ("granted", "Robin@Corp.Example", "")
+ assert [g.subject for g, _ in world.grants] == ["Robin@Corp.Example"]
+
+
+@pytest.mark.asyncio
+async def test_the_answer_names_the_subject_the_grant_is_written_under(world: World) -> None:
+ """An account's email-shaped handle that another account verified is written under that
+ account's handle, as `grants.create` writes it: the answer names the same one."""
+ world.verified["hana.home@x.example"] = "hana@corp.example"
+ world.verified["hana@corp.example"] = "hana-work"
+ out = await invite("hana.home@x.example")
+ assert (out.outcome, out.subject) == ("granted", "hana-work")
+ assert [g.subject for g, _ in world.grants] == ["hana-work"]
+
+
+@pytest.mark.asyncio
+async def test_a_verified_email_an_account_signs_in_as_is_granted_at_once(world: World) -> None:
+ """Under the handle as stored, whatever the case typed: grants are read by subject."""
+ out = await invite("robin@corp.example")
+ assert (out.outcome, out.subject, out.link_path) == ("granted", "Robin@Corp.Example", "")
+ assert [g.subject for g, _ in world.grants] == ["Robin@Corp.Example"]
+
+
+@pytest.mark.asyncio
+async def test_an_email_no_account_holds_gets_a_link_kept_only_as_its_hash(world: World) -> None:
+ out = await invite("Robin@Example.com")
+ assert out.outcome == "invited" and out.emailed is True
+ secret = secret_of(out.link_path)
+ stored = world.invites[out.invite_id]
+ assert out.invite_id == domain.invite_id(secret) != secret
+ assert secret not in repr(stored)
+ assert (stored.email, stored.role, stored.created_by, stored.state) == (
+ "robin@example.com",
+ "writer",
+ "admin-ann",
+ "open",
+ )
+ assert stored.expires_at - time.time() == pytest.approx(settings.invite_ttl_seconds, abs=5)
+ assert world.mail[0]["to"] == "robin@example.com"
+ listed = await mod.handle_grants_list_invites(GrantsListInvitesInput(org="o", namespace="ns"))
+ assert [r.email for r in listed.rows] == ["robin@example.com"]
+
+
+@pytest.mark.asyncio
+async def test_past_the_mail_limits_the_link_is_still_made_and_not_emailed(world: World) -> None:
+ world.may_mail = False
+ out = await invite("robin@example.com")
+ assert (out.outcome, out.emailed, world.mail) == ("invited", False, [])
+ assert out.invite_id in world.invites
+
+
+@pytest.mark.asyncio
+async def test_mail_waits_for_the_settings_counting_nothing(
+ auth_attempts: Any, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(invite_mail, "can_send", lambda: False)
+ assert await mod._may_mail("o", "ann", "m@example.com") is False
+ assert auth_attempts.rows == []
+
+
+@pytest.mark.asyncio
+async def test_mail_stops_at_twenty_an_hour_per_inviter_and_three_a_day_per_address(
+ auth_attempts: Any, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(invite_mail, "can_send", lambda: True)
+ to_one = [await mod._may_mail("o", f"ann-{i}", "m@example.com") for i in range(4)]
+ assert to_one == [True, True, True, False]
+ by_one = [await mod._may_mail("o", "bea", f"p{i}@example.com") for i in range(21)]
+ assert by_one == [True] * 20 + [False]
+ # Each limit is counted only once the one before it admits: the refused attempts
+ # spent no org or mailbox room.
+ kinds = Counter(r["kind"] for r in auth_attempts.rows)
+ assert kinds == {"invite.mail.inviter": 23, "invite.mail.org": 23, "invite.mail.address": 23}
+ # An address at its limit spends none of an inviter's, whatever `+tag` it carries.
+ tagged = [await mod._may_mail("o", "cid", f"m+{i}@example.com") for i in range(20)]
+ assert tagged == [False] * 20
+ assert await mod._may_mail("o", "cid", "fresh@example.com") is True
+ # Dots in the local part and a domain's Unicode and ASCII spellings are one mailbox.
+ spelled = ["jo@bücher.example", "j.o@xn--bcher-kva.example", "jo@BÜCHER.example"] * 2
+ assert [await mod._may_mail("o", f"dan-{i}", a) for i, a in enumerate(spelled)] == [
+ True,
+ True,
+ True,
+ False,
+ False,
+ False,
+ ]
+
+
+@pytest.mark.asyncio
+async def test_mail_stops_at_a_hundred_an_hour_per_org_however_many_inviters_sign_up(
+ auth_attempts: Any, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(invite_mail, "can_send", lambda: True)
+ sent = [await mod._may_mail("o", f"new-{i}", f"p{i}@example.com") for i in range(101)]
+ assert sent == [True] * 100 + [False]
+ # An org at its limit spends none of an inviter's.
+ assert sum(r["kind"] == "invite.mail.inviter" for r in auth_attempts.rows) == 100
+ # Another org's room is its own.
+ assert await mod._may_mail("p", "new-0", "q@example.com") is True
+
+
+@pytest.mark.asyncio
+async def test_the_accepter_again_is_not_answered_a_lower_role_as_done(world: World) -> None:
+ """Spent by robin, who holds only the viewer grant from before: the writer grant
+ failed and the link could not be reopened. Answering viewer would read as the
+ invitation done; the link is used, and a new one is asked for."""
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ invite_id = domain.invite_id(secret)
+ world.invites[invite_id] = world.invites[invite_id].accepted("robin")
+ world.grants.append(
+ (GrantsCreateInput(org="o", namespace="ns", subject="robin", role="viewer"), None)
+ )
+ signed_in("robin")
+ with pytest.raises(NotFoundError, match="used, cancelled or expired"):
+ await accept(secret)
+ world.grants.append(
+ (GrantsCreateInput(org="o", namespace="ns", subject="robin", role="writer"), None)
+ )
+ assert (await accept(secret)).role == "writer"
+
+
+@pytest.mark.asyncio
+async def test_the_code_ceiling_is_read_as_the_active_check_reads(
+ world: World, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Past a namespace just registered as a repository's: a lagging read would take it
+ for a memory namespace and store a writer link no accept can grant."""
+ seen: list[bool] = []
+
+ async def ceiling(*_a: Any) -> None:
+ seen.append(sequential_reads_active())
+
+ monkeypatch.setattr(mod, "enforce_code_ceiling", ceiling)
+ await invite("robin@example.com")
+ assert seen == [True]
+
+
+@pytest.mark.asyncio
+async def test_a_secret_no_invitation_holds_takes_no_claim(
+ world: World, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Any signed-in person can send one: it must not cost a lease's write and release."""
+
+ def no_claim(*_a: Any) -> Any:
+ raise AssertionError("claimed an invitation that does not exist")
+
+ monkeypatch.setattr(mod, "invite_change", no_claim)
+ signed_in("robin")
+ with pytest.raises(NotFoundError, match="used, cancelled or expired"):
+ await accept(domain.new_secret())
+
+
+@pytest.mark.asyncio
+async def test_the_link_lets_one_person_in_once_as_granted_by_its_maker(world: World) -> None:
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ signed_in("robin")
+ out = await accept(secret)
+ assert (out.namespace, out.role) == ("ns", "writer")
+ assert [(g.subject, g.role, issuer) for g, issuer in world.grants] == [
+ ("robin", "writer", "admin-ann")
+ ]
+ assert world.invites[domain.invite_id(secret)].accepted_by == "robin"
+ signed_in("someone-else")
+ with pytest.raises(NotFoundError, match="used, cancelled or expired"):
+ await accept(secret)
+ assert len(world.grants) == 1
+
+
+@pytest.mark.asyncio
+async def test_its_accepter_opening_a_used_link_again_is_answered_their_role(
+ world: World,
+) -> None:
+ """A retry after a lost reply writes nothing; once the grant is gone, the link is."""
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ signed_in("robin")
+ await accept(secret)
+ writes = len(world.writes)
+ assert (await accept(secret)).role == "writer"
+ assert (len(world.grants), len(world.writes)) == (1, writes)
+ world.grants.clear()
+ with pytest.raises(NotFoundError, match="used, cancelled or expired"):
+ await accept(secret)
+
+
+@pytest.mark.asyncio
+async def test_its_accepter_is_answered_their_role_after_a_cancel_of_the_used_link(
+ world: World,
+) -> None:
+ out = await invite("robin@example.com")
+ signed_in("robin")
+ await accept(secret_of(out.link_path))
+ scope = GrantsCancelInviteInput(org="o", namespace="ns", invite_id=out.invite_id)
+ assert (await mod.handle_grants_cancel_invite(scope)).cancelled is False
+ writes = len(world.writes)
+ assert (await accept(secret_of(out.link_path))).role == "writer"
+ assert len(world.writes) == writes
+
+
+@pytest.mark.asyncio
+async def test_a_higher_role_held_already_stands(world: World) -> None:
+ secret = secret_of((await invite("robin@example.com", "viewer")).link_path)
+ world.grant_error = GrantWouldDowngradeError(current_role="admin", requested_role="viewer")
+ signed_in("robin")
+ assert (await accept(secret)).role == "admin"
+ assert world.invites[domain.invite_id(secret)].state == "accepted"
+
+
+@pytest.mark.asyncio
+async def test_a_failed_grant_leaves_the_link_open(world: World) -> None:
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ world.grant_error = BackendUnavailableError("down")
+ signed_in("robin")
+ with pytest.raises(BackendUnavailableError):
+ await accept(secret)
+ iid = domain.invite_id(secret)
+ assert [w.state for w in world.writes if w.invite_id == iid] == ["open", "accepted", "open"]
+ world.grant_error = None
+ assert (await accept(secret)).role == "writer"
+
+
+@pytest.mark.asyncio
+async def test_a_lost_reply_to_the_spend_leaves_the_link_open(world: World) -> None:
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ world.put_error = BackendUnavailableError("lost reply")
+ signed_in("robin")
+ with pytest.raises(BackendUnavailableError):
+ await accept(secret)
+ iid = domain.invite_id(secret)
+ assert [w.state for w in world.writes if w.invite_id == iid] == ["open", "accepted", "open"]
+ assert world.grants == []
+
+
+@pytest.mark.asyncio
+async def test_a_cancelled_accept_leaves_the_link_open(world: World) -> None:
+ """anyio raises a cancellation again at every await of its scope: the reopen still
+ runs to its end."""
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ signed_in("robin")
+ with anyio.CancelScope() as scope:
+ world.cancel = scope
+ await accept(secret)
+ assert scope.cancelled_caught
+ iid = domain.invite_id(secret)
+ assert [w.state for w in world.writes if w.invite_id == iid] == ["open", "accepted", "open"]
+ assert world.grants == []
+
+
+@pytest.mark.asyncio
+async def test_two_people_opening_one_link_at_once_let_in_one(
+ world: World, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from server.auth import grant_claims
+ from tests.unit.claims_fake import memory_claims
+
+ claims = memory_claims(monkeypatch)
+ monkeypatch.setattr(grant_claims, "take", claims.take)
+ monkeypatch.setattr(mod, "invite_change", grant_claims.invite_change)
+ secret = secret_of((await invite("robin@example.com")).link_path)
+
+ async def as_(subject: str) -> Any:
+ signed_in(subject)
+ return await accept(secret)
+
+ got = await asyncio.gather(as_("robin"), as_("carol"), return_exceptions=True)
+ assert sorted(type(g).__name__ for g in got) == ["GrantsAcceptInviteOutput", "NotFoundError"]
+ assert len(world.grants) == 1
+
+
+@pytest.mark.asyncio
+async def test_a_namespace_retired_since_the_invitation_admits_nobody(world: World) -> None:
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ world.active = False
+ signed_in("robin")
+ with pytest.raises(NotFoundError, match="its namespace is deleted"):
+ await accept(secret)
+ assert world.grants == [] and world.invites[domain.invite_id(secret)].state == "open"
+
+
+@pytest.mark.asyncio
+async def test_a_cancel_while_a_failing_accept_is_in_flight_keeps_the_link_closed(
+ world: World,
+) -> None:
+ out = await invite("robin@example.com")
+ # A lower role robin holds already, which the link's retry must not answer.
+ world.grants.append(
+ (GrantsCreateInput(org="o", namespace="ns", subject="robin", role="viewer"), None)
+ )
+ answers: list[bool] = []
+
+ async def cancel() -> None:
+ signed_in("admin-ann")
+ scope = GrantsCancelInviteInput(org="o", namespace="ns", invite_id=out.invite_id)
+ answers.append((await mod.handle_grants_cancel_invite(scope)).cancelled)
+ signed_in("robin")
+
+ world.during_grant, world.grant_error = cancel, BackendUnavailableError("down")
+ signed_in("robin")
+ with pytest.raises(BackendUnavailableError):
+ await accept(secret_of(out.link_path))
+ # Not open when the cancel came, so not cancelled by it; and not reopened after it.
+ assert answers == [False] and world.invites[out.invite_id].state == "cancelled"
+ # Its grant never landed, so robin's retry finds the link closed.
+ world.during_grant, world.grant_error = None, None
+ with pytest.raises(NotFoundError, match="used, cancelled or expired"):
+ await accept(secret_of(out.link_path))
+
+
+@pytest.mark.asyncio
+async def test_a_failure_after_the_grant_landed_leaves_the_link_used(world: World) -> None:
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ world.grant_error, world.grant_lands = BackendUnavailableError("lost reply"), True
+ signed_in("robin")
+ with pytest.raises(BackendUnavailableError):
+ await accept(secret)
+ iid = domain.invite_id(secret)
+ assert [w.state for w in world.writes if w.invite_id == iid] == ["open", "accepted"]
+ world.grant_error, world.grant_lands = None, False
+ signed_in("someone-else")
+ with pytest.raises(NotFoundError):
+ await accept(secret)
+ assert [g.subject for g, _ in world.grants] == ["robin"]
+
+
+@pytest.mark.asyncio
+async def test_an_invitation_never_outlasts_its_makers_admin(world: World) -> None:
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ world.maker_roles["admin-ann"] = Role.WRITER # lowered, or None when revoked
+ signed_in("robin")
+ with pytest.raises(NotFoundError, match="no longer stands behind it"):
+ await accept(secret)
+ assert world.invites[domain.invite_id(secret)].state == "open"
+ assert world.grants == []
+
+
+@pytest.mark.asyncio
+async def test_a_stopped_link_admits_again_once_its_maker_is_admin_again(world: World) -> None:
+ """It stands on its maker's grants, as a delegated token does."""
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ world.maker_roles["admin-ann"] = Role.WRITER
+ signed_in("robin")
+ with pytest.raises(NotFoundError, match="no longer stands behind it"):
+ await accept(secret)
+ world.maker_roles["admin-ann"] = Role.ADMIN
+ assert (await accept(secret)).role == "writer"
+ assert [(g.subject, issuer) for g, issuer in world.grants] == [("robin", "admin-ann")]
+
+
+@pytest.mark.asyncio
+async def test_an_admin_only_a_token_makes_makes_no_link(world: World) -> None:
+ """A platform admin or an operator's token holds no grant a later read could tell
+ from a revoked one."""
+ world.maker_roles = {}
+ with pytest.raises(ValidationError, match="those of 'admin-ann' do not make them admin"):
+ await invite("robin@example.com")
+ assert world.invites == {} and world.mail_asked == []
+
+
+@pytest.mark.asyncio
+async def test_a_delegated_tokens_link_stands_on_its_creators_admin(world: World) -> None:
+ signed_in("sa:helper-1a2b", service=True, creator="admin-ann")
+ out = await invite("robin@example.com")
+ assert world.invites[out.invite_id].created_by == "admin-ann"
+ assert world.mail_asked == [("o", "admin-ann", "robin@example.com")]
+ world.maker_roles["admin-ann"] = None # the creator's admin revoked
+ signed_in("robin")
+ with pytest.raises(NotFoundError, match="no longer stands behind it"):
+ await accept(secret_of(out.link_path))
+ assert world.grants == []
+
+
+@pytest.mark.asyncio
+async def test_a_failed_read_of_the_makers_grants_refuses(
+ world: World, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ secret = secret_of((await invite("robin@example.com")).link_path)
+
+ async def unreadable(*_a: Any) -> Role | None:
+ fail_closed.note_unreadable()
+ return None
+
+ monkeypatch.setattr(mod, "subject_grant_role", unreadable)
+ signed_in("robin")
+ with pytest.raises(BackendUnavailableError, match="could not be read"):
+ await accept(secret) # a 503: the dashboard keeps the link
+ assert world.invites[domain.invite_id(secret)].state == "open"
+ signed_in("admin-ann")
+ with pytest.raises(BackendUnavailableError, match="could not be read"):
+ await invite("other@example.com")
+ assert world.grants == [] and len(world.invites) == 1
+
+
+@pytest.mark.parametrize("ended", ["disabled", "revoked"])
+@pytest.mark.asyncio
+async def test_a_link_stops_with_its_makers_account(world: World, ended: str) -> None:
+ """As a token delegated by the maker stops: a disabled account, or a revoked subject."""
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ getattr(world, ended).add("admin-ann")
+ signed_in("robin")
+ with pytest.raises(NotFoundError, match="no longer stands behind it"):
+ await accept(secret)
+ assert world.grants == [] and world.invites[domain.invite_id(secret)].state == "open"
+
+
+@pytest.mark.parametrize("role", ["writer", "viewer"])
+@pytest.mark.asyncio
+async def test_a_repository_takes_only_its_own_roles_by_invitation(
+ world: World, monkeypatch: pytest.MonkeyPatch, role: str
+) -> None:
+ """A repository's roles are viewer and admin: a writer invitation is refused before
+ any link is made, and a viewer one is accepted as viewer."""
+ from server.identity.app import grants as grants_app
+
+ class _Repo:
+ async def query_one(self, *_a: Any, **_k: Any) -> dict[str, Any]:
+ return {"kind": "code"}
+
+ monkeypatch.setattr(mod, "enforce_code_ceiling", grants_app.enforce_code_ceiling)
+ monkeypatch.setattr("server.core.ch.get_client", lambda: _Repo())
+ if role == "writer":
+ with pytest.raises(ValidationError) as refused:
+ await invite("robin@example.com", role)
+ assert refused.value.extra["code"] == "ROLE_CEILING" and world.invites == {}
+ return
+ secret = secret_of((await invite("robin@example.com", role)).link_path)
+ signed_in("robin")
+ assert (await accept(secret)).role == "viewer"
+
+
+@pytest.mark.asyncio
+async def test_a_collection_is_invited_to_and_accepted_on_as_a_namespace_is(
+ world: World, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A shared collection takes a writer invitation under the real ceiling, and its link
+ grants on the collection; a personal one is refused before any link is made."""
+ from server.identity.app import grants as grants_app
+
+ class _Collection:
+ async def query_one(self, *_a: Any, **_k: Any) -> dict[str, Any]:
+ return {"kind": "collection"}
+
+ monkeypatch.setattr(mod, "enforce_code_ceiling", grants_app.enforce_code_ceiling)
+ monkeypatch.setattr("server.core.ch.get_client", lambda: _Collection())
+ with pytest.raises(ValidationError, match="personal collection"):
+ await mod.handle_grants_invite(
+ GrantsInviteInput(
+ org="o", namespace="col-me-ann", to="robin@example.com", role="writer"
+ )
+ )
+ out = await mod.handle_grants_invite(
+ GrantsInviteInput(org="o", namespace="col-team", to="robin@example.com", role="writer")
+ )
+ fragment = parse_qs(urlsplit(out.link_path).fragment)
+ assert fragment["namespace"] == ["col-team"]
+ signed_in("robin")
+ got = await mod.handle_grants_accept_invite(
+ GrantsAcceptInviteInput(org="o", namespace="col-team", secret=fragment["invite"][0])
+ )
+ assert (got.namespace, got.role) == ("col-team", "writer")
+ assert [(g.namespace, g.subject, g.role) for g, _ in world.grants] == [
+ ("col-team", "robin", "writer")
+ ]
+
+
+@pytest.mark.asyncio
+async def test_the_held_handle_reads_see_another_replicas_write() -> None:
+ """`grants.invite` reads a handle or an email's account right after a grant, a sign-up
+ or a link another replica took, and a namespace right after its registration: each
+ read runs with sequential consistency."""
+ seen: list[bool] = []
+
+ class _CH:
+ async def query_one(self, *_a: object, **_k: object) -> None:
+ seen.append(sequential_reads_active())
+
+ async def query_all(self, *_a: object, **_k: object) -> list[Any]:
+ seen.append(sequential_reads_active())
+ return []
+
+ await mod.namespaces_repo.account_handle("acme", "robin", ch=_CH()) # type: ignore[arg-type]
+ await mod.grants_repo.granted_spelling("acme", "robin", ch=_CH()) # type: ignore[arg-type]
+ await mod.namespaces_repo.is_active("acme", "team", ch=_CH()) # type: ignore[arg-type]
+ await aliases.verified_owner("acme", "robin@corp.example", ch=_CH())
+ assert seen == [True, True, True, True]
+
+
+@pytest.mark.asyncio
+async def test_a_namespace_scoped_token_is_refused_at_the_gate() -> None:
+ """The gate checks no namespace role for an accept, and a namespace-scoped token's
+ authority is per namespace: it answers 400, as for every such op."""
+ from server.auth.authz import check_authorized
+ from server.operations.registry import ALL_OPERATIONS
+
+ op = next(o for o in ALL_OPERATIONS if o.name == "grants.accept_invite")
+ assert op.skip_namespace_authz and not (op.row_scoped or op.deployment_scoped)
+ scoped = AuthInfo(
+ subject="robin",
+ org="o",
+ namespaces=("home",),
+ roles=(),
+ is_service_account=False,
+ ns_roles=(("home", "admin"),),
+ )
+ with pytest.raises(IdentityIncompleteError):
+ await check_authorized(scoped, op.required_role, org="o")
+
+
+@pytest.mark.asyncio
+async def test_a_list_past_its_cap_says_it_was_cut(world: World) -> None:
+ made = datetime.now(UTC)
+ for n in range(mod._LISTED + 1):
+ world.invites[f"i{n}"] = domain.Invite(
+ org="o", namespace="ns", invite_id=f"i{n}", email=f"p{n}@example.com",
+ role="writer", created_by="admin-ann", created_at=made,
+ expires_at=int(time.time()) + 3600,
+ ) # fmt: skip
+ scope = GrantsListInvitesInput(org="o", namespace="ns")
+ listed = await mod.handle_grants_list_invites(scope)
+ assert (len(listed.rows), listed.truncated) == (mod._LISTED, True)
+ del world.invites["i0"]
+ listed = await mod.handle_grants_list_invites(scope)
+ assert (len(listed.rows), listed.truncated) == (mod._LISTED, False)
+
+
+@pytest.mark.parametrize("ended", ["lowered", "disabled", "revoked"])
+@pytest.mark.asyncio
+async def test_a_link_whose_maker_no_longer_stands_is_listed_stopped(
+ world: World, ended: str
+) -> None:
+ """It admits nobody but still holds the name, so it is listed, marked, to cancel."""
+ made = await invite("robin@example.com")
+ scope = GrantsListInvitesInput(org="o", namespace="ns")
+ assert [r.stopped for r in (await mod.handle_grants_list_invites(scope)).rows] == [False]
+ if ended == "lowered":
+ world.maker_roles["admin-ann"] = Role.WRITER
+ else:
+ getattr(world, ended).add("admin-ann")
+ listed = (await mod.handle_grants_list_invites(scope)).rows
+ assert [(r.invite_id, r.stopped) for r in listed] == [(made.invite_id, True)]
+
+
+@pytest.mark.parametrize(("cut", "stands"), [(60, False), (-60, True)])
+@pytest.mark.asyncio
+async def test_a_makers_cutoff_ends_only_the_links_made_before_it(
+ world: World, monkeypatch: pytest.MonkeyPatch, cut: int, stands: bool
+) -> None:
+ """A cutoff ends the maker's tokens issued before it, and so the links made before it,
+ judged by when the link was made, not by now."""
+ monkeypatch.setattr(mod, "is_revoked", revocation.is_revoked)
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ key = domain.invite_id(secret)
+ made = datetime.fromtimestamp(int(time.time()) - 3600, UTC)
+ world.invites[key] = replace(world.invites[key], created_at=made)
+ monkeypatch.setattr(revocation, "_cut_off", {"admin-ann": int(made.timestamp()) + cut})
+ listed = await mod.handle_grants_list_invites(GrantsListInvitesInput(org="o", namespace="ns"))
+ assert [r.stopped for r in listed.rows] == [not stands]
+ signed_in("robin")
+ if stands:
+ assert (await accept(secret)).role == "writer"
+ else:
+ with pytest.raises(NotFoundError, match="no longer stands behind it"):
+ await accept(secret)
+
+
+@pytest.mark.asyncio
+async def test_an_end_users_links_stop_with_their_revocation(world: World) -> None:
+ """An end user's tokens are revoked under `/user:`, and so are their links."""
+ world.maker_roles["user:42"] = Role.ADMIN
+ signed_in("user:42")
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ world.revoked.add("o/user:42")
+ listed = await mod.handle_grants_list_invites(GrantsListInvitesInput(org="o", namespace="ns"))
+ assert [r.stopped for r in listed.rows] == [True]
+ signed_in("robin")
+ with pytest.raises(NotFoundError, match="no longer stands behind it"):
+ await accept(secret)
+ assert world.grants == []
+
+
+@pytest.mark.asyncio
+async def test_a_failed_read_earlier_in_the_request_does_not_refuse_the_maker(
+ world: World,
+) -> None:
+ fail_closed.note_unreadable() # a read the gate made and survived
+ assert (await invite("robin@example.com")).outcome == "invited"
+
+
+@pytest.mark.asyncio
+async def test_a_role_this_build_does_not_know_is_unlisted_and_admits_nobody(
+ world: World,
+) -> None:
+ out = await invite("robin@example.com")
+ world.invites[out.invite_id] = replace(world.invites[out.invite_id], role="owner")
+ listed = await mod.handle_grants_list_invites(GrantsListInvitesInput(org="o", namespace="ns"))
+ assert listed.rows == []
+ signed_in("robin")
+ with pytest.raises(NotFoundError):
+ await accept(secret_of(out.link_path))
+ assert world.grants == []
+
+
+@pytest.mark.asyncio
+async def test_an_erased_makers_links_close_and_lose_their_name(world: World) -> None:
+ opened = await invite("a@example.com")
+ used = await invite("b@example.com")
+ signed_in("robin")
+ await accept(secret_of(used.link_path))
+ assert await mod.forget_maker("o", "admin-ann") == 2
+ assert [(i.state, i.created_by) for i in world.invites.values()] == [
+ ("cancelled", ""),
+ ("accepted", ""),
+ ]
+ with pytest.raises(NotFoundError):
+ await accept(secret_of(opened.link_path))
+
+
+@pytest.mark.asyncio
+async def test_an_inactive_namespace_gets_no_invitation(world: World) -> None:
+ world.active = False
+ with pytest.raises(NotFoundError, match="not an active namespace"):
+ await invite("robin@example.com")
+ assert world.invites == {}
+
+
+@pytest.mark.asyncio
+async def test_where_sign_in_is_single_sign_on_only_an_email_is_granted_as_typed(
+ world: World, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(settings, "oauth_login_provider", "oidc")
+ out = await invite("New@Example.com")
+ assert (out.outcome, out.subject, out.link_path) == ("granted", "New@Example.com", "")
+ assert [(g.subject, g.role) for g, _ in world.grants] == [("New@Example.com", "writer")]
+ assert world.invites == {} and world.mail == []
+ # The address is checked as for a link: one no identity provider signs in as is refused.
+ with pytest.raises(ValidationError, match="not an email address"):
+ await invite("alice@corp")
+ assert len(world.grants) == 1
+
+
+def test_a_state_this_build_does_not_know_is_closed() -> None:
+ made = datetime(2026, 1, 1, tzinfo=UTC)
+ open_row = domain.Invite(
+ org="o",
+ namespace="ns",
+ invite_id="h",
+ email="m@example.com",
+ role="writer",
+ created_by="ann",
+ created_at=made,
+ expires_at=2**31,
+ ).row()
+ assert domain.Invite.from_row(open_row).is_open(0)
+ assert not domain.Invite.from_row({**open_row, "state": "revoked"}).is_open(0)
+
+
+@pytest.mark.asyncio
+async def test_an_expired_or_cancelled_link_admits_nobody(world: World) -> None:
+ expired = secret_of((await invite("a@example.com")).link_path)
+ iid = domain.invite_id(expired)
+ world.invites[iid] = replace(world.invites[iid], expires_at=int(time.time()) - 1)
+ cancelled = (await invite("b@example.com")).invite_id
+ out = await mod.handle_grants_cancel_invite(
+ GrantsCancelInviteInput(org="o", namespace="ns", invite_id=cancelled)
+ )
+ assert out.cancelled is True
+ assert (world.invites[cancelled].state, world.invites[cancelled].accepted_by) == (
+ "cancelled",
+ "",
+ )
+ again = await mod.handle_grants_cancel_invite(
+ GrantsCancelInviteInput(org="o", namespace="ns", invite_id=cancelled)
+ )
+ assert again.cancelled is False
+ signed_in("robin")
+ with pytest.raises(NotFoundError):
+ await accept(expired)
+ with pytest.raises(NotFoundError):
+ await accept("not-a-link")
+ assert world.grants == []
+
+
+@pytest.mark.parametrize(
+ ("subject", "org", "service", "via", "words"),
+ [
+ ("sa:bot", "o", True, "", "a person"),
+ ("bot", "o", True, "", "a person"), # a service account's token, its subject unprefixed
+ ("group:eng", "o", False, "", "a person"),
+ ("robin", "other", False, "", "sign in to o"),
+ # A trusted caller acting for robin, whatever its own token: robin signs in himself.
+ ("robin", "o", False, "gateway", "a person"),
+ ("robin", "o", True, "gateway", "a person"),
+ ],
+)
+@pytest.mark.asyncio
+async def test_only_a_person_of_the_org_accepts(
+ world: World, subject: str, org: str, service: bool, via: str, words: str
+) -> None:
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ signed_in(subject, org=org, service=service, impersonated_by=via)
+ with pytest.raises(ValidationError, match=words):
+ await accept(secret)
+ assert world.invites[domain.invite_id(secret)].state == "open"
+
+
+@pytest.mark.parametrize(("org", "role"), [("*", Role.WRITER), ("other", Role.PLATFORM_ADMIN)])
+@pytest.mark.asyncio
+async def test_an_org_wildcard_or_other_org_token_is_refused_at_accept(
+ world: World, org: str, role: Role
+) -> None:
+ """An org-wildcard token and a platform admin's pass the transport's org check: the
+ invitation still asks for a sign-in to its own org."""
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ set_current_auth(
+ AuthInfo(
+ subject="robin", org=org, namespaces=("*",), roles=(role,), is_service_account=False
+ )
+ )
+ with pytest.raises(ValidationError, match="sign in to o"):
+ await accept(secret)
+ assert world.invites[domain.invite_id(secret)].state == "open"
+
+
+@pytest.mark.asyncio
+async def test_the_mail_carries_the_link(monkeypatch: pytest.MonkeyPatch) -> None:
+ sent: list[Any] = []
+ monkeypatch.setattr(invite_mail, "_send", sent.append)
+ args = {"inviter": "ann", "namespace": "ns", "role": "writer", "url": "u", "expires_at": 0}
+ monkeypatch.setattr(settings, "mail_from", "Loom ")
+ assert await invite_mail.send_invite("m@example.com", **{**args, "url": "https://x/l#s"})
+ assert "https://x/l#s" in sent[0].get_content()
+ assert sent[0]["Date"] and sent[0]["Message-ID"].endswith("@example.com>")
+ # An internationalised domain goes out in IDNA's ASCII form, for a relay without SMTPUTF8.
+ assert await invite_mail.send_invite("info@bücher.example", **args)
+ assert sent[1]["To"] == "info@xn--bcher-kva.example"
+ # A header with a line break is refused by the email library: reported as not sent.
+ assert await invite_mail.send_invite("m@example.com\nBcc: x@y.z", **args) is False
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("subject", "service", "creator", "via", "named"),
+ [
+ ("admin-ann", False, "", "", "admin-ann"),
+ ("sa:ann-7f3a2b", True, "admin-ann", "", "admin-ann"), # a delegated token: its creator
+ ("admin-ann", True, "", "gateway", "admin-ann"), # a trusted caller on her behalf
+ # A delegated trusted caller: its creator.
+ ("bob", True, "admin-ann", "gateway", "admin-ann"),
+ ("ci-bot", True, "", "", ""), # a service account acting as itself, prefix or not
+ ("sa:bot-7f3a2b", True, "", "", ""),
+ ("user:42", False, "", "", ""),
+ ],
+)
+async def test_the_mail_names_a_person_who_invited_and_no_service_account(
+ world: World, subject: str, service: bool, creator: str, via: str, named: str
+) -> None:
+ world.maker_roles[subject] = Role.ADMIN
+ signed_in(subject, service=service, creator=creator, impersonated_by=via)
+ await invite("robin@example.com")
+ assert world.mail[0]["inviter"] == named
+ msg = invite_mail._message(
+ "m@example.com", inviter=named, namespace="ns", role="writer", url="u", expires_at=0
+ )
+ lead = f"{named} invited you" if named else "You are invited"
+ assert msg["Subject"] == f"{lead} to ns on Loom"
+ assert msg.get_content().startswith(f"{lead} to the Loom namespace ns")
+
+
+@pytest.mark.asyncio
+async def test_a_send_past_the_timeout_is_reported_not_sent(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The bound is the whole send's: the invite answers only after it. A send that is
+ never bounded hangs here rather than passing."""
+ held = threading.Event()
+ monkeypatch.setattr(invite_mail, "_send", lambda msg: held.wait())
+ monkeypatch.setattr(settings, "mail_from", "Loom ")
+ monkeypatch.setattr(settings, "smtp_timeout_seconds", 0.05)
+ args = {"inviter": "ann", "namespace": "ns", "role": "writer", "url": "u", "expires_at": 0}
+ try:
+ assert await invite_mail.send_invite("m@example.com", **args) is False
+ finally:
+ held.set()
+
+
+@pytest.mark.parametrize(
+ "namespace",
+ [
+ "Your Loom account is locked. Restore access at https://evil.example/restore",
+ "evil.example/r",
+ ],
+)
+def test_the_email_names_a_namespace_only_as_the_server_names_one(
+ monkeypatch: pytest.MonkeyPatch, namespace: str
+) -> None:
+ """Any viewer can register a namespace under free text and invite to it; the email,
+ sent as the operator's address, prints no such text."""
+ monkeypatch.setattr(settings, "mail_from", "Loom ")
+ args = {"inviter": "ann", "role": "writer", "url": "u", "expires_at": 0}
+ msg = invite_mail._message("m@example.com", namespace=namespace, **args)
+ assert namespace not in msg.as_string()
+ assert msg["Subject"] == "ann invited you to a namespace on Loom"
+ assert msg.get_content().startswith("ann invited you to a Loom namespace, with the role")
+ named = invite_mail._message("m@example.com", namespace="team-alpha", **args)
+ assert named["Subject"] == "ann invited you to team-alpha on Loom"
+
+
+@pytest.mark.asyncio
+async def test_a_send_runs_on_the_mails_own_threads(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A stalled relay keeps a send's thread past the timeout: not one of the threads every
+ other `asyncio.to_thread` caller shares."""
+ ran_on: list[str] = []
+ monkeypatch.setattr(
+ invite_mail, "_send", lambda msg: ran_on.append(threading.current_thread().name)
+ )
+ monkeypatch.setattr(settings, "mail_from", "Loom ")
+ args = {"inviter": "ann", "namespace": "ns", "role": "writer", "url": "u", "expires_at": 0}
+ assert await invite_mail.send_invite("m@example.com", **args) is True
+ assert [n.startswith("loom-invite-mail") for n in ran_on] == [True]
+
+
+def test_a_mail_server_url_a_send_cannot_connect_to_is_refused_at_load() -> None:
+ from pydantic import ValidationError
+
+ from server.settings import Settings
+
+ for url in ("", "smtp://mail.example.com", "smtps://u:p@mail.example.com:465"):
+ assert Settings(_env_file=None, smtp_url=url).smtp_url == url # type: ignore[call-arg]
+ for url in (
+ "smtp+starttls://mail.example.com",
+ "mail://x",
+ "smtp://",
+ "smtps://user:pw@",
+ "smtp://mail.example.com:abc",
+ "smtp://mail.example.com:70000",
+ "smtp://mail.example.com:0",
+ # The password where urllib reads a port or a bracketed host: with no host, or
+ # after a `/` in it.
+ "smtps://loom:pw-canary",
+ "smtps://loom:pw-canary/x@mail.example.com:465",
+ "smtps://loom:pw@[canary]/x@mail.example.com:465",
+ ):
+ with pytest.raises(ValidationError, match="smtp_url") as refused:
+ Settings(_env_file=None, smtp_url=url) # type: ignore[call-arg]
+ assert "canary" not in str(refused.value)
+
+
+def test_a_from_value_that_names_no_single_address_is_refused_at_load() -> None:
+ from pydantic import ValidationError
+
+ from server.settings import Settings
+
+ for sender in (
+ "",
+ "loom@example.com",
+ "Loom ",
+ '"Acme, Inc." ',
+ "Lööm ",
+ ):
+ assert Settings(_env_file=None, mail_from=sender).mail_from == sender # type: ignore[call-arg]
+ # The four before the last read as two mailboxes, or as another one, when it is sent;
+ # a relay without SMTPUTF8 refuses the last.
+ for sender in (
+ "Loom",
+ "Loom ",
+ "loom@",
+ "loom@example.com\r\nBcc: x@example.com",
+ "Acme, Inc. ",
+ "Acme; Inc ",
+ "a@b ",
+ "a,b@example.com",
+ "Loom ",
+ ):
+ with pytest.raises(ValidationError, match="mail_from"):
+ Settings(_env_file=None, mail_from=sender) # type: ignore[call-arg]
+
+
+class _SMTP:
+ """smtplib's client as `_send` drives it, recording what it was asked."""
+
+ opened: ClassVar[list[tuple[str, int, float]]] = []
+ last: ClassVar[_SMTP]
+ starttls_offered = True
+
+ def __init__(self, host: str, port: int, *, timeout: float, context: Any = None) -> None:
+ self.calls: list[Any] = []
+ type(self).opened.append((host, port, timeout))
+ type(self).last = self
+
+ def __enter__(self) -> _SMTP:
+ return self
+
+ def __exit__(self, *_: object) -> None:
+ return None
+
+ def ehlo(self) -> None:
+ self.calls.append("ehlo")
+
+ def has_extn(self, name: str) -> bool:
+ return self.starttls_offered and name == "starttls"
+
+ def starttls(self, *, context: Any) -> None:
+ self.calls.append("starttls")
+
+ def login(self, user: str, password: str) -> None:
+ self.calls.append(("login", user, password))
+
+ def send_message(self, msg: Any) -> None:
+ self.calls.append("send")
+
+
+def test_smtp_is_reached_within_the_timeout_and_sends_only_over_tls(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(_SMTP, "opened", [])
+ monkeypatch.setattr(smtplib, "SMTP", _SMTP)
+ monkeypatch.setattr(smtplib, "SMTP_SSL", _SMTP)
+ monkeypatch.setattr(settings, "smtp_timeout_seconds", 3.0)
+ msg = invite_mail._message(
+ "m@example.com", inviter="ann", namespace="ns", role="writer", url="u", expires_at=0
+ )
+
+ monkeypatch.setattr(settings, "smtp_url", "smtps://loom%40example.com:p%40ss@mail.example.com")
+ invite_mail._send(msg)
+ assert _SMTP.last.calls == [("login", "loom@example.com", "p@ss"), "send"]
+
+ monkeypatch.setattr(settings, "smtp_url", "smtp://loom:pw@mail.example.com")
+ invite_mail._send(msg)
+ assert _SMTP.last.calls == ["ehlo", "starttls", "ehlo", ("login", "loom", "pw"), "send"]
+ assert _SMTP.opened == [("mail.example.com", 465, 3.0), ("mail.example.com", 587, 3.0)]
+
+ # A server without STARTTLS sees neither the password nor the link, login or not.
+ monkeypatch.setattr(_SMTP, "starttls_offered", False)
+ for url in ("smtp://loom:pw@mail.example.com", "smtp://mail.example.com"):
+ monkeypatch.setattr(settings, "smtp_url", url)
+ with pytest.raises(smtplib.SMTPNotSupportedError):
+ invite_mail._send(msg)
+ assert _SMTP.last.calls == ["ehlo"]
+
+
+class _Rows:
+ def __init__(self) -> None:
+ self.rows: list[dict[str, Any]] = []
+
+ async def query_one(self, sql: str, params: dict[str, Any]) -> dict[str, Any]:
+ return {"v": len(self.rows) + 1} # `next_version`'s read
+
+ async def insert(self, table: str, rows: list[dict[str, Any]], **_: Any) -> None:
+ assert table == "loom.namespace_invites"
+ self.rows.extend(rows)
+
+
+@pytest.mark.asyncio
+async def test_every_write_of_an_invitation_carries_every_column() -> None:
+ """Under FINAL a column a rewrite left out would fall back to its default."""
+ ch = _Rows()
+ made = datetime(2026, 1, 1, tzinfo=UTC)
+ invite = domain.Invite(
+ org="acme",
+ namespace="team",
+ invite_id="h",
+ email="m@example.com",
+ role="writer",
+ created_by="ann",
+ created_at=made,
+ expires_at=1,
+ )
+ await invites_repo.put(invite, ch=ch) # type: ignore[arg-type]
+ await invites_repo.put(invite.accepted("lee"), ch=ch) # type: ignore[arg-type]
+ await invites_repo.put(invite.forgotten(), ch=ch) # type: ignore[arg-type]
+ assert [sorted(r) for r in ch.rows] == [sorted(column_names("namespace_invites"))] * 3
+ assert [(r["state"], r["accepted_by"], r["version"]) for r in ch.rows] == [
+ ("open", "", 1),
+ ("accepted", "lee", 2),
+ ("cancelled", "", 3),
+ ]
+
+
+@pytest.mark.asyncio
+async def test_a_grant_written_under_the_accepters_handle_keeps_the_link_used(
+ world: World,
+) -> None:
+ """The accepter signs in as a verified email; the grant lands under its handle."""
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ world.grant_error, world.grant_lands = BackendUnavailableError("lost reply"), True
+ signed_in("sso@example.com")
+ with pytest.raises(BackendUnavailableError):
+ await accept(secret)
+ assert [g.subject for g, _ in world.grants] == ["sso-handle"]
+ assert world.invites[domain.invite_id(secret)].state == "accepted"
+
+
+@pytest.mark.asyncio
+async def test_a_link_its_maker_was_erased_from_during_a_failed_grant_stays_closed(
+ world: World, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ secret = secret_of((await invite("robin@example.com")).link_path)
+ # A lower role robin holds already, which the link's retry must not answer.
+ world.grants.append(
+ (GrantsCreateInput(org="o", namespace="ns", subject="robin", role="viewer"), None)
+ )
+
+ async def erased_meanwhile(*_a: Any, **_k: Any) -> None:
+ await mod.forget_maker("o", "admin-ann")
+ raise BackendUnavailableError("down")
+
+ monkeypatch.setattr(mod, "store_grant", erased_meanwhile)
+ signed_in("robin")
+ with pytest.raises(BackendUnavailableError):
+ await accept(secret)
+ stored = world.invites[domain.invite_id(secret)]
+ assert (stored.state, stored.created_by, stored.accepted_by) == ("accepted", "", "")
+ with pytest.raises(NotFoundError, match="used, cancelled or expired"):
+ await accept(secret)
+
+
+@pytest.mark.asyncio
+async def test_a_users_erasure_takes_them_off_their_invitations(
+ world: World, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from server.erasure.app import saga_steps
+ from server.identity.app import grants
+
+ async def _zero(*_a: Any, **_k: Any) -> int:
+ return 0
+
+ monkeypatch.setattr(grants, "revoke_subject", _zero)
+ monkeypatch.setattr(grants, "forget_granter", _zero)
+ monkeypatch.setattr(saga_steps.principal_steps, "delete_grant_rows_of_user", _zero)
+ world.maker_roles["user:42"] = Role.ADMIN
+ signed_in("user:42")
+ made = await invite("robin@example.com")
+ await saga_steps._step_revoke_grants_by_user("o", "42")
+ left = world.invites[made.invite_id]
+ assert (left.state, left.created_by) == ("cancelled", "")
diff --git a/tests/unit/test_invites_store_sql.py b/tests/unit/test_invites_store_sql.py
new file mode 100644
index 00000000000..890ac990c26
--- /dev/null
+++ b/tests/unit/test_invites_store_sql.py
@@ -0,0 +1,91 @@
+"""The invitation store's reads, and the two reads that say a person is held, on
+clickhouse-local against the real tables: the newest state of an invitation wins, the
+open list and an erasure's read find what they promise, and a held handle comes back in
+the spelling it is stored under."""
+
+from __future__ import annotations
+
+import time
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+
+from server.identity.domain.invites import Invite
+from server.identity.store import grants as grants_repo
+from server.identity.store import invites as invites_repo
+from server.identity.store import namespaces as namespaces_repo
+from tests.unit.clickhouse_local import CLICKHOUSE, KeptCH, ddl
+
+pytestmark = pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed")
+
+MADE = datetime(2026, 1, 1, tzinfo=UTC)
+LATER = int(time.time()) + 30 * 86400
+
+
+def _invite(
+ invite_id: str,
+ maker: str = "ann",
+ namespace: str = "team",
+ expires_at: int = LATER,
+ created_at: datetime = MADE,
+) -> Invite:
+ return Invite(
+ org="acme",
+ namespace=namespace,
+ invite_id=invite_id,
+ email="m@example.com",
+ role="writer",
+ created_by=maker,
+ created_at=created_at,
+ expires_at=expires_at,
+ )
+
+
+@pytest.mark.asyncio
+async def test_the_newest_state_wins_and_each_read_finds_what_it_promises(
+ tmp_path: Path,
+) -> None:
+ ch = KeptCH(tmp_path, ddl("namespace_invites"))
+ await invites_repo.put(_invite("a"), ch=ch) # type: ignore[arg-type]
+ await invites_repo.put(_invite("a").accepted("lee"), ch=ch) # type: ignore[arg-type]
+ await invites_repo.put(_invite("b"), ch=ch) # type: ignore[arg-type]
+ soon = int(time.time()) + 3600 # past it for the open list, short of the table's TTL
+ await invites_repo.put(_invite("c", expires_at=soon), ch=ch) # type: ignore[arg-type]
+ await invites_repo.put(_invite("d", maker="bea", namespace="other"), ch=ch) # type: ignore[arg-type]
+ newer = _invite("e", created_at=datetime(2026, 1, 2, tzinfo=UTC))
+ await invites_repo.put(newer, ch=ch) # type: ignore[arg-type]
+
+ got = await invites_repo.get("acme", "team", "a", ch=ch) # type: ignore[arg-type]
+ assert got == _invite("a").accepted("lee")
+ assert await invites_repo.get("acme", "other", "a", ch=ch) is None # type: ignore[arg-type]
+ listed = await invites_repo.open_on("acme", "team", soon + 1, 10, ch=ch) # type: ignore[arg-type]
+ assert [i.invite_id for i in listed] == ["e", "b"] # newest first
+ made = await invites_repo.made_by("acme", "ann", ch=ch) # type: ignore[arg-type]
+ assert sorted(i.invite_id for i in made) == ["a", "b", "c", "e"]
+ assert [i.invite_id for i in await invites_repo.made_by("acme", "bea", ch=ch)] == ["d"] # type: ignore[arg-type]
+ assert await invites_repo.made_by("other-org", "ann", ch=ch) == [] # type: ignore[arg-type]
+
+
+@pytest.mark.asyncio
+async def test_a_held_handle_comes_back_as_stored(tmp_path: Path) -> None:
+ ch = KeptCH(
+ tmp_path,
+ ddl("namespaces"),
+ ddl("namespace_grants"),
+ "INSERT INTO loom.namespaces (org, namespace, owner_email, active, created_at,"
+ " updated_at) VALUES ('acme', 'robin', 'Robin', 1, now(), now()),"
+ " ('acme', 'gone', 'Gone', 0, now(), now())",
+ "INSERT INTO loom.namespace_grants (org, namespace, subject, role, status, granted_by,"
+ " version) VALUES ('acme', 'team', 'Carol', 'writer', 'active', 'op', 1),"
+ " ('acme', 'team', 'dan', 'writer', 'pending', 'op', 1)",
+ "INSERT INTO loom.namespace_grants (org, namespace, subject, role, status, granted_by,"
+ " revoked_at, version) VALUES ('acme', 'team', 'eve', 'writer', 'active', 'op',"
+ " now(), 1)",
+ )
+ assert await namespaces_repo.account_handle("acme", "robin", ch=ch) == "Robin" # type: ignore[arg-type]
+ assert await namespaces_repo.account_handle("acme", "gone", ch=ch) is None # type: ignore[arg-type]
+ assert await namespaces_repo.account_handle("other", "robin", ch=ch) is None # type: ignore[arg-type]
+ assert await grants_repo.granted_spelling("acme", "carol", ch=ch) == "Carol" # type: ignore[arg-type]
+ assert await grants_repo.granted_spelling("acme", "dan", ch=ch) is None # type: ignore[arg-type]
+ assert await grants_repo.granted_spelling("acme", "eve", ch=ch) is None # type: ignore[arg-type]
diff --git a/tests/unit/test_repo_maintainers.py b/tests/unit/test_repo_maintainers.py
index 33b33ba8294..6d4ab0c9224 100644
--- a/tests/unit/test_repo_maintainers.py
+++ b/tests/unit/test_repo_maintainers.py
@@ -1234,7 +1234,7 @@ async def _revoke(org: str, ns: str, subject: str, **_k: Any) -> None:
monkeypatch.setattr(grants_repo, "find_active_grant", _find)
monkeypatch.setattr(grants_repo, "insert_row", _insert)
- monkeypatch.setattr(grants_mod, "_enforce_code_ceiling", _no_ceiling)
+ monkeypatch.setattr(grants_mod, "enforce_code_ceiling", _no_ceiling)
monkeypatch.setattr(maintainers, "sync_quietly", _sync)
monkeypatch.setattr(maintainers, "revoke_repo_maintainer", _revoke)
return calls
diff --git a/tests/unit/test_rmt_write_paths.py b/tests/unit/test_rmt_write_paths.py
index e2cfee9de7d..530ad3726ae 100644
--- a/tests/unit/test_rmt_write_paths.py
+++ b/tests/unit/test_rmt_write_paths.py
@@ -156,6 +156,7 @@
"memory_versions": ("view", "memory_versions_mv"),
"namespace_calibration_result": ("gap", "memory"),
"namespace_grants": ("gap", "platform"),
+ "namespace_invites": ("builder", "test_grants_invite.py"),
"namespace_ontology": ("gap", "platform"),
"namespace_policies": ("builder", "test_repository_column_sets_match_schema.py"),
"namespace_types": ("gap", "platform"),
diff --git a/tests/unit/test_schema_baseline.py b/tests/unit/test_schema_baseline.py
index 72a4fe33648..9bba0b77e39 100644
--- a/tests/unit/test_schema_baseline.py
+++ b/tests/unit/test_schema_baseline.py
@@ -188,6 +188,7 @@ def test_the_journal_files() -> None:
"135_knowledge_suite_drafts.sql",
"137_knowledge_reports.sql",
"138_knowledge_suite_required.sql",
+ "139_namespace_invites.sql",
]
diff --git a/tests/unit/test_settings_env_contract.py b/tests/unit/test_settings_env_contract.py
index a0d5e4d6d57..ffdca710964 100644
--- a/tests/unit/test_settings_env_contract.py
+++ b/tests/unit/test_settings_env_contract.py
@@ -103,6 +103,8 @@ def _bounded(f: FieldInfo, value: float) -> bool:
"cell_router_token": "lcr_" + "0" * 128,
"router_operator_sha256": "0" * 64,
"router_operator_token": "lco_" + "0" * 128,
+ "smtp_url": "smtps://mail.example:465",
+ "mail_from": "Loom ",
# The four other code_git_proxy_* settings load only beside it, and the bundle for
# the proxy's own certificate only beside an https one.
"code_git_proxy_url": "https://proxy.example:8443",
diff --git a/tests/unit/test_settings_repr_masks_secrets.py b/tests/unit/test_settings_repr_masks_secrets.py
index 06c18e18867..86d0b7df0da 100644
--- a/tests/unit/test_settings_repr_masks_secrets.py
+++ b/tests/unit/test_settings_repr_masks_secrets.py
@@ -27,6 +27,7 @@
("code_repos_json", f'[{{"namespace": "n", "github_token": "{_SECRET}"}}]'),
("otel_exporter_otlp_headers", f"Authorization=Bearer {_SECRET}"),
("rerank_endpoints_json", f'{{"gw": "https://user:{_SECRET}@rerank.example/v1"}}'),
+ ("smtp_url", f"smtps://loom:{_SECRET}@mail.example:465"),
],
)
def test_secret_fields_are_masked(field: str, value: str) -> None:
diff --git a/tests/unit/test_sharing.py b/tests/unit/test_sharing.py
index 2e23cc9b501..e496e3eb2bc 100644
--- a/tests/unit/test_sharing.py
+++ b/tests/unit/test_sharing.py
@@ -200,6 +200,19 @@ def test_a_group_grant_on_a_parent_reaches_its_child(org_state: dict[str, Any])
assert _shared(_user("alice")) == ["col-q3", "col-q3-docs"]
+def test_a_subjects_grants_alone_reach_a_collection_through_a_group_and_a_parent(
+ org_state: dict[str, Any],
+) -> None:
+ """What an invitation's maker holds: the role `sharing.roles` reads, with no token."""
+ from server.auth.authz import subject_grant_role
+
+ org_state["grants"] = {"group:finance": {"col-q3": 3}}
+ role = asyncio.run(subject_grant_role(ORG, "col-q3-docs", "user:alice"))
+ assert role is Role.ADMIN
+ assert asyncio.run(subject_grant_role(ORG, "col-q3-docs", "user:bob")) is None
+ assert asyncio.run(subject_grant_role(ORG, "col-gone", "user:alice")) is None
+
+
def test_the_best_role_of_every_principal_wins(org_state: dict[str, Any]) -> None:
org_state["grants"] = {"group:finance": {"col-q3": 1}, "user:alice": {"col-q3-docs": 2}}
assert _role(_user("alice"), "col-q3-docs") is Role.WRITER
@@ -635,10 +648,10 @@ def test_a_grant_to_a_principal_in_another_case_is_refused(subject: str) -> None
"""In another case, or after a `/` (the shape of an end user's revocation
key): no token carries such a subject, so no grant names one."""
from server.core.errors import ValidationError
- from server.identity.app.grants import _enforce_principal_target
+ from server.identity.app.grants import enforce_principal_target
with pytest.raises(ValidationError, match="well-formed principal"):
- _enforce_principal_target("col-hr", subject)
+ enforce_principal_target("col-hr", subject)
@pytest.mark.parametrize(
@@ -1208,11 +1221,11 @@ def test_a_grant_to_everyone_reaches_every_member_of_the_org(org_state: dict[str
def test_everyone_holds_grants_on_collections_only_and_no_token_is_it() -> None:
from server.core.errors import ValidationError
from server.core.principals import is_reserved_subject
- from server.identity.app.grants import _enforce_principal_target
+ from server.identity.app.grants import enforce_principal_target
- _enforce_principal_target("col-hr", "everyone")
+ enforce_principal_target("col-hr", "everyone")
with pytest.raises(ValidationError, match="collections only"):
- _enforce_principal_target("team", "everyone")
+ enforce_principal_target("team", "everyone")
assert is_reserved_subject("Everyone"), "no token, in any case, is everyone"
diff --git a/tests/unit/test_signup_name_in_use.py b/tests/unit/test_signup_name_in_use.py
index 58c35b7ab67..5875a8a22db 100644
--- a/tests/unit/test_signup_name_in_use.py
+++ b/tests/unit/test_signup_name_in_use.py
@@ -481,6 +481,18 @@ def _held(*rows: str) -> bool:
" VALUES ('dev', 'team', 'kim', {flag}, 1)",
("false", "true"),
),
+ (
+ "INSERT INTO loom.namespace_invites (org, namespace, invite_id, role, created_by,"
+ " created_at, expires_at, state) VALUES ('dev', 'team', 'i', 'writer',"
+ " 'kim', now64(3), toUInt32(now()) + 3600, {flag})",
+ ("'open'", "'cancelled'"),
+ ),
+ (
+ "INSERT INTO loom.namespace_invites (org, namespace, invite_id, role, created_by,"
+ " created_at, expires_at) VALUES ('dev', 'team', 'i', 'writer',"
+ " 'kim', now64(3), toUInt32(now()) {flag})",
+ ("+ 3600", "- 1"),
+ ),
(
"INSERT INTO loom.sso_links (email, org, namespace, linked, version)"
" VALUES ('kim@x.test', 'dev', 'team', {flag}, 1)",