authn

package
v11.1.4-modfix Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2024 License: AGPL-3.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ClientAPIKey      = "auth.client.api-key" // #nosec G101
	ClientAnonymous   = "auth.client.anonymous"
	ClientBasic       = "auth.client.basic"
	ClientJWT         = "auth.client.jwt"
	ClientExtendedJWT = "auth.client.extended-jwt"
	ClientRender      = "auth.client.render"
	ClientSession     = "auth.client.session"
	ClientForm        = "auth.client.form"
	ClientProxy       = "auth.client.proxy"
	ClientSAML        = "auth.client.saml"
)
View Source
const (
	MetaKeyUsername   = "username"
	MetaKeyAuthModule = "authModule"
	MetaKeyIsLogin    = "isLogin"
)
View Source
const (
	KeyOAuthPKCE  = "pkce"
	KeyOAuthState = "state"
)
View Source
const (
	NamespaceUser           = identity.NamespaceUser
	NamespaceAPIKey         = identity.NamespaceAPIKey
	NamespaceServiceAccount = identity.NamespaceServiceAccount
	NamespaceAnonymous      = identity.NamespaceAnonymous
	NamespaceRenderService  = identity.NamespaceRenderService
	NamespaceAccessPolicy   = identity.NamespaceAccessPolicy
)
View Source
const GlobalOrgID = int64(0)

Variables

View Source
var (
	ErrTokenNeedsRotation  = errutil.Unauthorized("session.token.rotate", errutil.WithLogLevel(errutil.LevelDebug))
	ErrUnsupportedClient   = errutil.BadRequest("auth.client.unsupported")
	ErrClientNotConfigured = errutil.BadRequest("auth.client.notConfigured")
	ErrUnsupportedIdentity = errutil.NotImplemented("auth.identity.unsupported")
	ErrExpiredAccessToken  = errutil.Unauthorized("oauth.expired-token", errutil.WithPublicMessage("OAuth access token expired"))
)
View Source
var (
	ParseNamespaceID      = identity.ParseNamespaceID
	MustParseNamespaceID  = identity.MustParseNamespaceID
	NewNamespaceID        = identity.NewNamespaceID
	NewNamespaceIDString  = identity.NewNamespaceIDString
	ErrInvalidNamespaceID = identity.ErrInvalidNamespaceID
)
View Source
var AnonymousNamespaceID = NewNamespaceID(NamespaceAnonymous, 0)

Functions

func ClientWithPrefix

func ClientWithPrefix(name string) string

ClientWithPrefix returns a client name prefixed with "auth.client."

func DeleteSessionCookie

func DeleteSessionCookie(w http.ResponseWriter, cfg *setting.Cfg)

func HandleLoginRedirect

func HandleLoginRedirect(r *http.Request, w http.ResponseWriter, cfg *setting.Cfg, identity *Identity, validator RedirectValidator)

HandleLoginRedirect is a utility function to perform common operations after a successful login and redirects

func HandleLoginRedirectResponse

func HandleLoginRedirectResponse(r *http.Request, w http.ResponseWriter, cfg *setting.Cfg, identity *Identity, validator RedirectValidator) *response.RedirectResponse

HandleLoginRedirectResponse is a utility function to perform common operations after a successful login and return a response.RedirectResponse

func HandleLoginResponse

func HandleLoginResponse(r *http.Request, w http.ResponseWriter, cfg *setting.Cfg, identity *Identity, validator RedirectValidator) *response.NormalResponse

HandleLoginResponse is a utility function to perform common operations after a successful login and returns response.NormalResponse

func WriteSessionCookie

func WriteSessionCookie(w http.ResponseWriter, cfg *setting.Cfg, token *usertoken.UserToken)

Types

type Client

type Client interface {
	// Name returns the name of a client
	Name() string
	// Authenticate performs the authentication for the request
	Authenticate(ctx context.Context, r *Request) (*Identity, error)
	// IsEnabled returns the enabled status of the client
	IsEnabled() bool
}

type ClientParams

type ClientParams struct {
	// SyncUser updates the internal representation of the identity from the identity provided
	SyncUser bool
	// AllowSignUp Adds identity to DB if it doesn't exist when, only work if SyncUser is enabled
	AllowSignUp bool
	// EnableUser will ensure the user is enabled, only work if SyncUser is enabled
	EnableUser bool
	// FetchSyncedUser ensure that all required information is added to the identity
	FetchSyncedUser bool
	// SyncTeams will sync the groups from identity to teams in grafana, enterprise only feature
	SyncTeams bool
	// SyncOrgRoles will sync the roles from the identity to orgs in grafana
	SyncOrgRoles bool
	// CacheAuthProxyKey  if this key is set we will try to cache the user id for proxy client
	CacheAuthProxyKey string
	// LookUpParams are the arguments used to look up the entity in the DB.
	LookUpParams login.UserLookupParams
	// SyncPermissions ensure that permissions are loaded from DB and added to the identity
	SyncPermissions bool
	// FetchPermissionsParams are the arguments used to fetch permissions from the DB
	FetchPermissionsParams FetchPermissionsParams
	// AllowGlobalOrg would allow a client to authenticate in global scope AKA org 0
	AllowGlobalOrg bool
}

ClientParams are hints to the auth service about how to handle the identity management from the authenticating client.

type ContextAwareClient

type ContextAwareClient interface {
	Client
	// Test should return true if client can be used to authenticate request
	Test(ctx context.Context, r *Request) bool
	// Priority for the client, a lower number means higher priority
	Priority() uint
}

ContextAwareClient is an optional interface that auth client can implement. Clients that implements this interface will be tried during request authentication.

type FetchPermissionsParams

type FetchPermissionsParams struct {
	// ActionsLookup will restrict the permissions to only these actions
	ActionsLookup []string
	// Roles permissions will be directly added to the identity permissions
	Roles []string
}

type HookClient

type HookClient interface {
	Client
	Hook(ctx context.Context, identity *Identity, r *Request) error
}

HookClient is an optional interface that auth clients can implement. Clients that implements this interface can specify an auth hook that will be called only for that client.

type Identity

type Identity struct {
	// ID is the unique identifier for the entity in the Grafana database.
	// If the entity is not found in the DB or this entity is non-persistent, this field will be empty.
	ID NamespaceID
	// UID is a unique identifier stored for the entity in Grafana database. Not all entities support uid so it can be empty.
	UID NamespaceID
	// OrgID is the active organization for the entity.
	OrgID int64
	// OrgName is the name of the active organization.
	OrgName string
	// OrgRoles is the list of organizations the entity is a member of and their roles.
	OrgRoles map[int64]org.RoleType
	// Login is the shorthand identifier of the entity. Should be unique.
	Login string
	// Name is the display name of the entity. It is not guaranteed to be unique.
	Name string
	// Email is the email address of the entity. Should be unique.
	Email string
	// EmailVerified is true if entity has verified their email with grafana.
	EmailVerified bool
	// IsGrafanaAdmin is true if the entity is a Grafana admin.
	IsGrafanaAdmin *bool
	// AuthenticatedBy is the name of the authentication client that was used to authenticate the current Identity.
	// For example, "password", "apikey", "auth_ldap" or "auth_azuread".
	AuthenticatedBy string
	// AuthId is the unique identifier for the entity in the external system.
	// Empty if the identity is provided by Grafana.
	AuthID string
	// IsDisabled is true if the entity is disabled.
	IsDisabled bool
	// HelpFlags1 is the help flags for the entity.
	HelpFlags1 user.HelpFlags1
	// LastSeenAt is the time when the entity was last seen.
	LastSeenAt time.Time
	// Teams is the list of teams the entity is a member of.
	Teams []int64
	// idP Groups that the entity is a member of. This is only populated if the
	// identity provider supports groups.
	Groups []string
	// OAuthToken is the OAuth token used to authenticate the entity.
	OAuthToken *oauth2.Token
	// SessionToken is the session token used to authenticate the entity.
	SessionToken *usertoken.UserToken
	// ClientParams are hints for the auth service on how to handle the identity.
	// Set by the authenticating client.
	ClientParams ClientParams
	// Permissions is the list of permissions the entity has.
	Permissions map[int64]map[string][]string
	// IDToken is a signed token representing the identity that can be forwarded to plugins and external services.
	// Will only be set when featuremgmt.FlagIdForwarding is enabled.
	IDToken string
}

