auth

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package auth provides OAuth 2.0 authentication for the OmniAgent web UI.

Index

Constants

View Source
const (
	ProtocolIDJAG = agentauth.ProtocolIDJAG
	ProtocolAAuth = agentauth.ProtocolAAuth
)

Protocol constants for convenience.

View Source
const (
	// SessionName is the name of the session cookie.
	SessionName = "omniagent_session"

	// SessionKeyUser is the key for user data in the session.
	SessionKeyUser = "user"

	// SessionKeyState is the key for OAuth state in the session.
	SessionKeyState = "oauth_state"

	// DefaultMaxAge is the default session max age (7 days).
	DefaultMaxAge = 7 * 24 * 60 * 60
)

Variables

View Source
var (
	// ErrMissingSessionSecret is returned when AUTH_SESSION_SECRET is not set.
	ErrMissingSessionSecret = errors.New("AUTH_SESSION_SECRET is required when auth is enabled")

	// ErrSessionSecretTooShort is returned when the session secret is less than 32 bytes.
	ErrSessionSecretTooShort = errors.New("AUTH_SESSION_SECRET must be at least 32 bytes")

	// ErrNoProviders is returned when no OAuth providers are configured.
	ErrNoProviders = errors.New("at least one OAuth provider (GitHub or Google) must be configured")

	// ErrInvalidState is returned when the OAuth state parameter is invalid.
	ErrInvalidState = errors.New("invalid OAuth state")

	// ErrEmailNotAllowed is returned when the user's email is not in the ACL.
	ErrEmailNotAllowed = errors.New("email not allowed")

	// ErrNoSession is returned when no valid session exists.
	ErrNoSession = errors.New("no valid session")

	// ErrProviderNotConfigured is returned when attempting to use an unconfigured provider.
	ErrProviderNotConfigured = errors.New("OAuth provider not configured")
)

Functions

This section is empty.

Types

type AAuthClaims

type AAuthClaims struct {
	jwt.RegisteredClaims

	// Scope is the space-separated list of granted scopes.
	Scope string `json:"scope,omitempty"`

	// Act contains the actor (agent) information for delegation tokens.
	Act map[string]any `json:"act,omitempty"`
}

AAuthClaims represents the claims in an AAuth token.

type AAuthConfig

type AAuthConfig struct {
	// Enabled controls whether AAuth token validation is enabled.
	Enabled bool

	// IssuerURL is the URL of the AAuth issuer (PeopleServer).
	// Used for token validation and JWKS fetching.
	IssuerURL string

	// Audience is the expected audience claim in AAuth tokens.
	// Typically the URL of this service.
	Audience string

	// JWKSURL is the URL to fetch public keys for token verification.
	// If not set, defaults to {IssuerURL}/.well-known/jwks.json
	JWKSURL string
}

AAuthConfig holds AAuth configuration.

func LoadAAuthFromEnv

func LoadAAuthFromEnv() *AAuthConfig

LoadAAuthFromEnv loads AAuth configuration from environment variables.

