Skip to content

auth: show API key permissions in status - #333

Merged
terencecho merged 3 commits into
mainfrom
codex/api-key-self-introspection-status
Sep 8, 2026
Merged

terencecho merged 3 commits into
mainfrom
codex/api-key-self-introspection-status

Conversation

@terencecho

@terencecho terencecho commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Adds API-key governance details to the existing heygen auth status command. When the active credential is an API key, the CLI calls GET /v3/api_keys/self and reports the key name, status, permission mode and scopes, lifecycle timestamps, and expiration alongside the local credential-source information. It continues to include account information when the key has account.read; a valid custom-scoped key without that permission still gets its own metadata instead of failing status. JSON output keeps the existing top-level data and credential envelope, while --human now renders both available sections instead of hiding credential metadata.

OAuth behavior is unchanged and does not call the API-key-only endpoint. This is intentionally a hand-written enhancement to auth status; the backend endpoint is excluded from generated CLI commands and remains excluded from MCP.

Backend dependency: heygen-com/experiment-framework#49894 provides the enriched API-key metadata endpoint. The CLI PR can merge independently because endpoint failures degrade to labeled partial status, but this change must not be cut or released until #49894 is merged and deployed to production: https://github.com/heygen-com/experiment-framework/pull/49894

Testing

  • go test ./...
  • golangci-lint run ./... (v2.11.4)
  • make build
  • Focused API-key, OAuth, missing-account.read, malformed-response, error-path, and human-output tests

@somanshreddy somanshreddy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review at a0fb000f — my own pass + an unbiased Codex pass, reconciled at source. The API-key JSON path is genuinely additive, the --human fix is correct, and the tests are strong — but I'm holding the approve on one regression I verified at source (F2), and flagging the merge-order dependency as a hard gate (F1). Codex caught F2; I confirmed it against origin/main and the client transport. tai independently flagged F1 and the scope-fixture nit.

What's solid (verified):

  • JSON envelope is unchanged. mergeStatusEnvelope produces {"data":…,"credential":…}, and JSONFormatter.Data ignores the dataField arg entirely — so flipping the final call from APIDataField to "" is a no-op for JSON. Existing consumers see strictly additive output.
  • The --human change is a fix, not a regression. unwrapPayload(v, "data") would strip to v["data"] and drop the credential block; "" renders the whole object, so --human now shows both sections (exactly as the description says).
  • OAuth is correctly gated away from /v3/api_keys/self (isAPIKey branch) — good, and F8-worthy.
  • Tests assert real behavior and fail on regression: success envelope, 500→hard-fail, 403-on-users/me→degrade (data absent, credential present), malformed-response rejection (invalid/missing/null), 401→ExitAuth with source-aware hint, non-auth 500→no hint mutation.

