Skip to content

pyagent-dns API Reference

pyagent_dns

pyagent-dns: Agent naming plane and authority graph for multi-agent systems.

Action

Bases: StrEnum

What a principal may do with a capability.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
class Action(StrEnum):
    """What a principal may do with a capability."""

    READ = "read"
    WRITE = "write"
    CALL = "call"
    DELEGATE = "delegate"
    APPROVE = "approve"
    EXPORT = "export"
    EXECUTE = "execute"
    SPEND = "spend"
    DELETE = "delete"

AttenuationError

Bases: Exception

Raised when a delegate would hold more authority than its parent.

Attributes:

Name Type Description
dimension

The field that would widen, for example limits.max_amount.

parent_value

The parent's value.

requested_value

The requested value.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
class AttenuationError(Exception):
    """Raised when a delegate would hold more authority than its parent.

    Attributes:
        dimension: The field that would widen, for example ``limits.max_amount``.
        parent_value: The parent's value.
        requested_value: The requested value.
    """

    def __init__(
        self, dimension: str, parent_value: Any, requested_value: Any, message: str | None = None
    ) -> None:
        super().__init__(
            message
            or f"Delegation would exceed its parent on {dimension}: "
            f"parent={parent_value!r}, requested={requested_value!r}"
        )
        self.dimension = dimension
        self.parent_value = parent_value
        self.requested_value = requested_value

AuthorityGraph

Grants and the delegation links between them, plus call-time authorization.

Not thread-safe; see NameRegistry.

Parameters:

Name Type Description Default
registry NameRegistry | None

Registry the graph reports coverage against. uncovered and revoke_record need one.

None
clock Callable[[], float] | None

Epoch-seconds time source. Defaults to the registry's, else wall-clock time.

None
Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
class AuthorityGraph:
    """Grants and the delegation links between them, plus call-time authorization.

    Not thread-safe; see ``NameRegistry``.

    Args:
        registry: Registry the graph reports coverage against. ``uncovered`` and
            ``revoke_record`` need one.
        clock: Epoch-seconds time source. Defaults to the registry's, else wall-clock time.
    """

    def __init__(
        self, registry: NameRegistry | None = None, *, clock: Callable[[], float] | None = None
    ) -> None:
        self._registry = registry
        self._clock = clock or (registry.clock if registry else time.time)
        self._grants: dict[str, Grant] = {}
        self._revoked: set[str] = set()

    @property
    def registry(self) -> NameRegistry | None:
        """The bound registry, if any."""
        return self._registry

    def _now(self) -> datetime:
        return datetime.fromtimestamp(self._clock(), UTC)

    def _live(self, grant: Grant) -> bool:
        return grant.grant_id not in self._revoked and not grant.is_expired(self._now())

    # -- Grants ---------------------------------------------------------------------------

    def add_grant(self, grant: Grant) -> str:
        """Add a grant and return its id.

        A grant that names a parent is checked against it: the parent must exist and allow
        delegation, and the grant must not exceed it on any dimension. The graph therefore
        holds no grant broader than its parent, however the grant was authored.

        Raises:
            ValueError: If the id is already used, or the parent is missing.
            AttenuationError: If the grant exceeds its parent.
        """
        if grant.grant_id in self._grants:
            raise ValueError(f"Grant id '{grant.grant_id}' is already in the graph")
        if grant.parent_grant_id is not None:
            parent = self._grants.get(grant.parent_grant_id)
            if parent is None:
                raise ValueError(
                    f"Grant '{grant.grant_id}' names parent '{grant.parent_grant_id}', which is not in the graph"
                )
            self._assert_attenuates(parent, grant)
        self._grants[grant.grant_id] = grant
        return grant.grant_id

    def add_grants(self, grants: Iterable[Grant]) -> None:
        """Add several grants, parents before children whatever their order in the input.

        All or nothing: if any grant is rejected, none of them are added.
        """
        pending = list(grants)
        added: list[str] = []
        try:
            while pending:
                ready = [
                    g
                    for g in pending
                    if g.parent_grant_id is None or g.parent_grant_id in self._grants
                ]
                if not ready:
                    missing = sorted({g.parent_grant_id or "" for g in pending})
                    raise ValueError(
                        f"Grants name parent(s) not in the graph: {', '.join(missing)}"
                    )
                for grant in ready:
                    added.append(self.add_grant(grant))
                    pending.remove(grant)
        except Exception:
            for grant_id in added:
                del self._grants[grant_id]
            raise

    def get_grant(self, grant_id: str) -> Grant | None:
        """Return a grant, or ``None`` if it is unknown or revoked."""
        return None if grant_id in self._revoked else self._grants.get(grant_id)

    def grants_for(self, principal: str, action: Action | None = None) -> list[Grant]:
        """Return a principal's unrevoked, unexpired grants. Ancestry is not checked."""
        return [
            g
            for g in self._grants.values()
            if g.principal == principal and (action is None or g.action == action) and self._live(g)
        ]

    def revoke(self, grant_id: str) -> bool:
        """Revoke a grant. Returns True if it was present and not already revoked.

        Grants delegated from it stop authorizing on the next check, because every check
        validates the whole chain.
        """
        if grant_id in self._grants and grant_id not in self._revoked:
            self._revoked.add(grant_id)
            return True
        return False

    def is_revoked(self, grant_id: str) -> bool:
        """Return whether a grant has been revoked."""
        return grant_id in self._revoked

    def revoke_record(self, name: str, version: str | None = None) -> bool:
        """Revoke a record in the bound registry, so both halves of an incident response
        can be done from one handle."""
        if self._registry is None:
            raise ValueError("No registry is bound to this AuthorityGraph")
        return self._registry.revoke(name, version)

    # -- Delegation -----------------------------------------------------------------------

    def delegate(
        self, parent_grant_id: str, *, delegate_principal: str, scope: GrantScope
    ) -> DelegationResult:
        """Issue a grant to ``delegate_principal`` that is no broader than its parent.

        Fields left ``None`` in ``scope`` are inherited. Capability, action, and effect are
        always inherited: a delegate that needs a different capability needs its own grant
        from a policy owner, and delegation can never weaken an approval requirement.

        Raises:
            ValueError: If the parent is unknown, revoked, or expired.
            AttenuationError: If the parent does not allow delegation, the scope exceeds
                the parent on any dimension, or the parent requires attenuation and the
                scope narrows nothing. ``dimension`` names the offending field.
        """
        parent = self._grants.get(parent_grant_id)
        if parent is None:
            raise ValueError(f"Parent grant '{parent_grant_id}' not found")
        if not self._live(parent):
            raise ValueError(f"Parent grant '{parent_grant_id}' is revoked or expired")

        resource, limits = scope.resource or ResourceSelector(), scope.limits or Limits()
        child = Grant(
            grant_id=uuid.uuid4().hex,
            principal=delegate_principal,
            action=parent.action,
            capability=parent.capability,
            resource=ResourceSelector(
                data_classes=resource.data_classes or parent.resource.data_classes,
                account_scope=_inherit(resource.account_scope, parent.resource.account_scope),
                name_scope=_inherit(resource.name_scope, parent.resource.name_scope),
            ),
            purpose=_inherit(scope.purpose, parent.purpose),
            limits=Limits(
                max_records_per_call=_inherit(
                    limits.max_records_per_call, parent.limits.max_records_per_call
                ),
                max_calls_per_session=_inherit(
                    limits.max_calls_per_session, parent.limits.max_calls_per_session
                ),
                max_amount=_inherit(limits.max_amount, parent.limits.max_amount),
                currency=limits.currency or parent.limits.currency,
            ),
            delegation=parent.delegation,
            effect=parent.effect,
            approver_role=parent.approver_role,
            granted_by=parent.granted_by,
            policy_version=parent.policy_version,
            expires=_inherit(scope.expires, parent.expires),
            parent_grant_id=parent.grant_id,
        )
        self.add_grant(child)

        chain, _ = self._chain(child)
        token_id = uuid.uuid4().hex
        effective = self._limits_along(chain)
        canonical = json.dumps(
            {
                "token_id": token_id,
                "grant_chain": [g.grant_id for g in chain],
                "principal_chain": [g.principal for g in chain],
                "effective_limits": effective.to_dict(),
                "expires": child.expires.isoformat() if child.expires else None,
            },
            sort_keys=True,
        ).encode()
        token = DelegationToken(
            token_id=token_id,
            grant_chain=tuple(g.grant_id for g in chain),
            principal_chain=tuple(g.principal for g in chain),
            effective_limits=effective,
            expires=child.expires,
            token_hash=f"sha256:{hashlib.sha256(canonical).hexdigest()}",
        )
        return DelegationResult(grant=child, token=token)

    @staticmethod
    def _assert_attenuates(parent: Grant, child: Grant) -> None:
        """Raise ``AttenuationError`` unless ``child`` is within ``parent`` on every dimension."""
        if not parent.delegation.allowed:
            raise AttenuationError("delegation.allowed", False, True)
        for dimension in ("action", "capability"):
            if getattr(child, dimension) != getattr(parent, dimension):
                raise AttenuationError(
                    dimension, getattr(parent, dimension), getattr(child, dimension)
                )
        if child.purpose != parent.purpose:
            raise AttenuationError("purpose", parent.purpose, child.purpose)
        if parent.effect == GrantEffect.REQUIRE_APPROVAL and child.effect != parent.effect:
            raise AttenuationError("effect", parent.effect, child.effect)

        p_res, c_res = parent.resource, child.resource
        if _rank(c_res.data_classes) > _rank(p_res.data_classes):
            raise AttenuationError("resource.data_classes", p_res.data_classes, c_res.data_classes)
        for scope in ("account_scope", "name_scope"):
            p_val, c_val = getattr(p_res, scope), getattr(c_res, scope)
            if p_val is not None and c_val != p_val:
                raise AttenuationError(f"resource.{scope}", p_val, c_val)

        p_lim, c_lim = parent.limits, child.limits
        for name in ("max_records_per_call", "max_calls_per_session", "max_amount"):
            p_val, c_val = getattr(p_lim, name), getattr(c_lim, name)
            if p_val is not None and (c_val is None or c_val > p_val):
                raise AttenuationError(f"limits.{name}", p_val, c_val)
        if p_lim.currency is not None and c_lim.currency != p_lim.currency:
            raise AttenuationError("limits.currency", p_lim.currency, c_lim.currency)

        if parent.expires is not None and (child.expires is None or child.expires > parent.expires):
            raise AttenuationError("expires", parent.expires, child.expires)

        if parent.delegation.must_attenuate and not _narrows(parent, child):
            raise AttenuationError(
                "must_attenuate",
                "full scope",
                "full scope",
                message=(
                    "The parent grant requires attenuation: a delegate must narrow at least one "
                    "of data classes, scope, limits, or expiry"
                ),
            )

    # -- Chains and limits ----------------------------------------------------------------

    def _chain(self, grant: Grant) -> tuple[list[Grant], _Failure | None]:
        """Walk ``grant`` up to its root. Returns the chain root first, and why it is broken."""
        chain, seen, current = [grant], {grant.grant_id}, grant
        while current.parent_grant_id is not None:
            parent = self._grants.get(current.parent_grant_id)
            if parent is None or parent.grant_id in seen or not self._live(parent):
                return chain, (
                    CHAIN_BROKEN,
                    f"Grant '{current.grant_id}' derives from '{current.parent_grant_id}', "
                    "which is missing, revoked, or expired",
                )
            chain.insert(0, parent)
            seen.add(parent.grant_id)
            current = parent
        return chain, None

    @staticmethod
    def _limits_along(chain: Sequence[Grant]) -> Limits:
        """Intersect limits along a chain: the minimum of each bounded dimension."""

        def tightest(values: list[Any]) -> Any:
            bounded = [v for v in values if v is not None]
            return min(bounded) if bounded else None

        return Limits(
            max_records_per_call=tightest([g.limits.max_records_per_call for g in chain]),
            max_calls_per_session=tightest([g.limits.max_calls_per_session for g in chain]),
            max_amount=tightest([g.limits.max_amount for g in chain]),
            currency=next((g.limits.currency for g in reversed(chain) if g.limits.currency), None),
        )

    def _select(
        self,
        principal_chain: Sequence[str],
        action: Action,
        capability: str,
        *,
        purpose: str | None,
        data_classes: tuple[str, ...],
        account_scope: str | None,
        name_scope: str | None,
    ) -> tuple[list[Grant] | None, _Failure | None]:
        """Pick the grant that authorizes a call, or say why none does.

        The one place grant selection happens, so ``authorize`` and ``effective_limit``
        cannot disagree about which grant, and therefore which limits, apply. The check order
        is: a grant exists, purpose, data coverage, expiry, then chain integrity. The first
        failing check is the one reported.
        """
        leaf = principal_chain[-1]
        candidates = [
            g
            for g in self._grants.values()
            if g.principal == leaf
            and g.action == action
            and g.capability == capability
            and g.grant_id not in self._revoked
        ]
        if not candidates:
            return None, (
                NO_GRANT,
                f"No covering grant for principal '{leaf}', action '{action}', capability '{capability}'",
            )

        if purpose is not None:
            matching = [g for g in candidates if g.purpose == purpose]
            if not matching:
                held = sorted({g.purpose for g in candidates})
                return None, (PURPOSE_MISMATCH, f"Call purpose is '{purpose}'; grants cover {held}")
            candidates = matching

        covering: list[Grant] = []
        gap = ""
        for grant in candidates:
            problem = self._coverage_gap(grant, data_classes, account_scope, name_scope)
            if problem is None:
                covering.append(grant)
            else:
                gap = gap or problem
        if not covering:
            return None, (DATA_CLASS_EXCEEDED, gap)

        now = self._now()
        live = [g for g in covering if not g.is_expired(now)]
        if not live:
            return None, (
                GRANT_EXPIRED,
                f"Grant '{covering[0].grant_id}' expired at {covering[0].expires}",
            )

        failure: _Failure | None = None
        for grant in live:
            chain, broken = self._chain(grant)
            if broken is None and len(principal_chain) > 1:
                actual = [g.principal for g in chain]
                if actual != list(principal_chain):
                    broken = (
                        CHAIN_BROKEN,
                        f"Principal chain {list(principal_chain)} does not match the grant's "
                        f"delegation chain {actual}",
                    )
            if broken is None:
                return chain, None
            failure = failure or broken
        return None, failure

    @staticmethod
    def _coverage_gap(
        grant: Grant,
        data_classes: tuple[str, ...],
        account_scope: str | None,
        name_scope: str | None,
    ) -> str | None:
        """Return why ``grant`` does not cover the request, or ``None`` if it does."""
        held = _rank(grant.resource.data_classes)
        if _rank(data_classes) > held:
            exceeded = next(d for d in data_classes if SENSITIVITY_ORDER[d] > held)
            return f"Requested data class '{exceeded}' exceeds what grant '{grant.grant_id}' covers"
        for label, wanted, offered in (
            ("account", grant.resource.account_scope, account_scope),
            ("name", grant.resource.name_scope, name_scope),
        ):
            if wanted is not None and wanted != offered:
                return f"Grant '{grant.grant_id}' is scoped to {label} '{wanted}', not '{offered}'"
        return None

    # -- Queries --------------------------------------------------------------------------

    def effective_limit(
        self,
        principal_chain: Sequence[str],
        action: Action,
        capability: str,
        resource: ResourceSelector,
        *,
        purpose: str | None = None,
    ) -> Limits | None:
        """Return the limits that would bind this call, or ``None`` if no grant authorizes it.

        Uses the same grant selection as :meth:`authorize`. Pass ``purpose`` when grants for
        the same capability differ by purpose, since their limits may differ.
        """
        if not principal_chain:
            return None
        chain, _ = self._select(
            principal_chain,
            action,
            capability,
            purpose=purpose,
            data_classes=resource.data_classes,
            account_scope=resource.account_scope,
            name_scope=resource.name_scope,
        )
        return None if chain is None else self._limits_along(chain)

    def reachable(self, principal: str, purpose: str | None = None) -> list[str]:
        """Return the sorted capabilities a principal can currently reach.

        A grant counts only if it is live and its whole delegation chain is intact.
        """
        return sorted(
            {
                g.capability
                for g in self.grants_for(principal)
                if (purpose is None or g.purpose == purpose) and self._chain(g)[1] is None
            }
        )

    def uncovered(self) -> list[str]:
        """Return the sorted names of usable records that no live grant covers.

        A grant covers a record when its capability is the record's name or one of the
        record's capabilities, and its name scope, if set, is that record's name.

        Raises:
            ValueError: If no registry is bound. Returning ``[]`` there would claim nothing
                is uncovered when nothing was checked.
        """
        if self._registry is None:
            raise ValueError("Cannot report uncovered records without a bound registry")
        grants = [g for g in self._grants.values() if self._live(g) and self._chain(g)[1] is None]
        return sorted(
            record.name
            for record in self._registry.discover(verified_only=False)
            if not any(
                g.capability in (record.name, *record.capabilities)
                and g.resource.name_scope in (None, record.name)
                for g in grants
            )
        )

    # -- Authorization --------------------------------------------------------------------

    def authorize(
        self,
        principal_chain: Sequence[str],
        action: Action,
        capability: str,
        resource: ResourceSelector,
        context: CallContext,
        resolution: Resolution | None = None,
    ) -> Decision:
        """Decide whether ``principal_chain`` may perform ``action`` on ``capability``.

        Checks run in a fixed order and the first failure is named in the decision's reason
        code: the resolved record (revoked, expired, signature, verification), then a covering
        grant (existence, purpose, data coverage, expiry, delegation chain), then limits, then
        the grant's effect. A discovered or verified record is never enough on its own.

        When a ``resolution`` is given, its record is authoritative about what is being
        touched. The record's data classes are a floor under whatever the caller declares, so
        a caller cannot understate sensitivity, and the record's name is the name scope.
        ``capability`` must be the record's name or one of its declared capabilities.

        Pure given the graph, the registry state, and the injected clock: no I/O.
        """
        if not principal_chain:
            return Decision(
                outcome=Outcome.DENY,
                reason_code=NO_GRANT,
                reason="Empty principal chain",
                principal="",
                action=action,
                capability=capability,
            )
        leaf = principal_chain[-1]
        record = resolution.record if resolution else None
        data_classes, name_scope, note = resource.data_classes, resource.name_scope, ""

        def decide(outcome: Outcome, code: str, reason: str, **extra: Any) -> Decision:
            return Decision(
                outcome=outcome,
                reason_code=code,
                reason=reason,
                principal=leaf,
                action=action,
                capability=capability,
                data_classes=data_classes,
                record_name=record.name if record else None,
                record_fingerprint=resolution.fingerprint if resolution else None,
                record_version=resolution.version if resolution else None,
                record_verification=resolution.verification if resolution else None,
                **extra,
            )

        def deny(code: str, reason: str, **extra: Any) -> Decision:
            return decide(Outcome.DENY, code, reason, **extra)

        # 1. The resolved record.
        if resolution is not None and record is not None:
            if capability != record.name and capability not in record.capabilities:
                return deny(NO_RECORD, f"Record '{record.name}' does not declare '{capability}'")
            if resolution.status == RecordStatus.REVOKED:
                return deny(RECORD_REVOKED, f"Record '{record.name}' has been revoked")
            if record.is_expired(self._now()):
                return deny(RECORD_EXPIRED, f"Record '{record.name}' expired at {record.expires}")
            if resolution.verification == VerificationStatus.FAILED:
                return deny(
                    RECORD_SIGNATURE_INVALID,
                    f"Signature verification failed for record '{record.name}'",
                )
            data_classes = tuple(dict.fromkeys((*resource.data_classes, *record.data_classes)))
            name_scope = record.name
            if resolution.verification == VerificationStatus.UNVERIFIED:
                public_read = (
                    action == Action.READ and bool(data_classes) and set(data_classes) == {"public"}
                )
                if not public_read:
                    return deny(
                        RECORD_UNVERIFIED,
                        f"Record '{record.name}' is unverified; only reads of public data are allowed",
                    )
            if resolution.status == RecordStatus.DEPRECATED:
                note = f" (record '{record.name}' is deprecated: {RECORD_DEPRECATED})"

        # 2-6. A covering grant, with an intact delegation chain.
        chain, failure = self._select(
            principal_chain,
            action,
            capability,
            purpose=context.purpose,
            data_classes=data_classes,
            account_scope=resource.account_scope,
            name_scope=name_scope,
        )
        if chain is None or failure is not None:
            code, reason = failure or (NO_GRANT, "No covering grant")
            return deny(code, reason)
        grant = chain[-1]
        path = tuple(g.grant_id for g in chain)
        versions = tuple(dict.fromkeys(g.policy_version for g in chain if g.policy_version))
        limits = self._limits_along(chain)
        evidence: dict[str, Any] = {
            "grant_path": path,
            "effective_limits": limits,
            "policy_versions": versions,
        }

        # 7. Limits.
        if (
            limits.max_records_per_call is not None
            and context.records_requested is not None
            and context.records_requested > limits.max_records_per_call
        ):
            return deny(
                LIMIT_EXCEEDED,
                f"records_requested ({context.records_requested}) exceeds limit "
                f"({limits.max_records_per_call})",
                **evidence,
            )
        if (
            limits.max_calls_per_session is not None
            and context.calls_in_session >= limits.max_calls_per_session
        ):
            return deny(
                SESSION_LIMIT_EXCEEDED,
                f"{context.calls_in_session} calls already made this session; "
                f"the limit is {limits.max_calls_per_session}",
                **evidence,
            )
        if limits.max_amount is not None:
            if context.amount is None and action == Action.SPEND:
                return deny(
                    AMOUNT_LIMIT_EXCEEDED,
                    "A spend under an amount limit must state its amount",
                    **evidence,
                )
            if context.amount is not None:
                if context.currency != limits.currency:
                    return deny(
                        AMOUNT_LIMIT_EXCEEDED,
                        f"Currency mismatch: limit is in '{limits.currency}', call is in '{context.currency}'",
                        **evidence,
                    )
                if context.amount > limits.max_amount:
                    return deny(
                        AMOUNT_LIMIT_EXCEEDED,
                        f"amount ({context.amount}) exceeds limit ({limits.max_amount})",
                        **evidence,
                    )

        # 8. The grant's effect.
        if grant.effect == GrantEffect.REQUIRE_APPROVAL:
            if context.request_payload is None:
                return deny(
                    APPROVAL_REQUIRED,
                    "An approval cannot be bound to an unhashed request: request_payload is missing",
                    **evidence,
                )
            digest = hashlib.sha256(context.request_payload).hexdigest()
            return decide(
                Outcome.REQUIRE_APPROVAL,
                GRANT_FOUND,
                f"Approval required for '{capability}' by role '{grant.approver_role}'{note}",
                obligations=(Obligation.REQUIRE_APPROVAL_BOUND_TO_HASH, Obligation.LOG_DECISION),
                approval_binding=f"sha256:{digest}",
                **evidence,
            )

        obligations: list[Obligation] = []
        # A tool call returning confidential data is a read, so CALL is treated like READ here.
        if _rank(data_classes) >= SENSITIVITY_ORDER["confidential"] and action in (
            Action.READ,
            Action.EXPORT,
            Action.CALL,
        ):
            obligations.append(Obligation.REDACT)
        if limits.max_calls_per_session is not None or limits.max_amount is not None:
            obligations.append(Obligation.COUNT_AGAINST_BUDGET)
        if obligations or action in HIGH_RISK_ACTIONS or len(chain) > 1:
            obligations.insert(0, Obligation.LOG_DECISION)

        return decide(
            Outcome.ALLOW_WITH_OBLIGATIONS if obligations else Outcome.ALLOW,
            GRANT_FOUND,
            f"Authorized under grant '{grant.grant_id}'{note}",
            obligations=tuple(obligations),
            **evidence,
        )

