auth

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: AGPL-3.0 Imports: 24 Imported by: 0

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

View Source
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.

View Source
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.

View Source
const CLIActor = "factory:cli"

CLIActor is the actor id of commands sent with the CLI token.

View Source
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.

View Source
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.

View Source
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

View Source
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.

View Source
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

func BearerToken(r *http.Request) string

BearerToken returns the request's bearer token ("" when there is none).

func SafeReturnTo

func SafeReturnTo(s string) (string, error)

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 "/".

func WithPrincipal

func WithPrincipal(ctx context.Context, p Principal) context.Context

WithPrincipal returns ctx carrying p.

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 New

func New(cfg Config, d Deps) (*Authenticator, error)

New returns an Authenticator.

func (*Authenticator) Agent

func (a *Authenticator) Agent(ctx context.Context, r *http.Request) (Principal, error)

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

func (a *Authenticator) IsAdmin(ctx context.Context, u *User) (bool, error)

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

func (a *Authenticator) IsReader(ctx context.Context, u *User) (bool, error)

IsReader reports whether u may read: a member of the readers Group or of the admin Group.

func (*Authenticator) Logout

func (a *Authenticator) Logout(ctx context.Context, r *http.Request) (*http.Cookie, error)

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

func (a *Authenticator) Session(ctx context.Context, r *http.Request) (*User, error)

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 Kind

type Kind string

Kind is what kind of caller a Principal is.

const (
	KindAgent Kind = "agent"
	KindUser  Kind = "user"
	KindCLI   Kind = "cli"
	// KindRun is a run token (P1 §5): its lease's agent, for that lease's task only.
	KindRun Kind = "run"
)

Principal kinds.

type Login

type Login struct {
	User       User
	Session    *http.Cookie
	ClearState *http.Cookie
	ReturnTo   string
}

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

func PrincipalFrom(ctx context.Context) (Principal, bool)

PrincipalFrom returns the principal ctx carries.

func (Principal) ActorID

func (p Principal) ActorID() string

ActorID is who the principal is, as an Actor id: "<provider>:<login>" for a user, the agent id, or CLIActor.

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) GetName

func (s *Session) GetName() string

GetName returns metadata.name (the hash of the session id).

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.

type User

type User struct {
	// Provider is the catalog Provider of the login (Config.Provider).
	Provider  string `json:"provider"`
	Login     string `json:"login"`
	Name      string `json:"name,omitzero"`
	AvatarURL string `json:"avatarUrl,omitzero"`
}

User is a signed-in GitHub user.

Jump to

Keyboard shortcuts

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