Documentation
¶
Index ¶
- Constants
- Variables
- func GetApiUrlFromPAT(pat string) (string, error)
- func GetAudienceClaimFromOauthToken(oauthTokenString string) ([]string, error)
- func GetAuthHeader(config configuration.Configuration) string
- func GetOAuthToken(config configuration.Configuration) (*oauth2.Token, error)
- func IsAuthTypePAT(token string) bool
- func IsAuthTypeToken(token string) bool
- func IsKnownOAuthEndpoint(endpoint string) bool
- func IsValidAuthHost(instance string, redirectAuthHostRE string) (bool, error)deprecated
- func IsValidSnykHost(conf configuration.Configuration, input string) (bool, error)
- func OpenBrowser(authUrl string)
- func RefreshToken(ctx context.Context, oauthConfig *oauth2.Config, token *oauth2.Token) (*oauth2.Token, error)
- func ShutdownServer(server *http.Server)
- func StoredClientCredential(config configuration.Configuration) (clientID, privateKeyPEM string, err error)
- type Authenticator
- type BearerTokenScoper
- type CancelableAuthenticator
- type Claims
- type ClientAssertionProvider
- type GrantType
- type OAuth2AuthenticatorOption
- func WithClientAssertionProvider(clientID string, p ClientAssertionProvider) OAuth2AuthenticatorOption
- func WithHttpClient(httpClient *http.Client) OAuth2AuthenticatorOption
- func WithLogger(logger *zerolog.Logger) OAuth2AuthenticatorOption
- func WithOpenBrowserFunc(openBrowserFunc func(string)) OAuth2AuthenticatorOption
- func WithShutdownServerFunc(shutdownServerFunc func(server *http.Server)) OAuth2AuthenticatorOption
- func WithTokenRefresherFunc(...) OAuth2AuthenticatorOption
Constants ¶
const ( // CONFIG_KEY_ALLOWED_HOST_REGEXP — no code within this module reads it // anymore, so setting this env var no longer has any effect here. It's // exported public API, though, so other repos may still reference it // directly; it's kept for now so any such references keep compiling // while we confirm they've migrated off it, and will be removed in a // follow-up once that's verified. // // Deprecated: use CONFIG_KEY_ALLOWED_HOSTS with IsValidSnykHost instead. //nolint:gosec // not a token value, but a configuration key CONFIG_KEY_ALLOWED_HOST_REGEXP = "INTERNAL_OAUTH_ALLOWED_HOSTS" // CONFIG_KEY_ALLOWED_HOSTS holds the allowlist of registrable domains // consulted by IsValidSnykHost. When set programmatically (e.g. via // Configuration.Set) it accepts a []string of multiple domains. When set // via the environment variable below, it supports a single domain only: // this key has no comma-splitting DefaultValueFunction, so GetStringSlice // returns the raw env var value as a one-element slice. For multiple // allowed domains, configure this key programmatically as a []string // rather than via the environment variable. //nolint:gosec // not a token value, but a configuration key CONFIG_KEY_ALLOWED_HOSTS = "INTERNAL_OAUTH_ALLOWED_HOST_DOMAINS" CONFIG_KEY_OAUTH_TOKEN string = "INTERNAL_OAUTH_TOKEN_STORAGE" OAUTH_CLIENT_ID string = "b56d4c2e-b9e1-4d27-8773-ad47eafb0956" CALLBACK_HOSTNAME string = "127.0.0.1" CALLBACK_PATH string = "/authorization-code/callback" TIMEOUT_SECONDS = 120 * time.Second AUTHENTICATED_MESSAGE = "Your account has been authenticated." PARAMETER_CLIENT_ID string = "client-id" PARAMETER_CLIENT_SECRET string = "client-secret" AUTH_TYPE_OAUTH = "oauth" )
const ( AUTH_TYPE_TOKEN = "token" AUTH_TYPE_PAT = "pat" CACHED_PAT_KEY_PREFIX = "cached_pat" CACHED_PAT_IS_VALID_KEY_PREFIX = "cached_pat_is_valid" CONFIG_KEY_TOKEN = "api" // the snyk config key for api token CONFIG_KEY_ENDPOINT = "endpoint" // the snyk config key for api endpoint PAT_REGEX = `(snyk_(?:uat|sat))\.([a-z0-9]{8}\.[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+)` )
Variables ¶
var ( // ErrAuthCanceled is returned when an auth request is canceled by the calling context. ErrAuthCanceled = errors.New("authentication failed (canceled)") // ErrAuthTimedOut is returned when an auth request times out. ErrAuthTimedOut = errors.New("authentication failed (timeout)") // ErrNoStoredClientCredential is returned by StoredClientCredential when no client credential is stored. ErrNoStoredClientCredential = machinecredential.ErrNotEnrolled )
Functions ¶
func GetApiUrlFromPAT ¶
func GetAudienceClaimFromOauthToken ¶
GetAudienceClaimFromOauthToken returns the API URL specified by the audience claim in a JWT token established by a prior OAuth authentication flow.
Returns an empty string if an OAuth token is not available, cannot be parsed, or lacks such an audience claim, along with an error that may have occurred in the attempt to parse it.
func GetAuthHeader ¶
func GetAuthHeader(config configuration.Configuration) string
GetAuthHeader returns the authentication header value based on the configuration.
func GetOAuthToken ¶
func GetOAuthToken(config configuration.Configuration) (*oauth2.Token, error)
GetOAuthToken extracts an oauth2.Token from the given configuration instance if available
func IsAuthTypePAT ¶
func IsAuthTypeToken ¶
func IsKnownOAuthEndpoint ¶
func IsValidAuthHost
deprecated
IsValidAuthHost — no code within this module calls it anymore; OAuth callback host validation goes exclusively through IsValidSnykHost. It's exported public API, though, so other repos may still call it directly; it's kept for now so any such callers keep compiling while we confirm they've migrated off it, and will be removed in a follow-up once that's verified.
Deprecated: use IsValidSnykHost instead.
func IsValidSnykHost ¶ added in v0.11.0
func IsValidSnykHost(conf configuration.Configuration, input string) (bool, error)
IsValidSnykHost reports whether input resolves to an "api." subdomain of one of the domains configured under CONFIG_KEY_ALLOWED_HOSTS. It fails closed: if no allowlist is configured, nothing is considered valid.
Validation runs as small, single-purpose steps: parse the input as a URL, confirm it carries nothing but a host, confirm the host's leading DNS label is "api", and confirm an allowlisted domain matches on DNS-label boundaries.
Each step is checked twice with two independent techniques — a url* helper that inspects the parsed *url.URL, and a string* helper that inspects the raw normalized string — and both must agree; this is intentional parser-differential defense, so a discrepancy between the two interpretations (e.g. a parser quirk that hides a smuggled component) fails closed rather than trusting either one alone.
func OpenBrowser ¶
func OpenBrowser(authUrl string)
func RefreshToken ¶
func ShutdownServer ¶
func StoredClientCredential ¶ added in v0.38.0
func StoredClientCredential(config configuration.Configuration) (clientID, privateKeyPEM string, err error)
StoredClientCredential returns the stored client credential: its client id and its private key as PKCS#8 PEM. The key is long-lived, so keep it off command lines, which other local users can read.
Types ¶
type Authenticator ¶
type Authenticator interface {
// Authenticate authenticates the user and returns an error if the authentication failed.
// Returns ErrAuthTimedOut if the underlying request times out.
Authenticate() error
// AddAuthenticationHeader adds the authentication header to the request.
AddAuthenticationHeader(request *http.Request) error
// IsSupported returns true if the authenticator is ready for use.
// If false is returned, it is not possible to add authentication headers/env vars.
IsSupported() bool
}
func CreateAuthenticator ¶
func CreateAuthenticator(config configuration.Configuration, httpClient *http.Client) Authenticator
func NewOAuth2AuthenticatorWithCustomFuncs
deprecated
func NewOAuth2AuthenticatorWithCustomFuncs( config configuration.Configuration, httpClient *http.Client, openBrowserFunc func(url string), shutdownServerFunc func(server *http.Server), ) Authenticator
Deprecated: use NewOAuth2AuthenticatorWithOpts instead
func NewTokenAuthenticator ¶
func NewTokenAuthenticator(tokenFunc func() string) Authenticator
type BearerTokenScoper ¶ added in v0.32.0
type BearerTokenScoper interface {
// GetToken returns a bearer token, without any prefix, that is restricted to the given scopes.
// A positive ttl requests a token lifetime; zero leaves the lifetime to the server's default.
// An error is returned if no authentication is available or the server rejects the request.
GetToken(ctx context.Context, scopes []string, ttl time.Duration) (string, error)
// RevokeToken revokes the given token.
RevokeToken(ctx context.Context, token string) error
}
BearerTokenScoper derives bearer tokens that are restricted to a subset of scopes from the current authentication, so that a caller can hand out a token with least privilege.
func NewBearerTokenScoper ¶ added in v0.32.0
func NewBearerTokenScoper(config configuration.Configuration, clients networktypes.NetworkClients) BearerTokenScoper
NewBearerTokenScoper creates a scoper that can down-scope the authentication token.
type CancelableAuthenticator ¶
type CancelableAuthenticator interface {
Authenticator
// CancelableAuthenticate authenticates the user and returns an error if the authentication failed.
// Takes a context that can be used to interrupt the authentication.
// Returns ErrAuthCanceled when interrupted due to a context cancellation.
// Returns ErrAuthTimedOut if the underlying request times out.
CancelableAuthenticate(ctx context.Context) error
}
func NewOAuth2Authenticator ¶
func NewOAuth2Authenticator(config configuration.Configuration, httpClient *http.Client) CancelableAuthenticator
func NewOAuth2AuthenticatorWithOpts ¶
func NewOAuth2AuthenticatorWithOpts(config configuration.Configuration, opts ...OAuth2AuthenticatorOption) CancelableAuthenticator
type Claims ¶
type Claims struct {
// Hostname PAT is valid for
Hostname string `json:"h"`
}
Claims represents the structure of the PATs claims, it does not represent all the claims; only the ones we need
type ClientAssertionProvider ¶ added in v0.35.0
type ClientAssertionProvider interface {
// ClientAssertion returns the client_assertion_type and a freshly signed client_assertion for a
// token request to tokenURL, authenticating as clientID. Implementations should mint a new
// assertion on every call; authorization servers are expected to accept each one only once.
ClientAssertion(ctx context.Context, clientID, tokenURL string) (assertionType, assertion string, err error)
}
ClientAssertionProvider supplies a private_key_jwt-style client assertion (RFC 7523) for the OAuth2 client_credentials grant, decoupling the authenticator from any specific key-management or enrollment scheme.
type OAuth2AuthenticatorOption ¶
type OAuth2AuthenticatorOption func(authenticator *oAuth2Authenticator)
func WithClientAssertionProvider ¶ added in v0.35.0
func WithClientAssertionProvider(clientID string, p ClientAssertionProvider) OAuth2AuthenticatorOption
WithClientAssertionProvider configures the authenticator to use the client_credentials grant with a client assertion minted by p, authenticating as clientID, instead of a static client secret.
func WithHttpClient ¶
func WithHttpClient(httpClient *http.Client) OAuth2AuthenticatorOption
func WithLogger ¶
func WithLogger(logger *zerolog.Logger) OAuth2AuthenticatorOption
func WithOpenBrowserFunc ¶
func WithOpenBrowserFunc(openBrowserFunc func(string)) OAuth2AuthenticatorOption
func WithShutdownServerFunc ¶
func WithShutdownServerFunc(shutdownServerFunc func(server *http.Server)) OAuth2AuthenticatorOption
WithShutdownServerFunc sets the function that is called on server shutdown. shutdownServerFunc must be/call a function which is race condition safe with server.Server if it is called first and will result in server.Server exiting immediately when called.