auth

package
v3.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AuthTypePAT = config.AuthTypePAT
	AuthTypeSSO = config.AuthTypeSSO
)
View Source
const (
	SSOAuthServerBase = "https://id.harness.io"

	SSOClientID = "harness-cli-client"

	AccessTokenGracePeriod = 15 * time.Second
)
View Source
const SourceEnv = "env"

Variables

View Source
var ErrSSOSessionExpired = fmt.Errorf("SSO session expired")

ErrSSOSessionExpired is the sentinel for an expired SSO refresh token. Use SSOSessionExpiredError to build the user-facing error with the correct login hint.

Functions

func AccessTokenExpiry

func AccessTokenExpiry(rawToken string) (time.Time, error)

AccessTokenExpiry returns the expiration time embedded in the JWT's "exp" claim.

func AccountIDFromToken

func AccountIDFromToken(token string) string

AccountIDFromToken extracts the account ID from a valid PAT/SAT of the form pat.{AccountID}.x.y or sat.{AccountID}.x.y. Callers must validate the token with ValidatePATFormat before calling this.

func CheckAndUpdateAccessToken

func CheckAndUpdateAccessToken(r *ResolvedAuth, now time.Time) error

CheckAndUpdateAccessToken checks whether the SSO access token in r is expiring soon and, if so, refreshes it. On a successful refresh the credentials file and r are both updated in place. No-ops for PAT profiles or env-sourced auth.

func CodeChallenge

func CodeChallenge(verifier string) string

CodeChallenge derives the S256 PKCE challenge from a verifier.

func DeleteCredential

func DeleteCredential(profileName string) error

DeleteCredential removes the token for the named profile and saves. It is a no-op if the profile does not exist in the credentials file.

func ExchangeCode

func ExchangeCode(tokenEndpoint, clientID, code, verifier, redirectURI string) (accessToken, refreshToken string, err error)

ExchangeCode exchanges an authorization code for access and refresh tokens.

func GenerateCodeVerifier

func GenerateCodeVerifier() (string, error)

GenerateCodeVerifier generates a random PKCE code verifier.

func IsAccessTokenExpiringSoon

func IsAccessTokenExpiringSoon(rawToken string, now time.Time) bool

IsAccessTokenExpiringSoon reports whether rawToken expires within AccessTokenGracePeriod. Returns true (treat as expired) if the expiry cannot be determined.

func LoadCredentials

func LoadCredentials() (map[string]*ProfileCredentials, error)

LoadCredentials reads ~/.harness/credentials and returns a map of profile → credentials. Returns an empty map if the file does not exist.

func Masked

func Masked(s string) string

Masked returns a display-safe representation of an arbitrary secret string by replacing every character with a bullet.

func MaskedToken

func MaskedToken(s string) string

MaskedToken returns a display-safe representation of a token. For PAT/SAT tokens it reveals <prefix>.<accountID> and masks the remaining segments. For anything else it falls back to Masked.

func NormalizeAPIURL

func NormalizeAPIURL(s string) string

NormalizeAPIURL expands a bare label shorthand (e.g. "harness0" → "https://harness0.harness.io") and, for anything else that has no scheme, prepends "https://" (e.g. "harness.onefiserv.net" → "https://harness.onefiserv.net"). Input that already has a scheme is returned unchanged.

func RandomState

func RandomState() (string, error)

RandomState generates a random OAuth2 state parameter.

func RefreshSSOToken

func RefreshSSOToken(oldRefreshToken string) (accessToken, refreshToken string, err error)

RefreshSSOToken exchanges a refresh token for a new access token (and possibly a new refresh token). If the server does not return a new refresh token, the original is returned unchanged.

func SSOAuthServerURL

func SSOAuthServerURL() string

SSOAuthServerURL returns the SSO authorization server base URL, honoring the HARNESS_SSO_AUTH_SERVER_URL override and falling back to SSOAuthServerBase.

func SSOClientIDValue

func SSOClientIDValue() string

SSOClientIDValue returns the SSO OAuth client ID, honoring the HARNESS_SSO_CLIENT_ID override and falling back to SSOClientID.

func SaveCredentials

func SaveCredentials(creds map[string]*ProfileCredentials) error

SaveCredentials writes the credentials map to ~/.harness/credentials with 0600 perms.

func SetCredential

func SetCredential(profileName, token string) error

SetCredential adds or updates the PAT/SAT token for the named profile and saves.

func SetSSOCredentials

func SetSSOCredentials(profileName, token, refreshToken string) error

SetSSOCredentials saves both the access token and refresh token for an SSO profile.

