auth

package
v0.41.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2025 License: MPL-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package auth authenticates and authorizes a subject attempting to access API resources.

Index

Constants

View Source
const (
	JobTokenType            string = "job"
	SCIMTokenType           string = "scim"
	ServiceAccountTokenType string = "service_account"
)

Valid token types used as private claims for tokens issued by Phobos.

Variables

View Source
var ErrNoCaller = errors.New("Authentication is required", errors.WithErrorCode(errors.EUnauthorized))

ErrNoCaller is the error returned when the context does not have a caller or a caller auth error

Functions

func FindToken

func FindToken(r *http.Request) string

FindToken returns the bearer token from an HTTP request

func GetSubject

func GetSubject(ctx context.Context) *string

GetSubject returns a context's subject. Return nil if no subject was found on the context.

func HandleCaller

func HandleCaller(
	ctx context.Context,
	userHandler func(ctx context.Context, c *UserCaller) error,
	serviceAccountHandler func(ctx context.Context, c *ServiceAccountCaller) error,
) error

HandleCaller will invoke the provided callback based on the type of caller

func NormalizeOIDCIssuer added in v0.39.0

func NormalizeOIDCIssuer(issuer string) string

NormalizeOIDCIssuer normalizes the OIDC issuer URL by adding "https://" prefix if not present and removing the trailing slash

func ParseUsername

func ParseUsername(username string) string

ParseUsername parses the username, if any, from the email.

func WithAgentID

func WithAgentID(id string) func(*constraints)

WithAgentID sets the agentID on Constraints struct.

func WithCaller

func WithCaller(ctx context.Context, caller Caller) context.Context

WithCaller adds the caller to the context

func WithCallerAuthenticationError added in v0.39.0

func WithCallerAuthenticationError(ctx context.Context, err error) context.Context

WithCallerAuthenticationError adds the auth error to the context

func WithJobID

func WithJobID(id string) func(*constraints)

WithJobID sets the job ID on the constraints struct.

func WithOrganizationID

func WithOrganizationID(id string) func(*constraints)

WithOrganizationID sets the organization ID on constraints struct.

func WithOrganizationIDs

func WithOrganizationIDs(ids []string) func(*constraints)

WithOrganizationIDs sets the organizationIDs on constraints struct.

func WithPipelineAction

func WithPipelineAction(path string) func(*constraints)

WithPipelineAction sets the pipeline action path on the constraints struct.

func WithPipelineID

func WithPipelineID(id string) func(*constraints)

WithPipelineID sets the pipeline ID on the constraints struct.

func WithPipelineTask

func WithPipelineTask(path string) func(*constraints)

WithPipelineTask sets the pipeline task path on the constraints struct.

func WithProjectID

func WithProjectID(id string) func(*constraints)

WithProjectID sets the project ID on the constraints struct.

func WithSubject

func WithSubject(ctx context.Context, subject string) context.Context

WithSubject adds the subject string to the context

func WithTeamID

func WithTeamID(id string) func(*constraints)

WithTeamID sets the TeamID on Constraints struct.

func WithUserID

func WithUserID(id string) func(*constraints)

WithUserID sets the UserID on constraints struct.

Types

type Authenticator

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

Authenticator is used to authenticate JWT tokens

func NewAuthenticator

func NewAuthenticator(
	userAuth *UserAuth,
	signingKeyManager SigningKeyManager,
	dbClient *db.Client,
	maintenanceMonitor maintenance.Monitor,
	issuerURL string,
) *Authenticator

NewAuthenticator creates a new Authenticator instance

func (*Authenticator) Authenticate

func (a *Authenticator) Authenticate(ctx context.Context, tokenString string, useCache bool) (Caller, error)

Authenticate verifies the token and returns a Caller

type Authorizer

type Authorizer interface {
	RequirePermissions(ctx context.Context, perms []models.Permission, checks ...func(*constraints)) error
	RequireAccessToInheritableResource(ctx context.Context, resourceType []types.ModelType, checks ...func(*constraints)) error
}

Authorizer is used to authorize access to Phobos resources.

type Caller

type Caller interface {
	GetSubject() string
	IsAdmin() bool
	RequirePermission(ctx context.Context, perm models.Permission, checks ...func(*constraints)) error
	RequireAccessToInheritableResource(ctx context.Context, resourceType types.ModelType, checks ...func(*constraints)) error
	UnauthorizedError(ctx context.Context, hasViewerAccess bool) error
	Authorized()
}

