auth

package
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2022 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ScopeAnonymous          = "anonymous"
	ContextUserInfo         = "auth0_user_info"
	ContextBFFClaims        = "auth0_bff_claims"
	ContextRegisteredClaims = "auth0_registered_claims"
)
View Source
const (
	CSRFCookie          = "csrf_token"
	CSRFReferenceCookie = "csrf_reference_token"
	CSRFHeader          = "X-CSRF-TOKEN"
)

Parameters and headers for double-cookie submit CSRF protection

View Source
const (
	// BFF Organization management
	ReadOrganizations   = "read:organizations"
	CreateOrganizations = "create:organizations"
	SwitchOrganizations = "switch:organizations"

	// Collaborators management
	ReadCollaborators   = "read:collaborators"
	UpdateCollaborators = "update:collaborators"

	// GDS Registration management
	ReadVASP   = "read:vasp"
	UpdateVASP = "update:vasp"

	// Posting announcements
	CreateAnnouncements = "create:announcements"

	// User roles
	LeaderRole       = "Organization Leader"
	CollaboratorRole = "Organization Collaborator"
)

TODO: Should these be configurable?

Variables

View Source
var (
	ErrUnauthenticated  = errors.New("request is unauthenticated")
	ErrNoClaims         = errors.New("no claims found on the request context")
	ErrNoUserInfo       = errors.New("no user info found on the request context")
	ErrInvalidAuthToken = errors.New("invalid authorization token")
	ErrNoAuthorization  = errors.New("could not authorize request")
	ErrAuthRequired     = errors.New("this endpoint requires authentication")
	ErrNoPermission     = errors.New("user does not have permission to perform this operation")
	ErrNoAuthUser       = errors.New("could not identify authenticated user in request")
	ErrNoAuthUserData   = errors.New("could not retrieve user data")
	ErrIncompleteUser   = errors.New("user is missing required fields")
	ErrUnverifiedUser   = errors.New("user is not verified")
	ErrCSRFVerification = errors.New("csrf verification failed for request")
)
View Source
var AnonymousClaims = Claims{Scope: ScopeAnonymous, Permissions: nil}

AnonymousClaims are used to identify unauthenticated requests that have no permissions.

Functions

func Authenticate

func Authenticate(conf config.AuthConfig, options ...jwks.ProviderOption) (_ gin.HandlerFunc, err error)

Authenticate is a middleware that will parse and validate any Auth0 token provided in the header of the request and will add the claims to the request context for downstream processing. If no JWT token is present in the header, this middleware will mark the request as unauthenticated but it does not perform any authorization. If the JWT token is invalid this middleware will return a 403 Forbidden response.

func Authorize

func Authorize(permissions ...string) gin.HandlerFunc

Authorize is a middleware that requires specific permissions in an authenticated user's claims. If those permissions do not match or the request is unauthenticated the middleware returns a 401 Unauthorized response. The Authorize middleware must follow the Authenticate middleware.

func DoubleCookie

func DoubleCookie() gin.HandlerFunc

DoubleCookie is a Cross-Site Request Forgery (CSR/XSRF) protection middleware that checks the presence of an X-CSRF-TOKEN header containing a cryptographically random token that matches a token contained in the CSRF-TOKEN cookie in the request. Because of the same-origin poicy, an attacker cannot access the cookies or scripts of the safe site, therefore the X-CSRF-TOKEN header cannot be forged, and if it is omitted because it is being re-posted by an attacker site then the request will be rejected with a 403 error. Note that this protection requires TLS to prevent MITM.

func GenerateCSRFToken

func GenerateCSRFToken() (_ string, err error)

func GetRegisteredClaims

func GetRegisteredClaims(c *gin.Context) (*validator.RegisteredClaims, error)

GetRegisteredClaims fetches and parses the access token claims from the gin context. Returns an error if no claims exist on the context rather than returning zero-valued claims. Panics if the claims are an incorrect type, but should be recovered.

func GetUserInfo

func GetUserInfo(c *gin.Context) (*management.User, error)

GetUserInfo fetches the user info from the gin context. Returns an error if no user exists on the context or if the user value is nil. Panics if user is incorrect type.

func NewClaims

func NewClaims() validator.CustomClaims

NewClaims implements the validator custom claims initializer interface.

func NewManagementClient added in v1.5.1

func NewManagementClient(conf config.AuthConfig) (manager *management.Management, err error)

NewManagementClient creates a new Auth0 management client from the configuration.

func SetDoubleCookieToken

func SetDoubleCookieToken(c *gin.Context, domain string, expires time.Time) error

SetDoubleCookieToken is a helper function to set cookies on a gin request.

func UserDisplayName added in v1.6.0

func UserDisplayName(user *management.User) (string, error)

UserDisplayName is a helper to get the user's display name from the Auth0 user record. This should be used when the backend needs to retrieve a user-facing display name for the user and returns an error if no name is available.

func UserInfo

func UserInfo(conf config.AuthConfig) (_ gin.HandlerFunc, err error)

