security

package
v0.1.39 Latest Latest
Warning

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

Go to latest
Published: May 9, 2026 License: MIT Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package security provides security-related functionality for the opampcommander application.

Index

Constants

View Source
const (
	// TokenTypeAccess marks a JWT issued as an access token.
	TokenTypeAccess = "access"
	// TokenTypeRefresh marks a JWT issued as a refresh token, accepted only by the refresh endpoint.
	TokenTypeRefresh = "refresh"
)

Token type values stored in the OPAMPClaims.TokenType claim.

View Source
const (
	// StateLength defines the length of the state string to be generated for OAuth2 authentication.
	StateLength = 16 // Length of the state string to be generated for OAuth2 authentication.
)

Variables

View Source
var (
	// ErrInvalidState is returned when the state parameter is invalid.
	ErrInvalidState = errors.New("invalid state parameter")
	// ErrStateExpired is returned when the state parameter has expired.
	ErrStateExpired = errors.New("state parameter has expired")
	// ErrInvalidToken is returned when the provided token is invalid.
	ErrInvalidToken = errors.New("invalid token")
	// ErrInvalidEmail is returned when the email in the token claims is invalid.
	ErrInvalidEmail = errors.New("invalid email in token claims")
	// ErrInvalidTokenClaims is returned when the token claims are invalid.
	ErrInvalidTokenClaims = errors.New("invalid token claims")
	// ErrTokenExpired is returned when the token has expired.
	ErrTokenExpired = errors.New("token has expired")
	// ErrInvalidUsernameOrPassword is returned when the provided username or password is invalid.
	ErrInvalidUsernameOrPassword = errors.New("invalid username or password")
	// ErrNoPrimaryEmailFound is returned when no primary email is found in the user's emails.
	ErrNoPrimaryEmailFound = errors.New("no primary verified email found")
	// ErrOAuth2ClientCreationFailed is returned when the OAuth2 client creation fails.
	ErrOAuth2ClientCreationFailed = errors.New("failed to create OAuth2 client")
)
View Source
var (
	// ErrNilContext is returned when the context is nil.
	ErrNilContext = errors.New("nil context")
	// ErrInvalidContext is returned when the context is not a valid Gin context.
	ErrInvalidContext = errors.New("invalid context")
	// ErrInvalidUserInContext is returned when the user in the context is not valid.
	ErrInvalidUserInContext = errors.New("invalid user in context")
)

Functions

func GetUserID added in v0.1.30

func GetUserID(ctx *gin.Context, userUsecase userport.UserUsecase) (uuid.UUID, error)

GetUserID is a helper that resolves the authenticated user's UUID.

func NewAuthJWTMiddleware

func NewAuthJWTMiddleware(
	service *Service,
) gin.HandlerFunc

NewAuthJWTMiddleware creates a new Gin middleware for JWT authentication.

func NewAuthorizationMiddleware added in v0.1.30

func NewAuthorizationMiddleware(
	rbacUsecase userport.RBACUsecase,
	userUsecase userport.UserUsecase,
	adminEmail string,
	logger *slog.Logger,
) gin.HandlerFunc

NewAuthorizationMiddleware creates a Gin middleware that enforces RBAC for both namespace-scoped (/api/v1/namespaces/:namespace/*) and global (/api/v1/users, /api/v1/roles, /api/v1/servers) resources. The adminEmail user bypasses all RBAC checks.

func SetUser added in v0.1.37

func SetUser(ctx *gin.Context, user *User)

SetUser injects a User into the Gin context. Intended for use in tests and middleware.

Types

type AdminUsecase

type AdminUsecase interface {
	// BasicAuth authenticates the user using basic authentication with username and password.
	BasicAuth(username, password string) (LoginResult, error)
}

AdminUsecase defines the use case for admin authentication.

type LoginResult added in v0.1.30

type LoginResult struct {
	Token        string
	RefreshToken string
	ExpiresAt    time.Time
	Email        string
	Groups       []string // provider group/org memberships, added as labels to the user on login
}

LoginResult contains the result of a successful authentication.

type OAuth2Usecase

type OAuth2Usecase interface {
	// AuthCodeURL generates the OAuth2 authorization URL with a unique state parameter.
	// cliRedirect is an optional loopback redirect URI (e.g. http://127.0.0.1:PORT/callback)
	// to be encoded into the state JWT; on callback the server redirects to it instead of
	// returning JSON. Empty string preserves the legacy JSON behavior.
	AuthCodeURL(cliRedirect string) (string, error)
	// CLIRedirectFromState extracts the loopback redirect URI from a state JWT, if any.
	CLIRedirectFromState(state string) (string, error)
	// Exchange exchanges the OAuth2 authorization code for an access token.
	Exchange(ctx context.Context, state, code string) (LoginResult, error)
}

OAuth2Usecase defines the use case for OAuth2 authentication.

type OAuthStateClaims

type OAuthStateClaims struct {
	jwt.RegisteredClaims

	// CLIRedirect, when non-empty, signals the callback handler to redirect the browser
	// to this loopback URI (with token query params) instead of returning JSON.
	CLIRedirect string `json:"cliRedirect,omitempty"`
}

OAuthStateClaims defines the custom claims for the JWT token used for the state parameter in OAuth2 authentication.

type OPAMPClaims

type OPAMPClaims struct {
	jwt.RegisteredClaims

	Email string `json:"email"`
	// TokenType is "access" or "refresh". Empty value is treated as "access" for backward compatibility.
	TokenType string `json:"tokenType,omitempty"`
}

OPAMPClaims defines the custom claims for the JWT token used for opampcommander's authentication. It includes the user's email and standard JWT registered claims.

type Service

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

Service provides security-related functionality for the opampcommander application.

func New

func New(
	logger *slog.Logger,
	settings *config.AuthSettings,
	httpClient *http.Client,
) *Service

New creates a new instance of the Service struct with the provided logger and OAuth settings.

func (*Service) AuthCodeURL

func (s *Service) AuthCodeURL(cliRedirect string) (string, error)

AuthCodeURL generates the OAuth2 authorization URL with a unique state parameter. If cliRedirect is non-empty, it is encoded into the state JWT and used by the callback handler to redirect to a loopback URL instead of returning JSON.

func (*Service) BasicAuth

func (s *Service) BasicAuth(username, password string) (LoginResult, error)

BasicAuth authenticates the user using basic authentication with username and password.

func (*Service) CLIRedirectFromState added in v0.1.39

func (s *Service) CLIRedirectFromState(state string) (string, error)

CLIRedirectFromState parses the state JWT and returns the embedded CLI loopback redirect, if any. Returns an empty string when the state has no CLI redirect.

func (*Service) DeviceAuth added in v0.1.1

func (s *Service) DeviceAuth(ctx context.Context) (*oauth2.DeviceAuthResponse, error)

DeviceAuth initiates the OAuth2 device authorization flow. It returns a device authorization response that contains the user code and verification URL.

func (*Service) Exchange

func (s *Service) Exchange(ctx context.Context, state, code string) (LoginResult, error)

Exchange exchanges the OAuth2 authorization code for an access token. It validates the state parameter to prevent CSRF attacks.

func (*Service) ExchangeDeviceAuth added in v0.1.1

func (s *Service) ExchangeDeviceAuth(
	ctx context.Context,
	deviceCode string,
	expiry time.Time,
) (LoginResult, error)

ExchangeDeviceAuth exchanges the device code for an access token. It retrieves the user's primary email from GitHub and creates a JWT token with the email as a claim. It returns the JWT token string or an error if the process fails.

func (*Service) Refresh added in v0.1.39

func (s *Service) Refresh(refreshToken string) (LoginResult, error)

Refresh validates a refresh token and issues a new access/refresh token pair for the same user. It rotates the refresh token (the old one remains valid until its own expiry — JWTs are stateless).

func (*Service) ValidateToken

func (s *Service) ValidateToken(tokenString string) (*OPAMPClaims, error)

ValidateToken validates the provided JWT token string and returns the claims if valid. It checks the token's validity, expiration, and rejects refresh tokens.

type UnsupportedTokenTypeError

type UnsupportedTokenTypeError struct {
	TokenType string
}

UnsupportedTokenTypeError is returned when the token type is not supported.

func (*UnsupportedTokenTypeError) Error

func (e *UnsupportedTokenTypeError) Error() string

type Usecase

type Usecase interface {
	// ValidateToken validates the provided JWT token string and returns the claims if valid.
	ValidateToken(tokenString string) (*OPAMPClaims, error)
	// Refresh exchanges a valid refresh token for a new access token (and rotated refresh token).
	Refresh(refreshToken string) (LoginResult, error)

	// AdminUsecase returns the use case for admin authentication.
	AdminUsecase
	// OAuth2Usecase returns the use case for OAuth2 authentication.
	OAuth2Usecase
}

Usecase defines the use case for the security package.

type User

type User struct {
	// Authenticated indicates if the user is authenticated
	Authenticated bool
	// Email is the primary email of the user
	// If the user is not authenticated, this will be nil
	Email *string
}

User represents a user in the system.

func GetUser

func GetUser(ctx context.Context) (*User, error)

GetUser retrieves the user from the Gin context.

func NewAnonymousUser added in v0.1.20

func NewAnonymousUser() *User

NewAnonymousUser creates a new anonymous user. Some operations needs an user (e.g., for audit logging) even if the user is not authenticated.

func (*User) String added in v0.1.18

func (user *User) String() string

Jump to

Keyboard shortcuts

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