rechallenge

package
v1.12.2-0...-eb60e09 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package rechallenge implements the Rechallenge v2 step-up authentication flow. Mirrors src/lib/rechallenge/* in the Node implementation.

Contract guarantees (load-bearing per project_rechallenge_v2.md):

  • Parker path templates and the elevated-header name come from extensions.rechallenge ON EACH response, never hardcoded.
  • Only mutations are eligible for step-up; queries surface errors unchanged.
  • The elevated-token cache uses a single keychain entry shared with the Node binary so logged-in state crosses binaries.

Index

Constants

View Source
const (
	// ElevatedPermissionErrorCode matches src/lib/rechallenge/types.ts.
	ElevatedPermissionErrorCode = "elevated-permission-required"
	// Version is the rechallenge protocol version this client supports.
	Version = "v2"
	// ClientType is sent in createSession to identify the caller.
	ClientType = "cli"
)
View Source
const MinPollInterval = 2 * time.Second

MinPollInterval floors the server-supplied poll interval. A missing, zero, or negative pollIntervalSeconds used to produce a zero sleep, i.e. an unthrottled status-poll loop against Parker for the life of the session. Matches MIN_POLL_INTERVAL_SECONDS in src/lib/rechallenge/flow.ts.

View Source
const WaitEnvVar = "VIP_RECHALLENGE_WAIT"

WaitEnvVar opts back in to waiting for a step-up approval in a non-interactive session. Named as a constant because the error text that tells the user about it must not be able to drift from the variable actually read.

View Source
const WaitFlag = "--rechallenge-wait"

WaitFlag is the command-line half of the same opt-in. Registered by the commands that can trip step-up (see NewDefensiveModeCmd), matching where Node registers it — src/bin/vip-defensive-mode-{enable,disable,configure}.js.

Variables

This section is empty.

Functions

func IsInteractiveContext

func IsInteractiveContext(argv []string) bool

IsInteractiveContext returns true when interactive prompts and browser opens are appropriate. Mirrors src/lib/rechallenge/flow.ts:isInteractiveContext.

Order:

  1. VIP_NON_INTERACTIVE=1 → false
  2. argv contains "--non-interactive" → false
  3. else stdin-is-tty

Sensed on STDIN for the same reason as appctx.IsInteractive (parity blocker B5): an approval has to be typed in, so stdout redirection is irrelevant.

func OpenBrowser

func OpenBrowser(url string)

OpenBrowser tries to open url in the user's default browser. Errors are swallowed (logged at debug level) — they're not actionable for the CLI. Mirrors src/lib/rechallenge/open-browser.ts.

func RedactSecrets

func RedactSecrets(value string, secrets ...string) string

RedactSecrets strips credentials from server-controlled text before it is shown, logged, or shipped.

Every string that passes through here is on its way somewhere durable: the user's terminal, a CI log, and cmd/vip-next/main.go's exit hook, which posts error text to the telemetry endpoint. Parker echoes request context into some error payloads, so a response body can carry back the Authorization header we sent it. Pass every credential in scope as a secret; an empty secret is ignored so a zero-valued token cannot blank the whole message.

func ServiceNameForHost

func ServiceNameForHost(apiHost string) string

ServiceNameForHost builds the keychain service name for the elevated-token cache. Returns the bare base name for the production API host; otherwise suffixes ":<sanitized-host>".

func ShouldWaitForRechallenge

func ShouldWaitForRechallenge() bool

ShouldWaitForRechallenge reports whether the caller has explicitly asked to block on a step-up challenge despite being non-interactive — the case where an operator running headless will approve on a phone.

Without this, a non-interactive step-up fails fast (see NewInteractionRequiredError): the default has to be "fail", because the common non-interactive caller is CI, which cannot approve anything and would otherwise block until the verification session expires.

Mirrors src/lib/rechallenge/flow.ts:185, including its argv scan and reason for it: the step-up middleware is built once at startup and cannot read a command's parsed options, so the flag is read from the raw command line even though cobra also parses it.

Types

type AbortedError

type AbortedError struct {
	// contains filtered or unexported fields
}

AbortedError — user cancelled the flow (signal or interactive cancel).

func NewAbortedError

func NewAbortedError(scope string) *AbortedError

func (*AbortedError) Error

func (e *AbortedError) Error() string

func (*AbortedError) Scope

func (e *AbortedError) Scope() string

func (*AbortedError) Unwrap

func (e *AbortedError) Unwrap() error

type Client

type Client struct {
	APIHost     string
	BearerToken string
	HTTP        *http.Client
}

Client speaks the Parker REST protocol. APIHost should NOT include a trailing slash; paths supplied to its methods come from extensions.rechallenge and already start with "/".

func (*Client) CreateSession

func (c *Client) CreateSession(in CreateSessionInput) (*Session, error)

func (*Client) Exchange

func (c *Client) Exchange(in ExchangeInput) (*ExchangeResponse, error)

func (*Client) GetSessionStatus

func (c *Client) GetSessionStatus(in GetSessionStatusInput) (*SessionStatus, error)

type CreateSessionInput

type CreateSessionInput struct {
	Path               string
	RequestedOperation string
}

type ElevatedToken

type ElevatedToken struct {
	Token      string    `json:"token"`
	ExpiresAt  time.Time `json:"expiresAt"`
	Purpose    string    `json:"purpose"`
	HeaderName string    `json:"headerName,omitempty"`
}

ElevatedToken is the elevated bearer issued after successful step-up. HeaderName is set by the flow orchestrator (copied from Extension.ElevatedHeaderName) so the link layer doesn't need to consult the Extension during replay.

type Error

type Error struct {
	// contains filtered or unexported fields
}

Error is the base rechallenge error. Specific failure modes carry one as their `base` field and expose it via Unwrap so errors.As(err, &*Error{}) recognizes the family. Naming note: we can't embed *Error anonymously because the type name and the Error() method collide.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Scope

func (e *Error) Scope() string

type ExchangeInput

type ExchangeInput struct {
	Template    string
	ChallengeID string
	Scope       string
}

type ExchangeResponse

type ExchangeResponse struct {
	ElevatedToken ElevatedToken `json:"elevatedToken"`
}

ExchangeResponse is the response from POST {exchangePathTemplate}.

type Extension

type Extension struct {
	Version              string `json:"version"`
	CreateSessionPath    string `json:"createSessionPath"`
	StatusPathTemplate   string `json:"statusPathTemplate"`
	ExchangePathTemplate string `json:"exchangePathTemplate"`
	ElevatedHeaderName   string `json:"elevatedHeaderName"`
}

Extension is the shape of errors[0].extensions.rechallenge from the API.

func (Extension) IsValid

func (e Extension) IsValid() bool

IsValid reports whether the extension has all required template fields. Mirrors the typeof checks in link.ts:extractElevatedPermission.

type GetSessionStatusInput

type GetSessionStatusInput struct {
	Template    string
	ChallengeID string
	Scope       string
}

type HttpError

type HttpError struct {
	// contains filtered or unexported fields
}

HttpError — Parker REST endpoint returned a non-2xx response.

func NewHttpError

func NewHttpError(statusCode int, bodyText, scope string) *HttpError

func (*HttpError) BodyText

func (e *HttpError) BodyText() string

func (*HttpError) Error

func (e *HttpError) Error() string

func (*HttpError) Scope

func (e *HttpError) Scope() string

func (*HttpError) StatusCode

func (e *HttpError) StatusCode() int

func (*HttpError) Unwrap

func (e *HttpError) Unwrap() error

type InteractionRequiredError

type InteractionRequiredError struct {
	// contains filtered or unexported fields
}

InteractionRequiredError — a step-up challenge was raised in a session where no human can answer it. Returned INSTEAD of opening a verification session, because polling one to expiry is an unbounded block in exactly the context (CI, cron, a piped script) that can least afford it.

Mirrors RechallengeInteractionRequiredError in src/lib/rechallenge/errors.ts. The wording differs on one point: Node offers `--rechallenge-wait` as well as the environment variable; vip-next has only the environment variable, because the flag has no cobra registration to land on and advertising it would be a promise the binary does not keep.

func NewInteractionRequiredError

func NewInteractionRequiredError(scope string) *InteractionRequiredError

func (*InteractionRequiredError) Error

func (e *InteractionRequiredError) Error() string

func (*InteractionRequiredError) Scope

func (e *InteractionRequiredError) Scope() string

func (*InteractionRequiredError) Unwrap

func (e *InteractionRequiredError) Unwrap() error

type RunInput

type RunInput struct {
	RequestedOperation string
	Extension          Extension
	Interactive        bool

	// Wait opts a non-interactive caller back in to polling. Without it a
	// step-up challenge raised outside a TTY fails immediately rather than
	// blocking on an approval nobody present can give. See
	// ShouldWaitForRechallenge.
	Wait bool
}

RunInput contains everything the runner needs for one invocation.

type Runner

type Runner struct {
	Client     *Client
	Tracker    Tracker
	TokenCache *TokenCache

	// Stdout receives the user-facing verification prompt. Defaults to os.Stderr
	// (Node's flow.ts uses console.warn so we mirror to stderr).
	Stdout io.Writer

	// OpenURL is called to open the browser when Interactive is true.
	// Defaults to OpenBrowser.
	OpenURL func(url string)

	// Sleep is called between polls. ctx-aware; tests inject a no-op or
	// ctx-blocking variant.
	Sleep func(ctx context.Context, d time.Duration) error
}

Runner orchestrates one step-up flow. All side-effect dependencies are injectable for testing.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, in RunInput) (*ElevatedToken, error)

Run executes the step-up flow and returns the elevated token on success.

type Session

type Session struct {
	ChallengeID         string    `json:"challengeId"`
	Status              Status    `json:"status"`
	VerificationURL     string    `json:"verificationUrl"`
	PollIntervalSeconds int       `json:"pollIntervalSeconds"`
	ExpiresAt           time.Time `json:"expiresAt"`
}

Session is the response from POST {createSessionPath}.

type SessionStatus

type SessionStatus struct {
	ChallengeID         string        `json:"challengeId"`
	Status              Status        `json:"status"`
	ExpiresAt           time.Time     `json:"expiresAt"`
	VerifiedAt          *time.Time    `json:"verifiedAt,omitempty"`
	Provider            string        `json:"provider,omitempty"`
	PollIntervalSeconds int           `json:"pollIntervalSeconds"`
	StatusReason        *StatusReason `json:"statusReason,omitempty"`
}

SessionStatus is the response from GET {statusPathTemplate}.

type Status

type Status string

Status mirrors RechallengeStatus from types.ts.

const (
	StatusPending   Status = "pending"
	StatusVerified  Status = "verified"
	StatusExpired   Status = "expired"
	StatusFailed    Status = "failed"
	StatusCancelled Status = "cancelled"
)

func (Status) IsTerminal

func (s Status) IsTerminal() bool

IsTerminal reports whether the status indicates the flow should stop polling.

type StatusReason

type StatusReason struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

StatusReason is the optional explanation returned with a terminal status.

type TerminalError

type TerminalError struct {
	// contains filtered or unexported fields
}

TerminalError — session ended in a non-verified terminal state.

func NewTerminalError

func NewTerminalError(status Status, scope, detail string) *TerminalError

func (*TerminalError) Error

func (e *TerminalError) Error() string

func (*TerminalError) Scope

func (e *TerminalError) Scope() string

func (*TerminalError) Status

func (e *TerminalError) Status() Status

func (*TerminalError) Unwrap

func (e *TerminalError) Unwrap() error

type TokenCache

type TokenCache struct {
	Keychain *keychain.Keychain
	// contains filtered or unexported fields
}

TokenCache stores elevated tokens per scope in a single Go-owned keychain entry. The on-disk shape is a JSON blob {scope: ElevatedToken}, keeping ClearAll cheap while preserving the Node data shape.

func (*TokenCache) ClearAll

func (c *TokenCache) ClearAll() error

ClearAll drops the keychain entry entirely. Called on logout.

func (*TokenCache) ClearScope

func (c *TokenCache) ClearScope(scope string) error

func (*TokenCache) Get

func (c *TokenCache) Get(scope string) (*ElevatedToken, error)

Get returns the cached token for scope, or nil if missing/expired. Expired tokens are evicted as a side effect (matches Node).

func (*TokenCache) Set

func (c *TokenCache) Set(scope string, tok ElevatedToken) error

type Tracker

type Tracker interface {
	Track(name string, props map[string]any)
}

Tracker is the minimal telemetry interface the runner needs.

type UnsupportedVersionError

type UnsupportedVersionError struct {
	// contains filtered or unexported fields
}

UnsupportedVersionError — server requested a version this CLI doesn't speak.

func NewUnsupportedVersionError

func NewUnsupportedVersionError(version, scope string) *UnsupportedVersionError

func (*UnsupportedVersionError) Error

func (e *UnsupportedVersionError) Error() string

func (*UnsupportedVersionError) Scope

func (e *UnsupportedVersionError) Scope() string

func (*UnsupportedVersionError) Unwrap

func (e *UnsupportedVersionError) Unwrap() error

func (*UnsupportedVersionError) Version

func (e *UnsupportedVersionError) Version() string

Jump to

Keyboard shortcuts

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