From 47210f602b2e4638f6e81096026a495faf99ac67 Mon Sep 17 00:00:00 2001
From: Lareb Zafar
Date: Fri, 4 Dec 2026 20:48:22 +0530
Subject: [PATCH 01/28] grants: invite a person to a namespace by handle or
email, with a single-use link
Co-Authored-By: Claude Opus 5.5
Signed-off-by: Lareb Zafar
---
docs/architecture/storage-layout.md | 1 +
docs/reference/configuration.md | 2 +
loom.example.yaml | 4 +
schemas/loom-settings.schema.json | 5 +
schemas/migrations/123_namespace_invites.sql | 28 ++
schemas/schema.sql | 21 ++
server/auth/grant_claims.py | 11 +-
server/erasure/store/census.py | 5 +
server/identity/api/models_grants.py | 77 +++++
server/identity/api/ops_grants.py | 68 +++++
server/identity/app/grants.py | 31 ++-
server/identity/app/invite_mail.py | 83 ++++++
server/identity/app/invites.py | 222 +++++++++++++++
server/identity/domain/invites.py | 85 ++++++
server/identity/store/invites.py | 61 ++++
server/identity/store/namespaces.py | 17 ++
server/settings/_env.py | 2 +
server/settings/catalog.py | 13 +
tests/integration/test_grants_invite.py | 111 ++++++++
tests/unit/test_grants_invite.py | 279 +++++++++++++++++++
20 files changed, 1116 insertions(+), 10 deletions(-)
create mode 100644 schemas/migrations/123_namespace_invites.sql
create mode 100644 server/identity/app/invite_mail.py
create mode 100644 server/identity/app/invites.py
create mode 100644 server/identity/domain/invites.py
create mode 100644 server/identity/store/invites.py
create mode 100644 tests/integration/test_grants_invite.py
create mode 100644 tests/unit/test_grants_invite.py
diff --git a/docs/architecture/storage-layout.md b/docs/architecture/storage-layout.md
index bbbccbed42c..b15edd027b6 100644
--- a/docs/architecture/storage-layout.md
+++ b/docs/architecture/storage-layout.md
@@ -934,6 +934,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 | no content | 1 | an invitation read by `(org, namespace, invite_id)` when its link is accepted or cancelled, and the open ones when a namespace's members are shown; 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` |
diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md
index 3342f383c83..7b6b611e85f 100644
--- a/docs/reference/configuration.md
+++ b/docs/reference/configuration.md
@@ -136,6 +136,8 @@ 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 an invitation is emailed through: `smtps://user:password@host:465` (TLS from the start) or `smtp://user:password@host:587` (STARTTLS, which a login requires). Empty: no email is sent, and whoever makes an invitation sends its link. |
+| `LOOM_MAIL_FROM` | `str` | `''` | | The From address of an invitation email, e.g. `Loom `. Empty sends none, as does an empty smtp_url or public_base_url (the link needs 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/loom.example.yaml b/loom.example.yaml
index e70ed7853ef..3e4e7cc3338 100644
--- a/loom.example.yaml
+++ b/loom.example.yaml
@@ -883,6 +883,10 @@ settings:
# Default org for self-signed tokens. [restart]
# self_signup_org: "dev"
+ # The From address of an invitation email, e.g. `Loom `. Empty sends
+ # none, as does an empty smtp_url or public_base_url (the link needs it). [restart]
+ # mail_from: ""
+
# 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 985d0bd043f..d4b67baf3a7 100644
--- a/schemas/loom-settings.schema.json
+++ b/schemas/loom-settings.schema.json
@@ -4065,6 +4065,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 `. Empty sends none, as does an empty smtp_url or public_base_url (the link needs it)."
+ },
"max_request_bytes": {
"default": 33554432,
"type": "integer",
diff --git a/schemas/migrations/123_namespace_invites.sql b/schemas/migrations/123_namespace_invites.sql
new file mode 100644
index 00000000000..d613be78470
--- /dev/null
+++ b/schemas/migrations/123_namespace_invites.sql
@@ -0,0 +1,28 @@
+-- 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. 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, grants.cancel_invite with `state = 'cancelled'`. 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 '',
+ changed_at DateTime64(3, 'UTC'),
+ 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 312e196b7fa..865cd96f7e7 100644
--- a/schemas/schema.sql
+++ b/schemas/schema.sql
@@ -3393,6 +3393,27 @@ 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 '',
+ `changed_at` DateTime64(3, 'UTC'),
+ `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/server/auth/grant_claims.py b/server/auth/grant_claims.py
index 7092f532bdd..fb2a22aa5a9 100644
--- a/server/auth/grant_claims.py
+++ b/server/auth/grant_claims.py
@@ -17,7 +17,8 @@
`hand_down_lineage`); then an address's sign-up claim (`self_signup.email_claim`);
then an org's collection tree or a SCIM group; then a subject's repository claim
(`maintainers.repo_change`), the repository's admins and the namespaces'
-admins, or the trusts; then a bot or a grant (several sorted by namespace).
+admins, or the trusts; then an invitation (`invite_change`); 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.
"""
@@ -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/erasure/store/census.py b/server/erasure/store/census.py
index 1e0ce762ad3..85c458bea09 100644
--- a/server/erasure/store/census.py
+++ b/server/erasure/store/census.py
@@ -747,6 +747,11 @@ def owner(self, scope_type: str) -> str | None:
"loom.oauth_claims": "auth plane: no code path writes it; never holds memory content.",
"loom.grant_claims": "auth plane: no code path writes it; never holds memory content.",
"loom.service_accounts": "auth plane: service-account definitions.",
+ "loom.namespace_invites": (
+ "auth plane: invitations to a namespace (the address invited, a role, who made and "
+ "who accepted it; the link's secret only as a SHA-256), dropped a week after the "
+ "link expires; no memory content."
+ ),
"loom.user_state": "per-subject UI state (default namespace).",
# -- ledgers of the erasure itself, kept by design ----------
"loom.erasure_requests": "the erasure ledger; scope_value names the scope, 90-day TTL.",
diff --git a/server/identity/api/models_grants.py b/server/identity/api/models_grants.py
index c91c2d480d5..d64bd1d9e8a 100644
--- a/server/identity/api/models_grants.py
+++ b/server/identity/api/models_grants.py
@@ -210,3 +210,80 @@ class GrantsUnshareAgentOutput(BaseModel):
revoked: bool
# When the revoke was written (UTC); None when nothing was revoked.
revoked_at: datetime | None = None
+
+
+class GrantsInviteInput(BaseModel):
+ org: str
+ namespace: str
+ # The person to give `role`: a login handle or an email. An account that signs in
+ # under it (by its handle or a verified email) is granted the role at once; an email
+ # no account holds gets an invitation link; a handle no account holds is refused.
+ 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": an account holds `to` and now has the role; "invited": no account
+ # holds the email, and `link_path` opens the invitation.
+ outcome: Literal["granted", "invited"]
+ role: GrantRoleStr
+ # On "granted", the login handle the grant is written under.
+ 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 = ""
+ # `link_path` on the server's public_base_url; "" when that is unset.
+ url: str = ""
+ # On "invited": when the link stops working (UTC), seven days on.
+ expires_at: datetime | None = None
+ # On "invited": the link was emailed to `to` (the server has mail settings).
+ emailed: bool = False
+
+
+class GrantsListInvitesInput(BaseModel):
+ 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
+
+
+class GrantsListInvitesOutput(BaseModel):
+ # The namespace's invitations not yet accepted, cancelled or expired, newest first;
+ # at most 200.
+ rows: list[_InviteEntry]
+
+
+class GrantsCancelInviteInput(BaseModel):
+ org: str
+ namespace: str
+ 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):
+ 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)
+
+
+class GrantsAcceptInviteOutput(BaseModel):
+ namespace: str
+ # The caller's role on the namespace now: the invitation's, or a higher one they held.
+ role: GrantRoleStr
diff --git a/server/identity/api/ops_grants.py b/server/identity/api/ops_grants.py
index 002ec3400f9..aac8bd60fb6 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,12 @@
handle_grants_pending_for_me,
handle_grants_revoke,
)
+from server.identity.app.invites import (
+ handle_grants_accept_invite,
+ handle_grants_cancel_invite,
+ handle_grants_invite,
+ handle_grants_list_invites,
+)
from server.operations.base import Operation, Role
grants_create = Operation(
@@ -116,6 +130,56 @@
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,
+)
+
+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 finds the link used and answers 404.
+ idempotent=False,
+ required_role=Role.VIEWER,
+ audit=True,
+ skip_namespace_authz=True,
+)
+
OPERATIONS: list[Operation] = [
grants_create,
@@ -125,4 +189,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..09b038babd3 100644
--- a/server/identity/app/grants.py
+++ b/server/identity/app/grants.py
@@ -190,14 +190,19 @@ async def handle_grants_create(input: GrantsCreateInput) -> GrantsCreateOutput:
async def create_grant(
- input: GrantsCreateInput, may_replace: Callable[[GrantState], None] | None = None
+ input: GrantsCreateInput,
+ may_replace: Callable[[GrantState], None] | None = None,
+ *,
+ issuer: str | None = None,
) -> 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."""
+ not write over, checked on the row read under the grant's claim. `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):
- now = await _create_grant(input, may_replace)
+ now = await _create_grant(input, may_replace, issuer)
return GrantsCreateOutput(
org=input.org,
namespace=input.namespace,
@@ -208,7 +213,9 @@ async def create_grant(
async def _create_grant(
- input: GrantsCreateInput, may_replace: Callable[[GrantState], None] | None
+ input: GrantsCreateInput,
+ may_replace: Callable[[GrantState], None] | None,
+ issuer: str | None = None,
) -> datetime:
"""`grants.create`'s write and what follows it; returns when it was granted."""
# A grant to a verified email is written under its account's login handle, so the
@@ -217,7 +224,7 @@ async def _create_grant(
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.
@@ -228,21 +235,24 @@ async def _create_grant(
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 +260,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."""
@@ -267,7 +278,9 @@ async def _write_grant(
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,
diff --git a/server/identity/app/invite_mail.py b/server/identity/app/invite_mail.py
new file mode 100644
index 00000000000..1265843c9d4
--- /dev/null
+++ b/server/identity/app/invite_mail.py
@@ -0,0 +1,83 @@
+"""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 datetime import UTC, datetime
+from email.message import EmailMessage
+from urllib.parse import unquote, urlsplit
+
+from server.core.logging_config import log_value
+from server.settings import settings
+
+log = logging.getLogger(__name__)
+
+_TIMEOUT_S = 10
+
+
+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
+ msg["To"] = to
+ msg["Subject"] = f"{inviter} invited you to {namespace} on Loom"
+ msg.set_content(
+ f"{inviter} invited you to the Loom namespace {namespace} as a {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=_TIMEOUT_S)
+ elif u.scheme == "smtp":
+ client = smtplib.SMTP(host, u.port or 587, timeout=_TIMEOUT_S)
+ else:
+ raise ValueError("smtp_url must start with smtp:// or smtps://")
+ with client:
+ if u.scheme == "smtp":
+ client.ehlo()
+ if client.has_extn("starttls"):
+ client.starttls(context=tls)
+ client.ehlo()
+ elif u.username:
+ # The password is never sent in the clear.
+ raise smtplib.SMTPNotSupportedError("the server offers no STARTTLS for the login")
+ if u.username:
+ client.login(unquote(u.username), unquote(u.password or ""))
+ client.send_message(msg)
+
+
+async def send_invite(
+ to: str, *, inviter: str, namespace: str, role: str, url: str, expires_at: int
+) -> bool:
+ """Email the link to `to`; True when the mail server took it."""
+ if not (to and can_send()):
+ return False
+ 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
+ )
+ await asyncio.to_thread(_send, msg)
+ except Exception as e: # noqa: BLE001 — a failed email leaves the link to copy
+ log.warning("invite mail: not sent to %s: %s", log_value(repr(to)), 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..0daa15317a5
--- /dev/null
+++ b/server/identity/app/invites.py
@@ -0,0 +1,222 @@
+"""grants.{invite,list_invites,cancel_invite,accept_invite} handlers.
+
+`grants.invite` gives a person a role by what an admin knows of them. An account
+that signs in under the handle or verified email is granted at once. An email no
+account holds gets an invitation: a link whose secret only its hash is kept of,
+emailed when the server has mail settings, which gives whoever opens it, once, the
+role, 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. A handle no account holds is refused, so a typo is never kept as a grant
+for whoever signs up under it later.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import re
+import time
+from datetime import UTC, datetime
+
+from server.auth.grant_claims import invite_change
+from server.core.errors import GrantWouldDowngradeError, NotFoundError, ValidationError
+from server.core.principals import SERVICE_ACCOUNT, has_aliases, is_reserved_subject
+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,
+ create_grant,
+)
+from server.identity.domain import invites as domain
+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
+from server.settings import settings
+
+# The open invitations a namespace lists.
+_LISTED = 200
+_EMAIL = re.compile(r"[^@\s]+@[^@\s]+\.[^@\s]+")
+_GONE = "this invitation link is used, cancelled or expired: ask for a new one"
+
+
+def _role(value: str) -> GrantRoleStr:
+ """A role read back from a row written from a GrantRoleStr."""
+ return next(r for r in GRANT_ROLES if r == value)
+
+
+def _caller() -> str:
+ from server.auth.context import current_auth
+
+ auth = current_auth()
+ return str(auth.subject) if auth is not None and auth.subject else "admin"
+
+
+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) or is_reserved_subject(person) or person.startswith(SERVICE_ACCOUNT):
+ 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`: its handle, or the handle a
+ verified email ties to; None when no account does."""
+ from server.auth.aliases import canonical_subject
+
+ subject = await canonical_subject(org, person)
+ if subject != person or await namespaces_repo.has_account(org, person):
+ return subject
+ return None
+
+
+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:
+ await create_grant(
+ GrantsCreateInput(
+ org=input.org, namespace=input.namespace, subject=person, role=input.role
+ )
+ )
+ return GrantsInviteOutput(outcome="granted", role=input.role, subject=subject)
+ 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 _EMAIL.fullmatch(person):
+ raise ValidationError(f"{person!r} is not an email address")
+ await _enforce_code_ceiling(input.org, input.namespace, input.role)
+ return await _invite(input, person.lower())
+
+
+async def _invite(input: GrantsInviteInput, email: str) -> GrantsInviteOutput:
+ 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=_caller(),
+ created_at=now,
+ expires_at=int(now.timestamp()) + domain.TTL_S,
+ )
+ 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 = await invite_mail.send_invite(
+ email,
+ 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,
+ )
+
+
+async def handle_grants_list_invites(input: GrantsListInvitesInput) -> GrantsListInvitesOutput:
+ rows = await invites_repo.open_on(input.org, input.namespace, int(time.time()), _LISTED)
+ return GrantsListInvitesOutput(
+ rows=[
+ _InviteEntry(
+ invite_id=r.invite_id,
+ email=r.email,
+ role=_role(r.role),
+ created_by=r.created_by,
+ created_at=r.created_at,
+ expires_at=datetime.fromtimestamp(r.expires_at, UTC),
+ )
+ for r in rows
+ ]
+ )
+
+
+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 or not invite.is_open(int(time.time())):
+ return GrantsCancelInviteOutput(cancelled=False)
+ await invites_repo.put(invite.settled("cancelled", _caller(), datetime.now(UTC)))
+ return GrantsCancelInviteOutput(cancelled=True)
+
+
+def _accepter(org: str) -> str:
+ """The signed-in person accepting: a service account, a principal 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 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)
+ async with invite_change(input.org, input.namespace, invite_id):
+ invite = await invites_repo.get(input.org, input.namespace, invite_id)
+ if invite is None or not invite.is_open(int(time.time())):
+ raise NotFoundError(_GONE)
+ if not await namespaces_repo.is_active(input.org, input.namespace):
+ raise NotFoundError(_GONE)
+ # Spent before the grant, under the claim: a link never lets two people in.
+ await invites_repo.put(invite.settled("accepted", subject, datetime.now(UTC)))
+ try:
+ role = await _grant(invite, subject)
+ except BaseException:
+ # Still under the claim, so no one took it since: a failed grant leaves the
+ # link open for another try. A failed put-back leaves it used, never open twice.
+ with contextlib.suppress(Exception):
+ await invites_repo.put(invite)
+ raise
+ return GrantsAcceptInviteOutput(namespace=input.namespace, role=role)
+
+
+async def _grant(invite: domain.Invite, subject: str) -> GrantRoleStr:
+ """The invitation's role for `subject`, stamped as granted by its maker; a higher
+ role they hold already stands."""
+ role = _role(invite.role)
+ try:
+ await create_grant(
+ GrantsCreateInput(
+ org=invite.org, namespace=invite.namespace, subject=subject, role=role
+ ),
+ issuer=invite.created_by,
+ )
+ except GrantWouldDowngradeError as e:
+ return _role(str(e.extra["current_role"]))
+ return role
diff --git a/server/identity/domain/invites.py b/server/identity/domain/invites.py
new file mode 100644
index 00000000000..1247de0e653
--- /dev/null
+++ b/server/identity/domain/invites.py
@@ -0,0 +1,85 @@
+"""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.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import secrets
+from dataclasses import asdict, dataclass, replace
+from datetime import datetime
+from typing import Any, Literal
+from urllib.parse import quote
+
+from server.core.datetimes import as_aware_utc
+
+InviteState = Literal["open", "accepted", "cancelled"]
+
+# How long a link stays open.
+TTL_S = 7 * 86400
+
+
+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 path that accepts it. The secret is the fragment, which a browser
+ never sends to a server or puts in a Referer."""
+ return f"/invite?org={quote(org, safe='')}&namespace={quote(namespace, safe='')}#{secret}"
+
+
+@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: InviteState = "open"
+ accepted_by: str = ""
+ changed_at: datetime | None = None
+
+ def is_open(self, now: int) -> bool:
+ return self.state == "open" and now < self.expires_at
+
+ def settled(self, state: InviteState, by: str, at: datetime) -> Invite:
+ return replace(
+ self, state=state, accepted_by=by if state == "accepted" else "", changed_at=at
+ )
+
+ def row(self) -> dict[str, Any]:
+ out = asdict(self)
+ out["changed_at"] = self.changed_at or self.created_at
+ return out
+
+ @classmethod
+ def from_row(cls, r: dict[str, Any]) -> Invite:
+ state = str(r.get("state") or "open")
+ return cls(
+ org=str(r["org"]),
+ namespace=str(r["namespace"]),
+ invite_id=str(r["invite_id"]),
+ email=str(r.get("email") or ""),
+ role=str(r["role"]),
+ created_by=str(r.get("created_by") or ""),
+ created_at=as_aware_utc(r["created_at"]),
+ expires_at=int(r["expires_at"]),
+ state="accepted"
+ if state == "accepted"
+ else "cancelled"
+ if state == "cancelled"
+ else "open",
+ accepted_by=str(r.get("accepted_by") or ""),
+ changed_at=as_aware_utc(r.get("changed_at")),
+ )
diff --git a/server/identity/store/invites.py b/server/identity/store/invites.py
new file mode 100644
index 00000000000..8f46143a2cb
--- /dev/null
+++ b/server/identity/store/invites.py
@@ -0,0 +1,61 @@
+"""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, changed_at"
+)
+
+
+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]
diff --git a/server/identity/store/namespaces.py b/server/identity/store/namespaces.py
index aae3c35355d..f4533c775d6 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
@@ -92,6 +93,22 @@ async def is_active(org: str, namespace: str, *, ch: _CHClient | None = None) ->
return row is not None
+async def has_account(org: str, subject: str, *, ch: _CHClient | None = None) -> bool:
+ """Does an active account of `org` sign in as `subject` (its login handle, in any
+ case)? Read past an account another replica just made."""
+ 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 ifNull(active, true) = true
+ AND owner_email != '' AND lower(owner_email) = lower({sub:String})
+ LIMIT 1
+ """,
+ params={"org": org, "sub": subject},
+ )
+ return row is not None
+
+
async def labels(
org: str, namespaces: list[str], *, ch: _CHClient | None = None
) -> dict[str, dict[str, str]]:
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 898f926e553..b8d382a89d0 100644
--- a/server/settings/catalog.py
+++ b/server/settings/catalog.py
@@ -460,6 +460,14 @@ def trusted_issuers(self) -> set[str]:
# Default org for self-signed tokens.
self_signup_org: str = "dev"
+ # The mail server an invitation is emailed through: `smtps://user:password@host:465`
+ # (TLS from the start) or `smtp://user:password@host:587` (STARTTLS, which a login
+ # requires). Empty: no email is sent, and whoever makes an invitation sends its link.
+ smtp_url: str = ""
+ # The From address of an invitation email, e.g. `Loom `. Empty
+ # sends none, as does an empty smtp_url or public_base_url (the link needs it).
+ mail_from: str = ""
+
# 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).
@@ -6570,9 +6578,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/tests/integration/test_grants_invite.py b/tests/integration/test_grants_invite.py
new file mode 100644
index 00000000000..e31f0f68242
--- /dev/null
+++ b/tests/integration/test_grants_invite.py
@@ -0,0 +1,111 @@
+"""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 urllib.parse import urlsplit
+
+import httpx
+
+from tests.integration._resources import unique_org
+
+
+def _person_token(*, org: str, subject: str, namespaces: list[str], roles: list[str]) -> str:
+ from server.auth.jwt import mint_token
+
+ return mint_token(
+ subject=subject,
+ org=org,
+ namespaces=namespaces,
+ roles=roles,
+ ttl_seconds=600,
+ is_service_account=False,
+ )
+
+
+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,
+) -> None:
+ org = unique_org("invite")
+ ns = f"ns-{uuid.uuid4().hex[:8]}"
+ admin = _person_token(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": "michael@example.com", "role": "writer"},
+ )
+ assert r.status_code == 200, r.text
+ made = r.json()
+ assert made["outcome"] == "invited"
+ secret = urlsplit(made["link_path"]).fragment
+ listed = _post(control_plane_url, admin, "grants.list_invites", {"org": org, "namespace": ns})
+ assert [row["email"] for row in listed.json()["rows"]] == ["michael@example.com"]
+
+ # The person signs in under a handle that is not the email.
+ person = _person_token(org=org, subject="mlex", 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"] == "mlex"]
+ assert [(g["role"], g["granted_by"]) for g in mine] == [("writer", "ann-admin")]
+
+ # Spent: a second open of the link admits nobody, and it is no longer listed.
+ other = _person_token(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) -> None:
+ org = unique_org("invite")
+ ns = f"ns-{uuid.uuid4().hex[:8]}"
+ admin = _person_token(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) -> None:
+ org = unique_org("invite")
+ ns = f"ns-{uuid.uuid4().hex[:8]}"
+ home = f"home-{ns}"
+ person = _person_token(org=org, subject="mlex", namespaces=[home], roles=["admin"])
+ _register(control_plane_url, person, org, home, "mlex")
+ admin = _person_token(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": "MLex", "role": "viewer"},
+ )
+ assert r.status_code == 200, r.text
+ assert (r.json()["outcome"], r.json()["link_path"]) == ("granted", "")
diff --git a/tests/unit/test_grants_invite.py b/tests/unit/test_grants_invite.py
new file mode 100644
index 00000000000..965947eff30
--- /dev/null
+++ b/tests/unit/test_grants_invite.py
@@ -0,0 +1,279 @@
+"""grants.invite gives a person a role by their handle or email: a grant when an account
+signs in under it, an invitation link for an email no account holds, and a refusal for
+a handle no account holds. 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 contextlib
+import time
+from collections.abc import AsyncIterator, Iterator
+from dataclasses import replace
+from typing import Any
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+
+from server.auth.context import set_current_auth
+from server.auth.jwt import AuthInfo
+from server.core.errors import (
+ BackendUnavailableError,
+ GrantWouldDowngradeError,
+ 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.operations.base import Role
+from server.settings import settings
+
+
+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] = []
+ self.accounts = {"mlex"}
+ self.verified = {"sso@example.com": "sso-handle"}
+ self.grants: list[tuple[GrantsCreateInput, str | None]] = []
+ self.grant_error: BaseException | None = None
+ self.mail: list[dict[str, Any]] = []
+
+
+@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)
+
+ async def get(org: str, namespace: str, invite_id: str, **_: Any) -> domain.Invite | None:
+ found = w.invites.get(invite_id)
+ 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 has_account(org: str, subject: str, **_: Any) -> bool:
+ return subject.lower() in w.accounts
+
+ async def is_active(org: str, namespace: str, **_: Any) -> bool:
+ return True
+
+ async def canonical(org: str, subject: str, **_: Any) -> str:
+ return w.verified.get(subject.lower(), subject)
+
+ async def create_grant(input: GrantsCreateInput, *_a: Any, issuer: str | None = None) -> None:
+ if w.grant_error is not None:
+ raise w.grant_error
+ w.grants.append((input, issuer))
+
+ async def no_ceiling(*_a: Any, **_k: Any) -> None:
+ return None
+
+ @contextlib.asynccontextmanager
+ async def claimed(*_a: Any) -> AsyncIterator[None]:
+ 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.namespaces_repo, "has_account", has_account)
+ monkeypatch.setattr(mod.namespaces_repo, "is_active", is_active)
+ monkeypatch.setattr("server.auth.aliases.canonical_subject", canonical)
+ monkeypatch.setattr(mod, "create_grant", create_grant)
+ monkeypatch.setattr(mod, "_enforce_code_ceiling", no_ceiling)
+ monkeypatch.setattr(mod, "invite_change", claimed)
+ monkeypatch.setattr(mod.invite_mail, "send_invite", send)
+ signed_in("admin-ann")
+ yield w
+ set_current_auth(None)
+
+
+def signed_in(subject: str, *, org: str = "o", service: bool = False) -> None:
+ set_current_auth(
+ AuthInfo(
+ subject=subject,
+ org=org,
+ namespaces=("ns",),
+ roles=(Role.WRITER,),
+ is_service_account=service,
+ )
+ )
+
+
+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 == "/invite"
+ assert parse_qs(parts.query) == {"org": ["o"], "namespace": ["ns"]}
+ return parts.fragment
+
+
+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("MLex")
+ assert (out.outcome, out.subject, out.link_path) == ("granted", "MLex", "")
+ assert [(g.subject, g.role) for g, _ in world.grants] == [("MLex", "writer")]
+ assert world.invites == {}
+
+
+@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 'mlexx'"):
+ await invite("mlexx")
+ assert world.grants == [] and world.invites == {}
+
+
+@pytest.mark.parametrize("to", ["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.asyncio
+async def test_an_email_no_account_holds_gets_a_link_kept_only_as_its_hash(world: World) -> None:
+ out = await invite("Michael@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) == (
+ "michael@example.com",
+ "writer",
+ "admin-ann",
+ "open",
+ )
+ assert stored.expires_at - time.time() == pytest.approx(domain.TTL_S, abs=5)
+ assert world.mail[0]["to"] == "michael@example.com"
+ listed = await mod.handle_grants_list_invites(GrantsListInvitesInput(org="o", namespace="ns"))
+ assert [r.email for r in listed.rows] == ["michael@example.com"]
+
+
+@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("michael@example.com")).link_path)
+ signed_in("mlex")
+ out = await accept(secret)
+ assert (out.namespace, out.role) == ("ns", "writer")
+ assert [(g.subject, g.role, issuer) for g, issuer in world.grants] == [
+ ("mlex", "writer", "admin-ann")
+ ]
+ assert world.invites[domain.invite_id(secret)].accepted_by == "mlex"
+ 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_a_higher_role_held_already_stands(world: World) -> None:
+ secret = secret_of((await invite("michael@example.com", "viewer")).link_path)
+ world.grant_error = GrantWouldDowngradeError(current_role="admin", requested_role="viewer")
+ signed_in("mlex")
+ 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("michael@example.com")).link_path)
+ world.grant_error = BackendUnavailableError("down")
+ signed_in("mlex")
+ 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_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
+ again = await mod.handle_grants_cancel_invite(
+ GrantsCancelInviteInput(org="o", namespace="ns", invite_id=cancelled)
+ )
+ assert again.cancelled is False
+ signed_in("mlex")
+ 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", "words"),
+ [
+ ("sa:bot", "o", True, "a person"),
+ ("group:eng", "o", False, "a person"),
+ ("mlex", "other", False, "sign in to o"),
+ ],
+)
+@pytest.mark.asyncio
+async def test_only_a_person_of_the_org_accepts(
+ world: World, subject: str, org: str, service: bool, words: str
+) -> None:
+ secret = secret_of((await invite("michael@example.com")).link_path)
+ signed_in(subject, org=org, service=service)
+ with pytest.raises(ValidationError, match=words):
+ await accept(secret)
+ assert world.invites[domain.invite_id(secret)].state == "open"
+
+
+@pytest.mark.asyncio
+async def test_no_mail_settings_send_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
+ sent: list[Any] = []
+ monkeypatch.setattr(invite_mail, "_send", sent.append)
+ monkeypatch.setattr(settings, "smtp_url", "")
+ args = {"inviter": "ann", "namespace": "ns", "role": "writer", "url": "u", "expires_at": 0}
+ assert await invite_mail.send_invite("m@example.com", **args) is False
+ monkeypatch.setattr(settings, "smtp_url", "smtp://mail.example.com")
+ monkeypatch.setattr(settings, "mail_from", "Loom ")
+ monkeypatch.setattr(settings, "public_base_url", "https://loom.example.com")
+ 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()
+ # 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
From 15c46f01eda0f92902a5cffa0252be1277596fd5 Mon Sep 17 00:00:00 2001
From: Lareb Zafar
Date: Fri, 4 Dec 2026 21:04:11 +0530
Subject: [PATCH 02/28] grants: accept an invitation from Namespaces in your
org; SDKs, reference and design docs
Co-Authored-By: Claude Opus 5.5
Signed-off-by: Lareb Zafar
---
docs/architecture/sharing.md | 33 +
docs/features/namespaces-and-sharing.md | 35 +-
docs/reference/operations.md | 6 +-
docs/reference/operations/grants.md | 64 +
docs/reference/schema.md | 3 +-
docs/reference/status.md | 4 +-
frontend/src/App.tsx | 2 +
frontend/src/api/invites.ts | 51 +
frontend/src/lib/boot.ts | 25 +
frontend/src/views/Browse.tsx | 2 +
frontend/src/views/InvitationCard.test.tsx | 81 +
frontend/src/views/InvitationCard.tsx | 91 +
sdk/go/client.gen.go | 79 +
sdk/go/wire/models.gen.go | 84 +-
sdk/python/loom/client.py | 35 +
sdk/python/loom/ops.py | 137 +
sdk/ruby/lib/clickhouse/loom/generated/ops.rb | 30 +-
sdk/rust/src/blocking_operations.rs | 68 +
sdk/rust/src/operations.rs | 72 +
sdk/rust/src/wire_models.rs | 6608 +++++++++--------
sdk/rust/tests/registry_contracts.rs | 79 +
sdk/typescript/src/generated/ops.ts | 71 +-
server/identity/domain/invites.py | 8 +-
server/operations/reach_manifest.py | 16 +
tests/integration/test_grants_invite.py | 4 +-
tests/unit/test_grants_invite.py | 11 +-
26 files changed, 4524 insertions(+), 3175 deletions(-)
create mode 100644 frontend/src/api/invites.ts
create mode 100644 frontend/src/views/InvitationCard.test.tsx
create mode 100644 frontend/src/views/InvitationCard.tsx
diff --git a/docs/architecture/sharing.md b/docs/architecture/sharing.md
index 9dd427d934f..5231bc7fbac 100644
--- a/docs/architecture/sharing.md
+++ b/docs/architecture/sharing.md
@@ -194,6 +194,31 @@ 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. A login handle an
+account signs in under, or an email verified for one (an SSO account or an `sso_links`
+row), is granted at once through `grants.create`. Any other email 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. 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. A handle no account holds is refused with 404, so a typo is never
+kept as a grant for whoever signs up under that handle later.
+
+`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 or a token of another org is refused.
+It runs under a lease per invitation (`grant_claims.invite_change`) and marks the
+invitation accepted before the grant, so one link never admits two people; a failed grant
+puts it back open. A higher role the caller holds already stands.
+
+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; the dashboard moves it into the tab's session storage at boot, so a single
+sign-on round trip keeps it.
+
## Consistency
Every change to a grant, a group or the tree writes a row to `loom.acl_versions` for its
@@ -370,6 +395,14 @@ 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.
- **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/features/namespaces-and-sharing.md b/docs/features/namespaces-and-sharing.md
index 04d9efa95c0..523fec50eb0 100644
--- a/docs/features/namespaces-and-sharing.md
+++ b/docs/features/namespaces-and-sharing.md
@@ -71,18 +71,29 @@ account, or a service account `sa:`) a role on one namespace: `viewer` rea
`writer` writes, `admin` manages grants and settings. The token carries the org and the
namespaces it may reach; the grant table decides the role.
-| 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. An account's handle, 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. A handle no account holds is refused. |
+| `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, 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. |
+
+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, and gives its role to whoever opens it signed in, under their own
+login handle, as granted by the admin who made it. 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/reference/operations.md b/docs/reference/operations.md
index afcfd662669..60e5267e87c 100644
--- a/docs/reference/operations.md
+++ b/docs/reference/operations.md
@@ -124,7 +124,7 @@ python scripts/codegen/docs_reference.py --check # exit 1 when a region is stal
-387 operations in 43 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores).
+391 operations in 43 groups. Every op is served at `POST /v1/` and 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`, unless it is hidden from MCP; **Audit** marks ops that leave an `audit_log` row.
@@ -376,9 +376,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) | | 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) | | 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) | | 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) | | 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 |
diff --git a/docs/reference/operations/grants.md b/docs/reference/operations/grants.md
index 52365d7121b..7b3c91c31dd 100644
--- a/docs/reference/operations/grants.md
+++ b/docs/reference/operations/grants.md
@@ -8,6 +8,21 @@ Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity
+## `grants.accept_invite`
+
+`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. |
+
## `grants.approve`
Approve (or reject) a pending grant request.
@@ -30,6 +45,20 @@ 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`
+
+`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 | |
+
+| 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 +82,28 @@ 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`
+
+`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 login handle or an email. |
+| `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": an account holds `to` and now has the role; "invited": no account holds the email, and `link_path` opens the invitation. |
+| `role` | `Literal['viewer', 'writer', 'admin']` | |
+| `subject` | `str` | On "granted", the login handle the grant is written under. |
+| `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` | `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), seven days on. |
+| `emailed` | `bool` | On "invited": the link was emailed to `to` (the server has mail settings). |
+
## `grants.list`
List active grants on a namespace — who has access, at which role.
@@ -73,6 +124,19 @@ 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`
+
+`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 invitations not yet accepted, cancelled or expired, newest first; at most 200. |
+
## `grants.pending_for_me`
Every pending request in the namespaces the caller administers, in one statement.
diff --git a/docs/reference/schema.md b/docs/reference/schema.md
index 60356c1f341..d8eddf35dcf 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,
-198 tables, 5 views and 19 materialized views in the `loom` and `loom_telemetry` databases; a `loom_telemetry` object keeps its database prefix.
+199 tables, 5 views and 19 materialized views in the `loom` and `loom_telemetry` databases; a `loom_telemetry` object keeps its database prefix.
#### Tables
@@ -291,6 +291,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 760593c1673..74bac516a0d 100644
--- a/docs/reference/status.md
+++ b/docs/reference/status.md
@@ -25,7 +25,7 @@ serves is in the [MCP reference](./mcp.md#toolsets).
-387 operations, 273 of them experimental.
+391 operations, 277 of them experimental.
| Group | Stable | Experimental |
| --- | --- | --- |
@@ -47,7 +47,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/App.tsx b/frontend/src/App.tsx
index 52c2b393172..709ec2912c5 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -34,6 +34,7 @@ import {
provisionalNamespace,
rememberKinds,
sameAccount,
+ takeInviteLink,
takeLinkToken,
takeSignInStarted,
takeSsoAsk,
@@ -310,6 +311,7 @@ export default function App() {
// and scrubbed before anything can fail. The return to the page its sign-in started on
// is a chunk of its own, and boot goes on without it.
link = takeLinkToken();
+ takeInviteLink();
const started = takeSignInStarted(link?.nonce ?? null);
if (takeSsoAsk()) setSsoAsked(true);
if (link) {
diff --git a/frontend/src/api/invites.ts b/frontend/src/api/invites.ts
new file mode 100644
index 00000000000..55a344a46bd
--- /dev/null
+++ b/frontend/src/api/invites.ts
@@ -0,0 +1,51 @@
+// Inviting a person to a namespace: by a login handle or verified email they are granted at
+// once; by any other email they get a single-use link, emailed when the server can send mail.
+// 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;
+ /** `/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;
+}
+
+export function invite(id: Scope, to: string, role: GrantRole): Promise {
+ return post("/v1/grants.invite", { org: id.org, namespace: id.namespace, to, role });
+}
+
+export function listInvites(id: Scope): Promise<{ rows: OpenInvite[] }> {
+ 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}`;
+}
diff --git a/frontend/src/lib/boot.ts b/frontend/src/lib/boot.ts
index 86cfb1b192d..0a917cd2f49 100644
--- a/frontend/src/lib/boot.ts
+++ b/frontend/src/lib/boot.ts
@@ -145,6 +145,31 @@ export function takeLinkToken(): { token: string | null; atRoot: boolean; nonce:
return { token, atRoot: fromHash && !qs && (pathname === "/" || pathname === "/me"), nonce };
}
+/** The session key for an invitation link's `{ secret, org, namespace }`: boot moves it out
+ * of the address (`/spaces#invite=&org=…&namespace=…`) before the sign-in gate, so a
+ * single sign-on's round trip keeps it, and Namespaces in your org offers to accept it. */
+export const INVITE_LINK = "loom_invite_v1";
+
+export interface InviteLink {
+ secret: string;
+ org: string;
+ namespace: string;
+}
+
+/** Take an invitation link out of the address into this tab's session. */
+export function takeInviteLink(): void {
+ const { hash, pathname, search } = window.location;
+ if (!hash.startsWith("#invite=")) return;
+ history.replaceState(history.state, "", pathname + search);
+ const p = new URLSearchParams(hash.slice(1));
+ const link = { secret: p.get("invite"), org: p.get("org"), namespace: p.get("namespace") };
+ try {
+ if (link.secret && link.org && link.namespace) sessionStorage.setItem(INVITE_LINK, JSON.stringify(link));
+ } catch {
+ /* no session storage: the link is opened again once signed in */
+ }
+}
+
/** Namespace kinds from the last membership answer this browser saw, so a
* deep link can tell a memory namespace from a code or QA one before
* list_mine answers again (a memory view never mounts on a code or tracker namespace;
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/InvitationCard.test.tsx b/frontend/src/views/InvitationCard.test.tsx
new file mode 100644
index 00000000000..40b02bf1aef
--- /dev/null
+++ b/frontend/src/views/InvitationCard.test.tsx
@@ -0,0 +1,81 @@
+import { cleanup, render, screen } from "../test/rtl";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { acceptInvite } from "../api/invites";
+import { INVITE_LINK, takeInviteLink } from "../lib/boot";
+import { ApiError } from "../lib/errors";
+import { useStore } from "../lib/state";
+import { InvitationCard } from "./InvitationCard";
+
+// An invitation link's secret rides in the fragment; boot moves it into the tab's session so
+// a sign-in keeps it, and the card accepts it as the signed-in person.
+
+vi.mock("../api/invites", () => ({ acceptInvite: vi.fn() }));
+
+beforeEach(() => {
+ sessionStorage.clear();
+ vi.mocked(acceptInvite).mockReset();
+ useStore.setState({ identity: { org: "dev", namespace: "home", agent: "loom-ui" } });
+});
+afterEach(() => cleanup());
+
+describe("takeInviteLink", () => {
+ it("moves the link out of the address into the session", () => {
+ history.replaceState(null, "", "/spaces#invite=s3cret&org=dev&namespace=team%2Falerts");
+ 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("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("accepts as the signed-in person and switches to the namespace", async () => {
+ vi.mocked(acceptInvite).mockResolvedValue({ namespace: "alerts", role: "writer" });
+ 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();
+ });
+
+ it("says why a spent link is refused and offers only Close", async () => {
+ vi.mocked(acceptInvite).mockRejectedValue(
+ new ApiError({
+ status: 404,
+ code: "NOT_FOUND",
+ message: "this invitation link is used, cancelled or expired: ask for a new one",
+ }),
+ );
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(await screen.findByText(/used, cancelled or expired/)).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Accept invitation" })).toBeNull();
+ expect(sessionStorage.getItem(INVITE_LINK)).toBeNull();
+ expect(useStore.getState().identity?.namespace).toBe("home");
+ });
+
+ it("shows nothing without an invitation", () => {
+ render();
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ });
+});
diff --git a/frontend/src/views/InvitationCard.tsx b/frontend/src/views/InvitationCard.tsx
new file mode 100644
index 00000000000..0a9a37dc663
--- /dev/null
+++ b/frontend/src/views/InvitationCard.tsx
@@ -0,0 +1,91 @@
+import { 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 { INVITE_LINK, type InviteLink } from "../lib/boot";
+import { humanizeError } from "../lib/errorWords";
+import { ApiError } from "../lib/errors";
+import { invalidateShared } from "../lib/sharedReads";
+import { useStore } from "../lib/state";
+
+function stashed(): InviteLink | null {
+ 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: no invitation */
+ }
+ return null;
+}
+
+function drop(): void {
+ try {
+ sessionStorage.removeItem(INVITE_LINK);
+ } catch {
+ /* no session storage: nothing was kept */
+ }
+}
+
+/** The invitation link this tab opened (`lib/boot.ts` keeps it through the sign-in), for the
+ * signed-in person to accept. */
+export function InvitationCard() {
+ const [link, setLink] = useState(stashed);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+ // The server refused the link (used, cancelled, expired, or for another org): only Close is left.
+ const [refused, setRefused] = useState(false);
+ const identity = useStore((s) => s.identity);
+ const setIdentity = useStore((s) => s.setIdentity);
+ if (!link) return null;
+
+ const close = () => {
+ drop();
+ setLink(null);
+ };
+ const accept = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ const out = await acceptInvite(link, link.secret);
+ close();
+ toast(`You're a ${out.role} on ${out.namespace}`, "ok");
+ invalidateShared("mine:");
+ if (identity && identity.org === link.org) {
+ setIdentity({ ...identity, namespace: out.namespace });
+ setSavedNamespace(out.namespace);
+ }
+ } catch (e) {
+ if (e instanceof ApiError && e.status >= 400 && e.status < 500) {
+ drop();
+ setRefused(true);
+ }
+ setError(humanizeError(e));
+ setBusy(false);
+ }
+ };
+
+ return (
+
+
+ You're invited to {link.namespace}
+ {identity && identity.org !== link.org ? ` in ${link.org}` : ""}. Accepting gives the account you're signed in
+ as the role the invitation names.
+