oauthproxy

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

README

oauthproxy

Sign in with a provider on preview and development deployments through the one callback URL registered at the provider. A provider console takes a fixed list of redirect URLs; a preview deployment gets a new URL on every push. With this plugin the console lists only production's callback, and every deployment signs in.

The module also holds oauthpopup, the popup sign-in for apps embedded on another site.

proxy := oauthproxy.New(
	oauthproxy.ProductionURL("https://app.example.com"),
	oauthproxy.WithSecret(sharedSecret), // the same on every deployment
)
a, err := auth.New(auth.WithBaseURL(os.Getenv("BASE_URL")), auth.WithSecret(appSecret),
	auth.WithTrustedOrigins("https://*.preview.example.com"), // production relays only to trusted origins
	auth.WithPlugins(oauth.New(oauth.WithProviders(proxy.Wrap(oauth.Google(id, secret)))), proxy))

Deploy the same code, the same provider credentials and the same proxy secret everywhere; only BASE_URL differs. Register https://app.example.com/auth/oauth/google/callback at the provider and nothing else.

How it works

  1. On a preview, the wrapped provider's authorization URL carries production's callback as redirect_uri and, as state, a sealed package naming the preview's own state and callback.
  2. Production's oauth callback sees the package (a Before hook on oauth.CallbackEndpoint(provider)), checks that the preview's callback is on a trusted origin and that the package is fresh, and redirects the browser to the preview's callback with the preview's state and the authorization code sealed for it. Production exchanges nothing and writes nothing; a callback whose state is not a package is production's own sign-in and runs as usual.
  3. The preview's own oauth callback runs unchanged: flow cookie, state, ValidateProfile, linking, sign-up rules, StoreTokens. The wrapped provider opens the sealed code and exchanges it with the provider itself, using production's redirect_uri and the PKCE verifier that never left the preview. The user and session are created in the preview's database.

By default what travels between deployments is an authorization code, never a profile (PassProfile below is the opt-in exception). It is sealed with AES-256-GCM under a key derived from the shared secret, bound to the provider and the preview's callback, accepted for MaxAge (60 seconds, with 10 seconds of clock skew), and useless without the PKCE verifier only the preview holds. A holder of the proxy secret can therefore relay codes but cannot make a deployment accept an identity the provider did not assert, which an encrypted-profile relay would allow.

Options

Option Default Notes
ProductionURL(u) required
WithSecret(current, previous...) the app's auth.WithSecret
MaxAge(d) 60 seconds
ProductionCallback(fn) the preview callback's path on the production origin
PassProfile() off: production relays the sealed code the encrypted-profile passthrough (see below)
HTTPClient(hc) 10-second timeout, no redirect followed production's exchange client under PassProfile

A sealed state lives StateMaxAge (10 minutes, the person signs in at the provider meanwhile). Keys are derived per purpose (oauthproxy-state, oauthproxy-code), so a state never opens as a code. Previous secrets still open values sealed under them, for rotation.

Opt-in: profile passthrough

