auth

package
v0.8.42 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const EnvTokenVar = "ENTIRE_TOKEN"

EnvTokenVar is the environment variable that, when set, bypasses contexts.json and the keyring entirely: its value is used verbatim as the login JWT for repo-scoped token exchange. This is the CI / workload-identity path — a runner injects a short-lived login or sa-session JWT and clones without an interactive `entire login`.

View Source
const (

	// JurisdictionIdentityScope is the scope jurisdiction identity tokens
	// are minted with (also used by git-remote-entire's jurisdiction git
	// auth). The receiving surface authorizes live per request, so the
	// scope carries identity semantics only, not a permission grant.
	JurisdictionIdentityScope = "openid"
)

Variables

View Source
var ErrNoCellForJurisdiction = errors.New("no entire-api cell configured for jurisdiction")

ErrNoCellForJurisdiction signals that the caller's home jurisdiction has no entire-api cell in the cluster catalog (or its row carries no apiUrl). It is not fatal: callers that also have a data-API path (e.g. activity/recap) treat it as "entire-api isn't serving this region yet" and fall back rather than failing the command. errors.Is unwraps it from the contextual message.

View Source
var ErrNotLoggedIn = tokenmanager.ErrNotLoggedIn

ErrNotLoggedIn re-exports tokenmanager.ErrNotLoggedIn so callers in the cli package can errors.Is against it without an extra import.

Functions

func Contexts added in v0.7.0

func Contexts() ([]*contexts.Context, string, error)

Contexts returns all stored login contexts and the current context name, for listing/switching. Order matches on-disk order.

func CoreURLFromEnvToken added in v0.7.4

func CoreURLFromEnvToken(rawToken string) (string, error)

CoreURLFromEnvToken derives the home-region core URL from an ENTIRE_TOKEN JWT's audience claim. Login and sa-session JWTs carry aud=<home-region URL>, which is what STS routing keys on — so we read aud, not iss (iss may be a regional core that can't mint the cross-region exchange).

SECURITY: the returned URL becomes the host the env token is POSTed to as a subject_token during exchange. ParseClaims does NOT verify the signature, so the audience is attacker-controlled if a forged token is injected. This function only enforces the *shape* of a safe endpoint (https, bare origin); the caller MUST additionally verify the URL is a trusted core for the target cluster (see clusterdiscovery.ResolveClusterCores) before exchanging, or a forged aud could redirect the token to an arbitrary host.

Structural rules, all required:

  • the aud is a well-formed absolute URL,
  • scheme is https (no cleartext token exchange),
  • it carries a host and no userinfo, path, query, or fragment — entire cores are bare origins (https://core.example.com), so anything richer is either a misconfigured token or an attempt to smuggle a path/redirect.

The aud claim may be a single string or an array (RFC 7519 §4.1.3); ParseClaims normalises both to a slice. Non-URL audiences (e.g. an OAuth client_id like "entire-cli") are skipped; the first URL-shaped audience is validated strictly. A token with no URL-shaped aud is rejected with a clear error rather than silently falling back to context resolution.

func EnableInsecureHTTP added in v0.6.3

func EnableInsecureHTTP()

EnableInsecureHTTP relaxes the token managers' HTTPS guard so non-loopback http:// resources (and the login server's STS endpoint) are permitted during token resolution. The CLI calls this when the user passes --insecure-http-auth to a command that hits the data API on a private network (e.g. a split-host local-dev box where both hosts are plain HTTP).

func HomeJurisdictionFromLoginJWT added in v0.8.0

func HomeJurisdictionFromLoginJWT(loginJWT string) (string, error)

HomeJurisdictionFromLoginJWT reads the home_jurisdiction claim without verifying the signature — callers only route with it; the server re-verifies. Returns "" (no error) when the claim is absent so each caller can phrase its own missing-claim error. Shared with git-remote-entire's jurisdiction git auth.

func JurisdictionToken added in v0.8.0

func JurisdictionToken(ctx context.Context, insecureHTTP bool, jurisdiction string) (string, error)

JurisdictionToken mints and returns a jurisdictional identity token (scope=openid, aud=jurisdiction host) for `jurisdiction`, for authenticating against that jurisdiction's entire-api cells (e.g. https://aws-us-east-2.api.entire.io/api/v1). Unlike NewEntireAPICellClient it returns the raw token string (it skips the cell-base-URL resolution, which is only needed to build a client) and it honours ENTIRE_TOKEN.

