View Source
const (
	RoleAdmin  = "admin"
	RoleMember = "member"
View Source
const (
	// CurrentOrganization current organization key
	CurrentOrganization utils.ContextKey = "org"

	// SignUp is present if the current request is a signing up
	SignUp utils.ContextKey = "signUp"

	// OAuthRefreshTokenID denotes the tokenID for the user's OAuth refresh token, there can be only one
	OAuthRefreshTokenID = "oauth_refresh"
View Source
const BanzaiCLIClient = "banzai-cli"
View Source
const ClusterToken auth.TokenType = "cluster"

ClusterToken is the token given to clusters to manage themselves.

View Source
const ErrOrganizationConflict = errors.Sentinel("organization already exists, but with mismatching parameters")

ErrOrganizationConflict is returned when an organization exists, but with mismatching parameters.

View Source
const PipelineSessionCookie = "_banzai_session"

PipelineSessionCookie holds the name of the Cookie Pipeline sets in the browser

View Source
const SessionCookieHTTPOnly = true

SessionCookieHTTPOnly describes if the cookies should be accessible from HTTP requests only (no JS)

View Source
const SessionCookieMaxAge = 30 * 24 * 60 * 60

SessionCookieMaxAge holds long an authenticated session should be valid in seconds

View Source
const SessionCookieName = "Pipeline session token"

SessionCookieName is the name of the token that is stored in the session cookie

View Source
const UserTokenType pkgAuth.TokenType = "user"

UserTokenType is the token type used for API sessions

View Source
const VirtualUserTokenType pkgAuth.TokenType = "hook"

VirtualUserTokenType is the token type used for API sessions by external services Used by PKE at the moment Legacy token type (used by CICD build hook originally)


View Source
var (
	Auth *auth.Auth

	// CookieDomain is the domain field for cookies
	CookieDomain string

	// Handler is the Gin authentication middleware
	Handler gin.HandlerFunc

	// InternalHandler is the Gin authentication middleware for internal clients
	InternalHandler gin.HandlerFunc

	// SessionManager is responsible for handling browser session Cookies
	SessionManager session.ManagerInterface

Init authorization nolint: gochecknoglobals


func DelCookie

func DelCookie(w http.ResponseWriter, r *http.Request, name string)

DelCookie deletes a cookie.

func GetCurrentOrganizationID

func GetCurrentOrganizationID(ctx context.Context) (uint, bool)

GetCurrentOrganizationID return the user's organization ID.

func GetCurrentUserID

func GetCurrentUserID(req *http.Request) uint

GetCurrentUserID returns the current user ID.

func GetOrgNameFromVirtualUser

func GetOrgNameFromVirtualUser(virtualUser string) string

GetOrgNameFromVirtualUser returns the organization name for which the virtual user has access

func GetUserNickNameById

func GetUserNickNameById(userId uint) (userName string)

GetUserNickNameById returns user's login name

func GormErrorToStatusCode

func GormErrorToStatusCode(err error) int

GormErrorToStatusCode translates GORM errors to HTTP status codes

func Init

func Init(db *gorm.DB, config Config, tokenStore bauth.TokenStore, tokenManager TokenManager, orgSyncer OIDCOrganizationSyncer, serviceAccountService ServiceAccountService)

Init initializes the auth

func Install

func Install(engine *gin.Engine)

Install the whole OAuth and JWT Token based authn/authz mechanism to the specified Gin Engine.

func InternalUserHandler

func InternalUserHandler(ctx *gin.Context)

func Migrate

func Migrate(db *gorm.DB, logger logrus.FieldLogger) error

Migrate executes the table migrations for the auth module.

func NewBanzaiDeregisterHandler

func NewBanzaiDeregisterHandler(tokenStore bauth.TokenStore) func(*auth.Context)

NewBanzaiDeregisterHandler returns a handler that deletes the user and all his/her tokens from the database

func SetCookie

func SetCookie(w http.ResponseWriter, r *http.Request, name, value string)

SetCookie writes the cookie value.

func SetCurrentOrganizationID

func SetCurrentOrganizationID(ctx context.Context, orgID uint) context.Context

SetCurrentOrganizationID returns a context with the organization ID set

func StartTokenStoreGC

func StartTokenStoreGC(tokenStore bauth.TokenStore)

func SyncOrgsForUser

func SyncOrgsForUser(
	organizationSyncer OIDCOrganizationSyncer,
	refreshTokenStore RefreshTokenStore,
	user *User,
	request *http.Request,
) error

func TLSConfigForClientAuth

func TLSConfigForClientAuth(caCertFile string) (*tls.Config, error)


type AuthIdentity

type AuthIdentity struct {
	ID        uint      `gorm:"primary_key" json:"id"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`

AuthIdentity auth identity session model

type AuthorizeHandler

type AuthorizeHandler func(*auth.Context) (*claims.Claims, error)

type Authorizer

type Authorizer struct {
	// contains filtered or unexported fields

Authorizer checks if a context has permission to execute an action.

func NewAuthorizer

func NewAuthorizer(db *gorm.DB, roleSource RoleSource) Authorizer

NewAuthorizer returns a new Authorizer.

func (Authorizer) Authorize

func (a Authorizer) Authorize(ctx context.Context, action string, object interface{}) (bool, error)

Authorize authorizes a context to execute an action on an object.

type BanzaiSessionStorer

type BanzaiSessionStorer struct {
	// contains filtered or unexported fields

BanzaiSessionStorer stores the banzai session

func (*BanzaiSessionStorer) Update

func (sessionStorer *BanzaiSessionStorer) Update(w http.ResponseWriter, req *http.Request, claims *claims.Claims) error

Update updates the BanzaiSessionStorer

type BanzaiUserStorer

type BanzaiUserStorer struct {
	// contains filtered or unexported fields

BanzaiUserStorer struct

func (BanzaiUserStorer) Save

func (bus BanzaiUserStorer) Save(schema *auth.Schema, authCtx *auth.Context) (user interface{}, userID string, err error)

Save differs from the default UserStorer.Save() in that it extracts Token and Login

func (BanzaiUserStorer) Update

func (bus BanzaiUserStorer) Update(schema *auth.Schema, authCtx *auth.Context) (err error)

Update updates the user's group mmeberships from the OIDC ID token at every login

type CICDUser

type CICDUser struct {
	ID     int64  `gorm:"column:user_id;primary_key"`
	Login  string `gorm:"column:user_login"`
	Token  string `gorm:"column:user_token"`
	Secret string `gorm:"column:user_secret"`
	Expiry int64  `gorm:"column:user_expiry"`
	Email  string `gorm:"column:user_email"`
	Image  string `gorm:"column:user_avatar"`
	Active bool   `gorm:"column:user_active"`
	Admin  bool   `gorm:"column:user_admin"`
	Hash   string `gorm:"column:user_hash"`
	Synced int64  `gorm:"column:user_synced"`

CICDUser struct

func (CICDUser) TableName

func (CICDUser) TableName() string

TableName sets CICDUser's table name

type CLIConfig

type CLIConfig struct {
	ClientID string

CLIConfig contains cli auth configuration.

func (CLIConfig) Validate

func (c CLIConfig) Validate() error

Validate validates the configuration.

type ClusterTokenGenerator

type ClusterTokenGenerator struct {
	// contains filtered or unexported fields

ClusterTokenGenerator looks up or generates and stores a token for a cluster.

func NewClusterTokenGenerator

func NewClusterTokenGenerator(tokenManager TokenManager, tokenStore bauth.TokenStore) ClusterTokenGenerator

NewClusterTokenGenerator returns a new ClusterTokenGenerator.

func (ClusterTokenGenerator) GenerateClusterToken

func (g ClusterTokenGenerator) GenerateClusterToken(orgID uint, clusterID uint) (string, string, error)

GenerateClusterToken looks up or generates and stores a token for a cluster.

type Config

type Config struct {
	OIDC        OIDCConfig
	CLI         CLIConfig
	RedirectURL RedirectURLConfig
	Cookie      CookieConfig
	Token       TokenConfig
	Role        RoleConfig

Config contains auth configuration.

func (*Config) Process

func (c *Config) Process() error

Process post-processes the configuration after loading (before validation).

func (Config) Validate

func (c Config) Validate() error

Validate validates the configuration.

type CookieConfig

type CookieConfig struct {
	Secure    bool
	Domain    string
	SetDomain bool

CookieConfig contains auth cookie configuration.

func (CookieConfig) Validate

func (c CookieConfig) Validate() error

Validate validates the configuration.

type EventBus

type EventBus interface {
	// Publish sends an event to the underlying message bus.
	Publish(ctx context.Context, event interface{}) error

EventBus is a generic event bus.

type IDTokenClaims

type IDTokenClaims struct {
	Subject           string            `json:"sub"`
	Name              string            `json:"name"`
	PreferredUsername string            `json:"preferred_username"`
	Email             string            `json:"email"`
	Verified          bool              `json:"email_verified"`
	Groups            []string          `json:"groups"`
	FederatedClaims   map[string]string `json:"federated_claims"`

type Logger

type Logger = common.Logger

Logger is the fundamental interface for all log operations.

type OIDCConfig

type OIDCConfig struct {
	Issuer       string
	Insecure     bool
	ClientID     string
	ClientSecret string

OIDCConfig contains OIDC auth configuration.

func (OIDCConfig) Validate

func (c OIDCConfig) Validate() error

Validate validates the configuration.

type OIDCOrganizationSyncer

type OIDCOrganizationSyncer interface {
	SyncOrganizations(ctx gocontext.Context, user User, idTokenClaims *IDTokenClaims) error

OIDCOrganizationSyncer synchronizes organizations of a user from an OIDC ID token.

func NewOIDCOrganizationSyncer

func NewOIDCOrganizationSyncer(organizationSyncer OrganizationSyncer, roleBinder RoleBinder) OIDCOrganizationSyncer

NewOIDCOrganizationSyncer returns a new OIDCOrganizationSyncer.

type OIDCProvider

type OIDCProvider struct {
	// contains filtered or unexported fields

OIDCProvider provide login with OIDC auth method

func (OIDCProvider) Callback

func (provider OIDCProvider) Callback(context *auth.Context)

Callback implement Callback with dex provider

func (OIDCProvider) ConfigAuth

func (provider OIDCProvider) ConfigAuth(*auth.Auth)

ConfigAuth config auth

func (OIDCProvider) Deregister

func (provider OIDCProvider) Deregister(context *auth.Context)

Deregister implemented deregister with dex provider

func (OIDCProvider) GetName

func (OIDCProvider) GetName() string

GetName return provider name

func (OIDCProvider) Login

func (provider OIDCProvider) Login(context *auth.Context)

Login implemented login with dex provider

func (OIDCProvider) Logout

func (OIDCProvider) Logout(context *auth.Context)

Logout implemented logout with dex provider

func (OIDCProvider) OAuthConfig

func (provider OIDCProvider) OAuthConfig(context *auth.Context) *oauth2.Config

OAuthConfig return oauth config based on configuration

func (OIDCProvider) RedeemRefreshToken

func (provider OIDCProvider) RedeemRefreshToken(context *auth.Context, refreshToken string) (*IDTokenClaims, *oauth2.Token, error)

RedeemRefreshToken plays an OAuth redeem refresh token flow

func (OIDCProvider) Register

func (provider OIDCProvider) Register(context *auth.Context)

Register implemented register with dex provider

func (OIDCProvider) ServeHTTP

func (OIDCProvider) ServeHTTP(*auth.Context)

ServeHTTP implement ServeHTTP with dex provider

type OIDCProviderConfig

type OIDCProviderConfig struct {
	PublicClientID     string
	ClientID           string
	ClientSecret       string
	IssuerURL          string
	InsecureSkipVerify bool
	RedirectURL        string
	Scopes             []string
	AuthorizeHandler   AuthorizeHandler

OIDCProviderConfig holds the oidc configuration parameters

type Organization

type Organization struct {
	ID             uint      `gorm:"primary_key" json:"id"`
	CreatedAt      time.Time `json:"createdAt"`
	UpdatedAt      time.Time `json:"updatedAt"`
	Name           string    `gorm:"unique;not null" json:"name"`
	Provider       string    `gorm:"not null" json:"provider"`
	NormalizedName string    `gorm:"unique" json:"normalizedName"`
	Users          []User    `gorm:"many2many:user_organizations" json:"users,omitempty"`
	Role           string    `json:"-" gorm:"-"` // Used only internally

Organization represents a unit of users and resources.

func GetCurrentOrganization

func GetCurrentOrganization(req *http.Request) *Organization

GetCurrentOrganization return the user's organization

func GetOrganizationById

func GetOrganizationById(orgID uint) (*Organization, error)

GetOrganizationById returns an organization from database by ID

func (*Organization) BeforeCreate

func (o *Organization) BeforeCreate(tx *gorm.DB) error

func (*Organization) IDString

func (o *Organization) IDString() string

IDString returns the ID as string.

type OrganizationCreated

type OrganizationCreated struct {
	// ID is the created organization ID.
	ID uint

	// UserID is the ID of the user whose login triggered the organization being created.
	UserID uint

OrganizationCreated event is triggered when an organization is created in the system.

type OrganizationEventDispatcher

type OrganizationEventDispatcher struct {
	// contains filtered or unexported fields

OrganizationEventDispatcher dispatches events through the underlying generic event bus.

func NewOrganizationEventDispatcher

func NewOrganizationEventDispatcher(bus EventBus) OrganizationEventDispatcher

NewOrganizationEventDispatcher returns a new OrganizationEventDispatcher instance.

func (OrganizationEventDispatcher) OrganizationCreated

func (d OrganizationEventDispatcher) OrganizationCreated(ctx context.Context, event OrganizationCreated) error

OrganizationCreated dispatches a(n) OrganizationCreated event.

type OrganizationEvents

type OrganizationEvents interface {
	// OrganizationCreated dispatches an OrganizationCreated event.
	OrganizationCreated(ctx context.Context, event OrganizationCreated) error

OrganizationEvents dispatches organization events.

type OrganizationStore

type OrganizationStore interface {
	// EnsureOrganizationExists ensures that an organization exists.
	// If one already exists with the same parameters it succeeds.
	// If one already exists with different parameters (eg. different provider),
	// it returns with an ErrOrganizationConflict error.
	// The function returns whether an organization was created or not, as well as it's ID.
	EnsureOrganizationExists(ctx context.Context, name string, provider string) (bool, uint, error)

	// GetOrganizationMembershipsOf returns the list of organization memberships for a user.
	GetOrganizationMembershipsOf(ctx context.Context, userID uint) ([]UserOrganization, error)

	// RemoveUserFromOrganization removes a user from an organization.
	RemoveUserFromOrganization(ctx context.Context, organizationID uint, userID uint) error

	// ApplyUserMembership ensures that a user is a member of an organization with the necessary role.
	ApplyUserMembership(ctx context.Context, organizationID uint, userID uint, role string) error

OrganizationStore is a persistence layer for organizations.

type OrganizationSyncer

type OrganizationSyncer interface {
	SyncOrganizations(ctx context.Context, user User, upstreamMemberships []UpstreamOrganizationMembership) error

OrganizationSyncer synchronizes organization membership for a user. It creates missing organizations, adds user to and removes from existing organizations, updates organization role. Note: it never deletes organizations, only creates them if they are missing.

func NewOrganizationSyncer

func NewOrganizationSyncer(store OrganizationStore, events OrganizationEvents, logger Logger) OrganizationSyncer

NewOrganizationSyncer returns a new OrganizationSyncer.

type RbacEnforcer

type RbacEnforcer struct {
	// contains filtered or unexported fields

RbacEnforcer makes authorization decisions based on user roles.

func NewRbacEnforcer

func NewRbacEnforcer(roleSource RoleSource, serviceAccountService ServiceAccountService, logger Logger) RbacEnforcer

NewRbacEnforcer returns a new RbacEnforcer.

func (RbacEnforcer) Enforce

func (e RbacEnforcer) Enforce(org *Organization, user *User, path, method string, query url.Values) (bool, error)

Enforce makes authorization decisions.

type RedirectURLConfig

type RedirectURLConfig struct {
	Login  string
	Signup string

RedirectURLConfig contains the URLs the user is redirected to after certain authentication events.

func (*RedirectURLConfig) Process

func (c *RedirectURLConfig) Process() error

Process post-processes the configuration after loading (before validation).

func (RedirectURLConfig) Validate

func (c RedirectURLConfig) Validate() error

Validate validates the configuration.

type RefreshTokenStore

type RefreshTokenStore struct {
	// contains filtered or unexported fields

RefreshTokenStore stores refresh tokens in the underlying store.

func NewRefreshTokenStore

func NewRefreshTokenStore(tokenStore auth.TokenStore) RefreshTokenStore

NewRefreshTokenStore returns a new RefreshTokenStore.

func (RefreshTokenStore) GetRefreshToken

func (s RefreshTokenStore) GetRefreshToken(userID string) (string, error)

GetRefreshToken returns the refresh token from the token store.

func (RefreshTokenStore) SaveRefreshToken

func (s RefreshTokenStore) SaveRefreshToken(userID string, refreshToken string) error

SaveRefreshToken saves the refresh token in the token store.

type RoleBinder

type RoleBinder struct {
	// contains filtered or unexported fields

RoleBinder binds groups from an OIDC ID token to Pipeline roles.

func NewRoleBinder

func NewRoleBinder(defaultRole string, rawBindings map[string]string) (RoleBinder, error)

NewRoleBinder returns a new RoleBinder.

func (RoleBinder) BindRole

func (rb RoleBinder) BindRole(groups []string) string

BindRole binds the highest possible role to the list of provided groups.

type RoleConfig

type RoleConfig struct {
	Default string
	Binding map[string]string

RoleConfig contains role based authorization configuration.

func (RoleConfig) Validate

func (c RoleConfig) Validate() error

Validate validates the configuration.

type RoleSource

type RoleSource interface {
	// FindUserRole returns the user's role in a given organization.
	// Returns false as the second parameter if the user is not a member of the organization.
	FindUserRole(ctx context.Context, organizationID uint, userID uint) (string, bool, error)

RoleSource returns the user's role in a given organization.

type ServiceAccountService

type ServiceAccountService interface {
	ExtractServiceAccount(*http.Request) *User
	IsAdminServiceAccount(*User) bool

func NewServiceAccountService

func NewServiceAccountService() ServiceAccountService

type TokenConfig

type TokenConfig struct {
	SigningKey string
	Issuer     string
	Audience   string

TokenConfig contains auth configuration.

func (TokenConfig) Validate

func (c TokenConfig) Validate() error

Validate validates the configuration.

type TokenManager

type TokenManager interface {
	// GenerateToken generates a token and stores it in the token store.
		sub string,
		expiresAt *time.Time,
		tokenType auth.TokenType,
		tokenText string,
		tokenName string,
		storeSecret bool,
	) (string, string, error)

TokenManager manages tokens.

type UpstreamOrganization

type UpstreamOrganization struct {
	Name     string
	Provider string

UpstreamOrganization represents an organization from the upstream authentication source.

type UpstreamOrganizationMembership

type UpstreamOrganizationMembership struct {
	Organization UpstreamOrganization
	Role         string

UpstreamOrganizationMembership represents an organization membership of a user from the upstream authentication source.

type User

type User struct {
	ID             uint           `gorm:"primary_key" json:"id"`
	CreatedAt      time.Time      `json:"createdAt"`
	UpdatedAt      time.Time      `json:"updatedAt"`
	Name           string         `form:"name" json:"name,omitempty"`
	Email          string         `form:"email" json:"email,omitempty"`
	Login          string         `gorm:"unique;not null" form:"login" json:"login"`
	Image          string         `form:"image" json:"image,omitempty"`
	Organizations  []Organization `gorm:"many2many:user_organizations" json:"organizations,omitempty"`
	Virtual        bool           `json:"-" gorm:"-"` // Used only internally
	APIToken       string         `json:"-" gorm:"-"` // Used only internally
	ServiceAccount bool           `json:"-" gorm:"-"` // Used only internally

User struct

func GetCurrentUser

func GetCurrentUser(req *http.Request) *User

GetCurrentUser returns the current user

func GetUserById

func GetUserById(userId uint) (*User, error)

GetUserById returns user

func (*User) IDString

func (user *User) IDString() string

IDString returns the ID as string

type UserExtractor

type UserExtractor struct{}

func (UserExtractor) GetUserID

func (e UserExtractor) GetUserID(ctx context.Context) (uint, bool)

func (UserExtractor) GetUserLogin

func (e UserExtractor) GetUserLogin(ctx context.Context) (string, bool)

type UserOrganization

type UserOrganization struct {
	User   User
	UserID uint

	Organization   Organization
	OrganizationID uint

	Role string `gorm:"default:'member'"`

UserOrganization describes a user organization membership.


Path Synopsis