PassProfile() is the encrypted-profile design, for deployments where only production can exchange a code. The preview seals a fresh PKCE verifier into the state and sends the provider its challenge; production exchanges the code with it and its own callback, and relays the profile (claims and the provider's tokens included) sealed under the oauthproxy-profile key, prefixed oxp1p., bound to the provider and the preview callback, valid MaxAge. The preview's own callback checks the flow cookie and state, then opens the profile instead of exchanging; a start with X-Skip-OAuth-Proxy still exchanges its own code. A refused exchange is relayed as error=invalid_code (RelayErrorInvalidCode); a relay with no profile is ErrMissingProfile (missing_profile), logged and answered oauth.provider_failed. Turn it on on every deployment: a production without it refuses a state that asks for an exchange, a preview without it never opens a profile.

Risk: whoever holds the proxy secret can then make a preview accept any identity. Init logs WarnPassProfile at every start.

Errors

Code Where When
oauthproxy.invalid_state production callback the package does not open, is too old, names another provider, or names an untrusted or relative callback
oauthproxy.invalid_code preview exchange the relayed code does not open, is too old, or is bound to another provider or callback; the oauth callback answers oauth.provider_failed

Limits

  • A wrapped provider forwards discovery, the issuer check (production relays iss), request parameters, form posts (Apple), refresh, revoke, profile reads and logout. ID-token sign-in and provider-initiated flows are not proxied, so a wrapped provider does not offer them.
  • The proxy decides by comparing the callback URL with ProductionURL; a start request carrying X-Skip-OAuth-Proxy (oauthproxy.SkipHeader, any value) is not proxied, through the oauth plugin's RequestAuthURLer hook, and its code, arriving unsealed, is exchanged with the deployment's own callback.
  • DeploymentURL(os.Getenv, fallback) infers a preview's base URL from its host (VERCEL_URL, NETLIFY_URL, RENDER_URL, and the serverless function-name variables), for auth.WithBaseURL.
  • Every participating deployment must run a compatible version: the sealed formats are versioned (oxp1.), and an in-flight sign-in across an upgrade starts again.

Documentation

Overview

Package oauthproxy lets preview and development deployments sign in with a provider through the one callback URL registered at the provider, better- auth's oauth-proxy plugin. A provider console takes a fixed list of callback URLs, and a preview deployment's URL is new every push; with this plugin the console lists only production's callback.

The flow, with the same plugin and the same secret on every deployment:

  1. On a preview, a provider wrapped by Wrap sends the browser to the provider with production's callback as redirect_uri and, as state, a sealed package naming the preview's own state and callback.
  2. Production's callback finds the package (a Before hook on the oauth plugin's callback operation), checks that the preview's origin is one it trusts, and redirects the browser to the preview's callback with the preview's state and the authorization code sealed for it. Production exchanges nothing and writes nothing.
  3. The preview's own oauth callback runs as always (flow cookie, state, account linking, sign-up rules); the wrapped provider opens the sealed code and exchanges it with the provider itself, with production's redirect_uri and the PKCE verifier that never left the preview.

What travels is an authorization code, not a profile: it is sealed (AES-256-GCM under a key derived from the shared secret, bound to the provider and the preview callback, valid MaxAge), and it is useless without the PKCE verifier only the preview holds. Whoever holds the secret can relay codes but cannot assert an identity to a deployment, as an encrypted-profile relay would allow. That design is available opt-in, with a warning at every start, as PassProfile.

Index

Constants

View Source
const (
	// DefaultMaxAge is how long a sealed state or code is accepted: a relay
	// takes a second; the provider sign-in between the two takes the state's
	// TTL, so the state gets StateMaxAge.
	//ds:def id=oauthproxy-defaultmaxage-4k8wq2nv owner=@khanakia stability=stable
	DefaultMaxAge = 60 * time.Second
	// StateMaxAge bounds a sealed state: the person signs in at the provider
	// between the start and production's callback, as long as the oauth
	// plugin's own state lives by default.
	//ds:def id=oauthproxy-statemaxage-7n2xk5qm owner=@khanakia stability=stable
	StateMaxAge = 10 * time.Minute
)

Defaults and formats.

View Source
const DefaultExchangeTimeout = 10 * time.Second

DefaultExchangeTimeout bounds production's code exchange under PassProfile when HTTPClient is not given.

View Source
const PluginName = "oauthproxy"

PluginName is the plugin's permanent identity.

View Source
const RelayErrorInvalidCode = "invalid_code"

RelayErrorInvalidCode is the error parameter production relays to the preview when, under PassProfile, its own code exchange failed: better- auth's invalid_code. The preview's oauth callback then answers oauth.provider_denied and redirects to the flow's error page.

View Source
const SkipHeader = "X-Skip-OAuth-Proxy"

SkipHeader on the request that starts a sign-in turns proxying off for it: any non-empty value. For a preview whose callback the provider does list, or a test.

View Source
const WarnPassProfile = "" /* 177-byte string literal not displayed */

WarnPassProfile is logged at every start under PassProfile.

Variables

