auth

package
v1.40.1 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 24 Imported by: 1 module, 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 auth holds the provider table and account auto-detection.

Index

Constants

View Source
const (
	IMAP = "imap"
	SMTP = "smtp"
	JMAP = "jmap"
	POP3 = "pop3"
	// EWS is both slots of an on-premises Exchange account (Exchange Web
	// Services); no provider has an entry for it.
	EWS = "ews"
	// Graph is both slots of a Microsoft Graph account, or the sending slot of
	// an account whose SMTP AUTH is disabled (OAuthConfig.GraphSend).
	Graph = "graph"
	// GmailAPI is both slots of a Gmail account using the Gmail REST API.
	GmailAPI = "gmailapi"
)

Protocols of a provider's entries and of an account's server slots.

View Source
const (
	GraphMailSend      = "https://graph.microsoft.com/Mail.Send"
	GraphMailReadWrite = "https://graph.microsoft.com/Mail.ReadWrite"
)

GraphMailSend and GraphMailReadWrite are Microsoft Graph's delegated permissions to send mail and to read and write mail as the user.

Variables

View Source
var (
	// ErrNotClientFile: the file is not a Google OAuth client file.
	ErrNotClientFile = errors.New("oauth: not an OAuth client file")
	// ErrWebClient: the file is a Web application client's, which cannot take
	// the sign-in on a loopback address as a Desktop app client can.
	ErrWebClient = errors.New("oauth: a web application client, not a desktop app one")
)
View Source
var (
	// ErrOAuthNotConfigured: the provider has no OAuth client ID in this build.
	ErrOAuthNotConfigured = errors.New("oauth: no client ID is configured for this provider")
	ErrRedirectPortBusy   = errors.New("oauth: the sign-in's callback port is already in use")
	// ErrFlowExpired: the user did not finish signing in within FlowTimeout.
	ErrFlowExpired = errors.New("oauth: sign-in timed out")
	// ErrInvalidGrant: the token endpoint answered invalid_grant (revoked, expired or used).
	ErrInvalidGrant = errors.New("oauth: the authorization is no longer valid")
	// ErrInvalidClient: the token endpoint answered invalid_client (an unknown client, or a wrong secret).
	ErrInvalidClient = errors.New("oauth: the token endpoint does not accept this client (invalid_client)")
)
View Source
var ErrAccessDenied = errors.New("oauth: access was denied at the provider")

ErrAccessDenied: the user declined at the provider.

View Source
var ErrScopeMissing = errors.New("oauth: the sign-in did not grant the access this app needs")

ErrScopeMissing: the token response did not include the required scope.

View Source
var FlowTimeout = 10 * time.Minute

FlowTimeout bounds an authorization flow from StartFlow to the callback.

View Source
var MicrosoftClientID = "13d71f3b-e47d-4cf4-a28d-25f01bae45d4"

MicrosoftClientID is Godwit's public client in Microsoft Entra (no secret; PKCE with a loopback redirect). It is read when the outlook provider is built.

Functions

func Detect

func Detect(ctx context.Context, r Resolver, email string) (Provider, Source, error)

Detect finds the provider for email: domain table, then the providers we sign in to by MX, then the mailservers database by domain and by MX, then SRV, then a guess. DNS errors fall through; only a malformed address is an error.

func ParseClientFile added in v1.22.0

func ParseClientFile(data []byte) (id, secret string, err error)

ParseClientFile reads the client_secret_….json Google Cloud offers for an OAuth client: a Desktop app client's ID and secret. Errors carry nothing from the file, whose secret is a credential.

Types

type DeviceFlow added in v1.1.0

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

DeviceFlow is one RFC 8628 device-authorization flow, polling the token endpoint while the user approves the code in a browser.

func StartDevice added in v1.1.0

func StartDevice(ctx context.Context, cfg OAuthConfig, hc *http.Client) (*DeviceFlow, error)

StartDevice requests a device code at cfg.DeviceURL and starts polling cfg.TokenURL in the background.

func (*DeviceFlow) AuthURL added in v1.1.0

func (f *DeviceFlow) AuthURL() string

AuthURL is the verification URL (verification_uri_complete when given, else verification_uri).

func (*DeviceFlow) Close added in v1.1.0

func (f *DeviceFlow) Close()

Close cancels polling; a pending Wait returns context.Canceled.

func (*DeviceFlow) UserCode added in v1.1.0

func (f *DeviceFlow) UserCode() string

UserCode is the short code shown to the user.

func (*DeviceFlow) Wait added in v1.1.0

func (f *DeviceFlow) Wait(ctx context.Context) (Grant, error)

Wait blocks until the device flow finishes or ctx is done, then closes the flow.

type Entry added in v1.33.0

type Entry struct {
	Protocol string
	Server
	Login string // app_password | authorization_code | client_password | password | oauth | api_token
}

Entry is one way to a provider's mail: a protocol, its server and the sign-in it takes.

func IMAPSMTP added in v1.33.0

