The OAuth2 Client Bridge provides a service to "convert" Authorization Code Grants to Clients Grants suitable for use in "native applications" where it is impractical to use Authorization Code grants directly.
This code exists to solve the "problem" of trying to authenticate native applications against OAuth providers that only allow for long term grants via Authorization Code Grants without giving the secrets to the native application.
After quite some back an forth this solution was devised as it felt the least hackish, and somewhat cleanly combines two existing flows instead of creating a strange hybrid flow.
Deploy with the NixOS module. Native NixOS is the only supported deployment path. See Nix packages for the packaged web server, management CLI, and assets.
Settings are managed by Pydantic and loaded from environment variables. Each
setting is prefixed based on its category (e.g., OAUTH_, DB_, BRIDGE_,
FETCH_). Refer to the Settings class in src/oauthclientbridge/settings.py
for all available options and their prefixes. A minimal setup should define the
following environment variables (see .env.example):
BRIDGE_SESSION_SECRET: Secret key used for signing session cookies.DB_DATABASE: SQLite3 database path.OAUTH_CLIENT_ID: Client ID from your OAuth provider.OAUTH_CLIENT_SECRET: Client secret from your OAuth provider.OAUTH_AUTHORIZATION_URI: Upstream authorization URI.OAUTH_TOKEN_URI: Upstream token URI.
The app can also read these settings from files in CREDENTIALS_DIRECTORY, using
their full environment-variable names as filenames. Environment values keep
precedence over file values. The NixOS module loads sops-nix secrets
through systemd credentials without exporting secret contents.
Use the module's management units
for database initialization, upgrades, and optional scheduled cleanup. The module
also configures worker count and graceful shutdown through workers and
gracefulShutdownTimeout.
See NixOS deployment.
The Nix runtime and development package set uses Determinate Systems' weekly nixpkgs feed, with a seven-day cooldown. Weekly publication can delay security fixes further. This does not constrain Python dependencies, fetched releases, or other flake inputs.
For an urgent fix, temporarily point inputs.nixpkgs.url at a reviewed upstream
revision or github:NixOS/nixpkgs/nixos-unstable, run nix flake update nixpkgs, and
validate through a PR. Restore the weekly feed once it includes the fix. Publish the
refreshed native packages before updating consumer pins; retain this
flake's own runtime package set for cache compatibility.
-
Always use HTTPS since we are passing access tokens around.
-
Session cookies are secure by default. Set
BRIDGE_SESSION_COOKIE_SECUREtofalseonly for local HTTP development. -
Ensure the deployment passes the correct request scheme, host, and client address to the application. The ASGI middleware trusts one reverse-proxy hop; sanitize forwarded headers at the proxy. See proxy configuration.
-
OAUTH_SCOPESis used when the authorization request omitsscope. SetOAUTH_ALLOWED_SCOPESto restrict requested scopes to that allowlist. Leaving it unset permits dynamic scopes for compatibility and should only be used when the caller is trusted. -
Callback HTML has a restrictive default CSP plus no-referrer, nosniff, and permissions-policy headers. Custom callback templates using scripts or external resources must set
BRIDGE_CALLBACK_CONTENT_SECURITY_POLICYto a suitable policy. For trusted inline scripts, use<script nonce="{{ csp_nonce }}">in the template and the policy below. The nonce is fresh per response and shared by the header and template. Both templates use Jinja's sandbox. The HTML template keeps autoescaping and standard filters. The header template receives onlycsp_nonce, has no globals, filters, tests, or loader, and rejects unknown variables. Header output is not HTML-escaped. Continue usingtojsonfor values embedded in JavaScript. An empty policy value explicitly disables CSP.default-src 'none'; script-src 'nonce-{{ csp_nonce }}'; form-action 'self'; base-uri 'none'; frame-ancestors 'none' -
/metricsis enabled by default. SetBRIDGE_METRICS_ENABLED=Falseto disable it, or setBRIDGE_METRICS_TOKENto require bearer authentication. Metrics expose operational information; additionally restrict the route to internal networks at Caddy or another edge proxy.
The following code snippet can be used to create a popup pointed at the oauth server, and the poll the it for the results:
var target = 'https://example.net/oauth';
var targetOrigin = 'https://example.net'
window.addEventListener('message', function(event) {
if (event.origin !== targetOrigin) return;
if (event.data['error']) {
// Update webpage with error data.
} else {
// Update webpage with client_id and client_secret.
}
event.source.close();
}, false);
var child = window.open(target);
var interval = setInterval(function() {
if (child.closed) {
clearInterval(interval);
} else {
child.postMessage('oauthclientbridge', targetOrigin)
}
}, 1000);
To get the snippet above to work setup the bridge with the following
template which will listen for the postMessage and then respond with
the results.:
BRIDGE_CALLBACK_TEMPLATE
The /metrics endpoint exposes oauth_refresh_token_responses_total for validated
successful upstream refresh responses. Its token_update label distinguishes an
omitted refresh token (absent), the submitted token returned again (unchanged),
and a different token (changed). Observations happen before database persistence;
they do not confirm that a replacement was saved. Token values and client identifiers
are not included in the metric.
Zero observed changes does not guarantee that concurrent refreshes are safe.
Logs go to stderr. When stdout is a terminal, logs use a readable console format;
otherwise they use one JSON object per line, suitable for journald and Loki. Set
LOG_JSON_OUTPUT=true or false to override the format. CLI help and usage errors
remain normal Typer output.
The CLI and application workers establish local logging before validating settings. Invalid logging settings use the default format as a fallback. Workers initialize Sentry before loading application settings, then start tracing and metrics after validation. Failures before Sentry is available remain visible locally.
Fatal startup errors exit nonzero and report their type and frame locations, plus validation fields or filesystem details where available. Raw validation inputs, arbitrary exception messages, and frame locals are omitted to avoid exposing credentials. Normal JSON exception logs and Sentry events also omit frame locals.
This project integrates with OpenTelemetry for distributed tracing and metrics collection. To enable OpenTelemetry, you need to configure the following environment variables:
-
TELEMETRY_COMPONENTS: A comma-separated list of OpenTelemetry components to enable. Valid values aretracingandmetrics. For example:TELEMETRY_COMPONENTS=tracing,metrics. -
TELEMETRY_EXPORTERS: A comma-separated list of exporters to use for traces and metrics. Valid values areotlp_httpandconsole. For example:TELEMETRY_EXPORTERS=otlp_http. -
TELEMETRY_ENDPOINT: The OTLP collector endpoint (e.g.,http://localhost:4318). Required ifotlp_httpexporter is used. -
TELEMETRY_SERVICE_NAME: The name of the service to be reported to OpenTelemetry (defaults tooauthclientbridge). -
TELEMETRY_SERVICE_VERSION: Service version reported asservice.versionin OpenTelemetry resources (defaults to package version). -
TELEMETRY_DEPLOYMENT_ENVIRONMENT: Deployment environment reported asdeployment.environmentin OpenTelemetry resources (defaults tounknown). -
TELEMETRY_VCS_REVISION: VCS revision (for example, git commit SHA) reported asvcs.revisionin OpenTelemetry resources. -
TELEMETRY_METRIC_EXPORT_INTERVAL_SECONDS: The interval in seconds at which metrics are exported (defaults to60).
Metrics are pushed over OTLP HTTP as this is the only exporter we support.
The bridge applies a provider-facing retry policy to upstream token endpoint responses and a narrower local invalidation policy to stored refresh tokens.
- Retryable upstream failures are determined by HTTP status and transport outcome, not by contradictory OAuth error payloads.
429,502,503,504, connection failures, timeouts, and similar transient upstream failures are retried according to the configured fetch budget and deadline.- If those retries are exhausted, the bridge surfaces
temporarily_unavailableto its caller and keeps any stored refresh token. - Stored refresh tokens are only invalidated on an authoritative,
non-retryable token refresh failure. For Spotify, this means
400with OAuth errorinvalid_grant. - A retryable response such as
503with a contradictory body like{"error":"invalid_grant"}is treated as transient provider failure, not proof that the stored refresh token is dead. - If the provider returns a new
refresh_tokenon success, the bridge stores it. If success omitsrefresh_token, the bridge keeps the existing stored refresh token.
This behavior matches Spotify's documented refresh-token expiration semantics:
expired refresh tokens return 400 Bad Request with invalid_grant and must
be discarded, while transient token-endpoint failures should not cause local
token invalidation.
For selected broken clients, the bridge can also serve a synthetic bearer token
after a refresh token has already been locally revoked. This is a temporary
workaround for clients that do not back off on token refresh invalid_grant
responses but do stop retrying after a 401 from the provider Web API. By
provoking that upstream 401, the bridge avoids repeated refresh attempts from
those clients against a grant it already knows is dead.