Environment variables:

  • AUTH_AAUTH_ENABLED: Enable AAuth token validation (default: false)
  • AUTH_AAUTH_ISSUER: AAuth issuer URL (PeopleServer URL)
  • AUTH_AAUTH_AUDIENCE: Expected audience claim (this service's URL)
  • AUTH_AAUTH_JWKS_URL: Optional custom JWKS URL (defaults to {issuer}/.well-known/jwks.json)

type AAuthVerifier

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

AAuthVerifier verifies AAuth tokens using JWKS.

func NewAAuthVerifier

func NewAAuthVerifier(cfg AAuthConfig) *AAuthVerifier

NewAAuthVerifier creates a new AAuth token verifier.

func (*AAuthVerifier) IsAAuthToken

func (v *AAuthVerifier) IsAAuthToken(tokenString string) bool

IsAAuthToken checks if a token string appears to be an AAuth JWT. It looks for JWT structure and AAuth-specific characteristics.

func (*AAuthVerifier) Verify

func (v *AAuthVerifier) Verify(ctx context.Context, tokenString string) (*AAuthClaims, error)

Verify validates an AAuth JWT token and returns the claims.

type ACL

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

ACL handles email-based access control.

func NewACL

func NewACL(cfg *Config) *ACL

NewACL creates a new ACL from the configuration.

func (*ACL) IsAllowed

func (a *ACL) IsAllowed(email string) bool

IsAllowed checks if an email address is allowed by the ACL. If no ACL rules are configured, all authenticated users are allowed.

func (*ACL) IsEmpty

func (a *ACL) IsEmpty() bool

IsEmpty returns true if no ACL rules are configured.

type AgentAuthClaims

type AgentAuthClaims = agentauth.TokenClaims

AgentAuthClaims is an alias for agentauth.TokenClaims for convenience.

type AgentAuthConfig

type AgentAuthConfig struct {
	// Enabled controls whether agent authentication is enabled.
	Enabled bool

	// IDJAGEnabled enables ID-JAG token verification (automatic auth).
	IDJAGEnabled bool

	// IDJAGIssuers maps issuer URLs to JWKS URLs for ID-JAG verification.
	// If JWKS URL is empty, defaults to {issuer}/.well-known/jwks.json
	IDJAGIssuers map[string]string

	// IDJAGAudience is the expected audience for ID-JAG tokens.
	IDJAGAudience string

	// AAuthEnabled enables AAuth token verification (human consent).
	AAuthEnabled bool

	// AAuthIssuers maps issuer URLs to JWKS URLs for AAuth verification.
	// If JWKS URL is empty, defaults to {issuer}/.well-known/jwks.json
	AAuthIssuers map[string]string

	// AAuthAudience is the expected audience for AAuth tokens.
	AAuthAudience string

	// SensitiveActions require AAuth (human consent).
	// Default: write, delete, update, create, send, upload, admin
	SensitiveActions []string

	// ActionPolicy maps specific actions to required protocols.
	// Overrides default behavior for specific actions.
	ActionPolicy map[string]agentauth.Protocol
}

AgentAuthConfig configures agent authentication with ID-JAG and AAuth support.

func DefaultAgentAuthConfig

func DefaultAgentAuthConfig() *AgentAuthConfig

DefaultAgentAuthConfig returns a default configuration with sensible defaults.

type AgentAuthProtocol

type AgentAuthProtocol = agentauth.Protocol

AgentAuthProtocol is an alias for agentauth.Protocol for convenience.

type AgentAuthVerifier

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

AgentAuthVerifier verifies both ID-JAG and AAuth tokens with action-based routing.

func NewAgentAuthVerifier

func NewAgentAuthVerifier(cfg *AgentAuthConfig) *AgentAuthVerifier

NewAgentAuthVerifier creates a new agent authentication verifier.

func (*AgentAuthVerifier) AddAAuthIssuer

func (v *AgentAuthVerifier) AddAAuthIssuer(issuerURL, jwksURL string)

AddAAuthIssuer adds a trusted AAuth issuer at runtime.

func (*AgentAuthVerifier) AddIDJAGIssuer

func (v *AgentAuthVerifier) AddIDJAGIssuer(issuerURL, jwksURL string)

AddIDJAGIssuer adds a trusted ID-JAG issuer at runtime.

func (*AgentAuthVerifier) GetRequiredProtocol

func (v *AgentAuthVerifier) GetRequiredProtocol(action string) agentauth.Protocol

GetRequiredProtocol returns the required protocol for an action.

func (*AgentAuthVerifier) IsAgentToken

func (v *AgentAuthVerifier) IsAgentToken(token string) bool

IsAgentToken checks if a token string appears to be an agent token (JWT).

func (*AgentAuthVerifier) IsSensitiveAction

func (v *AgentAuthVerifier) IsSensitiveAction(action string) bool

IsSensitiveAction returns true if the action requires AAuth (human consent).

func (*AgentAuthVerifier) Verify

Verify verifies a token without action checking.

func (*AgentAuthVerifier) VerifyForAction

func (v *AgentAuthVerifier) VerifyForAction(ctx context.Context, token, action string) (*agentauth.TokenClaims, error)

VerifyForAction verifies a token and checks if it's valid for the given action.

type Config

type Config struct {
	// Enabled controls whether authentication is required for the web UI.
	Enabled bool

	// SessionSecret is the secret key for signing session cookies.
	// Must be at least 32 bytes when auth is enabled.
	SessionSecret string

	// CookieDomain optionally restricts cookies to a specific domain.
	CookieDomain string

	// GitHub holds GitHub OAuth configuration.
	GitHub OAuthProviderConfig

	// Google holds Google OAuth configuration.
	Google OAuthProviderConfig

	// AllowedEmails is a list of exact email addresses allowed to login.
	AllowedEmails []string

	// AllowedDomains is a list of email domains allowed to login (e.g., "@company.com").
	AllowedDomains []string
}

Config holds authentication configuration.

func LoadFromEnv

func LoadFromEnv() *Config

LoadFromEnv loads authentication configuration from environment variables.

Environment variables:

  • AUTH_ENABLED: Enable auth (default: false)
  • AUTH_SESSION_SECRET: Secret for cookie signing (required when enabled)
  • AUTH_COOKIE_DOMAIN: Optional cookie domain
  • AUTH_GITHUB_CLIENT_ID: GitHub OAuth client ID
  • AUTH_GITHUB_CLIENT_SECRET: GitHub OAuth client secret
  • AUTH_GOOGLE_CLIENT_ID: Google OAuth client ID
  • AUTH_GOOGLE_CLIENT_SECRET: Google OAuth client secret
  • AUTH_ALLOWED_EMAILS: Comma-separated allowed emails
  • AUTH_ALLOWED_DOMAINS: Comma-separated allowed domains (e.g., "@company.com")

func (*Config) HasACL

func (c *Config) HasACL() bool

HasACL returns true if email or domain ACL is configured.

func (*Config) HasGitHub

func (c *Config) HasGitHub() bool

HasGitHub returns true if GitHub OAuth is configured.

func (*Config) HasGoogle

func (c *Config) HasGoogle() bool

HasGoogle returns true if Google OAuth is configured.

func (*Config) HasProviders

func (c *Config) HasProviders() bool

HasProviders returns true if at least one OAuth provider is configured.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the configuration for errors.

type Handlers

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

Handlers provides HTTP handlers for authentication.

func NewHandlers

func NewHandlers(cfg HandlersConfig) (*Handlers, error)

NewHandlers creates new auth handlers.

func (*Handlers) HandleLogin

func (h *Handlers) HandleLogin(w http.ResponseWriter, r *http.Request)

HandleLogin renders the login page.

func (*Handlers) HandleLogout

func (h *Handlers) HandleLogout(w http.ResponseWriter, r *http.Request)

HandleLogout clears the session and redirects to login.

func (*Handlers) HandleOAuthCallback

func (h *Handlers) HandleOAuthCallback(provider Provider) http.HandlerFunc

HandleOAuthCallback handles the OAuth callback from a provider.

func (*Handlers) HandleOAuthStart

func (h *Handlers) HandleOAuthStart(provider Provider) http.HandlerFunc

HandleOAuthStart initiates the OAuth flow for a provider.

type HandlersConfig

type HandlersConfig struct {
	Config    *Config
	Sessions  *SessionManager
	Providers *Providers
	ACL       *ACL
	Assets    fs.FS
	Logger    *slog.Logger
}

HandlersConfig configures the auth handlers.

type LoginData

type LoginData struct {
	HasGitHub bool
	HasGoogle bool
	Error     string
}

LoginData holds data for the login template.

type Middleware

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

Middleware provides HTTP middleware for session-based authentication.

func NewMiddleware

func NewMiddleware(sessions *SessionManager, cfg *Config) *Middleware

NewMiddleware creates a new auth middleware.

func (*Middleware) RequireAuth

func (m *Middleware) RequireAuth(next http.Handler) http.Handler

RequireAuth returns a middleware that requires authentication. It protects the web UI paths while allowing public and API paths through.

type OAuthProviderConfig

type OAuthProviderConfig struct {
	// ClientID is the OAuth client ID.
	ClientID string

	// ClientSecret is the OAuth client secret.
	ClientSecret string
}

OAuthProviderConfig holds OAuth configuration for a provider.

type Provider

type Provider string

Provider represents an OAuth provider.

const (
	// ProviderGitHub is the GitHub OAuth provider.
	ProviderGitHub Provider = "github"

	// ProviderGoogle is the Google OAuth provider.
	ProviderGoogle Provider = "google"
)

type Providers

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

Providers manages OAuth provider configurations.

func NewProviders

func NewProviders(cfg *Config, baseURL string) *Providers

NewProviders creates OAuth provider configurations from the config. The baseURL should be the base URL of the server (e.g., "http://localhost:8080").

func (*Providers) AvailableProviders

func (p *Providers) AvailableProviders() []Provider

AvailableProviders returns a list of configured providers.

func (*Providers) Exchange

func (p *Providers) Exchange(ctx context.Context, provider Provider, code string) (*User, error)

Exchange exchanges an authorization code for tokens and fetches user info.

func (*Providers) GetAuthURL

func (p *Providers) GetAuthURL(provider Provider, state string) (string, error)

GetAuthURL returns the OAuth authorization URL for the given provider.

func (*Providers) HasProvider

func (p *Providers) HasProvider(provider Provider) bool

HasProvider returns true if the specified provider is configured.

type SessionManager

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

SessionManager manages user sessions using gorilla/sessions.

func NewSessionManager

func NewSessionManager(cfg *Config) *SessionManager

NewSessionManager creates a new session manager.

func (*SessionManager) ClearSession

func (sm *SessionManager) ClearSession(w http.ResponseWriter, r *http.Request) error

ClearSession removes the user session.

func (*SessionManager) ClearState

func (sm *SessionManager) ClearState(w http.ResponseWriter, r *http.Request) error

ClearState removes the OAuth state from the session.

func (*SessionManager) GenerateState

func (sm *SessionManager) GenerateState(w http.ResponseWriter, r *http.Request) (string, error)

GenerateState generates a random state string for OAuth CSRF protection.

func (*SessionManager) GetUser

func (sm *SessionManager) GetUser(r *http.Request) *User

GetUser retrieves the authenticated user from the session. Returns nil if no valid session exists.

func (*SessionManager) SetDevelopmentMode

func (sm *SessionManager) SetDevelopmentMode(enabled bool)

SetDevelopmentMode configures the session manager for local development. This disables the Secure cookie flag to allow HTTP connections.

func (*SessionManager) SetUser

func (sm *SessionManager) SetUser(w http.ResponseWriter, r *http.Request, user *User) error

SetUser stores the authenticated user in the session.

func (*SessionManager) ValidateState

func (sm *SessionManager) ValidateState(r *http.Request, state string) bool

ValidateState validates the OAuth state parameter against the session.

type User

type User struct {
	Email     string    `json:"email"`
	Name      string    `json:"name"`
	Picture   string    `json:"picture"`
	Provider  string    `json:"provider"`
	LoginTime time.Time `json:"login_time"`
}

User represents an authenticated user.

Jump to

Keyboard shortcuts

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