registry property

The bound registry, if any.

add_grant(grant)

Add a grant and return its id.

A grant that names a parent is checked against it: the parent must exist and allow delegation, and the grant must not exceed it on any dimension. The graph therefore holds no grant broader than its parent, however the grant was authored.

Raises:

Type Description
ValueError

If the id is already used, or the parent is missing.

AttenuationError

If the grant exceeds its parent.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def add_grant(self, grant: Grant) -> str:
    """Add a grant and return its id.

    A grant that names a parent is checked against it: the parent must exist and allow
    delegation, and the grant must not exceed it on any dimension. The graph therefore
    holds no grant broader than its parent, however the grant was authored.

    Raises:
        ValueError: If the id is already used, or the parent is missing.
        AttenuationError: If the grant exceeds its parent.
    """
    if grant.grant_id in self._grants:
        raise ValueError(f"Grant id '{grant.grant_id}' is already in the graph")
    if grant.parent_grant_id is not None:
        parent = self._grants.get(grant.parent_grant_id)
        if parent is None:
            raise ValueError(
                f"Grant '{grant.grant_id}' names parent '{grant.parent_grant_id}', which is not in the graph"
            )
        self._assert_attenuates(parent, grant)
    self._grants[grant.grant_id] = grant
    return grant.grant_id

add_grants(grants)

Add several grants, parents before children whatever their order in the input.

All or nothing: if any grant is rejected, none of them are added.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def add_grants(self, grants: Iterable[Grant]) -> None:
    """Add several grants, parents before children whatever their order in the input.

    All or nothing: if any grant is rejected, none of them are added.
    """
    pending = list(grants)
    added: list[str] = []
    try:
        while pending:
            ready = [
                g
                for g in pending
                if g.parent_grant_id is None or g.parent_grant_id in self._grants
            ]
            if not ready:
                missing = sorted({g.parent_grant_id or "" for g in pending})
                raise ValueError(
                    f"Grants name parent(s) not in the graph: {', '.join(missing)}"
                )
            for grant in ready:
                added.append(self.add_grant(grant))
                pending.remove(grant)
    except Exception:
        for grant_id in added:
            del self._grants[grant_id]
        raise

get_grant(grant_id)

Return a grant, or None if it is unknown or revoked.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def get_grant(self, grant_id: str) -> Grant | None:
    """Return a grant, or ``None`` if it is unknown or revoked."""
    return None if grant_id in self._revoked else self._grants.get(grant_id)

grants_for(principal, action=None)

Return a principal's unrevoked, unexpired grants. Ancestry is not checked.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def grants_for(self, principal: str, action: Action | None = None) -> list[Grant]:
    """Return a principal's unrevoked, unexpired grants. Ancestry is not checked."""
    return [
        g
        for g in self._grants.values()
        if g.principal == principal and (action is None or g.action == action) and self._live(g)
    ]

revoke(grant_id)

Revoke a grant. Returns True if it was present and not already revoked.

Grants delegated from it stop authorizing on the next check, because every check validates the whole chain.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def revoke(self, grant_id: str) -> bool:
    """Revoke a grant. Returns True if it was present and not already revoked.

    Grants delegated from it stop authorizing on the next check, because every check
    validates the whole chain.
    """
    if grant_id in self._grants and grant_id not in self._revoked:
        self._revoked.add(grant_id)
        return True
    return False

is_revoked(grant_id)

Return whether a grant has been revoked.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def is_revoked(self, grant_id: str) -> bool:
    """Return whether a grant has been revoked."""
    return grant_id in self._revoked

revoke_record(name, version=None)

Revoke a record in the bound registry, so both halves of an incident response can be done from one handle.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def revoke_record(self, name: str, version: str | None = None) -> bool:
    """Revoke a record in the bound registry, so both halves of an incident response
    can be done from one handle."""
    if self._registry is None:
        raise ValueError("No registry is bound to this AuthorityGraph")
    return self._registry.revoke(name, version)

delegate(parent_grant_id, *, delegate_principal, scope)

Issue a grant to delegate_principal that is no broader than its parent.

Fields left None in scope are inherited. Capability, action, and effect are always inherited: a delegate that needs a different capability needs its own grant from a policy owner, and delegation can never weaken an approval requirement.

Raises:

Type Description
ValueError

If the parent is unknown, revoked, or expired.

AttenuationError

If the parent does not allow delegation, the scope exceeds the parent on any dimension, or the parent requires attenuation and the scope narrows nothing. dimension names the offending field.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def delegate(
    self, parent_grant_id: str, *, delegate_principal: str, scope: GrantScope
) -> DelegationResult:
    """Issue a grant to ``delegate_principal`` that is no broader than its parent.

    Fields left ``None`` in ``scope`` are inherited. Capability, action, and effect are
    always inherited: a delegate that needs a different capability needs its own grant
    from a policy owner, and delegation can never weaken an approval requirement.

    Raises:
        ValueError: If the parent is unknown, revoked, or expired.
        AttenuationError: If the parent does not allow delegation, the scope exceeds
            the parent on any dimension, or the parent requires attenuation and the
            scope narrows nothing. ``dimension`` names the offending field.
    """
    parent = self._grants.get(parent_grant_id)
    if parent is None:
        raise ValueError(f"Parent grant '{parent_grant_id}' not found")
    if not self._live(parent):
        raise ValueError(f"Parent grant '{parent_grant_id}' is revoked or expired")

    resource, limits = scope.resource or ResourceSelector(), scope.limits or Limits()
    child = Grant(
        grant_id=uuid.uuid4().hex,
        principal=delegate_principal,
        action=parent.action,
        capability=parent.capability,
        resource=ResourceSelector(
            data_classes=resource.data_classes or parent.resource.data_classes,
            account_scope=_inherit(resource.account_scope, parent.resource.account_scope),
            name_scope=_inherit(resource.name_scope, parent.resource.name_scope),
        ),
        purpose=_inherit(scope.purpose, parent.purpose),
        limits=Limits(
            max_records_per_call=_inherit(
                limits.max_records_per_call, parent.limits.max_records_per_call
            ),
            max_calls_per_session=_inherit(
                limits.max_calls_per_session, parent.limits.max_calls_per_session
            ),
            max_amount=_inherit(limits.max_amount, parent.limits.max_amount),
            currency=limits.currency or parent.limits.currency,
        ),
        delegation=parent.delegation,
        effect=parent.effect,
        approver_role=parent.approver_role,
        granted_by=parent.granted_by,
        policy_version=parent.policy_version,
        expires=_inherit(scope.expires, parent.expires),
        parent_grant_id=parent.grant_id,
    )
    self.add_grant(child)

    chain, _ = self._chain(child)
    token_id = uuid.uuid4().hex
    effective = self._limits_along(chain)
    canonical = json.dumps(
        {
            "token_id": token_id,
            "grant_chain": [g.grant_id for g in chain],
            "principal_chain": [g.principal for g in chain],
            "effective_limits": effective.to_dict(),
            "expires": child.expires.isoformat() if child.expires else None,
        },
        sort_keys=True,
    ).encode()
    token = DelegationToken(
        token_id=token_id,
        grant_chain=tuple(g.grant_id for g in chain),
        principal_chain=tuple(g.principal for g in chain),
        effective_limits=effective,
        expires=child.expires,
        token_hash=f"sha256:{hashlib.sha256(canonical).hexdigest()}",
    )
    return DelegationResult(grant=child, token=token)

effective_limit(principal_chain, action, capability, resource, *, purpose=None)

Return the limits that would bind this call, or None if no grant authorizes it.

Uses the same grant selection as :meth:authorize. Pass purpose when grants for the same capability differ by purpose, since their limits may differ.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def effective_limit(
    self,
    principal_chain: Sequence[str],
    action: Action,
    capability: str,
    resource: ResourceSelector,
    *,
    purpose: str | None = None,
) -> Limits | None:
    """Return the limits that would bind this call, or ``None`` if no grant authorizes it.

    Uses the same grant selection as :meth:`authorize`. Pass ``purpose`` when grants for
    the same capability differ by purpose, since their limits may differ.
    """
    if not principal_chain:
        return None
    chain, _ = self._select(
        principal_chain,
        action,
        capability,
        purpose=purpose,
        data_classes=resource.data_classes,
        account_scope=resource.account_scope,
        name_scope=resource.name_scope,
    )
    return None if chain is None else self._limits_along(chain)

reachable(principal, purpose=None)

Return the sorted capabilities a principal can currently reach.

A grant counts only if it is live and its whole delegation chain is intact.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def reachable(self, principal: str, purpose: str | None = None) -> list[str]:
    """Return the sorted capabilities a principal can currently reach.

    A grant counts only if it is live and its whole delegation chain is intact.
    """
    return sorted(
        {
            g.capability
            for g in self.grants_for(principal)
            if (purpose is None or g.purpose == purpose) and self._chain(g)[1] is None
        }
    )

uncovered()

Return the sorted names of usable records that no live grant covers.

A grant covers a record when its capability is the record's name or one of the record's capabilities, and its name scope, if set, is that record's name.

Raises:

Type Description
ValueError

If no registry is bound. Returning [] there would claim nothing is uncovered when nothing was checked.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def uncovered(self) -> list[str]:
    """Return the sorted names of usable records that no live grant covers.

    A grant covers a record when its capability is the record's name or one of the
    record's capabilities, and its name scope, if set, is that record's name.

    Raises:
        ValueError: If no registry is bound. Returning ``[]`` there would claim nothing
            is uncovered when nothing was checked.
    """
    if self._registry is None:
        raise ValueError("Cannot report uncovered records without a bound registry")
    grants = [g for g in self._grants.values() if self._live(g) and self._chain(g)[1] is None]
    return sorted(
        record.name
        for record in self._registry.discover(verified_only=False)
        if not any(
            g.capability in (record.name, *record.capabilities)
            and g.resource.name_scope in (None, record.name)
            for g in grants
        )
    )

authorize(principal_chain, action, capability, resource, context, resolution=None)

Decide whether principal_chain may perform action on capability.

Checks run in a fixed order and the first failure is named in the decision's reason code: the resolved record (revoked, expired, signature, verification), then a covering grant (existence, purpose, data coverage, expiry, delegation chain), then limits, then the grant's effect. A discovered or verified record is never enough on its own.

When a resolution is given, its record is authoritative about what is being touched. The record's data classes are a floor under whatever the caller declares, so a caller cannot understate sensitivity, and the record's name is the name scope. capability must be the record's name or one of its declared capabilities.

