oauthtest

package
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: 21 Imported by: 0

README

github.com/ubgo/auth/plugin/oauth/oauthtest

A conformance kit for oauth.Provider implementations. One call drives the provider against a fake authorization server and checks every rule the OAuth plugin relies on, so a provider written for one app, a preset, or an adapter over another OAuth library proves itself in a test rather than in production.

Install

go get github.com/ubgo/auth

The package is part of the core module and imports only the standard library, the core and plugin/oauth, so a provider's tests can use it from any module.

Use it

oauthtest.Run(t, newProvider, opts...) starts the server and calls newProvider(serverURL) once per case. Build the provider with oauthtest.ClientID, oauthtest.ClientSecret and the server's endpoints; the kit passes oauthtest.RedirectURI to AuthCodeURL and Exchange, and a provider that fixes its own redirect URI (goth) is built with that value.

TestConformance_OAuth2UserInfo · plugin/oauth/oauthtest/providers_test.go:76-81

func TestConformance_OAuth2UserInfo(t *testing.T) {
	oauthtest.Run(t, func(u string) oauth.Provider {
		return pointAt(&oauth.OAuth2{ID: "corp", ClientID: oauthtest.ClientID, ClientSecret: oauthtest.ClientSecret, Scopes: []string{"openid", "email"},
			FetchProfile: oauth.UserInfoProfile(u+oauthtest.UserInfoPath, "")}, u)
	}, oauthtest.WantScopes("openid", "email"))
}

An OpenID Connect provider takes the server URL as its issuer (oauth.OIDC("corp", u, oauthtest.ClientID, oauthtest.ClientSecret)); the discovery document at DiscoveryPath names every endpoint. A provider whose profile API is not userinfo adds the endpoints it calls with Route and renders the person the way its API does; providers_test.go does that for GitHub, Discord and Zoom:

TestConformance_GitHub · plugin/oauth/oauthtest/providers_test.go:61-73

func TestConformance_GitHub(t *testing.T) {
	oauthtest.Run(t, func(u string) oauth.Provider {
		g := pointAt(oauth.GitHub(oauthtest.ClientID, oauthtest.ClientSecret), u)
		g.FetchProfile = oauth.GitHubProfile(u + "/github")
		return g
	}, oauthtest.WantScopes("user:email"),
		oauthtest.Route("/github/user", func(p oauthtest.Person) any {
			return numericID(map[string]any{"login": "octo", "name": p.Name}, p.Subject)
		}),
		oauthtest.Route("/github/user/emails", func(p oauthtest.Person) any {
			return []map[string]any{{"email": "old@example.com", "primary": false, "verified": true}, {"email": p.Email, "primary": true, "verified": p.EmailVerified}}
		}))
}

The server

Path Constant Answers
/.well-known/openid-configuration DiscoveryPath the discovery document; the server URL is the issuer
/authorize AuthorizePath a 302 to the redirect URI with a code and the state, after checking response_type=code, the client id, the redirect URI, a state and (when sent) an S256 challenge; 400 with the reason otherwise
/token TokenPath the authorization_code grant: the client secret in the form or as HTTP Basic (the id alone under PublicClient), a single-use code, the same redirect URI and the PKCE verifier when a challenge was sent; an id_token (ES256) when openid was granted, with the nonce the request sent
/userinfo UserInfoPath sub, email, email_verified and name of the bearer token's person
/jwks JWKSPath the ID-token key

The rules

Case What the provider must do
the name is a route segment Name() matches auth.KindNamePattern
the authorization URL carries the client, redirect, state, scope and PKCE challenge the server's authorization endpoint, response_type=code, ClientID, RedirectURI, the state it was given, every scope WantScopes names, and code_challenge = the challenge it was given with method S256
a verified address signs in with the subject, email and verified flag the subject and email exactly, EmailVerified true, and the issued access token in Profile.Tokens
an unverified address is never reported verified EmailVerified false when the server said false
the token endpoint's error answer is an error an unknown or reused code (invalid_grant) fails
a wrong PKCE verifier is refused the verifier it was given is the one sent
a token answer that is not JSON is an error an HTML answer fails
a token answer without an access token is an error {"token_type":"Bearer"} fails
a failing profile endpoint is an error a 500 from the profile endpoint fails; skipped for a provider that reads its profile from the ID token
a profile without a subject is refused an answer with no subject fails, so no account is keyed on ""