func (*Identity) ExternalUserInfo

func (i *Identity) ExternalUserInfo() login.ExternalUserInfo

func (*Identity) GetAuthID

func (i *Identity) GetAuthID() string

func (*Identity) GetAuthenticatedBy

func (i *Identity) GetAuthenticatedBy() string

func (*Identity) GetCacheKey

func (i *Identity) GetCacheKey() string

func (*Identity) GetDisplayName

func (i *Identity) GetDisplayName() string

func (*Identity) GetEmail

func (i *Identity) GetEmail() string

func (*Identity) GetGlobalPermissions

func (i *Identity) GetGlobalPermissions() map[string][]string

GetGlobalPermissions returns the permissions of the active entity that are available across all organizations

func (*Identity) GetID

func (i *Identity) GetID() NamespaceID

func (*Identity) GetIDToken

func (i *Identity) GetIDToken() string

func (*Identity) GetIsGrafanaAdmin

func (i *Identity) GetIsGrafanaAdmin() bool

func (*Identity) GetLogin

func (i *Identity) GetLogin() string

func (*Identity) GetNamespacedID

func (i *Identity) GetNamespacedID() (namespace identity.Namespace, identifier string)

func (*Identity) GetOrgID

func (i *Identity) GetOrgID() int64

func (*Identity) GetOrgName

func (i *Identity) GetOrgName() string

func (*Identity) GetOrgRole

func (i *Identity) GetOrgRole() org.RoleType

func (*Identity) GetPermissions

func (i *Identity) GetPermissions() map[string][]string

func (*Identity) GetTeams

func (i *Identity) GetTeams() []int64

func (*Identity) GetUID

func (i *Identity) GetUID() NamespaceID

func (*Identity) HasRole

func (i *Identity) HasRole(role org.RoleType) bool

func (*Identity) HasUniqueId

func (i *Identity) HasUniqueId() bool

func (*Identity) IsAuthenticatedBy

func (i *Identity) IsAuthenticatedBy(providers ...string) bool

func (*Identity) IsEmailVerified

func (i *Identity) IsEmailVerified() bool

func (*Identity) IsNil

func (i *Identity) IsNil() bool

func (*Identity) SignedInUser

func (i *Identity) SignedInUser() *user.SignedInUser

SignedInUser returns a SignedInUser from the identity.

type IdentityResolverClient

type IdentityResolverClient interface {
	Client
	Namespace() string
	ResolveIdentity(ctx context.Context, orgID int64, namespaceID NamespaceID) (*Identity, error)
}

IdentityResolverClient is an optional interface that auth clients can implement. Clients that implements this interface can resolve an full identity from an orgID and namespaceID.

type IdentitySynchronizer

type IdentitySynchronizer interface {
	SyncIdentity(ctx context.Context, identity *Identity) error
}

type LogoutClient

type LogoutClient interface {
	Client
	Logout(ctx context.Context, user Requester) (*Redirect, bool)
}

LogoutCLient is an optional interface that auth client can implement. Clients that implements this interface can implement additional logic that should happen during logout and supports client specific redirect URL.

type Namespace

type Namespace = identity.Namespace

type NamespaceID

type NamespaceID = identity.NamespaceID

