application

package
v0.0.0-...-680b031 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidProvider    = errors.New("authentication: invalid provider")
	ErrInvalidState       = errors.New("authentication: invalid state parameter")
	ErrCodeExchangeFailed = errors.New("authentication: code exchange failed")
	ErrSessionNotFound    = errors.New("authentication: session not found")
	ErrSessionExpired     = errors.New("authentication: session expired")
	ErrSessionRevoked     = errors.New("authentication: session revoked")
	ErrTokenRefreshFailed = errors.New("authentication: token refresh failed")
	ErrCredentialNotFound = errors.New("authentication: credential not found")
)

Sentinel errors for the authentication domain.

Functions

func GenerateCodeChallenge

func GenerateCodeChallenge(verifier string) string

GenerateCodeChallenge generates a PKCE code challenge from a code verifier using the S256 method (SHA-256 hash, base64url-encoded).

func GenerateCodeVerifier

func GenerateCodeVerifier() (string, error)

GenerateCodeVerifier generates a cryptographically random PKCE code verifier. Returns a 43-character base64url-encoded string derived from 32 random bytes.

func GenerateNonce

func GenerateNonce() (string, error)

GenerateNonce generates a cryptographically random nonce for OpenID Connect ID token validation. Returns a 32-byte base64url-encoded string.

func GenerateState

func GenerateState() (string, error)

GenerateState generates a cryptographically random state parameter for OAuth CSRF protection. Returns a 32-byte base64url-encoded string.

Types

type AuthRequest

type AuthRequest struct {
	AuthURL      string
	State        string
	CodeVerifier string
	Nonce        string
	Provider     string
}

AuthRequest represents the result of initiating an OAuth authorization flow.

type AuthResult

type AuthResult struct {
	AccessToken  string
	RefreshToken string
	IDToken      string
	TokenType    string
	ExpiresIn    int
	UserInfo     UserInfo
}

AuthResult represents the result of a successful token exchange.

type AuthenticationService

type AuthenticationService interface {
	// InitiateAuthFlow generates PKCE parameters and returns the authorization URL.
	InitiateAuthFlow(ctx context.Context, provider string, redirectURI string) (*AuthRequest, error)

	// ExchangeCode exchanges an authorization code for tokens (server-to-server).
	ExchangeCode(ctx context.Context, code string, codeVerifier string, provider string, redirectURI string) (*AuthResult, error)

	// ValidateState verifies the OAuth state parameter matches the stored state.
	ValidateState(ctx context.Context, receivedState string, storedState string) error

	// FindOrCreateAgent looks up an agent by provider credentials, creates if not found.
	FindOrCreateAgent(ctx context.Context, userInfo UserInfo) (*entities.Agent, *entities.Credential, error)

	// CreateSession creates an authenticated session for an agent.
	CreateSession(ctx context.Context, agentID string, credentialID string, ipAddress string, userAgent string, duration time.Duration) (*entities.AuthSession, error)

	// ValidateSession validates and returns session info.
	ValidateSession(ctx context.Context, sessionID string) (*SessionInfo, error)

	// RefreshTokens refreshes OAuth tokens for a credential.
	RefreshTokens(ctx context.Context, credentialID string) (*AuthResult, error)

	// RevokeSession revokes an active session.
	RevokeSession(ctx context.Context, sessionID string) error

	// RevokeAllSessions revokes all sessions for an agent.
	RevokeAllSessions(ctx context.Context, agentID string) error
}

AuthenticationService defines the interface for authentication operations.

type AuthorizationChecker

type AuthorizationChecker interface {
	// IsAuthorized checks whether the given agent is authorized to perform
	// the specified action on the target resource.
	// It evaluates all applicable policies, considering:
	// - Direct agent permissions
	// - Role-based permissions (via agent's assigned roles)
	// - Prohibitions (which override permissions per ODRL semantics)
	IsAuthorized(ctx context.Context, agentID, action, target string) (bool, error)

	// IsAuthorizedInAccount checks whether the given agent is authorized within
	// a specific account context. It considers:
	// - Direct agent permissions
	// - Global role-based permissions (via agent's assigned roles)
	// - Account-scoped role-based permissions (via agent's role in the account)
	// - Prohibitions (which override permissions per ODRL semantics)
	IsAuthorizedInAccount(ctx context.Context, agentID, accountID, action, target string) (bool, error)

	// GetPermissions returns all effective permissions for the given agent,
	// including permissions inherited through role assignments.
	GetPermissions(ctx context.Context, agentID string) ([]Permission, error)

	// GetProhibitions returns all effective prohibitions for the given agent,
	// including prohibitions inherited through role assignments.
	GetProhibitions(ctx context.Context, agentID string) ([]Permission, error)
}