Options

Option Effect
WantScopes(scopes...) the authorization URL must carry each one; without it the scope is not checked (Zoom sets scopes on the app)
NoPKCE() for a provider that cannot send a challenge: the URL must then carry none (so the declaration cannot go stale), the verifier case is skipped, Report.PKCE is false and the run logs it
NeverVerified() for a provider whose API says nothing about verification: EmailVerified must be false even for a verified person
PublicClient() the token endpoint expects the client id and no secret
Route(path, render) an extra bearer-protected GET profile endpoint answering render(person) as JSON; leave the subject out when Person.Subject is ""

Run returns a Report (Provider, PKCE, ReportsVerified, ProfileCall) and logs it, so a provider's weaker guarantees show in the test output.

Tests

The kit is itself tested by breaking it: oauthtest_test.go runs every case against providers that each break one rule (another client id, a dropped state, no challenge, a stale NoPKCE, a verified claim for an unverified address, a swallowed error, a missing access token) and asserts which case refuses it and why; TestServer_Refusals checks the server's own refusals directly.

Run against Test
oauth.Google, oauth.GitHub, *oauth.OAuth2 (userinfo, ID-token profile, public client), oauth.OIDC, oauth.Okta, oauth.Keycloak, oauth.GitLab, oauth.Zitadel, oauth.Discord, oauth.Zoom providers_test.go
any goth provider through authgoth.Wrap contrib/goth

Documentation

Overview

Package oauthtest checks an oauth.Provider against the contract the oauth plugin relies on, by driving it against a fake authorization server it starts. A provider written for one app, a preset, or an adapter over another OAuth library proves itself with one call rather than by finding out in production which rule it broke. The plugin's own Google, GitHub, OAuth2, OIDC and preset providers and contrib/goth all run it.

What a provider must do, case by case:

  • build an authorization URL on the server's AuthorizePath carrying response_type=code, ClientID, RedirectURI, the state, the scopes WantScopes names and the S256 PKCE challenge it was given;
  • exchange the code for the person's profile: the subject, the email, and the email verified flag exactly as the provider reported it (or never verified, with NeverVerified), plus the issued access token;
  • turn every failure into an error: the token endpoint's error answer, a wrong PKCE verifier, a token answer that is not JSON or has no access token, a failing profile endpoint, and a profile without a subject.

It imports only the standard library, the core and plugin/oauth, so a provider's own tests can use it whatever else they depend on.

Index

Constants

View Source
const (
	// AuthorizePath is the authorization endpoint. It answers a valid
	// request with a 302 to the redirect URI carrying a code, as a provider
	// does once the person has consented.
	AuthorizePath = "/authorize"
	// TokenPath is the token endpoint (authorization_code grant only).
	TokenPath = "/token"
	// UserInfoPath is the OpenID Connect userinfo endpoint: sub, email,
	// email_verified and name of the person behind the bearer token.
	UserInfoPath = "/userinfo"
	// JWKSPath publishes the key the ID tokens are signed with (ES256).
	JWKSPath = "/jwks"
	// DiscoveryPath is the OpenID Connect discovery document; the server
	// URL is the issuer.
	DiscoveryPath = "/.well-known/openid-configuration"
)

The fake authorization server's endpoints, relative to the server URL a provider factory receives. The discovery document at DiscoveryPath names them too, so an OpenID Connect provider needs only the server URL as its issuer.