Caller represents a subject performing an API request

func AuthorizeCaller

func AuthorizeCaller(ctx context.Context) (Caller, error)

AuthorizeCaller verifies that a caller has been authenticated and returns the caller

func GetCaller

func GetCaller(ctx context.Context) Caller

GetCaller returns a context's caller. Return nil if no caller was found on the context.

type JobCaller

type JobCaller struct {
	JobID     string
	ProjectID string
	// contains filtered or unexported fields
}

JobCaller represents a job subject

func (*JobCaller) Authorized

func (j *JobCaller) Authorized()

Authorized marks the caller as authorized

func (*JobCaller) GetSubject

func (j *JobCaller) GetSubject() string

GetSubject returns the subject identifier for this caller

func (*JobCaller) IsAdmin

func (j *JobCaller) IsAdmin() bool

IsAdmin returns true if the caller is an admin

func (*JobCaller) RequireAccessToInheritableResource

func (j *JobCaller) RequireAccessToInheritableResource(ctx context.Context, _ types.ModelType, checks ...func(*constraints)) error

RequireAccessToInheritableResource will return an error if caller doesn't have permissions to inherited resources.

func (*JobCaller) RequirePermission

func (j *JobCaller) RequirePermission(ctx context.Context, perm models.Permission, checks ...func(*constraints)) error

RequirePermission will return an error if the caller doesn't have the specified permissions

func (*JobCaller) UnauthorizedError

func (j *JobCaller) UnauthorizedError(ctx context.Context, hasViewerAccess bool) error

UnauthorizedError returns the unauthorized error for this specific caller type

type MockAuthorizer

type MockAuthorizer struct {
	mock.Mock
}

MockAuthorizer is an autogenerated mock type for the Authorizer type

func NewMockAuthorizer

func NewMockAuthorizer(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockAuthorizer

NewMockAuthorizer creates a new instance of MockAuthorizer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockAuthorizer) RequireAccessToInheritableResource

func (_m *MockAuthorizer) RequireAccessToInheritableResource(ctx context.Context, resourceType []types.ModelType, checks ...func(*constraints)) error

RequireAccessToInheritableResource provides a mock function with given fields: ctx, resourceType, checks

func (*MockAuthorizer) RequirePermissions

func (_m *MockAuthorizer) RequirePermissions(ctx context.Context, perms []models.Permission, checks ...func(*constraints)) error

RequirePermissions provides a mock function with given fields: ctx, perms, checks

type MockCaller

type MockCaller struct {
	mock.Mock
}

MockCaller is an autogenerated mock type for the Caller type

func NewMockCaller

func NewMockCaller(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockCaller

NewMockCaller creates a new instance of MockCaller. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockCaller) Authorized

func (_m *MockCaller) Authorized()

Authorized provides a mock function with no fields

func (*MockCaller) GetSubject

func (_m *MockCaller) GetSubject() string

GetSubject provides a mock function with no fields

func (*MockCaller) IsAdmin

func (_m *MockCaller) IsAdmin() bool

IsAdmin provides a mock function with no fields

func (*MockCaller) RequireAccessToInheritableResource

func (_m *MockCaller) RequireAccessToInheritableResource(ctx context.Context, resourceType types.ModelType, checks ...func(*constraints)) error

RequireAccessToInheritableResource provides a mock function with given fields: ctx, resourceType, checks

func (*MockCaller) RequirePermission

func (_m *MockCaller) RequirePermission(ctx context.Context, perm models.Permission, checks ...func(*constraints)) error

RequirePermission provides a mock function with given fields: ctx, perm, checks

func (*MockCaller) UnauthorizedError

func (_m *MockCaller) UnauthorizedError(ctx context.Context, hasViewerAccess bool) error

UnauthorizedError provides a mock function with given fields: ctx, hasViewerAccess

type MockOIDCTokenVerifier added in v0.39.0

type MockOIDCTokenVerifier struct {
	mock.Mock
}

MockOIDCTokenVerifier is an autogenerated mock type for the OIDCTokenVerifier type

func NewMockOIDCTokenVerifier added in v0.39.0

func NewMockOIDCTokenVerifier(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockOIDCTokenVerifier

NewMockOIDCTokenVerifier creates a new instance of MockOIDCTokenVerifier. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockOIDCTokenVerifier) VerifyToken added in v0.39.0

