You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by ak...@apache.org on 2026/10/06 01:54:07 UTC

(tooling-llmao) 20/23: requests: exercise a key approval, and set its allowance

This is an automated email from the ASF dual-hosted git repository.

andrewmusselman pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-llmao.git

commit 46e426963b1680dc50e1fd8c502b464d47155034
Author: Andrew Musselman <ak...@apache.org>
AuthorDate: Tue Oct 6 00:44:46 2026 +0000

    requests: exercise a key approval, and set its allowance
    
    Completes the flow the approval exists for. An admin approves the RIGHT to
    create a key, not the key itself; the requester creates it and sees the
    secret once. It never passes through the admin, so there is no moment where
    a credential sits in a message somewhere -- which is the problem this shape
    was chosen to avoid.
    
    my_key_approvals was a placeholder calling a backend method that does not
    exist, returning [] always, so the approved row never appeared. It now reads
    the request store and filters expired and consumed approvals here rather
    than in the template, so the page cannot offer a button that would fail.
    
    CHECKED, NOT TRUSTED
    
    create_approved_key takes a request id from a form post, so four things are
    verified: the approval belongs to the caller, it is approved, it has not been
    used, and it has not lapsed. A missing approval and someone else's give the
    same message, because whether a request exists is not something a stranger
    should be able to probe for.
    
    Every parameter comes from the approval. A form that could name its own tier
    would make the approval decorative.
    
    The approval is consumed AFTER the key exists. The other order burns it on a
    failed creation and leaves the person with nothing and no way to retry.
    
    AN ALLOWANCE FOR A KEY WITH NOTHING TO DRAW ON
    
    A project key draws on the project's share, a personal key on the person's. A
    projectless service key has neither, and unattended automation would consume
    a week's worth in an afternoon. create_key takes a token_cap, which the admin
    sets when approving.
    
    That needed decide() to tell adding from adjusting. Changing a value the
    requester named is an adjustment and needs a reason; ADDING one they never
    named -- the allowance, which they have no business setting for themselves --
    is completing the request. Requiring a justification would train everyone to
    type "ok" in the box, which costs the reason field its meaning on the
    decisions that do need one.
---
 llmao/litellm_client.py |  9 +++++++
 llmao/requests.py       | 15 ++++++++---
 llmao/seam.py           | 67 +++++++++++++++++++++++++++++++++++++++++++------
 pages.py                | 46 ++++++++++++++++++++++++++++++++-
 tests/test_requests.py  | 27 ++++++++++++++++++++
 5 files changed, 152 insertions(+), 12 deletions(-)

diff --git a/llmao/litellm_client.py b/llmao/litellm_client.py
index d0886e9..b7cf65a 100644
--- a/llmao/litellm_client.py
+++ b/llmao/litellm_client.py
@@ -245,6 +245,7 @@ class Backend(Protocol):
         user: str | None = None,
         metadata: dict | None = None,
         tier: str = TIER_PROJECT,
+        token_cap: int | None = None,
     ) -> CreatedKey: ...
     async def delete_key(self, token_id: str) -> None: ...
     async def usage(self, project: str | None) -> list[dict]: ...
@@ -851,6 +852,7 @@ class LiteLLMBackend:
         user: str | None = None,
         metadata: dict | None = None,
         tier: str = TIER_PROJECT,
+        token_cap: int | None = None,
     ) -> CreatedKey:
         project = (project or "").strip()
         if not project:
@@ -868,6 +870,13 @@ class LiteLLMBackend:
         # without limits can saturate the fleet, and LiteLLM's default is
         # unlimited.
         meta.setdefault("tier", tier)
+        if token_cap is not None:
+            # A per-key allowance, set by an admin when approving. Only a
+            # projectless service key really needs one: a project key draws
+            # on the project's share and a personal key on the person's, but
+            # a key belonging to neither has nothing to draw on, and
+            # unattended automation would consume a week in an afternoon.
+            meta["token_cap"] = int(token_cap)
         limits = resolve_entitlement(self._cfg, tier)
 
         payload: dict[str, Any] = {
diff --git a/llmao/requests.py b/llmao/requests.py
index d8bc2f1..91607a7 100644
--- a/llmao/requests.py
+++ b/llmao/requests.py
@@ -175,14 +175,23 @@ class Request:
             raise ValueError(f"cannot decide into {state}")
         # Adjusting or denying without saying why is how a requester learns
         # to pad the next ask.
-        changed = granted is not None and granted != self.wanted
-        if (state == STATE_DENIED or changed) and not (reason or "").strip():
+        #
+        # Only a CHANGED value counts as an adjustment. An admin adding a
+        # field the requester never named -- the allowance on a projectless
+        # service key, which they have no business setting for themselves --
+        # is completing the request, not altering it. Demanding a
+        # justification for that would train everyone to type "ok" in the
+        # box, which costs the reason field its meaning on the decisions that
+        # do need one.
+        merged = {**self.wanted, **(granted or {})}
+        adjusted = any(merged[k] != v for k, v in self.wanted.items() if k in merged)
+        if (state == STATE_DENIED or adjusted) and not (reason or "").strip():
             raise ValueError("denying or adjusting a request requires a reason")
         self.state = state
         self.decided_by = by
         self.decided_at = _now()
         self.decision_reason = (reason or "").strip()
-        self.granted = dict(granted if granted is not None else self.wanted)
+        self.granted = merged
 
     def consume(self) -> None:
         if not self.is_actionable():
diff --git a/llmao/seam.py b/llmao/seam.py
index 165563c..5f190d4 100644
--- a/llmao/seam.py
+++ b/llmao/seam.py
@@ -418,16 +418,67 @@ class Seam:
             return {}
 
     async def my_key_approvals(self, identity: Identity) -> list[dict]:
-        """Approved key requests this person can still act on.
+        """Approved key requests this person can still exercise.
 
-        Shown on My Keys as a row that is not yet a key. The approval records
-        what may be created; the secret is revealed once, at creation, to the
-        requester -- so it never passes through anyone else.
+        Expired and consumed approvals are filtered here rather than in the
+        template, so the page cannot offer a button that would fail.
         """
-        try:
-            return await self._backend.key_approvals(identity.uid)
-        except (AttributeError, BackendUnavailableError):
-            return []
+        return [
+            {
+                "id": r.id,
+                "purpose": r.granted.get("purpose") or r.wanted.get("purpose") or "",
+                "tier": r.granted.get("tier") or r.wanted.get("tier") or TIER_SERVICE,
+                "project": r.project or "",
+                "token_cap": int(r.granted.get("token_cap") or 0),
+                "expires_at": r.expires_at(),
+            }
+            for r in await self._backend.list_requests()
+            if r.requester == identity.uid and r.is_actionable()
+        ]
+
+    async def create_approved_key(self, identity: Identity, request_id: str) -> CreatedKey:
+        """Exercise an approval: create the key, consume the approval.
+
+        An admin approved the RIGHT to create a key with fixed parameters.
+        The requester creates it and sees the secret once, so it never passes
+        through the admin -- there is no moment where a credential sits in a
+        message somewhere.
+
+        Four things are checked rather than trusted to the UI, because this
+        takes a request id from a form post: the approval belongs to the
+        caller, it is approved, it has not been used, and it has not lapsed.
+
+        The key is created with the APPROVED parameters, never with anything
+        the form carries. A form that could name its own tier would make the
+        approval decorative.
+        """
+        req = await self._backend.find_request(request_id)
+        if req is None or req.requester != identity.uid:
+            # Same message either way: whether a request exists is not
+            # something a stranger should be able to probe for.
+            raise AuthzError("No such approval.")
+        if not req.is_actionable():
+            if req.consumed_at:
+                raise AuthzError("That approval has already been used.")
+            if req.is_expired():
+                raise AuthzError("That approval has expired. Please request again.")
+            raise AuthzError("That request has not been approved.")
+
+        granted = {**req.wanted, **req.granted}
+        created = await self._backend.create_key(
+            project=req.project or self._backend._TIER_STORE_TEAM,
+            purpose=granted.get("purpose") or "",
+            user=identity.uid,
+            tier=granted.get("tier") or TIER_SERVICE,
+            token_cap=int(granted.get("token_cap") or 0) or None,
+        )
+
+        # Consumed AFTER the key exists. The other order burns the approval
+        # on a failed creation and leaves the person with nothing and no way
+        # to retry.
+        req.consume()
+        await self._backend.save_request(req)
+        return created
 
     async def my_allowance(self, identity: Identity):
         """This committer's rolling free-tier allowance.
diff --git a/pages.py b/pages.py
index c5ba214..f876845 100644
--- a/pages.py
+++ b/pages.py
@@ -809,7 +809,22 @@ async def keys_list(result):
         result.projects = []
 
     try:
-        result.approvals = [edict(a) for a in await APP.seam.my_key_approvals(ident)]
+        result.approvals = [
+            edict(
+                {
+                    "id": a["id"],
+                    "purpose": a["purpose"],
+                    "tier": a["tier"],
+                    "project": a["project"],
+                    # What this key will be allowed to do, said plainly. The
+                    # person about to create it has one question -- is this
+                    # what I asked for -- and the parameters are the answer.
+                    "limits_h": (f"{_tokens_h(a['token_cap'])} tokens/week" if a["token_cap"] else "tier defaults"),
+                    "expires_h": (_when_h(a["expires_at"].date()) if a.get("expires_at") else ""),
+                }
+            )
+            for a in await APP.seam.my_key_approvals(ident)
+        ]
     except (BackendUnavailableError, AttributeError):
         result.approvals = []
 
@@ -1107,6 +1122,35 @@ async def do_create_key():
     return _see_other("/keys")
 
 
+@APP.post("/do-create-approved-key")
+@asfquart.auth.require
+async def do_create_approved_key():
+    """Exercise an approval.
+
+    The admin approved the RIGHT to create this key, not the key itself. It
+    is created here, by the person who asked, and the secret is revealed to
+    them once -- so it never sits in a message anywhere.
+
+    The form carries only the approval id. Every parameter comes from the
+    approval, because a form that could name its own tier would make the
+    approval decorative.
+    """
+    form = await quart.request.form
+    try:
+        ident = await current_identity(APP.cfg)
+        created = await APP.seam.create_approved_key(ident, (form.get("approval_id") or "").strip())
+    except (AuthzError, BackendUnavailableError, ValueError) as e:
+        await flash_danger(str(e))
+        return _see_other("/keys")
+    await _flash_key_created(
+        created,
+        kind_label="Approved",
+        keys_back="/keys",
+        keys_create_another="/keys",
+    )
+    return _see_other("/keys")
+
+
 @APP.get("/keys/other/new")
 @asfquart.auth.require
 @APP.use_template(TEMPLATES / "key_create_other.ezt")
diff --git a/tests/test_requests.py b/tests/test_requests.py
index 532b5bd..a07d591 100644
--- a/tests/test_requests.py
+++ b/tests/test_requests.py
@@ -268,3 +268,30 @@ def test_prune_caps_decided_history():
 def test_prune_never_drops_a_pending_request():
     reqs = [_capacity() for _ in range(80)]
     assert len(prune(reqs, keep_decided=5)) == 80
+
+
+def test_setting_an_allowance_on_a_key_is_not_an_adjustment():
+    """Adding a field the requester never named is completing the request.
+
+    A projectless service key has nothing to draw on, so an admin sets its
+    allowance at approval -- the requester has no business naming it. Making
+    that need a justification would train everyone to type "ok" in the box,
+    which costs the reason field its meaning on decisions that do need one.
+    """
+    r = _key()
+    r.decide(state=STATE_APPROVED, by="admin", granted={"token_cap": 2_000_000})
+    assert r.state == STATE_APPROVED
+    assert r.granted["token_cap"] == 2_000_000
+    assert r.granted["purpose"] == "scrutineer-ci"
+
+
+def test_changing_a_value_the_requester_named_is_an_adjustment():
+    r = _key()
+    with pytest.raises(ValueError):
+        r.decide(state=STATE_APPROVED, by="admin", granted={"tier": "free_tier"})
+
+
+def test_granted_carries_everything_asked_for_plus_what_was_added():
+    r = _key()
+    r.decide(state=STATE_APPROVED, by="admin", granted={"token_cap": 500_000})
+    assert set(r.granted) == {"purpose", "tier", "token_cap"}


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org