auth

package
v0.40.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: Apache-2.0 Imports: 16 Imported by: 8

Documentation

Overview

Package auth provides caller identity, capability-based authorization, and context propagation for request actors including authenticated users, service accounts, and anonymous visitors

Index

Constants

View Source
const (
	// Authorization is the key used in HTTP headers or cookies to represent the authorization token
	Authorization = "Authorization"
	// APIKeyHeader is the key used in HTTP headers to represent the API key
	APIKeyHeader = "X-API-Key" //nolint:gosec
	// AccessTokenCookie is the key used in cookies to represent the access token
	AccessTokenCookie = "access_token"
	// RefreshTokenCookie is the key used in cookies to represent the refresh token
	RefreshTokenCookie = "refresh_token"
	// UserIDHeader is the header used by system admins to specify target user ID
	UserIDHeader = "X-User-ID"
	// OrganizationIDHeader is the header used by system admins to specify target organization ID
	OrganizationIDHeader = "X-Organization-ID"
	// ImpersonationScheme is the authorization scheme for impersonation tokens
	ImpersonationScheme = "Impersonation"
)
View Source
const (
	// UserSubjectType is the subject type for user accounts
	UserSubjectType = "user"
	// ServiceSubjectType is the subject type for service accounts
	ServiceSubjectType = "service"
)
View Source
const (
	// SupportSubjectID is the stable subject id of the virtual support identity
	SupportSubjectID = "01JSPPRT000000000000000000"
	// SupportDisplayName is the display name of the virtual support identity
	SupportDisplayName = "Openlane Support"
	// SupportEmail is the email of the virtual support identity
	SupportEmail = "support@theopenlane.io"

	// IntegrationSubjectID is the stable subject id of the virtual integration actor
	IntegrationSubjectID = "01JNTGACTR0000000000000000"
	// IntegrationDisplayName is the display name of the virtual integration actor
	IntegrationDisplayName = "Openlane Integrations"
	// IntegrationEmail is the email of the virtual integration actor
	IntegrationEmail = "integrations@theopenlane.io"
)

Stable, statically assigned virtual identities used for record attribution when no real user performs an action

Variables

View Source
var (
	// ErrNoClaims is returned when no claims are found on the request context
	ErrNoClaims = errors.New("no claims found on the request context")
	// ErrNoUserInfo is returned when no user info is found on the request context
	ErrNoUserInfo = errors.New("no user info found on the request context")
	// ErrNoAuthUser is returned when no authenticated user is found on the request context
	ErrNoAuthUser = errors.New("could not identify authenticated user in request")
	// ErrUnverifiedUser is returned when the user is not verified
	ErrUnverifiedUser = errors.New("user is not verified")
	// ErrParseBearer is returned when the bearer token could not be parsed from the authorization header
	ErrParseBearer = errors.New("could not parse bearer token from authorization header")
	// ErrNoAuthorization is returned when no authorization header is found in the request
	ErrNoAuthorization = errors.New("no authorization header in request")
	// ErrNoAPIKey is returned when no API key is found in the request
	ErrNoAPIKey = errors.New("no API key found in request")
	// ErrNoRequest is returned when no request is found on the context
	ErrNoRequest = errors.New("no request found on the context")
	// ErrNoRefreshToken is returned when no refresh token is found on the request
	ErrNoRefreshToken = errors.New("no refresh token available on request")
	// ErrRefreshDisabled is returned when re-authentication with refresh tokens is disabled
	ErrRefreshDisabled = errors.New("re-authentication with refresh tokens disabled")
	// ErrUnableToConstructValidator is returned when the validator cannot be constructed
	ErrUnableToConstructValidator = errors.New("unable to construct validator")
	// ErrPasswordTooWeak is returned when the password is too weak
	ErrPasswordTooWeak = errors.New("password is too weak: use a combination of upper and lower case letters, numbers, and special characters")
	// ErrCouldNotFetchSubscription is returned when the subscription could not be fetched
	ErrCouldNotFetchSubscription = errors.New("could not fetch subscription")
	// ErrNoOrganizationID is returned when no organization ID can be resolved from the context or input
	ErrNoOrganizationID = errors.New("no organization ID found in context or input")
	// ErrUnauthorizedOrg is returned when the provided organization ID is not in the caller's authorized list
	ErrUnauthorizedOrg = errors.New("organization is not authorized for the current caller")
	// ErrRandomStateGeneration is returned when random OAuth state generation fails
	ErrRandomStateGeneration = errors.New("oauth state generation failed")
)
View Source
var AccessTokenKey = contextx.NewKey[string]()

AccessTokenKey stores and retrieves the request access token.

View Source
var ActiveAssessmentIDKey = contextx.NewKey[string]()

ActiveAssessmentIDKey stores the assessment ID for the current anonymous questionnaire request.

View Source
var ActiveAssessmentPreviewKey = contextx.NewKey[bool]()

ActiveAssessmentPreviewKey marks the current anonymous questionnaire request as a sender preview (is_test)

