Files
python-sdk/pkg/hanzo-iam/tests/test_endpoints.py
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

94 lines
3.3 KiB
Python

"""Every IAM endpoint must live under the one /v1/iam prefix.
These fail against the shipped code, which composed OAuth URLs from the server
root: `/oauth/token`, `/oauth/authorize`, `/oauth/introspect`,
`/.well-known/jwks`. hanzo.id serves its sign-in SPA on every unmatched path,
so all four answered **200 text/html**. Nothing 404'd, nothing raised for
status, and the failure only surfaced deep inside `.json()`.
"""
from __future__ import annotations
import pytest
from hanzo_iam import models
from hanzo_iam.config import IAMConfig
SERVER = "https://hanzo.id"
PATHS = [
models.OIDC_AUTHORIZE_PATH,
models.OIDC_TOKEN_PATH,
models.OIDC_USERINFO_PATH,
models.OIDC_INTROSPECT_PATH,
models.OIDC_REVOKE_PATH,
models.OIDC_DEVICE_PATH,
models.OIDC_JWKS_PATH,
]
@pytest.mark.parametrize("path", PATHS)
def test_every_endpoint_is_under_the_prefix(path):
assert path.startswith(models.IAM_ROUTE_PREFIX + "/")
def test_paths_are_composed_from_the_prefix_not_retyped():
"""One seam: changing IAM_ROUTE_PREFIX must move every endpoint."""
for path in PATHS:
assert path.count("/v1/iam") == 1
def test_discovery_is_the_one_root_relative_path():
"""RFC 8414 pins /.well-known/openid-configuration at the origin root; it
is the only IAM path that is NOT prefixed, and it does resolve live."""
assert models.OIDC_DISCOVERY_PATH == "/.well-known/openid-configuration"
@pytest.mark.parametrize(
"attr,expected",
[
("token_endpoint", "/v1/iam/oauth/token"),
("authorize_endpoint", "/v1/iam/oauth/authorize"),
("userinfo_endpoint", "/v1/iam/oauth/userinfo"),
("device_endpoint", "/v1/iam/oauth/device"),
("jwks_uri", "/v1/iam/.well-known/jwks"),
],
)
def test_config_endpoints(attr, expected):
config = IAMConfig(server_url=SERVER, client_id="hanzo-app")
assert getattr(config, attr) == SERVER + expected
def test_config_tolerates_a_trailing_slash():
"""A doubled slash is a different path, and hanzo.id would answer it with
the SPA rather than a 404."""
config = IAMConfig(server_url=SERVER + "/", client_id="hanzo-app")
assert config.token_endpoint == f"{SERVER}/v1/iam/oauth/token"
assert "//v1" not in config.token_endpoint
def test_jwks_uri_is_not_the_unprefixed_well_known_path():
"""The exact trap: https://hanzo.id/.well-known/jwks returns 200 text/html,
so a JWKS client pointed there fetches a web page and verifies nothing."""
config = IAMConfig(server_url=SERVER, client_id="hanzo-app")
assert config.jwks_uri != f"{SERVER}/.well-known/jwks"
assert config.jwks_uri != f"{SERVER}/.well-known/jwks.json"
def test_no_module_still_spells_a_bare_oauth_path():
"""Guards against a regression creeping back into any client module."""
import pathlib
import hanzo_iam
root = pathlib.Path(hanzo_iam.__file__).parent
offenders = []
for py in root.glob("*.py"):
for lineno, line in enumerate(py.read_text().splitlines(), 1):
if line.lstrip().startswith("#"):
continue
for bad in ('"/oauth/', "'/oauth/", '"/.well-known/jwks', "'/.well-known/jwks"):
if bad in line:
offenders.append(f"{py.name}:{lineno}: {line.strip()}")
assert not offenders, "unprefixed IAM paths:\n" + "\n".join(offenders)