Subject credential precedence:

  • ENTIRE_TOKEN set: the env token is the exchange subject_token, and its own aud core drives the environment family (so this works with only ENTIRE_TOKEN set, no ENTIRE_API_BASE_URL, in prod/staging/loopback). Presence is exclusive and fail-closed — a malformed/blank value errors rather than falling back to a stored login. The env token must be a login JWT (subject-capable); a rejected exchange surfaces the server error.
  • otherwise: the active stored context's refreshed login JWT.

An empty `jurisdiction` falls back to the subject token's home_jurisdiction claim.

func LocalIdentityCacheKey added in v0.7.8

func LocalIdentityCacheKey() (string, error)

LocalIdentityCacheKey returns a non-secret local auth identity key.

func LoginTokenForContext added in v0.7.0

func LoginTokenForContext(c *contexts.Context) (string, error)

LoginTokenForContext returns the login JWT stored for c, read from the OS keyring slot the context points at. The encoded expiry is stripped; the server is the authority on validity and the device-flow login holds no refresh token, so an expired token surfaces as a 401 the caller can translate into a re-login hint.

func NewEntireAPICellClient added in v0.8.0

func NewEntireAPICellClient(ctx context.Context, insecureHTTP bool, target *CellTarget) (*api.Client, error)

NewEntireAPICellClient returns an authenticated client aimed at an entire-api cell, carrying a jurisdictional identity token (scope=openid, aud=jurisdiction host). Repo-scoped entire-api routes do not accept the narrowed api-access bearer minted for the BFF origin — they require a cell identity token (COR-666).

Cell selection, in precedence order:

  • target != nil: dial target.BaseURL and mint for target.Jurisdiction. This is the repo-scoped path — the caller (cli) resolved the repo's own cell.
  • the configured data host already targets a cell (host contains ".api."): keep that origin.
  • a loopback data host (local dev): keep that origin.
  • otherwise the data host is a BFF/apex: resolve the caller's home-cell apiUrl from the cluster catalog (home-jurisdiction fallback).

func NewRefreshingLoginProvider added in v0.7.4

func NewRefreshingLoginProvider(c *contexts.Context, transport http.RoundTripper, allowInsecureHTTP bool) (func(context.Context) (string, error), error)

NewRefreshingLoginProvider returns a login-JWT provider (the shape repocreds wants) for context c that transparently re-mints an expired login JWT from the stored refresh token.

It is backed by auth-go's tokenmanager, which is what makes this safe against the server's single-use refresh-token rotation: refreshes are serialised across processes (an advisory file lock) and goroutines, the store is re-read after locking so a late waiter reuses a peer's freshly minted token, and the rotated refresh token is persisted. Without that, two concurrent git-remote-entire processes (e.g. a recursive submodule fetch) could replay the same single-use token and trip the server's reuse detection, revoking the whole family.

A still-valid token is returned with no network call. A context with no stored refresh token degrades gracefully: valid token used, expired token surfaces a re-login error.

transport carries the caller's TLS configuration; allowInsecureHTTP permits an http:// core for loopback/dev.

func NewRefreshingResourceProvider added in v0.7.6

func NewRefreshingResourceProvider(c *contexts.Context, resourceOrigin string, transport http.RoundTripper, allowInsecureHTTP bool) (func(context.Context) (string, error), error)

NewRefreshingResourceProvider returns a provider that mints a bearer valid for resourceOrigin, by exchanging context c's login JWT at c's own core (RFC 8693). It is NewRefreshingLoginProvider's sibling for resource servers: where that returns the bare login JWT (the control plane / cluster cases, where the host is the core), this performs the token exchange the data API requires.

Both the silent login-JWT re-mint and the exchange run through the shared per-context tokenmanager (newContextTokenManager). resourceOrigin must already be origin-only (no path). No audience is passed: the token manager defaults the RFC 8693 audience to the resource origin, which is exactly what the data API requires (aud == its base URI), so the audience is derived from the host being dialed rather than read from discovery. Exchanged tokens are cached in-process by the tokenmanager for the life of this process.

transport carries the caller's TLS configuration; allowInsecureHTTP permits an http:// core/resource for loopback/dev.

func ParseEnvToken added in v0.7.8

func ParseEnvToken(raw string) (coreURL, token string, err error)