func Validate

func Validate(r *ResolvedAuth) error

Validate checks that a ResolvedAuth is complete enough to make API calls.

func ValidateAPIURL

func ValidateAPIURL(apiURL string) error

ValidateAPIURL returns an error if apiURL is not a well-formed https:// URL with a host. It no longer restricts the host to *.harness.io, so vanity and on-prem domains are accepted.

func ValidatePATFormat

func ValidatePATFormat(token string) error

ValidatePATFormat returns an error if token does not match pat.<accountId>.<tokenId>.<secret> or sat.<accountId>.<tokenId>.<secret>.

Types

type AuthServerMeta

type AuthServerMeta struct {
	Issuer                string `json:"issuer"`
	AuthorizationEndpoint string `json:"authorization_endpoint"`
	TokenEndpoint         string `json:"token_endpoint"`
	RegistrationEndpoint  string `json:"registration_endpoint"`
}

AuthServerMeta holds the endpoints from OAuth2 authorization server discovery.

func FetchAuthServerMeta

func FetchAuthServerMeta(c *http.Client, authServerBaseURL string) (*AuthServerMeta, error)

FetchAuthServerMeta retrieves OAuth2 authorization server metadata via discovery.

type AuthType

type AuthType = config.AuthType

AuthType is re-exported from pkg/config for callers that only import pkg/auth.

type ProfileCredentials

type ProfileCredentials struct {
	Token        string // PAT or SAT token
	SSOToken     string // access token; only present for SSO profiles
	RefreshToken string // only present for SSO profiles
}

type ResolvedAuth

type ResolvedAuth struct {
	Source          string   // "profile:<name>" or SourceEnv
	AuthType        AuthType // AuthTypePAT or AuthTypeSSO
	ExplicitProfile string   // non-empty only when --profile flag was explicitly passed
	APIUrl          string
	UIUrl           string // Harness UI base URL; only set for SSO profiles (from JWT subdomain)
	AccountID       string
	OrgID           string
	ProjectID       string
	RegistryURL     string
	Email           string    // user email from profile; empty for env-var auth or legacy profiles
	UserType        string    // config.UserTypeUser or config.UserTypeServiceAccount; empty for env-var auth, legacy profiles, or SSO
	UserID          string    // Harness user uuid from profile; empty for env-var auth, legacy profiles, or service accounts
	TokenKind       TokenKind // pat, sat, jwt, or "" (unknown)

	// Exactly one of these is set depending on AuthType.
	PATToken     string // set when AuthType == AuthTypePAT
	SSOToken     string // set when AuthType == AuthTypeSSO
	RefreshToken string // set when AuthType == AuthTypeSSO
}

ResolvedAuth is the result of auth resolution — the active credentials for a command invocation. Credential fields are never printed; callers that display auth context must omit them.

func Load

func Load(profileFlag string) (*ResolvedAuth, error)

Load populates a ResolvedAuth following the 4-step resolution order from auth.md. It never errors on missing optional fields — callers get whatever could be populated. Use Validate to check that the result is complete enough to make API calls.

func Resolve

func Resolve(profileFlag string) (*ResolvedAuth, error)

Resolve loads and validates credentials. Used by all normal commands.

func ResolveWithOverrides

func ResolveWithOverrides(profileFlag, orgOverride, projectOverride string) (*ResolvedAuth, error)

ResolveWithOverrides resolves credentials via Resolve, then applies orgOverride/ projectOverride on top of whatever the resolved profile/env already set. An empty override leaves the resolved value untouched.

func (*ResolvedAuth) LoginHint

func (r *ResolvedAuth) LoginHint(cmd string) string

LoginHint returns the appropriate 'harness auth login...' command for an error hint, including --profile <name> when the profile was explicitly set via the flag.

func (*ResolvedAuth) SetAuthHeader

func (a *ResolvedAuth) SetAuthHeader(req *http.Request)

SetAuthHeader sets the appropriate Authorization or x-api-key header on req.

type TokenKind

type TokenKind string

TokenKind identifies the type of a Harness token.

const (
	TokenKindPAT     TokenKind = "pat"
	TokenKindSAT     TokenKind = "sat"
	TokenKindJWT     TokenKind = "jwt"
	TokenKindUnknown TokenKind = ""
)

func TokenType

func TokenType(token string) TokenKind

TokenType returns the kind of token (PAT, SAT, JWT, or unknown) by inspecting its structure. JWT detection is structural only: exactly 3 non-empty base64url segments separated by dots.

Jump to

Keyboard shortcuts

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