View Source
var ActiveCampaignIDKey = contextx.NewKey[string]()

ActiveCampaignIDKey stores the campaign id for the questionnaire request

View Source
var ActiveTrustCenterIDKey = contextx.NewKey[string]()

ActiveTrustCenterIDKey stores the trust center ID for the current anonymous trust center request.

View Source
var CallerKey = contextx.NewKey[*Caller]()

CallerKey is the context key for storing and retrieving a *Caller

View Source
var RefreshTokenKey = contextx.NewKey[string]()

RefreshTokenKey stores and retrieves the request refresh token.

View Source
var RequestIDKey = contextx.NewKey[string]()

RequestIDKey stores and retrieves the request ID.

Functions

func APIKey added in v0.37.0

func APIKey(r *http.Request) (string, error)

APIKey retrieves the API key from the X-API-Key header.

func AccessTokenFromContext added in v0.4.2

func AccessTokenFromContext(ctx context.Context) (string, bool)

AccessTokenFromContext returns the request access token from ctx when present.

func AddOrganizationIDToContext

func AddOrganizationIDToContext(ctx context.Context, orgID string) (context.Context, error)

AddOrganizationIDToContext appends an authorized organization ID to the context. This generally should not be used, as the authorized organization should be determined by the claims or the token. This is only used in cases where the a user is newly authorized to an organization and the organization ID is not in the token claims

func BearerToken added in v0.37.0

func BearerToken(r *http.Request) (string, error)

BearerToken retrieves the bearer token from the authorization header and parses it to return only the JWT access token component of the header. Alternatively, if the authorization header is not present, then the token is fetched from cookies. If the header is missing or the token is not available, an error is returned.

NOTE: the authorization header takes precedence over access tokens in cookies.

func ClearAuthCookies

func ClearAuthCookies(w http.ResponseWriter, c sessions.CookieConfig)

ClearAuthCookies clears the access and refresh token cookies to effectively log out a user. The supplied CookieConfig must match the one the cookies were set with via SetAuthCookies (domain, path, secure, samesite); otherwise the browser will not match the expiry cookie and the original cookies will persist. Pass the same SessionConfig.CookieConfig used at login rather than a global default.

func CookieExpired

func CookieExpired(cookie *http.Cookie) bool

CookieExpired checks to see if a cookie is expired

func EnsureCallerOrg added in v0.35.4

func EnsureCallerOrg(ctx context.Context, orgID string) context.Context

EnsureCallerOrg returns ctx with orgID as the caller's active organization when the caller has none

func EnsureIntegrationCaller added in v0.35.4

func EnsureIntegrationCaller(ctx context.Context, orgID string) context.Context

EnsureIntegrationCaller fills the integration actor identity on subject-less callers, retaining attributed ones, granting audit-log bypass either way so integration-driven writes skip history tables

func GenerateOAuthState added in v0.26.0

func GenerateOAuthState(entropyBytes int) (string, error)

GenerateOAuthState returns a URL-safe, cryptographically random OAuth state value.

func GetAPIKey added in v0.7.1

func GetAPIKey(c echo.Context) (string, error)

GetAPIKey retrieves the API key from the X-API-Key header on the request held by the echo context, see APIKey

func GetAuthzSubjectType

func GetAuthzSubjectType(ctx context.Context) string

GetAuthzSubjectType returns the subject type based on the authentication type

func GetBearerToken added in v0.9.0

func GetBearerToken(c echo.Context) (string, error)

GetBearerToken retrieves the bearer token from the authorization header or access token cookie on the request held by the echo context, see BearerToken

func GetBearerTokenFromWebsocketRequest added in v0.23.3

func GetBearerTokenFromWebsocketRequest(initPayload transport.InitPayload) (string, error)

GetBearerTokenFromWebsocketRequest retrieves the bearer token from the WebSocket init payload and parses it to return only the JWT access token component. If the token is not available, an error is returned.

func GetImpersonationToken added in v0.14.3

func GetImpersonationToken(c echo.Context) (string, error)

GetImpersonationToken retrieves the impersonation token from the authorization header on the request held by the echo context, see ImpersonationToken

func GetOrganizationContextHeader added in v0.15.1

func GetOrganizationContextHeader(c echo.Context) string

GetOrganizationContextHeader retrieves the org context header from the request held by the echo context, see OrganizationContextHeader

func GetOrganizationIDFromContext

func GetOrganizationIDFromContext(ctx context.Context) (string, error)

GetOrganizationIDFromContext returns the organization ID from context

func GetOrganizationIDsFromContext

func GetOrganizationIDsFromContext(ctx context.Context) ([]string, error)

GetOrganizationIDsFromContext returns the organization IDs from context

func GetRefreshToken

func GetRefreshToken(c echo.Context) (string, error)

GetRefreshToken retrieves the refresh token from the cookies on the request held by the echo context, see RefreshToken

func GetSubjectIDFromContext added in v0.9.0

func GetSubjectIDFromContext(ctx context.Context) (string, error)

