oauth

package
v0.167.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package oauth signs Caprock Mail into Google and Microsoft accounts the way an installed app should (RFC 8252): the authorization code flow with PKCE (RFC 7636, S256) in the user's own browser, redirected back to the daemon on loopback. The result is a refresh token, kept in the mail secret store like a password, and short-lived access tokens that sign in to IMAP and SMTP with SASL XOAUTH2.

Nothing here talks to the network until the user clicks "Sign in with Google/Microsoft": the authorization code and the PKCE verifier go to that provider's token endpoint, and later the refresh token goes to the same endpoint to get a new access token (ADR-057).

Client IDs are the app registrations the Caprock owner makes (docs/mail-oauth.md). They come from the environment, else from package variables set at build time with -ldflags -X; a provider without one is reported unavailable and nothing else changes.

Index

Constants

View Source
const AuthPrefix = "oauth2:"

AuthPrefix marks an account that signs in with OAuth: its auth is "oauth2:google" or "oauth2:microsoft".

View Source
const CallbackPath = "/v1/mail/oauth/callback"

CallbackPath is where the provider sends the browser back.

View Source
const XOAuth2Mech = "XOAUTH2"

XOAuth2Mech is the mechanism name.

Variables

View Source
var (
	GoogleClientID     string
	GoogleClientSecret string
	MicrosoftClientID  string
)

Build-time client IDs, set with

-X github.com/dspv/caprock/internal/mail/oauth.GoogleClientID=...

Empty by default: the provider is then unavailable unless the environment names one (CAPROCK_MAIL_GOOGLE_CLIENT_ID and so on).

Google's "client secret" for a Desktop app client is not a secret: Google says installed apps cannot keep one ("it is assumed that these apps cannot keep secrets", developers.google.com/identity/protocols/oauth2/native-app), yet its token endpoint still wants it for that client type.

View Source
var ErrSignInAgain = errors.New("sign in again")

ErrSignInAgain means the refresh token no longer works (revoked, expired, password changed): only a new sign-in in the browser helps.

View Source
var Google = Provider{
	Name:     "google",
	Label:    "Google",
	AuthURL:  "https://accounts.google.com/o/oauth2/v2/auth",
	TokenURL: "https://oauth2.googleapis.com/token",

	RevokeURL:    "https://oauth2.googleapis.com/revoke",
	Scopes:       []string{"https://mail.google.com/", "openid", "email"},
	Extra:        map[string]string{"access_type": "offline", "prompt": "consent"},
	RedirectHost: "127.0.0.1",
	IMAPHost:     "imap.gmail.com", IMAPPort: 993, IMAPTLS: "tls",
	SMTPHost: "smtp.gmail.com", SMTPPort: 465, SMTPTLS: "tls",
	// contains filtered or unexported fields
}

