Documentation
¶
Overview ¶
Package auth authenticates the dispatcher's API callers (design/workstreams/dispatcher-runtime/ LLD/api-server.md §Auth):
- agents: `Authorization: Bearer <agentToken>`, checked by the scheduler;
- the CLI: `Authorization: Bearer <cliToken>`, a static token compared in constant time;
- the web UI: the GitHub OAuth web flow, then a server-side session cookie (`HttpOnly`, `Secure`, `SameSite=Lax`, 12 h). Reading needs the readers Group (or the admin Group); commands need the admin Group (`maintainers`), resolved through Conn.ResolveGroup and cached;
No token, code or cookie value is ever logged or stored in clear: sessions are stored by the hash of their id, and GitHub user tokens are dropped as soon as the login is known.
Index ¶
- Constants
- Variables
- func BearerToken(r *http.Request) string
- func SafeReturnTo(s string) (string, error)
- func WithPrincipal(ctx context.Context, p Principal) context.Context
- type AgentAuthenticator
- type Authenticator
- func (a *Authenticator) Agent(ctx context.Context, r *http.Request) (Principal, error)
- func (a *Authenticator) BeginLogin(ctx context.Context, returnTo string) (string, *http.Cookie, error)
- func (a *Authenticator) CLI(r *http.Request) (Principal, bool)
- func (a *Authenticator) FinishLogin(ctx context.Context, r *http.Request, code, state string) (*Login, error)
- func (a *Authenticator) IsAdmin(ctx context.Context, u *User) (bool, error)
- func (a *Authenticator) IsCLIToken(tok string) bool
- func (a *Authenticator) IsReader(ctx context.Context, u *User) (bool, error)
- func (a *Authenticator) Logout(ctx context.Context, r *http.Request) (*http.Cookie, error)
- func (a *Authenticator) Provider() string
- func (a *Authenticator) Run(ctx context.Context, r *http.Request) (Principal, error)
- func (a *Authenticator) Session(ctx context.Context, r *http.Request) (*User, error)
- func (a *Authenticator) SweepUsedStates(ctx context.Context) (int, error)
- type Config
- type Deps
- type Kind
- type Login
- type OAuthConfig
- type Principal
- type Session
- type UsedLoginState
- type User
Constants ¶
const ( DefaultSessionTTL = 12 * time.Hour DefaultStateTTL = 10 * time.Minute DefaultGroupCacheTTL = 10 * time.Minute DefaultAdminGroup = "maintainers" DefaultReadersGroup = "readers" DefaultAuthorizeURL = "https://github.com/login/oauth/authorize" DefaultTokenURL = "https://github.com/login/oauth/access_token" DefaultAPIBase = "https://api.github.com" )
Defaults for Config.
const ( // SessionCookie is the UI session (the spec's uiSession security scheme). SessionCookie = "factory_session" // StateCookie binds an OAuth login's state to the browser that started it. StateCookie = "factory_oauth_state" )
Cookie names.
const CLIActor = "factory:cli"
CLIActor is the actor id of commands sent with the CLI token.
const KindSession = "Session"
KindSession is a UI session (internal store kind, no API, no schema). It is named by the SHA-256 of the session id, so the store never holds a usable cookie value.
const KindUsedLoginState = "UsedLoginState"
KindUsedLoginState records a finished UI login (internal store kind, no API, no schema), so its OAuth state is used once on every dispatcher of the store. It is named by the SHA-256 of the state's id and holds nothing else but the state's expiry; the leader's sweep deletes it once the state has expired.
const MaxReturnTo = 1024
MaxReturnTo bounds a returnTo, which the signed OAuth state carries in its cookie: cookies over about 4 KB are dropped by browsers.
Variables ¶
var ( // ErrUnauthenticated: no credential, or a wrong, expired or malformed one (401). ErrUnauthenticated = errors.New("unauthenticated") // ErrForbidden: authenticated, but not allowed (403): not a member of the Group the route // needs, or a cross-site request. ErrForbidden = errors.New("forbidden") // ErrStateMismatch: an OAuth callback whose state isn't the one bound to this browser, or // is unknown or expired (400). ErrStateMismatch = errors.New("oauth state mismatch") // ErrBadReturnTo: a returnTo that isn't a same-origin path (400). ErrBadReturnTo = errors.New("returnTo must be a same-origin path") // ErrNotMember: a GitHub user who is in neither the readers nor the admin Group (403). ErrNotMember = fmt.Errorf("not a member of the factory's Groups: %w", ErrForbidden) // ErrOAuth: GitHub refused the code exchange or the user lookup (502 unless the token was // refused, which is ErrUnauthenticated). ErrOAuth = errors.New("github oauth failed") )
Errors. The API server maps them to statuses with errors.Is.
var DefaultScopes = []string{"read:user"}
DefaultScopes are the OAuth scopes of the UI login: GET /user is all it needs (Group membership is resolved with the App's credentials).
Functions ¶
func BearerToken ¶
BearerToken returns the request's bearer token ("" when there is none).
func SafeReturnTo ¶
SafeReturnTo validates a returnTo: it must be a same-origin absolute path ("/board?x=1") of at most MaxReturnTo bytes, not a URL, a scheme-relative "//host" or a backslash trick ("/\host"). "" is "/".
Types ¶
type AgentAuthenticator ¶
type AgentAuthenticator interface {
Authenticate(ctx context.Context, token string) (string, error)
AuthenticateRun(ctx context.Context, token string) (scheduler.RunAuth, error)
}
AgentAuthenticator checks an agent token and returns the agent id (scheduler.Authenticate), and a run token and returns its lease (scheduler.AuthenticateRun). Its errors for a bad token wrap scheduler.ErrUnauthorized.
type Authenticator ¶
type Authenticator struct {
// contains filtered or unexported fields
}
Authenticator authenticates requests. It is safe for concurrent use.
func (*Authenticator) Agent ¶
Agent authenticates the request's agent token. A missing or wrong token (or the CLI token) is ErrUnauthenticated.
func (*Authenticator) BeginLogin ¶
func (a *Authenticator) BeginLogin(ctx context.Context, returnTo string) (string, *http.Cookie, error)
BeginLogin starts the OAuth web flow: it returns the GitHub authorize URL to redirect to and the cookie that binds the login's state to this browser (CSRF). returnTo must be a same-origin path (ErrBadReturnTo).
func (*Authenticator) CLI ¶
func (a *Authenticator) CLI(r *http.Request) (Principal, bool)
CLI authenticates the request's CLI token.
func (*Authenticator) FinishLogin ¶
func (a *Authenticator) FinishLogin(ctx context.Context, r *http.Request, code, state string) (*Login, error)
FinishLogin is the OAuth callback. The state must equal the state cookie of r (constant time), carry a valid signature under the session key (or the previous one) and not have expired (ErrStateMismatch). The code is exchanged for a user token first, so a callback without a real OAuth round trip writes nothing. Each state is used once: then the login creates its UsedLoginState, so a second use, on any dispatcher of the store, is ErrStateMismatch. The token is exchanged for the login (GET /user) and dropped. A user in neither the readers nor the admin Group is ErrNotMember and gets no session.
func (*Authenticator) IsAdmin ¶
IsAdmin reports whether u is in the admin Group (may send commands).
func (*Authenticator) IsCLIToken ¶
func (a *Authenticator) IsCLIToken(tok string) bool
IsCLIToken reports whether tok is the CLI token, in constant time (over hashes, so not even the length leaks). It is false when no CLI token is configured.
func (*Authenticator) IsReader ¶
IsReader reports whether u may read: a member of the readers Group or of the admin Group.
func (*Authenticator) Logout ¶
Logout deletes the request's session, if any, and returns the cookie that clears it.
func (*Authenticator) Provider ¶
func (a *Authenticator) Provider() string
Provider is the catalog Provider the GitHub logins belong to.
func (*Authenticator) Run ¶
Run authenticates the request's run token. A missing, wrong or ended one is ErrUnauthenticated.
func (*Authenticator) Session ¶
Session returns the request's signed-in user. No cookie, a forged one, or an unknown or expired session is ErrUnauthenticated.
func (*Authenticator) SweepUsedStates ¶ added in v0.2.0
func (a *Authenticator) SweepUsedStates(ctx context.Context) (int, error)
SweepUsedStates deletes the UsedLoginStates whose state has expired (the leader's sweep), and returns how many it deleted.
type Config ¶
type Config struct {
// CLIToken is FACTORY_CLI_TOKEN; empty disables the CLI token.
CLIToken string
OAuth OAuthConfig
// Provider is the catalog Provider the GitHub logins belong to (e.g. github-public): the
// Groups' member sources on it are the ones checked, and owners are "<Provider>:<login>".
Provider string
// AdminGroup may send commands (default "maintainers"); ReadersGroup may read (default
// "readers"). A Group missing from the catalog has no members, so without a readers Group
// only admins can sign in (fail closed).
AdminGroup string
ReadersGroup string
// SessionKey (FACTORY_SESSION_KEY, 32 bytes) signs the session cookie and the OAuth state;
// when empty a random key is used, so sessions don't survive a restart (nor does the
// memory store) and no other dispatcher accepts them.
SessionKey []byte
// PreviousSessionKey (FACTORY_SESSION_KEY_PREVIOUS), when set, is also accepted when
// verifying, so rotating the key ends no session or login in flight. Drop it after the
// session lifetime.
PreviousSessionKey []byte
SessionTTL time.Duration
StateTTL time.Duration
// GroupCacheTTL caches Conn.ResolveGroup per member source (default 10 min, the LLD's).
GroupCacheTTL time.Duration
// HTTPClient calls GitHub (default http.DefaultClient).
HTTPClient *http.Client
Clock clock.Clock
Logger *slog.Logger
// Rand is the source of session ids and states (default crypto/rand).
Rand io.Reader
}
Config configures an Authenticator. Zero fields take the defaults.
type Deps ¶
type Deps struct {
// Store keeps the sessions.
Store store.Store
// Catalog gives the Groups; Conns resolve them.
Catalog controllers.CatalogProvider
Conns controllers.ConnSource
// Agents checks agent and run tokens.
Agents AgentAuthenticator
}
Deps are what the Authenticator reads.
type Login ¶
Login is a finished login: the session cookie to set, the state cookie to clear and where to send the browser.
type OAuthConfig ¶
type OAuthConfig struct {
ClientID string
ClientSecret string
// AuthorizeURL, TokenURL and APIBase default to github.com's; tests point them at an
// httptest server.
AuthorizeURL string
TokenURL string
APIBase string
// RedirectURL is the callback: <public URL>/api/v1/auth/callback.
RedirectURL string
// Scopes default to DefaultScopes.
Scopes []string
}
OAuthConfig is the GitHub OAuth App (or the author App's user-to-server client) the UI login uses.
type Principal ¶
type Principal struct {
Kind Kind
// AgentID is set for KindAgent, and for KindRun (the lease's agent).
AgentID string
// Lease and Task are set for KindRun: the run token's lease and its task.
Lease, Task string
// User is set for KindUser.
User *User
}
Principal is an authenticated caller.
func PrincipalFrom ¶
PrincipalFrom returns the principal ctx carries.
type Session ¶
type Session struct {
v1alpha1.TypeMeta
Metadata v1alpha1.ObjectMeta `json:"metadata"`
User User `json:"user"`
ExpiresAt time.Time `json:"expiresAt"`
}
Session is a stored UI session. It holds no GitHub token.
func (*Session) GetObjectMeta ¶
func (s *Session) GetObjectMeta() *v1alpha1.ObjectMeta
GetObjectMeta implements store.MetaObject.
type UsedLoginState ¶ added in v0.2.0
type UsedLoginState struct {
v1alpha1.TypeMeta
Metadata v1alpha1.ObjectMeta `json:"metadata"`
ExpiresAt time.Time `json:"expiresAt"`
}
UsedLoginState is a stored KindUsedLoginState.
func (*UsedLoginState) GetName ¶ added in v0.2.0
func (u *UsedLoginState) GetName() string
GetName returns metadata.name (the hash of the state's id).
func (*UsedLoginState) GetObjectMeta ¶ added in v0.2.0
func (u *UsedLoginState) GetObjectMeta() *v1alpha1.ObjectMeta
GetObjectMeta implements store.MetaObject.