GetSubjectIDFromContext returns the actor subject from the context In most cases this will be the user ID, but in the case of an API token it will be the token ID

func GetSubscriptionFromContext added in v0.3.2

func GetSubscriptionFromContext(ctx context.Context) bool

GetSubscriptionFromContext returns the active subscription from the context

func GetUserContextHeaders added in v0.14.3

func GetUserContextHeaders(c echo.Context) (userID, orgID string)

GetUserContextHeaders retrieves the user context headers from the request held by the echo context, see UserContextHeaders

func HasAnonymousTrustCenterCapability added in v0.40.0

func HasAnonymousTrustCenterCapability(ctx context.Context) bool

HasAnonymousTrustCenterCapability reports whether the caller in context has the CapTrustCenterAnonymous

func HasAnyInContextCaller added in v0.40.0

func HasAnyInContextCaller(ctx context.Context, caps Capability) bool

HasAnyInContextCaller reports whether the caller in context holds at least one of the specified capabilities

func HasCrossOrgCapabilities added in v0.40.0

func HasCrossOrgCapabilities(ctx context.Context) bool

HasCrossOrgCapabilities reports whether the caller in context has any capability that allows cross org queries

func HasFullOrgWriteAccessFromContext added in v0.23.6

func HasFullOrgWriteAccessFromContext(ctx context.Context) bool

HasFullOrgWriteAccessFromContext checks if the user has full write access to the organization This is true for owners and super admins; admins will have limited write access depending on the resource so authorization checks should be done at the resource level as needed

func HasFullSystemCapabilities added in v0.40.0

func HasFullSystemCapabilities(ctx context.Context) bool

HasFullSystemCapabilities reports whether the caller in context has all capabilities required for full system access

func HasInContextCaller added in v0.40.0

func HasInContextCaller(ctx context.Context, caps Capability) bool

HasInContextCaller reports whether the caller in context holds all of the specified capabilities

func HasInLineageContextCaller added in v0.40.0

func HasInLineageContextCaller(ctx context.Context, caps Capability) bool

HasInLineageContextCaller reports whether the caller in context or its original system-admin lineage holds all of the specified capabilities

func HasOrganizationContextHeader added in v0.15.1

func HasOrganizationContextHeader(c echo.Context) bool

HasOrganizationContextHeader checks if the required organization context header is present

func HasUserContextHeaders added in v0.14.3

func HasUserContextHeaders(c echo.Context) bool

HasUserContextHeaders checks if both required user context headers are present

func ImpersonationToken added in v0.37.0

func ImpersonationToken(r *http.Request) (string, error)

ImpersonationToken retrieves the impersonation token from the authorization header and parses it to return only the token component. If the header is missing or malformed, an error is returned.

func IsAPITokenAuthentication

func IsAPITokenAuthentication(ctx context.Context) bool

IsAPITokenAuthentication returns true if the authentication type is API token this is used to determine if the request is from a service account

func IsAnonymousFromContext added in v0.35.4

func IsAnonymousFromContext(ctx context.Context) bool

IsAnonymousFromContext reports whether ctx carries an anonymous-role caller

func IsImpersonatedCallerContext added in v0.40.0

func IsImpersonatedCallerContext(ctx context.Context) (string, bool)

IsImpersonatedCallerContext reports whether the caller in context is acting on behalf of another user and returns the user ID doing the impersonation

func IsInternalReadRequest added in v0.40.0

func IsInternalReadRequest(ctx context.Context) bool

IsInternalReadRequest checks if the context caller can bypass read authorization, via internal operation or internal read

func IsInternalRequest added in v0.40.0

func IsInternalRequest(ctx context.Context) bool

IsInternalRequest checks if the context caller has internal operation capability

func IsQuestionnaireFromContext added in v0.35.4

func IsQuestionnaireFromContext(ctx context.Context) bool

IsQuestionnaireFromContext reports whether ctx carries an anonymous questionnaire caller

func IsSystemAdminFromContext added in v0.14.1

func IsSystemAdminFromContext(ctx context.Context) bool

IsSystemAdminFromContext checks if the user is a system admin

func IsTrustCenterFromContext added in v0.35.4

func IsTrustCenterFromContext(ctx context.Context) bool

IsTrustCenterFromContext reports whether ctx carries an anonymous trust center caller

func IsUserlessContext added in v0.40.0

func IsUserlessContext(ctx context.Context) bool

IsUserlessContext returns true for any auth type that is not associated with a real user ID. this includes API tokens, support users via impersonation

func NewTestContextForSystemAdmin added in v0.14.1

func NewTestContextForSystemAdmin(sub, orgID string, opts ...CallerOption) context.Context

NewTestContextForSystemAdmin creates a context with system admin capabilities set for testing purposes only. Capabilities match CapabilitiesForSystemAdmin

func NewTestContextWithOrgID

func NewTestContextWithOrgID(sub, orgID string, opts ...CallerOption) context.Context