View Source
var (
	// ErrNoProductionURL is a configuration error: ProductionURL is required.
	ErrNoProductionURL = errors.New("oauthproxy: ProductionURL is required and must be an absolute http(s) URL")
	// ErrNoSecret is a configuration error: neither WithSecret nor
	// auth.WithSecret was given, so nothing can be sealed.
	ErrNoSecret = errors.New("oauthproxy: pass oauthproxy.WithSecret (the same on every deployment) or auth.WithSecret")
	// ErrNotWrapped is a configuration error: the plugin is registered but
	// no provider was wrapped, so it can do nothing on a preview.
	ErrNotWrapped = errors.New("oauthproxy: wrap at least one oauth provider with Plugin.Wrap")

	// ErrInvalidState is a sealed state that does not open, is too old, or
	// names an untrusted preview: production refuses to relay it.
	ErrInvalidState = auth.NewError("oauthproxy.invalid_state", http.StatusBadRequest, "The sign-in could not be completed. Start again.")
	// ErrInvalidCode is a relayed code that does not open or is too old: the
	// preview refuses to exchange it.
	ErrInvalidCode = auth.NewError("oauthproxy.invalid_code", http.StatusBadRequest, "The sign-in could not be completed. Start again.")
	// ErrMissingProfile is missing_profile: under PassProfile
	// the preview's callback arrived with neither a sealed profile nor an
	// error. The oauth callback logs it and answers oauth.provider_failed.
	ErrMissingProfile = errors.New("oauthproxy: missing_profile: the relayed callback carries no profile")
)

Errors.

Functions

func DeploymentURL

func DeploymentURL(getenv func(string) string, fallback string) string

DeploymentURL infers this deployment's URL from the host's environment, for auth.WithBaseURL on a preview:

auth.WithBaseURL(oauthproxy.DeploymentURL(os.Getenv, "http://localhost:8080"))

getenv is passed in (os.Getenv in an app) so nothing is read behind the caller's back; fallback is returned when no variable holds a usable URL.

Types

type Option

type Option func(*Plugin)

Option configures the plugin.

func HTTPClient

func HTTPClient(hc *http.Client) Option

HTTPClient sets the client production exchanges codes with under PassProfile. Default: DefaultExchangeTimeout and no redirect followed, the oauth plugin's own rule for provider calls.

func MaxAge

func MaxAge(d time.Duration) Option

MaxAge overrides DefaultMaxAge for a relayed code.

func PassProfile

func PassProfile() Option

PassProfile is the encrypted-profile design, opt-in: production exchanges the authorization code itself, with production's redirect_uri and a PKCE verifier the preview sealed into the state, and relays the profile and the provider's tokens to the preview sealed (AES-256-GCM, bound to the provider and the preview callback, valid MaxAge). The preview's own callback opens it and signs in as always (flow cookie and state checked first, single use with the state). Use it when only production can exchange a code (a client secret production alone holds).

Risk, which is why it is off by default and Init logs WarnPassProfile at every start: a deployment that accepts a sealed profile trusts whoever holds the proxy secret to say who signed in. With the default relay, the secret lets someone relay codes but never assert an identity. Turn it on on every participating deployment; one without it refuses a state that asks production to exchange (invalid_state) and a relayed profile (invalid_code).

func ProductionCallback

func ProductionCallback(fn func(previewCallback string) string) Option

ProductionCallback overrides how production's callback URL is found from the preview's: by default the preview callback's path on the production origin, which holds when every deployment mounts the routes alike.

func ProductionURL

func ProductionURL(u string) Option

ProductionURL is the deployment whose callback URL the provider has. Sign-ins on that origin are not proxied.

func WithSecret

func WithSecret(current []byte, previous ...[]byte) Option

WithSecret sets the secret the proxy keys are derived from. It must be the same on every participating deployment; previous secrets still open values sealed under them. Without it the app's auth.WithSecret is used, which then must be shared too.

type Plugin

type Plugin struct {
	// contains filtered or unexported fields
}

Plugin is the proxy plugin. Build it with New, wrap providers with Wrap, and register it beside the oauth plugin on every deployment.

func New

func New(opts ...Option) *Plugin

New builds the plugin.

func (*Plugin) Init

func (p *Plugin) Init(a *auth.Auth) error

Init captures the core handle and its clock.

func (*Plugin) IsProduction

func (p *Plugin) IsProduction(callback string) bool

IsProduction reports whether a callback URL is on the production origin, where nothing is proxied.

func (*Plugin) Name

func (p *Plugin) Name() string

Name returns PluginName.

func (*Plugin) OperationHooks

func (p *Plugin) OperationHooks() []auth.OperationHook

OperationHooks adds the relay before the oauth callback of every wrapped provider.

func (*Plugin) OptionErr

func (p *Plugin) OptionErr() error

OptionErr is every error the options recorded, such as auth.ErrNilOption naming an option given nil; auth.New refuses to start while it is not nil (auth.OptionChecker).

func (*Plugin) Requires

func (p *Plugin) Requires() []string

Requires names the oauth plugin, whose callback the plugin relays.