func (_m *MockOIDCTokenVerifier) VerifyToken(ctx context.Context, token string, validationOptions []jwt.ValidateOption) (jwt.Token, error)

VerifyToken provides a mock function with given fields: ctx, token, validationOptions

type MockOpenIDConfigFetcher added in v0.39.0

type MockOpenIDConfigFetcher struct {
	mock.Mock
}

MockOpenIDConfigFetcher is an autogenerated mock type for the OpenIDConfigFetcher type

func NewMockOpenIDConfigFetcher added in v0.39.0

func NewMockOpenIDConfigFetcher(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockOpenIDConfigFetcher

NewMockOpenIDConfigFetcher creates a new instance of MockOpenIDConfigFetcher. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockOpenIDConfigFetcher) GetOpenIDConfig added in v0.39.0

func (_m *MockOpenIDConfigFetcher) GetOpenIDConfig(ctx context.Context, issuer string) (*OIDCConfiguration, error)

GetOpenIDConfig provides a mock function with given fields: ctx, issuer

type MockSigningKeyManager added in v0.39.0

type MockSigningKeyManager struct {
	mock.Mock
}

MockSigningKeyManager is an autogenerated mock type for the SigningKeyManager type

func NewMockSigningKeyManager added in v0.39.0

func NewMockSigningKeyManager(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockSigningKeyManager

NewMockSigningKeyManager creates a new instance of MockSigningKeyManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockSigningKeyManager) GenerateToken added in v0.39.0

func (_m *MockSigningKeyManager) GenerateToken(ctx context.Context, input *TokenInput) ([]byte, error)

GenerateToken provides a mock function with given fields: ctx, input

func (*MockSigningKeyManager) GetKeys added in v0.39.0

func (_m *MockSigningKeyManager) GetKeys(ctx context.Context) ([]byte, error)

GetKeys provides a mock function with given fields: ctx

func (*MockSigningKeyManager) GetOpenIDConfig added in v0.39.0

func (_m *MockSigningKeyManager) GetOpenIDConfig() *OpenIDConfig

GetOpenIDConfig provides a mock function with no fields

func (*MockSigningKeyManager) VerifyToken added in v0.39.0

func (_m *MockSigningKeyManager) VerifyToken(ctx context.Context, token string, validateOptions ...jwt.ValidateOption) (*VerifyTokenOutput, error)

VerifyToken provides a mock function with given fields: ctx, token, validateOptions

type OIDCConfiguration

type OIDCConfiguration struct {
	Issuer        string `json:"issuer"`
	JwksURI       string `json:"jwks_uri"`
	TokenEndpoint string `json:"token_endpoint"`
	AuthEndpoint  string `json:"authorization_endpoint"`
}

OIDCConfiguration contains the OIDC information for an identity provider

type OIDCTokenVerifier added in v0.39.0

type OIDCTokenVerifier interface {
	// VerifyToken verifies the OIDC token and returns the decoded token
	// If the token is not valid, it returns an error
	VerifyToken(ctx context.Context, token string, validationOptions []jwt.ValidateOption) (jwt.Token, error)
}

OIDCTokenVerifier is an interface for verifying OIDC tokens

func NewOIDCTokenVerifier added in v0.39.0

func NewOIDCTokenVerifier(ctx context.Context, issuers []string, oidcConfigFetcher OpenIDConfigFetcher, enableCache bool) OIDCTokenVerifier

NewOIDCTokenVerifier creates a new OIDCTokenVerifier instance

type OpenIDConfig added in v0.39.0

type OpenIDConfig struct {
	Issuer                           string   `json:"issuer"`
	JwksURI                          string   `json:"jwks_uri"`
	AuthorizationEndpoint            string   `json:"authorization_endpoint"`
	ResponseTypesSupported           []string `json:"response_types_supported"`
	SubjectTypesSupported            []string `json:"subject_types_supported"`
	IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
}

OpenIDConfig represents the OpenID Connect configuration

type OpenIDConfigFetcher

type OpenIDConfigFetcher interface {
	// GetOpenIDConfig returns the OIDC configuration for the given issuer
	GetOpenIDConfig(ctx context.Context, issuer string) (*OIDCConfiguration, error)
}

OpenIDConfigFetcher is an interface for fetching OIDC configuration