ParseEnvToken is the single owner of the ENTIRE_TOKEN validation sequence shared by coreapi.New's bypass and `entire auth status`: it trims the raw value, enforces fail-closed that it is non-blank, and derives the control- plane core origin from its aud via CoreURLFromEnvToken. Callers pass the raw env value (presence is the caller's LookupEnv decision) and send the returned token verbatim as the bearer to coreURL. A blank or aud-less value is an error, never a silent fall-back to context resolution.

func RecordLoginContext added in v0.7.0

func RecordLoginContext(rawToken, refreshToken string, activate bool) (string, error)

RecordLoginContext records a freshly obtained login token in the shared contexts.json credential model: it derives the issuer (core URL), handle, and expiry from the token's own claims, stores the token in the OS keyring under the entire-core:<issuer> service scheme entiredb uses, and writes (or updates) the matching context.

Contexts are keyed by identity (core URL + handle): re-logging into the same identity updates its context in place, while a second identity on the same core gets its own context (named handle@host) instead of clobbering the first.

activate controls current_context: true makes the just-completed login active (kubectl use-context style); false records it without switching the user's active account, though it still sets current_context when none exists yet.

This is the CLI's only credential write: a login recorded here is what every consumer resolves against — the control plane, the data API, the in-CLI git remote helper, and entiredb's CLIs, which share this file and keychain layout.

Returns the context name on success.

func RefreshedLoginToken added in v0.7.6

func RefreshedLoginToken(ctx context.Context, c *contexts.Context) (string, error)

RefreshedLoginToken returns context c's login JWT, transparently re-minting an expired one from the stored refresh token. It is the convenience form of NewRefreshingLoginProvider for callers that want a single token now (e.g. `auth status` / `logout`, which must report a refreshable session as alive rather than telling the user to re-login). The insecure-HTTP decision mirrors the control-plane resolver: loopback cores and the --insecure-http-auth opt-in are permitted, everything else requires https.

Errors preserve the tokenmanager sentinels (ErrReauthRequired when the session is genuinely dead, ErrNotLoggedIn when no credential is usable) so callers can branch on errors.Is.

func RemoveContext added in v0.7.4

func RemoveContext(name string) error

RemoveContext deletes the named context's keyring tokens, then its contexts.json entry. A missing context is a no-op. Used by logout and `logout --all-contexts`. File.Delete clears current_context when name was the active one, so removing the current context this way also logs it out.

func RemoveCurrentContext added in v0.7.0

func RemoveCurrentContext() error

RemoveCurrentContext deletes the active context's keyring tokens and its contexts.json entry, clearing current_context. It is a no-op (returns nil) when there is no current context. Used by logout.

func ResolveDataAPIToken added in v0.7.6

func ResolveDataAPIToken(ctx context.Context, dataBaseURL string) (string, error)

ResolveDataAPIToken returns a bearer for the data API at dataBaseURL.

It dials the API's /.well-known/entire-api.json to learn which login server(s) the API trusts and which audience to exchange for, picks the matching local auth context (active-wins-if-eligible → sole → explicit choice), and exchanges that context's login JWT for the advertised audience at that context's core. This is what makes

ENTIRE_API_BASE_URL=https://partial.to entire activity

authenticate as the partial.to login even while the active context is a prod entire.io login — with no per-command override needed.

Discovery is the only path: an API host that doesn't advertise /.well-known/entire-api.json (unreachable / 404 / 503 / malformed) is an error — without it we can't know which login servers the host trusts, and guessing risks exchanging a token at a core the host doesn't accept.

Callers that honour --insecure-http-auth must call EnableInsecureHTTP before invoking this (as they already do); the per-context exchange reads that global opt-in.

func SetCellExchangeTransportForTest added in v0.8.0

func SetCellExchangeTransportForTest(t interface{ Helper() }, rt http.RoundTripper) func()

SetCellExchangeTransportForTest overrides the transport used for jurisdiction token exchange and cluster listing, returning a restore closure — the same set/restore convention the rest of the package uses for test seams.

func SetCurrentContext added in v0.7.0

func SetCurrentContext(name string) error

SetCurrentContext makes name the active context. Returns an error when no context with that name exists (a stale current pointer is a foot-gun).

func SetResolveContextForAPIForTest added in v0.7.6

func SetResolveContextForAPIForTest(t interface{ Helper() }, fn resolveContextFunc) func()