Pure given the graph, the registry state, and the injected clock: no I/O.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def authorize(
    self,
    principal_chain: Sequence[str],
    action: Action,
    capability: str,
    resource: ResourceSelector,
    context: CallContext,
    resolution: Resolution | None = None,
) -> Decision:
    """Decide whether ``principal_chain`` may perform ``action`` on ``capability``.

    Checks run in a fixed order and the first failure is named in the decision's reason
    code: the resolved record (revoked, expired, signature, verification), then a covering
    grant (existence, purpose, data coverage, expiry, delegation chain), then limits, then
    the grant's effect. A discovered or verified record is never enough on its own.

    When a ``resolution`` is given, its record is authoritative about what is being
    touched. The record's data classes are a floor under whatever the caller declares, so
    a caller cannot understate sensitivity, and the record's name is the name scope.
    ``capability`` must be the record's name or one of its declared capabilities.

    Pure given the graph, the registry state, and the injected clock: no I/O.
    """
    if not principal_chain:
        return Decision(
            outcome=Outcome.DENY,
            reason_code=NO_GRANT,
            reason="Empty principal chain",
            principal="",
            action=action,
            capability=capability,
        )
    leaf = principal_chain[-1]
    record = resolution.record if resolution else None
    data_classes, name_scope, note = resource.data_classes, resource.name_scope, ""

    def decide(outcome: Outcome, code: str, reason: str, **extra: Any) -> Decision:
        return Decision(
            outcome=outcome,
            reason_code=code,
            reason=reason,
            principal=leaf,
            action=action,
            capability=capability,
            data_classes=data_classes,
            record_name=record.name if record else None,
            record_fingerprint=resolution.fingerprint if resolution else None,
            record_version=resolution.version if resolution else None,
            record_verification=resolution.verification if resolution else None,
            **extra,
        )

    def deny(code: str, reason: str, **extra: Any) -> Decision:
        return decide(Outcome.DENY, code, reason, **extra)

    # 1. The resolved record.
    if resolution is not None and record is not None:
        if capability != record.name and capability not in record.capabilities:
            return deny(NO_RECORD, f"Record '{record.name}' does not declare '{capability}'")
        if resolution.status == RecordStatus.REVOKED:
            return deny(RECORD_REVOKED, f"Record '{record.name}' has been revoked")
        if record.is_expired(self._now()):
            return deny(RECORD_EXPIRED, f"Record '{record.name}' expired at {record.expires}")
        if resolution.verification == VerificationStatus.FAILED:
            return deny(
                RECORD_SIGNATURE_INVALID,
                f"Signature verification failed for record '{record.name}'",
            )
        data_classes = tuple(dict.fromkeys((*resource.data_classes, *record.data_classes)))
        name_scope = record.name
        if resolution.verification == VerificationStatus.UNVERIFIED:
            public_read = (
                action == Action.READ and bool(data_classes) and set(data_classes) == {"public"}
            )
            if not public_read:
                return deny(
                    RECORD_UNVERIFIED,
                    f"Record '{record.name}' is unverified; only reads of public data are allowed",
                )
        if resolution.status == RecordStatus.DEPRECATED:
            note = f" (record '{record.name}' is deprecated: {RECORD_DEPRECATED})"

    # 2-6. A covering grant, with an intact delegation chain.
    chain, failure = self._select(
        principal_chain,
        action,
        capability,
        purpose=context.purpose,
        data_classes=data_classes,
        account_scope=resource.account_scope,
        name_scope=name_scope,
    )
    if chain is None or failure is not None:
        code, reason = failure or (NO_GRANT, "No covering grant")
        return deny(code, reason)
    grant = chain[-1]
    path = tuple(g.grant_id for g in chain)
    versions = tuple(dict.fromkeys(g.policy_version for g in chain if g.policy_version))
    limits = self._limits_along(chain)
    evidence: dict[str, Any] = {
        "grant_path": path,
        "effective_limits": limits,
        "policy_versions": versions,
    }

    # 7. Limits.
    if (
        limits.max_records_per_call is not None
        and context.records_requested is not None
        and context.records_requested > limits.max_records_per_call
    ):
        return deny(
            LIMIT_EXCEEDED,
            f"records_requested ({context.records_requested}) exceeds limit "
            f"({limits.max_records_per_call})",
            **evidence,
        )
    if (
        limits.max_calls_per_session is not None
        and context.calls_in_session >= limits.max_calls_per_session
    ):
        return deny(
            SESSION_LIMIT_EXCEEDED,
            f"{context.calls_in_session} calls already made this session; "
            f"the limit is {limits.max_calls_per_session}",
            **evidence,
        )
    if limits.max_amount is not None:
        if context.amount is None and action == Action.SPEND:
            return deny(
                AMOUNT_LIMIT_EXCEEDED,
                "A spend under an amount limit must state its amount",
                **evidence,
            )
        if context.amount is not None:
            if context.currency != limits.currency:
                return deny(
                    AMOUNT_LIMIT_EXCEEDED,
                    f"Currency mismatch: limit is in '{limits.currency}', call is in '{context.currency}'",
                    **evidence,
                )
            if context.amount > limits.max_amount:
                return deny(
                    AMOUNT_LIMIT_EXCEEDED,
                    f"amount ({context.amount}) exceeds limit ({limits.max_amount})",
                    **evidence,
                )

    # 8. The grant's effect.
    if grant.effect == GrantEffect.REQUIRE_APPROVAL:
        if context.request_payload is None:
            return deny(
                APPROVAL_REQUIRED,
                "An approval cannot be bound to an unhashed request: request_payload is missing",
                **evidence,
            )
        digest = hashlib.sha256(context.request_payload).hexdigest()
        return decide(
            Outcome.REQUIRE_APPROVAL,
            GRANT_FOUND,
            f"Approval required for '{capability}' by role '{grant.approver_role}'{note}",
            obligations=(Obligation.REQUIRE_APPROVAL_BOUND_TO_HASH, Obligation.LOG_DECISION),
            approval_binding=f"sha256:{digest}",
            **evidence,
        )

    obligations: list[Obligation] = []
    # A tool call returning confidential data is a read, so CALL is treated like READ here.
    if _rank(data_classes) >= SENSITIVITY_ORDER["confidential"] and action in (
        Action.READ,
        Action.EXPORT,
        Action.CALL,
    ):
        obligations.append(Obligation.REDACT)
    if limits.max_calls_per_session is not None or limits.max_amount is not None:
        obligations.append(Obligation.COUNT_AGAINST_BUDGET)
    if obligations or action in HIGH_RISK_ACTIONS or len(chain) > 1:
        obligations.insert(0, Obligation.LOG_DECISION)

    return decide(
        Outcome.ALLOW_WITH_OBLIGATIONS if obligations else Outcome.ALLOW,
        GRANT_FOUND,
        f"Authorized under grant '{grant.grant_id}'{note}",
        obligations=tuple(obligations),
        **evidence,
    )

CallContext dataclass

Facts about one call, supplied by the caller.

calls_in_session, records_requested, and amount are taken on trust: a caller that always passes zero has disabled that limit. DnsMiddleware keeps a real session counter; a direct caller of authorize must supply one.

Parameters:

Name Type Description Default
purpose str

Why this call is being made.

required
session_id str | None

Identifies the session, for logging.

None
calls_in_session int

Calls already made this session.

0
records_requested int | None

Records this call asks for, if known.

None
amount float | None

Amount this call would spend, if any.

None
currency str | None

Currency of amount.

None
request_payload bytes | None

Exact request bytes. An approval is bound to their SHA-256 and the bytes themselves are never stored.

None
Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
@dataclass(frozen=True)
class CallContext:
    """Facts about one call, supplied by the caller.

    ``calls_in_session``, ``records_requested``, and ``amount`` are taken on trust: a caller
    that always passes zero has disabled that limit. ``DnsMiddleware`` keeps a real session
    counter; a direct caller of ``authorize`` must supply one.

    Args:
        purpose: Why this call is being made.
        session_id: Identifies the session, for logging.
        calls_in_session: Calls already made this session.
        records_requested: Records this call asks for, if known.
        amount: Amount this call would spend, if any.
        currency: Currency of ``amount``.
        request_payload: Exact request bytes. An approval is bound to their SHA-256 and the
            bytes themselves are never stored.
    """

    purpose: str
    session_id: str | None = None
    calls_in_session: int = 0
    records_requested: int | None = None
    amount: float | None = None
    currency: str | None = None
    request_payload: bytes | None = None

Decision dataclass

The result of an authorization check, with the evidence needed to explain it later.

Parameters:

Name Type Description Default
outcome Outcome

ALLOW, ALLOW_WITH_OBLIGATIONS, REQUIRE_APPROVAL, or DENY.

required
reason_code str

Stable code naming the check that decided it.

required
reason str

Human-readable explanation.

required
principal str

The leaf principal the check was for.

required
action Action

Action requested.

required
capability str

Capability requested.

required
grant_path tuple[str, ...]

Grant ids root first, leaf last, that authorized the call.

()
effective_limits Limits | None

Limits intersected along that path.

None
obligations tuple[Obligation, ...]

What must be done for an allow to be honored.

()
approval_binding str | None

sha256: of the request an approval must be bound to.

None
data_classes tuple[str, ...]

Data classes the check evaluated: what the caller declared plus what the resolved record declares.

()
record_name str | None

Record the call resolved to.

None
record_fingerprint str | None

Digest of the exact record bytes resolved.

None
record_version str | None

Version resolved.

None
record_verification VerificationStatus | None

Signature verification outcome for that record.

None
policy_versions tuple[str, ...]

Versions of the policies that issued the grants on the path.

()
Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
@dataclass(frozen=True)
class Decision:
    """The result of an authorization check, with the evidence needed to explain it later.

    Args:
        outcome: ``ALLOW``, ``ALLOW_WITH_OBLIGATIONS``, ``REQUIRE_APPROVAL``, or ``DENY``.
        reason_code: Stable code naming the check that decided it.
        reason: Human-readable explanation.
        principal: The leaf principal the check was for.
        action: Action requested.
        capability: Capability requested.
        grant_path: Grant ids root first, leaf last, that authorized the call.
        effective_limits: Limits intersected along that path.
        obligations: What must be done for an allow to be honored.
        approval_binding: ``sha256:`` of the request an approval must be bound to.
        data_classes: Data classes the check evaluated: what the caller declared plus what
            the resolved record declares.
        record_name: Record the call resolved to.
        record_fingerprint: Digest of the exact record bytes resolved.
        record_version: Version resolved.
        record_verification: Signature verification outcome for that record.
        policy_versions: Versions of the policies that issued the grants on the path.
    """

    outcome: Outcome
    reason_code: str
    reason: str
    principal: str
    action: Action
    capability: str
    grant_path: tuple[str, ...] = ()
    effective_limits: Limits | None = None
    obligations: tuple[Obligation, ...] = ()
    approval_binding: str | None = None
    data_classes: tuple[str, ...] = ()
    record_name: str | None = None
    record_fingerprint: str | None = None
    record_version: str | None = None
    record_verification: VerificationStatus | None = None
    policy_versions: tuple[str, ...] = ()

    @property
    def allowed(self) -> bool:
        """True for ``ALLOW`` and ``ALLOW_WITH_OBLIGATIONS`` only."""
        return self.outcome in (Outcome.ALLOW, Outcome.ALLOW_WITH_OBLIGATIONS)

    def to_dict(self) -> dict[str, Any]:
        """Return the decision as a plain dictionary."""
        return {
            "outcome": str(self.outcome),
            "reason_code": self.reason_code,
            "reason": self.reason,
            "principal": self.principal,
            "action": str(self.action),
            "capability": self.capability,
            "grant_path": list(self.grant_path),
            "effective_limits": self.effective_limits.to_dict() if self.effective_limits else None,
            "obligations": [str(o) for o in self.obligations],
            "approval_binding": self.approval_binding,
            "data_classes": list(self.data_classes),
            "record_name": self.record_name,
            "record_fingerprint": self.record_fingerprint,
            "record_version": self.record_version,
            "record_verification": str(self.record_verification)
            if self.record_verification
            else None,
            "policy_versions": list(self.policy_versions),
        }

allowed property

True for ALLOW and ALLOW_WITH_OBLIGATIONS only.

to_dict()

Return the decision as a plain dictionary.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def to_dict(self) -> dict[str, Any]:
    """Return the decision as a plain dictionary."""
    return {
        "outcome": str(self.outcome),
        "reason_code": self.reason_code,
        "reason": self.reason,
        "principal": self.principal,
        "action": str(self.action),
        "capability": self.capability,
        "grant_path": list(self.grant_path),
        "effective_limits": self.effective_limits.to_dict() if self.effective_limits else None,
        "obligations": [str(o) for o in self.obligations],
        "approval_binding": self.approval_binding,
        "data_classes": list(self.data_classes),
        "record_name": self.record_name,
        "record_fingerprint": self.record_fingerprint,
        "record_version": self.record_version,
        "record_verification": str(self.record_verification)
        if self.record_verification
        else None,
        "policy_versions": list(self.policy_versions),
    }

DelegationResult dataclass

A delegated grant, and the token describing its chain.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
@dataclass(frozen=True)
class DelegationResult:
    """A delegated grant, and the token describing its chain."""

    grant: Grant
    token: DelegationToken

DelegationTerms dataclass

Whether a grant may be delegated.

must_attenuate means a delegate must hold strictly less authority than the grant on at least one dimension. When False, a delegate may hold an equal grant. In neither case may a delegate hold more: attenuation is a ceiling.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
@dataclass(frozen=True)
class DelegationTerms:
    """Whether a grant may be delegated.

    ``must_attenuate`` means a delegate must hold strictly less authority than the grant
    on at least one dimension. When False, a delegate may hold an equal grant. In neither
    case may a delegate hold more: attenuation is a ceiling.
    """

    allowed: bool = False
    must_attenuate: bool = True

    def to_dict(self) -> dict[str, Any]:
        """Return the terms as a plain dictionary."""
        return {"allowed": self.allowed, "must_attenuate": self.must_attenuate}

    @classmethod
    def from_dict(cls, data: Mapping[str, Any], *, where: str = "delegation") -> DelegationTerms:
        """Build from a mapping. Values must be real booleans.

        ``bool("false")`` is True, so a quoted YAML value is rejected rather than coerced.
        """
        check_keys(
            data,
            required=[],
            optional=["allowed", "must_attenuate"],
            where=where,
            error=GrantLoadError,
        )
        for key, value in data.items():
            if not isinstance(value, bool):
                raise GrantLoadError(f"{where}: '{key}' must be true or false, got {value!r}")
        return cls(**dict(data))

to_dict()

Return the terms as a plain dictionary.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def to_dict(self) -> dict[str, Any]:
    """Return the terms as a plain dictionary."""
    return {"allowed": self.allowed, "must_attenuate": self.must_attenuate}

from_dict(data, *, where='delegation') classmethod

Build from a mapping. Values must be real booleans.

bool("false") is True, so a quoted YAML value is rejected rather than coerced.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
@classmethod
def from_dict(cls, data: Mapping[str, Any], *, where: str = "delegation") -> DelegationTerms:
    """Build from a mapping. Values must be real booleans.

    ``bool("false")`` is True, so a quoted YAML value is rejected rather than coerced.
    """
    check_keys(
        data,
        required=[],
        optional=["allowed", "must_attenuate"],
        where=where,
        error=GrantLoadError,
    )
    for key, value in data.items():
        if not isinstance(value, bool):
            raise GrantLoadError(f"{where}: '{key}' must be true or false, got {value!r}")
    return cls(**dict(data))

DelegationToken dataclass

A structured record of a delegation chain.

It is data, not a signed credential: the issuer and the checker are the same process in 0.1, so the graph can re-derive and re-check the chain. A portable signed format is a later decision.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
@dataclass(frozen=True)
class DelegationToken:
    """A structured record of a delegation chain.

    It is data, not a signed credential: the issuer and the checker are the same process in
    0.1, so the graph can re-derive and re-check the chain. A portable signed format is a
    later decision.
    """

    token_id: str
    grant_chain: tuple[str, ...]
    principal_chain: tuple[str, ...]
    effective_limits: Limits
    expires: datetime | None
    token_hash: str

Grant dataclass

Permission for one principal to perform one action on one capability.

Parameters:

Name Type Description Default
grant_id str

Stable identifier. Decision logs and delegation chains refer to it.

required
principal str

Who holds the grant.

required
action Action

What it permits.

required
capability str

What it applies to: a record name, or one of a record's capabilities.

required
resource ResourceSelector

Data the grant covers.

ResourceSelector()
purpose str

Why the grant exists. A call for a different purpose is not covered.

''
limits Limits

Numeric ceilings.

Limits()
delegation DelegationTerms

Whether and how the grant may be delegated.

DelegationTerms()
effect GrantEffect

ALLOW, or REQUIRE_APPROVAL to hold each call for a human.

ALLOW
approver_role str | None

Who should approve, for REQUIRE_APPROVAL. Informational.

None
granted_by str

Policy that issued it.

''
policy_version str

Version of that policy, so a log can name the deciding policy.

''
expires datetime | None

Timezone-aware expiry, or None.

None
parent_grant_id str | None

The grant this was delegated from, if any.

