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
- Variables
- func AccessToken(ctx context.Context, provider, refresh string) (string, string, error)
- func Available() map[string]bool
- func Challenge(verifier string) string
- func EmailFromIDToken(idToken string) (string, error)
- func Forget(refresh string)
- func ParseXOAuth2(resp []byte) (user, token string, err error)
- func ProviderOf(auth string) string
- func RandomString(n int) string
- func Remember(t Token)
- func XOAuth2(user, token string) sasl.Client
- type Provider
- func (p Provider) AuthCodeURL(state, verifier, redirect string) string
- func (p Provider) AuthCodeURLHint(state, verifier, redirect, hint string) string
- func (p Provider) Exchange(ctx context.Context, code, verifier, redirect string) (Token, error)
- func (p Provider) RedirectURI(port string) string
- func (p Provider) Refresh(ctx context.Context, refresh string) (Token, error)
- func (p Provider) Revoke(ctx context.Context, refresh string) (ok bool, err error)
- type Token
Constants ¶
const AuthPrefix = "oauth2:"
AuthPrefix marks an account that signs in with OAuth: its auth is "oauth2:google" or "oauth2:microsoft".
const CallbackPath = "/v1/mail/oauth/callback"
CallbackPath is where the provider sends the browser back.
const XOAuth2Mech = "XOAUTH2"
XOAuth2Mech is the mechanism name.
Variables ¶
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.
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.
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).
var HTTPClient = &http.Client{Timeout: 20 * time.Second}
HTTPClient is used for every token request; tests may replace it.
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.
var Names = []string{"google", "microsoft"}
Names lists the providers in the order the screen offers them.
Functions ¶
func AccessToken ¶
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 EmailFromIDToken ¶
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 ¶
ParseXOAuth2 splits an XOAUTH2 initial response; for test servers.
func ProviderOf ¶
ProviderOf returns the provider name of an account's auth value, or "" for a password account.
func RandomString ¶
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 ¶
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 ¶
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 ¶
AuthCodeURL is the page the user's browser opens.
func (Provider) AuthCodeURLHint ¶ added in v0.117.2
AuthCodeURLHint is AuthCodeURL starting on the account hint names, when it names one: login_hint is honoured by both Google and Microsoft.
func (Provider) RedirectURI ¶
RedirectURI is the callback address for a daemon listening on port.
func (Provider) Refresh ¶
Refresh gets a new access token. A refresh token the provider refuses is ErrSignInAgain.
func (Provider) Revoke ¶ added in v0.133.0
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.
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. |