NewTestContextWithOrgID creates a context with the given subject and org ID for testing purposes only. Optional CallerOption values are applied after the base Caller is constructed, allowing callers to set OrganizationRole, Capabilities, ActiveSubscription, or any other Caller field.

func NewTestContextWithSubscription added in v0.3.2

func NewTestContextWithSubscription(subscription bool, opts ...CallerOption) context.Context

NewTestContextWithSubscription creates a context with random subject/org IDs and the given ActiveSubscription value for testing purposes only.

func NewTestContextWithValidUser

func NewTestContextWithValidUser(subject string, opts ...CallerOption) context.Context

NewTestContextWithValidUser creates a context with a fixed org placeholder for testing purposes only. It is equivalent to NewTestContextWithOrgID(subject, "ulid_id_of_org", opts...).

func OrganizationContextHeader added in v0.37.0

func OrganizationContextHeader(r *http.Request) string

OrganizationContextHeader retrieves the org context header to specify which organization context to operate under. This can be useful in scenarios when using a PAT that has access to multiple organizations and some preliminary check is needed for the operation. e.g checking if they have access to some modules.

If this is present, it will be the default OrganizationID when using a PAT

func RefreshToken added in v0.37.0

func RefreshToken(r *http.Request) (string, error)

RefreshToken retrieves the refresh token from the cookies in the request. If the cookie is not present or expired then an error is returned.

func RefreshTokenFromContext added in v0.9.0

func RefreshTokenFromContext(ctx context.Context) (string, bool)

RefreshTokenFromContext returns the request refresh token from ctx when present.

func RequestIDFromContext added in v0.4.2

func RequestIDFromContext(ctx context.Context) (string, bool)

RequestIDFromContext returns the request ID from ctx when present.

func ResolveOrganizationForContext added in v0.26.0

func ResolveOrganizationForContext(ctx context.Context, inputOrgID *string) (context.Context, error)

ResolveOrganizationForContext resolves and sets the active organization ID in the context. If inputOrgID is nil, it falls back to the single authorized org (e.g., for API tokens with one org). Returns ErrNoOrganizationID if no org can be resolved, or ErrUnauthorizedOrg if the provided org is not in the caller's authorized list.

func SetAuthCookies

func SetAuthCookies(w http.ResponseWriter, accessToken, refreshToken string, c sessions.CookieConfig)

SetAuthCookies is a helper function to set authentication cookies on a echo request. The access token cookie (access_token) is an http only cookie that expires when the access token expires. The refresh token cookie is not an http only cookie (it can be accessed by client-side scripts) and it expires when the refresh token expires. Both cookies require https and will not be set (silently) over http connections.

func SetOrganizationIDInAuthContext added in v0.1.4

func SetOrganizationIDInAuthContext(ctx context.Context, orgID string) (context.Context, error)

SetOrganizationIDInAuthContext sets the organization ID in the auth context this should only be used when creating a new organization and subsequent updates need to happen in the context of the new organization

func TrustCenterScopeFromContext added in v0.35.4

func TrustCenterScopeFromContext(ctx context.Context) (tcID, orgID string, ok bool)

TrustCenterScopeFromContext reports the trust center and org for an anonymous trust center caller

func UserContextHeaders added in v0.37.0

func UserContextHeaders(r *http.Request) (userID, orgID string)

UserContextHeaders retrieves the user context headers used by system admins to specify which user context to operate under. Returns the user ID and organization ID from the X-User-ID and X-Organization-ID headers respectively.

func WithAccessToken added in v0.4.2

func WithAccessToken(ctx context.Context, token string) context.Context

WithAccessToken stores the request access token in ctx.

func WithCaller added in v0.24.2

func WithCaller(ctx context.Context, c *Caller) context.Context

WithCaller stores c in ctx and returns the updated context it replaces any existing caller, including its capabilities, so apply capability helpers after calling it

func WithCallerCapabilities added in v0.40.0

func WithCallerCapabilities(ctx context.Context, caps Capability) context.Context

WithCallerCapabilities adds the capabilities to a copy of the caller in context, creating an empty caller when none is set the created caller means later "no caller" checks no longer see an empty context, so only use it where a caller is expected

func WithCallerScopedToOrg added in v0.40.0

func WithCallerScopedToOrg(ctx context.Context, orgID string) context.Context

WithCallerScopedToOrg returns ctx with a copy of the caller scoped to orgID as its only organization it does not verify membership, callers must check the subject belongs to orgID first

func WithCrossOrgContext added in v0.40.0

func WithCrossOrgContext(ctx context.Context) context.Context

WithCrossOrgContext adds the org filter bypass to the current caller which allows for cross-org queries

func WithInternalCrossOrgContext added in v0.40.0

func WithInternalCrossOrgContext(ctx context.Context) context.Context

WithInternalCrossOrgContext adds internal operation and the org filter bypass to the current caller: skips privacy, FGA, module, and edge checks and reads every org's rows; only for lookups before the org is known

func WithInternalOperationContext added in v0.40.0