func (*Plugin) Validate

func (p *Plugin) Validate(c *auth.Config) error

Validate refuses a configuration that cannot proxy.

func (*Plugin) Wrap

func (p *Plugin) Wrap(prov oauth.Provider) *Proxied

Wrap returns prov routed through production when the deployment is not production. Wrap every provider whose console lists only production's callback, on every deployment, before auth.New.

type Proxied

type Proxied struct {
	// contains filtered or unexported fields
}

Proxied is a provider wrapped by Wrap. On the production origin it is the provider itself; elsewhere it sends the sign-in through production. It forwards the provider's optional capabilities (discovery, issuer check, request parameters, form posts, refresh, revoke, profile reads, logout); an ID-token sign-in and a provider-initiated flow are not proxied, so a wrapped provider does not offer them.

func (*Proxied) ApplyPosted

func (x *Proxied) ApplyPosted(raw string, prof *oauth.Profile)

ApplyPosted applies a form-post user field, if the provider reads one.

func (*Proxied) AuthCodeURL

func (x *Proxied) AuthCodeURL(state, challenge, redirectURI string) string

AuthCodeURL is the provider's URL; off production it carries production's callback and a sealed state naming this deployment's state and callback.

func (*Proxied) AuthCodeURLForRequest

func (x *Proxied) AuthCodeURLForRequest(ctx context.Context, state, challenge, redirectURI string, rp oauth.RequestParams) string

AuthCodeURLForRequest is the oauth plugin's start: AuthCodeURL (with the request's parameters when the provider takes them), unproxied when the request carries SkipHeader.

func (*Proxied) AuthCodeURLWithParams

func (x *Proxied) AuthCodeURLWithParams(state, challenge, redirectURI string, rp oauth.RequestParams) string

AuthCodeURLWithParams is AuthCodeURL with request parameters, when the provider takes them.

func (*Proxied) Discover

func (x *Proxied) Discover(ctx context.Context, hc *http.Client) error

Discover runs the provider's discovery, if it has one.

func (*Proxied) EndSession

func (x *Proxied) EndSession(ctx context.Context, hc *http.Client) (string, error)

EndSession is the provider's logout URL, or "" for none.

func (*Proxied) Exchange

func (x *Proxied) Exchange(ctx context.Context, hc *http.Client, code, verifier, redirectURI string) (oauth.Profile, error)

Exchange trades the code; off production a sealed code is the one production relayed, opened and exchanged with production's callback.

func (*Proxied) ExpectedIssuer

func (x *Proxied) ExpectedIssuer() string

ExpectedIssuer is the provider's RFC 9207 issuer, or "" for none. Production relays iss, so the check runs on the preview unchanged.

func (*Proxied) FetchProfileWith

func (x *Proxied) FetchProfileWith(ctx context.Context, hc *http.Client, ts oauth.TokenSet) (oauth.Profile, error)

FetchProfileWith reads the profile, or answers oauth.ErrProfileUnsupported.

func (*Proxied) Label

func (x *Proxied) Label() string

Label is the provider's label, or "" (the oauth plugin then shows Name).

func (*Proxied) Load

func (x *Proxied) Load(ctx context.Context, hc *http.Client) error

Load runs the provider's loader, if it has one.

func (*Proxied) Name

func (x *Proxied) Name() string

Name is the provider's name.

func (*Proxied) OptionalScopeList

func (x *Proxied) OptionalScopeList() []string

OptionalScopeList is the provider's optional scopes, or none.

func (*Proxied) PostsBack

func (x *Proxied) PostsBack() bool

PostsBack reports whether the provider answers with a form post.

func (*Proxied) Refresh

func (x *Proxied) Refresh(ctx context.Context, hc *http.Client, rt auth.Token) (oauth.TokenSet, error)

Refresh refreshes with the provider, or fails for one that cannot.

func (*Proxied) Revoke

func (x *Proxied) Revoke(ctx context.Context, hc *http.Client, ts oauth.TokenSet) error

Revoke revokes at the provider, or does nothing for one with no endpoint.

func (*Proxied) Unwrap

func (x *Proxied) Unwrap() oauth.Provider

Unwrap returns the wrapped provider.

Directories

Path Synopsis
Package oauthpopup runs a provider sign-in in a popup and hands the new session to the page that opened it.
Package oauthpopup runs a provider sign-in in a popup and hands the new session to the page that opened it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL