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

148 lines
4.4 KiB
Python

"""The ONE token store for Hanzo credentials.
Order of preference:
1. The OS keyring (Keychain / libsecret / Windows Credential Locker) when the
`keyring` package is installed AND a real backend is available.
2. ``~/.hanzo/auth/token.json``, created with mode 0600 ATOMICALLY.
"Atomically" is the whole point of the fallback. The code this replaces did
``write_text()`` then ``chmod(0600)``: between those two calls the file exists
at ``0666 & ~umask`` — commonly 0644 — holding a bearer token. Any process on
the box could read it in that window. Here the bytes are written to a
private temp file that is created 0600 by `mkstemp` and never named
``token.json`` until it is already correct, then `os.replace` swaps it in.
"""
from __future__ import annotations
import json
import os
import stat
import tempfile
from pathlib import Path
from typing import Any
TOKEN_DIR = Path.home() / ".hanzo" / "auth"
TOKEN_FILE = TOKEN_DIR / "token.json"
# Keyring coordinates. <org>-<app> naming, matching IAM.
KEYRING_SERVICE = "hanzo-cli"
KEYRING_USERNAME = "default"
FILE_MODE = 0o600
DIR_MODE = 0o700
def _keyring() -> Any | None:
"""Return a usable keyring module, or None.
Installed-but-headless is the common case on a server: `keyring` imports
fine and then raises on first use. Probing the backend here means the file
fallback is chosen deliberately rather than discovered mid-write.
"""
try:
import keyring
from keyring.backends.fail import Keyring as FailKeyring
except Exception:
return None
try:
if isinstance(keyring.get_keyring(), FailKeyring):
return None
except Exception:
return None
return keyring
def save(data: dict[str, Any]) -> str:
"""Persist token data. Returns the backend used: "keyring" or "file"."""
blob = json.dumps(data, indent=2, sort_keys=True)
kr = _keyring()
if kr is not None:
try:
kr.set_password(KEYRING_SERVICE, KEYRING_USERNAME, blob)
# A stale plaintext copy is still a plaintext copy.
_unlink_file()
return "keyring"
except Exception:
pass # fall through to the file store
_write_private(TOKEN_FILE, blob)
return "file"
def load() -> dict[str, Any] | None:
"""Read stored token data, or None when nothing is stored."""
kr = _keyring()
if kr is not None:
try:
blob = kr.get_password(KEYRING_SERVICE, KEYRING_USERNAME)
if blob:
return json.loads(blob)
except Exception:
pass
if not TOKEN_FILE.exists():
return None
try:
return json.loads(TOKEN_FILE.read_text())
except (json.JSONDecodeError, OSError):
return None
def clear() -> None:
"""Remove stored credentials from every backend."""
kr = _keyring()
if kr is not None:
try:
kr.delete_password(KEYRING_SERVICE, KEYRING_USERNAME)
except Exception:
pass
_unlink_file()
def backend() -> str:
"""Name the backend a save would use right now — for `auth status`."""
return "keyring" if _keyring() is not None else "file"
def file_mode() -> int | None:
"""Permission bits of the token file, or None when it does not exist."""
try:
return stat.S_IMODE(TOKEN_FILE.stat().st_mode)
except FileNotFoundError:
return None
def _unlink_file() -> None:
try:
TOKEN_FILE.unlink()
except FileNotFoundError:
pass
def _write_private(path: Path, text: str) -> None:
"""Write `text` to `path` so it is NEVER world- or group-readable.
mkstemp creates at 0600 before any byte is written, and os.replace is
atomic within a filesystem — a reader either sees the old file or the new
one, never a partial or over-permissive one.
"""
path.parent.mkdir(parents=True, exist_ok=True, mode=DIR_MODE)
# mkdir's mode is ignored when the directory already exists, so an
# inherited-permissive ~/.hanzo/auth is tightened here too.
os.chmod(path.parent, DIR_MODE)
fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=".token-", suffix=".tmp")
try:
os.fchmod(fd, FILE_MODE) # explicit: do not inherit mkstemp's guarantee by luck
with os.fdopen(fd, "w") as f:
f.write(text)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
except BaseException:
os.unlink(tmp)
raise