func WithInternalOperationContext(ctx context.Context) context.Context

WithInternalOperationContext adds internal operation to the current caller, keeping its user and orgs: skips privacy, FGA, module, and edge checks but reads stay limited to the caller's orgs

func WithInternalReadContext added in v0.40.0

func WithInternalReadContext(ctx context.Context) context.Context

WithInternalReadContext adds internal read to the current caller, keeping its user and orgs: skips FGA and query privacy checks on reads only, reads stay limited to the caller's orgs

func WithInternalReadCrossOrgContext added in v0.40.0

func WithInternalReadCrossOrgContext(ctx context.Context) context.Context

WithInternalReadCrossOrgContext adds internal read and the org filter bypass to the current caller: skips FGA and query privacy checks on reads across every org's rows; only for lookups before the org is known

func WithOrgInternalCaller added in v0.40.0

func WithOrgInternalCaller(ctx context.Context, orgID string) context.Context

WithOrgInternalCaller replaces the current caller with OrgInternalCaller, dropping its user and any other capabilities

func WithOrganizationBootstrapCapabilities added in v0.40.0

func WithOrganizationBootstrapCapabilities(ctx context.Context) context.Context

WithOrganizationBootstrapCapabilities adds the organization bootstrap capabilities to the caller in context

func WithOriginalSystemAdminCaller added in v0.26.0

func WithOriginalSystemAdminCaller(ctx context.Context, c *Caller) context.Context

WithOriginalSystemAdminCaller stores the original admin caller in ctx.

func WithRefreshToken added in v0.9.0

func WithRefreshToken(ctx context.Context, token string) context.Context

WithRefreshToken stores the request refresh token in ctx.

func WithRequestID added in v0.4.2

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID stores the request ID in ctx.

func WithSystemSweepContext added in v0.40.0

func WithSystemSweepContext(ctx context.Context) context.Context

WithSystemSweepContext builds a cross-organization system caller context bypassing org filtering and FGA

Types

type AuthenticationType

type AuthenticationType string

AuthenticationType represents the type of authentication used It can be JWT, PAT (Personal Access Token), or API Token

const (
	// JWTAuthentication is the authentication type for JWT tokens
	JWTAuthentication AuthenticationType = "jwt"
	// PATAuthentication is the authentication type for personal access tokens
	PATAuthentication AuthenticationType = "pat"
	// APITokenAuthentication is the authentication type for API tokens, commonly used for service authentication for machine-to-machine communication
	APITokenAuthentication AuthenticationType = "api_token"
)

func GetAuthTypeFromContext

func GetAuthTypeFromContext(ctx context.Context) AuthenticationType

GetAuthTypeFromContext retrieves the authentication type from the context if it was set

func GetAuthTypeFromEchoContext

func GetAuthTypeFromEchoContext(ctx echo.Context) AuthenticationType

GetAuthTypeFromEchoContext retrieves the authentication type from the echo context

func (AuthenticationType) String added in v0.40.0

func (a AuthenticationType) String() string

type Caller added in v0.24.2

type Caller struct {
	// SubjectID is the unique identifier for this actor
	SubjectID string `json:"subject_id,omitempty"`
	// SubjectName is the display name of the actor
	SubjectName string `json:"subject_name,omitempty"`
	// SubjectEmail is the email address of the actor
	SubjectEmail string `json:"subject_email,omitempty"`
	// OrganizationID is the active org for this request; set for JWT callers
	OrganizationID string `json:"organization_id,omitempty"`
	// OrganizationName is the display name of the active org
	OrganizationName string `json:"organization_name,omitempty"`
	// OrganizationIDs is the set of orgs this actor is authorized to access; set for token callers
	OrganizationIDs []string `json:"organization_ids,omitempty"`
	// AuthenticationType describes how this actor was authenticated
	AuthenticationType AuthenticationType `json:"authentication_type,omitempty"`
	// OrganizationRole is the actor's role within the active org
	OrganizationRole OrganizationRoleType `json:"organization_role,omitempty"`
	// ActiveSubscription reports whether the active org has a current subscription
	ActiveSubscription bool `json:"active_subscription,omitempty"`
	// Capabilities is the set of bypass flags granted to this caller
	Capabilities Capability `json:"capabilities,omitempty"`
	// Impersonation is set when this Caller is acting on behalf of another user
	Impersonation *ImpersonationContext `json:"impersonation,omitempty"`
	// OriginalSystemAdmin is set when a system admin is executing as another caller.
	// This keeps caller lineage in one root identity tree instead of a parallel context key.
	OriginalSystemAdmin *Caller `json:"original_system_admin,omitempty"`
}

Caller holds the identity and capabilities for any request actor — authenticated users, anonymous visitors, internal service calls, etc.

func CallerFromContext added in v0.24.2

func CallerFromContext(ctx context.Context) (*Caller, bool)

CallerFromContext returns the Caller stored in ctx and true, or nil and false if not set

func GetTrustCenterUserCaller added in v0.40.0