None
Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
@dataclass(frozen=True)
class Grant:
    """Permission for one principal to perform one action on one capability.

    Args:
        grant_id: Stable identifier. Decision logs and delegation chains refer to it.
        principal: Who holds the grant.
        action: What it permits.
        capability: What it applies to: a record name, or one of a record's capabilities.
        resource: Data the grant covers.
        purpose: Why the grant exists. A call for a different purpose is not covered.
        limits: Numeric ceilings.
        delegation: Whether and how the grant may be delegated.
        effect: ``ALLOW``, or ``REQUIRE_APPROVAL`` to hold each call for a human.
        approver_role: Who should approve, for ``REQUIRE_APPROVAL``. Informational.
        granted_by: Policy that issued it.
        policy_version: Version of that policy, so a log can name the deciding policy.
        expires: Timezone-aware expiry, or ``None``.
        parent_grant_id: The grant this was delegated from, if any.
    """

    grant_id: str
    principal: str
    action: Action
    capability: str
    resource: ResourceSelector = ResourceSelector()
    purpose: str = ""
    limits: Limits = Limits()
    delegation: DelegationTerms = DelegationTerms()
    effect: GrantEffect = GrantEffect.ALLOW
    approver_role: str | None = None
    granted_by: str = ""
    policy_version: str = ""
    expires: datetime | None = None
    parent_grant_id: str | None = None

    def __post_init__(self) -> None:
        for name in ("grant_id", "principal", "capability"):
            if not getattr(self, name):
                raise GrantLoadError(f"grant {name} must not be empty")
        if self.expires is not None:
            ensure_aware(self.expires, f"grant '{self.grant_id}' expires")
        if self.limits.max_amount is not None and not self.limits.currency:
            raise GrantLoadError(f"grant '{self.grant_id}': max_amount requires a currency")

    def is_expired(self, now: datetime | None = None) -> bool:
        """Return whether the grant's expiry has passed at ``now`` (default: current UTC time)."""
        if self.expires is None:
            return False
        current = datetime.now(UTC) if now is None else ensure_aware(now, "now")
        return current > self.expires

    def to_dict(self) -> dict[str, Any]:
        """Return the grant as a plain dictionary that :meth:`from_dict` accepts."""
        return {
            "grant_id": self.grant_id,
            "principal": self.principal,
            "action": str(self.action),
            "capability": self.capability,
            "resource": self.resource.to_dict(),
            "purpose": self.purpose,
            "limits": self.limits.to_dict(),
            "delegation": self.delegation.to_dict(),
            "effect": str(self.effect),
            "approver_role": self.approver_role,
            "granted_by": self.granted_by,
            "policy_version": self.policy_version,
            "expires": self.expires.astimezone(UTC).isoformat() if self.expires else None,
            "parent_grant_id": self.parent_grant_id,
        }

    @classmethod
    def from_dict(cls, data: Mapping[str, Any], *, where: str = "grant") -> Grant:
        """Build a grant from a mapping.

        ``grant_id``, ``principal``, ``action``, ``capability``, and ``purpose`` are required,
        and unknown keys are rejected. A misspelled ``effect`` must not fall back to
        ``allow``, and an id generated at load time would differ on every run and could not
        be referenced by a delegation or a decision log.

        A single ``granted_by: policy_v14`` is accepted and split into ``granted_by`` and
        ``policy_version`` when ``policy_version`` is absent.

        Raises:
            GrantLoadError: On a missing, unknown, or malformed field.
        """
        required = ["grant_id", "principal", "action", "capability", "purpose"]
        optional = ["resource", "limits", "delegation", "effect", "approver_role", "granted_by"]
        optional += ["policy_version", "expires", "parent_grant_id"]
        check_keys(data, required=required, optional=optional, where=where, error=GrantLoadError)
        for key in ("grant_id", "principal", "capability", "purpose"):
            if not isinstance(data[key], str):
                raise GrantLoadError(f"{where}: '{key}' must be a string, got {data[key]!r}")
        for key in ("resource", "limits", "delegation"):
            if key in data and not isinstance(data[key], dict):
                raise GrantLoadError(f"{where}: '{key}' must be a mapping")
        try:
            action = Action(data["action"])
            effect = GrantEffect(data.get("effect", "allow"))
        except ValueError as exc:
            raise GrantLoadError(f"{where}: {exc}") from None

        granted_by = _optional_str(data, "granted_by", where) or ""
        policy_version = _optional_str(data, "policy_version", where) or ""
        if granted_by and not policy_version and "_v" in granted_by:
            granted_by, version = granted_by.rsplit("_v", 1)
            policy_version = f"v{version}"

        try:
            return cls(
                grant_id=data["grant_id"],
                principal=data["principal"],
                action=action,
                capability=data["capability"],
                resource=ResourceSelector.from_dict(
                    data.get("resource", {}), where=f"{where}.resource"
                ),
                purpose=data["purpose"],
                limits=Limits.from_dict(data.get("limits", {}), where=f"{where}.limits"),
                delegation=DelegationTerms.from_dict(
                    data.get("delegation", {}), where=f"{where}.delegation"
                ),
                effect=effect,
                approver_role=_optional_str(data, "approver_role", where),
                granted_by=granted_by,
                policy_version=policy_version,
                expires=parse_expiry(
                    data.get("expires"), where=f"{where}.expires", error=GrantLoadError
                ),
                parent_grant_id=_optional_str(data, "parent_grant_id", where),
            )
        except GrantLoadError as exc:
            raise GrantLoadError(f"{where}: {exc}") from None

is_expired(now=None)

Return whether the grant's expiry has passed at now (default: current UTC time).

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def is_expired(self, now: datetime | None = None) -> bool:
    """Return whether the grant's expiry has passed at ``now`` (default: current UTC time)."""
    if self.expires is None:
        return False
    current = datetime.now(UTC) if now is None else ensure_aware(now, "now")
    return current > self.expires

to_dict()

Return the grant as a plain dictionary that :meth:from_dict accepts.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def to_dict(self) -> dict[str, Any]:
    """Return the grant as a plain dictionary that :meth:`from_dict` accepts."""
    return {
        "grant_id": self.grant_id,
        "principal": self.principal,
        "action": str(self.action),
        "capability": self.capability,
        "resource": self.resource.to_dict(),
        "purpose": self.purpose,
        "limits": self.limits.to_dict(),
        "delegation": self.delegation.to_dict(),
        "effect": str(self.effect),
        "approver_role": self.approver_role,
        "granted_by": self.granted_by,
        "policy_version": self.policy_version,
        "expires": self.expires.astimezone(UTC).isoformat() if self.expires else None,
        "parent_grant_id": self.parent_grant_id,
    }

from_dict(data, *, where='grant') classmethod

Build a grant from a mapping.

grant_id, principal, action, capability, and purpose are required, and unknown keys are rejected. A misspelled effect must not fall back to allow, and an id generated at load time would differ on every run and could not be referenced by a delegation or a decision log.

A single granted_by: policy_v14 is accepted and split into granted_by and policy_version when policy_version is absent.

Raises:

Type Description
GrantLoadError

On a missing, unknown, or malformed field.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
@classmethod
def from_dict(cls, data: Mapping[str, Any], *, where: str = "grant") -> Grant:
    """Build a grant from a mapping.

    ``grant_id``, ``principal``, ``action``, ``capability``, and ``purpose`` are required,
    and unknown keys are rejected. A misspelled ``effect`` must not fall back to
    ``allow``, and an id generated at load time would differ on every run and could not
    be referenced by a delegation or a decision log.

    A single ``granted_by: policy_v14`` is accepted and split into ``granted_by`` and
    ``policy_version`` when ``policy_version`` is absent.

    Raises:
        GrantLoadError: On a missing, unknown, or malformed field.
    """
    required = ["grant_id", "principal", "action", "capability", "purpose"]
    optional = ["resource", "limits", "delegation", "effect", "approver_role", "granted_by"]
    optional += ["policy_version", "expires", "parent_grant_id"]
    check_keys(data, required=required, optional=optional, where=where, error=GrantLoadError)
    for key in ("grant_id", "principal", "capability", "purpose"):
        if not isinstance(data[key], str):
            raise GrantLoadError(f"{where}: '{key}' must be a string, got {data[key]!r}")
    for key in ("resource", "limits", "delegation"):
        if key in data and not isinstance(data[key], dict):
            raise GrantLoadError(f"{where}: '{key}' must be a mapping")
    try:
        action = Action(data["action"])
        effect = GrantEffect(data.get("effect", "allow"))
    except ValueError as exc:
        raise GrantLoadError(f"{where}: {exc}") from None

    granted_by = _optional_str(data, "granted_by", where) or ""
    policy_version = _optional_str(data, "policy_version", where) or ""
    if granted_by and not policy_version and "_v" in granted_by:
        granted_by, version = granted_by.rsplit("_v", 1)
        policy_version = f"v{version}"

    try:
        return cls(
            grant_id=data["grant_id"],
            principal=data["principal"],
            action=action,
            capability=data["capability"],
            resource=ResourceSelector.from_dict(
                data.get("resource", {}), where=f"{where}.resource"
            ),
            purpose=data["purpose"],
            limits=Limits.from_dict(data.get("limits", {}), where=f"{where}.limits"),
            delegation=DelegationTerms.from_dict(
                data.get("delegation", {}), where=f"{where}.delegation"
            ),
            effect=effect,
            approver_role=_optional_str(data, "approver_role", where),
            granted_by=granted_by,
            policy_version=policy_version,
            expires=parse_expiry(
                data.get("expires"), where=f"{where}.expires", error=GrantLoadError
            ),
            parent_grant_id=_optional_str(data, "parent_grant_id", where),
        )
    except GrantLoadError as exc:
        raise GrantLoadError(f"{where}: {exc}") from None

GrantEffect

Bases: StrEnum

What a matching grant does: allow outright, or hold the call for approval.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
class GrantEffect(StrEnum):
    """What a matching grant does: allow outright, or hold the call for approval."""

    ALLOW = "allow"
    REQUIRE_APPROVAL = "require_approval"

GrantScope dataclass

The scope requested for a delegate. None means inherit the parent's value.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
@dataclass(frozen=True)
class GrantScope:
    """The scope requested for a delegate. ``None`` means inherit the parent's value."""

    resource: ResourceSelector | None = None
    purpose: str | None = None
    limits: Limits | None = None
    expires: datetime | None = None

Limits dataclass

Numeric ceilings. None means this link does not bound that dimension.

Parameters:

Name Type Description Default
max_records_per_call int | None

Most records one call may request.

None
max_calls_per_session int | None

Most calls allowed within one session.

None
max_amount float | None

Largest amount one call may spend. A grant that sets this must set currency, since an amount with no currency cannot be compared.

None
currency str | None

Currency max_amount is in.

None
Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
@dataclass(frozen=True)
class Limits:
    """Numeric ceilings. ``None`` means this link does not bound that dimension.

    Args:
        max_records_per_call: Most records one call may request.
        max_calls_per_session: Most calls allowed within one session.
        max_amount: Largest amount one call may spend. A grant that sets this must set
            ``currency``, since an amount with no currency cannot be compared.
        currency: Currency ``max_amount`` is in.
    """

    max_records_per_call: int | None = None
    max_calls_per_session: int | None = None
    max_amount: float | None = None
    currency: str | None = None

    def __post_init__(self) -> None:
        for name in ("max_records_per_call", "max_calls_per_session"):
            value = getattr(self, name)
            if value is not None and (
                isinstance(value, bool) or not isinstance(value, int) or value < 0
            ):
                raise GrantLoadError(f"{name} must be a non-negative integer, got {value!r}")
        amount = self.max_amount
        if amount is not None and (
            isinstance(amount, bool) or not isinstance(amount, (int, float)) or amount < 0
        ):
            raise GrantLoadError(f"max_amount must be a non-negative number, got {amount!r}")

    def to_dict(self) -> dict[str, Any]:
        """Return the limits as a plain dictionary."""
        return {
            "max_records_per_call": self.max_records_per_call,
            "max_calls_per_session": self.max_calls_per_session,
            "max_amount": self.max_amount,
            "currency": self.currency,
        }

    @classmethod
    def from_dict(cls, data: Mapping[str, Any], *, where: str = "limits") -> Limits:
        """Build from a mapping, rejecting unknown keys."""
        check_keys(
            data,
            required=[],
            optional=["max_records_per_call", "max_calls_per_session", "max_amount", "currency"],
            where=where,
            error=GrantLoadError,
        )
        try:
            return cls(**dict(data))
        except GrantLoadError as exc:
            raise GrantLoadError(f"{where}: {exc}") from None

to_dict()

Return the limits as a plain dictionary.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def to_dict(self) -> dict[str, Any]:
    """Return the limits as a plain dictionary."""
    return {
        "max_records_per_call": self.max_records_per_call,
        "max_calls_per_session": self.max_calls_per_session,
        "max_amount": self.max_amount,
        "currency": self.currency,
    }

from_dict(data, *, where='limits') classmethod

Build from a mapping, rejecting unknown keys.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
@classmethod
def from_dict(cls, data: Mapping[str, Any], *, where: str = "limits") -> Limits:
    """Build from a mapping, rejecting unknown keys."""
    check_keys(
        data,
        required=[],
        optional=["max_records_per_call", "max_calls_per_session", "max_amount", "currency"],
        where=where,
        error=GrantLoadError,
    )
    try:
        return cls(**dict(data))
    except GrantLoadError as exc:
        raise GrantLoadError(f"{where}: {exc}") from None

Obligation

Bases: StrEnum

Something the caller must do for an allow to be honored. One that cannot be done is a deny.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
class Obligation(StrEnum):
    """Something the caller must do for an allow to be honored. One that cannot be done is a deny."""

    LOG_DECISION = "log_decision"
    REDACT = "redact"
    REQUIRE_APPROVAL_BOUND_TO_HASH = "require_approval_bound_to_hash"
    COUNT_AGAINST_BUDGET = "count_against_budget"

Outcome

Bases: StrEnum

The four structured results of an authorization check.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
class Outcome(StrEnum):
    """The four structured results of an authorization check."""

    ALLOW = "allow"
    ALLOW_WITH_OBLIGATIONS = "allow_with_obligations"
    REQUIRE_APPROVAL = "require_approval"
    DENY = "deny"

ResourceSelector dataclass

The data a call touches, or the data a grant covers.

Parameters:

Name Type Description Default
data_classes tuple[str, ...]

Sensitivity classes. A grant covers a request when its highest class is at least the request's highest class, so a grant for internal covers public and internal but not confidential. A grant naming none covers only public data.

()
account_scope str | None

Account the call is for. A grant that sets it requires an exact match.

None
name_scope str | None

Exact record name; there are no glob patterns in 0.1.

None
Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
@dataclass(frozen=True)
class ResourceSelector:
    """The data a call touches, or the data a grant covers.

    Args:
        data_classes: Sensitivity classes. A grant covers a request when its highest class
            is at least the request's highest class, so a grant for ``internal`` covers
            ``public`` and ``internal`` but not ``confidential``. A grant naming none covers
            only public data.
        account_scope: Account the call is for. A grant that sets it requires an exact match.
        name_scope: Exact record name; there are no glob patterns in 0.1.
    """

    data_classes: tuple[str, ...] = ()
    account_scope: str | None = None
    name_scope: str | None = None

    def __post_init__(self) -> None:
        if isinstance(self.data_classes, str):
            raise GrantLoadError(
                f"data_classes must be a sequence of strings, got {self.data_classes!r}"
            )
        object.__setattr__(self, "data_classes", tuple(self.data_classes))
        for data_class in self.data_classes:
            if data_class not in VALID_DATA_CLASSES:
                raise GrantLoadError(
                    f"Unknown data class '{data_class}'. Expected one of: {sorted(VALID_DATA_CLASSES)}"
                )

    def to_dict(self) -> dict[str, Any]:
        """Return the selector as a plain dictionary."""
        return {
            "data_classes": list(self.data_classes),
            "account_scope": self.account_scope,
            "name_scope": self.name_scope,
        }

    @classmethod
    def from_dict(cls, data: Mapping[str, Any], *, where: str = "resource") -> ResourceSelector:
        """Build from a mapping, rejecting unknown keys."""
        check_keys(
            data,
            required=[],
            optional=["data_classes", "account_scope", "name_scope"],
            where=where,
            error=GrantLoadError,
        )
        data_classes = data.get("data_classes", [])
        if not isinstance(data_classes, list):
            raise GrantLoadError(f"{where}: 'data_classes' must be a list, got {data_classes!r}")
        try:
            return cls(
                data_classes=tuple(data_classes),
                account_scope=_optional_str(data, "account_scope", where),
                name_scope=_optional_str(data, "name_scope", where),
            )
        except GrantLoadError as exc:
            raise GrantLoadError(f"{where}: {exc}") from None

to_dict()

Return the selector as a plain dictionary.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
def to_dict(self) -> dict[str, Any]:
    """Return the selector as a plain dictionary."""
    return {
        "data_classes": list(self.data_classes),
        "account_scope": self.account_scope,
        "name_scope": self.name_scope,
    }

from_dict(data, *, where='resource') classmethod

Build from a mapping, rejecting unknown keys.

Source code in packages/pyagent-dns/src/pyagent_dns/authority.py
@classmethod
def from_dict(cls, data: Mapping[str, Any], *, where: str = "resource") -> ResourceSelector:
    """Build from a mapping, rejecting unknown keys."""
    check_keys(
        data,
        required=[],
        optional=["data_classes", "account_scope", "name_scope"],
        where=where,
        error=GrantLoadError,
    )
    data_classes = data.get("data_classes", [])
    if not isinstance(data_classes, list):
        raise GrantLoadError(f"{where}: 'data_classes' must be a list, got {data_classes!r}")
    try:
        return cls(
            data_classes=tuple(data_classes),
            account_scope=_optional_str(data, "account_scope", where),
            name_scope=_optional_str(data, "name_scope", where),
        )
    except GrantLoadError as exc:
        raise GrantLoadError(f"{where}: {exc}") from None

DnsBundle dataclass

A blueprint's dns configuration, loaded and wired together.

Source code in packages/pyagent-dns/src/pyagent_dns/blueprint.py
@dataclass
class DnsBundle:
    """A blueprint's dns configuration, loaded and wired together."""

    spec: DnsExtensionSpec
    registry: NameRegistry
    resolver: Resolver
    graph: AuthorityGraph
    source_path: Path | None = None

DnsExtensionSpec

Bases: BaseModel

The shape of the x-pyagent:dns block. Unknown keys are rejected.

Source code in packages/pyagent-dns/src/pyagent_dns/blueprint.py
class DnsExtensionSpec(BaseModel):
    """The shape of the ``x-pyagent:dns`` block. Unknown keys are rejected."""

    model_config = ConfigDict(extra="forbid")

    records_files: list[str] = Field(default_factory=list)
    grants_files: list[str] = Field(default_factory=list)
    trusted_keys_file: str | None = None
    enforcement: DnsEnforcement = DnsEnforcement.REQUIRED

AuthorizationDeniedError

Bases: Exception

Raised when an agent handoff is denied. decision carries the structured reason.

Source code in packages/pyagent-dns/src/pyagent_dns/middleware.py
class AuthorizationDeniedError(Exception):
    """Raised when an agent handoff is denied. ``decision`` carries the structured reason."""

    def __init__(self, decision: Decision) -> None:
        super().__init__(f"Authorization denied [{decision.reason_code}]: {decision.reason}")
        self.decision = decision

AuthorizedAgent

Bases: Agent

An agent whose run first checks authorization. Build with wrap_agent.

Source code in packages/pyagent-dns/src/pyagent_dns/middleware.py
class AuthorizedAgent(Agent):
    """An agent whose ``run`` first checks authorization. Build with ``wrap_agent``."""

    def __init__(
        self,
        agent: Agent,
        middleware: DnsMiddleware,
        principal: str,
        purpose: str,
        session_id: str | None = None,
    ) -> None:
        super().__init__(
            name=agent.name,
            llm=agent.llm,
            system_prompt=agent.system_prompt,
            description=agent.description,
        )
        self._wrapped_agent = agent
        self._middleware = middleware
        self._principal = principal
        self._purpose = purpose
        self._session_id = session_id

    async def run(self, messages: list[Message]) -> Message:
        """Authorize, run the wrapped agent, and apply any obligation to its reply.

        Raises:
            AuthorizationDeniedError: If the call is denied, requires approval (an agent
                handoff has no request payload to bind an approval to), or an obligation
                cannot be honored.
        """
        mw = self._middleware
        decision = mw.authorize_call(
            principal_chain=[self._principal],
            action=Action.CALL,
            capability=self.name,
            resource=ResourceSelector(),
            context=CallContext(purpose=self._purpose, session_id=self._session_id),
        )
        if not decision.allowed:
            raise AuthorizationDeniedError(decision)
        mw._require_obligations_possible(decision)
        reply = await self._wrapped_agent.run(messages)
        if Obligation.REDACT in decision.obligations:
            reply = dataclasses.replace(
                reply, content=mw._redact(decision, self.name, reply.content)
            )
        return reply

run(messages) async

Authorize, run the wrapped agent, and apply any obligation to its reply.

Raises:

Type Description
AuthorizationDeniedError

If the call is denied, requires approval (an agent handoff has no request payload to bind an approval to), or an obligation cannot be honored.

Source code in packages/pyagent-dns/src/pyagent_dns/middleware.py
async def run(self, messages: list[Message]) -> Message:
    """Authorize, run the wrapped agent, and apply any obligation to its reply.

    Raises:
        AuthorizationDeniedError: If the call is denied, requires approval (an agent
            handoff has no request payload to bind an approval to), or an obligation
            cannot be honored.
    """
    mw = self._middleware
    decision = mw.authorize_call(
        principal_chain=[self._principal],
        action=Action.CALL,
        capability=self.name,
        resource=ResourceSelector(),
        context=CallContext(purpose=self._purpose, session_id=self._session_id),
    )
    if not decision.allowed:
        raise AuthorizationDeniedError(decision)
    mw._require_obligations_possible(decision)
    reply = await self._wrapped_agent.run(messages)
    if Obligation.REDACT in decision.obligations:
        reply = dataclasses.replace(
            reply, content=mw._redact(decision, self.name, reply.content)
        )
    return reply

DnsMiddleware

Resolve a name, check the grants, and enforce the answer at call time.

Every decision is appended to :attr:decisions and, if an event bus is wired, emitted as an authority_decision trace event. The decision list grows for the life of the middleware; clear it by discarding the middleware.

Parameters:

Name Type Description Default
resolver Resolver

Resolves capability names to verified records.

required
graph AuthorityGraph

Grants and delegation chains.

required
event_bus Any

Optional TraceEventBus. Emission failures never block a call.

None
approver ApproverFn | None

Called for REQUIRE_APPROVAL decisions. With none wired, such calls are denied; there is deliberately no approving default.

None
redactor Any

A ContextRedactor for the REDACT obligation. With none wired, a call that carries that obligation is denied rather than returned unredacted.

None
session_counter SessionCounter | None

Counter for session limits. A private one is created if omitted.

None
Source code in packages/pyagent-dns/src/pyagent_dns/middleware.py
class DnsMiddleware:
    """Resolve a name, check the grants, and enforce the answer at call time.

    Every decision is appended to :attr:`decisions` and, if an event bus is wired, emitted as
    an ``authority_decision`` trace event. The decision list grows for the life of the
    middleware; clear it by discarding the middleware.

    Args:
        resolver: Resolves capability names to verified records.
        graph: Grants and delegation chains.
        event_bus: Optional ``TraceEventBus``. Emission failures never block a call.
        approver: Called for ``REQUIRE_APPROVAL`` decisions. With none wired, such calls are
            denied; there is deliberately no approving default.
        redactor: A ``ContextRedactor`` for the ``REDACT`` obligation. With none wired, a call
            that carries that obligation is denied rather than returned unredacted.
        session_counter: Counter for session limits. A private one is created if omitted.
    """

    def __init__(
        self,
        resolver: Resolver,
        graph: AuthorityGraph,
        *,
        event_bus: Any = None,
        approver: ApproverFn | None = None,
        redactor: Any = None,
        session_counter: SessionCounter | None = None,
    ) -> None:
        self._resolver = resolver
        self._graph = graph
        self._event_bus = event_bus
        self._approver = approver
        self._redactor = redactor
        self._sessions = session_counter or SessionCounter()
        self._decisions: list[Decision] = []

    @property
    def decisions(self) -> list[Decision]:
        """A copy of every decision made, in order."""
        return list(self._decisions)

    def _record(self, decision: Decision) -> Decision:
        self._decisions.append(decision)
        if self._event_bus is not None:
            try:
                self._event_bus.emit(decision_event(decision, agent_name=decision.principal))
            except Exception:
                logger.debug("authority_decision event emission failed", exc_info=True)
        return decision

    def authorize_call(
        self,
        *,
        principal_chain: Sequence[str],
        action: Action,
        capability: str,
        resource: ResourceSelector,
        context: CallContext,
    ) -> Decision:
        """Resolve ``capability`` as a record name, check the grants, and record the decision.

        High-risk actions resolve fresh, bypassing the cache. Does not run approvals or
        obligations; a caller that integrates directly handles those itself.
        """
        if action in HIGH_RISK_ACTIONS:
            resolution = self._resolver.resolve_fresh(capability)
        else:
            resolution = self._resolver.resolve(capability)

        if resolution is None:
            decision = Decision(
                outcome=Outcome.DENY,
                reason_code=NO_RECORD,
                reason=f"No NameRecord found for '{capability}'",
                principal=principal_chain[-1] if principal_chain else "",
                action=action,
                capability=capability,
            )
        else:
            decision = self._graph.authorize(
                principal_chain, action, capability, resource, context, resolution
            )
        return self._record(decision)

    def _settle_approval(self, decision: Decision, context: CallContext) -> Decision:
        """Turn a ``REQUIRE_APPROVAL`` decision into a final allow or deny, and record it.

        Other outcomes pass through. The approval is bound to the request's hash, which is
        kept on the final decision.
        """
        if decision.outcome != Outcome.REQUIRE_APPROVAL:
            return decision
        if self._approver is None:
            changes: dict[str, Any] = {
                "outcome": Outcome.DENY,
                "reason_code": APPROVAL_REQUIRED,
                "reason": "The call requires approval and no approver is configured",
                "obligations": (),
            }
        elif self._approver(decision, context):
            changes = {
                "outcome": Outcome.ALLOW_WITH_OBLIGATIONS,
                "reason_code": GRANT_FOUND,
                "reason": f"Approved by approver; bound to {decision.approval_binding}",
                "obligations": (Obligation.LOG_DECISION,),
            }
        else:
            changes = {
                "outcome": Outcome.DENY,
                "reason_code": APPROVAL_DENIED,
                "reason": "The approver rejected the request",
                "obligations": (),
            }
        return self._record(dataclasses.replace(decision, **changes))

    def _unavailable(self, decision: Decision, why: str) -> AuthorizationDeniedError:
        """Record a deny for an obligation that cannot be performed, and return the error."""
        return AuthorizationDeniedError(
            self._record(
                dataclasses.replace(
                    decision,
                    outcome=Outcome.DENY,
                    reason_code=OBLIGATION_UNAVAILABLE,
                    reason=why,
                    obligations=(),
                )
            )
        )

    def _require_obligations_possible(self, decision: Decision) -> None:
        """Before running anything, deny if an obligation could not be honored afterwards."""
        if Obligation.REDACT in decision.obligations and self._redactor is None:
            raise self._unavailable(
                decision, "The call requires redaction but no redactor is configured"
            )

    def _redact(self, decision: Decision, capability: str, content: str) -> str:
        """Redact ``content`` at the highest sensitivity the decision evaluated.

        Raises:
            AuthorizationDeniedError: If redaction fails for any reason. The content is
                withheld; it is never returned unredacted.
        """
        try:
            from pyagent_context.item import ContextItem, Sensitivity

            top = max(decision.data_classes, key=SENSITIVITY_ORDER.__getitem__, default="public")
            item = ContextItem(content=content, source=capability, sensitivity=Sensitivity(top))
            redacted = self._redactor.redact_item(item)
        except Exception as exc:
            raise self._unavailable(
                decision, f"Redaction failed ({type(exc).__name__}); output withheld"
            ) from exc
        return "" if redacted is None else str(redacted.content)

    def guard_tools(
        self,
        tools: dict[str, Callable[[str], str]],
        *,
        principal_chain: Sequence[str],
        purpose: str,
        action: Action = Action.CALL,
        session_id: str | None = None,
    ) -> dict[str, Callable[[str], str]]:
        """Return ``tools`` with every function wrapped in an authorization check.

        Each dict key is resolved as a record name, so a tools dict whose keys are not
        record names is denied with ``NO_RECORD``. That is correct, and it is how drifted
        names get noticed. A denied call returns ``DENIED [REASON_CODE] reason`` instead of
        raising, because ReAct feeds the result back to the model as an observation and the
        model can replan. The denied function is never invoked.

        Limits that need request facts (``records_requested``, ``amount``) cannot be derived
        from a ReAct call's single input string, so they are enforced only through
        ``authorize_call``. Session limits are enforced here.

        Args:
            session_id: Scopes the call counter. Defaults to a fresh id per ``guard_tools``
                call, so unrelated guarded tool sets never share a count.
        """
        session = session_id or uuid.uuid4().hex
        return {
            name: self._guard(name, fn, tuple(principal_chain), purpose, action, session)
            for name, fn in tools.items()
        }

    def _guard(
        self,
        name: str,
        fn: Callable[[str], str],
        principal_chain: tuple[str, ...],
        purpose: str,
        action: Action,
        session_id: str,
    ) -> Callable[[str], str]:
        def guarded(action_input: str) -> str:
            context = CallContext(
                purpose=purpose,
                session_id=session_id,
                calls_in_session=self._sessions.count(session_id, name),
                request_payload=action_input.encode("utf-8"),
            )
            decision = self.authorize_call(
                principal_chain=principal_chain,
                action=action,
                capability=name,
                resource=ResourceSelector(),
                context=context,
            )
            try:
                decision = self._settle_approval(decision, context)
                if not decision.allowed:
                    return f"DENIED [{decision.reason_code}] {decision.reason}"
                self._require_obligations_possible(decision)
                self._sessions.increment(session_id, name)
                output = fn(action_input)
                if Obligation.REDACT in decision.obligations:
                    output = self._redact(decision, name, output)
                return output
            except AuthorizationDeniedError as denied:
                d = denied.decision
                return f"DENIED [{d.reason_code}] {d.reason}"

        return guarded

    def wrap_agent(
        self, agent: Agent, *, principal: str, purpose: str, session_id: str | None = None
    ) -> AuthorizedAgent:
        """Wrap an agent so that calling it is authorized first.

        Calling the agent counts as ``CALL`` on the capability named by ``agent.name``,
        performed by ``principal``. The check runs before the LLM call, so a denied handoff
        spends no model call. A denial raises :class:`AuthorizationDeniedError`, because a
        pattern awaiting ``agent.run`` has no channel for a deny string, and fabricating an
        assistant message would put words in the target agent's mouth.

        Only handoffs through the returned object are governed. ``Supervisor`` holds its
        routes directly, so wrapping a classifier does not govern the specialists it routes
        to: wrap the specialists.
        """
        return AuthorizedAgent(agent, self, principal, purpose, session_id)

    def wrap_all(
        self, agents: list[Agent], *, principal: str, purpose: str
    ) -> list[AuthorizedAgent]:
        """Wrap several agents with the same principal and purpose."""
        return [self.wrap_agent(a, principal=principal, purpose=purpose) for a in agents]

decisions property

A copy of every decision made, in order.

authorize_call(*, principal_chain, action, capability, resource, context)

Resolve capability as a record name, check the grants, and record the decision.

High-risk actions resolve fresh, bypassing the cache. Does not run approvals or obligations; a caller that integrates directly handles those itself.

Source code in packages/pyagent-dns/src/pyagent_dns/middleware.py
def authorize_call(
    self,
    *,
    principal_chain: Sequence[str],
    action: Action,
    capability: str,
    resource: ResourceSelector,
    context: CallContext,
) -> Decision:
    """Resolve ``capability`` as a record name, check the grants, and record the decision.

    High-risk actions resolve fresh, bypassing the cache. Does not run approvals or
    obligations; a caller that integrates directly handles those itself.
    """
    if action in HIGH_RISK_ACTIONS:
        resolution = self._resolver.resolve_fresh(capability)
    else:
        resolution = self._resolver.resolve(capability)

    if resolution is None:
        decision = Decision(
            outcome=Outcome.DENY,
            reason_code=NO_RECORD,
            reason=f"No NameRecord found for '{capability}'",
            principal=principal_chain[-1] if principal_chain else "",
            action=action,
            capability=capability,
        )
    else:
        decision = self._graph.authorize(
            principal_chain, action, capability, resource, context, resolution
        )
    return self._record(decision)

guard_tools(tools, *, principal_chain, purpose, action=Action.CALL, session_id=None)

Return tools with every function wrapped in an authorization check.

Each dict key is resolved as a record name, so a tools dict whose keys are not record names is denied with NO_RECORD. That is correct, and it is how drifted names get noticed. A denied call returns DENIED [REASON_CODE] reason instead of raising, because ReAct feeds the result back to the model as an observation and the model can replan. The denied function is never invoked.

Limits that need request facts (records_requested, amount) cannot be derived from a ReAct call's single input string, so they are enforced only through authorize_call. Session limits are enforced here.

Parameters:

Name Type Description Default
session_id str | None

Scopes the call counter. Defaults to a fresh id per guard_tools call, so unrelated guarded tool sets never share a count.

None
Source code in packages/pyagent-dns/src/pyagent_dns/middleware.py
def guard_tools(
    self,
    tools: dict[str, Callable[[str], str]],
    *,
    principal_chain: Sequence[str],
    purpose: str,
    action: Action = Action.CALL,
    session_id: str | None = None,
) -> dict[str, Callable[[str], str]]:
    """Return ``tools`` with every function wrapped in an authorization check.

    Each dict key is resolved as a record name, so a tools dict whose keys are not
    record names is denied with ``NO_RECORD``. That is correct, and it is how drifted
    names get noticed. A denied call returns ``DENIED [REASON_CODE] reason`` instead of
    raising, because ReAct feeds the result back to the model as an observation and the
    model can replan. The denied function is never invoked.

    Limits that need request facts (``records_requested``, ``amount``) cannot be derived
    from a ReAct call's single input string, so they are enforced only through
    ``authorize_call``. Session limits are enforced here.

    Args:
        session_id: Scopes the call counter. Defaults to a fresh id per ``guard_tools``
            call, so unrelated guarded tool sets never share a count.
    """
    session = session_id or uuid.uuid4().hex
    return {
        name: self._guard(name, fn, tuple(principal_chain), purpose, action, session)
        for name, fn in tools.items()
    }

wrap_agent(agent, *, principal, purpose, session_id=None)

Wrap an agent so that calling it is authorized first.

Calling the agent counts as CALL on the capability named by agent.name, performed by principal. The check runs before the LLM call, so a denied handoff spends no model call. A denial raises :class:AuthorizationDeniedError, because a pattern awaiting agent.run has no channel for a deny string, and fabricating an assistant message would put words in the target agent's mouth.

Only handoffs through the returned object are governed. Supervisor holds its routes directly, so wrapping a classifier does not govern the specialists it routes to: wrap the specialists.

Source code in packages/pyagent-dns/src/pyagent_dns/middleware.py
def wrap_agent(
    self, agent: Agent, *, principal: str, purpose: str, session_id: str | None = None
) -> AuthorizedAgent:
    """Wrap an agent so that calling it is authorized first.

    Calling the agent counts as ``CALL`` on the capability named by ``agent.name``,
    performed by ``principal``. The check runs before the LLM call, so a denied handoff
    spends no model call. A denial raises :class:`AuthorizationDeniedError`, because a
    pattern awaiting ``agent.run`` has no channel for a deny string, and fabricating an
    assistant message would put words in the target agent's mouth.

    Only handoffs through the returned object are governed. ``Supervisor`` holds its
    routes directly, so wrapping a classifier does not govern the specialists it routes
    to: wrap the specialists.
    """
    return AuthorizedAgent(agent, self, principal, purpose, session_id)

wrap_all(agents, *, principal, purpose)

Wrap several agents with the same principal and purpose.