UserInfo is a middleware that requires an authenticated user's claims, it then fetches the user profile including app_data from Auth0 and adds them to the Gin context. This middleware is primarily used for endpoints that manage the user state, not for endpoints that simply need access to resources or permissions (those should be added to the claims to prevent calls to Auth0 on every RPC). If the user is not authenticated before this step, a 401 is returned.

func WithHTTPClient

func WithHTTPClient(client *http.Client) jwks.ProviderOption

WithHTTPClient configures the authentication provider to use the specified client. This is used in tests to configure the client to use a localhost TLS httptest server. This option should NOT be used in production.

NOTE: this has been added to the jwks code but not tagged yet. Once the library gets updated we can remove this function and use their implementation. https://github.com/auth0/go-jwt-middleware/blob/master/jwks/provider.go#L55

Types

type AppMetadata

type AppMetadata struct {
	OrgID         string   `json:"orgid"`
	VASPs         VASPs    `json:"vasps"`
	Organizations []string `json:"organizations"`
}

AppMetadata makes it easier to serialize and deserialize JSON from the auth0 app_metadata assigned to the user by the BFF (and ensures the data is structured).

func (*AppMetadata) AddOrganization added in v1.6.0

func (meta *AppMetadata) AddOrganization(orgID string)

AddOrganization adds an organization ID to the set of organizations the user is a part of. This method is idempotent and will not add the organization ID if it already exists.

func (*AppMetadata) ClearOrganization added in v1.6.0

func (meta *AppMetadata) ClearOrganization()

ClearOrganization removes all organization-related data from the app metadata.

func (*AppMetadata) Dump

func (meta *AppMetadata) Dump() (appdata map[string]interface{}, err error)

func (*AppMetadata) Equals added in v1.6.0

func (meta *AppMetadata) Equals(other *AppMetadata) bool

TODO: Hash-based method might be more maintainable, but this avoids error handling for now

func (*AppMetadata) GetOrganizations added in v1.6.0

func (meta *AppMetadata) GetOrganizations() []string

func (*AppMetadata) Load

func (meta *AppMetadata) Load(appdata map[string]interface{}) (err error)

func (*AppMetadata) RemoveOrganization added in v1.6.0

func (meta *AppMetadata) RemoveOrganization(orgID string)

RemoveOrganization removes an organization ID from the set of organizations the user is a part of. This method is idempotent and will not error if the organization ID does not exist in the metadata.

func (*AppMetadata) UpdateOrganization added in v1.6.0

func (meta *AppMetadata) UpdateOrganization(org *models.Organization)

UpdateOrganization completely replaces the organization data in the app metadata with data from the organization record.

type Claims

type Claims struct {
	Scope         string   `json:"scope"`
	Permissions   []string `json:"permissions"`
	OrgID         string   `json:"https://vaspdirectory.net/orgid"`
	VASPs         VASPs    `json:"https://vaspdirectory.net/vasps"`
	Organizations []string `json:"https://vaspdirectory.net/organizations"`
	Email         string   `json:"https://vaspdirectory.net/email"`
}

Claims extracts custom data from the JWT token provided by Auth0

func GetClaims

func GetClaims(c *gin.Context) (*Claims, error)

GetClaims fetches and parses the BFF claims from the gin context. Returns an error if no claims exist on the context rather than returning anonymous claims. Panics if the claims are an incorrect type, but the panic should be recovered by middleware.

func (Claims) HasAllPermissions

func (c Claims) HasAllPermissions(requiredPermissions ...string) bool

HasAllPermissions checks if all specified permissions are in the claims.

func (Claims) HasPermission

func (c Claims) HasPermission(requiredPermission string) bool

HasPermission checks if the claims contain the specified permission.

func (Claims) HasScope

func (c Claims) HasScope(requiredScope string) bool

HasScope checks if the claims contain the specified scope.

func (Claims) IsAnonymous

func (c Claims) IsAnonymous() bool

IsAnonymous returns true if the claims refer to an anonymous user

func (Claims) Validate

func (c Claims) Validate(ctx context.Context) error

Validate implements the validator.CustomClaims interface for Auth0 parsing. Claims can have empty scope (e.g. no permissions) and no associated VASP.

type UserProfile added in v1.6.1

type UserProfile struct {
	Name  string
	Roles []string
}

UserProfile is a subset of the Auth0 user record that can be safely cached on the BFF server.

type VASPs

type VASPs struct {
	MainNet string `json:"mainnet"`
	TestNet string `json:"testnet"`
}

Directories

Path Synopsis
Package authtest provides a wrapped httptest.Server that will respond to auth0 requests.
Package authtest provides a wrapped httptest.Server that will respond to auth0 requests.
Package clive provides CLI-Live interactions with Auth0 by running a local server for OAuth challenges and handling them on behalf of the user.
Package clive provides CLI-Live interactions with Auth0 by running a local server for OAuth challenges and handling them on behalf of the user.

Jump to

Keyboard shortcuts

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