func IMAPSMTP(imap, smtp Server, login string) []Entry

IMAPSMTP is the IMAP and SMTP entries of a provider, both signing in with login.

type Flow

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

Flow is one authorization-code flow with PKCE, waiting for the browser on a loopback listener.

func StartFlow

func StartFlow(cfg OAuthConfig, loginHint string, hc *http.Client) (*Flow, error)

StartFlow listens on 127.0.0.1 for the redirect and builds the authorization URL. The listener closes when the flow ends: callback handled, Wait's ctx done, FlowTimeout passed or Close.

func (*Flow) AuthURL

func (f *Flow) AuthURL() string

AuthURL is the address to open in the user's browser.

func (*Flow) Close

func (f *Flow) Close()

Close ends the flow (a pending Wait returns context.Canceled) and releases the listener.

func (*Flow) Wait

func (f *Flow) Wait(ctx context.Context) (Grant, error)

Wait returns the grant once the browser came back and the code was exchanged, or the flow's error. The listener is closed when it returns.

type Grant

type Grant struct {
	Email, RefreshToken, AccessToken string
	Expiry                           time.Time
	ClientID, Scope                  string // ClientID is only set for DynamicClient flows
}

Grant is the outcome of an authorization or a refresh. Secrets: never log it. Expiry is never zero: without expires_in it is 30 minutes after receipt.

func Refresh

func Refresh(ctx context.Context, cfg OAuthConfig, hc *http.Client, refreshToken string) (Grant, error)

Refresh trades refreshToken for a new access token. Grant.RefreshToken is "" unless the server rotated it; Grant.Email is "" without an id_token.

func RefreshForm added in v1.1.0

func RefreshForm(ctx context.Context, cfg OAuthConfig, hc *http.Client, refreshToken string) (Grant, error)

RefreshForm trades refreshToken for a new access token with a form POST that includes cfg.TokenParams. Grant.RefreshToken is "" unless the server rotated it.

type OAuthConfig

type OAuthConfig struct {
	ClientID, AuthURL, TokenURL string
	ClientSecret                string // a user's own client only (Google's desktop clients need one); never log it
	Scopes                      []string
	RedirectHost, RedirectPath  string            // "" = "localhost", "/callback"
	RedirectPort                int               // 0 = any free port; a client registered with one fixed port needs it
	AuthParams, TokenParams     map[string]string // extra authorize / token & refresh parameters
	DynamicClient               bool              // callback carries client_id; use it afterwards
	NoPrompt                    bool              // omit prompt=select_account
	Nonce                       bool              // send a random nonce on authorize
	RequireScope                string            // non-empty: token response scope must include it
	DeviceURL                   string            // non-empty: device-code flow
	Public                      *PublicClient     // with no ClientID: another app's verified client, offered beside the user's own
	// GraphSend non-empty: the Microsoft Graph scope that sends mail, also in Scopes;
	// a mailbox whose SMTP AUTH is disabled sends through Graph with a token for it.
	GraphSend string
	// GraphRead non-empty: the Microsoft Graph scope that reads and writes mail, also in Scopes;
	// a Graph receiving account syncs with a token for it.
	GraphRead string
}

OAuthConfig describes a provider's OAuth 2.0 endpoints (flow lives elsewhere).

func GoogleCardDAVOAuth added in v1.36.0

func GoogleCardDAVOAuth() OAuthConfig

GoogleCardDAVOAuth returns the OAuth 2.0 configuration for Google's standard CardDAV endpoint (kept out of ListProviders, which lists mail providers only).

type Provider

type Provider struct {
	ID, Name string
	Domains  []string
	Entries  []Entry
	HelpURL  string
	Username string // when the servers want something other than the address
	OAuth    *OAuthConfig
}

Provider is a known mail service. Entries lists its protocols in order of preference, one each; HelpURL is about the sign-in of its IMAP and SMTP.

func ByID

func ByID(id string) (Provider, bool)

func ListProviders

func ListProviders() []Provider

ListProviders returns the known providers in display order (no "other").

func (Provider) Entry added in v1.33.0

func (p Provider) Entry(protocol string) Entry

Entry returns p's entry for protocol, the zero Entry if it has none.

type PublicClient added in v1.22.0

type PublicClient struct{ ID, Secret string }

PublicClient is a desktop client another app registered and the provider verified, whose ID and secret that app publishes; signing in with it, the consent page names that app, not Godwit.

type Resolver

type Resolver interface {
	LookupMX(ctx context.Context, name string) ([]*net.MX, error)
	LookupSRV(ctx context.Context, service, proto, name string) (string, []*net.SRV, error)
}

Resolver is satisfied by *net.Resolver.

type Server

type Server struct {
	Host     string
	Port     int
	Security conn.Security
}

type Source

type Source string
const (
	SourceDomain Source = "domain"
	SourceMX     Source = "mx"
	SourceSRV    Source = "srv"
	SourceGuess  Source = "guess"
)

Jump to

Keyboard shortcuts

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