Source code in packages/pyagent-dns/src/pyagent_dns/middleware.py
def wrap_all(
    self, agents: list[Agent], *, principal: str, purpose: str
) -> list[AuthorizedAgent]:
    """Wrap several agents with the same principal and purpose."""
    return [self.wrap_agent(a, principal=principal, purpose=purpose) for a in agents]

SessionCounter

Counts calls per session and capability, for max_calls_per_session.

Not thread-safe: it is a plain dict, like the registries. Sessions are only as real as the ids callers give them.

Source code in packages/pyagent-dns/src/pyagent_dns/middleware.py
class SessionCounter:
    """Counts calls per session and capability, for ``max_calls_per_session``.

    Not thread-safe: it is a plain dict, like the registries. Sessions are only as real as
    the ids callers give them.
    """

    def __init__(self) -> None:
        self._counts: dict[tuple[str, str], int] = {}

    def count(self, session_id: str, capability: str) -> int:
        """Return calls made so far in this session for this capability."""
        return self._counts.get((session_id, capability), 0)

    def increment(self, session_id: str, capability: str) -> int:
        """Record a call and return the new count."""
        key = (session_id, capability)
        self._counts[key] = self._counts.get(key, 0) + 1
        return self._counts[key]

    def reset(self, session_id: str | None = None) -> None:
        """Clear one session's counts, or every session's."""
        if session_id is None:
            self._counts.clear()
        else:
            for key in [k for k in self._counts if k[0] == session_id]:
                del self._counts[key]

count(session_id, capability)

Return calls made so far in this session for this capability.

Source code in packages/pyagent-dns/src/pyagent_dns/middleware.py
def count(self, session_id: str, capability: str) -> int:
    """Return calls made so far in this session for this capability."""
    return self._counts.get((session_id, capability), 0)

increment(session_id, capability)

Record a call and return the new count.

Source code in packages/pyagent-dns/src/pyagent_dns/middleware.py
def increment(self, session_id: str, capability: str) -> int:
    """Record a call and return the new count."""
    key = (session_id, capability)
    self._counts[key] = self._counts.get(key, 0) + 1
    return self._counts[key]

reset(session_id=None)

Clear one session's counts, or every session's.

Source code in packages/pyagent-dns/src/pyagent_dns/middleware.py
def reset(self, session_id: str | None = None) -> None:
    """Clear one session's counts, or every session's."""
    if session_id is None:
        self._counts.clear()
    else:
        for key in [k for k in self._counts if k[0] == session_id]:
            del self._counts[key]

Identity dataclass

Identity claims and key reference carried by a record.

Parameters:

Name Type Description Default
public_key_fingerprint str

sha256: followed by the hex digest of the signing key.

required
public_key str | None

Optional signing key, base64 raw Ed25519 or PEM. Informational only: verification never trusts a key supplied by the record itself.

None
workload_id str | None

Optional workload identifier, for example a SPIFFE ID.

None
signed_by str

Name of the signer, a key into the trusted keys file.

''
Source code in packages/pyagent-dns/src/pyagent_dns/records.py
@dataclass(frozen=True)
class Identity:
    """Identity claims and key reference carried by a record.

    Args:
        public_key_fingerprint: ``sha256:`` followed by the hex digest of the signing key.
        public_key: Optional signing key, base64 raw Ed25519 or PEM. Informational only:
            verification never trusts a key supplied by the record itself.
        workload_id: Optional workload identifier, for example a SPIFFE ID.
        signed_by: Name of the signer, a key into the trusted keys file.
    """

    public_key_fingerprint: str
    public_key: str | None = None
    workload_id: str | None = None
    signed_by: str = ""

    def to_dict(self) -> dict[str, Any]:
        """Return the identity as a plain dictionary."""
        return {
            "public_key_fingerprint": self.public_key_fingerprint,
            "public_key": self.public_key,
            "workload_id": self.workload_id,
            "signed_by": self.signed_by,
        }

    @classmethod
    def from_dict(cls, data: Mapping[str, Any], *, where: str = "identity") -> Identity:
        """Build an Identity from a mapping, rejecting unknown or missing keys."""
        check_keys(
            data,
            required=["public_key_fingerprint"],
            optional=["public_key", "workload_id", "signed_by"],
            where=where,
            error=RecordLoadError,
        )
        for key in ("public_key_fingerprint", "public_key", "workload_id", "signed_by"):
            value = data.get(key)
            if value is not None and not isinstance(value, str):
                raise RecordLoadError(f"{where}: '{key}' must be a string, got {value!r}")
        return cls(
            public_key_fingerprint=data["public_key_fingerprint"],
            public_key=data.get("public_key"),
            workload_id=data.get("workload_id"),
            signed_by=data.get("signed_by") or "",
        )

to_dict()

Return the identity as a plain dictionary.

Source code in packages/pyagent-dns/src/pyagent_dns/records.py
def to_dict(self) -> dict[str, Any]:
    """Return the identity as a plain dictionary."""
    return {
        "public_key_fingerprint": self.public_key_fingerprint,
        "public_key": self.public_key,
        "workload_id": self.workload_id,
        "signed_by": self.signed_by,
    }

from_dict(data, *, where='identity') classmethod

Build an Identity from a mapping, rejecting unknown or missing keys.

Source code in packages/pyagent-dns/src/pyagent_dns/records.py
@classmethod
def from_dict(cls, data: Mapping[str, Any], *, where: str = "identity") -> Identity:
    """Build an Identity from a mapping, rejecting unknown or missing keys."""
    check_keys(
        data,
        required=["public_key_fingerprint"],
        optional=["public_key", "workload_id", "signed_by"],
        where=where,
        error=RecordLoadError,
    )
    for key in ("public_key_fingerprint", "public_key", "workload_id", "signed_by"):
        value = data.get(key)
        if value is not None and not isinstance(value, str):
            raise RecordLoadError(f"{where}: '{key}' must be a string, got {value!r}")
    return cls(
        public_key_fingerprint=data["public_key_fingerprint"],
        public_key=data.get("public_key"),
        workload_id=data.get("workload_id"),
        signed_by=data.get("signed_by") or "",
    )

NameRecord dataclass

A versioned record naming an agent, tool, provider, data source, or approver.

The record is the naming plane: it says what something is and who vouches for it. It grants nothing. Permissions live in :class:pyagent_dns.authority.Grant.

capabilities and data_classes are tuples so that a signed record cannot be altered through a shared list. Lists passed to the constructor are converted.

Parameters:

Name Type Description Default
name str

Unique identifier, for example portfolio-data.reader.

required
kind RecordKind

Entity type.

required
version str

Semantic version string.

required
endpoint str

Invocation URI or reference. Resolution never connects to it.

required
identity Identity

Signer and key details.

required
schema_hash str

sha256: digest of the capability's schema.

required
capabilities tuple[str, ...]

Declared capability names, used for discovery.

required
data_classes tuple[str, ...]

Sensitivity classes this record touches; a floor that callers cannot understate when authorization is evaluated.

required
owner str

Responsible team.

required
status RecordStatus

Lifecycle status declared by the owner.

ACTIVE
expires datetime | None

Timezone-aware expiry, or None for no expiry.

None
ttl_seconds int

How long a resolution may be cached.

300
signature str | None

Base64 Ed25519 signature over :meth:canonical_bytes.

None
signature_algorithm str

Signature algorithm; only ed25519 is supported.

'ed25519'
Source code in packages/pyagent-dns/src/pyagent_dns/records.py
@dataclass(frozen=True)
class NameRecord:
    """A versioned record naming an agent, tool, provider, data source, or approver.

    The record is the *naming plane*: it says what something is and who vouches for it.
    It grants nothing. Permissions live in :class:`pyagent_dns.authority.Grant`.

    ``capabilities`` and ``data_classes`` are tuples so that a signed record cannot be
    altered through a shared list. Lists passed to the constructor are converted.

    Args:
        name: Unique identifier, for example ``portfolio-data.reader``.
        kind: Entity type.
        version: Semantic version string.
        endpoint: Invocation URI or reference. Resolution never connects to it.
        identity: Signer and key details.
        schema_hash: ``sha256:`` digest of the capability's schema.
        capabilities: Declared capability names, used for discovery.
        data_classes: Sensitivity classes this record touches; a floor that callers
            cannot understate when authorization is evaluated.
        owner: Responsible team.
        status: Lifecycle status declared by the owner.
        expires: Timezone-aware expiry, or ``None`` for no expiry.
        ttl_seconds: How long a resolution may be cached.
        signature: Base64 Ed25519 signature over :meth:`canonical_bytes`.
        signature_algorithm: Signature algorithm; only ``ed25519`` is supported.
    """

    name: str
    kind: RecordKind
    version: str
    endpoint: str
    identity: Identity
    schema_hash: str
    capabilities: tuple[str, ...]
    data_classes: tuple[str, ...]
    owner: str
    status: RecordStatus = RecordStatus.ACTIVE
    expires: datetime | None = None
    ttl_seconds: int = 300
    signature: str | None = None
    signature_algorithm: str = "ed25519"

    def __post_init__(self) -> None:
        if not self.name:
            raise RecordLoadError("record name must not be empty")
        version_key(self.version)
        for field_name in ("capabilities", "data_classes"):
            value = getattr(self, field_name)
            if isinstance(value, str) or not all(isinstance(item, str) for item in value):
                raise RecordLoadError(
                    f"record '{self.name}': {field_name} must be a sequence of strings, got {value!r}"
                )
            object.__setattr__(self, field_name, tuple(value))
        for data_class in self.data_classes:
            if data_class not in VALID_DATA_CLASSES:
                raise RecordLoadError(
                    f"record '{self.name}': unknown data class '{data_class}'. "
                    f"Expected one of: {sorted(VALID_DATA_CLASSES)}"
                )
        if self.expires is not None:
            ensure_aware(self.expires, f"record '{self.name}' expires")
        if isinstance(self.ttl_seconds, bool) or not isinstance(self.ttl_seconds, int):
            raise RecordLoadError(f"record '{self.name}': ttl_seconds must be an integer")
        if self.ttl_seconds < 0:
            raise RecordLoadError(f"record '{self.name}': ttl_seconds must not be negative")

    def canonical_bytes(self) -> bytes:
        """Return the exact bytes that are signed: sorted-key compact JSON, UTF-8.

        ``signature`` is excluded. The ``_pyagent_dns`` marker is a domain separator, so a
        signature over a record cannot be replayed as a signature in another protocol.
        """
        expires: str | None = None
        if self.expires is not None:
            utc = self.expires.astimezone(UTC)
            expires = utc.strftime(
                "%Y-%m-%dT%H:%M:%S.%fZ" if utc.microsecond else "%Y-%m-%dT%H:%M:%SZ"
            )
        payload = {
            "_pyagent_dns": "record/v1",
            "capabilities": list(self.capabilities),
            "data_classes": list(self.data_classes),
            "endpoint": self.endpoint,
            "expires": expires,
            "identity": self.identity.to_dict(),
            "kind": str(self.kind),
            "name": self.name,
            "owner": self.owner,
            "schema_hash": self.schema_hash,
            "signature_algorithm": self.signature_algorithm,
            "status": str(self.status),
            "ttl_seconds": self.ttl_seconds,
            "version": self.version,
        }
        return json.dumps(
            payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True
        ).encode()

    @property
    def fingerprint(self) -> str:
        """``sha256:`` digest of :meth:`canonical_bytes`, the stable name of these exact bytes."""
        return f"sha256:{hashlib.sha256(self.canonical_bytes()).hexdigest()}"

    def is_expired(self, now: datetime | None = None) -> bool:
        """Return whether the record's expiry has passed at ``now`` (default: current UTC time)."""
        if self.expires is None:
            return False
        current = datetime.now(UTC) if now is None else ensure_aware(now, "now")
        return current > self.expires

    def to_dict(self) -> dict[str, Any]:
        """Return the record as a plain dictionary that :meth:`from_dict` accepts."""
        return {
            "name": self.name,
            "kind": str(self.kind),
            "version": self.version,
            "endpoint": self.endpoint,
            "identity": self.identity.to_dict(),
            "schema_hash": self.schema_hash,
            "capabilities": list(self.capabilities),
            "data_classes": list(self.data_classes),
            "owner": self.owner,
            "status": str(self.status),
            "expires": self.expires.astimezone(UTC).isoformat() if self.expires else None,
            "ttl_seconds": self.ttl_seconds,
            "signature": self.signature,
            "signature_algorithm": self.signature_algorithm,
        }

    @classmethod
    def from_dict(cls, data: Mapping[str, Any], *, where: str = "record") -> NameRecord:
        """Build a record from a mapping.

        Every field without a default in the dataclass is required, and unknown keys are
        rejected, so a typo cannot silently change what is signed or granted.

        Raises:
            RecordLoadError: On a missing, unknown, or malformed field.
        """
        required = ["name", "kind", "version", "endpoint", "identity", "schema_hash"]
        required += ["capabilities", "data_classes", "owner"]
        optional = ["status", "expires", "ttl_seconds", "signature", "signature_algorithm"]
        check_keys(data, required=required, optional=optional, where=where, error=RecordLoadError)
        for key in ("name", "version", "endpoint", "schema_hash", "owner"):
            if not isinstance(data[key], str):
                raise RecordLoadError(f"{where}: '{key}' must be a string, got {data[key]!r}")
        if not isinstance(data["identity"], dict):
            raise RecordLoadError(f"{where}: 'identity' must be a mapping")
        signature = data.get("signature")
        if signature is not None and not isinstance(signature, str):
            raise RecordLoadError(f"{where}: 'signature' must be a string")
        try:
            kind = RecordKind(data["kind"])
            status = RecordStatus(data.get("status", "active"))
        except ValueError as exc:
            raise RecordLoadError(f"{where}: {exc}") from None

        identity = Identity.from_dict(data["identity"], where=f"{where}.identity")
        capabilities = _string_list(data["capabilities"], key="capabilities", where=where)
        data_classes = _string_list(data["data_classes"], key="data_classes", where=where)
        expires = parse_expiry(data.get("expires"), where=f"{where}.expires", error=RecordLoadError)
        try:
            return cls(
                name=data["name"],
                kind=kind,
                version=data["version"],
                endpoint=data["endpoint"],
                identity=identity,
                schema_hash=data["schema_hash"],
                capabilities=capabilities,
                data_classes=data_classes,
                owner=data["owner"],
                status=status,
                expires=expires,
                ttl_seconds=data.get("ttl_seconds", 300),
                signature=signature,
                signature_algorithm=str(data.get("signature_algorithm", "ed25519")),
            )
        except RecordLoadError as exc:
            raise RecordLoadError(f"{where}: {exc}") from None

    @classmethod
    def from_agent_card(
        cls,
        card: Mapping[str, Any],
        *,
        owner: str,
        expires: datetime | None,
        identity: Identity,
        data_classes: tuple[str, ...],
    ) -> NameRecord:
        """Import an A2A Agent Card as an unsigned agent record.

        A card carries a name, URL, version, and skills. It does not say who owns the agent,
        when its authority should lapse, who vouches for it, or what data it touches, so the
        caller must say so. Nothing is guessed. ``expires=None`` is an explicit choice of no
        expiry. Capability names come from each skill's ``id`` (falling back to ``name``).
        ``schema_hash`` is the SHA-256 of the card as imported, so a changed card is a
        changed record. The result is unsigned; sign it with ``sign_record``.

        Raises:
            ValueError: If the card lacks a name, url, version, or usable skill, or the
                caller supplies an empty owner or an identity with no signer or fingerprint.
        """
        if not owner:
            raise ValueError("owner is required when importing an agent card")
        if not identity.signed_by or not identity.public_key_fingerprint:
            raise ValueError("identity with signed_by and public_key_fingerprint is required")
        missing = [key for key in ("name", "url", "version") if not card.get(key)]
        if missing:
            raise ValueError(f"agent card is missing required field(s): {', '.join(missing)}")

        capabilities: list[str] = []
        for skill in card.get("skills", []):
            if isinstance(skill, str):
                skill_name: Any = skill
            elif isinstance(skill, dict):
                skill_name = skill.get("id") or skill.get("name")
            else:
                skill_name = None
            if not skill_name:
                raise ValueError(f"agent card skill has neither 'id' nor 'name': {skill!r}")
            capabilities.append(str(skill_name))

        card_bytes = json.dumps(card, sort_keys=True, separators=(",", ":"), default=str).encode()
        return cls(
            name=str(card["name"]),
            kind=RecordKind.AGENT,
            version=str(card["version"]),
            endpoint=str(card["url"]),
            identity=identity,
            schema_hash=f"sha256:{hashlib.sha256(card_bytes).hexdigest()}",
            capabilities=tuple(capabilities),
            data_classes=data_classes,
            owner=owner,
            expires=expires,
        )

fingerprint property

sha256: digest of :meth:canonical_bytes, the stable name of these exact bytes.

canonical_bytes()

Return the exact bytes that are signed: sorted-key compact JSON, UTF-8.

signature is excluded. The _pyagent_dns marker is a domain separator, so a signature over a record cannot be replayed as a signature in another protocol.

Source code in packages/pyagent-dns/src/pyagent_dns/records.py
def canonical_bytes(self) -> bytes:
    """Return the exact bytes that are signed: sorted-key compact JSON, UTF-8.

    ``signature`` is excluded. The ``_pyagent_dns`` marker is a domain separator, so a
    signature over a record cannot be replayed as a signature in another protocol.
    """
    expires: str | None = None
    if self.expires is not None:
        utc = self.expires.astimezone(UTC)
        expires = utc.strftime(
            "%Y-%m-%dT%H:%M:%S.%fZ" if utc.microsecond else "%Y-%m-%dT%H:%M:%SZ"
        )
    payload = {
        "_pyagent_dns": "record/v1",
        "capabilities": list(self.capabilities),
        "data_classes": list(self.data_classes),
        "endpoint": self.endpoint,
        "expires": expires,
        "identity": self.identity.to_dict(),
        "kind": str(self.kind),
        "name": self.name,
        "owner": self.owner,
        "schema_hash": self.schema_hash,
        "signature_algorithm": self.signature_algorithm,
        "status": str(self.status),
        "ttl_seconds": self.ttl_seconds,
        "version": self.version,
    }
    return json.dumps(
        payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True
    ).encode()