func GetTrustCenterUserCaller(ctx context.Context) (*Caller, string, bool)

GetTrustCenterUserCaller verifies that the caller context is for an anonymous trust center user containing a subject email. It returns the caller or nil if its not valid, the authorized trust center ID, along with a boolean check

func GetVerifiedTrustCenterUserCaller added in v0.40.0

func GetVerifiedTrustCenterUserCaller(ctx context.Context, providedTrustCenterID string) (*Caller, bool)

GetVerifiedTrustCenterUserCaller verifies that the caller context is for an anonymous trust center user containing a subject email and matches the trust center id being targeted It returns the verified caller or nil if its not valid, along with a boolean check

func MustCallerFromContext added in v0.24.2

func MustCallerFromContext(ctx context.Context) *Caller

MustCallerFromContext returns the Caller stored in ctx, panicking if not set

func NewAcmeSolverCaller deprecated added in v0.24.2

func NewAcmeSolverCaller(orgID string) *Caller

NewAcmeSolverCaller returns a Caller for an ACME challenge solver request. Bypasses org-filter and FGA checks but not feature-flag enforcement.

Deprecated: will be removed in a future PR

func NewAnonBootstrapCallerOrgBypass added in v0.40.0

func NewAnonBootstrapCallerOrgBypass() *Caller

NewAnonBootstrapCallerOrgBypass returns an anon caller with org bypass and subscription bypass that can be used for anon callers before authorization to issue the JWT

func NewIntegrationCaller added in v0.35.4

func NewIntegrationCaller(orgID string) *Caller

NewIntegrationCaller returns a Caller for the virtual integration user

func NewKeystoreCaller deprecated added in v0.24.2

func NewKeystoreCaller() *Caller

NewKeystoreCaller returns a Caller for keystore operations. Bypasses org-filter, FGA, and feature-flag checks.

Deprecated: will be removed in a future PR

func NewOrgInternalCaller added in v0.40.0

func NewOrgInternalCaller(orgID string) *Caller

NewOrgInternalCaller returns a new caller with no user, one org, and internal operation: skips privacy, FGA, module, and edge checks, reads only that org's rows, and new rows are owned by that org

func NewOrgSupportCaller added in v0.34.1

func NewOrgSupportCaller(orgID, subjectID, subjectName, subjectEmail string) *Caller

NewOrgSupportCaller returns a Caller for an org-scoped support session within orgID. Keeps the org filter and owner assignment; bypasses feature-flag and subscription checks.

func NewQuestionnaireCaller added in v0.24.2

func NewQuestionnaireCaller(orgID, subjectID, subjectName, subjectEmail string) *Caller

NewQuestionnaireCaller returns a Caller for an anonymous questionnaire respondent. Bypasses subscription checks.

func NewSystemAdminCaller added in v0.24.2

func NewSystemAdminCaller(subjectID, subjectName, subjectEmail string) *Caller

NewSystemAdminCaller returns a Caller for a system administrator. Capabilities match CapabilitiesForSystemAdmin

func NewTrustCenterBootstrapCaller added in v0.24.2

func NewTrustCenterBootstrapCaller(orgID string) *Caller

NewTrustCenterBootstrapCaller returns a Caller for trust center initialization before a subject identity is known. Bypasses subscription checks.

func NewTrustCenterCaller added in v0.24.2

func NewTrustCenterCaller(orgID, subjectID, subjectName, subjectEmail string) *Caller

NewTrustCenterCaller returns a Caller for an anonymous trust center viewer with a resolved identity. Bypasses subscription checks.

func NewWebhookCaller deprecated added in v0.24.2

func NewWebhookCaller(orgID string) *Caller

NewWebhookCaller returns a Caller for an inbound webhook delivery. Bypasses org-filter and FGA checks.

Deprecated: will be removed in a future PR

func OriginalSystemAdminCallerFromContext added in v0.26.0

func OriginalSystemAdminCallerFromContext(ctx context.Context) (*Caller, bool)

OriginalSystemAdminCallerFromContext returns the original admin caller from ctx when present.

func (*Caller) ActiveOrg added in v0.24.2

func (c *Caller) ActiveOrg() (string, bool)

ActiveOrg returns OrganizationID if set, or the single entry in OrganizationIDs if exactly one is present. Returns ("", false) otherwise.

func (*Caller) CanAccessOrg added in v0.24.2

func (c *Caller) CanAccessOrg(orgID string) bool

CanAccessOrg reports whether the caller is authorized to access orgID

func (*Caller) Has added in v0.24.2

func (c *Caller) Has(caps Capability) bool

Has reports whether the Caller holds all of the specified capabilities

func (*Caller) HasAny added in v0.40.0

func (c *Caller) HasAny(caps Capability) bool

HasAny reports whether the Caller holds at least one of the specified capabilities

func (*Caller) HasInLineage added in v0.26.0

func (c *Caller) HasInLineage(caps Capability) bool

HasInLineage reports whether the Caller or its original system-admin lineage holds all of the specified capabilities

func (*Caller) IsAnonymous added in v0.26.0

func (c *Caller) IsAnonymous() bool

IsAnonymous reports whether this Caller is an anonymous user (trust center visitor, questionnaire respondent, etc.) with no standard authentication type

func (*Caller) IsImpersonated added in v0.24.2

func (c *Caller) IsImpersonated() bool

IsImpersonated reports whether this Caller is acting on behalf of another user

func (*Caller) IsQuestionnaire added in v0.35.4

func (c *Caller) IsQuestionnaire() bool

IsQuestionnaire reports whether this Caller is an anonymous questionnaire respondent

func (*Caller) IsTrustCenter added in v0.35.4

func (c *Caller) IsTrustCenter() bool

IsTrustCenter reports whether this Caller is an anonymous trust center visitor

func (*Caller) OrgIDs added in v0.24.2

func (c *Caller) OrgIDs() []string

OrgIDs returns the org IDs this caller is authorized to access

func (*Caller) SubjectType added in v0.26.0

func (c *Caller) SubjectType() string

SubjectType returns the FGA subject type for this caller based on the authentication type. Returns UserSubjectType for JWT/PAT callers and ServiceSubjectType for API token callers.

func (*Caller) WithCapabilities added in v0.24.2

func (c *Caller) WithCapabilities(caps Capability) *Caller

WithCapabilities returns a copy of the Caller with the given capabilities added

func (*Caller) WithoutCapabilities added in v0.24.2

func (c *Caller) WithoutCapabilities(caps Capability) *Caller

WithoutCapabilities returns a copy of the Caller with the given capabilities removed

type CallerOption added in v0.26.0

type CallerOption func(*Caller)

CallerOption configures a Caller built for use in test contexts.

func WithActiveSubscription added in v0.26.0

func WithActiveSubscription(active bool) CallerOption

WithActiveSubscription sets the ActiveSubscription flag on the test Caller.

func WithCapabilities added in v0.26.0

func WithCapabilities(caps Capability) CallerOption

WithCapabilities adds the given capabilities to the test Caller.

func WithOrganizationRole added in v0.26.0

func WithOrganizationRole(role OrganizationRoleType) CallerOption

WithOrganizationRole sets the OrganizationRole on the test Caller.

type Capability added in v0.24.2

type Capability uint64

Capability is a set of flags describing what a Caller is allowed to bypass. Values are explicit powers of two so they remain stable if constants are reordered, which matters when Caller is serialized by gala.

const (
	// CapBypassOrgFilter skips org-scoped interceptor filtering
	// This capability should only be used when a cross-org query is required to retrieve data
	// which is rarely ever required, and if required, usually only for an initial query
	// Examples would include: during organization creation, anonymous calls for initial lookup, and cross
	// organization async jobs
	// includes bypass on: org_mixin, subprocessors, trust center filters
	CapBypassOrgFilter Capability = 1 << 0
	// CapBypassFeatureCheck skips feature-flag checks
	// This capability is used to skip module checks, it is not needed when
	// the caller has InternalOperation as well; system admins get it from CapabilitiesForSystemAdmin
	CapBypassFeatureCheck Capability = 1 << 1
	// CapInternalRead marks the caller as a trusted internal read
	// Used to skip FGA filtering and query privacy checks on reads; mutations still require CapInternalOperation
	CapInternalRead Capability = 1 << 2
	// CapBypassManagedGroup bypasses managed-group mutation guards
	// used to allow updates to managed groups, which are only allowed
	// for internal requests and not all users
	CapBypassManagedGroup Capability = 1 << 3
	// CapBypassAuditLog suppresses audit log emission, skips writes to history tables, commonly used by integrations with heavy churn of data
	CapBypassAuditLog Capability = 1 << 4
	// CapInternalOperation marks the caller as a trusted internal service operation
	// This is the most common capability use to bypass certain restrictions
	CapInternalOperation Capability = 1 << 5
	// CapSystemAdmin is set by the auth middleware for callers holding the FGA system_admin relation
	// and grants platform-wide administrator access across all organizations
	CapSystemAdmin Capability = 1 << 7
	// CapTrustCenterAnonymous gives select bypass to checks
	// used for anonymous trust center visitors scoped to a single trust center
	CapTrustCenterAnonymous Capability = 1 << 8
	// CapQuestionnaireAnonymous gives select bypass to checks
	CapQuestionnaireAnonymous Capability = 1 << 9
	// CapOrgSupport grants org-scoped support access without bypassing the org filter or owner assignment
	CapOrgSupport Capability = 1 << 10
	// CapIntegrationActor is used to identify an integration installation virtual user/actor
	CapIntegrationActor Capability = 1 << 11
	// CapSystemSweep marks a full system job that skips org owner handling, e.g. backfills, org bootstrap and scheduled sweeps
	CapSystemSweep Capability = 1 << 12
)

func CapabilitiesForOrgBootstrap added in v0.40.0

func CapabilitiesForOrgBootstrap() Capability

