Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(show-page-acl): limited /p admission for group and organization entries (#1600)
Maxdb4d24d08fe0
diff --git a/core/internal_server.py b/core/internal_server.pyindex 987903efd..497bf6599 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -658,46 +658,35 @@ def create_app(@app.post("/internal/show-access/apply")async def _show_access_apply(request: Request) -> Any:- from core.show_pages import ShowPageError, ShowPageStore, show_access_payload+ from core.show_pages import (+ ShowPageError,+ ShowPageStore,+ parse_show_access_apply_request,+ show_access_payload,+ )payload = await _safe_json(request)- required = {- "page_id",- "expected_revision",- "target_access_mode",- "target_share_id",- "target_emails",- }- if (- set(payload) != required- or not isinstance(payload.get("page_id"), str)- or isinstance(payload.get("expected_revision"), bool)- or not isinstance(payload.get("expected_revision"), int)- or payload["expected_revision"] < 0- or not isinstance(payload.get("target_access_mode"), str)- or not (- payload.get("target_share_id") is None- or isinstance(payload.get("target_share_id"), str)- )- or not isinstance(payload.get("target_emails"), list)- or any(not isinstance(email, str) for email in payload["target_emails"])- ):+ parsed = parse_show_access_apply_request(payload)+ if parsed is None:return JSONResponse(status_code=400,content={"ok": False, "error": "invalid_show_access_apply_request"},)- page_id = payload["page_id"]+ page_id = parsed["page_id"]def _apply() -> dict[str, Any]:store = ShowPageStore()try:- result = store.apply_access(- page_id,- expected_revision=payload["expected_revision"],- target_access_mode=payload["target_access_mode"],- target_share_id=payload["target_share_id"],- target_emails=payload["target_emails"],- )+ apply_kwargs = {+ "expected_revision": parsed["expected_revision"],+ "target_access_mode": parsed["target_access_mode"],+ "target_share_id": parsed["target_share_id"],+ }+ if "target_emails" in parsed:+ apply_kwargs["target_emails"] = parsed["target_emails"]+ else:+ apply_kwargs["target_entries"] = parsed["target_entries"]+ result = store.apply_access(page_id, **apply_kwargs)finally:store.close()if result.show_access.page_id != page_id:diff --git a/core/show_pages.py b/core/show_pages.pyindex c650fb06c..7557d0c9a 100644--- a/core/show_pages.py+++ b/core/show_pages.py@@ -58,6 +58,14 @@ ORGANIZATION_ACCESS_ENTRY_KINDS = (ACCESS_ENTRY_KIND_GROUP,ACCESS_ENTRY_KIND_ORGANIZATION,)+# Active-member roles the show-identity organization block may assert. A+# missing or unknown role is fail-closed for group and organization entries.+SHOW_ACCESS_ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})+# Bound the group list one assertion may claim, so matching a visitor stays a+# bounded amount of work. It is independent of SHOW_ACCESS_GROUP_MAX_COUNT (how+# many groups a page may grant), and the list is never persisted: what outlives+# the match is the single matched entry.+SHOW_ACCESS_VISITOR_GROUP_MAX_COUNT = 256SHOW_ACCESS_EMAIL_MAX_COUNT = 64SHOW_ACCESS_GROUP_MAX_COUNT = 64# Per-kind write caps. "This organization may read" is one switch, so it caps at@@ -194,6 +202,101 @@ class ShowAccess:return tuple(entry for entry in self.entries if entry.kind == kind)+@dataclass(frozen=True)+class ShowAccessVisitor:+ """Identity used to match a Limited ``/p`` audience.++ ``organization_id`` / ``organization_member_id`` / ``organization_role`` /+ ``group_ids`` are the optional show-identity organization block. Absence is+ fail-closed for group and organization entries and never grants them.+ """++ normalized_email: str+ organization_id: str | None = None+ organization_member_id: str | None = None+ organization_role: str | None = None+ group_ids: frozenset[str] = frozenset()++ @property+ def has_organization_block(self) -> bool:+ return bool(+ self.organization_id+ and self.organization_member_id+ and self.organization_role in SHOW_ACCESS_ORGANIZATION_ROLES+ )+++def limited_show_access_grant(+ access: ShowAccess,+ visitor: ShowAccessVisitor,+) -> ShowAccessEntry | None:+ """Return the audience entry that admits a Limited visitor, if any.++ The three kinds are peers and OR-ed: an email hit, a group intersection,+ or active membership of the page's organization. Every hit is read-only;+ this function does not grant HMR, annotations, or Agent. Group and+ organization entries fail closed when the visitor has no organization+ block, including a block for a different organization.++ The matched entry -- not the visitor's membership list -- is what a caller+ persists to re-check a later request: one entry is bounded by the same+ per-entry write caps the audience already enforces, while a membership+ list is bounded only by the identity provider.+ """++ if access.access_mode != ACCESS_MODE_LIMITED:+ return None+ for entry in access.entries:+ if entry.kind == ACCESS_ENTRY_KIND_EMAIL:+ if visitor.normalized_email and visitor.normalized_email == entry.value:+ return entry+ continue+ if not visitor.has_organization_block:+ continue+ if entry.kind == ACCESS_ENTRY_KIND_GROUP:+ if (+ entry.organization_id == visitor.organization_id+ and entry.value in visitor.group_ids+ ):+ return entry+ elif entry.kind == ACCESS_ENTRY_KIND_ORGANIZATION:+ if (+ entry.value == visitor.organization_id+ and entry.organization_id == visitor.organization_id+ and visitor.organization_role in SHOW_ACCESS_ORGANIZATION_ROLES+ ):+ return entry+ return None+++def limited_show_access_admits(access: ShowAccess, visitor: ShowAccessVisitor) -> bool:+ """Whether any Limited audience entry admits this visitor."""++ return limited_show_access_grant(access, visitor) is not None+++def limited_show_access_grant_is_current(+ access: ShowAccess,+ grant: ShowAccessEntry | None,+) -> bool:+ """Whether a previously matched entry is still in the Limited audience.++ Re-checking the grant instead of re-running the match keeps a resumed+ visitor's proof bounded. It is fail-closed and self-healing: withdrawing+ the entry ends the grant immediately, and a visitor who still matches some+ other entry is re-admitted through a fresh identity round trip.+ """++ if grant is None or access.access_mode != ACCESS_MODE_LIMITED:+ return False+ return any(+ entry.kind == grant.kind+ and entry.value == grant.value+ and entry.organization_id == grant.organization_id+ for entry in access.entries+ )++@dataclass(frozen=True)class ShowAccessApplyResult:status: str@@ -393,17 +496,96 @@ def show_access_entry_payload(entry: ShowAccessEntry) -> dict[str, Any]:def show_access_payload(show_access: ShowAccess) -> dict[str, Any]:- # The wire shape stays email-only until the admission/UI lanes consume the- # heterogeneous set. ``show_access_entry_payload`` and ``ShowAccess.entries``- # are the additive surface those lanes read; putting ``entries`` on this- # payload here would change the internal-server JSON contract in this lane.return {"page_id": show_access.page_id,"access_mode": show_access.access_mode,"share_id": show_access.share_id,"revision": show_access.revision,"normalized_emails": list(show_access.normalized_emails),+ "entries": [show_access_entry_payload(entry) for entry in show_access.entries],+ }+++def _is_show_access_entries_payload(entries: Any) -> bool:+ if not isinstance(entries, list):+ return False+ for entry in entries:+ if not isinstance(entry, Mapping):+ return False+ if set(entry) - {"kind", "value", "organization_id"}:+ return False+ kind = entry.get("kind")+ value = entry.get("value")+ organization_id = entry.get("organization_id")+ if "kind" in entry and not isinstance(kind, str):+ return False+ if "value" in entry and value is not None and not isinstance(value, str):+ return False+ if (+ "organization_id" in entry+ and organization_id is not None+ and not isinstance(organization_id, str)+ ):+ return False+ return True+++def parse_show_access_apply_request(payload: Any) -> dict[str, Any] | None:+ """Return store kwargs for a well-formed apply body, else None.++ Exactly one of ``target_emails`` or ``target_entries`` may be present.+ The email-only form remains the complete-replacement shorthand; the+ entry form is how group and organization grants are written.+ """++ if not isinstance(payload, Mapping):+ return None+ keys = set(payload)+ has_emails = "target_emails" in keys+ has_entries = "target_entries" in keys+ if has_emails == has_entries:+ return None+ expected = {+ "page_id",+ "expected_revision",+ "target_access_mode",+ "target_share_id",}+ expected.add("target_emails" if has_emails else "target_entries")+ if keys != expected:+ return None+ page_id = payload.get("page_id")+ expected_revision = payload.get("expected_revision")+ target_access_mode = payload.get("target_access_mode")+ target_share_id = payload.get("target_share_id")+ if (+ not isinstance(page_id, str)+ or isinstance(expected_revision, bool)+ or not isinstance(expected_revision, int)+ or expected_revision < 0+ or not isinstance(target_access_mode, str)+ or not (target_share_id is None or isinstance(target_share_id, str))+ ):+ return None+ parsed: dict[str, Any] = {+ "page_id": page_id,+ "expected_revision": expected_revision,+ "target_access_mode": target_access_mode,+ "target_share_id": target_share_id,+ }+ if has_emails:+ emails = payload.get("target_emails")+ if not isinstance(emails, list) or any(+ not isinstance(email, str) for email in emails+ ):+ return None+ parsed["target_emails"] = emails+ return parsed+ entries = payload.get("target_entries")+ if not _is_show_access_entries_payload(entries):+ return None+ parsed["target_entries"] = entries+ return parseddef show_page_dir(session_id: str) -> Path:diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex b30349ce1..7aeab2033 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -8528,6 +8528,18 @@ def test_show_access_settings_read_returns_controller_snapshot(monkeypatch):"share_id": "stable-link","revision": 7,"normalized_emails": ["[email protected]", "[email protected]"],+ "entries": [+ {+ "kind": "email",+ "value": "[email protected]",+ "organization_id": None,+ },+ {+ "kind": "email",+ "value": "[email protected]",+ "organization_id": None,+ },+ ],}}assert captured == ["ses-show-access", "closed"]@@ -8617,6 +8629,7 @@ def test_show_access_apply_preserves_atomic_result_status(monkeypatch, status):"share_id": "current-link","revision": 9,"normalized_emails": [],+ "entries": [],},}assert captured == {@@ -8628,6 +8641,74 @@ def test_show_access_apply_preserves_atomic_result_status(monkeypatch, status):}+def test_show_access_apply_writes_and_reads_group_and_organization_entries(monkeypatch):+ from core import show_pages++ captured: dict = {}++ class _Store:+ def apply_access(self, page_id, **kwargs):+ captured.update(page_id=page_id, **kwargs)+ return show_pages.ShowAccessApplyResult(+ status="applied",+ show_access=show_pages.ShowAccess(+ page_id=page_id,+ access_mode="limited",+ share_id="stable-link",+ revision=2,+ entries=(+ show_pages.ShowAccessEntry("group", "group-7", "org-1"),+ show_pages.ShowAccessEntry("organization", "org-1", "org-1"),+ ),+ ),+ )++ def close(self):+ return None++ monkeypatch.setattr(show_pages, "ShowPageStore", _Store)+ app = internal_server.create_app(_build_controller_double())+ payload = {+ "page_id": "ses-show-access",+ "expected_revision": 1,+ "target_access_mode": "limited",+ "target_share_id": "stable-link",+ "target_entries": [+ {"kind": "group", "value": "group-7"},+ {"kind": "organization", "value": "org-1"},+ ],+ }++ async def _exercise():+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ return await client.post("/internal/show-access/apply", json=payload)++ response = asyncio.run(_exercise())++ assert response.status_code == 200+ assert response.json() == {+ "status": "applied",+ "show_access": {+ "page_id": "ses-show-access",+ "access_mode": "limited",+ "share_id": "stable-link",+ "revision": 2,+ "normalized_emails": [],+ "entries": [+ {"kind": "group", "value": "group-7", "organization_id": "org-1"},+ {+ "kind": "organization",+ "value": "org-1",+ "organization_id": "org-1",+ },+ ],+ },+ }+ assert captured["target_entries"] == payload["target_entries"]+ assert "target_emails" not in captured++def test_show_access_internal_identity_mismatch_fails_closed(monkeypatch):from core import show_pagesdiff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.pyindex c7cb3762d..4524ed3c5 100644--- a/tests/test_resource_acl_show_pages.py+++ b/tests/test_resource_acl_show_pages.py@@ -1172,6 +1172,63 @@ def test_show_access_owner_read_and_apply_use_controller_ipc(monkeypatch, tmp_pa]+def test_show_access_apply_forwards_group_and_organization_entries(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ store = ShowPageStore()+ try:+ store.ensure("ses-access-entries")+ finally:+ store.close()+ calls: list[tuple[str, dict]] = []+ request_payload = {+ "page_id": "ses-access-entries",+ "expected_revision": 0,+ "target_access_mode": "limited",+ "target_share_id": "stable-link",+ "target_entries": [+ {"kind": "group", "value": "group-7"},+ {"kind": "organization", "value": "org-1"},+ ],+ }++ async def _apply(payload):+ calls.append(("apply", payload))+ return {+ "status_code": 200,+ "body": {+ "status": "applied",+ "show_access": {+ **_show_access_payload("ses-access-entries", revision=1),+ "access_mode": "limited",+ "entries": [+ {+ "kind": "group",+ "value": "group-7",+ "organization_id": "org-1",+ },+ {+ "kind": "organization",+ "value": "org-1",+ "organization_id": "org-1",+ },+ ],+ },+ },+ }++ monkeypatch.setattr(internal_client, "show_access_apply", _apply)+ client = app.test_client()+ applied = client.post(+ "/api/show-pages/ses-access-entries/access-settings/apply",+ json=request_payload,+ headers=csrf_headers(client),+ )++ assert applied.status_code == 200+ assert applied.get_json()["show_access"]["entries"][0]["kind"] == "group"+ assert calls == [("apply", request_payload)]++def test_show_access_route_identity_mismatch_is_rejected_before_ipc(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))diff --git a/tests/test_show_identity.py b/tests/test_show_identity.pyindex fcbd8bd4f..c1e74265c 100644--- a/tests/test_show_identity.py+++ b/tests/test_show_identity.py@@ -8,6 +8,11 @@ import jwtimport pytestfrom cryptography.hazmat.primitives.asymmetric import rsa+from core.show_pages import (+ ACCESS_ENTRY_KINDS,+ SHOW_ACCESS_ENTRY_VALUE_MAX_LENGTH,+ ShowAccessEntry,+)from tests.ui_server_test_helpers import _save_configfrom vibe import show_identity@@ -23,6 +28,28 @@ def _identity_config(monkeypatch, tmp_path):return config+def _signed_assertion(monkeypatch, claims):+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ assertion = jwt.encode(+ claims,+ private_key,+ algorithm="RS256",+ headers={"typ": "JWT", "kid": "current"},+ )++ class JwkClientStub:+ def __init__(self, uri, *, timeout):+ assert uri == "https://backend.test/oauth/jwks.json"+ assert timeout == 5++ def get_signing_key_from_jwt(self, token):+ assert token == assertion+ return type("SigningKey", (), {"key": private_key.public_key()})()++ monkeypatch.setattr(show_identity, "PyJWKClient", JwkClientStub)+ return assertion++def test_show_identity_state_round_trips_only_for_its_callback_origin(monkeypatch, tmp_path):config = _identity_config(monkeypatch, tmp_path)authorization_url = show_identity.begin_show_identity_authorization(@@ -127,6 +154,7 @@ def test_show_identity_assertion_verifies_paired_issuer_instance_and_nonce(assert identity.normalized_email == "[email protected]"assert identity.assertion_id == "assertion-1"assert identity.expires_at == issued_at + 300+ assert identity.organization is Nonewith pytest.raises(show_identity.ShowIdentityError, match="invalid_assertion"):show_identity.verify_show_identity_assertion(@@ -233,3 +261,150 @@ def test_show_guest_lease_is_page_and_share_bound_without_live_membership_state(token,expected_share_id="other-page",)+++def _base_assertion_claims(*, issued_at: int, extra: dict | None = None) -> dict:+ claims = {+ "iss": "https://backend.test",+ "aud": "avibe-show-identity:vr_client_123",+ "sub": "user-1",+ "iat": issued_at,+ "exp": issued_at + 300,+ "jti": "assertion-org",+ "nonce": "nonce-1",+ "instance_id": "inst_123",+ "verified_email": "[email protected]",+ }+ if extra:+ claims.update(extra)+ return claims+++def test_show_identity_assertion_accepts_complete_organization_block(monkeypatch, tmp_path):+ config = _identity_config(monkeypatch, tmp_path)+ issued_at = int(time.time())+ assertion = _signed_assertion(+ monkeypatch,+ _base_assertion_claims(+ issued_at=issued_at,+ extra={+ "organization_id": "org-1",+ "organization_member_id": "mem-1",+ "organization_role": "member",+ "group_ids": ["group-7", "group-8"],+ },+ ),+ )++ identity = show_identity.verify_show_identity_assertion(+ config,+ assertion,+ expected_nonce="nonce-1",+ )+ assert identity.organization is not None+ assert identity.organization.organization_id == "org-1"+ assert identity.organization.organization_member_id == "mem-1"+ assert identity.organization.organization_role == "member"+ assert identity.organization.group_ids == frozenset({"group-7", "group-8"})+ visitor = identity.visitor()+ assert visitor.has_organization_block+ assert visitor.group_ids == frozenset({"group-7", "group-8"})++ # The lease records the entry that admitted the visitor, never the+ # membership list that matched it.+ grant = ShowAccessEntry(kind="group", value="group-7", organization_id="org-1")+ token = show_identity.make_show_guest_lease(+ config,+ page_id="page-1",+ share_id="shared-page",+ normalized_email=identity.normalized_email,+ grant=grant,+ )+ lease = show_identity.read_show_guest_lease(+ config,+ token,+ expected_share_id="shared-page",+ )+ assert lease.grant == grant+++def test_every_mintable_guest_lease_stays_readable(monkeypatch, tmp_path):+ """Whatever ``make_show_guest_lease`` writes, ``read_show_guest_lease`` reads.++ The lease is a cookie with a hard reader budget, so any field the writer+ can grow past that budget is an admission loop: the callback sets the+ cookie and the very next request rejects it. Seed every bounded field at+ its maximum instead of listing the sizes that happen to fit today, so a+ field widened later fails here rather than in a visitor's browser.+ """++ config = _identity_config(monkeypatch, tmp_path)+ longest_value = "g" * SHOW_ACCESS_ENTRY_VALUE_MAX_LENGTH+ longest_email = "e" * (SHOW_ACCESS_ENTRY_VALUE_MAX_LENGTH - len("@example.com")) + "@example.com"+ grants = [None] + [+ ShowAccessEntry(+ kind=kind,+ value=longest_email if kind == "email" else longest_value,+ organization_id=None if kind == "email" else longest_value,+ )+ for kind in ACCESS_ENTRY_KINDS+ ]++ for grant in grants:+ token = show_identity.make_show_guest_lease(+ config,+ page_id="s" * 128,+ share_id="shared-page",+ normalized_email=longest_email,+ grant=grant,+ )+ assert len(token.encode("utf-8")) <= show_identity.MAX_STATE_BYTES+ lease = show_identity.read_show_guest_lease(+ config,+ token,+ expected_share_id="shared-page",+ )+ assert lease.grant == (grant or ShowAccessEntry(kind="email", value=longest_email))+++def test_show_identity_assertion_rejects_a_partial_organization_block(monkeypatch, tmp_path):+ config = _identity_config(monkeypatch, tmp_path)+ issued_at = int(time.time())+ assertion = _signed_assertion(+ monkeypatch,+ _base_assertion_claims(+ issued_at=issued_at,+ extra={"organization_id": "org-1", "organization_role": "member"},+ ),+ )++ with pytest.raises(show_identity.ShowIdentityError, match="invalid_assertion"):+ show_identity.verify_show_identity_assertion(+ config,+ assertion,+ expected_nonce="nonce-1",+ )+++def test_show_identity_assertion_rejects_an_unknown_organization_role(monkeypatch, tmp_path):+ config = _identity_config(monkeypatch, tmp_path)+ issued_at = int(time.time())+ assertion = _signed_assertion(+ monkeypatch,+ _base_assertion_claims(+ issued_at=issued_at,+ extra={+ "organization_id": "org-1",+ "organization_member_id": "mem-1",+ "organization_role": "guest",+ "group_ids": [],+ },+ ),+ )++ with pytest.raises(show_identity.ShowIdentityError, match="invalid_assertion"):+ show_identity.verify_show_identity_assertion(+ config,+ assertion,+ expected_nonce="nonce-1",+ )diff --git a/tests/test_show_pages.py b/tests/test_show_pages.pyindex 9d46ebabf..085ffbbe1 100644--- a/tests/test_show_pages.py+++ b/tests/test_show_pages.py@@ -9,10 +9,17 @@ from config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig,from core.show_pages import (SHOW_ACCESS_EMAIL_MAX_COUNT,SHOW_ACCESS_ENTRY_MAX_COUNTS,+ ShowAccess,ShowAccessEntry,+ ShowAccessVisitor,ShowPage,ShowPageError,ShowPageStore,+ limited_show_access_admits,+ limited_show_access_grant,+ limited_show_access_grant_is_current,+ parse_show_access_apply_request,+ show_access_payload,_default_index_html,_extract_icon_path,ensure_show_page_dir,@@ -1117,6 +1124,198 @@ def test_show_access_stamps_organization_entries_from_the_pairing_held_at_persisstore.close()+def _limited_access(*entries: ShowAccessEntry) -> ShowAccess:+ return ShowAccess(+ page_id="ses-admit",+ access_mode="limited",+ share_id="share-admit",+ revision=1,+ entries=entries,+ )+++def _visitor(+ *,+ email: str = "[email protected]",+ organization_id: str | None = None,+ organization_member_id: str | None = None,+ organization_role: str | None = None,+ group_ids: frozenset[str] = frozenset(),+) -> ShowAccessVisitor:+ return ShowAccessVisitor(+ normalized_email=email,+ organization_id=organization_id,+ organization_member_id=organization_member_id,+ organization_role=organization_role,+ group_ids=group_ids,+ )+++def test_limited_show_access_admits_any_matching_entry() -> None:+ access = _limited_access(+ ShowAccessEntry("email", "[email protected]"),+ ShowAccessEntry("group", "group-7", "org-1"),+ ShowAccessEntry("organization", "org-1", "org-1"),+ )+ member = dict(+ organization_id="org-1",+ organization_member_id="mem-1",+ organization_role="member",+ )++ assert limited_show_access_admits(access, _visitor(email="[email protected]"))+ assert limited_show_access_admits(+ access,+ _visitor(email="[email protected]", group_ids=frozenset({"group-7"}), **member),+ )+ assert limited_show_access_admits(+ access,+ _visitor(email="[email protected]", **member),+ )+ assert not limited_show_access_admits(+ access,+ _visitor(email="[email protected]"),+ )+ assert not limited_show_access_admits(+ _limited_access(),+ _visitor(email="[email protected]", **member),+ )+ private = ShowAccess(+ page_id="ses-admit",+ access_mode="private",+ share_id="share-admit",+ revision=1,+ entries=access.entries,+ )+ assert not limited_show_access_admits(private, _visitor(email="[email protected]"))+++def test_limited_show_access_grant_names_the_matched_entry_and_is_rechecked() -> None:+ """A grant is a whole audience entry, and it lasts exactly as long as it does.++ Persisting the matched entry is what keeps a resumed visitor's proof+ bounded: whatever the identity provider claims, what outlives the match is+ one entry the audience's own write caps already bound.+ """++ entries = (+ ShowAccessEntry("email", "[email protected]"),+ ShowAccessEntry("group", "group-7", "org-1"),+ ShowAccessEntry("organization", "org-1", "org-1"),+ )+ access = _limited_access(*entries)+ member = dict(+ organization_id="org-1",+ organization_member_id="mem-1",+ organization_role="member",+ )+ visitors = (+ _visitor(email="[email protected]"),+ _visitor(email="[email protected]", group_ids=frozenset({"group-7"}), **member),+ _visitor(email="[email protected]", **member),+ )++ for entry, visitor in zip(entries, visitors, strict=True):+ grant = limited_show_access_grant(access, visitor)+ assert grant == entry+ # The grant holds while its entry is in the audience...+ assert limited_show_access_grant_is_current(access, grant)+ # ...and ends the moment that entry is withdrawn, even when the rest of+ # the audience is untouched.+ remaining = _limited_access(*(other for other in entries if other != entry))+ assert not limited_show_access_grant_is_current(remaining, grant)++ assert limited_show_access_grant(access, _visitor(email="[email protected]")) is None+ assert not limited_show_access_grant_is_current(access, None)+ private = ShowAccess(+ page_id="ses-admit",+ access_mode="private",+ share_id="share-admit",+ revision=1,+ entries=entries,+ )+ assert not limited_show_access_grant_is_current(private, entries[0])+++def test_limited_show_access_organization_block_is_fail_closed() -> None:+ access = _limited_access(+ ShowAccessEntry("email", "[email protected]"),+ ShowAccessEntry("group", "group-7", "org-1"),+ ShowAccessEntry("organization", "org-1", "org-1"),+ )+ email_only = _visitor(email="[email protected]")+ other_org = _visitor(+ email="[email protected]",+ organization_id="org-2",+ organization_member_id="mem-2",+ organization_role="member",+ group_ids=frozenset({"group-7"}),+ )+ incomplete = _visitor(+ email="[email protected]",+ organization_id="org-1",+ organization_role="member",+ group_ids=frozenset({"group-7"}),+ )++ assert limited_show_access_admits(access, email_only)+ assert not limited_show_access_admits(+ _limited_access(+ ShowAccessEntry("group", "group-7", "org-1"),+ ShowAccessEntry("organization", "org-1", "org-1"),+ ),+ email_only,+ )+ assert not limited_show_access_admits(access, other_org)+ assert not limited_show_access_admits(access, incomplete)+ assert not limited_show_access_admits(+ _limited_access(ShowAccessEntry("group", "group-7", "org-1")),+ _visitor(+ email="[email protected]",+ organization_id="org-1",+ organization_member_id="mem-1",+ organization_role="member",+ group_ids=frozenset({"group-8"}),+ ),+ )+++def test_show_access_payload_includes_the_entry_set() -> None:+ access = _limited_access(+ ShowAccessEntry("email", "[email protected]"),+ ShowAccessEntry("group", "group-7", "org-1"),+ ShowAccessEntry("organization", "org-1", "org-1"),+ )++ assert show_access_payload(access)["entries"] == [+ {"kind": "email", "value": "[email protected]", "organization_id": None},+ {"kind": "group", "value": "group-7", "organization_id": "org-1"},+ {"kind": "organization", "value": "org-1", "organization_id": "org-1"},+ ]+ assert parse_show_access_apply_request(+ {+ "page_id": "ses-admit",+ "expected_revision": 1,+ "target_access_mode": "limited",+ "target_share_id": "share-admit",+ "target_emails": ["[email protected]"],+ "target_entries": [{"kind": "group", "value": "group-7"}],+ }+ ) is None+ parsed_entries = parse_show_access_apply_request(+ {+ "page_id": "ses-admit",+ "expected_revision": 1,+ "target_access_mode": "limited",+ "target_share_id": "share-admit",+ "target_entries": [{"kind": "group", "value": "group-7"}],+ }+ )+ assert parsed_entries is not None+ assert "target_emails" not in parsed_entries+ assert parsed_entries["target_entries"] == [{"kind": "group", "value": "group-7"}]++def test_set_share_id_rejects_archived_session(monkeypatch, tmp_path):from storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_statediff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex 7375c5e9d..27fee2515 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -21,6 +21,8 @@ from starlette.websockets import WebSocketDisconnectfrom config import pathsfrom core.show_pages import (+ SHOW_ACCESS_ENTRY_VALUE_MAX_LENGTH,+ SHOW_ACCESS_VISITOR_GROUP_MAX_COUNT,SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS,VISIBILITIES,ShowPageError,@@ -780,6 +782,7 @@ def test_limited_show_callback_maps_outages_and_rechecks_share_binding(access_mode=access.access_mode,share_id="rotated-share",normalized_emails=access.normalized_emails,+ entries=access.entries,)monkeypatch.setattr(ShowPageStore, "get_access", get_rotated_access)@@ -1465,6 +1468,189 @@ def test_limited_show_guest_is_rechecked_after_access_changes(set_show_runtime_manager_for_tests(None)+def test_limited_show_page_admits_group_and_organization_entries_readonly(+ monkeypatch,+ tmp_path,+):+ from core.show_pages import ShowPageStore as LiveStore++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ _configure_show_identity(config)+ share_id = _create_show_page("ses123", "limited")+ monkeypatch.setattr(+ LiveStore,+ "_resolve_instance_ownership",+ staticmethod(lambda: {"mode": "organization", "organization_id": "org-1"}),+ )+ store = LiveStore()+ try:+ access = store.get_access("ses123")+ assert access is not None+ applied = store.apply_access(+ "ses123",+ expected_revision=access.revision,+ target_access_mode="limited",+ target_share_id=share_id,+ target_entries=[+ {"kind": "group", "value": "group-7"},+ {"kind": "organization", "value": "org-1"},+ ],+ )+ assert applied.status == "applied"+ assert applied.show_access.normalized_emails == ()+ finally:+ store.close()++ # A full-size membership list: admission must survive it on every request+ # after the callback, not just the callback itself.+ organization = show_identity.ShowIdentityOrganization(+ organization_id="org-1",+ organization_member_id="mem-1",+ organization_role="member",+ group_ids=frozenset({"group-7"})+ | {+ f"group-{index}-{'x' * (SHOW_ACCESS_ENTRY_VALUE_MAX_LENGTH - 16)}"+ for index in range(SHOW_ACCESS_VISITOR_GROUP_MAX_COUNT - 1)+ },+ )+ manager = _FakeShowRuntimeManager(+ body=(+ b'<!doctype html><html><body><script type="module" '+ b'src="/src/main.tsx"></script></body></html>'+ ),+ )++ def verify_identity(*_args, **_kwargs):+ return show_identity.VerifiedShowIdentity(+ subject="member-1",+ normalized_email="[email protected]",+ assertion_id=f"assertion-{_kwargs['expected_nonce']}",+ expires_at=int(ui_server.time.time()) + 300,+ organization=organization,+ )++ monkeypatch.setattr(+ show_identity,+ "verify_show_identity_assertion",+ verify_identity,+ )+ set_show_runtime_manager_for_tests(manager)+ try:+ client = app.test_client()+ login = client.get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ query = urllib.parse.parse_qs(+ urllib.parse.urlsplit(login.headers["Location"]).query+ )+ callback = client.post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data={"state": query["state"][0], "assertion": "signed-assertion"},+ follow_redirects=False,+ )+ assert callback.status_code == 303+ page = client.get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ )+ assert page.status_code == 200+ assert b'"authenticated":false' in page.content+ assert b"__show/annotation.js" not in page.content+ events = client.get(+ f"/p/{share_id}/__show/events",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ assert events.status_code == 404+ finally:+ set_show_runtime_manager_for_tests(None)++ def verify_email_only(*_args, **_kwargs):+ return show_identity.VerifiedShowIdentity(+ subject="outsider-1",+ normalized_email="[email protected]",+ assertion_id=f"email-only-{_kwargs['expected_nonce']}",+ expires_at=int(ui_server.time.time()) + 300,+ )++ monkeypatch.setattr(+ show_identity,+ "verify_show_identity_assertion",+ verify_email_only,+ )+ denied_client = app.test_client()+ denied_login = denied_client.get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ denied_query = urllib.parse.parse_qs(+ urllib.parse.urlsplit(denied_login.headers["Location"]).query+ )+ denied = denied_client.post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data={+ "state": denied_query["state"][0],+ "assertion": "signed-assertion",+ },+ )+ assert denied.status_code == 404+ assert denied.get_json() == {"error": "not_found"}++ other_org = show_identity.ShowIdentityOrganization(+ organization_id="org-2",+ organization_member_id="mem-2",+ organization_role="member",+ group_ids=frozenset({"group-7"}),+ )++ def verify_other_org(*_args, **_kwargs):+ return show_identity.VerifiedShowIdentity(+ subject="other-1",+ normalized_email="[email protected]",+ assertion_id=f"other-org-{_kwargs['expected_nonce']}",+ expires_at=int(ui_server.time.time()) + 300,+ organization=other_org,+ )++ monkeypatch.setattr(+ show_identity,+ "verify_show_identity_assertion",+ verify_other_org,+ )+ other_client = app.test_client()+ other_login = other_client.get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ other_query = urllib.parse.parse_qs(+ urllib.parse.urlsplit(other_login.headers["Location"]).query+ )+ other = other_client.post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data={"state": other_query["state"][0], "assertion": "signed-assertion"},+ )+ assert other.status_code == 404++def test_public_show_page_still_requires_remote_login(monkeypatch, tmp_path):# Auth parity: serving public pages here adds no anonymous exposure — the# authed route still bounces a remote request without a session to logindiff --git a/vibe/show_identity.py b/vibe/show_identity.pyindex f339815fb..9dd450c6b 100644--- a/vibe/show_identity.py+++ b/vibe/show_identity.py@@ -16,7 +16,17 @@ from jwt import PyJWKClientfrom jwt.exceptions import PyJWKClientConnectionErrorfrom config.v2_config import V2Config-from core.show_pages import normalize_show_access_email, validate_share_id+from core.show_pages import (+ ACCESS_ENTRY_KIND_EMAIL,+ ACCESS_ENTRY_KINDS,+ SHOW_ACCESS_ENTRY_VALUE_MAX_LENGTH,+ SHOW_ACCESS_ORGANIZATION_ROLES,+ SHOW_ACCESS_VISITOR_GROUP_MAX_COUNT,+ ShowAccessEntry,+ ShowAccessVisitor,+ normalize_show_access_email,+ validate_share_id,+)CALLBACK_PATH = "/auth/show-identity/callback"@@ -48,12 +58,46 @@ class ShowIdentityState:callback_origin: str+_ORGANIZATION_CLAIM_NAMES = (+ "organization_id",+ "organization_member_id",+ "organization_role",+ "group_ids",+)+_GRANT_CLAIM_NAMES = (+ "grant_kind",+ "grant_value",+ "grant_organization_id",+)+++@dataclass(frozen=True)+class ShowIdentityOrganization:+ organization_id: str+ organization_member_id: str+ organization_role: str+ group_ids: frozenset[str]++@dataclass(frozen=True)class VerifiedShowIdentity:subject: strnormalized_email: strassertion_id: strexpires_at: int+ organization: ShowIdentityOrganization | None = None++ def visitor(self) -> ShowAccessVisitor:+ organization = self.organization+ if organization is None:+ return ShowAccessVisitor(normalized_email=self.normalized_email)+ return ShowAccessVisitor(+ normalized_email=self.normalized_email,+ organization_id=organization.organization_id,+ organization_member_id=organization.organization_member_id,+ organization_role=organization.organization_role,+ group_ids=organization.group_ids,+ )@dataclass(frozen=True)@@ -61,6 +105,11 @@ class ShowGuestLease:page_id: strshare_id: strnormalized_email: str+ # The audience entry that admitted this browser, re-checked against the+ # page's current access on every later request. The visitor's group list+ # never enters the cookie: it is bounded only by the identity provider,+ # while one entry is bounded by SHOW_ACCESS_ENTRY_VALUE_MAX_LENGTH.+ grant: ShowAccessEntry | None = Nonedef _b64url_encode(value: bytes) -> str:@@ -334,6 +383,7 @@ def verify_show_identity_assertion(raise ShowIdentityError("invalid_assertion")try:normalized_email = normalize_show_access_email(claims["verified_email"])+ organization = _parse_show_identity_organization(claims)except Exception as exc:raise ShowIdentityError("invalid_assertion") from excreturn VerifiedShowIdentity(@@ -341,9 +391,97 @@ def verify_show_identity_assertion(normalized_email=normalized_email,assertion_id=claims["jti"],expires_at=claims["exp"],+ organization=organization,)+def _optional_organization_identifier(value: Any) -> str | None:+ if value is None:+ return None+ if not isinstance(value, str):+ raise ShowIdentityError("invalid_assertion")+ identifier = value.strip()+ if not identifier or len(identifier) > SHOW_ACCESS_ENTRY_VALUE_MAX_LENGTH:+ raise ShowIdentityError("invalid_assertion")+ return identifier+++def _parse_show_identity_organization(claims: dict[str, Any]) -> ShowIdentityOrganization | None:+ """Read the optional all-or-nothing organization block.++ Backend signs the four claims together or not at all. A partial block,+ an unknown role, or a malformed group list is an invalid assertion, not+ a missing block: missing means fail-closed for group/organization+ entries, invalid means the visitor never reached admission.+ """++ present = [name for name in _ORGANIZATION_CLAIM_NAMES if name in claims]+ if not present:+ return None+ if set(present) != set(_ORGANIZATION_CLAIM_NAMES):+ raise ShowIdentityError("invalid_assertion")++ organization_id = _optional_organization_identifier(claims.get("organization_id"))+ organization_member_id = _optional_organization_identifier(+ claims.get("organization_member_id")+ )+ organization_role = claims.get("organization_role")+ raw_group_ids = claims.get("group_ids")+ if (+ organization_id is None+ or organization_member_id is None+ or not isinstance(organization_role, str)+ or organization_role not in SHOW_ACCESS_ORGANIZATION_ROLES+ or not isinstance(raw_group_ids, list)+ or len(raw_group_ids) > SHOW_ACCESS_VISITOR_GROUP_MAX_COUNT+ ):+ raise ShowIdentityError("invalid_assertion")+ group_ids: set[str] = set()+ for raw in raw_group_ids:+ group_id = _optional_organization_identifier(raw)+ if group_id is None:+ raise ShowIdentityError("invalid_assertion")+ group_ids.add(group_id)+ return ShowIdentityOrganization(+ organization_id=organization_id,+ organization_member_id=organization_member_id,+ organization_role=organization_role,+ group_ids=frozenset(group_ids),+ )+++def _grant_lease_payload(grant: ShowAccessEntry) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "grant_kind": grant.kind,+ "grant_value": grant.value,+ }+ if grant.organization_id is not None:+ payload["grant_organization_id"] = grant.organization_id+ return payload+++def _parse_lease_grant(payload: dict[str, Any], *, normalized_email: str) -> ShowAccessEntry | None:+ present = [name for name in _GRANT_CLAIM_NAMES if name in payload]+ if not present:+ # A lease minted before grants were recorded proves only the email it+ # already carries, which is exactly the entry it was admitted by.+ if not normalized_email:+ raise ShowIdentityError("invalid_lease")+ return ShowAccessEntry(kind=ACCESS_ENTRY_KIND_EMAIL, value=normalized_email)+ kind = payload.get("grant_kind")+ value = _optional_organization_identifier(payload.get("grant_value"))+ organization_id = _optional_organization_identifier(payload.get("grant_organization_id"))+ if kind not in ACCESS_ENTRY_KINDS or value is None:+ raise ShowIdentityError("invalid_lease")+ if (kind == ACCESS_ENTRY_KIND_EMAIL) != (organization_id is None):+ # Email entries are never organization-scoped; group and organization+ # entries always are.+ raise ShowIdentityError("invalid_lease")+ if kind == ACCESS_ENTRY_KIND_EMAIL and value != normalized_email:+ raise ShowIdentityError("invalid_lease")+ return ShowAccessEntry(kind=kind, value=value, organization_id=organization_id)++def consume_verified_show_identity(identity: VerifiedShowIdentity,*,@@ -380,20 +518,31 @@ def make_show_guest_lease(page_id: str,share_id: str,normalized_email: str,+ grant: ShowAccessEntry | None = None,) -> str:# Deliberately a browser-session lease: access changes govern new# admissions without interrupting a page the user already opened.- return _encode_signed_payload(+ payload: dict[str, Any] = {+ "v": 1,+ "page_id": page_id,+ "share_id": validate_share_id(share_id),+ "normalized_email": normalize_show_access_email(normalized_email),+ "lease_id": secrets.token_urlsafe(18),+ }+ if grant is not None:+ payload.update(_grant_lease_payload(grant))+ token = _encode_signed_payload(_lease_secret(config),_LEASE_PREFIX,- {- "v": 1,- "page_id": page_id,- "share_id": validate_share_id(share_id),- "normalized_email": normalize_show_access_email(normalized_email),- "lease_id": secrets.token_urlsafe(18),- },+ payload,)+ if len(token.encode("utf-8")) > MAX_STATE_BYTES:+ # The reader rejects an oversized token, so minting one would admit the+ # visitor at the callback and then reject every later request. Every+ # field above is individually bounded, so this is unreachable; keep it+ # as the mechanical guarantee that what we mint is what we can read.+ raise ShowIdentityError("identity_unavailable")+ return tokendef read_show_guest_lease(@@ -408,13 +557,17 @@ def read_show_guest_lease(token,max_bytes=MAX_STATE_BYTES,)- if set(payload) != {+ required = {"v","page_id","share_id","normalized_email","lease_id",- }:+ }+ extra = set(payload) - required+ if not extra <= set(_GRANT_CLAIM_NAMES):+ raise ShowIdentityError("invalid_lease")+ if not required.issubset(payload):raise ShowIdentityError("invalid_lease")if payload.get("v") != 1:raise ShowIdentityError("invalid_lease")@@ -436,10 +589,12 @@ def read_show_guest_lease(raise ShowIdentityError("invalid_lease")try:normalized_email = normalize_show_access_email(payload.get("normalized_email"))+ grant = _parse_lease_grant(payload, normalized_email=normalized_email)except Exception as exc:raise ShowIdentityError("invalid_lease") from excreturn ShowGuestLease(page_id=page_id,share_id=share_id,normalized_email=normalized_email,+ grant=grant,)diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 0d66490be..5a984c6ee 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -5841,19 +5841,9 @@ def _show_access_page_identity_matches(body: Any, page_id: str) -> bool:def _valid_show_access_apply_payload(payload: dict[str, Any]) -> bool:- return bool(- isinstance(payload.get("page_id"), str)- and not isinstance(payload.get("expected_revision"), bool)- and isinstance(payload.get("expected_revision"), int)- and payload["expected_revision"] >= 0- and isinstance(payload.get("target_access_mode"), str)- and (- payload.get("target_share_id") is None- or isinstance(payload.get("target_share_id"), str)- )- and isinstance(payload.get("target_emails"), list)- and all(isinstance(email, str) for email in payload["target_emails"])- )+ from core.show_pages import parse_show_access_apply_request++ return parse_show_access_apply_request(payload) is not None@app.route("/api/show-pages/<session_id>/access-settings/read", methods=["POST"])@@ -5902,19 +5892,12 @@ async def show_page_access_settings_apply(session_id):from vibe import api, internal_clientpayload = request.json if isinstance(request.json, dict) else {}- required = {- "page_id",- "expected_revision",- "target_access_mode",- "target_share_id",- "target_emails",- }if payload.get("page_id") != session_id:return _show_access_http_response({"ok": False, "error": "show_access_page_identity_mismatch"},400,)- if set(payload) != required or not _valid_show_access_apply_payload(payload):+ if not _valid_show_access_apply_payload(payload):return _show_access_http_response({"ok": False, "error": "invalid_show_access_apply_request"},400,@@ -13036,6 +13019,44 @@ def _show_public_authenticated_context(config: V2Config | None):return context_from_session_payload(session) if session is not None else None+def _show_access_visitor_from_context(context: Any):+ from core.show_pages import ShowAccessVisitor, normalize_show_access_email++ if context is None:+ return None+ normalized_email = ""+ if context.email:+ try:+ normalized_email = normalize_show_access_email(context.email)+ except (TypeError, ValueError):+ normalized_email = ""+ return ShowAccessVisitor(+ normalized_email=normalized_email,+ organization_id=context.organization_id,+ organization_member_id=context.organization_member_id,+ organization_role=context.organization_role,+ group_ids=frozenset(context.group_ids or ()),+ )+++def _limited_show_access_grant(access: Any, visitor: Any):+ from core.show_pages import limited_show_access_grant++ if access is None or visitor is None:+ return None+ return limited_show_access_grant(access, visitor)+++def _limited_show_access_admits(access: Any, visitor: Any) -> bool:+ return _limited_show_access_grant(access, visitor) is not None+++def _limited_show_access_grant_is_current(access: Any, grant: Any) -> bool:+ from core.show_pages import limited_show_access_grant_is_current++ return access is not None and limited_show_access_grant_is_current(access, grant)++def _show_limited_viewer_is_allowed(context: Any,access: Any,@@ -13043,18 +13064,9 @@ def _show_limited_viewer_is_allowed(*,allow_page_scoped: bool = True,) -> bool:- from core.show_pages import normalize_show_access_email-- allowlisted = False- if context.email:- try:- allowlisted = (- access is not None- and normalize_show_access_email(context.email)- in access.normalized_emails- )- except (TypeError, ValueError):- allowlisted = False+ allowlisted = _limited_show_access_admits(+ access, _show_access_visitor_from_context(context)+ )return allowlisted or (allow_page_scoped and context.can_use_show_page(page_id))@@ -14901,11 +14913,12 @@ async def complete_show_identity_login():_show_identity_error_status(exc.reason),)return redirect(state.return_target, code=303)+ grant = _limited_show_access_grant(access, identity.visitor())if (access.access_mode != "limited"or page.visibility != "limited"or access.share_id != state.share_id- or identity.normalized_email not in access.normalized_emails+ or grant is None):return _show_identity_not_found_response()@@ -14924,6 +14937,7 @@ async def complete_show_identity_login():page_id=page.session_id,share_id=state.share_id,normalized_email=identity.normalized_email,+ grant=grant,)response = redirect(state.return_target, code=303)response.set_cookie(@@ -14974,12 +14988,7 @@ def redirect_public_show_page_to_canonical_path(share_id):methods=["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],)async def serve_public_show_page(share_id, asset_path):- from core.show_pages import (- ShowPageError,- ShowPageStore,- ensure_show_page_dir,- normalize_show_access_email,- )+ from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dirfrom vibe import show_identityconfig = _load_remote_access_config()@@ -15034,7 +15043,7 @@ async def serve_public_show_page(share_id, asset_path):and page.visibility == "limited"and access.access_mode == "limited"and access.share_id == share_id- and lease.normalized_email in access.normalized_emails+ and _limited_show_access_grant_is_current(access, lease.grant))if not lease_is_current:current_limited_binding = (