is_expired(now=None)

Return whether the record's expiry has passed at now (default: current UTC time).

Source code in packages/pyagent-dns/src/pyagent_dns/records.py
def is_expired(self, now: datetime | None = None) -> bool:
    """Return whether the record's expiry has passed at ``now`` (default: current UTC time)."""
    if self.expires is None:
        return False
    current = datetime.now(UTC) if now is None else ensure_aware(now, "now")
    return current > self.expires

to_dict()

Return the record as a plain dictionary that :meth:from_dict accepts.

Source code in packages/pyagent-dns/src/pyagent_dns/records.py
def to_dict(self) -> dict[str, Any]:
    """Return the record as a plain dictionary that :meth:`from_dict` accepts."""
    return {
        "name": self.name,
        "kind": str(self.kind),
        "version": self.version,
        "endpoint": self.endpoint,
        "identity": self.identity.to_dict(),
        "schema_hash": self.schema_hash,
        "capabilities": list(self.capabilities),
        "data_classes": list(self.data_classes),
        "owner": self.owner,
        "status": str(self.status),
        "expires": self.expires.astimezone(UTC).isoformat() if self.expires else None,
        "ttl_seconds": self.ttl_seconds,
        "signature": self.signature,
        "signature_algorithm": self.signature_algorithm,
    }

from_dict(data, *, where='record') classmethod

Build a record from a mapping.

Every field without a default in the dataclass is required, and unknown keys are rejected, so a typo cannot silently change what is signed or granted.

Raises:

Type Description
RecordLoadError

On a missing, unknown, or malformed field.

Source code in packages/pyagent-dns/src/pyagent_dns/records.py
@classmethod
def from_dict(cls, data: Mapping[str, Any], *, where: str = "record") -> NameRecord:
    """Build a record from a mapping.

    Every field without a default in the dataclass is required, and unknown keys are
    rejected, so a typo cannot silently change what is signed or granted.

    Raises:
        RecordLoadError: On a missing, unknown, or malformed field.
    """
    required = ["name", "kind", "version", "endpoint", "identity", "schema_hash"]
    required += ["capabilities", "data_classes", "owner"]
    optional = ["status", "expires", "ttl_seconds", "signature", "signature_algorithm"]
    check_keys(data, required=required, optional=optional, where=where, error=RecordLoadError)
    for key in ("name", "version", "endpoint", "schema_hash", "owner"):
        if not isinstance(data[key], str):
            raise RecordLoadError(f"{where}: '{key}' must be a string, got {data[key]!r}")
    if not isinstance(data["identity"], dict):
        raise RecordLoadError(f"{where}: 'identity' must be a mapping")
    signature = data.get("signature")
    if signature is not None and not isinstance(signature, str):
        raise RecordLoadError(f"{where}: 'signature' must be a string")
    try:
        kind = RecordKind(data["kind"])
        status = RecordStatus(data.get("status", "active"))
    except ValueError as exc:
        raise RecordLoadError(f"{where}: {exc}") from None

    identity = Identity.from_dict(data["identity"], where=f"{where}.identity")
    capabilities = _string_list(data["capabilities"], key="capabilities", where=where)
    data_classes = _string_list(data["data_classes"], key="data_classes", where=where)
    expires = parse_expiry(data.get("expires"), where=f"{where}.expires", error=RecordLoadError)
    try:
        return cls(
            name=data["name"],
            kind=kind,
            version=data["version"],
            endpoint=data["endpoint"],
            identity=identity,
            schema_hash=data["schema_hash"],
            capabilities=capabilities,
            data_classes=data_classes,
            owner=data["owner"],
            status=status,
            expires=expires,
            ttl_seconds=data.get("ttl_seconds", 300),
            signature=signature,
            signature_algorithm=str(data.get("signature_algorithm", "ed25519")),
        )
    except RecordLoadError as exc:
        raise RecordLoadError(f"{where}: {exc}") from None

from_agent_card(card, *, owner, expires, identity, data_classes) classmethod

Import an A2A Agent Card as an unsigned agent record.

A card carries a name, URL, version, and skills. It does not say who owns the agent, when its authority should lapse, who vouches for it, or what data it touches, so the caller must say so. Nothing is guessed. expires=None is an explicit choice of no expiry. Capability names come from each skill's id (falling back to name). schema_hash is the SHA-256 of the card as imported, so a changed card is a changed record. The result is unsigned; sign it with sign_record.

Raises:

Type Description
ValueError

If the card lacks a name, url, version, or usable skill, or the caller supplies an empty owner or an identity with no signer or fingerprint.

Source code in packages/pyagent-dns/src/pyagent_dns/records.py
@classmethod
def from_agent_card(
    cls,
    card: Mapping[str, Any],
    *,
    owner: str,
    expires: datetime | None,
    identity: Identity,
    data_classes: tuple[str, ...],
) -> NameRecord:
    """Import an A2A Agent Card as an unsigned agent record.

    A card carries a name, URL, version, and skills. It does not say who owns the agent,
    when its authority should lapse, who vouches for it, or what data it touches, so the
    caller must say so. Nothing is guessed. ``expires=None`` is an explicit choice of no
    expiry. Capability names come from each skill's ``id`` (falling back to ``name``).
    ``schema_hash`` is the SHA-256 of the card as imported, so a changed card is a
    changed record. The result is unsigned; sign it with ``sign_record``.

    Raises:
        ValueError: If the card lacks a name, url, version, or usable skill, or the
            caller supplies an empty owner or an identity with no signer or fingerprint.
    """
    if not owner:
        raise ValueError("owner is required when importing an agent card")
    if not identity.signed_by or not identity.public_key_fingerprint:
        raise ValueError("identity with signed_by and public_key_fingerprint is required")
    missing = [key for key in ("name", "url", "version") if not card.get(key)]
    if missing:
        raise ValueError(f"agent card is missing required field(s): {', '.join(missing)}")

    capabilities: list[str] = []
    for skill in card.get("skills", []):
        if isinstance(skill, str):
            skill_name: Any = skill
        elif isinstance(skill, dict):
            skill_name = skill.get("id") or skill.get("name")
        else:
            skill_name = None
        if not skill_name:
            raise ValueError(f"agent card skill has neither 'id' nor 'name': {skill!r}")
        capabilities.append(str(skill_name))

    card_bytes = json.dumps(card, sort_keys=True, separators=(",", ":"), default=str).encode()
    return cls(
        name=str(card["name"]),
        kind=RecordKind.AGENT,
        version=str(card["version"]),
        endpoint=str(card["url"]),
        identity=identity,
        schema_hash=f"sha256:{hashlib.sha256(card_bytes).hexdigest()}",
        capabilities=tuple(capabilities),
        data_classes=data_classes,
        owner=owner,
        expires=expires,
    )

RecordInfo dataclass

A summary of a stored record. status is the effective lifecycle status, which includes operator revocation, and verification is computed by the verifier.

Source code in packages/pyagent-dns/src/pyagent_dns/records.py
@dataclass(frozen=True)
class RecordInfo:
    """A summary of a stored record. ``status`` is the effective lifecycle status, which
    includes operator revocation, and ``verification`` is computed by the verifier."""

    name: str
    kind: RecordKind
    version: str
    status: RecordStatus
    owner: str
    fingerprint: str
    verification: VerificationStatus

RecordKind

Bases: StrEnum

The kind of entity named by a NameRecord.

Source code in packages/pyagent-dns/src/pyagent_dns/records.py
class RecordKind(StrEnum):
    """The kind of entity named by a NameRecord."""

    AGENT = "agent"
    TOOL = "tool"
    PROVIDER = "provider"
    DATA = "data"
    APPROVER = "approver"

RecordLoadError

Bases: ValueError

Raised when a record is malformed, whether loaded from a file or built in code.

Source code in packages/pyagent-dns/src/pyagent_dns/records.py
class RecordLoadError(ValueError):
    """Raised when a record is malformed, whether loaded from a file or built in code."""

RecordStatus

Bases: StrEnum

Lifecycle status the record's owner declared inside the signed payload.

Source code in packages/pyagent-dns/src/pyagent_dns/records.py
class RecordStatus(StrEnum):
    """Lifecycle status the record's owner declared inside the signed payload."""

    ACTIVE = "active"
    DEPRECATED = "deprecated"
    REVOKED = "revoked"

NameRegistry

Versioned store of signed records, with capability discovery and revocation.

Records are keyed by (name, version) so several versions of one name can coexist. revoke records the revocation in the registry and leaves the stored record exactly as the owner signed it. Rewriting the record's status would break its signature and change its fingerprint, and an audit log would then report a legitimately revoked record as failed. Use :meth:status_of for the effective lifecycle status.

Revocation lasts for the registry's lifetime: re-registering a revoked (name, version) does not restore it. Reload from files to clear it.

Not thread-safe. Like ProviderRegistry, it assumes single-process, event-loop use; serialize access yourself if you mutate it from several threads.

Parameters:

Name Type Description Default
trusted_keys TrustedKeys | None

Keys records are verified against. With none, every record is UNVERIFIED.

None
clock Callable[[], float]

Returns the current time in epoch seconds. Inject one in tests instead of sleeping.

time
Source code in packages/pyagent-dns/src/pyagent_dns/registry.py
class NameRegistry:
    """Versioned store of signed records, with capability discovery and revocation.

    Records are keyed by ``(name, version)`` so several versions of one name can coexist.
    ``revoke`` records the revocation in the registry and leaves the stored record exactly
    as the owner signed it. Rewriting the record's ``status`` would break its signature and
    change its fingerprint, and an audit log would then report a legitimately revoked record
    as ``failed``. Use :meth:`status_of` for the effective lifecycle status.

    Revocation lasts for the registry's lifetime: re-registering a revoked ``(name,
    version)`` does not restore it. Reload from files to clear it.

    Not thread-safe. Like ``ProviderRegistry``, it assumes single-process, event-loop use;
    serialize access yourself if you mutate it from several threads.

    Args:
        trusted_keys: Keys records are verified against. With none, every record is
            ``UNVERIFIED``.
        clock: Returns the current time in epoch seconds. Inject one in tests instead of
            sleeping.
    """

    def __init__(
        self,
        trusted_keys: TrustedKeys | None = None,
        *,
        clock: Callable[[], float] = time.time,
    ) -> None:
        self._trusted_keys = trusted_keys
        self._clock = clock
        self._records: dict[_Key, NameRecord] = {}
        self._revoked: set[_Key] = set()
        self._reported_expired: set[_Key] = set()
        self._generation = 0

    @property
    def trusted_keys(self) -> TrustedKeys | None:
        """The keys records are verified against."""
        return self._trusted_keys

    @trusted_keys.setter
    def trusted_keys(self, value: TrustedKeys | None) -> None:
        self._trusted_keys = value
        self._generation += 1

    @property
    def clock(self) -> Callable[[], float]:
        """The time source, in epoch seconds."""
        return self._clock

    @property
    def generation(self) -> int:
        """Counter that increases on every change that could alter a resolution."""
        return self._generation

    @property
    def count(self) -> int:
        """Number of stored records, counting each version."""
        return len(self._records)

    def __len__(self) -> int:
        return len(self._records)

    def __contains__(self, name: str) -> bool:
        return any(record_name == name for record_name, _ in self._records)

    def now(self) -> datetime:
        """The current time as an aware UTC datetime, from the injected clock."""
        return datetime.fromtimestamp(self._clock(), UTC)

    def register(self, record: NameRecord) -> None:
        """Store a record, replacing any record with the same name and version.

        Unsigned and unverifiable records are accepted, because a registry may hold them for
        review. Verification is reported, and enforced at authorization time.
        """
        self.register_many([record])

    def register_many(self, records: Iterable[NameRecord]) -> None:
        """Store several records as one change."""
        changed = False
        for record in records:
            key = (record.name, record.version)
            self._records[key] = record
            self._reported_expired.discard(key)
            changed = True
        if changed:
            self._generation += 1

    @classmethod
    def from_directory(
        cls, path: str | Path, *, trusted_keys: TrustedKeys | None = None
    ) -> NameRegistry:
        """Build a registry from every record file under a directory."""
        registry = cls(trusted_keys=trusted_keys)
        registry.register_many(load_records_directory(path))
        return registry

    def status_of(self, name: str, version: str) -> RecordStatus | None:
        """Effective lifecycle status of one version, or ``None`` if it is not stored.

        ``REVOKED`` if the owner declared it or an operator revoked it here.
        """
        record = self._records.get((name, version))
        if record is None:
            return None
        if (name, version) in self._revoked:
            return RecordStatus.REVOKED
        return record.status

    def _usable(self, record: NameRecord, now: datetime) -> bool:
        status = self.status_of(record.name, record.version)
        return status != RecordStatus.REVOKED and not record.is_expired(now)

    def _versions(self, name: str) -> list[NameRecord]:
        """Stored versions of ``name``, newest first."""
        matching = [record for (n, _), record in self._records.items() if n == name]
        return sorted(matching, key=lambda r: (version_key(r.version), r.version), reverse=True)

    def get(self, name: str, version: str | None = None) -> NameRecord | None:
        """Return a record as published.

        With ``version``, returns exactly that version or ``None``. Without it, returns the
        newest version that is neither revoked nor expired. If every version is revoked or
        expired it returns the newest anyway, so a caller can tell "this name was revoked"
        from "this name never existed". Check :meth:`status_of` before relying on the result.
        """
        if version is not None:
            return self._records.get((name, version))
        versions = self._versions(name)
        if not versions:
            return None
        now = self.now()
        return next((r for r in versions if self._usable(r, now)), versions[0])

    def list_records(self) -> list[RecordInfo]:
        """Summarize every stored record, including its computed verification status."""
        return [
            RecordInfo(
                name=record.name,
                kind=record.kind,
                version=record.version,
                status=self.status_of(record.name, record.version) or record.status,
                owner=record.owner,
                fingerprint=record.fingerprint,
                verification=self.verify(record.name, record.version),
            )
            for _, record in sorted(self._records.items())
        ]

    def discover(
        self,
        required_capabilities: set[str] | None = None,
        *,
        kind: RecordKind | None = None,
        verified_only: bool = True,
    ) -> list[NameRecord]:
        """Find records whose capabilities include every required capability.

        Matching is exact set inclusion, the same semantics as ``ProviderRegistry.discover``.
        Each name contributes at most its newest version that is usable (not revoked or
        expired) and passes the filters. Unverified records are excluded unless
        ``verified_only`` is False; discovery never implies permission to call.
        """
        required = required_capabilities or set()
        now = self.now()
        found: list[NameRecord] = []
        for name in sorted({n for n, _ in self._records}):
            for record in self._versions(name):
                if not self._usable(record, now):
                    continue
                if kind is not None and record.kind != kind:
                    continue
                if not required <= set(record.capabilities):
                    continue
                if (
                    verified_only
                    and self.verify(record.name, record.version) != VerificationStatus.VERIFIED
                ):
                    continue
                found.append(record)
                break
        return found

    def verify(self, name: str, version: str | None = None) -> VerificationStatus:
        """Verify a stored record's signature. ``UNVERIFIED`` if absent or no keys are set."""
        record = self.get(name, version)
        if record is None or self._trusted_keys is None:
            return VerificationStatus.UNVERIFIED
        return verify_record(record, self._trusted_keys)

    def expire(self, now: datetime | None = None) -> list[str]:
        """Report names whose versions have newly crossed their expiry. Nothing is deleted.

        An expired record stays stored so a decision log that names its fingerprint can
        still be explained. Each ``(name, version)`` is reported once.
        """
        current = self.now() if now is None else ensure_aware(now, "now")
        newly = [
            key
            for key, record in self._records.items()
            if key not in self._reported_expired and record.is_expired(current)
        ]
        if newly:
            self._reported_expired.update(newly)
            self._generation += 1
        return sorted({name for name, _ in newly})

    def revoke(self, name: str, version: str | None = None) -> bool:
        """Revoke one version, or every version of ``name``. Returns whether anything changed."""
        keys = [k for k in self._records if k[0] == name and (version is None or k[1] == version)]
        newly = [k for k in keys if self.status_of(*k) != RecordStatus.REVOKED]
        if newly:
            self._revoked.update(newly)
            self._generation += 1
        return bool(newly)

    def remove(self, name: str, version: str | None = None) -> None:
        """Delete one version, or every version of ``name``, including its revocation."""
        keys = [k for k in self._records if k[0] == name and (version is None or k[1] == version)]
        for key in keys:
            del self._records[key]
            self._revoked.discard(key)
            self._reported_expired.discard(key)
        if keys:
            self._generation += 1

trusted_keys property writable

The keys records are verified against.

clock property

The time source, in epoch seconds.

generation property

Counter that increases on every change that could alter a resolution.

count property

Number of stored records, counting each version.

now()

The current time as an aware UTC datetime, from the injected clock.

Source code in packages/pyagent-dns/src/pyagent_dns/registry.py
def now(self) -> datetime:
    """The current time as an aware UTC datetime, from the injected clock."""
    return datetime.fromtimestamp(self._clock(), UTC)

register(record)

Store a record, replacing any record with the same name and version.