CapabilitiesForOrgBootstrap are the capabilities required to bootstrap an organization

func CapabilitiesForSupportCaller added in v0.40.0

func CapabilitiesForSupportCaller() Capability

CapabilitiesForSupportCaller returns capability flags for support callers

func CapabilitiesForSystemAdmin added in v0.40.0

func CapabilitiesForSystemAdmin(isSystemAdmin bool) Capability

CapabilitiesForSystemAdmin returns capability flags for System Admins

type ImpersonationAuditLog added in v0.14.3

type ImpersonationAuditLog struct {
	SessionID         string            `json:"session_id"`
	Type              ImpersonationType `json:"type"`
	ImpersonatorID    string            `json:"impersonator_id"`
	ImpersonatorEmail string            `json:"impersonator_email"`
	TargetUserID      string            `json:"target_user_id"`
	TargetUserEmail   string            `json:"target_user_email"`
	Action            string            `json:"action"` // "start", "end", "action_performed"
	Reason            string            `json:"reason"`
	Timestamp         time.Time         `json:"timestamp"`
	IPAddress         string            `json:"ip_address,omitempty"`
	UserAgent         string            `json:"user_agent,omitempty"`
	OrganizationID    string            `json:"organization_id"`
	AdditionalData    map[string]any    `json:"additional_data,omitempty"`
}

ImpersonationAuditLog represents an audit log entry for impersonation events

type ImpersonationContext added in v0.14.3

type ImpersonationContext struct {
	// Type indicates what kind of impersonation this is
	Type ImpersonationType
	// ImpersonatorID is the user ID of the person doing the impersonation
	ImpersonatorID string
	// ImpersonatorEmail is the email of the person doing the impersonation
	ImpersonatorEmail string
	// TargetUserID is the user being impersonated
	TargetUserID string
	// TargetUserEmail is the email of the user being impersonated
	TargetUserEmail string
	// Reason is the justification for the impersonation
	Reason string
	// StartedAt is when the impersonation session began
	StartedAt time.Time
	// ExpiresAt is when the impersonation session expires
	ExpiresAt time.Time
	// SessionID is a unique identifier for this impersonation session
	SessionID string
}

ImpersonationContext contains information about an active impersonation session

func (*ImpersonationContext) IsExpired added in v0.14.3

func (i *ImpersonationContext) IsExpired() bool

IsExpired checks if the impersonation session has expired

type ImpersonationType added in v0.14.3

type ImpersonationType string

ImpersonationType represents the type of impersonation being performed

const (
	// SupportImpersonation is for support staff helping users debug issues
	SupportImpersonation ImpersonationType = "support"
	// JobImpersonation is for async jobs running with user context
	JobImpersonation ImpersonationType = "job"
	// AdminImpersonation is for admin operations that need to act as a user
	AdminImpersonation ImpersonationType = "admin"
)

type OrganizationRoleType added in v0.23.6

type OrganizationRoleType string

OrganizationRoleType represents the role of the user in the organization

const (
	// AdminRole is the admin role in the organization - with general read and creation access, this does not guarantee write access to all resources
	AdminRole OrganizationRoleType = "admin"
	// SuperAdminRole is the super admin role in the organization - with full access to all resources, similar to owner but without ownership transfer capabilities
	SuperAdminRole OrganizationRoleType = "super_admin"
	// OwnerRole is the owner role in the organization - with full access to all resources including ownership transfer capabilities
	OwnerRole OrganizationRoleType = "owner"
	// MemberRole is the member role in the organization - with limited read access and no creation or write access by default
	MemberRole OrganizationRoleType = "member"
	// AuditorRole is the auditor role in the organization - with read-only access to resources for auditing purposes and limited write access for commenting, notes, etc.
	AuditorRole OrganizationRoleType = "auditor"
	// AnonymousRole is used for anonymous users with minimal access for public resources such as trust center and questionnaires
	AnonymousRole OrganizationRoleType = "anonymous"
)

func ToOrganizationRoleType added in v0.23.6

func ToOrganizationRoleType(role string) (OrganizationRoleType, bool)

ToOrganizationRoleType converts a string to an OrganizationRoleType

func (OrganizationRoleType) HasFullWriteAccess added in v0.26.0

func (ort OrganizationRoleType) HasFullWriteAccess() bool

HasFullWriteAccess reports whether this role grants full organization write access, which is true for owners and super admins

func (OrganizationRoleType) HasOrgAdminAccess added in v0.40.0

func (ort OrganizationRoleType) HasOrgAdminAccess() bool

HasOrgAdminAccess returns true if the user role is admin, super admin or owner

func (OrganizationRoleType) IsValid added in v0.23.6

func (ort OrganizationRoleType) IsValid() bool

IsValid checks if the OrganizationRoleType is valid

func (OrganizationRoleType) String added in v0.23.6

func (ort OrganizationRoleType) String() string

String returns the string representation of the OrganizationRoleType

Jump to

Keyboard shortcuts

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