Files
zeekayandHanzo Dev d08a7d5599 auth: verify tokens instead of asserting they exist
is_authenticated() was `load_token() is not None` — a string-presence check
that returned True for the literal "fake.not.a.real.jwt". Every permission
decision downstream of it was therefore a lie. This makes the client side of
Hanzo auth actually work, end to end. Builds on the /v1/iam prefix already on
main; the endpoint paths were necessary but not sufficient.

hanzo_iam.tokens — the ONE credential judge. Verifies the signature against
the issuer's published JWKS plus exp/iss/aud, and fails CLOSED: an unreachable
JWKS is not a pass, because a client that cannot check a signature does not
know the token is good. Reason codes distinguish "expired" from "offline".
`alg: none` is absent from the accepted list by construction. An opaque API
key cannot be judged offline, so it is confirmed against userinfo rather than
assumed valid for being a non-empty string.

hanzo_iam.oauth — a real login: authorization code + PKCE (S256) over a
loopback redirect, with a deadline. Not the device grant, which would be the
better CLI UX: iam implements RFC 8628 fully and advertises it, but no PUBLIC
client is registered, so POST /v1/iam/oauth/device answers 401 invalid_client
for hanzo-cli, hanzo-app, hanzo-cloud and hanzo-console alike. Registering one
public app is the whole server-side fix; shipping a device path that always
401s would be a lie in code. The password grant is out for the same reason
(401 invalid_client without a secret), so `--no-browser` now prints the URL
instead of prompting for a password it cannot use.

The loopback listener binds a REGISTERED redirect_uri. iam compares
redirect_uri by exact string and does not apply RFC 8252 §7.3 port-agnostic
loopback matching, so a CLI cannot pick a free ephemeral port — the previous
code bound 8399 (cli) and 8398 (bot), neither registered, and /authorize
refused both with a bare 400 before the user saw a login page. It listens on
127.0.0.1 and ::1 because the registered URIs spell "localhost", and sets
SO_REUSEADDR because the previous callback sits in TIME_WAIT for ~60s and
would otherwise EADDRINUSE a second login on a port nothing is using.

hanzo_iam.store — keyring first, else an atomic 0600 file. The old path did
write_text() then chmod(0600), so with umask 022 a bearer token sat at 0644
between the two calls. Now it is created private and renamed into place. The
PaaS session cache goes through the same writer.

Two definitions of IAMConfig existed; models.py's was the one every client
imported, so the endpoint properties main had just fixed on config.py's were
dead code. One now, in config.py, plus jwks_uri and device_endpoint.

The bot and CLI login copies are gone; both call the one flow. whoami and
`hanzo bot login` no longer print claims from an unverified decode — that
rendered an attacker-chosen identity as fact.

The Team tool refuses instead of pretending: api.hanzo.ai/team is the
marketing SPA (200 text/html), so raise_for_status() passed and .json() blew
up. There is no Team API; HANZO_TEAM_URL stays as the seam for when one ships.

PaaS token exchange reports its real diagnosis: POST /v1/auth/login 404s while
/v1/org and /v1/user 401, so the API is up and gated but the exchange route is
not deployed at that edge. No client-side workaround exists, so it says so.

Tests fail against the old behaviour, which is the point: 5 session tests fail
against the shipped is_authenticated and 4 store tests fail against
write-then-chmod. 134 pass alongside main's KMS suite.

Co-authored-by: Hanzo Dev <[email protected]>
2026-07-27 18:55:24 -07:00

113 lines
3.8 KiB
Python

"""Configuration for Hanzo IAM client."""
from __future__ import annotations
import os
from typing import ClassVar
from pydantic import BaseModel, ConfigDict, Field
from hanzo_iam.models import (
OIDC_AUTHORIZE_PATH,
OIDC_DEVICE_PATH,
OIDC_JWKS_PATH,
OIDC_TOKEN_PATH,
OIDC_USERINFO_PATH,
)
class IAMConfig(BaseModel):
"""Configuration for Hanzo IAM client.
Can be initialized directly or from environment variables via from_env().
"""
model_config = ConfigDict(frozen=True)
# Canonical environment variable prefix. There is exactly one prefix —
# no upstream-brand aliases, no per-org fallbacks. See
# ~/work/hanzo/iam/CLAUDE.md "Configuration" section.
ENV_PREFIX: ClassVar[str] = "IAM_"
server_url: str = Field(description="IAM server URL (e.g., https://hanzo.id)")
client_id: str = Field(description="OAuth2 client ID")
client_secret: str = Field(default="", description="OAuth2 client secret")
organization: str = Field(default="hanzo", description="IAM organization name")
application: str = Field(default="app", description="IAM application name")
certificate: str = Field(
default="", description="JWT verification certificate (PEM)"
)
@classmethod
def from_env(cls, prefix: str | None = None) -> IAMConfig:
"""Create config from environment variables.
The canonical prefix is ``IAM_`` (no upstream-brand aliases, no
per-org variants). The ``prefix`` argument exists for advanced
callers that scope multiple IAM clients in a single process; new
code should leave it at the default.
Environment variables (with the default prefix):
IAM_ENDPOINT - IAM server URL (preferred)
IAM_CLIENT_ID - OAuth2 client ID
IAM_CLIENT_SECRET - OAuth2 client secret
IAM_ORG - Organization name
IAM_APP - Application name
IAM_CERT - JWT verification certificate (PEM content or file path)
"""
p = prefix or cls.ENV_PREFIX
server_url = os.environ.get(f"{p}ENDPOINT", "")
client_id = os.environ.get(f"{p}CLIENT_ID", "")
client_secret = os.environ.get(f"{p}CLIENT_SECRET", "")
organization = os.environ.get(f"{p}ORG", "hanzo")
application = os.environ.get(f"{p}APP", "app")
# Certificate can be content or file path
cert_val = os.environ.get(f"{p}CERT", "")
if cert_val and not cert_val.startswith("-----BEGIN"):
# Treat as file path
cert_path = os.path.expanduser(cert_val)
if os.path.isfile(cert_path):
with open(cert_path) as f:
cert_val = f.read()
return cls(
server_url=server_url,
client_id=client_id,
client_secret=client_secret,
organization=organization,
application=application,
certificate=cert_val,
)
@property
def base_url(self) -> str:
"""Server URL with any trailing slash removed."""
return self.server_url.rstrip("/")
@property
def token_endpoint(self) -> str:
"""OAuth2 token endpoint URL."""
return f"{self.base_url}{OIDC_TOKEN_PATH}"
@property
def authorize_endpoint(self) -> str:
"""OAuth2 authorization endpoint URL."""
return f"{self.base_url}{OIDC_AUTHORIZE_PATH}"
@property
def device_endpoint(self) -> str:
"""RFC 8628 device authorization endpoint URL."""
return f"{self.base_url}{OIDC_DEVICE_PATH}"
@property
def jwks_uri(self) -> str:
"""JWKS URL used to verify tokens this issuer signed."""
return f"{self.base_url}{OIDC_JWKS_PATH}"
@property
def userinfo_endpoint(self) -> str:
"""OIDC UserInfo endpoint URL (HIP-0111 canonical path)."""
return f"{self.base_url}{OIDC_USERINFO_PATH}"