func NewOpenIDConfigFetcher

func NewOpenIDConfigFetcher() OpenIDConfigFetcher

NewOpenIDConfigFetcher returns a new NewOpenIDConfigFetcher

type SCIMCaller

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

SCIMCaller represents a SCIM subject.

func NewSCIMCaller

func NewSCIMCaller(dbClient *db.Client, maintenanceMonitor maintenance.Monitor) *SCIMCaller

NewSCIMCaller returns a new SCIM caller.

func (*SCIMCaller) Authorized

func (s *SCIMCaller) Authorized()

Authorized marks the caller as authorized

func (*SCIMCaller) GetSubject

func (s *SCIMCaller) GetSubject() string

GetSubject returns the subject identifier for this caller.

func (*SCIMCaller) IsAdmin

func (s *SCIMCaller) IsAdmin() bool

IsAdmin returns true if the caller is an admin.

func (*SCIMCaller) RequireAccessToInheritableResource

func (s *SCIMCaller) RequireAccessToInheritableResource(ctx context.Context, _ types.ModelType, _ ...func(*constraints)) error

RequireAccessToInheritableResource will return an error if the caller doesn't have access to the specified resource type.

func (*SCIMCaller) RequirePermission

func (s *SCIMCaller) RequirePermission(ctx context.Context, perm models.Permission, checks ...func(*constraints)) error

RequirePermission will return an error if the caller doesn't have the specified models.

func (*SCIMCaller) UnauthorizedError

func (s *SCIMCaller) UnauthorizedError(_ context.Context, hasViewerAccess bool) error

UnauthorizedError returns the unauthorized error for this specific caller type

type ServiceAccountCaller

type ServiceAccountCaller struct {
	ServiceAccountID  string
	ServiceAccountPRN string
	// contains filtered or unexported fields
}

ServiceAccountCaller represents a service account subject

func NewServiceAccountCaller

func NewServiceAccountCaller(
	id,
	prn string,
	authorizer Authorizer,
	dbClient *db.Client,
	maintenanceMonitor maintenance.Monitor,
) *ServiceAccountCaller

NewServiceAccountCaller returns a new ServiceAccountCaller

func (*ServiceAccountCaller) Authorized

func (s *ServiceAccountCaller) Authorized()

Authorized marks the caller as authorized

func (*ServiceAccountCaller) GetSubject

func (s *ServiceAccountCaller) GetSubject() string

GetSubject returns the subject identifier for this caller

func (*ServiceAccountCaller) IsAdmin

func (s *ServiceAccountCaller) IsAdmin() bool

IsAdmin returns true if the caller is an admin

func (*ServiceAccountCaller) RequireAccessToInheritableResource

func (s *ServiceAccountCaller) RequireAccessToInheritableResource(ctx context.Context, resourceType types.ModelType, checks ...func(*constraints)) error

RequireAccessToInheritableResource will return an error if caller doesn't have permissions to inherited resources.

func (*ServiceAccountCaller) RequirePermission

func (s *ServiceAccountCaller) RequirePermission(ctx context.Context, perm models.Permission, checks ...func(*constraints)) error

RequirePermission will return an error if the caller doesn't have the specified permissions

func (*ServiceAccountCaller) UnauthorizedError

func (s *ServiceAccountCaller) UnauthorizedError(_ context.Context, hasViewerAccess bool) error

UnauthorizedError returns the unauthorized error for this specific caller type

type SigningKeyManager added in v0.39.0

type SigningKeyManager interface {
	// GenerateToken creates a new JWT token
	GenerateToken(ctx context.Context, input *TokenInput) ([]byte, error)
	// VerifyToken verifies that the token is valid
	VerifyToken(ctx context.Context, token string, validateOptions ...jwt.ValidateOption) (*VerifyTokenOutput, error)
	// GetKeys returns the JSON Web Key Set (JWKS)
	GetKeys(ctx context.Context) ([]byte, error)
	// GetOpenIDConfig returns the OpenID Connect configuration
	GetOpenIDConfig() *OpenIDConfig
}

SigningKeyManager is an interface for generating and verifying JWT tokens

func NewSigningKeyManager added in v0.39.0

func NewSigningKeyManager(
	ctx context.Context,
	logger logger.Logger,
	jwsPlugin jwsplugin.Provider,
	dbClient *db.Client,
	eventManager *events.EventManager,
	cfg *config.Config,
) (SigningKeyManager, error)

