auth

package
v0.2.65 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidRefreshToken = errors.New("auth: invalid refresh token")

ErrInvalidRefreshToken indicates the stored refresh token is invalid/expired.

Functions

func Bearer

func Bearer(ctx context.Context) string

Bearer returns a raw bearer token from context, if present.

func ClientIP added in v0.2.2

func ClientIP(r *http.Request, trusted []string) string

ClientIP extracts the client IP honoring X-Forwarded-For when the request comes from a trusted proxy. trusted is a list of CIDRs.

func EffectiveUserID added in v0.2.2

func EffectiveUserID(ctx context.Context) string

EffectiveUserID returns a stable user identifier from context (subject or email). Returns empty string when no identity is present.

func EnsureUser added in v0.2.2

func EnsureUser(ctx context.Context, cfg *Config) context.Context

EnsureUser populates a user identity in context when missing using config fallbacks (e.g., local mode default username). Returns the original context when no action is needed.

func ExtractBearer

func ExtractBearer(authzHeader string) string

ExtractBearer strips the Bearer prefix from an Authorization header value.

func HashIP added in v0.2.2

func HashIP(ip, key string) string

HashIP returns hex(HMAC-SHA256(key, ip)). Returns empty string when ip or key is empty.

func IDToken added in v0.2.2

func IDToken(ctx context.Context) string

IDToken returns a raw ID token from context, if present.

func IsInvalidRefreshToken added in v0.2.40

func IsInvalidRefreshToken(err error) bool

IsInvalidRefreshToken reports whether the error represents an invalid refresh token.

func JWKSFromBFFConfig added in v0.2.2

func JWKSFromBFFConfig(ctx context.Context, configURL string) (string, error)

JWKSFromBFFConfig derives a JWKS URL from an OAuth client config loaded via scy's authorizer. Strategy: 1) Build discovery URL candidates from AuthURL/TokenURL path patterns and fetch jwks_uri. 2) Fallback to <scheme>://<host>/.well-known/openid-configuration 3) Fallback to <scheme>://<host>/.well-known/jwks.json

func JWKSFromDiscovery added in v0.2.2

func JWKSFromDiscovery(ctx context.Context, discoveryURL string) (string, error)

JWKSFromDiscovery fetches the OpenID discovery document and returns jwks_uri.

func MCPAuthToken added in v0.2.35

func MCPAuthToken(ctx context.Context, useIDToken bool) string

MCPAuthToken selects a single token string suitable for outbound MCP calls. When useIDToken is true, it prefers IDToken and falls back to legacy IDToken/Bearer keys. When false, it prefers AccessToken and falls back to the legacy bearer key.

func NewOIDCVerifierFromEnv added in v0.2.2

func NewOIDCVerifierFromEnv(ctx context.Context) (*vcfg.Service, error)

NewOIDCVerifierFromEnv constructs a JWT verifier using JWKS URL from env:

AGENTLY_OIDC_JWKS_URL

Returns nil when not configured.

func TokensFromContext added in v0.2.35

func TokensFromContext(ctx context.Context) *scyauth.Token

TokensFromContext returns the token bundle from context, if present.

func WithBearer

func WithBearer(ctx context.Context, token string) context.Context

WithBearer stores a raw bearer token in context.

func WithIDToken added in v0.2.2

func WithIDToken(ctx context.Context, token string) context.Context

WithIDToken stores a raw ID token in context.

func WithTokens added in v0.2.35

func WithTokens(ctx context.Context, t *scyauth.Token) context.Context

WithTokens stores a token bundle in context.

func WithUserInfo

func WithUserInfo(ctx context.Context, info *UserInfo) context.Context

WithUserInfo stores identity data in context.

Types

type Config added in v0.2.2

type Config struct {
	Enabled         bool     `yaml:"enabled" json:"enabled"`
	CookieName      string   `yaml:"cookieName" json:"cookieName"`
	SessionTTLHours int      `yaml:"sessionTTLHours,omitempty" json:"sessionTTLHours,omitempty"` // cookie/session lifetime; default 168h (7 days)
	DefaultUsername string   `yaml:"defaultUsername" json:"defaultUsername"`
	IpHashKey       string   `yaml:"ipHashKey" json:"ipHashKey"`
	TrustedProxies  []string `yaml:"trustedProxies" json:"trustedProxies"`
	RedirectPath    string   `yaml:"redirectPath" json:"redirectPath"`
	// New unified model
	OAuth *OAuth `yaml:"oauth" json:"oauth"`
	Local *Local `yaml:"local" json:"local"`
}

Config defines global authentication settings. Modes:

  • local : username-only with HttpOnly session cookie
  • bff : backend-for-frontend OAuth (PKCE) setting HttpOnly cookie
  • oidc : frontend obtains tokens and calls APIs with Bearer; server validates
  • mixed : accept both Bearer and cookie

func (*Config) IsBearerAccepted added in v0.2.2

func (c *Config) IsBearerAccepted() bool

IsBearerAccepted returns true when a Bearer token is an acceptable auth credential given the current configuration.

func (*Config) IsCookieAccepted added in v0.2.2

func (c *Config) IsCookieAccepted() bool

IsCookieAccepted returns true when a session cookie is an acceptable auth credential given the current configuration.

func (*Config) IsLocalAuth added in v0.2.2

func (c *Config) IsLocalAuth() bool

IsLocalAuth returns true when auth is enabled and the effective mode is local-only (i.e. cookie-based session, no OAuth mode configured).

func (*Config) Validate added in v0.2.2

func (c *Config) Validate() error

Validate checks internal consistency; when disabled minimal fields are required.

type Local added in v0.2.2

type Local struct {
	Enabled bool `yaml:"enabled" json:"enabled"`
}

type Manager added in v0.2.2

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

func NewManager added in v0.2.2

func NewManager(cfg *Config, opts ...ManagerOption) *Manager

func (*Manager) Create added in v0.2.2

func (m *Manager) Create(w http.ResponseWriter, userID string) *Session

Create stores a session and sets the cookie.

func (*Manager) CreateWithProvider added in v0.2.38

func (m *Manager) CreateWithProvider(w http.ResponseWriter, userID, provider string) *Session

CreateWithProvider stores a session with an explicit provider and sets the cookie.

func (*Manager) CreateWithTokens added in v0.2.2

func (m *Manager) CreateWithTokens(w http.ResponseWriter, userID, access, refresh, id string, expiry time.Time) *Session

CreateWithTokens stores a session with OAuth tokens (BFF) and sets the cookie.

func (*Manager) CreateWithTokensProvider added in v0.2.38

func (m *Manager) CreateWithTokensProvider(w http.ResponseWriter, userID, provider, access, refresh, id string, expiry time.Time) *Session

CreateWithTokensProvider stores a session with OAuth tokens (BFF) and sets the cookie.

func (*Manager) Destroy added in v0.2.2

func (m *Manager) Destroy(w http.ResponseWriter, r *http.Request)

Destroy removes session and expires the cookie.

func (*Manager) Get added in v0.2.2

func (m *Manager) Get(r *http.Request) *Session

Get returns a live session from cookie.

func (*Manager) Tokens added in v0.2.2

func (m *Manager) Tokens(r *http.Request) (access, refresh, id string, exp time.Time)

Tokens returns a snapshot of tokens for the current session, if any.

type ManagerOption added in v0.2.38

type ManagerOption func(*Manager)

func WithSessionStore added in v0.2.38

func WithSessionStore(store SessionStore) ManagerOption

WithSessionStore enables persisted session storage (e.g., Datly-backed).

type OAuth added in v0.2.2

type OAuth struct {
	Mode   string       `yaml:"mode" json:"mode"` // bearer|spa|bff|mixed
	Name   string       `yaml:"name" json:"name"`
	Label  string       `yaml:"label" json:"label"`
	Client *OAuthClient `yaml:"client" json:"client"`
}

New unified structures

type OAuthClient added in v0.2.2