View Source
const (
	// ClientID is the client id the server knows.
	ClientID = "oauthtest-client"
	// ClientSecret is that client's secret, checked at the token endpoint
	// in the form body or as HTTP Basic, unless PublicClient is given.
	ClientSecret = "oauthtest-secret"
	// RedirectURI is the redirect URI the kit passes to AuthCodeURL and
	// Exchange; a provider that sends another (goth's fixed callback URL)
	// is refused at the authorization endpoint.
	RedirectURI = "https://app.example/auth/oauth/callback"
)

The credentials and redirect URI the provider under test must be built with. Fixed values rather than parameters, so the factory signature stays one argument and every provider is checked against the same expectations.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

type Option func(*config)

Option adjusts what Run expects of the provider.

func NeverVerified

func NeverVerified() Option

NeverVerified declares that the provider reports every address as unverified, because its API says nothing about verification. The verified case then requires EmailVerified false; a provider must never claim more than its server said.

func NoPKCE

func NoPKCE() Option

NoPKCE declares that the provider cannot send a PKCE challenge (an adapter over a library whose authorization URL takes none). The URL is then required to carry NO challenge, so the declaration cannot go stale silently, the wrong-verifier case is skipped, and Report.PKCE is false. The oauth plugin always generates a verifier; such a provider simply does not use it, and the flow rests on the state alone.

func PublicClient

func PublicClient() Option

PublicClient makes the token endpoint expect the client id alone, with no secret, for a provider built with oauth.PublicClient.

func Route

func Route(path string, render func(Person) any) Option

Route adds a GET profile endpoint at path that answers render(person) as JSON to the holder of an access token the server issued, for a provider whose profile API is not OpenID Connect userinfo (GitHub's /user and /user/emails, Discord's /users/@me). render must leave the subject out when Person.Subject is "", which is how the missing-subject case reaches the provider.

func WantScopes

func WantScopes(scopes ...string) Option

WantScopes makes the authorization URL carry every one of scopes in its space-separated scope parameter. Without it the scope is not checked, since some providers (Zoom) configure scopes on the app, not the URL.

type Person

type Person struct {
	// Subject is the server's stable id for the person; "" in the case
	// that proves a profile without one is refused. Numeric, so a provider
	// that parses its subject as a number (GitHub) can be checked.
	Subject string
	Email   string
	// EmailVerified is the server's claim that the person controls Email.
	EmailVerified bool
	Name          string
}

Person is who signs in at the fake server in a case: what the provider reads back and must map onto oauth.Profile.

type Report

type Report struct {
	// Provider is the provider's Name.
	Provider string
	// PKCE says the authorization URL carried the S256 challenge and the
	// token request the verifier. False only under NoPKCE.
	PKCE bool
	// ReportsVerified says the provider passed the server's email_verified
	// claim through. False only under NeverVerified, where every address is
	// treated as unverified.
	ReportsVerified bool
	// ProfileCall says the provider read the profile from an endpoint (the
	// userinfo or a Route) rather than only from the ID token; the failing
	// profile endpoint case runs only when it did.
	ProfileCall bool
}

Report is what Run learned about the provider, for the test to assert or log. Run also logs it, so a provider's weaker guarantees (no PKCE) appear in the test output rather than only in its documentation.

func Run

func Run(t *testing.T, newProvider func(serverURL string) oauth.Provider, opts ...Option) Report

Run checks the provider that newProvider builds against a fake authorization server at the URL it is given. newProvider is called once per case, so a provider that caches (discovery) starts fresh; it must use ClientID, ClientSecret (unless PublicClient), RedirectURI as its redirect where it fixes one, and the server's endpoints (AuthorizePath, TokenPath, UserInfoPath, Route paths, or the URL itself as an OpenID Connect issuer).

type T

type T interface {
	Helper()
	Fatalf(format string, args ...any)
	Logf(format string, args ...any)
}

T is the part of testing.T a case uses. An interface so the kit's own tests can run a case against a provider that breaks a rule and read the failure, which is how the kit proves it would catch that rule.

Jump to

Keyboard shortcuts

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