Help us shape the future of Go! Take the 2026 Go Developer Survey

auth

package
v0.3.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SchemeBearer = "bearer"
	SchemeBasic  = "basic"
)

Auth schemes used when attaching credentials to a request.

View Source
const DefaultScopeLevel = "write"

DefaultScopeLevel is the preset requested when none is specified.

Variables

View Source
var ForceFileStorage = false

ForceFileStorage can be set to true in tests to skip keyring

Functions

func AccessTokenExpiredOrUnknown

func AccessTokenExpiredOrUnknown() bool

AccessTokenExpiredOrUnknown reports whether the stored OAuth access token has expired (or is within the refresh buffer of expiring), or whether its expiry is unknown (ExpiresAt == 0, e.g. stored by an older version). Used to decide whether a 404 — which Bitbucket returns for expired access to private resources — is worth a refresh-and-retry rather than a genuine not-found.

func BuildAuthorizeURL

func BuildAuthorizeURL(cfg OAuthConfig) (authURL, state string, err error)

BuildAuthorizeURL returns the Bitbucket authorize URL plus the random state to match against the callback. Used by the manual (no-server) login flow.

func DebugLogPath

func DebugLogPath() string

DebugLogPath is where token-operation traces are written when BB_AUTH_DEBUG is set.

func DefaultScopes

func DefaultScopes() []string

DefaultScopes returns the OAuth scopes for the default level.

func DeleteTokens

func DeleteTokens() error

DeleteTokens clears every production backend, regardless of the current mode. ForceFileStorage isolates tests from the keyring.

func GetAPIEmail

func GetAPIEmail() string

GetAPIEmail returns the BITBUCKET_EMAIL if set. When paired with BITBUCKET_API_TOKEN it selects HTTP Basic auth (the scheme required by Atlassian scoped API tokens, the replacement for deprecated app passwords).

func GetAPIToken

func GetAPIToken() string

GetAPIToken returns the BITBUCKET_API_TOKEN if set

func GetValidToken

func GetValidToken() (string, error)

GetValidToken returns a valid access token string. Retained for callers that only need the raw token; prefer GetCredential, which also carries the scheme.

func HasAPIToken

func HasAPIToken() bool

HasAPIToken checks if BITBUCKET_API_TOKEN is set

func HasStoredTokens

func HasStoredTokens() bool

HasStoredTokens checks if tokens are stored

func Logout

func Logout() error

Logout clears stored tokens

func ResolveScopes

func ResolveScopes(spec string) ([]string, error)

ResolveScopes turns a --scopes spec into a concrete scope list. An empty spec yields the default level. A known preset name (read/write/admin) expands to its set; any other value is treated as an explicit comma/space-separated scope list, so power users can request an exact set.

func ScopePresetNames

func ScopePresetNames() []string

ScopePresetNames returns the preset names in increasing-privilege order.

func SetKeyringServiceForTesting

func SetKeyringServiceForTesting(name string) func()

SetKeyringServiceForTesting overrides the keyring service name and returns a restore func. Tests (including in other packages) MUST call this so the suite never reads or deletes the real user's stored OAuth token.

func SetTokenStoreMode

func SetTokenStoreMode(m string)

SetTokenStoreMode sets the token storage mode ("auto", "keyring", or "file"). Empty selects auto; unrecognised values fail closed to keyring-only storage.

func StoreTokens

func StoreTokens(data *TokenData) error

StoreTokens saves tokens to the system keyring

Types

type AuthMethod

type AuthMethod string

AuthMethod indicates how authentication is configured

const (
	AuthMethodNone  AuthMethod = "none"
	AuthMethodToken AuthMethod = "token" // BITBUCKET_API_TOKEN
	AuthMethodOAuth AuthMethod = "oauth" // OAuth 2.0 flow
)

type AuthStatus

type AuthStatus struct {
	LoggedIn        bool
	Method          AuthMethod
	Scheme          string // auth scheme when Method is token: "basic" or "bearer"
	Scopes          string
	ExpiresAt       int64 // absolute Unix expiry of the OAuth access token (0 = unknown)
	HasRefreshToken bool  // whether a refresh token is stored (enables silent renewal)
	LegacyTokenFile bool  // an inactive token file exists; never implicitly imported
}

AuthStatus returns information about the current authentication state

func GetStatus

func GetStatus() (*AuthStatus, error)

GetStatus returns the current authentication status

type Credential

type Credential struct {
	Scheme   string
	Username string // basic-auth username (account email); empty for bearer
	Token    string // bearer token, or basic-auth password
}

Credential carries the resolved authentication for a request along with the scheme used to attach it. OAuth access tokens and Bitbucket Access Tokens use Bearer; Atlassian scoped API tokens use Basic (email:token).

func GetCredential

func GetCredential() (Credential, error)

GetCredential resolves the credential to use for API requests.

Selection order:

  1. BITBUCKET_API_TOKEN + BITBUCKET_EMAIL -> Basic (Atlassian API token)
  2. BITBUCKET_API_TOKEN alone -> Bearer (Access Token / raw token)
  3. stored OAuth access token -> Bearer

func (Credential) Apply

func (c Credential) Apply(req *http.Request)

Apply attaches the credential to an outgoing request.

type OAuthConfig

type OAuthConfig struct {
	ClientID     string
	ClientSecret string
	Scopes       []string
}

OAuthConfig holds OAuth configuration

type TokenData

type TokenData struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"`
	ExpiresAt    int64  `json:"expires_at"` // absolute Unix seconds; computed at store time
	TokenType    string `json:"token_type"`
	Scopes       string `json:"scopes"`
}

TokenData holds the stored token information

func ExchangeCallbackURL

func ExchangeCallbackURL(cfg OAuthConfig, expectedState, pasted string) (*TokenData, error)

ExchangeCallbackURL completes the OAuth flow from a pasted callback URL (the full `http://localhost:34106/callback?...` redirect) or a bare authorization code. When the input is a full URL and expectedState is non-empty, the state is validated. This avoids needing the local callback server (e.g. over SSH).

func LoadTokens

func LoadTokens() (*TokenData, error)

LoadTokens retrieves tokens, preferring the system keyring and (in auto mode) falling back to the 0600 file mirror.

func Login

func Login(cfg OAuthConfig) (*TokenData, error)

Login performs the OAuth 2.0 authorization code flow

func RefreshAccessToken

func RefreshAccessToken() (*TokenData, error)

RefreshAccessToken uses the refresh token to get a new access token

func (*TokenData) NeedsRefresh

func (t *TokenData) NeedsRefresh() bool

NeedsRefresh reports whether the access token has expired or is within the refresh buffer of expiring. Returns false when expiry is unknown (ExpiresAt == 0, e.g. tokens stored by an older version), so callers fall back to optimistic use plus reactive 401 refresh.

Jump to

Keyboard shortcuts

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