Documentation
¶
Index ¶
- Constants
- Variables
- func AccessTokenExpiresAt(tokenSet *TokenSet) (time.Time, error)
- func CompleteLoginWithCode(authProvider *AuthProviderConfig, pasted string) error
- func DeleteSessionState(authProvider *AuthProviderConfig) error
- func ExplainUserInfoError(err error, authProvider *AuthProviderConfig, userType UserType) error
- func LoginWithBrowser(ctx context.Context, authProvider *AuthProviderConfig, interactive bool) error
- func LoginWithoutBrowser(authProvider *AuthProviderConfig, codeInput io.Reader) error
- func MachineLogin(authProvider *AuthProviderConfig, clientID, clientSecret string) error
- func RevokeAndDeleteSession(authProvider *AuthProviderConfig) error
- func RevokeRefreshToken(authProvider *AuthProviderConfig, refreshToken string)
- func SaveSessionState(authProvider *AuthProviderConfig, userType UserType, tokenSet *TokenSet) error
- type AuthProviderConfig
- type PersistedConfig
- type PersistedPendingLogin
- type PersistedSessionState
- type SessionState
- type TokenSet
- type UserInfoError
- type UserInfoResponse
- type UserType
Constants ¶
const AuthProviderFileEnvVar = "METAPLAYCLI_AUTH_PROVIDER_FILE"
AuthProviderFileEnvVar names a YAML file with an AuthProviderConfig to use in place of Metaplay Auth. Internal dev tool for targeting a non-managed platform, see DEVELOPMENT.md.
Variables ¶
var ErrKeyNotFound = errors.New("encryption key not found in keyring")
ErrKeyNotFound is returned when the encryption key is not found in the keyring.
var ErrSessionProviderMismatch = errors.New("session belongs to a different auth provider")
ErrSessionProviderMismatch reports a stored session whose tokens were minted by a different auth provider than the one now asking for it. Callers that only want the session gone (logout) can recognise it and clear the session locally.
Functions ¶
func AccessTokenExpiresAt ¶
AccessTokenExpiresAt returns when the access token of the tokenSet expires.
func CompleteLoginWithCode ¶
func CompleteLoginWithCode(authProvider *AuthProviderConfig, pasted string) error
CompleteLoginWithCode finishes a login started by LoginWithoutBrowser, with the code the sign-in page showed.
func DeleteSessionState ¶
func DeleteSessionState(authProvider *AuthProviderConfig) error
DeleteSessionState removes the current session state (i.e., signs out the user).
func ExplainUserInfoError ¶
func ExplainUserInfoError(err error, authProvider *AuthProviderConfig, userType UserType) error
ExplainUserInfoError converts a FetchUserInfo failure into a CLI error. When the server refused the user, the error leads with the server's own message, which says why (an unknown identity, an email that is not allowed, or one already taken by another account). userType picks how to sign in again.
func LoginWithBrowser ¶
func LoginWithBrowser(ctx context.Context, authProvider *AuthProviderConfig, interactive bool) error
LoginWithBrowser signs in a human user with a browser on this machine, which returns the authorization code to a loopback port. interactive says whether someone is at a terminal to open the URL by hand should the browser not open.
func LoginWithoutBrowser ¶
func LoginWithoutBrowser(authProvider *AuthProviderConfig, codeInput io.Reader) error
LoginWithoutBrowser signs in a human user whose browser cannot reach the CLI's loopback callback: over SSH, in a container, or with an agent running the CLI. The authorization request returns to the provider's NoBrowserRedirectURI, a page that shows a code for the user to paste back.
The login is saved as pending before anything is printed, so it can be finished by CompleteLoginWithCode in a later invocation. When codeInput is given, the code is also read from it and the login finished here; when it is nil, the CLI prints how to finish and returns.
func MachineLogin ¶
func MachineLogin(authProvider *AuthProviderConfig, clientID, clientSecret string) error
func RevokeAndDeleteSession ¶
func RevokeAndDeleteSession(authProvider *AuthProviderConfig) error
RevokeAndDeleteSession revokes tokens server-side and removes local session state. Server-side revocation is best-effort; local deletion always proceeds.
func RevokeRefreshToken ¶
func RevokeRefreshToken(authProvider *AuthProviderConfig, refreshToken string)
RevokeRefreshToken revokes a refresh token at the authorization server per RFC 7009. This is best-effort: errors are logged at Warn level but not returned, since local cleanup should proceed regardless of server-side revocation success.
func SaveSessionState ¶
func SaveSessionState(authProvider *AuthProviderConfig, userType UserType, tokenSet *TokenSet) error
SaveSessionState saves the current session state (with GCM-encrypted tokenSet), stamped with the fingerprint of the provider that minted the tokens.
Types ¶
type AuthProviderConfig ¶
type AuthProviderConfig struct {
Name string `yaml:"name"` // Name of the provider. The session ID derives from it; see GetSessionID.
ClientID string `yaml:"clientId"` // OAuth2 client ID.
AuthEndpoint string `yaml:"authEndpoint"` // Eg, "https://auth.metaplay.dev/oauth2/auth".
TokenEndpoint string `yaml:"tokenEndpoint"` // Eg, "https://auth.metaplay.dev/oauth2/token".
RevokeEndpoint string `yaml:"revokeEndpoint"` // Eg, "https://auth.metaplay.dev/oauth2/revoke".
UserInfoEndpoint string `yaml:"userInfoEndpoint"` // Eg, "https://portal.metaplay.dev/api/external/userinfo"
Scopes string `yaml:"scopes"` // Eg, "openid profile email offline_access"
Audience string `yaml:"audience"` // Eg, "managed-gameservers"
// Optional. Redirect URI of a page that shows the authorization code for the user
// to paste into the CLI, which is how 'auth login --no-browser' signs in when the
// browser cannot reach the CLI's loopback callback. Eg, "https://auth-ui.metaplay.dev/cli/code".
NoBrowserRedirectURI string `yaml:"noBrowserRedirectUri"`
// contains filtered or unexported fields
}
OAuth2 client configuration.
func NewDefaultAuthProvider ¶
func NewDefaultAuthProvider() (*AuthProviderConfig, error)
NewDefaultAuthProvider resolves the auth provider used when a project does not name one of its own: Metaplay Auth, or the provider described by the file named in METAPLAYCLI_AUTH_PROVIDER_FILE when that is set, which is how a platform other than the managed one is reached.
func NewMetaplayAuthProvider ¶
func NewMetaplayAuthProvider() *AuthProviderConfig
NewMetaplayAuthProvider returns the auth provider for Metaplay's managed platform. Commands should call NewDefaultAuthProvider instead, which honors AuthProviderFileEnvVar.
func (*AuthProviderConfig) Fingerprint ¶
func (provider *AuthProviderConfig) Fingerprint() string
Fingerprint identifies the platform and client a session's tokens were minted for. The token endpoint issues them and the client ID is who they were issued to, so the pair pins the audience. Stored with the session, to catch a provider that shares a session key before it is handed tokens it did not mint.
The guarantee is narrow. Only these two fields are hashed, so a provider reusing both is accepted, and revokeEndpoint and userInfoEndpoint are not pinned at all. Sessions written before this field existed carry no fingerprint and any provider sharing their key is accepted — see sessionBelongsToProvider. This guards against collision and misconfiguration among providers that are all trusted. It is not a boundary against a project config that is not.
The endpoint is hashed verbatim, so a host differing only in letter case or an explicit ':443' reads as a different provider.
func (*AuthProviderConfig) GetSessionID ¶
func (provider *AuthProviderConfig) GetSessionID() string
func (*AuthProviderConfig) IsBuiltinMetaplayAuth ¶
func (provider *AuthProviderConfig) IsBuiltinMetaplayAuth() bool
IsBuiltinMetaplayAuth reports whether this is the built-in Metaplay Auth provider, as opposed to one loaded from AuthProviderFileEnvVar or named by the project. A session from any other provider belongs to a different platform: its tokens name that platform as their audience and must not be presented to Metaplay-operated services.
A file provider cannot claim this name; validation rejects it. A provider defined in metaplay-project.yaml can, because pkg/metaproj validates it separately and does not apply the reserved name. Such a provider reports true here and shares the built-in session key, so a caller gating a token on this is trusting the project file.
func (*AuthProviderConfig) LoginCommand ¶
func (provider *AuthProviderConfig) LoginCommand() string
LoginCommand returns the command that signs in to this provider, for error suggestions. A bare 'metaplay auth login' resolves the default provider, so it reaches the built-in provider and a file one, but never a project-defined provider.
It names the authProviders key, not Name. Name is not a reliable argument: two providers may share one, a Name may collide with another provider's key, and a provider named 'metaplay' would resolve back to the default.
It branches on provenance rather than IsBuiltinMetaplayAuth, which a project provider can make true by taking the built-in name — handing the bare command to exactly the providers it cannot reach.
func (*AuthProviderConfig) SetProjectKey ¶
func (provider *AuthProviderConfig) SetProjectKey(key string)
SetProjectKey records the authProviders key this provider is filed under. For the project loader; nothing else has reason to call it.
type PersistedConfig ¶
type PersistedConfig struct {
Sessions map[string]PersistedSessionState `json:"sessions"` // Persisted sessions, use sessionID as key.
// Logins started with 'auth login --no-browser' and not yet finished, use sessionID as key.
PendingLogins map[string]PersistedPendingLogin `json:"pendingLogins,omitempty"`
}
Represents the config.json persisted on disk.
type PersistedPendingLogin ¶
type PersistedPendingLogin struct {
State string `json:"state"` // OAuth2 state the authorization request carried
VerifierGCM string `json:"verifierGcm"` // GCM-encrypted PKCE code verifier
RedirectURI string `json:"redirectUri"` // Redirect URI the code was issued for, needed again in the exchange
ProviderPrint string `json:"providerPrint"` // AuthProviderConfig.Fingerprint() of the provider the login was started with
ExpiresAt time.Time `json:"expiresAt"` // After this, the code can no longer be exchanged
}
A login started without a browser, waiting for the user to paste the code the sign-in page showed. Persisted because the CLI that finishes it may be a later invocation than the one that started it.
type PersistedSessionState ¶
type PersistedSessionState struct {
UserType UserType `json:"userType"` // Type of the user (human or machine)
TokenSetLegacy string `json:"tokenSet,omitempty"` // Legacy CFB-encrypted tokenSet (deprecated)
TokenSetGCM string `json:"tokenSetGcm,omitempty"` // GCM-encrypted tokenSet
ProviderPrint string `json:"providerPrint,omitempty"` // AuthProviderConfig.Fingerprint() of the provider that minted these tokens
}
Persisted session state (with encrypted tokenSet).
type SessionState ¶
type SessionState struct {
UserType UserType // Type of user in portal.
TokenSet *TokenSet // TokenSet for the user.
}
In-memory session state.
func LoadSessionState ¶
func LoadSessionState(authProvider *AuthProviderConfig) (*SessionState, error)
LoadSessionState loads a session state and decrypts the tokenSet. Returns nil if there is no existing session. If a legacy CFB-encrypted session is found, it is automatically migrated to GCM. On Linux, sessions encrypted with the fallback key are re-encrypted with the keyring-based key if a keyring becomes available.
type TokenSet ¶
type TokenSet struct {
IDToken string `json:"id_token"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type,omitempty"`
Scope string `json:"scope,omitempty"`
}
Type for Metaplay Auth. Get this using OAuth2 code exchange with auth.metaplay.dev.
func LoadAndRefreshTokenSet ¶
func LoadAndRefreshTokenSet(authProvider *AuthProviderConfig) (*TokenSet, error)
Load the current token set. If not logged in, just return empty tokens. If logged in and tokens have expired, refresh the tokens. If the refresh fails, return an error. refreshTokenSet decides whether the session is kept.
func LoadAndRefreshTokenSetValidFor ¶
func LoadAndRefreshTokenSetValidFor(authProvider *AuthProviderConfig, validFor time.Duration) (*TokenSet, error)
LoadAndRefreshTokenSetValidFor is LoadAndRefreshTokenSet, but also refreshes tokens that expire within validFor, for a caller handing the token on to something that will hold it that long. If that early refresh fails, other than by the grant being refused, the current token is handed on instead, since it still works until it expires; the next call tries the refresh again. A machine user's token, which cannot be refreshed, is likewise handed on until it expires.
type UserInfoError ¶
type UserInfoError struct {
StatusCode int // HTTP status code, e.g. 401
Status string // HTTP status line, e.g. "401 Unauthorized"
Message string // Server's explanation from the response body, or empty
// MessageIsField reports whether Message came from a message field of a JSON
// body, rather than being the raw body, such as a proxy's HTML error page.
MessageIsField bool
}
UserInfoError is returned by FetchUserInfo when the userinfo endpoint responds with a non-2xx status code. Callers can use errors.AsType to inspect the status code.
func (*UserInfoError) Error ¶
func (e *UserInfoError) Error() string
Error implements the error interface.
type UserInfoResponse ¶
type UserInfoResponse struct {
Subject string `json:"sub"` // Same as account.provideAccountId (not portal userID)
Email string `json:"email"`
Picture string `json:"picture"`
GivenName string `json:"given_name"`
FamilyName string `json:"family_name"`
Name string `json:"name"`
Roles []string `json:"https://schemas.metaplay.io/roles"`
}
*
- OIDC UserInfo Response object.
- @see https://openid.net/specs/openid-connect-core-1_0.html#UserInfo
func FetchUserInfo ¶
func FetchUserInfo(authProvider *AuthProviderConfig, tokenSet *TokenSet) (*UserInfoResponse, error)