SetResolveContextForAPIForTest overrides the /.well-known/entire-api.json discovery seam and returns a cleanup func. Tests in other packages that exercise a data-API command (activity/search/dispatch/recap) MUST install this — otherwise ResolveDataAPIToken makes a real network call to the configured data host. Test-only.

func SetResolveContextForCellAPIForTest added in v0.8.0

func SetResolveContextForCellAPIForTest(t interface{ Helper() }, fn resolveContextFunc) func()

SetResolveContextForCellAPIForTest overrides the cell-API discovery seam.

Types

type BrowserAuthFlow added in v0.7.6

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

BrowserAuthFlow is one in-progress loopback authorization-code login. It wraps an authcode.Flow, flattening the TokenSet to the (access, refresh) pair login.go persists — mirroring how PollDeviceAuth flattens the device-flow result. login.go depends on a small local interface that this concrete type satisfies, so it can fake the flow in tests.

func (*BrowserAuthFlow) AuthorizationURL added in v0.7.6

func (f *BrowserAuthFlow) AuthorizationURL() string

AuthorizationURL is the URL to open in the user's browser.

func (*BrowserAuthFlow) Close added in v0.7.6

func (f *BrowserAuthFlow) Close() error

Close tears down the loopback listener. Safe to call after Wait.

func (*BrowserAuthFlow) Exchange added in v0.7.6

func (f *BrowserAuthFlow) Exchange(ctx context.Context, code string) (accessToken, refreshToken string, err error)

Exchange redeems code for access + refresh tokens.

func (*BrowserAuthFlow) Wait added in v0.7.6

func (f *BrowserAuthFlow) Wait(ctx context.Context) (string, error)

Wait blocks until the browser is redirected to the loopback listener, returning the authorization code.

type CellClientFactory added in v0.8.1

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

