Skip to content

About

No description, website, or topics provided.

Resources

Stars

5 stars

Watchers

1 watching

Forks

Repository files navigation

OAuth-Client-Bridge

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.

Background

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.

Installation

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

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.

Setting up a production instance

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_SECURE to false only 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_SCOPES is used when the authorization request omits scope. Set OAUTH_ALLOWED_SCOPES to 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_POLICY to 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 only csp_nonce, has no globals, filters, tests, or loader, and rejects unknown variables. Header output is not HTML-escaped. Continue using tojson for 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'
    
  • /metrics is enabled by default. Set BRIDGE_METRICS_ENABLED=False to disable it, or set BRIDGE_METRICS_TOKEN to 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

Refresh token metrics

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.

Logging and startup diagnostics

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.

OpenTelemetry Integration

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 are tracing and metrics. For example: TELEMETRY_COMPONENTS=tracing,metrics.

  • TELEMETRY_EXPORTERS: A comma-separated list of exporters to use for traces and metrics. Valid values are otlp_http and console. For example: TELEMETRY_EXPORTERS=otlp_http.

  • TELEMETRY_ENDPOINT: The OTLP collector endpoint (e.g., http://localhost:4318). Required if otlp_http exporter is used.

  • TELEMETRY_SERVICE_NAME: The name of the service to be reported to OpenTelemetry (defaults to oauthclientbridge).

  • TELEMETRY_SERVICE_VERSION: Service version reported as service.version in OpenTelemetry resources (defaults to package version).

  • TELEMETRY_DEPLOYMENT_ENVIRONMENT: Deployment environment reported as deployment.environment in OpenTelemetry resources (defaults to unknown).

  • TELEMETRY_VCS_REVISION: VCS revision (for example, git commit SHA) reported as vcs.revision in OpenTelemetry resources.

  • TELEMETRY_METRIC_EXPORT_INTERVAL_SECONDS: The interval in seconds at which metrics are exported (defaults to 60).

Metrics are pushed over OTLP HTTP as this is the only exporter we support.

Retry And Refresh Token Semantics

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_unavailable to 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 400 with OAuth error invalid_grant.
  • A retryable response such as 503 with 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_token on success, the bridge stores it. If success omits refresh_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.

About

No description, website, or topics provided.

Resources

Stars

5 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages