Skip to content

Commit 70e2fae

Browse files
rustyconoverclaude
andcommitted
feat(identity): a worker can mint delegation grants
``vgi_rpc.Identity.v1`` has always had two methods. Only one was reachable: ``_build_identity`` passed ``resolve_token=`` and nothing else, and there was no ``mint_grant`` anywhere in this package, so ``offered_methods()`` could never include ``issue_grant`` however a worker was written. The protocol was designed; the wiring was missing. ``Worker.mint_grant`` is the hook, detected by override exactly as ``resolve_token`` is — identity comparison against the base, not a "supports grants" flag, because the method must be absent unless a worker actually wrote the minting and a flag can be set without one. A worker may now resolve credentials, mint grants, or both, and the protocol it hosts describes what it does rather than what the version supports. What a grant is for: OAuth cannot express durable delegation. It fuses the grant, the credential and the session into one refresh token, so an IdP shortening session lifetime shortens the grant. This mints the durable record — created while the user is present, presented later by unattended automation as an ordinary bearer. Two guards come from upstream and are worth stating because they are what make the method safe to expose at all: - **No subject on the wire.** ``issue_grant`` has no subject field; the framework passes the caller's own authenticated principal. Cross-subject minting is closed by construction rather than by a check, which is why this needs no allowlist while ``introspect_token`` has one. The allowlist is now passed only when a resolver is supplied — requiring one from a worker that mints but resolves nothing would be a startup error for a worker that is not an oracle, the opposite of the guard's purpose. - **No ``auth_time``, no minting.** A credential that cannot prove a recent human login is refused. That single rule stops a grant minting another grant — a grant is not IdP-issued, so it carries no ``auth_time`` — and makes a static bearer token, which proves a machine holds a secret rather than that anyone authenticated, fail closed. Pinned here, because it is the property that keeps delegation accountable to a login. ``IssuedGrant.token`` is opaque to the framework: a sealed envelope, a database row, or an IdP-brokered credential are equally valid and equally invisible. The docstring says plainly what a self-contained sealed token costs — with no server-side record there is nothing to delete, so individual grants cannot be revoked and rotating the sealing key invalidates all of them at once. A deployment that needs per-grant revocation has to put something lookupable in the token. ``vgi.auth`` re-exports ``IssuedGrant`` and a ``GrantMinter`` alias so a worker author never names a private vgi_rpc module. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent cb7ebbf commit 70e2fae

4 files changed

Lines changed: 259 additions & 12 deletions

File tree

‎tests/test_serve.py‎

Lines changed: 157 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
from vgi_rpc.rpc import AuthContext, PeerResolutionContext, peer_identity_primary
2525

2626
from vgi.arguments import Arguments, Auth, Param, Returns
27-
from vgi.auth import TokenIdentity
27+
from vgi.auth import IssuedGrant, TokenIdentity
2828
from vgi.client import Client
2929
from vgi.scalar_function import ScalarFunction
3030
from vgi.serve import (
@@ -486,6 +486,32 @@ def resolve_token(cls, token: str) -> TokenIdentity | None:
486486
return None
487487

488488

489+
class _MintingWorker(Worker):
490+
"""Worker that implements only the optional grant-minting hook."""
491+
492+
functions = [_DoubleFunc]
493+
494+
@classmethod
495+
def mint_grant(cls, principal: str, purpose: str, scopes: list[str], ttl_seconds: int) -> IssuedGrant:
496+
# A sealed self-contained credential: the worker owns the format and
497+
# the framework never parses it. Capped TTL, to pin that a worker may
498+
# issue SHORTER than asked.
499+
ttl = min(ttl_seconds, 3600)
500+
return IssuedGrant(
501+
token=f"sealed:{principal}:{':'.join(scopes)}:{purpose}",
502+
expires_at=1_000_000.0 + ttl,
503+
grant_id="grant-1",
504+
)
505+
506+
507+
class _BothWorker(_IntrospectingWorker):
508+
"""Worker that both resolves credentials and mints grants."""
509+
510+
@classmethod
511+
def mint_grant(cls, principal: str, purpose: str, scopes: list[str], ttl_seconds: int) -> IssuedGrant:
512+
return IssuedGrant(token=f"sealed:{principal}", expires_at=1_000_000.0, grant_id="g")
513+
514+
489515
class TestIntrospectResolverDetection:
490516
"""``resolve_token`` presence is detected by override, not by a flag."""
491517

@@ -516,6 +542,31 @@ def _introspector_ctx(principal: str) -> object:
516542
)
517543

518544

545+
def _minting_ctx(principal: str, *, auth_age_s: float = 0.0) -> object:
546+
"""Build a ``CallContext`` for a caller who authenticated *auth_age_s* ago.
547+
548+
Minting reads ``auth_time`` off the credential's claims, and a credential
549+
without one cannot mint at all. That single rule is what stops a grant
550+
minting another grant — a grant is not IdP-issued, so it carries no
551+
``auth_time`` — and what makes a static bearer token, which proves a
552+
machine holds a secret rather than that a human just authenticated,
553+
fail closed here.
554+
"""
555+
import time
556+
557+
from vgi_rpc.rpc import AuthContext, CallContext
558+
559+
return CallContext(
560+
auth=AuthContext(
561+
domain="test",
562+
authenticated=True,
563+
principal=principal,
564+
claims={"auth_time": time.time() - auth_age_s},
565+
),
566+
emit_client_log=lambda *a, **k: None,
567+
)
568+
569+
519570
def _hosted_protocols(worker_cls: type[Worker]) -> frozenset[str]:
520571
"""Return the protocol names the server built for *worker_cls* hosts.
521572
@@ -655,6 +706,111 @@ def test_the_retired_rate_limit_is_not_passed(self) -> None:
655706
create_app(_IntrospectingWorker, prefix="/vgi", describe=False)
656707

657708

709+
class TestGrantMinting:
710+
"""``issue_grant`` — the other half of ``vgi_rpc.Identity.v1``.
711+
712+
Guarded very differently from ``introspect_token``, and deliberately so.
713+
Introspection answers a question about *somebody else's* credential, so it
714+
needs an allowlist. Minting produces a credential for the *caller* — there
715+
is no subject on the wire, so cross-subject minting is closed by
716+
construction and no allowlist applies. What this repo owns is the wiring:
717+
a ``mint_grant`` override becomes an ``IdentityImpl`` that offers the
718+
method, and a worker that never wrote one does not host it.
719+
"""
720+
721+
@staticmethod
722+
def _identity(worker_cls: type[Worker], **env: str) -> object:
723+
from vgi.serve import _build_identity
724+
725+
with pytest.MonkeyPatch.context() as mp:
726+
mp.delenv("VGI_INTROSPECT_PRINCIPALS", raising=False)
727+
for key, value in env.items():
728+
mp.setenv(key, value)
729+
return _build_identity(worker_cls, None)
730+
731+
def test_base_worker_has_no_minter(self) -> None:
732+
"""A worker that never wrote the minting gets no issuer."""
733+
assert _SingleWorker._grant_minter() is None
734+
735+
def test_override_is_detected(self) -> None:
736+
"""Implementing the hook is what enables it."""
737+
minter = _MintingWorker._grant_minter()
738+
assert minter is not None
739+
740+
def test_minting_alone_hosts_the_protocol(self) -> None:
741+
"""A worker may mint without resolving — the two are independent."""
742+
assert "vgi_rpc.Identity.v1" in _hosted_protocols(_MintingWorker)
743+
744+
def test_minting_alone_offers_only_issue_grant(self) -> None:
745+
"""The protocol describes what the worker does, not what it could do."""
746+
identity = self._identity(_MintingWorker)
747+
assert identity is not None
748+
assert identity.offered_methods() == frozenset({"issue_grant"}) # type: ignore[attr-defined]
749+
750+
def test_minting_alone_needs_no_introspect_allowlist(self) -> None:
751+
"""No allowlist is required to mint: a grant is not an oracle.
752+
753+
Requiring one would be a startup error for a worker that never exposes
754+
anybody else's identity — the exact opposite of the guard's purpose.
755+
"""
756+
with pytest.MonkeyPatch.context() as mp:
757+
mp.delenv("VGI_INTROSPECT_PRINCIPALS", raising=False)
758+
create_app(_MintingWorker, prefix="/vgi", describe=False)
759+
760+
def test_both_hooks_offer_both_methods(self) -> None:
761+
"""Resolving and minting compose."""
762+
identity = self._identity(_BothWorker, VGI_INTROSPECT_PRINCIPALS="proxy-a")
763+
assert identity is not None
764+
assert identity.offered_methods() == frozenset({"introspect_token", "issue_grant"}) # type: ignore[attr-defined]
765+
766+
def test_the_caller_is_the_subject(self) -> None:
767+
"""The framework supplies the principal; the wire method has no subject field.
768+
769+
This is the property that makes an allowlist unnecessary, so pin it
770+
here rather than trusting the signature to stay that way.
771+
"""
772+
identity = self._identity(_MintingWorker)
773+
assert identity is not None
774+
grant = identity.issue_grant( # type: ignore[attr-defined]
775+
"nightly-etl", ["read"], 600, _minting_ctx("alice")
776+
)
777+
assert grant.token.startswith("sealed:alice:")
778+
assert grant.grant_id == "grant-1"
779+
780+
def test_a_worker_may_issue_a_shorter_ttl_than_asked(self) -> None:
781+
"""A worker may narrow the request; it must never widen it."""
782+
identity = self._identity(_MintingWorker)
783+
assert identity is not None
784+
grant = identity.issue_grant( # type: ignore[attr-defined]
785+
"long", [], 86_400, _minting_ctx("alice")
786+
)
787+
assert grant.expires_at == 1_000_000.0 + 3600
788+
789+
def test_stale_authentication_cannot_mint(self) -> None:
790+
"""Minting while the user is present is enforced, not just documented."""
791+
from vgi_rpc.rpc._token_identity import StaleAuthError
792+
793+
identity = self._identity(_MintingWorker)
794+
assert identity is not None
795+
with pytest.raises(StaleAuthError):
796+
identity.issue_grant("x", [], 60, _minting_ctx("alice", auth_age_s=86_400)) # type: ignore[attr-defined]
797+
798+
def test_a_credential_with_no_auth_time_cannot_mint(self) -> None:
799+
"""A grant cannot mint another grant, and a static bearer cannot mint at all.
800+
801+
Neither carries ``auth_time`` — only an IdP-issued credential does — so
802+
the lineage cannot escape the identity provider. This is the rule that
803+
makes delegation accountable to a human login rather than to whoever
804+
currently holds a machine secret.
805+
"""
806+
from vgi_rpc.rpc._token_identity import StaleAuthError
807+
808+
identity = self._identity(_MintingWorker)
809+
assert identity is not None
810+
with pytest.raises(StaleAuthError):
811+
identity.issue_grant("x", [], 60, _introspector_ctx("etl-service")) # type: ignore[attr-defined]
812+
813+
658814
class TestAuthUnavailableReExport:
659815
"""``AuthUnavailableError`` is reachable without naming a vgi_rpc module."""
660816

‎vgi/auth.py‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99
bearer_authenticate, bearer_authenticate_static, chain_authenticate,
1010
OAuthResourceMetadata, AuthUnavailableError
1111
12-
Token introspection (always available):
13-
TokenIdentity, TokenResolver
12+
Token introspection and delegation (always available):
13+
TokenIdentity, TokenResolver, IssuedGrant, GrantMinter
1414
1515
JWT auth (requires ``vgi[oauth]``):
1616
jwt_authenticate
@@ -30,16 +30,25 @@
3030
# on the ``http`` extra. Still not re-exported by ``vgi_rpc.rpc`` itself, so
3131
# the private module remains the only import path; re-exported here so a worker
3232
# that implements ``resolve_token`` never has to name one.
33-
from vgi_rpc.rpc._token_identity import TokenIdentity
33+
from vgi_rpc.rpc._token_identity import IssuedGrant, TokenIdentity
3434

3535
#: What :meth:`vgi.worker.Worker.resolve_token` is. Upstream dropped its own
3636
#: alias when identity moved to the RPC layer; it is spelled out here so the
3737
#: name ``vgi.auth.TokenResolver`` keeps working.
3838
TokenResolver = Callable[[str], "TokenIdentity | None"]
3939

40+
#: What :meth:`vgi.worker.Worker.mint_grant` is: ``(principal, purpose, scopes,
41+
#: ttl_seconds) -> IssuedGrant``. The subject is a *parameter of the call the
42+
#: framework makes*, never of the wire method — ``issue_grant`` has no subject
43+
#: field, so a worker is handed the caller's own principal and cannot be asked
44+
#: to mint for anybody else.
45+
GrantMinter = Callable[[str, str, list[str], int], "IssuedGrant"]
46+
4047
__all__ = [
4148
"AuthContext",
4249
"CallContext",
50+
"GrantMinter",
51+
"IssuedGrant",
4352
"TokenIdentity",
4453
"TokenResolver",
4554
]

‎vgi/serve.py‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -791,9 +791,12 @@ def _build_identity(
791791
) -> IdentityImpl | None:
792792
"""Build the ``vgi_rpc.Identity.v1`` implementation, or ``None``.
793793
794-
``None`` unless the worker class actually implements the lookup, and that
795-
is the point: ``RpcServer`` then does not host the protocol at all, rather
796-
than hosting it and refusing every call. Absent beats routed-and-refusing —
794+
``None`` unless the worker class implements at least one of the two
795+
methods, and that is the point: ``RpcServer`` then does not host the
796+
protocol at all, rather than hosting it and refusing every call. The two
797+
are independent — a worker may resolve credentials without minting them,
798+
mint without resolving, or do both, and ``offered_methods()`` reports
799+
exactly what it wrote. Absent beats routed-and-refusing —
797800
it is what keeps a dependency upgrade from growing a
798801
credential-to-identity oracle on every existing worker.
799802
@@ -804,8 +807,8 @@ def _build_identity(
804807
calling and reading an error.
805808
806809
Args:
807-
worker_cls: The worker class, consulted for a ``resolve_token``
808-
override.
810+
worker_cls: The worker class, consulted for ``resolve_token`` and
811+
``mint_grant`` overrides.
809812
introspect_principals: Principals permitted to introspect, or ``None``
810813
to read the environment.
811814
@@ -815,7 +818,8 @@ def _build_identity(
815818
816819
"""
817820
resolver = worker_cls._introspect_resolver()
818-
if resolver is None:
821+
minter = worker_cls._grant_minter()
822+
if resolver is None and minter is None:
819823
return None
820824

821825
# Not re-exported by ``vgi_rpc.rpc``, so the private module is the only
@@ -824,7 +828,11 @@ def _build_identity(
824828

825829
return IdentityImpl(
826830
resolve_token=resolver,
827-
introspect_principals=_resolve_introspect_principals(introspect_principals),
831+
mint_grant=minter,
832+
# Only meaningful for ``introspect_token``, and ``IdentityImpl``
833+
# validates it only when a resolver is supplied — a worker that mints
834+
# grants but resolves nothing is not an oracle and needs no allowlist.
835+
introspect_principals=(_resolve_introspect_principals(introspect_principals) if resolver is not None else None),
828836
)
829837

830838

‎vgi/worker.py‎

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ class MyWorker(Worker):
173173
from ssl import SSLContext
174174

175175
from vgi_rpc.rpc import PeerAuthenticationPolicy, PeerIdentityProvider
176-
from vgi_rpc.rpc._token_identity import TokenIdentity
176+
from vgi_rpc.rpc._token_identity import IssuedGrant, TokenIdentity
177177

178178
from vgi.catalog.descriptors import Catalog
179179
from vgi.protocol import (
@@ -1478,6 +1478,80 @@ def _introspect_resolver(cls) -> Callable[[str], TokenIdentity | None] | None:
14781478
return None
14791479
return cls.resolve_token
14801480

1481+
@classmethod
1482+
def mint_grant(cls, principal: str, purpose: str, scopes: list[str], ttl_seconds: int) -> IssuedGrant:
1483+
"""Mint a standing delegation credential for *principal*.
1484+
1485+
Override to host ``vgi_rpc.Identity.v1``'s ``issue_grant``. Like
1486+
``resolve_token``, the method is absent until it is overridden rather
1487+
than hosted-and-refusing, so no worker grows a credential *issuer* by
1488+
upgrading a dependency.
1489+
1490+
OAuth cannot express durable delegation: it fuses the grant, the
1491+
credential and the session into one refresh token, so an IdP shortening
1492+
session lifetime shortens the grant. This mints the durable record —
1493+
created while the user is present, presented later by unattended
1494+
automation as an ordinary bearer.
1495+
1496+
**There is no subject on the wire.** ``issue_grant`` takes no subject
1497+
field; the framework passes the *caller's own* authenticated principal,
1498+
so cross-subject minting is closed by construction rather than by a
1499+
check that could be forgotten. That is also why this needs no allowlist
1500+
while ``introspect_token`` has one — it is not an oracle about anybody
1501+
else. The framework additionally refuses a caller whose authentication
1502+
is stale (``max_auth_age``, 15 minutes by default), because "minted
1503+
while the user is present" is the property that makes a grant
1504+
accountable to them.
1505+
1506+
``IssuedGrant.token`` is **opaque to the framework** — a sealed
1507+
envelope, a database row, or a credential brokered from the IdP are all
1508+
equally valid and equally invisible here. It is never parsed and never
1509+
logged. Note that a self-contained sealed token cannot be revoked
1510+
individually: with no server-side record there is nothing to delete,
1511+
and rotating the sealing key invalidates every grant at once. If
1512+
per-grant revocation matters, the token has to name something the
1513+
worker can look up and remove.
1514+
1515+
Args:
1516+
principal: The caller's authenticated principal, in the form this
1517+
worker derives itself. Supplied by the framework, never by the
1518+
caller.
1519+
purpose: Free-text reason recorded with the grant, for the audit
1520+
trail.
1521+
scopes: Scopes the grant is limited to. A worker that ignores this
1522+
is issuing a credential broader than the caller asked for.
1523+
ttl_seconds: Lifetime the caller requested. A worker may issue a
1524+
shorter one — and should say so in ``expires_at`` — but must
1525+
never issue a longer one.
1526+
1527+
Returns:
1528+
The minted ``IssuedGrant``. ``expires_at`` is a declaration rather
1529+
than an enforcement: the real lifetime lives inside the opaque
1530+
token, so a worker that states one has thought about one.
1531+
1532+
Raises:
1533+
GrantRefusedError: When this caller may not mint this grant —
1534+
an unsupported scope, a ttl beyond policy, a principal the
1535+
worker declines to delegate for.
1536+
1537+
"""
1538+
from vgi_rpc.rpc._token_identity import GrantRefusedError
1539+
1540+
raise GrantRefusedError("this worker does not mint grants")
1541+
1542+
@classmethod
1543+
def _grant_minter(cls) -> Callable[[str, str, list[str], int], IssuedGrant] | None:
1544+
"""Return this worker's grant minter, or ``None`` when it has none.
1545+
1546+
Identity comparison against the base implementation, for the same
1547+
reason ``_introspect_resolver`` uses one: the method must be absent
1548+
unless a worker actually wrote the minting, and a "supports grants"
1549+
flag can be set without one.
1550+
"""
1551+
if cls.mint_grant.__func__ is Worker.mint_grant.__func__: # type: ignore[attr-defined]
1552+
return None
1553+
return cls.mint_grant
1554+
14811555
@final
14821556
@classmethod
14831557
def main(cls) -> None:

0 commit comments

Comments
 (0)