type PasswordClient

type PasswordClient interface {
	AuthenticatePassword(ctx context.Context, r *Request, username, password string) (*Identity, error)
}

type PostAuthHookFn

type PostAuthHookFn func(ctx context.Context, identity *Identity, r *Request) error

type PostLoginHookFn

type PostLoginHookFn func(ctx context.Context, identity *Identity, r *Request, err error)

type PreLogoutHookFn

type PreLogoutHookFn func(ctx context.Context, requester identity.Requester, sessionToken *usertoken.UserToken) error

type ProxyClient

type ProxyClient interface {
	AuthenticateProxy(ctx context.Context, r *Request, username string, additional map[string]string) (*Identity, error)
}

type Redirect

type Redirect struct {
	// Url used for redirect
	URL string
	// Extra contains data used for redirect, e.g. for oauth this would be state and pkce
	Extra map[string]string
}

type RedirectClient

type RedirectClient interface {
	Client
	RedirectURL(ctx context.Context, r *Request) (*Redirect, error)
}

RedirectClient is an optional interface that auth clients can implement. Clients that implements this interface can be used to generate redirect urls for authentication flows, e.g. oauth clients.

type RedirectValidator

type RedirectValidator func(url string) error

type Request

type Request struct {
	// OrgID will be populated by authn.Service
	OrgID int64
	// HTTPRequest is the original HTTP request to authenticate
	HTTPRequest *http.Request

	// Resp is the response writer to use for the request
	// Used to set cookies and headers
	Resp web.ResponseWriter
	// contains filtered or unexported fields
}

func (*Request) GetMeta

func (r *Request) GetMeta(k string) string

func (*Request) SetMeta

func (r *Request) SetMeta(k, v string)

type Requester

type Requester = identity.Requester

type Service

type Service interface {
	// Authenticate authenticates a request
	Authenticate(ctx context.Context, r *Request) (*Identity, error)
	// RegisterPostAuthHook registers a hook with a priority that is called after a successful authentication.
	// A lower number means higher priority.
	RegisterPostAuthHook(hook PostAuthHookFn, priority uint)
	// Login authenticates a request and creates a session on successful authentication.
	Login(ctx context.Context, client string, r *Request) (*Identity, error)
	// RegisterPostLoginHook registers a hook that that is called after a login request.
	// A lower number means higher priority.
	RegisterPostLoginHook(hook PostLoginHookFn, priority uint)
	// RedirectURL will generate url that we can use to initiate auth flow for supported clients.
	RedirectURL(ctx context.Context, client string, r *Request) (*Redirect, error)
	// Logout revokes session token and does additional clean up if client used to authenticate supports it
	Logout(ctx context.Context, user identity.Requester, sessionToken *usertoken.UserToken) (*Redirect, error)
	// RegisterPreLogoutHook registers a hook that is called before a logout request.
	RegisterPreLogoutHook(hook PreLogoutHookFn, priority uint)
	// ResolveIdentity resolves an identity from org and namespace id.
	ResolveIdentity(ctx context.Context, orgID int64, namespaceID NamespaceID) (*Identity, error)

	// RegisterClient will register a new authn.Client that can be used for authentication
	RegisterClient(c Client)

	// IsClientEnabled returns true if the client is enabled.
	//
	// The client lookup follows the same formats used by the `authn` package
	// constants.
	//
	// For OAuth clients, use the `authn.ClientWithPrefix(name)` to get the provider
	// name. Append the prefix `auth.client.{providerName}`.
	//
	// Example:
	// - "saml" = "auth.client.saml"
	// - "github" = "auth.client.github"
	IsClientEnabled(client string) bool
}

type UsageStatClient

type UsageStatClient interface {
	Client
	UsageStatFn(ctx context.Context) (map[string]any, error)
}

UsageStatClient is an optional interface that auth clients can implement. Clients that implements this interface can specify a usage stat collection hook.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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