AuthorizationChecker defines the interface for authorization decisions. Implementations resolve agent roles, policy assignments, and evaluate ODRL permissions and prohibitions to reach a decision.

type DefaultAuthenticationService

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

DefaultAuthenticationService implements AuthenticationService using OAuth providers and the domain's event-sourced aggregates.

func NewDefaultAuthenticationService

func NewDefaultAuthenticationService(
	providers OAuthProviderRegistry,
	agents repositories.AgentRepository,
	credentials repositories.CredentialRepository,
	sessions repositories.AuthSessionRepository,
	tokens TokenStore,
	authorization AuthorizationChecker,
) *DefaultAuthenticationService

NewDefaultAuthenticationService creates a new DefaultAuthenticationService.

func (*DefaultAuthenticationService) CreateSession

func (s *DefaultAuthenticationService) CreateSession(ctx context.Context, agentID string, credentialID string, ipAddress string, userAgent string, duration time.Duration) (*entities.AuthSession, error)

CreateSession creates an authenticated session for an agent.

func (*DefaultAuthenticationService) ExchangeCode

func (s *DefaultAuthenticationService) ExchangeCode(ctx context.Context, code string, codeVerifier string, provider string, redirectURI string) (*AuthResult, error)

ExchangeCode exchanges an authorization code for tokens.

func (*DefaultAuthenticationService) FindOrCreateAgent

func (s *DefaultAuthenticationService) FindOrCreateAgent(ctx context.Context, userInfo UserInfo) (*entities.Agent, *entities.Credential, error)

FindOrCreateAgent looks up an agent by provider credentials, creates if not found.

func (*DefaultAuthenticationService) InitiateAuthFlow

func (s *DefaultAuthenticationService) InitiateAuthFlow(ctx context.Context, provider string, redirectURI string) (*AuthRequest, error)

InitiateAuthFlow generates PKCE parameters and returns the authorization URL.

func (*DefaultAuthenticationService) RefreshTokens

func (s *DefaultAuthenticationService) RefreshTokens(ctx context.Context, credentialID string) (*AuthResult, error)

RefreshTokens refreshes OAuth tokens for a credential.

func (*DefaultAuthenticationService) RevokeAllSessions

func (s *DefaultAuthenticationService) RevokeAllSessions(ctx context.Context, agentID string) error

RevokeAllSessions revokes all sessions for an agent.

func (*DefaultAuthenticationService) RevokeSession

func (s *DefaultAuthenticationService) RevokeSession(ctx context.Context, sessionID string) error

RevokeSession revokes an active session.

func (*DefaultAuthenticationService) ValidateSession

func (s *DefaultAuthenticationService) ValidateSession(ctx context.Context, sessionID string) (*SessionInfo, error)

ValidateSession validates and returns session info.

func (*DefaultAuthenticationService) ValidateState

func (s *DefaultAuthenticationService) ValidateState(_ context.Context, receivedState string, storedState string) error

ValidateState verifies the OAuth state parameter matches the stored state. Uses constant-time comparison to prevent timing attacks.

type OAuthProvider

type OAuthProvider interface {
	// Name returns the provider identifier (e.g., "google", "github").
	Name() string

	// AuthCodeURL generates the authorization URL with PKCE parameters.
	AuthCodeURL(state string, codeChallenge string, nonce string, redirectURI string) string

	// Exchange exchanges an authorization code for tokens.
	Exchange(ctx context.Context, code string, codeVerifier string, redirectURI string) (*AuthResult, error)

	// RefreshToken refreshes an access token using a refresh token.
	RefreshToken(ctx context.Context, refreshToken string) (*AuthResult, error)

	// RevokeToken revokes a token at the provider.
	RevokeToken(ctx context.Context, token string) error

	// ValidateIDToken validates the ID token and extracts user claims.
	ValidateIDToken(ctx context.Context, idToken string, nonce string) (*UserInfo, error)
}