Blocking (recommend fixing before merge):

  1. [F2 — confirmed regression, Codex's catch] OAuth status now renders pre-refresh metadata. This PR hoists credMeta := credentialMetadata() to the top of RunE (it needs isAPIKey early). But on origin/main the order was the reverse — Execute(gen.UserMeGet) ran first, then credentialMetadata() — so the metadata was captured after any token refresh. The OAuth transport (client.go:202-205) proactively refreshes a near-expiry access token before the request and persists the new tokens; credentialMetadata() reads the credential from disk/env with no network. So for an OAuth user whose token is near-expiry or expired-but-refreshable — the exact case auth status exists to diagnose — the request refreshes successfully while the output reports stale expiry/scope, and for CredentialTypeOAuthExpired stamps expired: true right after a successful refresh. That contradicts the PR's "OAuth behavior is unchanged." Fix: for the OAuth path, re-resolve credentialMetadata() after the /v3/users/me request (or snapshot a post-refresh non-secret credential view), and add an expired/near-expiry OAuth test with a fake token endpoint asserting refreshed metadata renders. (API-key path is unaffected — it has no refresh.)

  2. [F1 — hard merge-order gate; tai + Codex + me] /v3/api_keys/self is an unguarded prerequisite. For an API key, the command calls /v3/api_keys/self and returns the error on any failure (TestAuthStatus_APIKeySelfError codifies a 500 → whole-command failure). If #333 merges before heygen-com/experiment-framework#49894, that endpoint 404s and heygen auth status hard-fails for every API-key caller — the isForbidden degrade only covers a 403 on /v3/users/me, not a missing self-endpoint. The body says "merge after #49894," but nothing enforces it. Minimum: treat this as a release gate — do not merge this ahead of #49894. Better (belt): degrade specifically on endpoint-unavailable (404) — fall through to the legacy /v3/users/me + local-credential envelope with a warning — so a premature or out-of-order merge can't brick the command, while still propagating 401/5xx.


Nonblocking / questions (none gate merge on their own):

  1. [F3, question] Is every 403 from /v3/users/me only "missing account.read"? isForbidden converts any 403 into exit 0 with the account section omitted — a suspension/plan/policy 403 would be silently swallowed as partial success. Consider gating the fallback on a stable insufficient-scope code rather than bare HTTP 403, and document the taxonomy the backend guarantees.
  2. [F4, nonblocking, trade-off] mergeAPIKeyMetadata blind-copies every data key into credMeta. This is a deliberate forward-compat choice (it absorbs new backend fields like key_id generically — a real virtue), but it also lets a future backend field named type/source/user overwrite the locally-authoritative value. If you want both, keep the opaque copy-through for unknown keys but skip the handful of locally-owned names. Keep scope strings opaque either way so *:* / *:read / videos:read pass through untouched.
  3. [F5, low] The missing-account.read success path emits {"credential":…} with no data key (result = json.RawMessage("{}")), a second successful envelope shape versus the stated stable data/credential contract. Merging from {"data":{}} would keep both top-level keys present.
  4. [F6, low] The --human test asserts the credential fields but not that the account section / email renders — so the "renders both sections" claim isn't fully pinned. Add a Data:/email assertion, and consider an OAuth --human case (the shared formatter call changed OAuth output too).
  5. [F7, nit — tai + Codex + me] Scope fixture "video.read" isn't the real grammar (videos:read / *:read / *:*). Cosmetic — the CLI echoes scope strings opaquely — but it's the value asserted in the human-output test, so it's the one that gets copied. Use realistic scopes.

Net: additive JSON, correct --human fix, strong tests, and clean OAuth gating. Two things to resolve: fix the OAuth pre-refresh metadata (F2), and treat the /v3/api_keys/self dependency as a hard merge-order gate (F1, ideally with a 404 fallback). Happy to stamp once F2 is addressed (or if you decide it's acceptable/out-of-scope, say so and I'll re-evaluate). Docs (README/SKILL) are accurate.

@terencecho
terencecho force-pushed the codex/api-key-self-introspection-status branch from a0fb000 to b5b754f Compare September 8, 2026 22:01
@terencecho

Copy link
Copy Markdown
Collaborator Author

Addressed the review in b5b754f:

  • F2: OAuth metadata is re-resolved after /v3/users/me, with an expired-token refresh regression test proving the refreshed scope/expiry is rendered.
  • F1: a missing /v3/api_keys/self endpoint (404) now falls back to legacy status with a structured warning; 401 and 5xx still fail. #49894 remains the deployment dependency for enriched API-key metadata.
  • F3: only the backend’s stable insufficient_api_key_scope 403 degrades the optional account section; other 403s propagate.
  • F4/F5: backend metadata cannot overwrite locally owned type, source, or user, and missing account:read keeps an empty data object in the success envelope.
  • F6/F7: human-output tests now pin both account and credential sections for API keys and OAuth, and fixtures use real scope grammar (videos:read, account:read).

Validated with go test ./..., golangci-lint v2.11.4 (0 issues), build, and CLI help smoke check.

… status

Addresses the review discussion on #333: `auth status` hard-failed on any
/v3/api_keys/self error except 404, so a transient 5xx or a misconfigured
gateway took down the whole command.

`auth status` is a diagnostic -- it is run precisely when something already
looks wrong. Failing to *enrich* the credential with permission metadata must
not take down the answer the CLI can always give from disk: which credential
is in use, and whether it authenticates.

Only 401 stays fatal, because "this credential was rejected" is the one
question the command must never answer optimistically -- degrading it would
render "credential present, from local file" for a revoked key.

Everything else degrades, each carrying its own reason, so the routine
pre-deploy state and a genuine anomaly never render identically:

  401       -> fail loudly (a credential verdict, not enrichment)
  404       -> "this server does not support /v3/api_keys/self yet"
  403       -> flagged as unexpected: the endpoint carries no
               x-heygen-required-scopes, so any valid key may introspect
               itself; a 403 points at a scope-exemption regression or an
               upstream proxy intercepting the request
  5xx/other -> reported with the status, noted as usually transient
  no HTTP   -> network/timeout, noted as usually transient

The reason is recorded inline as credential.permissions_unavailable as well as
on stderr, so a JSON consumer can tell "we could not read this key's
permissions" apart from "this key has none" -- blank scope rows are the wrong
answer to the question someone debugging a 403 is actually asking.

Side effect worth having: an out-of-order CLI release now omits a labeled
section instead of bricking `auth status` for every API-key caller, so the
release-ordering discipline stops being load-bearing.

TestAuthStatus_APIKeySelfError is replaced rather than amended: it pinned
hard-fail-on-500, which is exactly the behaviour being changed.

Signed-off-by: tai
@terencecho

Copy link
Copy Markdown
Collaborator Author

Pushed 8da972d — implements the degrade taxonomy settled in the Slack thread with @somanshreddy.

What changed. auth status previously hard-failed on any /v3/api_keys/self error except 404, so a transient 5xx or a misconfigured gateway took down the whole command. It's a diagnostic — it gets run precisely when something already looks wrong — so failing to enrich the credential shouldn't destroy the answer the CLI can always give from disk: which credential is in use, and whether it authenticates.

status behaviour
401 fails loudly — a credential verdict, not enrichment
404 calm "this server does not support /v3/api_keys/self yet"
403 degrades, but flagged unexpected (see below)
5xx / other degrades, reports the status, noted as usually transient
no HTTP response degrades, network/timeout, noted as usually transient

401 stays fatal because degrading it would render "credential present, from local file" for a revoked key — false reassurance about the single question this command exists to answer.

Why 403 is not folded into 404's wording. /v3/api_keys/self deliberately carries no x-heygen-required-scopes — any valid key may introspect itself, and heygen-com/experiment-framework@353d0412 registered that exemption in the required-scopes test. So a 403 there cannot be a legitimately under-scoped key; it means the exemption regressed or something upstream is intercepting. If it rendered as the routine pre-deploy state, nobody would go looking.

Reason is inline, not just on stderr. It lands as credential.permissions_unavailable in addition to the warning, so a JSON consumer — or anyone piping stdout — can tell "we could not read this key's permissions" apart from "this key has none". Blank scope rows are the wrong answer to the question someone debugging a 403 is actually asking.

One test deliberately replaced: TestAuthStatus_APIKeySelfError pinned hard-fail-on-500, which is the behaviour being changed. Replaced with TestAuthStatus_APIKeySelfServerErrorDegrades, plus new tests for the 401-stays-fatal and 403-reads-as-anomalous cases, and the 404 test now also pins its calm wording so the two can't converge.

Side effect worth having: an out-of-order release now omits a labeled section instead of bricking auth status for every API-key caller — so the release-ordering discipline stops being load-bearing. Worth keeping the ordering anyway.

Verified locally: go build ./..., go vet ./..., go test ./... (all packages pass), golangci-lint run ./... → 0 issues, gofmt clean on both changed files. (gofmt -l does flag four pre-existing files under internal/ that I didn't touch and left alone.)

Note for anyone reviewing against the earlier discussion: the force-push to b5b754f had already fixed the OAuth metadata-ordering regression, the bare-403 assumption, the locally-owned-key overwrite, and the video.read → videos:read fixture. This commit is only the failure-class taxonomy.

— tai

@somanshreddy somanshreddy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at 8da972d — my F2 hold is resolved and every finding is addressed at source. Approving.

Verified each fix at the new head (Terence's b5b754f + tai's 8da972d):

  • F2 (the OAuth pre-refresh regression I held on) — fixed. For the OAuth path, credentialMetadata() is now re-resolved after /v3/users/me (which may proactively refresh + persist the token), so the rendered expiry/scope reflect the refreshed credential. TestAuthStatus_OAuthRefreshReportsUpdatedMetadata is a genuine guard: it seeds an expired token, returns a fresh one from the token endpoint, and asserts Bearer fresh_access_token was sent, scope == "openid refreshed_scope", expired absent, and a future expires_at — it would fail on all three if the re-resolve were reverted.
  • F1 — degrade-by-class, exactly the agreed taxonomy. classifyAPIKeySelfFailure: 401 → fatal; 404 → calm "does not support … yet"; 403 → loud/anomalous (the endpoint is scope-exempt, so a 403 signals an exemption regression or upstream interception — not under-scoping); 5xx/network → transient. The reason lands inline as credential.permissions_unavailable, so a consumer distinguishes "couldn't read permissions" from "has none." Covered by dedicated tests for 401/403/404/5xx.
  • F3 — fixed. The /v3/users/me degrade now gates on Code == "insufficient_api_key_scope", not bare HTTP 403 (TestAuthStatus_APIKeyOtherForbiddenDoesNotDegrade pins it).
  • F4 — fixed. mergeAPIKeyMetadata skips a locallyOwned set {source, type, user}, so backend fields can't overwrite locally-authoritative values while the opaque copy-through still absorbs new fields like key_id.
  • F5 — fixed. The degrade path emits {"data":{}}, keeping both top-level keys.
  • F6 — fixed. The --human test now asserts the account section (Data:, Email, email) alongside the credential fields.
  • F7 — fixed. Fixture uses videos:read (+ key_id), asserted in the human-output test.

CI is 10/10 green at this head. One release-order note (not a code gate): per the thread, the CLI can merge anytime but should not be cut/released until EF#49894 is merged and deployed to prod — and with the 404-degradation now in place, an out-of-order cut is a labeled missing section, not a bricked command. LGTM.

@terencecho

Copy link
Copy Markdown
Collaborator Author

Follow-up review addressed: the implementation at 8da972d already satisfies F1–F7 with no unresolved inline threads and 10/10 green checks. I updated the PR description so #49894 is accurately recorded as a release/deployment gate rather than a merge-order gate. GitHub recorded the review as COMMENTED despite the “Approving” text, so I have re-requested formal approval.

@somanshreddy somanshreddy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving at 8da972d. Re-verified the full set at source: every finding from my review is resolved with discriminating tests, and CI is 10/10 green.

  • F2 (my hold — OAuth pre-refresh regression): fixed — the OAuth path re-resolves credential metadata after /v3/users/me, and TestAuthStatus_OAuthRefreshReportsUpdatedMetadata genuinely guards it (seeds an expired token, serves a fresh one, asserts refreshed scope/expiry + no expired).
  • Degrade taxonomy (F1): classifyAPIKeySelfFailure is exactly the agreed shape — 401 fatal / 404 calm / 403 loud-anomalous (scope-exempt) / 5xx-network transient, reason inline as credential.permissions_unavailable; one test per class.
  • F3/F4/F5/F6/F7: coded-403 gate (not bare 403), locally-owned-key overwrite guard, {"data":{}} envelope, human test asserts the account section, videos:read fixture — all fixed.

Reminder that's a release-checklist item, not a code gate: hold the CLI release cut until EF#49894 is merged + deployed to prod (the 404-degradation makes an out-of-order cut a labeled missing section rather than a broken command). Nice work.

@terencecho
terencecho merged commit b791cef into main Sep 8, 2026
10 checks passed
@terencecho
terencecho deleted the codex/api-key-self-introspection-status branch September 8, 2026 23:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants