M1: Implement secure Z.ai quota acquisition #11
No reviewers
Labels
No labels
accessibility
bug
documentation
duplicate
enhancement
good first issue
help wanted
invalid
P1
P2
P3
question
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Creatidy/scarcity-router!11
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "m1-zai-secure-acquisition"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Closes #10
What this adds
The production acquisition boundary for the Z.ai Coding Plan collector: the
existing Kilo credential -> strict credential discovery -> fixed HTTPS quota
GET -> bounded strict JSON decoding -> existing
parse_zai_quota_response(...)->
CapacitySnapshot. The pure parser inscarcity_router/providers/zai.pyis untouched; acquisition adds zero quota semantics of its own.
Acquisition API
The explicit
auth_fileexists for deterministic tests and controlled localconfiguration. The credential path and value never enter the snapshot.
Credential-source contract
zai-coding-plankey is selected. Thekeyvalue is inspected only afterthe target entry is established; unrelated provider entries are never read
as candidates and never appear in output.
type == "api"and a non-empty stringkey.No alternative fields (
token,value,apiKey,api_key,tokenValue) and no token-like types are accepted.Bearerprefix, no strip, no reformat.MAX_AUTH_FILE_BYTES); oversized, unreadable,missing, invalid-UTF-8 and invalid-JSON files all fail safely to
auth_required. The filesystem path is never included in diagnostics.Credential header safety (security-review hardening)
A credential is accepted only if it can be represented byte-for-value as
an HTTP header value: a conservative printable-ASCII allowlist (space
through tilde). CR, LF, CRLF, NUL, every other C0 control, DEL, C1 controls
and values the stdlib latin-1 header encoding cannot represent are rejected
during discovery - before any request object or transport exists - so no
malformed credential can ever be formatted into a transport exception
(
http.clientraisesValueError("Illegal header value %r")/UnicodeEncodeErrorcontaining the value). Accepted values (includingleading/trailing spaces) are still transmitted exactly as stored; nothing is
stripped, normalized or escaped. Unsafe credentials normalize to
auth_requiredwith zero transport calls.Duplicate-key ambiguity (security-review hardening)
The auth document is parsed with a duplicate-rejecting JSON
object_pairs_hook: any duplicate object key anywhere in the documentfails closed to
auth_requiredwith zero requests - a repeated top-levelzai-coding-planentry, repeatedtype/keyfields inside the targetentry, and (documented conservative choice) duplicates in unrelated entries.
Credential selection never trusts last-key-wins parser overwrite behavior,
and neither candidate value can reach the transport or any output.
Fixed endpoint and destination validation
GET https://api.z.ai/api/monitor/usage/quota/limitis a module constant;the public API exposes no endpoint override.
is_approved_destination(small, independently testable) rejects atminimum: non-HTTPS, wrong host, host-suffix tricks
(
api.z.ai.example.com), userinfo, explicit unexpected ports, query andfragments, wrong paths; malformed URLs fail closed.
constant itself ever failed policy, a
RuntimeErroris raised before anyheader exists (programmer error, not disguised telemetry) - asserted by
test that Authorization is never attached in that case.
Redirect policy
HTTPRedirectHandler.redirect_requestis overridden to decline every 3xx(public
NoRedirecthandler;open_responsebuilds the opener with it).Coverage of the real production boundary, network-free:
NoRedirect.redirect_requestreturnsNonefor 301/302/303/307/308 andconstructs no replacement request;
open_responseobtains its opener viaurllib.request.build_openerwithexactly the
NoRedirecthandler and passes the original authenticatedrequest object exactly once - the test fails if production ever switches
to
urlopen(...)or a default redirect-following opener.Mapping tests additionally assert per 3xx code: redirect not followed, zero
second requests, credential never forwarded, snapshot contains no raw
Location.Authorization behavior and bounds
Authorization: <stored credential exactly>andAccept: application/json; no other secret-bearing header.TIMEOUT_SECONDS = 15.MAX_BODY_BYTES); oversized bodies areneither parsed nor persisted. Auth-file read bounded at 1 MiB.
Failure/status mapping (v1 capacity contract)
auth_requiredauth_requiredauth_requiredauth_requiredschema_changedschema_changedunavailablesource_unavailableunknowntelemetry_unknownNo raw transport exception escapes; invalid
retrieved_atstill failsthrough the typed capacity-contract validation instead of being misreported
as telemetry. Programmer errors (endpoint-policy violation of the fixed
constant) raise instead of becoming telemetry.
Parser-integration boundary
For every valid fixture payload,
collect_zai_capacity(...)normalizesidentically (dataclass equality) to a direct
parse_zai_quota_response(decoded_payload, retrieved_at=...)call - assertedfor the known-windows, unknown-window and degraded-values fixtures. All
window/percentage/reset semantics remain in the pure parser.
Secret non-leak guarantees
A sweep over 27 scenarios (success, every transport failure class, every
malformed-credential class, and the duplicate-key classes) asserts every
synthetic secret is absent from
snapshot.to_dict()JSON,repr(snapshot),diagnostic fields, and captured stdout/stderr; production code emits no
stdout/stderr at all and no raw provider response is persisted. The safety
invariant is enforced by rejection before the transport layer: unsafe or
ambiguous credentials can never reach code that would build an exception
containing them; there is no reliance on catching-and-redacting.
Tests
tests/test_zai_acquisition.py: 69 tests, all network-free - mockedtransport seam (
open_response), fake openers/responses, temporary authfiles, conspicuous synthetic secrets only (
TEST_ONLY_*). Thereconnaissance helper
tools/m1_zai_quota_recon.pyremains untouchedevidence tooling and is not imported.
No test performs a live request, reads the real Kilo credential, or
requires the owner's secret.
Results
suppressions, no baselines)
make check: exit 0Explicit non-scope
No CLI
status, provider aggregation, freshness caching, history, OpenAI/Codex collector, Codex app-server, Ollama inspection, model selection,
capability ratings, scarcity calculations, REST, MCP, dashboard, model
execution, retry/backoff, endpoint configuration framework, credential
migration, OS keyring, new runtime dependencies (stdlib
urllib/jsononly), packaging metadata (U-008 untouched), and no live
credential-dependent integration test.
kilo referenced this pull request2026-10-04 23:43:29 +00:00
kilo referenced this pull request2026-10-15 18:49:32 +00:00
kilo referenced this pull request2026-10-18 17:29:03 +00:00