NewSigningKeyManager initializes the SigningKeyManager type

type SystemCaller

type SystemCaller struct {
	Subject string
}

SystemCaller is the caller subject for internal system calls

func (*SystemCaller) Authorized

func (s *SystemCaller) Authorized()

Authorized marks the caller as authorized

func (*SystemCaller) GetSubject

func (s *SystemCaller) GetSubject() string

GetSubject returns the subject identifier for this caller

func (*SystemCaller) IsAdmin

func (s *SystemCaller) IsAdmin() bool

IsAdmin returns true if the caller is an admin

func (*SystemCaller) RequireAccessToInheritableResource

func (s *SystemCaller) RequireAccessToInheritableResource(ctx context.Context, _ types.ModelType, _ ...func(*constraints)) error

RequireAccessToInheritableResource will return an error if the caller doesn't have access to the specified resource type

func (*SystemCaller) RequirePermission

func (s *SystemCaller) RequirePermission(ctx context.Context, _ models.Permission, _ ...func(*constraints)) error

RequirePermission will return an error if the caller doesn't have the specified permissions

func (*SystemCaller) UnauthorizedError

func (s *SystemCaller) UnauthorizedError(_ context.Context, _ bool) error

UnauthorizedError returns the unauthorized error for this specific caller type

type TokenInput

type TokenInput struct {
	Expiration *time.Time
	Claims     map[string]string
	Subject    string
	JwtID      string
	Audience   string
}

TokenInput provides options for creating a new service account token

type UserAuth

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

UserAuth implements JWT authentication

func NewUserAuth

func NewUserAuth(
	ctx context.Context,
	identityProviders []config.IdpConfig,
	logger logger.Logger,
	dbClient *db.Client,
	maintenanceMonitor maintenance.Monitor,
	oidcConfigFetcher OpenIDConfigFetcher,
) *UserAuth

NewUserAuth creates an instance of UserAuth

func (*UserAuth) Authenticate

func (u *UserAuth) Authenticate(ctx context.Context, tokenString string, useCache bool) (Caller, error)

Authenticate validates a user JWT and returns a UserCaller

func (*UserAuth) GetUsernameClaim

func (u *UserAuth) GetUsernameClaim(token jwt.Token) (string, error)

GetUsernameClaim returns the username from a JWT token

func (*UserAuth) Use added in v0.39.0

func (u *UserAuth) Use(token jwt.Token) bool

Use checks if the UserAuth instance can handle the given issuer URL

type UserCaller

type UserCaller struct {
	User *models.User
	// contains filtered or unexported fields
}

UserCaller represents a user subject

func NewUserCaller

func NewUserCaller(user *models.User, authorizer Authorizer, dbClient *db.Client, maintenanceMonitor maintenance.Monitor) *UserCaller

NewUserCaller returns a new UserCaller

func (*UserCaller) Authorized

func (u *UserCaller) Authorized()

Authorized marks the caller as authorized

func (*UserCaller) GetSubject

func (u *UserCaller) GetSubject() string

GetSubject returns the subject identifier for this caller

func (*UserCaller) GetTeams

func (u *UserCaller) GetTeams(ctx context.Context) ([]models.Team, error)

GetTeams does lazy initialization of the list of teams for this user caller.

func (*UserCaller) IsAdmin

func (u *UserCaller) IsAdmin() bool

IsAdmin returns true if the caller is an admin

func (*UserCaller) RequireAccessToInheritableResource

func (u *UserCaller) RequireAccessToInheritableResource(ctx context.Context, resourceType types.ModelType, checks ...func(*constraints)) error

RequireAccessToInheritableResource will return an error if caller doesn't have permissions to inherited resources.

func (*UserCaller) RequirePermission

func (u *UserCaller) RequirePermission(ctx context.Context, perm models.Permission, checks ...func(*constraints)) error

RequirePermission will return an error if the caller doesn't have the specified permissions

func (*UserCaller) UnauthorizedError

func (u *UserCaller) UnauthorizedError(_ context.Context, hasViewerAccess bool) error

UnauthorizedError returns the unauthorized error for this specific caller type

type VerifyTokenOutput

type VerifyTokenOutput struct {
	Token         jwt.Token
	PrivateClaims map[string]string
}

VerifyTokenOutput is the response from verifying a token

Jump to

Keyboard shortcuts

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