Unsigned and unverifiable records are accepted, because a registry may hold them for review. Verification is reported, and enforced at authorization time.

Source code in packages/pyagent-dns/src/pyagent_dns/registry.py
def register(self, record: NameRecord) -> None:
    """Store a record, replacing any record with the same name and version.

    Unsigned and unverifiable records are accepted, because a registry may hold them for
    review. Verification is reported, and enforced at authorization time.
    """
    self.register_many([record])

register_many(records)

Store several records as one change.

Source code in packages/pyagent-dns/src/pyagent_dns/registry.py
def register_many(self, records: Iterable[NameRecord]) -> None:
    """Store several records as one change."""
    changed = False
    for record in records:
        key = (record.name, record.version)
        self._records[key] = record
        self._reported_expired.discard(key)
        changed = True
    if changed:
        self._generation += 1

from_directory(path, *, trusted_keys=None) classmethod

Build a registry from every record file under a directory.

Source code in packages/pyagent-dns/src/pyagent_dns/registry.py
@classmethod
def from_directory(
    cls, path: str | Path, *, trusted_keys: TrustedKeys | None = None
) -> NameRegistry:
    """Build a registry from every record file under a directory."""
    registry = cls(trusted_keys=trusted_keys)
    registry.register_many(load_records_directory(path))
    return registry

status_of(name, version)

Effective lifecycle status of one version, or None if it is not stored.

REVOKED if the owner declared it or an operator revoked it here.

Source code in packages/pyagent-dns/src/pyagent_dns/registry.py
def status_of(self, name: str, version: str) -> RecordStatus | None:
    """Effective lifecycle status of one version, or ``None`` if it is not stored.

    ``REVOKED`` if the owner declared it or an operator revoked it here.
    """
    record = self._records.get((name, version))
    if record is None:
        return None
    if (name, version) in self._revoked:
        return RecordStatus.REVOKED
    return record.status

get(name, version=None)

Return a record as published.

With version, returns exactly that version or None. Without it, returns the newest version that is neither revoked nor expired. If every version is revoked or expired it returns the newest anyway, so a caller can tell "this name was revoked" from "this name never existed". Check :meth:status_of before relying on the result.

Source code in packages/pyagent-dns/src/pyagent_dns/registry.py
def get(self, name: str, version: str | None = None) -> NameRecord | None:
    """Return a record as published.

    With ``version``, returns exactly that version or ``None``. Without it, returns the
    newest version that is neither revoked nor expired. If every version is revoked or
    expired it returns the newest anyway, so a caller can tell "this name was revoked"
    from "this name never existed". Check :meth:`status_of` before relying on the result.
    """
    if version is not None:
        return self._records.get((name, version))
    versions = self._versions(name)
    if not versions:
        return None
    now = self.now()
    return next((r for r in versions if self._usable(r, now)), versions[0])

list_records()

Summarize every stored record, including its computed verification status.

Source code in packages/pyagent-dns/src/pyagent_dns/registry.py
def list_records(self) -> list[RecordInfo]:
    """Summarize every stored record, including its computed verification status."""
    return [
        RecordInfo(
            name=record.name,
            kind=record.kind,
            version=record.version,
            status=self.status_of(record.name, record.version) or record.status,
            owner=record.owner,
            fingerprint=record.fingerprint,
            verification=self.verify(record.name, record.version),
        )
        for _, record in sorted(self._records.items())
    ]

discover(required_capabilities=None, *, kind=None, verified_only=True)

Find records whose capabilities include every required capability.

Matching is exact set inclusion, the same semantics as ProviderRegistry.discover. Each name contributes at most its newest version that is usable (not revoked or expired) and passes the filters. Unverified records are excluded unless verified_only is False; discovery never implies permission to call.

Source code in packages/pyagent-dns/src/pyagent_dns/registry.py
def discover(
    self,
    required_capabilities: set[str] | None = None,
    *,
    kind: RecordKind | None = None,
    verified_only: bool = True,
) -> list[NameRecord]:
    """Find records whose capabilities include every required capability.

    Matching is exact set inclusion, the same semantics as ``ProviderRegistry.discover``.
    Each name contributes at most its newest version that is usable (not revoked or
    expired) and passes the filters. Unverified records are excluded unless
    ``verified_only`` is False; discovery never implies permission to call.
    """
    required = required_capabilities or set()
    now = self.now()
    found: list[NameRecord] = []
    for name in sorted({n for n, _ in self._records}):
        for record in self._versions(name):
            if not self._usable(record, now):
                continue
            if kind is not None and record.kind != kind:
                continue
            if not required <= set(record.capabilities):
                continue
            if (
                verified_only
                and self.verify(record.name, record.version) != VerificationStatus.VERIFIED
            ):
                continue
            found.append(record)
            break
    return found

verify(name, version=None)

Verify a stored record's signature. UNVERIFIED if absent or no keys are set.

Source code in packages/pyagent-dns/src/pyagent_dns/registry.py
def verify(self, name: str, version: str | None = None) -> VerificationStatus:
    """Verify a stored record's signature. ``UNVERIFIED`` if absent or no keys are set."""
    record = self.get(name, version)
    if record is None or self._trusted_keys is None:
        return VerificationStatus.UNVERIFIED
    return verify_record(record, self._trusted_keys)

expire(now=None)

Report names whose versions have newly crossed their expiry. Nothing is deleted.

An expired record stays stored so a decision log that names its fingerprint can still be explained. Each (name, version) is reported once.

Source code in packages/pyagent-dns/src/pyagent_dns/registry.py
def expire(self, now: datetime | None = None) -> list[str]:
    """Report names whose versions have newly crossed their expiry. Nothing is deleted.

    An expired record stays stored so a decision log that names its fingerprint can
    still be explained. Each ``(name, version)`` is reported once.
    """
    current = self.now() if now is None else ensure_aware(now, "now")
    newly = [
        key
        for key, record in self._records.items()
        if key not in self._reported_expired and record.is_expired(current)
    ]
    if newly:
        self._reported_expired.update(newly)
        self._generation += 1
    return sorted({name for name, _ in newly})

revoke(name, version=None)

Revoke one version, or every version of name. Returns whether anything changed.

Source code in packages/pyagent-dns/src/pyagent_dns/registry.py
def revoke(self, name: str, version: str | None = None) -> bool:
    """Revoke one version, or every version of ``name``. Returns whether anything changed."""
    keys = [k for k in self._records if k[0] == name and (version is None or k[1] == version)]
    newly = [k for k in keys if self.status_of(*k) != RecordStatus.REVOKED]
    if newly:
        self._revoked.update(newly)
        self._generation += 1
    return bool(newly)

remove(name, version=None)

Delete one version, or every version of name, including its revocation.

Source code in packages/pyagent-dns/src/pyagent_dns/registry.py
def remove(self, name: str, version: str | None = None) -> None:
    """Delete one version, or every version of ``name``, including its revocation."""
    keys = [k for k in self._records if k[0] == name and (version is None or k[1] == version)]
    for key in keys:
        del self._records[key]
        self._revoked.discard(key)
        self._reported_expired.discard(key)
    if keys:
        self._generation += 1

Resolution dataclass

The result of resolving a name: a record, and what is known about it right now.

Lifecycle and verification are separate facts. status is the effective lifecycle status, including operator revocation. verification is computed by the verifier, and a record cannot declare its own verification outcome.

Parameters:

Name Type Description Default
record NameRecord

The record as published and signed.

required
version str

Exact version resolved.

required
fingerprint str

Digest of the signed bytes. Stable across revocation, so a decision log can name exactly what was resolved.

required
resolved_at float

Epoch seconds, from the resolver's clock.

required
verified bool

Whether verification is VERIFIED.

required
verification VerificationStatus

Signature verification outcome.

required
status RecordStatus

Effective lifecycle status.

ACTIVE
from_cache bool

Whether this was served from the TTL cache.

False
Source code in packages/pyagent-dns/src/pyagent_dns/resolver.py
@dataclass(frozen=True)
class Resolution:
    """The result of resolving a name: a record, and what is known about it right now.

    Lifecycle and verification are separate facts. ``status`` is the effective lifecycle
    status, including operator revocation. ``verification`` is computed by the verifier, and
    a record cannot declare its own verification outcome.

    Args:
        record: The record as published and signed.
        version: Exact version resolved.
        fingerprint: Digest of the signed bytes. Stable across revocation, so a decision
            log can name exactly what was resolved.
        resolved_at: Epoch seconds, from the resolver's clock.
        verified: Whether ``verification`` is ``VERIFIED``.
        verification: Signature verification outcome.
        status: Effective lifecycle status.
        from_cache: Whether this was served from the TTL cache.
    """

    record: NameRecord
    version: str
    fingerprint: str
    resolved_at: float
    verified: bool
    verification: VerificationStatus
    status: RecordStatus = RecordStatus.ACTIVE
    from_cache: bool = False

Resolver

Resolve names to verified records, caching each result for the record's TTL.

The cache is dropped whenever the registry changes, and a revoked or expired record is never served from it. Resolution is a local lookup plus a signature check. It never connects to the record's endpoint.

Parameters:

Name Type Description Default
registry NameRegistry

The registry to resolve against.

required
clock Callable[[], float] | None

Epoch-seconds time source. Defaults to the registry's, so TTLs and record expiry always agree.

None
Source code in packages/pyagent-dns/src/pyagent_dns/resolver.py
class Resolver:
    """Resolve names to verified records, caching each result for the record's TTL.

    The cache is dropped whenever the registry changes, and a revoked or expired record is
    never served from it. Resolution is a local lookup plus a signature check. It never
    connects to the record's endpoint.

    Args:
        registry: The registry to resolve against.
        clock: Epoch-seconds time source. Defaults to the registry's, so TTLs and record
            expiry always agree.
    """

    def __init__(self, registry: NameRegistry, *, clock: Callable[[], float] | None = None) -> None:
        self._registry = registry
        self._clock = clock or registry.clock
        self._cache: dict[tuple[str, str], Resolution] = {}
        self._seen_generation = registry.generation

    @property
    def cache_size(self) -> int:
        """Number of cached resolutions."""
        self._drop_stale_cache()
        return len(self._cache)

    def _drop_stale_cache(self) -> None:
        if self._registry.generation != self._seen_generation:
            self._cache.clear()
            self._seen_generation = self._registry.generation

    def invalidate(self, name: str | None = None) -> None:
        """Drop the whole cache, or only the entries for ``name``."""
        if name is None:
            self._cache.clear()
        else:
            for key in [k for k in self._cache if k[0] == name]:
                del self._cache[key]

    def _status(self, record: NameRecord) -> RecordStatus:
        return self._registry.status_of(record.name, record.version) or record.status

    def _is_live(self, record: NameRecord) -> bool:
        return self._status(record) != RecordStatus.REVOKED and not record.is_expired(
            self._registry.now()
        )

    def _build(self, record: NameRecord) -> Resolution:
        verification = self._registry.verify(record.name, record.version)
        resolution = Resolution(
            record=record,
            version=record.version,
            fingerprint=record.fingerprint,
            resolved_at=self._clock(),
            verified=verification == VerificationStatus.VERIFIED,
            verification=verification,
            status=self._status(record),
        )
        key = (record.name, record.version)
        if self._is_live(record):
            self._cache[key] = resolution
        else:
            self._cache.pop(key, None)
        return resolution

    def resolve(self, name: str, version: str | None = None) -> Resolution | None:
        """Resolve ``name``, using the cache while the entry is within the record's TTL.

        Returns ``None`` only if the name was never registered. A revoked or expired record
        still resolves, with that fact in ``status``, because "revoked" and "never existed"
        are different audit facts.
        """
        self._drop_stale_cache()
        record = self._registry.get(name, version)
        if record is None:
            return None
        cached = self._cache.get((record.name, record.version))
        if (
            cached is not None
            and self._is_live(record)
            and self._clock() - cached.resolved_at < record.ttl_seconds
        ):
            return dataclasses.replace(cached, from_cache=True)
        return self._build(record)

    def resolve_fresh(self, name: str, version: str | None = None) -> Resolution | None:
        """Resolve and verify without consulting the cache. Used for high-risk actions."""
        self._drop_stale_cache()
        record = self._registry.get(name, version)
        return None if record is None else self._build(record)

    def resolve_capability(self, capability: str) -> list[Resolution]:
        """Resolve every usable record that declares ``capability``, verified or not."""
        found = self._registry.discover({capability}, verified_only=False)
        return [r for record in found if (r := self.resolve(record.name, record.version))]

cache_size property

Number of cached resolutions.

invalidate(name=None)

Drop the whole cache, or only the entries for name.

Source code in packages/pyagent-dns/src/pyagent_dns/resolver.py
def invalidate(self, name: str | None = None) -> None:
    """Drop the whole cache, or only the entries for ``name``."""
    if name is None:
        self._cache.clear()
    else:
        for key in [k for k in self._cache if k[0] == name]:
            del self._cache[key]

resolve(name, version=None)

Resolve name, using the cache while the entry is within the record's TTL.

Returns None only if the name was never registered. A revoked or expired record still resolves, with that fact in status, because "revoked" and "never existed" are different audit facts.

Source code in packages/pyagent-dns/src/pyagent_dns/resolver.py
def resolve(self, name: str, version: str | None = None) -> Resolution | None:
    """Resolve ``name``, using the cache while the entry is within the record's TTL.

    Returns ``None`` only if the name was never registered. A revoked or expired record
    still resolves, with that fact in ``status``, because "revoked" and "never existed"
    are different audit facts.
    """
    self._drop_stale_cache()
    record = self._registry.get(name, version)
    if record is None:
        return None
    cached = self._cache.get((record.name, record.version))
    if (
        cached is not None
        and self._is_live(record)
        and self._clock() - cached.resolved_at < record.ttl_seconds
    ):
        return dataclasses.replace(cached, from_cache=True)
    return self._build(record)

resolve_fresh(name, version=None)

Resolve and verify without consulting the cache. Used for high-risk actions.

Source code in packages/pyagent-dns/src/pyagent_dns/resolver.py
def resolve_fresh(self, name: str, version: str | None = None) -> Resolution | None:
    """Resolve and verify without consulting the cache. Used for high-risk actions."""
    self._drop_stale_cache()
    record = self._registry.get(name, version)
    return None if record is None else self._build(record)

resolve_capability(capability)

Resolve every usable record that declares capability, verified or not.

Source code in packages/pyagent-dns/src/pyagent_dns/resolver.py
def resolve_capability(self, capability: str) -> list[Resolution]:
    """Resolve every usable record that declares ``capability``, verified or not."""
    found = self._registry.discover({capability}, verified_only=False)
    return [r for record in found if (r := self.resolve(record.name, record.version))]

VerificationStatus

Bases: StrEnum

Outcome of checking a record's signature. Computed by the verifier, never read from a file.

UNVERIFIED means nothing was proven false: the record is unsigned, its signer is not trusted, or it pins a key this reader does not trust. FAILED means a trusted key was found and the signature does not match, which is a stronger and more alarming result.

Source code in packages/pyagent-dns/src/pyagent_dns/signing.py
class VerificationStatus(StrEnum):
    """Outcome of checking a record's signature. Computed by the verifier, never read from a file.

    ``UNVERIFIED`` means nothing was proven false: the record is unsigned, its signer is not
    trusted, or it pins a key this reader does not trust. ``FAILED`` means a trusted key was
    found and the signature does not match, which is a stronger and more alarming result.
    """

    VERIFIED = "verified"
    UNVERIFIED = "unverified"
    FAILED = "failed"

load_blueprint_dns(path)

Load a blueprint's x-pyagent:dns block into a wired :class:DnsBundle.

Relative file references resolve against the blueprint's directory, not the working directory. Returns None if the blueprint has no dns block.

Raises:

Type Description
FileNotFoundError

If the blueprint file does not exist.

DnsBlueprintError

If the block, or any file it references, is invalid. The message names the blueprint. With enforcement: advisory this becomes a warning and None is returned instead.

Source code in packages/pyagent-dns/src/pyagent_dns/blueprint.py
def load_blueprint_dns(path: str | Path) -> DnsBundle | None:
    """Load a blueprint's ``x-pyagent:dns`` block into a wired :class:`DnsBundle`.

    Relative file references resolve against the blueprint's directory, not the working
    directory. Returns ``None`` if the blueprint has no dns block.

    Raises:
        FileNotFoundError: If the blueprint file does not exist.
        DnsBlueprintError: If the block, or any file it references, is invalid. The message
            names the blueprint. With ``enforcement: advisory`` this becomes a warning and
            ``None`` is returned instead.
    """
    blueprint_path = Path(path)
    if not blueprint_path.exists():
        raise FileNotFoundError(f"Blueprint file not found: {blueprint_path}")
    try:
        data = yaml.safe_load(blueprint_path.read_text(encoding="utf-8"))
    except yaml.YAMLError as exc:
        raise DnsBlueprintError(f"{blueprint_path}: cannot parse: {exc}") from exc
    if not isinstance(data, dict):
        raise DnsBlueprintError(f"{blueprint_path}: a blueprint must be a mapping")

    try:
        spec = load_dns_block(data)
    except DnsBlueprintError as exc:
        raise DnsBlueprintError(f"{blueprint_path}: {exc}") from None
    if spec is None:
        return None

    try:
        return _build_bundle(spec, blueprint_path)
    except (OSError, ValueError, AttenuationError) as exc:
        message = f"{blueprint_path}: {EXTENSION_KEY}: {exc}"
        if spec.enforcement == DnsEnforcement.ADVISORY:
            warnings.warn(
                f"{message} (enforcement is advisory; no dns bundle was loaded)", stacklevel=2
            )
            return None
        raise DnsBlueprintError(message) from exc