Documentation
¶
Index ¶
- Constants
- Variables
- func Contexts() ([]*contexts.Context, string, error)
- func CoreURLFromEnvToken(rawToken string) (string, error)
- func EnableInsecureHTTP()
- func LoginTokenForContext(c *contexts.Context) (string, error)
- func NewRefreshingLoginProvider(c *contexts.Context, transport http.RoundTripper, allowInsecureHTTP bool) (func(context.Context) (string, error), error)
- func NewRefreshingResourceProvider(c *contexts.Context, resourceOrigin string, transport http.RoundTripper, ...) (func(context.Context) (string, error), error)
- func RecordLoginContext(rawToken, refreshToken string, activate bool) (string, error)
- func RefreshedLoginToken(ctx context.Context, c *contexts.Context) (string, error)
- func RemoveContext(name string) error
- func RemoveCurrentContext() error
- func RepoScopedToken(ctx context.Context, clusterHost, repoSlug, action string) (string, error)
- func ResolveDataAPIToken(ctx context.Context, dataBaseURL string) (string, error)
- func SetCurrentContext(name string) error
- func SetRepoExchangeTransportForTest(rt http.RoundTripper) func()
- func SetResolveContextForAPIForTest(t interface{ ... }, fn resolveContextFunc) func()
- type BrowserAuthFlow
- type Client
- type ControlPlaneTarget
- type DeviceAuthPoll
- type DeviceAuthStart
- type RepoTokenSource
Constants ¶
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`.
Variables ¶
var ErrNotLoggedIn = tokenmanager.ErrNotLoggedIn
ErrNotLoggedIn re-exports tokenmanager.ErrNotLoggedIn so callers in the cli package can errors.Is against it without an extra import.
var ErrRepoTargetUnknown = errors.New("cluster has no servable mirror at this audience")
ErrRepoTargetUnknown reports that the cluster's STS refused the exchange with RFC 8693 `invalid_target`: it has no servable mirror at the requested audience. The placement row may well exist but be suspended — the data plane's auth gate deliberately hides suspended mirrors behind invalid_target rather than disclosing their state (an enumeration guard; see entiredb's validateMirrorRepoExchange). Callers that already know the mirror exists (e.g. the create flow's clone probe) use this to render an actionable message instead of the raw OAuth error.
Functions ¶
func Contexts ¶ added in v0.7.0
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
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 LoginTokenForContext ¶ added in v0.7.0
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 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 RecordLoginContext ¶ added in v0.7.0
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
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
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 RepoScopedToken ¶ added in v0.7.0
RepoScopedToken is the one-shot form of RepoTokenSource: resolve, mint once, discard. Callers that re-mint (e.g. a polling wait) should hold a RepoTokenSource instead, so re-mints skip cluster discovery.
func ResolveDataAPIToken ¶ added in v0.7.6
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 SetCurrentContext ¶ added in v0.7.0
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 SetRepoExchangeTransportForTest ¶ added in v0.7.0
func SetRepoExchangeTransportForTest(rt http.RoundTripper) func()
SetRepoExchangeTransportForTest installs rt as the transport used by RepoScopedToken and returns a cleanup function. Test-only.
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.
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.
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 ¶
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) PollDeviceAuth ¶
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
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.
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.
type RepoTokenSource ¶ added in v0.7.6
type RepoTokenSource struct {
// contains filtered or unexported fields
}
RepoTokenSource mints short-lived, repo-scoped access tokens usable against one data-plane cluster's git endpoints (clone / fetch / info-refs). The data plane's git gate rejects the raw login bearer: it only accepts a token whose RFC 8693 audience is https://<clusterHost><repoSlug> and whose scope is "repo:<action>".
The login context is resolved once, at construction, the way git-remote-entire resolves it: the cluster's /.well-known/entire-cluster.json names the core(s) it trusts, and the matching local context (active if eligible, else the sole eligible one, else an explicit-choice error) supplies the subject token — exchanged at that context's core, never at the active context's. Token calls then only exchange (through repocreds, the same code path and wire form git-remote-entire uses), re-minting an expired login JWT from the stored refresh token as needed — so a poller's re-mints don't depend on discovery staying reachable.
func NewRepoTokenSource ¶ added in v0.7.6
func NewRepoTokenSource(ctx context.Context, clusterHost string) (*RepoTokenSource, error)
NewRepoTokenSource resolves clusterHost's trusted core and login context and returns a source minting tokens for that cluster.
func (*RepoTokenSource) Invalidate ¶ added in v0.7.6
func (s *RepoTokenSource) Invalidate(repoSlug, action string)
Invalidate drops the cached (repoSlug, action) token so the next Token call re-exchanges — for when the data plane rejected it (401) ahead of its recorded expiry.