CellClientFactory builds entire-api cell clients from a single resolved exchange subject, minting at most one jurisdictional identity token per jurisdiction. Identity tokens are per-jurisdiction, not per-cell — every cell in a jurisdiction accepts the same token — so a caller dialing several cells in one operation (multi-cell fan-out over the caller's repos) should build one factory and reuse it for every cell, instead of paying discovery + login refresh + RFC 8693 exchange once per cell via NewEntireAPICellClient.

A factory is safe for concurrent use, and holds credentials resolved at construction time — build it per operation, don't store it long-term. Like NewEntireAPICellClient it deliberately does NOT consult ENTIRE_TOKEN.

func NewEntireAPICellClientFactory added in v0.8.1

func NewEntireAPICellClientFactory(ctx context.Context, insecureHTTP bool) (*CellClientFactory, error)

NewEntireAPICellClientFactory resolves the exchange subject (active stored login context) once, for building clients aimed at several cells. See NewEntireAPICellClient for the single-cell convenience wrapper.

func (*CellClientFactory) ClientFor added in v0.8.1

func (f *CellClientFactory) ClientFor(ctx context.Context, target *CellTarget) (*api.Client, error)

ClientFor returns an authenticated client for the given cell target (nil falls back to home-jurisdiction routing), reusing an already-minted identity token when the target's jurisdiction matches an earlier call.

type CellTarget added in v0.8.0

type CellTarget struct {
	// BaseURL is the cell's apiUrl to dial (e.g. https://aws-eu-west-1.api.entire.io).
	BaseURL string
	// Jurisdiction is the repo's cluster jurisdiction; it drives the identity
	// token's audience and the core the exchange is performed at.
	Jurisdiction string
}

CellTarget pins the entire-api cell a repo-scoped call must reach and the jurisdiction its identity token must be minted for. The cli layer resolves it from the repo's own cluster (via coreapi mirrors/clusters), so a repo-scoped route reaches the cell that HOSTS the repo — not the caller's home cell. A nil target falls back to home-jurisdiction routing (derived from the login JWT), which is correct for the common same-region case and for local dev.

type Client

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

Client wraps a deviceflow.Client and an authcode.Client preconfigured for the entire-cli public client (see provider.go for the endpoint wiring).

func NewClient

func NewClient(server string, httpClient *http.Client, allowInsecureHTTP bool) *Client

NewClient constructs a Client for the device-flow login against server (the login-server origin, validated by the caller — `entire login --server`). httpClient.Transport is reused when non-nil (its TLS / proxy config flows through); a nil httpClient or nil Transport falls back to the deviceflow default (http.DefaultTransport).

HTTPS is required by default. Loopback http:// (localhost, 127.0.0.1, ::1) is always permitted — see isLoopbackHTTP. allowInsecureHTTP=true additionally permits non-loopback http:// for cases like local-dev auth hosts on a private network (e.g. http://devbox.internal); the CLI plumbs this from the --insecure-http-auth flag.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the issuer base URL this client talks to.

func (*Client) PollDeviceAuth

func (c *Client) PollDeviceAuth(ctx context.Context, deviceCode string) (*DeviceAuthPoll, error)

PollDeviceAuth polls the token endpoint. On any OAuth-protocol error (recognised RFC 8628 §3.5 sentinel or unknown but spec-shaped code like invalid_request / invalid_client / server_error), the wire-side code is returned in DeviceAuthPoll.Error so the existing polling loop in login.go can branch on it — known codes hit the dedicated switch arms, unknown codes fall through to the default arm and fail fast. Non-protocol errors (network, decode) are returned as a real error and treated as transient by the polling loop.

func (*Client) StartBrowserAuth added in v0.7.6

func (c *Client) StartBrowserAuth(ctx context.Context) (*BrowserAuthFlow, error)

StartBrowserAuth begins the loopback authorization-code flow: it binds a local listener and returns a flow carrying the browser URL to open.

func (*Client) StartDeviceAuth

func (c *Client) StartDeviceAuth(ctx context.Context) (*DeviceAuthStart, error)

StartDeviceAuth requests a fresh device code.

type ControlPlaneTarget added in v0.7.6

type ControlPlaneTarget struct {
	CoreURL     string
	TokenSource func(context.Context) (string, error)
}

ControlPlaneTarget is the resolved login server a control-plane request (org/repo/project/grant) should dial, plus the bearer source for it.

CoreURL is an origin (no /api/v1 suffix); the caller appends the API base path. TokenSource returns a bearer valid for CoreURL, re-minting silently from the stored refresh token when the active context drives resolution.

func ResolveControlPlaneTarget added in v0.7.6

func ResolveControlPlaneTarget() (ControlPlaneTarget, error)

ResolveControlPlaneTarget chooses which core the control-plane commands talk to and how their bearer is obtained. The control-plane host *is* a core, so there is no /.well-known discovery here — the active context names the core, which is what makes `entire auth use <ctx>` retarget the control plane onto that login server. The bearer is a per-context refreshing provider (silent JWT re-mint from the stored refresh token).

No active context means not logged in: the error wraps ErrNotLoggedIn so callers render the `entire login` hint. There is no fallback host — a control-plane command without a login has no identity to act as.

func ResolveControlPlaneTargetForCluster added in v0.7.8

func ResolveControlPlaneTargetForCluster(ctx context.Context, clusterHost string) (ControlPlaneTarget, error)

ResolveControlPlaneTargetForCluster chooses which core a *resource-provider* control-plane command should dial — one whose subject is a mirror on a specific cluster (mirror create/remove, mirror collaborators list) rather than the caller's own account.

Unlike ResolveControlPlaneTarget, the core is NOT taken from the active context: a cluster's mirror lives in the federation that fronts that cluster, which may differ from the active login (e.g. a partial.to context acting on a prod entire.io cluster). We discover the cluster's trusted cores from its /.well-known/entire-cluster.json and pick the local context eligible for one of them — active-wins-if-eligible, else the sole eligible context, else an explicit-choice / login hint — exactly as git and data-API resolution do (see ResolveDataAPIToken). The bearer is that context's refreshing login provider (silent JWT re-mint from its stored refresh token).

With no eligible local context the discovery resolver returns its login hint naming the cluster's cores, so the user logs in to the right federation rather than seeing an opaque "unknown cluster_host" 400 from the active context's core.

type DeviceAuthPoll

type DeviceAuthPoll struct {
	AccessToken      string
	RefreshToken     string
	TokenType        string
	ExpiresIn        int
	Scope            string
	Error            string
	ErrorDescription string
}

DeviceAuthPoll is the historical token-poll response shape. The shim flattens deviceflow's typed errors back into the Error field so existing login.go logic that switches on result.Error keeps working.

ErrorDescription carries the optional `error_description` from the server's RFC 8628 §3.5 error response, when present. Used to give callers a more actionable message than the bare error code.

type DeviceAuthStart

type DeviceAuthStart = deviceflow.DeviceCode

DeviceAuthStart preserves the historical type name; the shape now matches deviceflow.DeviceCode field-for-field.

Jump to

Keyboard shortcuts

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