Google: endpoints and parameters from developers.google.com/identity/protocols/oauth2/native-app (auth https://accounts.google.com/o/oauth2/v2/auth, token https://oauth2.googleapis.com/token, loopback redirect, PKCE S256) and developers.google.com/identity/protocols/oauth2/web-server (access_type= offline, prompt=consent so a refresh token comes back on a repeat sign-in). IMAP and SMTP need the scope https://mail.google.com/ (developers.google.com/workspace/gmail/imap/xoauth2-protocol).

View Source
var HTTPClient = &http.Client{Timeout: 20 * time.Second}

HTTPClient is used for every token request; tests may replace it.

View Source
var Microsoft = Provider{
	Name:     "microsoft",
	Label:    "Microsoft",
	AuthURL:  "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
	TokenURL: "https://login.microsoftonline.com/common/oauth2/v2.0/token",
	Scopes: []string{"https://outlook.office.com/IMAP.AccessAsUser.All", "https://outlook.office.com/SMTP.Send",
		"offline_access", "openid", "email"},
	Extra:        map[string]string{"prompt": "select_account"},
	RedirectHost: "localhost",
	IMAPHost:     "outlook.office365.com", IMAPPort: 993, IMAPTLS: "tls",
	SMTPHost: "smtp.office365.com", SMTPPort: 587, SMTPTLS: "starttls",
	// contains filtered or unexported fields
}

Microsoft: the v2.0 endpoints on the "common" tenant, so both personal (Outlook.com) and work accounts sign in (learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow). Scopes and servers from learn.microsoft.com/exchange/client-developer/ legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth: https://outlook.office.com/IMAP.AccessAsUser.All, .../SMTP.Send, and offline_access for a refresh token; outlook.office365.com:993 and smtp.office365.com:587 with STARTTLS. A public client sends no secret. The Microsoft identity platform has no endpoint for an app to revoke its own refresh token (only Graph's revokeSignInSessions, which signs the user out of every app and device), so RevokeURL stays empty and removing the account says where the user takes the access back.

View Source
var Names = []string{"google", "microsoft"}

Names lists the providers in the order the screen offers them.

Functions

func AccessToken

func AccessToken(ctx context.Context, provider, refresh string) (string, string, error)

AccessToken returns a usable access token for a refresh token, refreshing when the cached one is within a minute of expiry. The second result is the refresh token to keep from now on (Microsoft rotates them); it equals the one passed in when nothing changed.

func Available

func Available() map[string]bool

Available reports which providers have a client ID.

func Challenge

func Challenge(verifier string) string

Challenge is the S256 PKCE challenge of a verifier (RFC 7636 §4.2).

func EmailFromIDToken

func EmailFromIDToken(idToken string) (string, error)

EmailFromIDToken reads the address from an ID token's claims: "email", else Microsoft's "preferred_username" when it is an address.

The signature is not checked: the token came straight from the provider's token endpoint over TLS, which OpenID Connect Core 1.0 §3.1.3.7 allows in place of checking the signature ("the TLS server validation MAY be used to validate the issuer"). The address is then proven by the IMAP sign-in.

func Forget

func Forget(refresh string)

Forget drops a cached access token, after a server refused it.

func ParseXOAuth2

func ParseXOAuth2(resp []byte) (user, token string, err error)

ParseXOAuth2 splits an XOAUTH2 initial response; for test servers.

func ProviderOf

func ProviderOf(auth string) string

ProviderOf returns the provider name of an account's auth value, or "" for a password account.

func RandomString

func RandomString(n int) string

RandomString is n random bytes, base64url without padding.

func Remember

func Remember(t Token)

Remember caches a fresh token's access token under its refresh token.

func XOAuth2

func XOAuth2(user, token string) sasl.Client

XOAuth2 is the SASL XOAUTH2 client: "user=" email ^A "auth=Bearer " token ^A^A (developers.google.com/workspace/gmail/imap/xoauth2-protocol; the same format at Microsoft). On failure the server sends a JSON error as a challenge, which is answered with an empty response, and then refuses.

Types

type Provider

type Provider struct {
	Name     string // "google" | "microsoft"
	Label    string // "Google", for messages
	AuthURL  string
	TokenURL string
	// RevokeURL takes a token back (RFC 7009) when the account is removed;
	// "" for a provider that offers apps no way to (Microsoft).
	RevokeURL string
	Scopes    []string
	Extra     map[string]string // added to the authorization URL
	// RedirectHost is the loopback name in the redirect URI. Google's desktop
	// clients accept http://127.0.0.1:<any port>/<any path>; Microsoft
	// ignores the port only for "localhost", and an http 127.0.0.1 redirect
	// cannot be registered in the Azure portal, so it gets localhost.
	RedirectHost string

	IMAPHost string
	IMAPPort int
	IMAPTLS  string
	SMTPHost string
	SMTPPort int
	SMTPTLS  string

	// Resolved per call by Lookup.
	ClientID     string
	ClientSecret string
	// contains filtered or unexported fields
}

Provider is one OAuth identity provider and the mail servers its tokens open.

func Lookup

func Lookup(name string) (Provider, bool)

Lookup returns a provider with its client ID resolved. ok is false for an unknown name; an unconfigured provider comes back with an empty ClientID.

func (Provider) AuthCodeURL

func (p Provider) AuthCodeURL(state, verifier, redirect string) string

AuthCodeURL is the page the user's browser opens.

func (Provider) AuthCodeURLHint added in v0.117.2

func (p Provider) AuthCodeURLHint(state, verifier, redirect, hint string) string

AuthCodeURLHint is AuthCodeURL starting on the account hint names, when it names one: login_hint is honoured by both Google and Microsoft.

func (Provider) Exchange

func (p Provider) Exchange(ctx context.Context, code, verifier, redirect string) (Token, error)

Exchange trades an authorization code for tokens.

func (Provider) RedirectURI

func (p Provider) RedirectURI(port string) string

RedirectURI is the callback address for a daemon listening on port.

func (Provider) Refresh

func (p Provider) Refresh(ctx context.Context, refresh string) (Token, error)

Refresh gets a new access token. A refresh token the provider refuses is ErrSignInAgain.

func (Provider) Revoke added in v0.133.0

func (p Provider) Revoke(ctx context.Context, refresh string) (ok bool, err error)

Revoke takes a refresh token back at the provider (RFC 7009), so removing an account in Mail also ends Caprock's access there. ok is false when the provider has no revocation endpoint. A token the provider already considers invalid counts as revoked: either way it no longer works.

At Google a refresh token stands for the whole grant: the user's other Caprock installs signed in with the same build's client lose access too.

type Token

type Token struct {
	AccessToken  string
	RefreshToken string
	IDToken      string
	Expiry       time.Time
}

Token is what the token endpoint answers.

Directories

Path Synopsis
Package oauthtest is a fake OAuth provider for tests: an authorization step that stands in for the user's browser, and a token endpoint that checks PKCE, issues ID tokens and refreshes.
Package oauthtest is a fake OAuth provider for tests: an authorization step that stands in for the user's browser, and a token endpoint that checks PKCE, issues ID tokens and refreshes.

Jump to

Keyboard shortcuts

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