Callback Server and Token Errors¶
Summary¶
This chapter covers two components that support OAuth authorization flows. First, the LocalCallbackServer used for capturing OAuth redirect callbacks, including the ephemeral HTTP server, callback capture with state validation, the prompt-for-code fallback, and manual redirect mode for headless environments. Second, the typed exceptions for token operation failures: TokenExchangeError with its diagnostic URL, and TokenRefreshError with HTTP status code context.
The Callback Problem¶
OAuth authorization flows require capturing a redirect from the authorization server back to the client. The authorization server appends an authorization code and state parameter to a redirect URI, and the client must receive these values to continue the flow. In web applications, the redirect URI points to an application endpoint. In CLI tools and desktop applications, there is no pre-existing HTTP endpoint to receive the redirect.
The mountainash-auth-client library solves this with a short-lived local HTTP server that starts, waits for a single redirect, extracts the parameters, and shuts down. For environments where binding a local port is not possible (containers, remote SSH sessions, CI/CD), the library provides a fallback mode where the user manually copies the redirect URL or authorization code.
LocalCallbackServer¶
The LocalCallbackServer class manages the lifecycle of an ephemeral HTTP server that captures a single OAuth callback. It binds to localhost, generates a redirect URI based on the assigned port, and blocks until a callback request arrives or a timeout expires.
The constructor accepts two parameters: the port number (defaulting to 0 for automatic assignment) and a timeout in seconds (defaulting to 120).
class LocalCallbackServer:
def __init__(self, port: int = 0, timeout: int = 120) -> None:
self._server = HTTPServer(("localhost", port), _CallbackHandler)
self._server._callback_params = None
self._timeout = timeout
Specifying port 0 tells the operating system to assign an available ephemeral port. This avoids conflicts with other services and removes the need for users to configure a specific port. The actual assigned port is available through the port property after construction.
Two properties provide the server's addressing information:
port-- the actual port number assigned by the OS (useful for constructing the redirect URI)redirect_uri-- the full callback URL in the formathttp://localhost:{port}/callback
Ephemeral HTTP Server¶
The underlying HTTP server uses Python's standard library HTTPServer from http.server. It is configured with a custom request handler class (_CallbackHandler) that processes a single GET request and extracts query parameters from the URL.
class _CallbackHandler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
parsed = urlparse(self.path)
params = parse_qs(parsed.query)
self.server._callback_params = {k: v[0] for k, v in params.items()}
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write(b"<html><body><h1>Authorization complete.</h1>"
b"<p>You can close this window.</p></body></html>")
def log_message(self, format, *args) -> None:
pass
The handler does four things on receiving a request. First, it parses the query string into a dictionary (flattening multi-value params by taking the first value). Second, it stores the parameters on the server instance for later retrieval. Third, it responds with a simple HTML page telling the user they can close the browser tab. Fourth, it suppresses the default request logging by overriding log_message with a no-op.
The term "ephemeral" is significant: the server handles exactly one request and then shuts down. It is not a long-running service. This minimizes the window during which the port is open, reducing the attack surface.
Callback Capture¶
The wait_for_callback method blocks the calling thread until the HTTP server receives a callback request or the timeout expires. It delegates to HTTPServer.handle_request(), which processes a single incoming request.
def wait_for_callback(self) -> dict[str, str]:
self._server.timeout = self._timeout
self._server.handle_request()
if self._server._callback_params is None:
raise TimeoutError("No callback received within timeout")
try:
return self._server._callback_params
finally:
self._server.server_close()
After the callback is captured, the method closes the server socket (via server_close()) in a finally block to ensure cleanup even if subsequent code raises an exception. The returned dictionary typically contains code (the authorization code) and state (the CSRF protection token).
If the timeout expires before any request arrives, the method raises a TimeoutError. This can happen when the user closes the browser without completing authorization, when a firewall blocks the redirect, or when the provider's redirect URI does not match the registered callback URL.
Diagram: Callback Server Lifecycle¶
Callback Server Lifecycle
Type: workflow
sim-id: callback-server-lifecycle
Library: vis-network
Status: Specified
Purpose: Show the complete lifecycle of the LocalCallbackServer from instantiation through port binding, waiting, callback receipt, parameter extraction, response to browser, and server close.
Components: Sequential nodes: Construct (port=0) -> OS assigns port -> redirect_uri available -> wait_for_callback() blocking -> Browser redirects to localhost:port/callback?code=X&state=Y -> Handler extracts params -> 200 response sent -> server_close() -> return params dict. A timeout branch shows the TimeoutError path.
Interactions: Click "Play" to animate the normal flow. Click "Simulate Timeout" to see the timeout path. Hover on the "blocking" node to see what the thread is doing while waiting. Click the browser redirect to see the full URL with query parameters.
Colors: Server lifecycle=SteelBlue, Browser interaction=Gold, Success path=DarkGreen, Timeout path=Crimson.
Learning Objective: Understand (Bloom Level 2) the complete lifecycle of the LocalCallbackServer and how it bridges the gap between browser-based OAuth redirects and CLI applications.
Fallback Modes¶
Not every environment can bind a local port. Remote SSH sessions, Docker containers without exposed ports, headless CI runners, and sandboxed environments all present situations where LocalCallbackServer cannot function. The library provides two fallback approaches.
Prompt For Code¶
The prompt_for_code function implements the simplest fallback: print the authorization URL, ask the user to visit it in a browser, complete the consent flow, and then paste either the redirect URL or the bare authorization code back into the terminal.
def prompt_for_code(authorize_url: str) -> dict[str, str]:
print(f"\nOpen this URL in your browser to authorize:\n\n {authorize_url}\n")
user_input = input("Paste the redirect URL or authorization code: ")
return extract_code_from_input(user_input)
The companion extract_code_from_input function handles two input formats. If the user pastes a full URL (starting with http), it parses the query parameters and extracts code and state. If the user pastes a bare string (the authorization code itself), it wraps it in a {"code": user_input} dictionary.
def extract_code_from_input(user_input: str) -> dict[str, str]:
user_input = user_input.strip()
if user_input.startswith("http"):
parsed = urlparse(user_input)
params = parse_qs(parsed.query)
result: dict[str, str] = {}
if "code" in params:
result["code"] = params["code"][0]
if "state" in params:
result["state"] = params["state"][0]
return result
return {"code": user_input}
This dual-format handling accommodates different provider behaviors. Some providers redirect to the callback URL (which the user can copy from the browser address bar). Others display the code directly on a page (particularly when using the urn:ietf:wg:oauth:2.0:oob redirect URI).
Manual Redirect Mode¶
Manual redirect mode is engaged at the OAuthFlow.authorize() level by passing redirect_mode="manual". When this mode is active, the flow uses urn:ietf:wg:oauth:2.0:oob as the redirect URI instead of a localhost URL. This special URI tells the authorization server to display the authorization code on-screen rather than performing an HTTP redirect.
The urn:ietf:wg:oauth:2.0:oob URI is a well-known special value defined by Google's OAuth implementation and adopted by other providers. When the authorization server receives this as the redirect URI, it knows to display the authorization code on a page rather than issuing an HTTP redirect. Not all providers support this URI -- some require a registered http://localhost redirect URI even for manual mode. The library's use of this URI works with the major providers in the mountainash ecosystem.
The two redirect modes and their use cases are:
| Mode | Redirect URI | User Interaction | Best For |
|---|---|---|---|
local_server |
http://localhost:{port}/callback |
Browser opens automatically; callback captured silently | Desktop environments with browser access |
manual |
urn:ietf:wg:oauth:2.0:oob |
User copies URL to browser, pastes code back | SSH sessions, containers, headless environments |
The flow logic for choosing between modes is straightforward: the OAuthFlow.authorize method checks the redirect_mode parameter and either starts a LocalCallbackServer or calls prompt_for_code.
Token Error Types¶
Token operations retain a safe endpoint display, the actual HTTP response status, and a recognised protocol error code. Public constructors enforce this contract even when called directly. Failures before a response use RuntimeError; no synthetic HTTP status is assigned.
TokenExchangeError¶
TokenExchangeError is raised when the authorization code exchange fails -- typically because the code has expired, the redirect URI does not match, or the client credentials are invalid.
import json
from mountainash_auth_client import TokenExchangeError
error = TokenExchangeError(
url="https://user:password@issuer.example/token?signature=secret#fragment",
status_code=400,
body='{"error":"invalid_grant","error_description":"private material"}',
)
assert error.url == "https://issuer.example/token"
assert error.error_code == "invalid_grant"
assert json.loads(error.body) == {"error": "invalid_grant"}
The structured attributes are:
url— display-only location, with userinfo, query and fragment removed from hierarchical URLs. Other schemes display as***; local paths remain visible.status_code— the actual integer HTTP response status, including a successful status when response parsing or validation fails.error_code— one ofinvalid_request,invalid_client,invalid_grant,unauthorized_client,unsupported_grant_type,invalid_scope, orinvalid_token; otherwiseNone.body— reconstructed JSON containing only that recognisederror, or"". Provider descriptions, unknown codes and raw response bodies are not retained.
Token Exchange URL¶
The url attribute on TokenExchangeError serves a specific diagnostic purpose. When a token exchange fails, knowing which URL was called helps determine whether the issue is a misconfigured endpoint (wrong URL), a network problem (connection refused), or a provider-side error. The same URL is used for both initial exchange and refresh, so the error message includes the HTTP method (POST) for clarity.
The error message carries the safe location and status, not provider prose. Hostnames and path segments remain visible: applications must not place credentials there. Display strings are diagnostic values, not URLs to use for retries.
TokenRefreshError¶
TokenRefreshError has an identical structure to TokenExchangeError but represents a different failure context: the refresh token exchange failed, meaning the refresh token may be expired or revoked.
from mountainash_auth_client import TokenRefreshError
try:
tokens = flow.refresh(refresh_token=refresh_token, client_id=client_id)
except TokenRefreshError as error:
print(error.url, error.status_code, error.error_code)
Refresh Status Code¶
Status describes the HTTP response; it does not alone determine whether credentials should be deleted. The acquisition flow clears a stored credential only for recognised invalid_grant or invalid_token refresh errors. It then follows the existing auto_authorize setting. Unknown codes, other token errors and no-response failures propagate without that recovery action.
The package does not add retries. A consumer may apply its own retry policy without treating every HTTP 400 or refresh failure as a revoked credential.
Diagram: Token Error Hierarchy and Recovery¶
Token Error Hierarchy and Recovery
Type: workflow
sim-id: token-error-recovery
Library: vis-network
Status: Specified
Purpose: Show how TokenExchangeError and TokenRefreshError are raised, caught, and used to determine recovery actions in the connection mixin.
Components: Exchange and refresh operations lead to their respective response-backed token errors. Refresh recovery branches on recognised invalid_grant/invalid_token, then on auto_authorize; other failures propagate without deleting the credential.
Interactions: Compare exchange and refresh contexts, then inspect the recognised-code recovery branch. HTTP status remains diagnostic data rather than a credential-deletion rule.
Colors: Error types=Crimson, Recovery actions=DarkGreen, Decision nodes=Gold, Source methods=SteelBlue.
Learning Objective: Distinguish diagnostic HTTP status from the protocol codes that trigger credential recovery.
Error Design Philosophy¶
The token error types in mountainash-auth-client follow several design principles that are worth examining.
Structured attributes over message parsing. Each error carries typed attributes (url, status_code, body) rather than embedding all information in the exception message string. This allows programmatic error handling without regex parsing. Code can inspect exc.status_code directly rather than extracting it from a message like "Token exchange failed: HTTP 400...".
Keyword-only constructors. Both error classes use * in their __init__ signatures, forcing callers to use named arguments: TokenExchangeError(url=..., status_code=..., body=...). This prevents a common bug where positional arguments are accidentally swapped (passing the body as the URL, for example).
Constructor-owned safety. Both public constructors recognise the documented token codes and reconstruct the body. Flow callers cannot bypass that boundary by supplying raw provider text. Unknown codes and malformed JSON produce an empty body.
Separation of exchange and refresh errors. Despite having identical structures, TokenExchangeError and TokenRefreshError are separate classes. This allows except clauses to catch them independently, enabling different recovery strategies. An exchange failure during initial authorization has different implications than a refresh failure during background token renewal.
Exception chaining. OAuth boundaries remove unsafe native causes and contexts. An OSError with an errno may contribute a fresh cause containing only its errno and strerror, never its filenames or custom attributes. Other native failures contribute only their class name; original HTTPX/Authlib exception objects and response/request objects are not retained.
Callback denial. AuthorizationDeniedError.error retains only invalid_request, unauthorized_client, access_denied, unsupported_response_type, invalid_scope, server_error, or temporarily_unavailable. Other values become unknown_error; description is always "". State validation still precedes provider denial handling.
Consumer policy. Credential-bearing hook failures are sanitized. An operation-policy PermissionError retains that category without arbitrary prose. Trust validation still precedes persistence; operation-policy validation follows persistence, including after refresh-token rotation and on cached acquisition.
HTTP logging. Importing either OAuth flow installs idempotent filters on the emitting HTTPX/httpcore loggers. These filters apply process-wide without changing log levels or handlers. HTTPX retains method, safe URL and numeric status; httpcore retains event identity only. Reason phrases, headers and native exception repr are discarded. Successful authorization URLs shown intentionally to the user are not replaced with diagnostic display strings.
How the Components Work Together¶
The callback server and token errors are support components that plug into the OAuth 2.0 flow (Chapter 5) and connection mixin (Chapter 8). Their interactions form a coherent error-handling and user-interaction layer.
During authorization, the flow is:
OAuthFlow.authorize()decides the redirect mode- If
local_server:LocalCallbackServerstarts, browser opens, callback is captured - If
manual:prompt_for_codeprints URL and reads user input OAuthFlow.exchange_code()sends the code to the token endpoint- Response-backed failures raise
TokenExchangeErrorwith safe diagnostic fields; failures before a response raise a safeRuntimeError
During token refresh (triggered by the connection mixin):
OAuthFlow.refresh()sends the refresh token to the token endpoint- If the endpoint returns an error:
TokenRefreshErroris raised - For
invalid_grantorinvalid_token, acquisition clears the stored credential and either re-authorizes or raisesAuthorizationRequired; other failures preserve the record and propagate
Debugging Token Errors
Inspect error_code, the actual status_code and the safe endpoint location. Provider descriptions are deliberately unavailable, including through exception chains. A missing code means no recognised protocol code was retained, not that the stored credential is invalid.
Security Considerations for the Callback Server¶
The LocalCallbackServer listens on localhost only, which means it is not accessible from other machines on the network. However, other processes on the same machine can make requests to it. This creates a theoretical attack vector where a malicious local process sends a forged callback with a fake authorization code.
The state parameter mitigates this attack. Because the state is a cryptographic random value generated fresh for each flow and validated on receipt, a local attacker would need to guess the state value (256 bits of entropy) to forge a valid callback. Without the correct state, the OAuthFlow.authorize method rejects the callback with a state mismatch error.
Additionally, the server handles exactly one request and then shuts down. The window of vulnerability is narrow -- typically a few seconds to two minutes. Combined with the state validation, this makes callback forgery attacks impractical in real-world scenarios.
For high-security environments where even local-host callbacks are unacceptable, the manual redirect mode avoids binding a port entirely. The tradeoff is user convenience: manual mode requires the user to copy and paste a URL rather than having the browser handle the redirect automatically.
Key Takeaways¶
- LocalCallbackServer is an ephemeral HTTP server that binds to
localhoston an OS-assigned port, captures a single OAuth redirect callback, responds with a user-friendly HTML page, and shuts down. - The ephemeral server uses Python's
HTTPServerwith a custom handler that extracts query parameters from the redirect URL and stores them for retrieval. - Callback capture blocks until a request arrives or the timeout (default 120 seconds) expires. The server is closed in a
finallyblock to guarantee cleanup. prompt_for_codeis the fallback for environments without local port access. It accepts both full redirect URLs and bare authorization codes as user input.- Manual redirect mode uses the
urn:ietf:wg:oauth:2.0:oobURI to signal that the provider should display the code on-screen rather than performing an HTTP redirect. TokenExchangeErrorcarries the safe endpoint location, actual HTTP status and recognised code-only body.TokenRefreshErrorhas the same contract for refresh; a pre-response native failure instead raises safeRuntimeError.- Recovery uses recognised
invalid_grant/invalid_token, not HTTP status alone; unknown failures do not delete credentials. - Both errors use keyword-only constructors (
*, url, status_code, body) for clarity at the call site, preventing argument ordering mistakes.