diff --git a/loopx/extensions/external_connector_permissions.py b/loopx/extensions/external_connector_permissions.py new file mode 100644 index 0000000000..5bbd298aa4 --- /dev/null +++ b/loopx/extensions/external_connector_permissions.py @@ -0,0 +1,479 @@ +"""Permission requirement, guidance, and projection helpers for external Connectors.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +import re +from typing import TypedDict +from urllib.parse import urlsplit + +from .external_connector_runtime import ( + SAFE_TOKEN_PATTERN, + ExternalConnectorCapability, + ExternalResponsePolicy, +) + +PERMISSION_REQUIREMENT_SCHEMA_VERSION = ( + "agent_external_connector_permission_requirement_v0" +) +PERMISSION_GUIDANCE_SCHEMA_VERSION = "agent_external_connector_permission_guidance_v0" +PERMISSION_STATUS_SCHEMA_VERSION = "agent_external_connector_permission_status_v0" + +SAFE_SCOPE_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}") + +PermissionRequirementFingerprint = tuple[str, str, str, tuple[str, ...], bool, str] + + +class ExternalConnectorPermissionStatus(TypedDict): + """Typed public-safe permission status projection without secret scopes.""" + + schema_version: str + ready: bool + requirement_count: int + missing_requirement_count: int + operations: list[str] + publication_required: bool + private_scope_values_captured: bool + private_repair_urls_captured: bool + private_provider_identity_captured: bool + + +@dataclass(frozen=True) +class _RequirementSpec: + provider_kind: str + provider_identity: str + operation: str + required_scopes: tuple[str, ...] + publication_required: bool + repair_url: str + + def identity_key(self) -> tuple[str, str, str]: + return (self.provider_kind, self.provider_identity, self.operation) + + def fingerprint(self) -> PermissionRequirementFingerprint: + return ( + self.provider_kind, + self.provider_identity, + self.operation, + self.required_scopes, + self.publication_required, + self.repair_url, + ) + + def to_dict(self) -> dict[str, object]: + return { + "schema_version": PERMISSION_REQUIREMENT_SCHEMA_VERSION, + "provider_kind": self.provider_kind, + "provider_identity": self.provider_identity, + "operation": self.operation, + "required_scopes": list(self.required_scopes), + "publication_required": self.publication_required, + "repair_url": self.repair_url, + } + + +def safe_token( + value: object, + *, + field: str, + pattern: re.Pattern[str] = SAFE_TOKEN_PATTERN, +) -> str: + """Validate and return a normalized opaque connector token.""" + normalized = str(value or "").strip() + if not pattern.fullmatch(normalized): + raise ValueError(f"{field} must be an opaque public-safe token") + return normalized + + +def scope_values(values: Sequence[str], *, field: str) -> list[str]: + """Validate and return sorted unique provider scope tokens.""" + normalized = {str(value or "").strip() for value in values} + if not normalized or any( + not SAFE_SCOPE_PATTERN.fullmatch(value) for value in normalized + ): + raise ValueError(f"{field} must contain provider scope tokens") + return sorted(normalized) + + +def repair_url(value: object) -> str: + """Validate a bounded HTTPS repair URL without credentials or fragments.""" + normalized = str(value or "").strip() + parsed = urlsplit(normalized) + if ( + parsed.scheme != "https" + or not parsed.netloc + or parsed.username + or parsed.password + or parsed.fragment + or len(normalized) > 2048 + ): + raise ValueError("repair_url must be a bounded official HTTPS URL") + return normalized + + +def _requirement_spec_from_args( + *, + provider_kind: str, + provider_identity: str, + operation: str, + required_scopes: Sequence[str], + publication_required: bool, + repair_url_value: str, +) -> _RequirementSpec: + try: + capability = ExternalConnectorCapability(str(operation or "").strip()).value + except ValueError as exc: + allowed = ", ".join(item.value for item in ExternalConnectorCapability) + raise ValueError(f"operation must be one of: {allowed}") from exc + return _RequirementSpec( + provider_kind=safe_token(provider_kind, field="provider_kind"), + provider_identity=safe_token(provider_identity, field="provider_identity"), + operation=capability, + required_scopes=tuple(scope_values(required_scopes, field="required_scopes")), + publication_required=bool(publication_required), + repair_url=repair_url(repair_url_value), + ) + + +def _normalize_requirement_spec(value: Mapping[str, object]) -> _RequirementSpec: + if value.get("schema_version") != PERMISSION_REQUIREMENT_SCHEMA_VERSION: + raise ValueError("external connector permission requirement schema is invalid") + scopes = value.get("required_scopes") + if not isinstance(scopes, Sequence) or isinstance(scopes, (str, bytes)): + raise TypeError("required_scopes must be a sequence") + return _requirement_spec_from_args( + provider_kind=str(value.get("provider_kind") or ""), + provider_identity=str(value.get("provider_identity") or ""), + operation=str(value.get("operation") or ""), + required_scopes=[str(scope) for scope in scopes], + publication_required=value.get("publication_required") is True, + repair_url_value=str(value.get("repair_url") or ""), + ) + + +def build_external_connector_permission_requirement( + *, + provider_kind: str, + provider_identity: str, + operation: str, + required_scopes: Sequence[str], + publication_required: bool, + repair_url: str, +) -> dict[str, object]: + """Build provider-owned, owner-local permission repair guidance.""" + + return _requirement_spec_from_args( + provider_kind=provider_kind, + provider_identity=provider_identity, + operation=operation, + required_scopes=required_scopes, + publication_required=publication_required, + repair_url_value=repair_url, + ).to_dict() + + +def normalize_permission_requirement( + value: Mapping[str, object], +) -> dict[str, object]: + """Validate and normalize one permission requirement payload.""" + return _normalize_requirement_spec(value).to_dict() + + +def normalize_permission_requirement_specs( + values: Sequence[Mapping[str, object]], +) -> list[_RequirementSpec]: + """Validate, normalize, and check uniqueness for requirement specs.""" + if isinstance(values, (str, bytes)) or any( + not isinstance(requirement, Mapping) for requirement in values + ): + raise TypeError("external connector permission requirements are invalid") + specs: list[_RequirementSpec] = [] + identities: set[tuple[str, str, str]] = set() + for requirement in values: + spec = _normalize_requirement_spec(requirement) + specs.append(spec) + identities.add(spec.identity_key()) + if len(specs) != len(identities): + raise ValueError("external connector permission requirements are duplicated") + return specs + + +def normalize_permission_requirements( + values: Sequence[Mapping[str, object]], +) -> list[dict[str, object]]: + """Validate and normalize a unique sequence of permission requirements.""" + return [spec.to_dict() for spec in normalize_permission_requirement_specs(values)] + + +def permission_requirement_fingerprint( + requirement: Mapping[str, object], +) -> PermissionRequirementFingerprint: + """Return a hashable comparison tuple for one permission requirement.""" + raw_scopes = requirement["required_scopes"] + if not isinstance(raw_scopes, Sequence) or isinstance(raw_scopes, (str, bytes)): + raise TypeError("required_scopes must be a sequence") + return ( + str(requirement["provider_kind"]), + str(requirement["provider_identity"]), + str(requirement["operation"]), + tuple(str(scope) for scope in raw_scopes), + bool(requirement["publication_required"]), + str(requirement["repair_url"]), + ) + + +def evaluate_external_connector_permissions( + *, + requirements: Sequence[Mapping[str, object]], + granted_scopes: Mapping[str, Sequence[str]], + published: bool, +) -> dict[str, object]: + """Return exact owner-local guidance without promoting it to public status.""" + + specs = normalize_permission_requirement_specs(requirements) + items: list[dict[str, object]] = [] + missing_count = 0 + granted_cache: dict[str, set[str]] = {} + for spec in specs: + granted = granted_cache.get(spec.provider_identity) + if granted is None: + granted = { + str(scope or "").strip() + for scope in granted_scopes.get(spec.provider_identity, ()) + } + granted_cache[spec.provider_identity] = granted + missing_scopes = [ + scope for scope in spec.required_scopes if scope not in granted + ] + publication_ready = bool(published or not spec.publication_required) + ready = not missing_scopes and publication_ready + if not ready: + missing_count += 1 + items.append( + { + **spec.to_dict(), + "missing_scopes": missing_scopes, + "publication_ready": publication_ready, + "ready": ready, + } + ) + return { + "ok": True, + "schema_version": PERMISSION_GUIDANCE_SCHEMA_VERSION, + "ready": missing_count == 0, + "requirement_count": len(items), + "missing_requirement_count": missing_count, + "items": items, + "local_private_guidance_returned": bool(items), + "credentials_captured": False, + } + + +def _normalize_permission_guidance_items( + value: Mapping[str, object], +) -> tuple[bool, int, list[tuple[_RequirementSpec, dict[str, object]]]]: + if value.get("schema_version") != PERMISSION_GUIDANCE_SCHEMA_VERSION: + raise ValueError("external connector permission guidance schema is invalid") + raw_items = value.get("items") + if not isinstance(raw_items, list) or any( + not isinstance(item, Mapping) for item in raw_items + ): + raise TypeError("external connector permission guidance items are invalid") + entries: list[tuple[_RequirementSpec, dict[str, object]]] = [] + missing_count = 0 + for raw_item in raw_items: + spec = _normalize_requirement_spec(raw_item) + missing_scopes = raw_item.get("missing_scopes") + if not isinstance(missing_scopes, list): + raise TypeError("permission missing_scopes are invalid") + normalized_missing = ( + scope_values( + [str(scope) for scope in missing_scopes], + field="missing_scopes", + ) + if missing_scopes + else [] + ) + if not set(normalized_missing).issubset(spec.required_scopes): + raise ValueError("missing_scopes must belong to required_scopes") + publication_ready = raw_item.get("publication_ready") is True + expected_ready = not normalized_missing and publication_ready + if (raw_item.get("ready") is True) != expected_ready: + raise ValueError("permission guidance ready state is inconsistent") + if not expected_ready: + missing_count += 1 + entries.append( + ( + spec, + { + **spec.to_dict(), + "missing_scopes": normalized_missing, + "publication_ready": publication_ready, + "ready": expected_ready, + }, + ) + ) + ready = missing_count == 0 + if (value.get("ready") is True) != ready: + raise ValueError("permission guidance aggregate ready state is inconsistent") + return ready, missing_count, entries + + +def normalize_permission_guidance(value: Mapping[str, object]) -> dict[str, object]: + """Validate and normalize a permission guidance payload.""" + ready, missing_count, entries = _normalize_permission_guidance_items(value) + return { + "schema_version": PERMISSION_GUIDANCE_SCHEMA_VERSION, + "ready": ready, + "requirement_count": len(entries), + "missing_requirement_count": missing_count, + "items": [item for _, item in entries], + } + + +def _project_permission_status_entries( + *, + ready: bool, + missing_count: int, + entries: Sequence[tuple[_RequirementSpec, Mapping[str, object]]], +) -> ExternalConnectorPermissionStatus: + operations = sorted( + {safe_token(spec.operation, field="operation") for spec, _ in entries} + ) + publication_required = any(spec.publication_required for spec, _ in entries) + return { + "schema_version": PERMISSION_STATUS_SCHEMA_VERSION, + "ready": ready, + "requirement_count": len(entries), + "missing_requirement_count": missing_count, + "operations": operations, + "publication_required": publication_required, + "private_scope_values_captured": False, + "private_repair_urls_captured": False, + "private_provider_identity_captured": False, + } + + +def project_permission_status_for_registration( + *, + expected_specs: Sequence[_RequirementSpec], + permission_guidance: Mapping[str, object], +) -> ExternalConnectorPermissionStatus: + """Validate guidance alignment against registration specs and project status once.""" + ready, missing_count, entries = _normalize_permission_guidance_items( + permission_guidance + ) + expected = sorted(spec.fingerprint() for spec in expected_specs) + observed = sorted(spec.fingerprint() for spec, _ in entries) + if observed != expected: + raise ValueError( + "permission guidance must match the registered Connector requirements" + ) + return _project_permission_status_entries( + ready=ready, + missing_count=missing_count, + entries=entries, + ) + + +def permission_guidance_for_registration( + *, + registration: Mapping[str, object], + permission_guidance: Mapping[str, object], +) -> dict[str, object]: + """Verify permission guidance covers exact registration requirement fingerprints.""" + raw_expected = registration["permission_requirements"] + if not isinstance(raw_expected, Sequence) or isinstance(raw_expected, (str, bytes)): + raise TypeError("registration permission_requirements are invalid") + expected_specs = [ + _normalize_requirement_spec(item) + if isinstance(item, Mapping) + else _invalid_requirement_type() + for item in raw_expected + ] + ready, missing_count, entries = _normalize_permission_guidance_items( + permission_guidance + ) + expected = sorted(spec.fingerprint() for spec in expected_specs) + observed = sorted(spec.fingerprint() for spec, _ in entries) + if observed != expected: + raise ValueError( + "permission guidance must match the registered Connector requirements" + ) + return { + "schema_version": PERMISSION_GUIDANCE_SCHEMA_VERSION, + "ready": ready, + "requirement_count": len(entries), + "missing_requirement_count": missing_count, + "items": [item for _, item in entries], + } + + +def _invalid_requirement_type() -> _RequirementSpec: + raise TypeError("external connector permission requirements are invalid") + + +def project_external_connector_permission_status( + guidance: Mapping[str, object], +) -> ExternalConnectorPermissionStatus: + """Hide exact scopes and repair URLs from status and quota projections.""" + + ready, missing_count, entries = _normalize_permission_guidance_items(guidance) + return _project_permission_status_entries( + ready=ready, + missing_count=missing_count, + entries=entries, + ) + + +def validate_permission_requirements_for_connector( + *, + connector: Mapping[str, object], + requirements: Sequence[Mapping[str, object]], +) -> None: + """Ensure registered permission requirements cover Connector operations.""" + specs = [ + _RequirementSpec( + provider_kind=str(req["provider_kind"]), + provider_identity="", + operation=str(req["operation"]), + required_scopes=(), + publication_required=False, + repair_url="", + ) + for req in requirements + ] + validate_permission_specs_for_connector(connector=connector, specs=specs) + + +def validate_permission_specs_for_connector( + *, + connector: Mapping[str, object], + specs: Sequence[_RequirementSpec], +) -> None: + """Validate provider kind and advertised capability coverage against specs.""" + raw_capabilities = connector.get("capabilities") + if not isinstance(raw_capabilities, Sequence) or isinstance( + raw_capabilities, (str, bytes) + ): + raise TypeError("connector capabilities must be a sequence") + capability_values = {str(cap) for cap in raw_capabilities} + provider_kind = str(connector.get("provider_kind") or "") + for spec in specs: + if spec.provider_kind != provider_kind: + raise ValueError("permission provider_kind must match the Connector") + if spec.operation not in capability_values: + raise ValueError("permission operation must be advertised by the Connector") + required_operations = {ExternalConnectorCapability.HISTORY_CATCH_UP.value} + if connector.get("response_policy") != ExternalResponsePolicy.NO_RESPONSE.value: + required_operations.update( + { + ExternalConnectorCapability.RESPONSE_WRITE.value, + ExternalConnectorCapability.RESPONSE_READBACK.value, + } + ) + if required_operations.difference(spec.operation for spec in specs): + raise ValueError( + "document-comment permission requirements do not cover provider calls" + ) diff --git a/loopx/extensions/external_connector_provider.py b/loopx/extensions/external_connector_provider.py index db984e8d60..17609cac2c 100644 --- a/loopx/extensions/external_connector_provider.py +++ b/loopx/extensions/external_connector_provider.py @@ -7,13 +7,33 @@ from __future__ import annotations -import hashlib -import re from collections.abc import Callable, Mapping, Sequence -from typing import Any -from urllib.parse import urlsplit +import hashlib +from typing import TypedDict from ..authority import normalize_project_materials +from .external_connector_permissions import ( + PERMISSION_GUIDANCE_SCHEMA_VERSION, + PERMISSION_REQUIREMENT_SCHEMA_VERSION, + SAFE_SCOPE_PATTERN, + ExternalConnectorPermissionStatus, + _RequirementSpec, + build_external_connector_permission_requirement, + evaluate_external_connector_permissions, + normalize_permission_guidance as _normalize_permission_guidance, + normalize_permission_requirement as _normalize_permission_requirement, + normalize_permission_requirement_specs, + normalize_permission_requirements as _normalize_permission_requirements, + permission_guidance_for_registration as _permission_guidance_for_registration, + permission_requirement_fingerprint as _permission_requirement_fingerprint, + project_external_connector_permission_status, + project_permission_status_for_registration, + repair_url as _repair_url, + safe_token, + scope_values as _scope_values, + validate_permission_requirements_for_connector as _validate_permission_requirements_for_connector, + validate_permission_specs_for_connector, +) from .external_connector_runtime import ( CONNECTOR_SCHEMA_VERSION, EVENT_SCHEMA_VERSION, @@ -30,322 +50,114 @@ settle_external_connector_event, ) -PERMISSION_REQUIREMENT_SCHEMA_VERSION = ( - "agent_external_connector_permission_requirement_v0" -) -PERMISSION_GUIDANCE_SCHEMA_VERSION = "agent_external_connector_permission_guidance_v0" DOCUMENT_COMMENT_REGISTRATION_SCHEMA_VERSION = ( "agent_document_comment_connector_registration_v0" ) PROVIDER_PAGE_SCHEMA_VERSION = "agent_external_connector_provider_page_v0" +PROVIDER_CAPTURE_SCHEMA_VERSION = "agent_external_connector_provider_capture_v0" +PROVIDER_SETTLEMENT_SCHEMA_VERSION = "agent_external_connector_provider_settlement_v0" -SAFE_SCOPE_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}") - -ProviderPageReader = Callable[[Mapping[str, Any], str | None, int], Mapping[str, Any]] +ProviderPageReader = Callable[ + [dict[str, object], str | None, int], + Mapping[str, object], +] ProviderResponseWriter = Callable[ - [Mapping[str, Any], Mapping[str, Any], str, str], - Mapping[str, Any], + [dict[str, object], dict[str, object], str, str], + Mapping[str, object], ] -def _safe_token(value: Any, *, field: str) -> str: - normalized = str(value or "").strip() - if not SAFE_TOKEN_PATTERN.fullmatch(normalized): - raise ValueError(f"{field} must be an opaque public-safe token") - return normalized +class DocumentCommentConnectorRegistration(TypedDict): + """Typed document-comment connector registration payload.""" + schema_version: str + connector: dict[str, object] + authority_material_ref: str + authority_relation: str + comment_authority: str + permission_requirements: list[dict[str, object]] -def _scope_values(values: Sequence[str], *, field: str) -> list[str]: - normalized = {str(value or "").strip() for value in values} - if not normalized or any( - not SAFE_SCOPE_PATTERN.fullmatch(value) for value in normalized - ): - raise ValueError(f"{field} must contain provider scope tokens") - return sorted(normalized) - - -def _repair_url(value: Any) -> str: - normalized = str(value or "").strip() - parsed = urlsplit(normalized) - if ( - parsed.scheme != "https" - or not parsed.netloc - or parsed.username - or parsed.password - or parsed.fragment - or len(normalized) > 2048 - ): - raise ValueError("repair_url must be a bounded official HTTPS URL") - return normalized +class DocumentCommentConnectorStatus(TypedDict): + """Typed content-free document-comment connector status projection.""" -def build_external_connector_permission_requirement( - *, - provider_kind: str, - provider_identity: str, - operation: str, - required_scopes: Sequence[str], - publication_required: bool, - repair_url: str, -) -> dict[str, Any]: - """Build provider-owned, owner-local permission repair guidance.""" - - try: - capability = ExternalConnectorCapability(str(operation or "").strip()).value - except ValueError as exc: - allowed = ", ".join(item.value for item in ExternalConnectorCapability) - raise ValueError(f"operation must be one of: {allowed}") from exc - return { - "schema_version": PERMISSION_REQUIREMENT_SCHEMA_VERSION, - "provider_kind": _safe_token(provider_kind, field="provider_kind"), - "provider_identity": _safe_token( - provider_identity, - field="provider_identity", - ), - "operation": capability, - "required_scopes": _scope_values( - required_scopes, - field="required_scopes", - ), - "publication_required": bool(publication_required), - "repair_url": _repair_url(repair_url), - } + schema_version: str + connector: dict[str, object] + authority_material_bound: bool + authority_relation: str + comment_authority: str + permissions: ExternalConnectorPermissionStatus + private_authority_material_ref_captured: bool -def _normalize_permission_requirement(value: Mapping[str, Any]) -> dict[str, Any]: - if value.get("schema_version") != PERMISSION_REQUIREMENT_SCHEMA_VERSION: - raise ValueError("external connector permission requirement schema is invalid") - scopes = value.get("required_scopes") - if not isinstance(scopes, Sequence) or isinstance(scopes, (str, bytes)): - raise TypeError("required_scopes must be a sequence") - return build_external_connector_permission_requirement( - provider_kind=str(value.get("provider_kind") or ""), - provider_identity=str(value.get("provider_identity") or ""), - operation=str(value.get("operation") or ""), - required_scopes=[str(scope) for scope in scopes], - publication_required=value.get("publication_required") is True, - repair_url=str(value.get("repair_url") or ""), - ) - - -def _normalize_permission_requirements( - values: Sequence[Mapping[str, Any]], -) -> list[dict[str, Any]]: - if isinstance(values, (str, bytes)) or any( - not isinstance(requirement, Mapping) for requirement in values - ): - raise TypeError("external connector permission requirements are invalid") - requirements = [ - _normalize_permission_requirement(requirement) for requirement in values - ] - identities = [ - ( - requirement["provider_kind"], - requirement["provider_identity"], - requirement["operation"], - ) - for requirement in requirements - ] - if len(identities) != len(set(identities)): - raise ValueError("external connector permission requirements are duplicated") - return requirements - - -def _permission_requirement_fingerprint( - requirement: Mapping[str, Any], -) -> tuple[Any, ...]: - return ( - requirement["provider_kind"], - requirement["provider_identity"], - requirement["operation"], - tuple(requirement["required_scopes"]), - requirement["publication_required"], - requirement["repair_url"], - ) +def _safe_token(value: object, *, field: str) -> str: + return safe_token(value, field=field, pattern=SAFE_TOKEN_PATTERN) -def evaluate_external_connector_permissions( - *, - requirements: Sequence[Mapping[str, Any]], - granted_scopes: Mapping[str, Sequence[str]], - published: bool, -) -> dict[str, Any]: - """Return exact owner-local guidance without promoting it to public status.""" - - normalized_requirements = _normalize_permission_requirements(requirements) - items: list[dict[str, Any]] = [] - for requirement in normalized_requirements: - identity = str(requirement["provider_identity"]) - granted = { - str(scope or "").strip() for scope in granted_scopes.get(identity, []) - } - missing_scopes = [ - scope for scope in requirement["required_scopes"] if scope not in granted - ] - publication_ready = bool( - published or requirement["publication_required"] is not True - ) - ready = not missing_scopes and publication_ready - items.append( - { - **requirement, - "missing_scopes": missing_scopes, - "publication_ready": publication_ready, - "ready": ready, - } - ) - return { - "ok": True, - "schema_version": PERMISSION_GUIDANCE_SCHEMA_VERSION, - "ready": all(item["ready"] for item in items), - "requirement_count": len(items), - "missing_requirement_count": sum(not item["ready"] for item in items), - "items": items, - "local_private_guidance_returned": bool(items), - "credentials_captured": False, +def _normalized_registration_parts( + value: Mapping[str, object], +) -> tuple[DocumentCommentConnectorRegistration, dict[str, object], list[_RequirementSpec]]: + if value.get("schema_version") != DOCUMENT_COMMENT_REGISTRATION_SCHEMA_VERSION: + raise ValueError("document-comment Connector registration schema is invalid") + connector = value.get("connector") + if not isinstance(connector, Mapping): + raise TypeError("document-comment Connector is invalid") + raw_connector = normalize_external_connector_binding(connector) + normalized_connector: dict[str, object] = { + str(key): item for key, item in raw_connector.items() } - - -def _normalize_permission_guidance(value: Mapping[str, Any]) -> dict[str, Any]: - if value.get("schema_version") != PERMISSION_GUIDANCE_SCHEMA_VERSION: - raise ValueError("external connector permission guidance schema is invalid") - raw_items = value.get("items") - if not isinstance(raw_items, list) or any( - not isinstance(item, Mapping) for item in raw_items + if normalized_connector["schema_version"] != CONNECTOR_SCHEMA_VERSION: + raise ValueError("document-comment Connector schema is invalid") + if normalized_connector["source_kind"] != ExternalSourceKind.DOCUMENT_COMMENT.value: + raise ValueError("document-comment registration source kind is invalid") + if value.get("authority_relation") != "reference_only": + raise ValueError("document-comment authority relation is invalid") + if value.get("comment_authority") != "external_input_only": + raise ValueError("document-comment authority policy is invalid") + requirements = value.get("permission_requirements") + if not isinstance(requirements, list) or any( + not isinstance(requirement, Mapping) for requirement in requirements ): - raise TypeError("external connector permission guidance items are invalid") - items: list[dict[str, Any]] = [] - for raw_item in raw_items: - requirement = _normalize_permission_requirement(raw_item) - missing_scopes = raw_item.get("missing_scopes") - if not isinstance(missing_scopes, list): - raise TypeError("permission missing_scopes are invalid") - normalized_missing = ( - _scope_values( - [str(scope) for scope in missing_scopes], - field="missing_scopes", - ) - if missing_scopes - else [] - ) - if not set(normalized_missing).issubset(requirement["required_scopes"]): - raise ValueError("missing_scopes must belong to required_scopes") - publication_ready = raw_item.get("publication_ready") is True - expected_ready = not normalized_missing and publication_ready - if (raw_item.get("ready") is True) != expected_ready: - raise ValueError("permission guidance ready state is inconsistent") - items.append( - { - **requirement, - "missing_scopes": normalized_missing, - "publication_ready": publication_ready, - "ready": expected_ready, - } - ) - ready = all(item["ready"] for item in items) - if (value.get("ready") is True) != ready: - raise ValueError("permission guidance aggregate ready state is inconsistent") - return { - "schema_version": PERMISSION_GUIDANCE_SCHEMA_VERSION, - "ready": ready, - "requirement_count": len(items), - "missing_requirement_count": sum(not item["ready"] for item in items), - "items": items, - } - - -def _permission_guidance_for_registration( - *, - registration: Mapping[str, Any], - permission_guidance: Mapping[str, Any], -) -> dict[str, Any]: - normalized_guidance = _normalize_permission_guidance(permission_guidance) - expected = sorted( - _permission_requirement_fingerprint(requirement) - for requirement in registration["permission_requirements"] - ) - observed = sorted( - _permission_requirement_fingerprint(requirement) - for requirement in normalized_guidance["items"] - ) - if observed != expected: - raise ValueError( - "permission guidance must match the registered Connector requirements" - ) - return normalized_guidance - - -def project_external_connector_permission_status( - guidance: Mapping[str, Any], -) -> dict[str, Any]: - """Hide exact scopes and repair URLs from status and quota projections.""" - - normalized = _normalize_permission_guidance(guidance) - items = normalized["items"] - operations = sorted( - { - _safe_token(item.get("operation"), field="operation") - for item in items - if isinstance(item, Mapping) - } + raise TypeError("document-comment permission requirements are invalid") + specs = normalize_permission_requirement_specs(requirements) + validate_permission_specs_for_connector( + connector=normalized_connector, + specs=specs, ) - return { - "schema_version": "agent_external_connector_permission_status_v0", - "ready": normalized["ready"], - "requirement_count": len(items), - "missing_requirement_count": sum( - isinstance(item, Mapping) and item.get("ready") is not True - for item in items - ), - "operations": operations, - "publication_required": any( - isinstance(item, Mapping) and item.get("publication_required") is True - for item in items + registration: DocumentCommentConnectorRegistration = { + "schema_version": DOCUMENT_COMMENT_REGISTRATION_SCHEMA_VERSION, + "connector": normalized_connector, + "authority_material_ref": _safe_token( + value.get("authority_material_ref"), + field="authority_material_ref", ), - "private_scope_values_captured": False, - "private_repair_urls_captured": False, - "private_provider_identity_captured": False, + "authority_relation": "reference_only", + "comment_authority": "external_input_only", + "permission_requirements": [spec.to_dict() for spec in specs], } + return registration, normalized_connector, specs -def _validate_permission_requirements_for_connector( - *, - connector: Mapping[str, Any], - requirements: Sequence[Mapping[str, Any]], -) -> None: - capability_values = set(connector["capabilities"]) - for requirement in requirements: - if requirement["provider_kind"] != connector["provider_kind"]: - raise ValueError("permission provider_kind must match the Connector") - if requirement["operation"] not in capability_values: - raise ValueError("permission operation must be advertised by the Connector") - required_operations = {ExternalConnectorCapability.HISTORY_CATCH_UP.value} - if connector["response_policy"] != ExternalResponsePolicy.NO_RESPONSE.value: - required_operations.update( - { - ExternalConnectorCapability.RESPONSE_WRITE.value, - ExternalConnectorCapability.RESPONSE_READBACK.value, - } - ) - missing_operations = required_operations.difference( - requirement["operation"] for requirement in requirements - ) - if missing_operations: - raise ValueError( - "document-comment permission requirements do not cover provider calls" - ) +def _normalize_document_comment_registration( + value: Mapping[str, object], +) -> DocumentCommentConnectorRegistration: + registration, _, _ = _normalized_registration_parts(value) + return registration def build_document_comment_connector_registration( *, - connector: Mapping[str, Any], + connector: Mapping[str, object], authority_material_ref: str, - project_materials: Mapping[str, Any] | Sequence[Mapping[str, Any]], - permission_requirements: Sequence[Mapping[str, Any]], -) -> dict[str, Any]: + project_materials: Mapping[str, object] | Sequence[Mapping[str, object]], + permission_requirements: Sequence[Mapping[str, object]], +) -> DocumentCommentConnectorRegistration: """Link comments to a separately registered material without granting authority.""" - normalized_connector = normalize_external_connector_binding(connector) + raw_connector = normalize_external_connector_binding(connector) + normalized_connector: dict[str, object] = { + str(key): item for key, item in raw_connector.items() + } if normalized_connector["source_kind"] != ExternalSourceKind.DOCUMENT_COMMENT.value: raise ValueError("document-comment registration requires document_comment") material_ref = _safe_token( @@ -355,10 +167,10 @@ def build_document_comment_connector_registration( materials = normalize_project_materials(project_materials) if material_ref not in materials: raise ValueError("authority material must be registered before its comments") - requirements = _normalize_permission_requirements(permission_requirements) - _validate_permission_requirements_for_connector( + specs = normalize_permission_requirement_specs(permission_requirements) + validate_permission_specs_for_connector( connector=normalized_connector, - requirements=requirements, + specs=specs, ) return { "schema_version": DOCUMENT_COMMENT_REGISTRATION_SCHEMA_VERSION, @@ -366,91 +178,54 @@ def build_document_comment_connector_registration( "authority_material_ref": material_ref, "authority_relation": "reference_only", "comment_authority": "external_input_only", - "permission_requirements": requirements, + "permission_requirements": [spec.to_dict() for spec in specs], } def project_document_comment_connector_status( *, - registration: Mapping[str, Any], - permission_guidance: Mapping[str, Any], -) -> dict[str, Any]: + registration: Mapping[str, object], + permission_guidance: Mapping[str, object], +) -> DocumentCommentConnectorStatus: """Project a content-free registration and permission status.""" - normalized = _normalize_document_comment_registration(registration) - normalized_guidance = _permission_guidance_for_registration( - registration=normalized, + normalized, connector, expected_specs = _normalized_registration_parts( + registration + ) + permission_status = project_permission_status_for_registration( + expected_specs=expected_specs, permission_guidance=permission_guidance, ) + raw_status = project_external_connector_status(connector) return { "schema_version": "agent_document_comment_connector_status_v0", - "connector": project_external_connector_status(normalized["connector"]), + "connector": {str(key): item for key, item in raw_status.items()}, "authority_material_bound": True, "authority_relation": normalized["authority_relation"], "comment_authority": normalized["comment_authority"], - "permissions": project_external_connector_permission_status( - normalized_guidance - ), + "permissions": permission_status, "private_authority_material_ref_captured": False, } -def _normalize_document_comment_registration( - value: Mapping[str, Any], -) -> dict[str, Any]: - if value.get("schema_version") != DOCUMENT_COMMENT_REGISTRATION_SCHEMA_VERSION: - raise ValueError("document-comment Connector registration schema is invalid") - connector = value.get("connector") - if not isinstance(connector, Mapping): - raise TypeError("document-comment Connector is invalid") - normalized_connector = normalize_external_connector_binding(connector) - if normalized_connector["schema_version"] != CONNECTOR_SCHEMA_VERSION: - raise ValueError("document-comment Connector schema is invalid") - if normalized_connector["source_kind"] != ExternalSourceKind.DOCUMENT_COMMENT.value: - raise ValueError("document-comment registration source kind is invalid") - if value.get("authority_relation") != "reference_only": - raise ValueError("document-comment authority relation is invalid") - if value.get("comment_authority") != "external_input_only": - raise ValueError("document-comment authority policy is invalid") - requirements = value.get("permission_requirements") - if not isinstance(requirements, list) or any( - not isinstance(requirement, Mapping) for requirement in requirements - ): - raise TypeError("document-comment permission requirements are invalid") - normalized_requirements = _normalize_permission_requirements(requirements) - _validate_permission_requirements_for_connector( - connector=normalized_connector, - requirements=normalized_requirements, - ) - return { - "schema_version": DOCUMENT_COMMENT_REGISTRATION_SCHEMA_VERSION, - "connector": normalized_connector, - "authority_material_ref": _safe_token( - value.get("authority_material_ref"), - field="authority_material_ref", - ), - "authority_relation": "reference_only", - "comment_authority": "external_input_only", - "permission_requirements": normalized_requirements, - } - - def build_external_connector_provider_page( *, - events: Sequence[Mapping[str, Any]], + events: Sequence[Mapping[str, object]], expected_cursor: str | None, next_cursor: str, has_more: bool, -) -> dict[str, Any]: +) -> dict[str, object]: """Build one owner-private page returned by a provider adapter.""" if len(events) > 500: raise ValueError("external connector provider page exceeds 500 events") + copied_events: list[dict[str, object]] = [] for event in events: if not isinstance(event, Mapping): raise TypeError("provider page events must be objects") if event.get("schema_version") != EVENT_SCHEMA_VERSION: raise ValueError("provider page contains an invalid event schema") + copied_events.append(dict(event)) normalized_next_cursor = str(next_cursor or "").strip() if not normalized_next_cursor or len(normalized_next_cursor) > 2048: raise ValueError("next_cursor must be a bounded owner-private value") @@ -466,35 +241,32 @@ def build_external_connector_provider_page( "expected_cursor": normalized_expected_cursor, "next_cursor": normalized_next_cursor, "has_more": bool(has_more), - "events": [dict(event) for event in events], + "events": copied_events, } def capture_document_comment_provider_page( *, project: str, - registration: Mapping[str, Any], - permission_guidance: Mapping[str, Any], + registration: Mapping[str, object], + permission_guidance: Mapping[str, object], page_reader: ProviderPageReader, expected_cursor: str | None, limit: int = 100, max_pending: int = 1000, execute: bool = False, -) -> dict[str, Any]: +) -> dict[str, object]: """Read and durably capture one provider page after permission readiness.""" - normalized = _normalize_document_comment_registration(registration) - normalized_guidance = _permission_guidance_for_registration( - registration=normalized, + _, connector, expected_specs = _normalized_registration_parts(registration) + permission_status = project_permission_status_for_registration( + expected_specs=expected_specs, permission_guidance=permission_guidance, ) - permission_status = project_external_connector_permission_status( - normalized_guidance - ) if permission_status["ready"] is not True: return { "ok": False, - "schema_version": "agent_external_connector_provider_capture_v0", + "schema_version": PROVIDER_CAPTURE_SCHEMA_VERSION, "status": "permission_required", "execute": execute, "external_read_performed": False, @@ -504,13 +276,13 @@ def capture_document_comment_provider_page( if not execute: return { "ok": True, - "schema_version": "agent_external_connector_provider_capture_v0", + "schema_version": PROVIDER_CAPTURE_SCHEMA_VERSION, "status": "preview_ready", "execute": False, "external_read_performed": False, "private_provider_payload_captured": False, } - page = page_reader(normalized["connector"], expected_cursor, bounded_limit) + page = page_reader(connector, expected_cursor, bounded_limit) if not isinstance(page, Mapping): raise TypeError("external connector provider page is invalid") if page.get("schema_version") != PROVIDER_PAGE_SCHEMA_VERSION: @@ -526,7 +298,7 @@ def capture_document_comment_provider_page( raise ValueError("external connector provider exceeded the requested limit") capture = capture_external_connector_events( project=project, - binding=normalized["connector"], + binding=connector, events=events, expected_cursor=expected_cursor, next_cursor=str(page.get("next_cursor") or ""), @@ -535,7 +307,7 @@ def capture_document_comment_provider_page( ) return { **capture, - "schema_version": "agent_external_connector_provider_capture_v0", + "schema_version": PROVIDER_CAPTURE_SCHEMA_VERSION, "provider_status": "captured" if capture["ok"] else capture["status"], "has_more": page.get("has_more") is True, "external_read_performed": True, @@ -543,36 +315,49 @@ def capture_document_comment_provider_page( } +def _settlement_guard_result( + *, + ok: bool, + status: str, + execute: bool, + ack_decision: Mapping[str, object] | None = None, +) -> dict[str, object]: + payload: dict[str, object] = { + "ok": ok, + "schema_version": PROVIDER_SETTLEMENT_SCHEMA_VERSION, + "status": status, + "execute": execute, + "external_write_performed": False, + } + if ack_decision is not None: + payload["ack_decision"] = dict(ack_decision) + return payload + + def reply_and_settle_document_comment_event( *, project: str, - registration: Mapping[str, Any], - permission_guidance: Mapping[str, Any], + registration: Mapping[str, object], + permission_guidance: Mapping[str, object], event_id: str, - effect_receipt: Mapping[str, Any] | None, + effect_receipt: Mapping[str, object] | None, reply_text: str | None, response_writer: ProviderResponseWriter | None, execute: bool = False, -) -> dict[str, Any]: +) -> dict[str, object]: """Enforce effect-before-response-before-ACK at the provider call site.""" - normalized = _normalize_document_comment_registration(registration) - connector = normalized["connector"] - normalized_guidance = _permission_guidance_for_registration( - registration=normalized, + _, connector, expected_specs = _normalized_registration_parts(registration) + permission_status = project_permission_status_for_registration( + expected_specs=expected_specs, permission_guidance=permission_guidance, ) - permission_status = project_external_connector_permission_status( - normalized_guidance - ) if permission_status["ready"] is not True: - return { - "ok": False, - "schema_version": "agent_external_connector_provider_settlement_v0", - "status": "permission_required", - "execute": execute, - "external_write_performed": False, - } + return _settlement_guard_result( + ok=False, + status="permission_required", + execute=execute, + ) pending = drain_external_connector_inbox( project=project, binding=connector, @@ -581,29 +366,25 @@ def reply_and_settle_document_comment_event( items = pending.get("items") item = items[0] if isinstance(items, list) and items else None if not isinstance(item, Mapping) or str(item.get("event_id") or "") != event_id: - return { - "ok": False, - "schema_version": "agent_external_connector_provider_settlement_v0", - "status": "ordered_event_required", - "execute": execute, - "external_write_performed": False, - } + return _settlement_guard_result( + ok=False, + status="ordered_event_required", + execute=execute, + ) effect_decision = decide_external_event_ack( event_id=event_id, effect_receipt=effect_receipt, response_policy=ExternalResponsePolicy.NO_RESPONSE.value, ) if effect_decision["effect_ready"] is not True: - return { - "ok": False, - "schema_version": "agent_external_connector_provider_settlement_v0", - "status": "durable_effect_required", - "execute": execute, - "external_write_performed": False, - "ack_decision": effect_decision, - } + return _settlement_guard_result( + ok=False, + status="durable_effect_required", + execute=execute, + ack_decision=effect_decision, + ) response_policy = str(connector["response_policy"]) - response_receipt: Mapping[str, Any] | None = None + response_receipt: Mapping[str, object] | None = None if response_policy != ExternalResponsePolicy.NO_RESPONSE.value: text = " ".join(str(reply_text or "").split())[:1200] if not text: @@ -611,13 +392,11 @@ def reply_and_settle_document_comment_event( if response_writer is None: raise ValueError("response-capable Connector requires a response_writer") if not execute: - return { - "ok": True, - "schema_version": "agent_external_connector_provider_settlement_v0", - "status": "preview_ready", - "execute": False, - "external_write_performed": False, - } + return _settlement_guard_result( + ok=True, + status="preview_ready", + execute=False, + ) idempotency_key = ( "sha256:" + hashlib.sha256( @@ -630,28 +409,28 @@ def reply_and_settle_document_comment_event( ).encode("utf-8") ).hexdigest() ) - response_receipt = response_writer( + raw_receipt = response_writer( connector, - item, + dict(item), text, idempotency_key, ) - if not isinstance(response_receipt, Mapping): + if not isinstance(raw_receipt, Mapping): raise TypeError("response_writer must return a response receipt") - if response_receipt.get("idempotency_key") != idempotency_key: + if raw_receipt.get("idempotency_key") != idempotency_key: raise ValueError("response receipt must bind the requested idempotency_key") response_receipt = build_external_event_response_receipt( event_id=event_id, external_write_performed=( - response_receipt.get("external_write_performed") is True + raw_receipt.get("external_write_performed") is True ), verification_performed=( - response_receipt.get("verification_performed") is True + raw_receipt.get("verification_performed") is True ), response_verified=( - response_receipt.get("response_verified") is True - or response_receipt.get("reply_verified") is True - or response_receipt.get("readback_verified") is True + raw_receipt.get("response_verified") is True + or raw_receipt.get("reply_verified") is True + or raw_receipt.get("readback_verified") is True ), ) settlement = settle_external_connector_event( @@ -664,7 +443,7 @@ def reply_and_settle_document_comment_event( ) return { **settlement, - "schema_version": "agent_external_connector_provider_settlement_v0", + "schema_version": PROVIDER_SETTLEMENT_SCHEMA_VERSION, "external_write_performed": bool( response_receipt and response_receipt.get("external_write_performed") is True @@ -676,3 +455,40 @@ def reply_and_settle_document_comment_event( ), "private_provider_payload_captured": False, } + + +__all__ = [ + "DOCUMENT_COMMENT_REGISTRATION_SCHEMA_VERSION", + "EVENT_SCHEMA_VERSION", + "PERMISSION_GUIDANCE_SCHEMA_VERSION", + "PERMISSION_REQUIREMENT_SCHEMA_VERSION", + "PROVIDER_CAPTURE_SCHEMA_VERSION", + "PROVIDER_PAGE_SCHEMA_VERSION", + "PROVIDER_SETTLEMENT_SCHEMA_VERSION", + "SAFE_SCOPE_PATTERN", + "SAFE_TOKEN_PATTERN", + "DocumentCommentConnectorRegistration", + "DocumentCommentConnectorStatus", + "ExternalConnectorCapability", + "ExternalConnectorPermissionStatus", + "ProviderPageReader", + "ProviderResponseWriter", + "_normalize_document_comment_registration", + "_normalize_permission_guidance", + "_normalize_permission_requirement", + "_normalize_permission_requirements", + "_permission_guidance_for_registration", + "_permission_requirement_fingerprint", + "_repair_url", + "_safe_token", + "_scope_values", + "_validate_permission_requirements_for_connector", + "build_document_comment_connector_registration", + "build_external_connector_permission_requirement", + "build_external_connector_provider_page", + "capture_document_comment_provider_page", + "evaluate_external_connector_permissions", + "project_document_comment_connector_status", + "project_external_connector_permission_status", + "reply_and_settle_document_comment_event", +] diff --git a/tests/extensions/test_external_connector_provider.py b/tests/extensions/test_external_connector_provider.py index 46ad928596..74a2fe4058 100644 --- a/tests/extensions/test_external_connector_provider.py +++ b/tests/extensions/test_external_connector_provider.py @@ -6,6 +6,7 @@ import pytest from loopx.extensions.external_connector_provider import ( + DocumentCommentConnectorRegistration, build_document_comment_connector_registration, build_external_connector_permission_requirement, build_external_connector_provider_page, @@ -71,7 +72,7 @@ def _requirements() -> list[dict[str, Any]]: ] -def _registration() -> dict[str, Any]: +def _registration() -> DocumentCommentConnectorRegistration: return build_document_comment_connector_registration( connector=_connector(), authority_material_ref="material-alpha", diff --git a/tests/extensions/test_external_connector_provider_contract.py b/tests/extensions/test_external_connector_provider_contract.py new file mode 100644 index 0000000000..84afe1f930 --- /dev/null +++ b/tests/extensions/test_external_connector_provider_contract.py @@ -0,0 +1,352 @@ +"""Contract, zero-Any, boundary, and efficiency tests for external_connector_provider.""" + +from __future__ import annotations + +import ast +from collections.abc import Mapping +from pathlib import Path +from types import MappingProxyType +import pytest + +from loopx import authority +from loopx.extensions import ( + external_connector_permissions as perms, + external_connector_provider as provider, + external_connector_runtime as runtime, +) + + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +def _binding(response_policy: str = "source_thread") -> dict[str, object]: + caps = ["history_catch_up", "acknowledge"] + if response_policy != "no_response": + caps.extend(["response_write", "response_readback"]) + raw = runtime.build_external_connector_binding( + goal_ref="goal-1", + agent_ref="agent-1", + provider_kind="provider-x", + source_kind=runtime.ExternalSourceKind.DOCUMENT_COMMENT.value, + source_ref="src-1", + capture_policy=runtime.ExternalCapturePolicy.INCREMENTAL.value, + ingress_policy=runtime.ExternalIngressPolicy.ASYNC_INBOX.value, + response_policy=response_policy, + cursor_ref=".loopx/inbox/doc/cursor.json", + lifecycle=runtime.ExternalConnectorLifecycle.CONNECTED.value, + capabilities=caps, + inbox_ref=".loopx/inbox/doc", + ) + return {str(k): v for k, v in raw.items()} + + +def _req(op: str) -> dict[str, object]: + return provider.build_external_connector_permission_requirement( + provider_kind="provider-x", + provider_identity="bot-x", + operation=op, + required_scopes=[f"scope:{op}", "scope:shared"], + publication_required=True, + repair_url="https://example.org/apps/x/permissions", + ) + + +def _event(event_id: str = "evt-1") -> dict[str, object]: + raw = runtime.build_external_connector_event( + event_id=event_id, + content="Review comment body", + occurred_at="2026-11-26T00:00:00Z", + addressed=True, + event_cursor=f"cur-{event_id}", + anchor_ref="anchor-1", + reply_chain_ref="chain-1", + ) + return {str(k): v for k, v in raw.items()} + + +def test_connector_provider_zero_any_budgets_and_pin_preservation() -> None: + targets = [ + ("loopx/extensions/external_connector_provider.py", 550), + ("loopx/extensions/external_connector_permissions.py", 550), + ("tests/extensions/test_external_connector_provider_contract.py", 500), + ] + for rel, max_loc in targets: + src = (REPO_ROOT / rel).read_text(encoding="utf-8") + assert len(src.splitlines()) <= max_loc, rel + tree = ast.parse(src) + anys = [n for n in ast.walk(tree) if isinstance(n, ast.Name) and n.id == "Any"] + assert anys == [], rel + assert ("type: " + "ignore") not in src, rel + assert ("no" + "qa") not in src, rel + + assert provider.SAFE_TOKEN_PATTERN is runtime.SAFE_TOKEN_PATTERN + assert provider.SAFE_SCOPE_PATTERN is perms.SAFE_SCOPE_PATTERN + assert provider.build_external_connector_permission_requirement is ( + perms.build_external_connector_permission_requirement + ) + assert provider.evaluate_external_connector_permissions is ( + perms.evaluate_external_connector_permissions + ) + assert provider.project_external_connector_permission_status is ( + perms.project_external_connector_permission_status + ) + + +def test_token_scope_and_repair_url_boundaries() -> None: + assert provider._safe_token("a" * 200, field="tok") == "a" * 200 + for bad_token in ("", "-lead", "bad token", "a/b", "a" * 201): + with pytest.raises(ValueError, match="opaque public-safe token"): + provider._safe_token(bad_token, field="tok") + + assert provider._scope_values(["b:1", "a/2", "a/2"], field="scopes") == ["a/2", "b:1"] + for bad_scopes in ([], ["ok", "bad scope"], ["a/b/" + "x" * 200]): + with pytest.raises(ValueError, match="provider scope tokens"): + provider._scope_values(bad_scopes, field="scopes") + + for bad_url in ( + "http://example.org/x", + "https://user:pass@example.org/x", + "https://example.org/x#frag", + "https://example.org/" + "a" * 2040, + ): + with pytest.raises(ValueError, match="official HTTPS URL"): + provider._repair_url(bad_url) + + with pytest.raises(ValueError, match="operation must be one of"): + provider.build_external_connector_permission_requirement( + provider_kind="provider-x", + provider_identity="bot-x", + operation="invalid_op", + required_scopes=["scope:a"], + publication_required=False, + repair_url="https://example.org/repair", + ) + + +def test_permission_compound_error_precedence_and_guidance_consistency() -> None: + r0 = _req("history_catch_up") + bad_schema = {**r0, "schema_version": "wrong"} + normalize_reqs = getattr(provider, "_normalize_permission_requirements") + with pytest.raises(TypeError, match="requirements are invalid"): + normalize_reqs([r0, r0, "not_mapping"]) + with pytest.raises(ValueError, match="requirement schema is invalid"): + provider._normalize_permission_requirements([r0, r0, bad_schema]) + with pytest.raises(ValueError, match="requirements are duplicated"): + provider._normalize_permission_requirements([r0, r0]) + + valid_guidance = provider.evaluate_external_connector_permissions( + requirements=[r0], + granted_scopes={"bot-x": ["scope:history_catch_up", "scope:shared"]}, + published=True, + ) + items = valid_guidance["items"] + assert isinstance(items, list) and len(items) == 1 + first = dict(items[0]) + with pytest.raises(ValueError, match="belong to required_scopes"): + provider._normalize_permission_guidance( + { + **valid_guidance, + "items": [{**first, "missing_scopes": ["scope:foreign"]}], + } + ) + with pytest.raises(ValueError, match="ready state is inconsistent"): + provider._normalize_permission_guidance( + { + **valid_guidance, + "items": [{**first, "ready": False}], + } + ) + with pytest.raises(ValueError, match="aggregate ready state is inconsistent"): + provider._normalize_permission_guidance({**valid_guidance, "ready": False}) + + +def test_provider_page_bounds_and_mapping_proxy_compatibility() -> None: + ev = _event() + with pytest.raises(ValueError, match="exceeds 500 events"): + provider.build_external_connector_provider_page( + events=[ev] * 501, + expected_cursor=None, + next_cursor="next-1", + has_more=False, + ) + with pytest.raises(ValueError, match="next_cursor"): + provider.build_external_connector_provider_page( + events=[], + expected_cursor=None, + next_cursor="c" * 2049, + has_more=False, + ) + with pytest.raises(ValueError, match="expected_cursor"): + provider.build_external_connector_provider_page( + events=[], + expected_cursor="", + next_cursor="next-1", + has_more=False, + ) + + page = provider.build_external_connector_provider_page( + events=[MappingProxyType(ev)], + expected_cursor="cur-0", + next_cursor="next-1", + has_more=True, + ) + assert page["events"] == [ev] + + +def test_capture_and_settlement_validation_and_single_guidance_pass( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + reqs = [_req("history_catch_up"), _req("response_write"), _req("response_readback")] + conn = MappingProxyType(_binding("source_thread")) + reg = provider.build_document_comment_connector_registration( + connector=conn, + authority_material_ref="mat-1", + project_materials={"mat-1": {"id": "mat-1"}}, + permission_requirements=[MappingProxyType(r) for r in reqs], + ) + + non_canonical: tuple[tuple[Mapping[str, object] | tuple[dict[str, object], ...] | list[Mapping[str, object]], str], ...] = ( + (({"title": "doc"},), "source_1"), + (MappingProxyType({"mat-1": {"id": "mat-1"}}), "mat-1"), + (MappingProxyType({"mat-1": MappingProxyType({"id": "mat-1"})}), "mat-1"), + ([MappingProxyType({"id": "mat-1"})], "mat-1"), + ) + for bad_materials, ref in non_canonical: + assert authority.normalize_project_materials(bad_materials) == {} + with pytest.raises(ValueError, match="must be registered before its comments"): + provider.build_document_comment_connector_registration( + connector=conn, + authority_material_ref=ref, + project_materials=bad_materials, + permission_requirements=reqs, + ) + guidance = provider.evaluate_external_connector_permissions( + requirements=reqs, + granted_scopes={ + "bot-x": [ + "scope:history_catch_up", + "scope:response_write", + "scope:response_readback", + "scope:shared", + ] + }, + published=True, + ) + reg_view = MappingProxyType(reg) + guidance_view = MappingProxyType(guidance) + + norm_calls = 0 + real_norm = perms._normalize_permission_guidance_items + + def _counting_norm( + value: object, + ) -> tuple[bool, int, list[tuple[perms._RequirementSpec, dict[str, object]]]]: + nonlocal norm_calls + norm_calls += 1 + assert isinstance(value, dict | MappingProxyType) + return real_norm(value) + + monkeypatch.setattr(perms, "_normalize_permission_guidance_items", _counting_norm) + + status = provider.project_document_comment_connector_status( + registration=reg_view, + permission_guidance=guidance_view, + ) + assert status["permissions"]["ready"] is True + assert norm_calls == 1 + + with pytest.raises(ValueError, match="exceeded the requested limit"): + provider.capture_document_comment_provider_page( + project=str(tmp_path), + registration=reg_view, + permission_guidance=guidance_view, + page_reader=lambda _c, cur, _l: provider.build_external_connector_provider_page( + events=[_event("e1"), _event("e2")], + expected_cursor=cur, + next_cursor="c2", + has_more=False, + ), + expected_cursor=None, + limit=1, + execute=True, + ) + assert norm_calls == 2 + + captured = provider.capture_document_comment_provider_page( + project=str(tmp_path), + registration=reg_view, + permission_guidance=guidance_view, + page_reader=lambda _c, cur, _l: provider.build_external_connector_provider_page( + events=[_event("evt-1")], + expected_cursor=cur, + next_cursor="c2", + has_more=False, + ), + expected_cursor=None, + execute=True, + ) + assert captured["ok"] is True and norm_calls == 3 + + effect = MappingProxyType( + { + "schema_version": runtime.EFFECT_RECEIPT_SCHEMA_VERSION, + "event_id": "evt-1", + "effect_id": "eff-1", + "effect_kind": runtime.ExternalEffectKind.TODO_UPDATE.value, + "status": "committed", + } + ) + with pytest.raises(ValueError, match="requires reply_text"): + provider.reply_and_settle_document_comment_event( + project=str(tmp_path), + registration=reg_view, + permission_guidance=guidance_view, + event_id="evt-1", + effect_receipt=effect, + reply_text=" ", + response_writer=lambda *_a: {}, + execute=True, + ) + with pytest.raises(ValueError, match="requires a response_writer"): + provider.reply_and_settle_document_comment_event( + project=str(tmp_path), + registration=reg_view, + permission_guidance=guidance_view, + event_id="evt-1", + effect_receipt=effect, + reply_text="Ack", + response_writer=None, + execute=True, + ) + with pytest.raises(ValueError, match="idempotency_key"): + provider.reply_and_settle_document_comment_event( + project=str(tmp_path), + registration=reg_view, + permission_guidance=guidance_view, + event_id="evt-1", + effect_receipt=effect, + reply_text="Ack", + response_writer=lambda *_a: {"idempotency_key": "wrong"}, + execute=True, + ) + + settled = provider.reply_and_settle_document_comment_event( + project=str(tmp_path), + registration=reg_view, + permission_guidance=guidance_view, + event_id="evt-1", + effect_receipt=effect, + reply_text="Done.", + response_writer=lambda _c, _i, _t, ik: MappingProxyType( + { + "idempotency_key": ik, + "external_write_performed": True, + "verification_performed": True, + "readback_verified": True, + } + ), + execute=True, + ) + assert settled["ok"] is True + assert settled["response_readback_verified"] is True