Sync shared snapshot from f5a20b7
Docker / Docker Build & Push (push) Successful in 4m34s

This commit is contained in:
Gabriel20xx committed 2026-09-02 10:38:52 +02:00
1 parent 51e0a4217b
commit ab3a6a19fb
5 files changed
+1094 -35

No files matched your search

+286 -4
View File
@@ -3,10 +3,24 @@
// directly against its own private database.
//
// A service that switches to AuthGuard trades "its own local user table"
// for "one HTTP call per request to AuthGuard's /api/session/validate",
// gaining a single shared identity across every project that does the
// same. Mirrors shared/backend/authclient (the Go equivalent) - keep the
// two in sync if either changes shape.
// for "HTTP calls to AuthGuard's API", gaining a single shared identity
// across every project that does the same. Mirrors shared/backend/authclient
// (the Go equivalent) and shared/packages/python-backend/src/shared_backend/authclient.py
// (the Python equivalent) - keep all three in sync if any changes shape.
//
// Two kinds of consumer, two parts of this module:
//
// - A service that only needs to gate requests behind "is this a valid
// AuthGuard session" uses `AuthClient.validate` / `tokenFromRequest` /
// `middleware()`, calling only GET /api/session/validate. This is the
// original, minimal surface of this module.
// - A service that runs its own login/register/admin-user-management
// screens proxied to AuthGuard (mirroring shared/backend/authclient's full
// method set - see e.g. Original/GameStream/backend/cmd/gamestreamd/auth.go
// for the reference Go implementation of this pattern) uses the additional
// methods below: register, login, logout, me, totpEnable/Verify/Disable,
// requestPasswordReset/confirmPasswordReset, list/create/update/delete
// ManagedUser(s), setupStatus.
const DEFAULT_COOKIE_NAME = 'auth_session';
const DEFAULT_TIMEOUT_MS = 5000;
@@ -18,6 +32,28 @@ export class InvalidSessionError extends Error {
}
}
// APIError is raised when AuthGuard responds with a non-2xx status to one of
// the register/login/.../setupStatus methods below (not raised by
// validate(), which uses InvalidSessionError for its one specific non-2xx
// case). Mirrors Go's *authclient.APIError / Python's APIError - carries the
// status code and (when AuthGuard's JSON body decoded successfully) its
// {"error": "..."} message, so a caller can map it back onto its own
// service's response shape/status code rather than exposing AuthGuard's
// wording verbatim.
export class APIError extends Error {
constructor(statusCode, message, { totpRequired = false } = {}) {
super(`authclient: authguard responded ${statusCode}: ${message}`);
this.name = 'APIError';
this.statusCode = statusCode;
this.detailMessage = message;
// Mirrors AuthGuard's {"totp_required": true} flag on a 401 from
// POST /api/login that means "credentials were correct, but this
// account has two-factor auth enabled and no (or an incorrect) code
// was supplied" - distinct from a plain invalid-credentials 401.
this.totpRequired = totpRequired;
}
}
export class AuthClient {
/**
* @param {string} baseUrl - AuthGuard's base URL (e.g. from AUTHGUARD_URL), no trailing slash required.
@@ -30,6 +66,8 @@ export class AuthClient {
this.fetchImpl = options.fetchImpl ?? fetch;
}
// --- session validation (the original, minimal surface) -----------------
/**
* Calls AuthGuard's GET /api/session/validate with token as a Bearer
* credential and returns the resolved user. Throws InvalidSessionError
@@ -114,6 +152,250 @@ export class AuthClient {
}
return '';
}
// --- shared request/response plumbing for everything below --------------
/**
* Runs one JSON request/response round trip against AuthGuard. Returns
* the decoded JSON body (an empty object for a 2xx response with no
* body) and the raw Set-Cookie header value(s) the response carried.
* Throws APIError for a non-2xx response, a plain Error for a
* transport/decoding failure - mirrors Go's Client.call / Python's
* AuthClient._call exactly.
* @returns {Promise<{payload: any, cookies: string[]}>}
*/
async _call(method, path, { token = '', body } = {}) {
if (!this.baseUrl) {
throw new Error('authclient: client has no base URL');
}
const headers = {};
if (body !== undefined) headers['Content-Type'] = 'application/json';
if (token) headers.Authorization = `Bearer ${token}`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
let response;
try {
response = await this.fetchImpl(`${this.baseUrl}${path}`, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
signal: controller.signal,
});
} catch (err) {
throw new Error(`authclient: call AuthGuard: ${err.message}`, { cause: err });
} finally {
clearTimeout(timer);
}
// fetch's Headers.getSetCookie() (Node >= 18.14 / undici) returns every
// Set-Cookie header value separately, unlike .get('set-cookie') which
// would fold them into one comma-joined string and break parsing.
const cookies = typeof response.headers.getSetCookie === 'function'
? response.headers.getSetCookie()
: [];
let payload = {};
const text = await response.text();
if (text) {
try {
payload = JSON.parse(text);
} catch (err) {
if (!response.ok) {
throw new APIError(response.status, `request failed (${response.status})`);
}
throw new Error(`authclient: decode AuthGuard response: ${err.message}`, { cause: err });
}
}
if (!response.ok) {
const message = payload?.error || `request failed (${response.status})`;
throw new APIError(response.status, message, { totpRequired: Boolean(payload?.totp_required) });
}
return { payload, cookies };
}
static _publicUser(payload) {
const user = payload?.user ?? {};
return {
id: user.id,
username: user.username ?? '',
email: user.email ?? '',
role: user.role ?? '',
totpEnabled: Boolean(user.totp_enabled),
};
}
static _managedUser(user) {
return {
id: user?.id,
username: user?.username ?? '',
email: user?.email ?? '',
role: user?.role ?? '',
createdAt: user?.created_at ?? '',
};
}
// --- setup / registration -------------------------------------------------
/**
* Calls GET /api/setup-status, an unauthenticated endpoint that reports
* whether AuthGuard has any account at all. Accounts are centralized in
* AuthGuard, so a caller with its own "first launch, create the initial
* admin" flow should consult this first: when it returns false, some
* account already exists (possibly created by a different project, or
* directly against AuthGuard), and the caller should show its ordinary
* login screen instead of its own account-creation form.
* @returns {Promise<boolean>}
*/
async setupStatus() {
const { payload } = await this._call('GET', '/api/setup-status');
return Boolean(payload.setup_required);
}
/**
* Calls POST /api/register, creating a new AuthGuard account and
* starting a session for it.
* @returns {Promise<{user: object, cookies: string[]}>}
*/
async register(username, email, password) {
const { payload, cookies } = await this._call('POST', '/api/register', {
body: { username, email, password },
});
return { user: AuthClient._publicUser(payload), cookies };
}
/**
* Calls POST /api/login. totpToken may be empty; AuthGuard raises an
* APIError with totpRequired set when the account has two-factor auth
* enabled and no valid code was supplied.
* @returns {Promise<{user: object, cookies: string[]}>}
*/
async login(usernameOrEmail, password, totpToken = '') {
const body = { username_or_email: usernameOrEmail, password };
if (totpToken) body.totp_token = totpToken;
const { payload, cookies } = await this._call('POST', '/api/login', { body });
return { user: AuthClient._publicUser(payload), cookies };
}
/**
* Calls POST /api/logout, deleting the session identified by token
* server-side. Returns the (cookie-clearing) Set-Cookie header value(s)
* AuthGuard's response carried.
* @returns {Promise<string[]>}
*/
async logout(token) {
const { cookies } = await this._call('POST', '/api/logout', { token });
return cookies;
}
/** Calls GET /api/me, resolving token to its account. */
async me(token) {
const { payload } = await this._call('GET', '/api/me', { token });
return AuthClient._publicUser(payload);
}
// --- TOTP -----------------------------------------------------------------
/**
* Calls POST /api/totp/enable, provisioning (or re-provisioning) a
* pending TOTP secret for token's account. The secret is not active
* until totpVerify confirms a generated code.
* @returns {Promise<{secret: string, otpauthUrl: string, enabled: boolean}>}
*/
async totpEnable(token) {
const { payload } = await this._call('POST', '/api/totp/enable', { token });
return {
secret: payload.secret ?? '',
otpauthUrl: payload.otpauth_url ?? '',
enabled: Boolean(payload.enabled),
};
}
/**
* Calls POST /api/totp/verify, confirming code against the pending
* secret totpEnable provisioned and activating two-factor auth.
*/
async totpVerify(token, code) {
await this._call('POST', '/api/totp/verify', { token, body: { token: code } });
}
/**
* Calls POST /api/totp/disable, turning two-factor auth off for token's
* account. AuthGuard requires code to be one last valid TOTP code as
* proof of possession.
*/
async totpDisable(token, code) {
await this._call('POST', '/api/totp/disable', { token, body: { token: code } });
}
// --- password reset ("break glass", console-only - see AuthGuard's README) --
/**
* Calls POST /api/password-reset/request. AuthGuard prints a one-time
* code to its own process console; only an operator with access to that
* console can relay it onward. Called with no usernameOrEmail, the
* target is AuthGuard's superadmin account - AuthGuard's own web UI is
* the intended place to drive this, not an individual project (see
* AuthGuard's README's "Web UI" section).
*/
async requestPasswordReset(usernameOrEmail = '') {
const body = usernameOrEmail ? { username_or_email: usernameOrEmail } : {};
await this._call('POST', '/api/password-reset/request', { body });
}
/**
* Calls POST /api/password-reset/confirm with the code an operator
* relayed out-of-band and a new password, and invalidates every
* existing session for that account.
*/
async confirmPasswordReset(code, newPassword) {
await this._call('POST', '/api/password-reset/confirm', {
body: { code, password: newPassword },
});
}
// --- admin user management --------------------------------------------------
/**
* Calls GET /api/admin/users. token's account must satisfy AuthGuard's
* CanManageUsers check (admin or superadmin), or this throws an
* APIError with statusCode 401/403.
* @returns {Promise<object[]>}
*/
async listManagedUsers(token) {
const { payload } = await this._call('GET', '/api/admin/users', { token });
return (payload.users ?? []).map(AuthClient._managedUser);
}
/**
* Calls POST /api/admin/users. Only a superadmin actor may set role to
* anything other than "user"; anyone else's requested role is silently
* ignored by AuthGuard.
* @param {{username: string, email: string, password: string, role?: string}} input
*/
async createManagedUser(token, input) {
const { payload } = await this._call('POST', '/api/admin/users', { token, body: input });
return AuthClient._managedUser(payload.user);
}
/**
* Calls PUT /api/admin/users/{id}. An omitted field means "leave
* unchanged" (AuthGuard applies only non-empty fields); role is only
* honored per AuthGuard's own authorization rules (only a superadmin
* actor, and never onto/away from a superadmin target) - this client
* does not re-implement or pre-validate those rules.
* @param {{username?: string, email?: string, password?: string, role?: string}} input
*/
async updateManagedUser(token, id, input) {
await this._call('PUT', `/api/admin/users/${encodeURIComponent(id)}`, { token, body: input });
}
/** Calls DELETE /api/admin/users/{id}. */
async deleteManagedUser(token, id) {
await this._call('DELETE', `/api/admin/users/${encodeURIComponent(id)}`, { token });
}
}
/**
+1 -1
View File
@@ -31,4 +31,4 @@ export {
verifyTotp,
} from './totp.js';
export { runMigrations } from './migrate.js';
export { AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
@@ -1,19 +1,36 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { AuthClient, InvalidSessionError } from '../src/authclient.js';
import { APIError, AuthClient, InvalidSessionError } from '../src/authclient.js';
function fakeFetch(responses) {
let call = 0;
return async () => {
const res = responses[Math.min(call, responses.length - 1)];
call += 1;
const bodyText = res.body === undefined ? '' : JSON.stringify(res.body);
return {
status: res.status,
ok: res.status >= 200 && res.status < 300,
json: async () => res.body,
text: async () => bodyText,
headers: { getSetCookie: () => res.cookies ?? [] },
};
};
}
// Records every (url, init) pair a fakeFetch call received, for assertions
// on method/headers/body without a full fetch mock library.
function recordingFetch(responses) {
const calls = [];
const inner = fakeFetch(responses);
const wrapped = async (url, init) => {
calls.push({ url, init });
return inner(url, init);
};
wrapped.calls = calls;
return wrapped;
}
test('validate resolves the user on a valid session', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]),
@@ -81,3 +98,187 @@ test('middleware attaches authUser on success and 401s on failure', async () =>
assert.equal(statusCode, 401);
assert.deepEqual(jsonBody, { error: 'authentication required' });
});
// --- register/login/.../setupStatus: the additional surface a service that
// runs its own login/admin screens proxied to AuthGuard needs, beyond the
// original validate()-only surface. ---
test('setupStatus reflects AuthGuard setup_required', async () => {
for (const setupRequired of [true, false]) {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { setup_required: setupRequired } }]),
});
assert.equal(await client.setupStatus(), setupRequired);
}
});
test('register returns the user and forwards Set-Cookie values', async () => {
const fetchImpl = recordingFetch([
{
status: 201,
body: { user: { id: 1, username: 'root', email: 'root@example.com', role: 'superadmin', totp_enabled: false } },
cookies: ['auth_session=abc; HttpOnly'],
},
]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
const result = await client.register('root', 'root@example.com', 'correct horse battery staple');
assert.deepEqual(result.user, {
id: 1,
username: 'root',
email: 'root@example.com',
role: 'superadmin',
totpEnabled: false,
});
assert.deepEqual(result.cookies, ['auth_session=abc; HttpOnly']);
const sent = JSON.parse(fetchImpl.calls[0].init.body);
assert.deepEqual(sent, { username: 'root', email: 'root@example.com', password: 'correct horse battery staple' });
});
test('login success reports totpEnabled from AuthGuard', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([
{
status: 200,
body: { user: { id: 2, username: 'alice', email: 'alice@example.com', role: 'user', totp_enabled: true } },
cookies: ['auth_session=xyz'],
},
]),
});
const result = await client.login('alice', 'correct horse battery staple', '123456');
assert.equal(result.user.username, 'alice');
assert.equal(result.user.totpEnabled, true);
assert.deepEqual(result.cookies, ['auth_session=xyz']);
});
test('login raises APIError with totpRequired on a 401 asking for a code', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([
{ status: 401, body: { error: 'two-factor authentication code required', totp_required: true } },
]),
});
await assert.rejects(
() => client.login('alice', 'correct horse battery staple'),
(err) => err instanceof APIError && err.statusCode === 401 && err.totpRequired === true,
);
});
test('login raises APIError without totpRequired on invalid credentials', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 401, body: { error: 'invalid username/email or password' } }]),
});
await assert.rejects(
() => client.login('alice', 'wrong password'),
(err) => err instanceof APIError && err.totpRequired === false && err.detailMessage === 'invalid username/email or password',
);
});
test('logout returns the clearing cookies', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true }, cookies: ['auth_session=; Max-Age=0'] }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
const cookies = await client.logout('a-token');
assert.deepEqual(cookies, ['auth_session=; Max-Age=0']);
assert.equal(fetchImpl.calls[0].init.headers.Authorization, 'Bearer a-token');
});
test('me resolves the public user', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([
{ status: 200, body: { user: { id: 3, username: 'bob', email: 'bob@example.com', role: 'admin', totp_enabled: false } } },
]),
});
const user = await client.me('a-token');
assert.equal(user.id, 3);
assert.equal(user.role, 'admin');
});
test('totpEnable returns the provisioned secret', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { secret: 'SECRET', otpauth_url: 'otpauth://...', enabled: false } }]),
});
const result = await client.totpEnable('a-token');
assert.equal(result.secret, 'SECRET');
assert.equal(result.enabled, false);
});
test('totpVerify and totpDisable send the code as {token}', async () => {
let fetchImpl = recordingFetch([{ status: 200, body: { enabled: true } }]);
let client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.totpVerify('a-token', '123456');
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { token: '123456' });
fetchImpl = recordingFetch([{ status: 200, body: { enabled: false } }]);
client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.totpDisable('a-token', '654321');
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { token: '654321' });
});
test('requestPasswordReset with no identifier sends an empty body (targets the superadmin)', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.requestPasswordReset();
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), {});
});
test('confirmPasswordReset sends the code and new password', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.confirmPasswordReset('ABCD1234', 'a brand new passphrase');
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { code: 'ABCD1234', password: 'a brand new passphrase' });
});
test('listManagedUsers maps every row', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([
{
status: 200,
body: {
users: [
{ id: 1, username: 'root', email: 'root@example.com', role: 'superadmin', created_at: '2026-01-01T00:00:00Z' },
{ id: 2, username: 'bob', email: 'bob@example.com', role: 'user', created_at: '2026-01-02T00:00:00Z' },
],
},
},
]),
});
const users = await client.listManagedUsers('a-token');
assert.equal(users.length, 2);
assert.deepEqual(users[0], {
id: 1,
username: 'root',
email: 'root@example.com',
role: 'superadmin',
createdAt: '2026-01-01T00:00:00Z',
});
});
test('createManagedUser sends only the given fields', async () => {
const fetchImpl = recordingFetch([
{ status: 201, body: { user: { id: 4, username: 'carol', email: 'carol@example.com', role: 'user', created_at: '' } } },
]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
const created = await client.createManagedUser('a-token', {
username: 'carol',
email: 'carol@example.com',
password: 'correct horse battery staple',
});
assert.equal(created.username, 'carol');
const sent = JSON.parse(fetchImpl.calls[0].init.body);
assert.equal('role' in sent, false);
});
test('updateManagedUser PUTs to /api/admin/users/{id}', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.updateManagedUser('a-token', 5, { email: 'new@example.com' });
assert.equal(fetchImpl.calls[0].init.method, 'PUT');
assert.equal(fetchImpl.calls[0].url, 'https://auth.example.com/api/admin/users/5');
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { email: 'new@example.com' });
});
test('deleteManagedUser DELETEs /api/admin/users/{id}', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.deleteManagedUser('a-token', 6);
assert.equal(fetchImpl.calls[0].init.method, 'DELETE');
assert.equal(fetchImpl.calls[0].url, 'https://auth.example.com/api/admin/users/6');
});
@@ -3,39 +3,47 @@ a sibling of this shared/python-backend package) instead of embedding this
package's own asyncpg-backed AuthStore against a service's private database.
A service that switches to AuthGuard trades "its own local user table" for
"one HTTP call per request to AuthGuard's GET /api/session/validate",
gaining a single shared identity across every project that does the same.
This module is additive: it does not change how shared_backend.auth works,
and no project in this workspace is wired up to use it yet -- that migration
is a deliberate per-project decision. Mirrors
shared/backend/authclient/client.go and
shared/packages/node-backend/src/authclient.js (the Go and Node
"HTTP calls to AuthGuard's API", gaining a single shared identity across
every project that does the same. This module is additive: it does not
change how shared_backend.auth works. Mirrors shared/backend/authclient/client.go
and shared/packages/node-backend/src/authclient.js (the Go and Node
equivalents) -- keep all three in sync if any changes shape.
Two kinds of consumer, two parts of this module:
- A service that only needs to gate requests behind "is this a valid
AuthGuard session" (HordeWorker, Heretic) uses `AuthClient.validate` /
`token_from_request` / `resolve_user`, calling only GET
/api/session/validate. This is the original, minimal surface of this
module.
- A service that runs its own login/register/admin-user-management screens
proxied to AuthGuard (mirroring shared/backend/authclient/client.go's
full method set -- see e.g. Original/GameStream/backend/cmd/gamestreamd/auth.go
for the reference Go implementation of this pattern) uses the additional
methods below: register, login, logout, me, totp_*, *_password_reset,
*_managed_user(s), setup_status.
Sync vs. async: every other I/O-bound module in this package (auth.py,
postgres.py) is async, built on asyncpg, because a service using this
package already runs its own request handling on an async event loop. A
per-request session check is exactly the kind of call such a handler would
`await`, so `AuthClient.validate` is async too, for the same reason the Go
and Node versions are async/Promise-based: so it composes with the rest of
an async request path instead of blocking it. This package's dependency
list (asyncpg, bcrypt) has no async HTTP client, and adding one (aiohttp,
httpx) just for a single small GET request is more than this needs. Instead,
the actual HTTP call is a plain blocking `urllib.request.urlopen`, run off
package already runs its own request handling on an async event loop. Every
method here is `async` for the same reason. This package's dependency list
(asyncpg, bcrypt) has no async HTTP client, and adding one (aiohttp, httpx)
just for occasional small JSON requests is more than this needs. Instead,
the actual HTTP calls are plain blocking `urllib.request.urlopen`, run off
the event loop via `asyncio.to_thread` -- stdlib-only, and the awkwardness
of raw async stdlib sockets/TLS/redirects is not worth it for one endpoint.
of raw async stdlib sockets/TLS/redirects is not worth it here.
Framework-agnostic vs. framework-specific: this package's own README says
"HTTP framework adapters stay in each service", and the two real prospective
consumers of this module do not even share a framework -- HordeWorker's
webui/server.py is aiohttp.web, Heretic's src/heretic/api/app.py is FastAPI.
So there is no single framework to special-case here. Instead of a
decorator/dependency tied to one framework, this module exposes
`token_from_request`/`resolve_user` as plain functions over headers/cookies
mappings (which is all `aiohttp.web.Request` and FastAPI/Starlette's
`Request` both expose), and each service wires those into its own
framework's idiom (an aiohttp `@web.middleware`, a FastAPI `Depends`, etc.)
the same way it already owns its own routing.
"HTTP framework adapters stay in each service". `token_from_request`/
`resolve_user` are plain functions over headers/cookies mappings (which is
all `aiohttp.web.Request` and FastAPI/Starlette's `Request` both expose),
and each service wires those into its own framework's idiom (an aiohttp
`@web.middleware`, a FastAPI `Depends`, etc.) the same way it already owns
its own routing. The register/login/logout methods return the raw
Set-Cookie header values AuthGuard's response carried rather than trying to
set them on a framework-specific response object -- see SessionResult --
for the same reason: each service's own route handler already owns the
concrete Response object and knows how to attach headers to it.
"""
from __future__ import annotations
@@ -44,8 +52,8 @@ import asyncio
import json
import urllib.error
import urllib.request
from dataclasses import dataclass
from typing import Mapping
from dataclasses import dataclass, field
from typing import Any, Mapping
DEFAULT_COOKIE_NAME = "auth_session"
DEFAULT_TIMEOUT = 5.0
@@ -69,6 +77,26 @@ class AuthClientError(Exception):
fail closed (401) on both."""
class APIError(AuthClientError):
"""Raised when AuthGuard responds with a non-2xx status to one of the
register/login/.../setup_status methods below (not raised by validate(),
which uses InvalidSessionError for its one specific non-2xx case).
Mirrors Go's *authclient.APIError -- carries the status code and (when
AuthGuard's JSON body decoded successfully) its {"error": "..."}
message, so a caller can map it back onto its own service's response
shape/status code rather than exposing AuthGuard's wording verbatim."""
def __init__(self, status_code: int, message: str, *, totp_required: bool = False) -> None:
self.status_code = status_code
self.message = message
# Mirrors AuthGuard's {"totp_required": true} flag on a 401 from
# POST /api/login that means "credentials were correct, but this
# account has two-factor auth enabled and no (or an incorrect) code
# was supplied" -- distinct from a plain invalid-credentials 401.
self.totp_required = totp_required
super().__init__(f"authclient: authguard responded {status_code}: {message}")
@dataclass(frozen=True, slots=True)
class AuthGuardUser:
"""The account AuthGuard resolved for a validated session. Mirrors the
@@ -82,6 +110,55 @@ class AuthGuardUser:
role: str
@dataclass(frozen=True, slots=True)
class PublicUser:
"""The account object AuthGuard returns from POST /api/register,
POST /api/login, and GET /api/me. Mirrors AuthGuard's publicUser (see
internal/httpapi/server.go's toPublicUser) -- includes totp_enabled,
which AuthGuardUser (from /api/session/validate) does not carry."""
id: int
username: str
email: str
role: str
totp_enabled: bool = False
@dataclass(frozen=True, slots=True)
class ManagedUser:
"""One row of GET /api/admin/users, and the payload returned by
create_managed_user. Additionally carries created_at, which PublicUser
does not."""
id: int
username: str
email: str
role: str
created_at: str = ""
@dataclass(frozen=True, slots=True)
class SessionResult:
"""Returned by register() and login(): the account AuthGuard resolved,
plus the raw Set-Cookie header value(s) its response carried. A caller
forwards these onto its own framework's response object, e.g. in
FastAPI: `for cookie in result.cookies: response.headers.append("set-cookie", cookie)`."""
user: PublicUser
cookies: list[str] = field(default_factory=list)
@dataclass(frozen=True, slots=True)
class TOTPEnableResult:
"""Returned by totp_enable(): a freshly provisioned, not yet active TOTP
secret and its otpauth:// URI for a QR code / authenticator app. Confirm
it with totp_verify()."""
secret: str
otpauth_url: str
enabled: bool = False
class AuthClient:
"""Calls a centralized AuthGuard instance over HTTP."""
@@ -101,6 +178,8 @@ class AuthClient:
self.cookie_name = cookie_name
self.timeout = timeout
# --- session validation (the original, minimal surface) ----------------
async def validate(self, token: str) -> AuthGuardUser:
"""Calls AuthGuard's GET /api/session/validate with token as a Bearer
credential and returns the resolved user. Raises InvalidSessionError
@@ -152,6 +231,244 @@ class AuthClient:
role=str(payload.get("role") or ""),
)
# --- shared request/response plumbing for everything below -------------
async def _call(
self,
method: str,
path: str,
*,
token: str = "",
body: Any = None,
) -> tuple[dict[str, Any], list[str]]:
"""Runs one JSON request/response round trip against AuthGuard, off
the event loop. Returns the decoded JSON body (an empty dict for a
2xx response with no body) and the raw Set-Cookie header value(s)
the response carried. Raises APIError for a non-2xx response,
AuthClientError for a transport/decoding failure -- mirroring Go's
Client.call exactly, just spread across two return values instead
of one (Go, request, out any)."""
if not self.base_url:
raise AuthClientError("authclient: client has no base URL")
return await asyncio.to_thread(self._call_sync, method, path, token, body)
def _call_sync(
self, method: str, path: str, token: str, body: Any
) -> tuple[dict[str, Any], list[str]]:
data = None
headers: dict[str, str] = {}
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
if token:
headers["Authorization"] = f"{_BEARER_PREFIX}{token}"
request = urllib.request.Request(
f"{self.base_url}{path}", data=data, headers=headers, method=method
)
try:
with urllib.request.urlopen(request, timeout=self.timeout) as response:
status = response.status
raw = response.read()
cookies = response.headers.get_all("Set-Cookie") or []
except urllib.error.HTTPError as exc:
status = exc.code
raw = exc.read()
cookies = []
except urllib.error.URLError as exc:
raise AuthClientError(f"authclient: call AuthGuard: {exc}") from exc
except OSError as exc:
raise AuthClientError(f"authclient: call AuthGuard: {exc}") from exc
payload: dict[str, Any] = {}
if raw:
try:
decoded = json.loads(raw)
if isinstance(decoded, dict):
payload = decoded
except (ValueError, TypeError, UnicodeDecodeError) as exc:
if not (200 <= status < 300):
raise APIError(status, f"request failed ({status})") from exc
raise AuthClientError(f"authclient: decode AuthGuard response: {exc}") from exc
if not (200 <= status < 300):
message = str(payload.get("error") or f"request failed ({status})")
raise APIError(status, message, totp_required=bool(payload.get("totp_required")))
return payload, list(cookies)
@staticmethod
def _public_user(payload: dict[str, Any]) -> PublicUser:
user = payload.get("user") or {}
return PublicUser(
id=int(user.get("id") or 0),
username=str(user.get("username") or ""),
email=str(user.get("email") or ""),
role=str(user.get("role") or ""),
totp_enabled=bool(user.get("totp_enabled")),
)
@staticmethod
def _managed_user(user: dict[str, Any]) -> ManagedUser:
return ManagedUser(
id=int(user.get("id") or 0),
username=str(user.get("username") or ""),
email=str(user.get("email") or ""),
role=str(user.get("role") or ""),
created_at=str(user.get("created_at") or ""),
)
# --- setup / registration ------------------------------------------------
async def setup_status(self) -> bool:
"""Calls GET /api/setup-status, an unauthenticated endpoint that
reports whether AuthGuard has any account at all. Accounts are
centralized in AuthGuard, so a caller with its own "first launch,
create the initial admin" flow should consult this first: when it
returns False, some account already exists (possibly created by a
different project, or directly against AuthGuard), and the caller
should show its ordinary login screen instead of its own
account-creation form."""
payload, _ = await self._call("GET", "/api/setup-status")
return bool(payload.get("setup_required"))
async def register(self, username: str, email: str, password: str) -> SessionResult:
"""Calls POST /api/register, creating a new AuthGuard account and
starting a session for it."""
payload, cookies = await self._call(
"POST",
"/api/register",
body={"username": username, "email": email, "password": password},
)
return SessionResult(user=self._public_user(payload), cookies=cookies)
async def login(
self, username_or_email: str, password: str, totp_token: str = ""
) -> SessionResult:
"""Calls POST /api/login. totp_token may be empty; AuthGuard raises
an APIError with totp_required set when the account has two-factor
auth enabled and no valid code was supplied."""
body: dict[str, str] = {"username_or_email": username_or_email, "password": password}
if totp_token:
body["totp_token"] = totp_token
payload, cookies = await self._call("POST", "/api/login", body=body)
return SessionResult(user=self._public_user(payload), cookies=cookies)
async def logout(self, token: str) -> list[str]:
"""Calls POST /api/logout, deleting the session identified by token
server-side. Returns the (cookie-clearing) Set-Cookie header
value(s) AuthGuard's response carried."""
_, cookies = await self._call("POST", "/api/logout", token=token)
return cookies
async def me(self, token: str) -> PublicUser:
"""Calls GET /api/me, resolving token to its account."""
payload, _ = await self._call("GET", "/api/me", token=token)
return self._public_user(payload)
# --- TOTP ------------------------------------------------------------------
async def totp_enable(self, token: str) -> TOTPEnableResult:
"""Calls POST /api/totp/enable, provisioning (or re-provisioning) a
pending TOTP secret for token's account. The secret is not active
until totp_verify confirms a generated code."""
payload, _ = await self._call("POST", "/api/totp/enable", token=token)
return TOTPEnableResult(
secret=str(payload.get("secret") or ""),
otpauth_url=str(payload.get("otpauth_url") or ""),
enabled=bool(payload.get("enabled")),
)
async def totp_verify(self, token: str, code: str) -> None:
"""Calls POST /api/totp/verify, confirming code against the pending
secret totp_enable provisioned and activating two-factor auth."""
await self._call("POST", "/api/totp/verify", token=token, body={"token": code})
async def totp_disable(self, token: str, code: str) -> None:
"""Calls POST /api/totp/disable, turning two-factor auth off for
token's account. AuthGuard requires code to be one last valid TOTP
code as proof of possession."""
await self._call("POST", "/api/totp/disable", token=token, body={"token": code})
# --- password reset ("break glass", console-only -- see AuthGuard's README) --
async def request_password_reset(self, username_or_email: str = "") -> None:
"""Calls POST /api/password-reset/request. AuthGuard prints a
one-time code to its own process console; only an operator with
access to that console can relay it onward. Sent with no
username_or_email, the target is AuthGuard's superadmin account --
AuthGuard's own web UI is the intended place to drive this, not an
individual project (see AuthGuard's README's "Web UI" section)."""
body = {"username_or_email": username_or_email} if username_or_email else {}
await self._call("POST", "/api/password-reset/request", body=body)
async def confirm_password_reset(self, code: str, new_password: str) -> None:
"""Calls POST /api/password-reset/confirm with the code an operator
relayed out-of-band and a new password, and invalidates every
existing session for that account."""
await self._call(
"POST",
"/api/password-reset/confirm",
body={"code": code, "password": new_password},
)
# --- admin user management --------------------------------------------------
async def list_managed_users(self, token: str) -> list[ManagedUser]:
"""Calls GET /api/admin/users. token's account must satisfy
AuthGuard's CanManageUsers check (admin or superadmin), or this
raises an APIError with status_code 401/403."""
payload, _ = await self._call("GET", "/api/admin/users", token=token)
return [self._managed_user(u) for u in payload.get("users") or []]
async def create_managed_user(
self,
token: str,
*,
username: str,
email: str,
password: str,
role: str | None = None,
) -> ManagedUser:
"""Calls POST /api/admin/users. Only a superadmin actor may set role
to anything other than "user"; anyone else's requested role is
silently ignored by AuthGuard."""
body: dict[str, Any] = {"username": username, "email": email, "password": password}
if role is not None:
body["role"] = role
payload, _ = await self._call("POST", "/api/admin/users", token=token, body=body)
return self._managed_user(payload.get("user") or {})
async def update_managed_user(
self,
token: str,
user_id: int,
*,
username: str | None = None,
email: str | None = None,
password: str | None = None,
role: str | None = None,
) -> None:
"""Calls PUT /api/admin/users/{id}. A None field means "leave
unchanged" (AuthGuard applies only non-empty fields); role is only
honored per AuthGuard's own authorization rules (only a superadmin
actor, and never onto/away from a superadmin target) -- this client
does not re-implement or pre-validate those rules."""
body: dict[str, Any] = {}
if username is not None:
body["username"] = username
if email is not None:
body["email"] = email
if password is not None:
body["password"] = password
if role is not None:
body["role"] = role
await self._call("PUT", f"/api/admin/users/{user_id}", token=token, body=body)
async def delete_managed_user(self, token: str, user_id: int) -> None:
"""Calls DELETE /api/admin/users/{id}."""
await self._call("DELETE", f"/api/admin/users/{user_id}", token=token)
def token_from_request(
headers: Mapping[str, str],
@@ -6,10 +6,13 @@ from email.message import Message
from unittest.mock import patch
from shared_backend.authclient import (
APIError,
AuthClient,
AuthClientError,
AuthGuardUser,
InvalidSessionError,
ManagedUser,
PublicUser,
resolve_user,
token_from_request,
)
@@ -18,9 +21,12 @@ from shared_backend.authclient import (
class _FakeResponse:
"""Minimal stand-in for the context manager urllib.request.urlopen returns."""
def __init__(self, status: int, payload: dict) -> None:
def __init__(self, status: int, payload: dict, cookies: list[str] | None = None) -> None:
self.status = status
self._body = json.dumps(payload).encode("utf-8")
self.headers = Message()
for cookie in cookies or []:
self.headers.add_header("Set-Cookie", cookie)
def __enter__(self) -> "_FakeResponse":
return self
@@ -154,5 +160,258 @@ class ResolveUserTests(unittest.IsolatedAsyncioTestCase):
urlopen.assert_not_called()
class AuthClientProxyMethodTests(unittest.IsolatedAsyncioTestCase):
"""Covers the register/login/.../setup_status surface: the additional
methods a service that runs its own login/admin screens proxied to
AuthGuard needs, beyond the original validate()-only surface."""
def setUp(self) -> None:
self.client = AuthClient("https://authguard.example")
async def test_setup_status_true_and_false(self) -> None:
for setup_required in (True, False):
response = _FakeResponse(200, {"setup_required": setup_required})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
result = await self.client.setup_status()
self.assertEqual(result, setup_required)
request = urlopen.call_args.args[0]
self.assertEqual(request.get_method(), "GET")
self.assertTrue(request.full_url.endswith("/api/setup-status"))
async def test_register_returns_user_and_forwards_cookies(self) -> None:
payload = {
"user": {
"id": 1,
"username": "root",
"email": "root@example.com",
"role": "superadmin",
"totp_enabled": False,
}
}
response = _FakeResponse(201, payload, cookies=["auth_session=abc; HttpOnly"])
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
result = await self.client.register(
"root", "root@example.com", "correct horse battery staple"
)
self.assertEqual(
result.user,
PublicUser(
id=1,
username="root",
email="root@example.com",
role="superadmin",
totp_enabled=False,
),
)
self.assertEqual(result.cookies, ["auth_session=abc; HttpOnly"])
request = urlopen.call_args.args[0]
self.assertEqual(request.get_method(), "POST")
sent = json.loads(request.data)
self.assertEqual(
sent,
{
"username": "root",
"email": "root@example.com",
"password": "correct horse battery staple",
},
)
async def test_login_success(self) -> None:
payload = {
"user": {
"id": 2,
"username": "alice",
"email": "alice@example.com",
"role": "user",
"totp_enabled": True,
}
}
response = _FakeResponse(200, payload, cookies=["auth_session=xyz"])
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
result = await self.client.login("alice", "correct horse battery staple", "123456")
self.assertEqual(result.user.username, "alice")
self.assertTrue(result.user.totp_enabled)
self.assertEqual(result.cookies, ["auth_session=xyz"])
async def test_login_totp_required_raises_api_error_with_flag(self) -> None:
error = _fake_http_error(
401, {"error": "two-factor authentication code required", "totp_required": True}
)
with patch("shared_backend.authclient.urllib.request.urlopen", side_effect=error):
with self.assertRaises(APIError) as ctx:
await self.client.login("alice", "correct horse battery staple")
self.assertEqual(ctx.exception.status_code, 401)
self.assertTrue(ctx.exception.totp_required)
async def test_login_invalid_credentials_raises_api_error_without_totp_flag(self) -> None:
error = _fake_http_error(401, {"error": "invalid username/email or password"})
with patch("shared_backend.authclient.urllib.request.urlopen", side_effect=error):
with self.assertRaises(APIError) as ctx:
await self.client.login("alice", "wrong password")
self.assertFalse(ctx.exception.totp_required)
self.assertEqual(ctx.exception.message, "invalid username/email or password")
async def test_logout_returns_clearing_cookies(self) -> None:
response = _FakeResponse(200, {"ok": True}, cookies=["auth_session=; Max-Age=0"])
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
cookies = await self.client.logout("a-token")
self.assertEqual(cookies, ["auth_session=; Max-Age=0"])
request = urlopen.call_args.args[0]
self.assertEqual(request.get_header("Authorization"), "Bearer a-token")
async def test_me_resolves_public_user(self) -> None:
payload = {
"user": {
"id": 3,
"username": "bob",
"email": "bob@example.com",
"role": "admin",
"totp_enabled": False,
}
}
response = _FakeResponse(200, payload)
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
user = await self.client.me("a-token")
self.assertEqual(user.id, 3)
self.assertEqual(user.role, "admin")
async def test_totp_enable_returns_secret(self) -> None:
payload = {"secret": "SECRET", "otpauth_url": "otpauth://...", "enabled": False}
response = _FakeResponse(200, payload)
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
result = await self.client.totp_enable("a-token")
self.assertEqual(result.secret, "SECRET")
self.assertFalse(result.enabled)
async def test_totp_verify_and_disable_send_token(self) -> None:
response = _FakeResponse(200, {"enabled": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.totp_verify("a-token", "123456")
sent = json.loads(urlopen.call_args.args[0].data)
self.assertEqual(sent, {"token": "123456"})
response = _FakeResponse(200, {"enabled": False})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.totp_disable("a-token", "654321")
sent = json.loads(urlopen.call_args.args[0].data)
self.assertEqual(sent, {"token": "654321"})
async def test_request_password_reset_targets_superadmin_by_default(self) -> None:
response = _FakeResponse(200, {"ok": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.request_password_reset()
sent = json.loads(urlopen.call_args.args[0].data)
self.assertEqual(sent, {})
async def test_confirm_password_reset_sends_code_and_password(self) -> None:
response = _FakeResponse(200, {"ok": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.confirm_password_reset("ABCD1234", "a brand new passphrase")
sent = json.loads(urlopen.call_args.args[0].data)
self.assertEqual(sent, {"code": "ABCD1234", "password": "a brand new passphrase"})
async def test_list_managed_users(self) -> None:
payload = {
"users": [
{
"id": 1,
"username": "root",
"email": "root@example.com",
"role": "superadmin",
"created_at": "2026-01-01T00:00:00Z",
},
{
"id": 2,
"username": "bob",
"email": "bob@example.com",
"role": "user",
"created_at": "2026-01-02T00:00:00Z",
},
]
}
response = _FakeResponse(200, payload)
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
users = await self.client.list_managed_users("a-token")
self.assertEqual(len(users), 2)
self.assertEqual(
users[0],
ManagedUser(
id=1,
username="root",
email="root@example.com",
role="superadmin",
created_at="2026-01-01T00:00:00Z",
),
)
async def test_create_managed_user_omits_role_when_not_given(self) -> None:
payload = {
"user": {
"id": 4,
"username": "carol",
"email": "carol@example.com",
"role": "user",
"created_at": "",
}
}
response = _FakeResponse(201, payload)
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
created = await self.client.create_managed_user(
"a-token",
username="carol",
email="carol@example.com",
password="correct horse battery staple",
)
self.assertEqual(created.username, "carol")
sent = json.loads(urlopen.call_args.args[0].data)
self.assertNotIn("role", sent)
async def test_update_managed_user_only_sends_provided_fields(self) -> None:
response = _FakeResponse(200, {"ok": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.update_managed_user("a-token", 5, email="new@example.com")
request = urlopen.call_args.args[0]
self.assertEqual(request.get_method(), "PUT")
self.assertTrue(request.full_url.endswith("/api/admin/users/5"))
sent = json.loads(request.data)
self.assertEqual(sent, {"email": "new@example.com"})
async def test_delete_managed_user(self) -> None:
response = _FakeResponse(200, {"ok": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.delete_managed_user("a-token", 6)
request = urlopen.call_args.args[0]
self.assertEqual(request.get_method(), "DELETE")
self.assertTrue(request.full_url.endswith("/api/admin/users/6"))
async def test_transport_error_raises_auth_client_error_not_api_error(self) -> None:
transport_error = urllib.error.URLError("connection refused")
with patch("shared_backend.authclient.urllib.request.urlopen", side_effect=transport_error):
with self.assertRaises(AuthClientError) as ctx:
await self.client.setup_status()
self.assertNotIsInstance(ctx.exception, APIError)
if __name__ == "__main__":
unittest.main()