OAuthProvider defines a provider-agnostic interface for OAuth 2.0 / OpenID Connect operations.

type OAuthProviderRegistry

type OAuthProviderRegistry map[string]OAuthProvider

OAuthProviderRegistry maps provider names to their OAuthProvider implementations.

type Permission

type Permission struct {
	Assignee string // Agent or Role ID that holds this permission
	Action   string // ODRL action IRI (e.g., odrl:read)
	Target   string // Asset/resource identifier or wildcard "*"
}

Permission represents a resolved permission or prohibition for querying.

type PermissionStore

type PermissionStore interface {
	// GetPermissionsForAssignee returns all permissions for a specific assignee (agent or role).
	GetPermissionsForAssignee(ctx context.Context, assigneeID string) ([]Permission, error)

	// GetProhibitionsForAssignee returns all prohibitions for a specific assignee.
	GetProhibitionsForAssignee(ctx context.Context, assigneeID string) ([]Permission, error)

	// GetRolesForAgent returns all global role IDs currently assigned to the given agent.
	GetRolesForAgent(ctx context.Context, agentID string) ([]string, error)

	// GetRolesForAgentInAccount returns role IDs assigned to the agent within a specific account.
	GetRolesForAgentInAccount(ctx context.Context, agentID, accountID string) ([]string, error)
}

PermissionStore provides read access to permission data for authorization decisions. This interface abstracts the projection/read model that stores resolved permissions. Consuming applications implement this against their storage layer.

type PolicyDecisionPoint

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

PolicyDecisionPoint implements AuthorizationChecker using a PermissionStore for resolving authorization decisions following ODRL semantics.

Decision logic:

  1. Collect all assignee IDs (agent + their roles)
  2. Check prohibitions — if any match, deny (prohibitions override permissions)
  3. Check permissions — if any match, allow
  4. Default deny

func NewPolicyDecisionPoint

func NewPolicyDecisionPoint(store PermissionStore) *PolicyDecisionPoint

NewPolicyDecisionPoint creates a new PolicyDecisionPoint with the given store.

func (*PolicyDecisionPoint) GetPermissions

func (pdp *PolicyDecisionPoint) GetPermissions(ctx context.Context, agentID string) ([]Permission, error)

GetPermissions returns all effective permissions for the agent.

func (*PolicyDecisionPoint) GetProhibitions

func (pdp *PolicyDecisionPoint) GetProhibitions(ctx context.Context, agentID string) ([]Permission, error)

GetProhibitions returns all effective prohibitions for the agent.

func (*PolicyDecisionPoint) IsAuthorized

func (pdp *PolicyDecisionPoint) IsAuthorized(ctx context.Context, agentID, action, target string) (bool, error)

IsAuthorized checks whether the agent is authorized following ODRL semantics.

func (*PolicyDecisionPoint) IsAuthorizedInAccount

func (pdp *PolicyDecisionPoint) IsAuthorizedInAccount(ctx context.Context, agentID, accountID, action, target string) (bool, error)

IsAuthorizedInAccount checks whether the agent is authorized within an account context. It collects both global roles and account-scoped roles before evaluating.

type SessionInfo

type SessionInfo struct {
	SessionID   string
	AgentID     string
	AccountID   string
	Permissions []Permission
	ExpiresAt   time.Time
}

SessionInfo represents validated session information returned to consumers.

type TokenStore

type TokenStore interface {
	// StoreTokens stores OAuth tokens for a credential.
	StoreTokens(ctx context.Context, credentialID string, accessToken, refreshToken, idToken string, expiresAt time.Time) error

	// GetTokens retrieves stored OAuth tokens for a credential.
	GetTokens(ctx context.Context, credentialID string) (accessToken, refreshToken string, expiresAt time.Time, err error)

	// DeleteTokens removes all stored tokens for a credential.
	DeleteTokens(ctx context.Context, credentialID string) error

	// NeedsRefresh checks if the stored access token needs refreshing.
	NeedsRefresh(ctx context.Context, credentialID string) (bool, error)
}

TokenStore defines the interface for encrypted server-side token storage.

type UserInfo

type UserInfo struct {
	ProviderUserID string
	Email          string
	DisplayName    string
	AvatarURL      string
	Provider       string
}

UserInfo represents normalized user information from any identity provider.

Jump to

Keyboard shortcuts

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