type OAuthClient struct {
	ConfigURL    string   `yaml:"configURL" json:"configURL"`       // for bff
	DiscoveryURL string   `yaml:"discoveryURL" json:"discoveryURL"` // for spa/bearer
	JWKSURL      string   `yaml:"jwksURL" json:"jwksURL"`           // for bearer verifier
	RedirectURI  string   `yaml:"redirectURI" json:"redirectURI"`
	ClientID     string   `yaml:"clientID" json:"clientID"`
	Scopes       []string `yaml:"scopes" json:"scopes"`
	Issuer       string   `yaml:"issuer" json:"issuer"`       // optional expected iss claim
	Audiences    []string `yaml:"audiences" json:"audiences"` // optional expected aud claim(s)
}

type OAuthToken added in v0.2.2

type OAuthToken struct {
	AccessToken  string    `json:"access_token,omitempty"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	IDToken      string    `json:"id_token,omitempty"`
	ExpiresAt    time.Time `json:"expires_at,omitempty"`
}

OAuthToken is a minimal serialized token shape stored encrypted in DB.

type Session added in v0.2.2

type Session struct {
	ID        string
	UserID    string
	ExpiresAt time.Time
	// Optional OAuth tokens captured during BFF login. Not exposed to clients.
	AccessToken  string
	RefreshToken string
	IDToken      string
	TokenExpiry  time.Time
}

type SessionRecord added in v0.2.38

type SessionRecord struct {
	ID        string
	UserID    string
	Provider  string
	CreatedAt time.Time
	UpdatedAt *time.Time
	ExpiresAt time.Time
}

SessionRecord is the minimal persisted session data.

type SessionStore added in v0.2.38

type SessionStore interface {
	Get(ctx context.Context, id string) (*SessionRecord, error)
	Upsert(ctx context.Context, rec *SessionRecord) error
	Delete(ctx context.Context, id string) error
}

SessionStore persists session metadata for reuse across restarts.

type SessionStoreDAO added in v0.2.38

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

SessionStoreDAO uses Datly operate with internal components to persist sessions.

func NewSessionStoreDAO added in v0.2.38

func NewSessionStoreDAO(dao *datly.Service) *SessionStoreDAO

NewSessionStoreDAO constructs a Datly-backed session store.

func (*SessionStoreDAO) Delete added in v0.2.38

func (s *SessionStoreDAO) Delete(ctx context.Context, id string) error

Delete removes a session by id.

func (*SessionStoreDAO) Get added in v0.2.38

Get loads a session by id.

func (*SessionStoreDAO) Upsert added in v0.2.38

func (s *SessionStoreDAO) Upsert(ctx context.Context, rec *SessionRecord) error

Upsert inserts or updates a session record.

type TokenStoreDAO added in v0.2.2

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

TokenStoreDAO uses Datly operate with internal components to persist encrypted tokens.

func NewTokenStoreDAO added in v0.2.2

func NewTokenStoreDAO(dao *datly.Service, salt string) *TokenStoreDAO

NewTokenStoreDAO constructs a Datly-backed token store (package-level for external calls).

func (*TokenStoreDAO) EnsureToken added in v0.2.35

func (s *TokenStoreDAO) EnsureToken(ctx context.Context, userID, provider, configURL string) (*OAuthToken, error)

EnsureToken refreshes if needed; updates DB on rotation.

func (*TokenStoreDAO) Get added in v0.2.2

func (s *TokenStoreDAO) Get(ctx context.Context, userID, provider string) (*OAuthToken, error)

Get loads and decrypts token from DB.

func (*TokenStoreDAO) Upsert added in v0.2.2

func (s *TokenStoreDAO) Upsert(ctx context.Context, userID, provider string, tok *OAuthToken) error

Upsert encrypts and saves token via internal write handler.

type UserInfo

type UserInfo struct {
	Subject string
	Email   string
}

UserInfo carries minimal identity extracted from a bearer token.

func DecodeUserInfo

func DecodeUserInfo(token string) (*UserInfo, error)

DecodeUserInfo parses a JWT token payload without verifying signature and extracts common identity fields (email, sub). It returns nil when parsing fails or when no useful claims are present.

func User

func User(ctx context.Context) *UserInfo

User returns identity data from context when available.

Directories

Path Synopsis
mcp

Jump to

Keyboard shortcuts

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