Documentation
Index ¶
- Constants
- Variables
- func DelCookie(w http.ResponseWriter, r *http.Request, name string)
- func GetCurrentOrganizationID(ctx context.Context) (uint, bool)
- func GetCurrentUserID(req *http.Request) uint
- func GetOrgNameFromVirtualUser(virtualUser string) string
- func GetUserNickNameById(userId uint) (userName string)
- func GormErrorToStatusCode(err error) int
- func Init(db *gorm.DB, config Config, tokenStore bauth.TokenStore, ...)
- func Install(engine *gin.Engine)
- func InternalUserHandler(ctx *gin.Context)
- func Migrate(db *gorm.DB, logger logrus.FieldLogger) error
- func NewBanzaiDeregisterHandler(tokenStore bauth.TokenStore) func(*auth.Context)
- func SetCookie(w http.ResponseWriter, r *http.Request, name, value string)
- func SetCurrentOrganizationID(ctx context.Context, orgID uint) context.Context
- func StartTokenStoreGC(tokenStore bauth.TokenStore)
- func SyncOrgsForUser(organizationSyncer OIDCOrganizationSyncer, refreshTokenStore RefreshTokenStore, ...) error
- func TLSConfigForClientAuth(caCertFile string) (*tls.Config, error)
- type AuthIdentity
- type AuthorizeHandler
- type Authorizer
- type BanzaiSessionStorer
- type BanzaiUserStorer
- type CICDUser
- type CLIConfig
- type ClusterTokenGenerator
- type Config
- type CookieConfig
- type EventBus
- type IDTokenClaims
- type Logger
- type OIDCConfig
- type OIDCOrganizationSyncer
- type OIDCProvider
- func (provider OIDCProvider) Callback(context *auth.Context)
- func (provider OIDCProvider) ConfigAuth(*auth.Auth)
- func (provider OIDCProvider) Deregister(context *auth.Context)
- func (OIDCProvider) GetName() string
- func (provider OIDCProvider) Login(context *auth.Context)
- func (OIDCProvider) Logout(context *auth.Context)
- func (provider OIDCProvider) OAuthConfig(context *auth.Context) *oauth2.Config
- func (provider OIDCProvider) RedeemRefreshToken(context *auth.Context, refreshToken string) (*IDTokenClaims, *oauth2.Token, error)
- func (provider OIDCProvider) Register(context *auth.Context)
- func (OIDCProvider) ServeHTTP(*auth.Context)
- type OIDCProviderConfig
- type Organization
- type OrganizationCreated
- type OrganizationEventDispatcher
- type OrganizationEvents
- type OrganizationStore
- type OrganizationSyncer
- type RbacEnforcer
- type RedirectURLConfig
- type RefreshTokenStore
- type RoleBinder
- type RoleConfig
- type RoleSource
- type ServiceAccountService
- type TokenConfig
- type TokenManager
- type UpstreamOrganization
- type UpstreamOrganizationMembership
- type User
- type UserExtractor
- type UserOrganization
Constants ¶
const ( RoleAdmin = "admin" RoleMember = "member" )
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" )
const BanzaiCLIClient = "banzai-cli"
const ClusterToken auth.TokenType = "cluster"
ClusterToken is the token given to clusters to manage themselves.
const ErrOrganizationConflict = errors.Sentinel("organization already exists, but with mismatching parameters")
ErrOrganizationConflict is returned when an organization exists, but with mismatching parameters.
const PipelineSessionCookie = "_banzai_session"
PipelineSessionCookie holds the name of the Cookie Pipeline sets in the browser
const SessionCookieHTTPOnly = true
SessionCookieHTTPOnly describes if the cookies should be accessible from HTTP requests only (no JS)
const SessionCookieMaxAge = 30 * 24 * 60 * 60
SessionCookieMaxAge holds long an authenticated session should be valid in seconds
const SessionCookieName = "Pipeline session token"
SessionCookieName is the name of the token that is stored in the session cookie
const UserTokenType pkgAuth.TokenType = "user"
UserTokenType is the token type used for API sessions
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)
Variables ¶
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
Functions ¶
func DelCookie ¶
func DelCookie(w http.ResponseWriter, r *http.Request, name string)
DelCookie deletes a cookie.
func GetCurrentOrganizationID ¶
GetCurrentOrganizationID return the user's organization ID.
func GetCurrentUserID ¶
GetCurrentUserID returns the current user ID.
func GetOrgNameFromVirtualUser ¶
GetOrgNameFromVirtualUser returns the organization name for which the virtual user has access
func GetUserNickNameById ¶
GetUserNickNameById returns user's login name
func GormErrorToStatusCode ¶
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 ¶
Install the whole OAuth and JWT Token based authn/authz mechanism to the specified Gin Engine.
func InternalUserHandler ¶
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 ¶
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
Types ¶
type AuthIdentity ¶
type AuthIdentity struct { ID uint `gorm:"primary_key" json:"id"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` auth_identity.Basic auth_identity.SignLogs }
AuthIdentity auth identity session model
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.
type BanzaiSessionStorer ¶
type BanzaiSessionStorer struct { auth.SessionStorer // 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 { auth.UserStorer // contains filtered or unexported fields }
BanzaiUserStorer struct
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
type CLIConfig ¶
type CLIConfig struct {
ClientID string
}
CLIConfig contains cli auth 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.
type CookieConfig ¶
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 OIDCConfig ¶
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 { *OIDCProviderConfig // 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) 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 https://www.oauth.com/oauth2-servers/access-tokens/refreshing-access-tokens/
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 ¶
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 ¶
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 ¶
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. GenerateToken( sub string, expiresAt *time.Time, tokenType auth.TokenType, tokenText string, tokenName string, storeSecret bool, ) (string, string, error) }
TokenManager manages tokens.
type UpstreamOrganization ¶
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 ¶
GetCurrentUser returns the current user
type UserExtractor ¶
type UserExtractor struct{}
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.
Source Files
Directories
Path | Synopsis |
---|---|
authadapter | |
authdriver |