apigateway

package
v0.5.0 Latest Latest
Warning

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

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

Documentation

Overview

Package apigateway implements the authenticating reverse proxy that lets a sandboxed job reach configured HTTP APIs without ever holding the credential itself. See docs/plans/api-gateway.md for design background.

The package is self-contained: it does not import internal/dispatcher, internal/db, internal/api, internal/server, or internal/sandbox. Secret resolution and notification/recording are expressed as small function-typed seams (SecretResolver, UpstreamAuthFailureNotifier, RequestRecorder) that callers adapt to the real internal/dispatcher.SecretStore, internal/notify, and the task timeline.

Index

Constants

View Source
const DefaultDeviceSlowDownIncrement = 5 * time.Second

DefaultDeviceSlowDownIncrement is RFC 8628 §3.5's mandated backoff on a "slow_down" response: "the client MUST increase its polling interval by 5 seconds for each subsequent request". Overridable via LoginManager.SlowDownIncrement — tests only (mirroring OAuth2TokenSource.RefreshMargin's own override convention, so a slow_down test doesn't have to wait out a real 5-second backoff); production callers always get the spec value.

View Source
const DefaultOAuth2RefreshMargin = 5 * time.Minute

DefaultOAuth2RefreshMargin is how far before expires_at an OAuth2TokenSource proactively refreshes an access token, absent an explicit override. Comfortably covers the gateway's own request latency plus ordinary clock skew, while staying well inside every provider's shortest observed access-token lifetime (freee: 6h; Google/GitHub/Microsoft: ~1h).

View Source
const PathPrefix = "/api/"

PathPrefix is the fixed prefix every gateway route starts with: /api/<job-token>/<service>/<path...>.

Variables

ValidLoginFlows is the fixed set of Flow values internal/config's validateOAuthProviderConfig accepts — exported so that validation and login.go's own flow switch can never silently drift apart (a new LoginFlow constant added to one without the other would otherwise be a config-load acceptance / request-time-rejection mismatch, or vice versa).

ValidOAuthGrants is the fixed set of Grant values internal/config's validateOAuthProviderConfig accepts — exported for the exact same drift-prevention reason ValidLoginFlows exists (that constant's own doc comment): config-load acceptance and every runtime switch on Grant (only refresh's own branch today) must never silently diverge.

Functions

func GenerateToken

func GenerateToken() string

GenerateToken returns a random hex-encoded job token. Duplicated from internal/gitgateway.GenerateToken to keep this leaf package independent of it (see doc.go).

func OAuthSecretKey

func OAuthSecretKey(provider, field string) string

OAuthSecretKey returns the secret-store key an OAuth2TokenSource reads or writes for one (provider, field) pair. Exported so an operator's `boid secret set` invocation and this package's own tests share the exact same naming convention, rather than two independently-typed-out string literals silently drifting apart. The "oauth2:" prefix keeps this namespaced apart from any other secret-store key a service's static auth kinds (bearer/basic/header/query) might use in the same secret-store namespace.

func ValidateAccountName added in v0.4.0

func ValidateAccountName(account string) error

ValidateAccountName is validateAccountName's exported form, so that callers outside this package (e.g. `boid secret oauth login --account`) can gate an account name on the identical rule parsePath's splitServiceAccount enforces, rather than risk a login that creates a credential the gateway can never route a request to.

Like validateAccountName itself, this rejects "" — a caller for whom an empty string legitimately means "no account requested" must check account != "" itself before calling this.

func ValidateBaseURL added in v0.5.0

func ValidateBaseURL(serviceName, fieldName, rawURL string, allowInsecure bool) error

ValidateBaseURL validates that rawURL is safe to use as a service's outbound upstream address: an absolute URL with scheme and host, no query string or fragment, https unless allowInsecure is set, and only http/https schemes even then.

Shared by config.ValidateServiceURL (config-load time) and CredentialProvider.BaseURLFor (request time, for a secret-backed base_url); keep both call sites in sync if this changes.

Types

type AuthKind

type AuthKind string

AuthKind selects how the gateway injects credentials into a proxied request. bearer/basic/header/query are static SecretStore wrappers; oauth2 resolves its access token through an OAuth2AccessTokenSource instead of the static resolver — see CredentialProvider.SetOAuth2TokenSource.

const (
	AuthBearer AuthKind = "bearer"
	AuthBasic  AuthKind = "basic"
	AuthHeader AuthKind = "header"
	AuthQuery  AuthKind = "query"
	// AuthOAuth2 injects `Authorization: Bearer <access_token>`, where
	// access_token is supplied by the CredentialProvider's
	// OAuth2AccessTokenSource. A CredentialProvider on which
	// SetOAuth2TokenSource was never called has no TokenSource wired, and
	// Resolve/Inject both return a clear "no OAuth2 TokenSource configured"
	// error for it rather than panicking or silently no-op'ing — a service
	// misconfigured with kind: oauth2 in that state fails a request with a
	// 502 (see Server.ServeHTTP), not a build/startup error and not a
	// silent bypass.
	AuthOAuth2 AuthKind = "oauth2"
)

type CredentialProvider

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

CredentialProvider knows which services the gateway can reach (name → base_url + auth config) and how to resolve each one's secret. The static AuthKind variants resolve through resolver; oauth2 resolves through oauth (SetOAuth2TokenSource).

func NewCredentialProvider

func NewCredentialProvider(services []ServiceConfig, resolver SecretResolver) *CredentialProvider

NewCredentialProvider builds a CredentialProvider from the daemon's configured services and the resolver used to fetch each service's secret value. A service whose LITERAL base_url fails to parse, or parses without both a scheme and a host, is skipped with a warning rather than aborting construction — config.yaml validation (internal/config) is expected to have already rejected this at load time, so reaching this point is defensive-only. This "already validated by config load" invariant does NOT extend to a BaseURLSecretKey-backed service: that service's real base_url string does not exist yet at config-load time (it lives in the secret store, account-qualified), so such a service is always admitted into the map in secret-backed mode, and BaseURLFor validates the resolved value at request time instead.

func (*CredentialProvider) AllowsReadOnlyWrite added in v0.3.6

func (c *CredentialProvider) AllowsReadOnlyWrite(name string) bool

AllowsReadOnlyWrite reports whether name's ServiceConfig opted into the read-only-write escape hatch (ServiceConfig.AllowReadOnlyWrite's own doc comment). An unknown service (or a nil CredentialProvider) reports false — fail-closed, matching KnowsService/BaseURLFor's own posture for an unknown name.

func (*CredentialProvider) BaseURLFor

func (c *CredentialProvider) BaseURLFor(namespace, name, account string) (*url.URL, error)

BaseURLFor returns the upstream base URL for (name, account). For a LITERAL base_url service this is the pre-parsed value from NewCredentialProvider — a zero-cost lookup, no resolver call. For a BaseURLSecretKey-backed service it resolves "<key>@<account>" (or the bare key when account is empty) from the secret store, scoped to namespace, and validates the result with the same rules config.ValidateServiceURL enforces at config-load time for a literal base_url (ValidateBaseURL — the shared implementation both call): an absolute URL, no query/fragment, https unless the service's AllowInsecure opted out. namespace/account are therefore ignored entirely for a literal-base_url service.

Returns an error — never a bare ok=false — because a secret-backed resolution has real failure modes (missing secret, malformed URL value) that deserve a specific message, the same shape Resolve/Inject already use for credential resolution. Server.ServeHTTP logs the full error server-side but must never echo it (or the resolved URL) to the sandbox — see that call site's own comment.

func (*CredentialProvider) Configured

func (c *CredentialProvider) Configured() bool

Configured reports whether c has any secret resolver wired at all — distinguishing a systemic "no secret store configured" state (every request would fail identically) from an ordinary per-key miss on an otherwise-healthy store. Mirrors internal/gitgateway.CredentialProvider.Configured.

func (*CredentialProvider) Inject

func (c *CredentialProvider) Inject(req *http.Request, namespace, name, account string) error

Inject resolves name/account's configured secret — scoped to namespace — and applies it to req according to the service's AuthKind. It returns an error (and leaves req unmodified) on any failure: unknown service, no resolver configured, a secret-store lookup error, or the reserved oauth2 kind. Inject re-resolves the secret rather than reusing a prior Resolve call's result — Server.ServeHTTP's Resolve pre-check and this Inject call are two independent SecretStore reads, cheap in the common case.

account behaves exactly as documented on Resolve — same accountSecretKey composition for the static kinds, same credentialID composition for oauth2. namespace is the first parameter for the same reason documented on Resolve.

func (*CredentialProvider) KnowsService

func (c *CredentialProvider) KnowsService(name string) bool

KnowsService reports whether c has a ServiceConfig entry for name — i.e. whether name is in the gateway's configured service registry. A nil CredentialProvider knows no services (fail-closed).

func (*CredentialProvider) OAuth2ProviderFor

func (c *CredentialProvider) OAuth2ProviderFor(service string) (provider string, ok bool)

OAuth2ProviderFor resolves service to the oauth_providers.<name> its auth.kind: oauth2 config references — `boid secret oauth login <service>` needs this to hand LoginManager.StartLogin the provider name it actually operates on (login.go's own methods take a provider, never a service). ok is false when service is unknown OR is configured with any auth.kind OTHER than oauth2 — there is no OAuth2 grant to obtain for those.

func (*CredentialProvider) RequiresAccount added in v0.4.0

func (c *CredentialProvider) RequiresAccount(name string) bool

RequiresAccount reports whether name's ServiceConfig opted into rejecting account-less requests (ServiceConfig.RequireAccount's own doc comment). An unknown service (or a nil CredentialProvider) reports false.

Unlike AllowsReadOnlyWrite, false here is not a fail-closed default but a deliberate choice to defer to BaseURLFor's diagnosis: a name can clear the workspace authorization check yet still be absent from c.services (the workspace's enabled-services list and config.yaml's services: map can drift). For such a name, BaseURLFor already returns "service %q is not configured" and Server.ServeHTTP reports that 502 — reporting 400 "account required" instead, before that check runs, would be misleading. RequiresAccount only ever has an opinion once a service definitely exists.

func (*CredentialProvider) Resolve

func (c *CredentialProvider) Resolve(namespace, name, account string) error

Resolve validates that credential injection for name/account would succeed — without mutating any request — resolving the underlying secret (for the static kinds) so a bad/missing secret-store entry surfaces here rather than only once Inject is called on a live outbound request. This is the "pre-check" half of a fail-fast pattern: Server.ServeHTTP calls Resolve before proxying so it can 502 without ever contacting the upstream when credentials fail to resolve.

account is the optional credential-account qualifier. For the static kinds it composes the secret-store key (accountSecretKey): there is no fallback to the account-less key when the qualified one is missing, so a non-empty account whose secret was never set fails here exactly like any other missing secret. For oauth2 it is folded into a credentialID and handed to c.oauth.AccessToken, which applies the identical no-fallback contract.

namespace is deliberately the FIRST parameter, not adjacent to the other two string args: with three plain strings in a row, a call site that accidentally writes them in the wrong order still compiles, and workspace-scoped credential isolation depends on namespace never being mixed up with account or name (a wrong namespace resolves a DIFFERENT workspace's secret). This also matches this package's own SecretResolver convention (namespace, key).

func (*CredentialProvider) SetOAuth2TokenSource

func (c *CredentialProvider) SetOAuth2TokenSource(oauth OAuth2AccessTokenSource)

SetOAuth2TokenSource wires the OAuth2 access-token supplier oauth2-kind services resolve through. A CredentialProvider on which this is never called has oauth == nil: Resolve/Inject still always return a non-nil error for oauth2 in that state, never silently bypass or panic on a nil deref. A separate setter (rather than a NewCredentialProvider parameter) avoids touching every existing call site.

type Entry

type Entry struct {
	Token     string
	Namespace string
	TaskID    string
	ReadOnly  bool
	Services  map[string]bool
}

Entry is one job token's authorization: the set of logical service names it may reach, whether it is restricted to safe (GET/HEAD) methods, plus the secret-store namespace and originating task id used downstream (credential resolution and timeline/audit recording, respectively).

Services holds the effective enabled-service set for the registering job's workspace — the caller (dispatcher) computes this before calling Register; Registry itself has no notion of a floor or a workspace.

ReadOnly mirrors task.readonly / command.readonly — Server.ServeHTTP rejects any non-GET/HEAD request when this is true, regardless of which service is targeted.

TaskID is the originating task, used only for timeline/audit recording — empty for a taskless job (`boid exec`), in which case recording is skipped rather than attributed to no task.

type LoginFlow

type LoginFlow string

LoginFlow selects which of the three RFC-defined initial-grant flows a provider uses for `boid secret oauth login <service>`.

const (
	// LoginFlowDevice is RFC 8628's device authorization grant: no browser
	// redirect at all, the CLI displays a short user_code + verification
	// URI and the daemon polls DeviceAuthorizationEndpoint/TokenEndpoint in
	// the background until the user completes the grant elsewhere
	// (Microsoft/GitHub use this flow).
	LoginFlowDevice LoginFlow = "device"
	// LoginFlowLoopback is RFC 6749's authorization code grant with RFC
	// 7636 PKCE, using an RFC 8252 §7.3 loopback redirect_uri the CLI binds
	// dynamically (Google/Atlassian use this flow).
	LoginFlowLoopback LoginFlow = "loopback"
	// LoginFlowManual is RFC 6749's authorization code grant via the
	// urn:ietf:wg:oauth:2.0:oob redirect URI — the provider displays the
	// code directly in the browser instead of redirecting anywhere, and
	// the user pastes it into the CLI by hand. No PKCE (freee, a PKCE-less
	// provider, is this flow's motivating case) — ClientSecretKey, not a
	// code_verifier, is what keeps the code alone unusable off the daemon
	// for this flow.
	LoginFlowManual LoginFlow = "manual"
)

type LoginManager

type LoginManager struct {

	// HTTPClient defaults to tokens.httpClient() (same anti-redirect
	// hardening — see OAuth2TokenSource.HTTPClient's own doc comment) when
	// nil; overridable by tests independently of tokens' own client.
	HTTPClient *http.Client
	// Now defaults to tokens.now() when nil.
	Now func() time.Time
	// SlowDownIncrement overrides DefaultDeviceSlowDownIncrement — see that
	// constant's own doc comment. Zero means "use the default".
	SlowDownIncrement time.Duration
	// contains filtered or unexported fields
}

LoginManager orchestrates the pending-login-session lifecycle for `boid secret oauth login <service>`, reusing tokens (the daemon's single OAuth2TokenSource) for provider lookup and — critically — the exact same persistGrant persistence-order guarantee every refresh already relies on, so a login-obtained grant and a refresh-rotated one are indistinguishable to every downstream reader.

func NewLoginManager

func NewLoginManager(tokens *OAuth2TokenSource) *LoginManager

NewLoginManager builds a LoginManager sharing tokens' provider registry, secret resolver/writer, and persistGrant. tokens must not be nil.

func (*LoginManager) CompleteLogin

func (m *LoginManager) CompleteLogin(sessionID, code, state string) error

CompleteLogin finishes a loopback or manual pendingLogin: exchanges code (RFC 6749 §4.1.3 authorization_code grant) for tokens and persists the grant through tokens.persistGrant — the SAME durable-write-ordering contract a refresh gets. state is required (and checked, against CSRF) for loopback; ignored for manual, which never had one to check (no redirect occurs for OOB — see startManual).

A session is single-shot: once it leaves LoginStatusPending (success OR failure), every subsequent CompleteLogin call for the same sessionID is rejected outright rather than retried — RFC 6749 §4.1.2 authorization codes are single-use, so a failed exchange attempt has, in general, already burned the code upstream (whether the provider actually invalidated it or not is provider-specific and not worth guessing at); the correct recovery is always a fresh `boid secret oauth login`, not a retry against the same session.

func (*LoginManager) KnowsProvider added in v0.2.1

func (m *LoginManager) KnowsProvider(name string) bool

KnowsProvider reports whether name is a configured oauth_providers.<name> entry. Exported for internal/api's Start handler, which accepts a provider name as an alternative to a service name (see its own doc comment) and needs to tell "names a provider" apart from "names nothing at all" BEFORE calling StartLogin — an unknown name must 404, not begin a login that fails later.

func (*LoginManager) StartLogin

func (m *LoginManager) StartLogin(namespace, provider, redirectURI, account string) (*LoginStart, error)

StartLogin begins a new login session for (namespace, provider) using whichever LoginFlow that provider's config.yaml oauth_providers entry declares. redirectURI is the CLI's freshly-opened RFC 8252 §7.3 loopback listener's callback URL — always supplied by the CLI regardless of which flow it turns out to be (cheap to open a local port; StartLogin simply ignores it for device/manual) so a single request/response round trip suffices for every flow (no second "now tell me your redirect_uri" hop).

account is the optional credential-account qualifier `boid secret oauth login --account` supplies — "" (the overwhelmingly common case) means this login targets the unqualified credential. A non-empty account is validated against EXACTLY the rule parsePath's splitServiceAccount enforces on an inbound gateway request's "<service>@<account>" segment — reusing validateAccountName directly (cmd/secret_oauth.go, a different package, goes through this package's exported ValidateAccountName instead) rather than re-implementing the character-class check a second time. This is deliberate: a login this function accepted with an account name the gateway would reject as malformed would durably persist a credential under a secret-store key that no gateway request could ever be routed to — a permanently unreachable "successful" login.

func (*LoginManager) Status

func (m *LoginManager) Status(sessionID string) (status LoginStatus, errMsg string, ok bool)

Status returns the current lifecycle state of sessionID, for the CLI's device-flow poll (loopback/manual complete synchronously via CompleteLogin's own return value and rarely need this, but it works for them too). ok is false when sessionID is unknown — never registered, or already reaped (this package does not currently reap completed sessions itself; they simply live until process restart, which is an acceptable bound for a single-user personal daemon's in-memory session count).

type LoginStart

type LoginStart struct {
	SessionID string
	Flow      LoginFlow

	// Account echoes back the account StartLogin was actually called with —
	// "" for an ordinary unqualified login. This exists SOLELY so a caller
	// across a version-skew boundary (an older daemon build that does not
	// know about --account at all) can detect that mismatch: an old
	// daemon's StartLogin always returns "" here regardless of what the CLI
	// asked for — see cmd/secret_oauth.go's own post-Start comparison for
	// why silently proceeding on that mismatch is dangerous (a login the
	// CLI believes is account-qualified would actually overwrite the
	// unqualified credential).
	Account string

	// loopback/manual only.
	AuthorizeURL string

	// device only.
	UserCode                string
	VerificationURI         string
	VerificationURIComplete string
	IntervalSeconds         int
	ExpiresInSeconds        int
}

LoginStart is StartLogin's result — everything the CLI needs to carry out its half of whichever flow the provider is configured for.

type LoginStatus

type LoginStatus string

LoginStatus is the lifecycle state of one pendingLogin, exposed to the CLI via LoginManager.Status.

const (
	LoginStatusPending  LoginStatus = "pending"
	LoginStatusComplete LoginStatus = "complete"
	LoginStatusFailed   LoginStatus = "failed"
	LoginStatusExpired  LoginStatus = "expired"
)

type NotifierFuncs

type NotifierFuncs struct {
	UpstreamAuthFailure func(service string)
	CredentialError     func(service string, err error)
}

NotifierFuncs adapts plain functions to UpstreamAuthFailureNotifier. Either field may be left nil, in which case the corresponding notification is a no-op.

func (NotifierFuncs) NotifyCredentialError

func (f NotifierFuncs) NotifyCredentialError(service string, err error)

NotifyCredentialError implements UpstreamAuthFailureNotifier.

func (NotifierFuncs) NotifyUpstreamAuthFailure

func (f NotifierFuncs) NotifyUpstreamAuthFailure(service string)

NotifyUpstreamAuthFailure implements UpstreamAuthFailureNotifier.

type OAuth2AccessTokenSource

type OAuth2AccessTokenSource interface {
	AccessToken(namespace string, cred credentialID) (string, error)
}

OAuth2AccessTokenSource resolves a currently-valid access token for a (namespace, credentialID) pair, refreshing it first if needed. Implemented by *OAuth2TokenSource; CredentialProvider depends on this narrow interface — not the concrete type — so CredentialProvider's own tests can substitute a fake without exercising a real token endpoint (see CredentialProvider.SetOAuth2TokenSource).

type OAuth2TokenSource

type OAuth2TokenSource struct {

	// RefreshMargin/Now/HTTPClient are exported so tests can override them
	// on an otherwise-normally-constructed *OAuth2TokenSource, rather than a
	// parallel constructor-with-options surface — mirrors this package's
	// existing preference for plain constructors (NewCredentialProvider,
	// NewServer) over an options struct. NewOAuth2TokenSource sets
	// production-sane defaults for all three; nothing outside this
	// package's own tests needs to touch them.
	RefreshMargin time.Duration
	Now           func() time.Time
	HTTPClient    *http.Client
	// contains filtered or unexported fields
}

OAuth2TokenSource is the daemon's single OAuth2 refresher: every oauth2-kind service's Resolve/Inject call funnels through the one instance internal/server/wire.go constructs, so two sandboxed jobs — or two concurrent requests from the same job — hitting the same (namespace, provider) grant at once are coalesced into a single token-endpoint round trip (singleflightGroup) rather than racing two independent refreshes: exactly the race a rotating-refresh-token provider (freee) cannot survive, since the loser's refresh_token has already been invalidated by the winner's token-endpoint call by the time it would try to use it.

func NewOAuth2TokenSource

func NewOAuth2TokenSource(providers []OAuthProviderConfig, resolver SecretResolver, writer SecretWriter) *OAuth2TokenSource

NewOAuth2TokenSource builds an OAuth2TokenSource from the daemon's configured OAuth2 providers and the resolver/writer pair used to read and persist each (namespace, provider)'s refresh_token/access_token/ expires_at secret-store state. resolver is also used to look up a provider's ClientSecretKey (when set) — the same resolver CredentialProvider itself uses for the static auth kinds' secrets.

func (*OAuth2TokenSource) AccessToken

func (t *OAuth2TokenSource) AccessToken(namespace string, cred credentialID) (string, error)

AccessToken returns a currently-valid access token for (namespace, provider), proactively refreshing it first when there is no cached access_token yet, the cached expires_at cannot be parsed, or the cached token is within RefreshMargin of expiring. "No cached access_token yet" is the expected starting state right after an operator seeds only a refresh_token via `boid secret set` — not an error.

Concurrent callers for the SAME (namespace, provider) that all decide a refresh is needed are coalesced into a single token-endpoint round trip via t.sf — see refresh's own doc comment for why only one of them actually performs it. The cache is re-checked a SECOND time once inside t.sf.Do, immediately before calling refresh: a caller can decide "needs refresh" from its OWN cache read, then stall (goroutine scheduling) long enough for a DIFFERENT caller's refresh for the same key to complete and release the singleflight slot entirely — singleflightGroup, like golang.org/x/sync/singleflight, only coalesces calls that overlap in time, never calls arriving strictly after a prior one already finished. Re-checking right before the network call closes that window down to the ordinary, industry-standard residual TOCTOU any check-then-act pattern has (not a new one this package introduces), and in particular avoids the double-refresh-within-one-request shape entirely for the common case: Resolve's own refresh already left a fresh entry in memCache by the time Inject's call reaches this same recheck.

type OAuthGrant added in v0.2.0

type OAuthGrant string

OAuthGrant selects which RFC 6749 grant OAuth2TokenSource.refresh performs for a provider. A separate axis from LoginFlow — see OAuthProviderConfig.Grant's own doc comment for why the two are never merged into one enum.

const (
	// GrantAuthorizationCode is the default — every 3-legged (delegated)
	// grant: refresh() sends grant_type=refresh_token against a
	// refresh_token obtained through one of LoginFlow's three
	// initial-authorization flows.
	GrantAuthorizationCode OAuthGrant = "authorization_code"
	// GrantClientCredentials is RFC 6749 §4.4's 2-legged / app-only grant
	// (Service Principal): refresh() sends grant_type=client_credentials
	// directly against TokenEndpoint with client_id + client_secret (a
	// confidential client is REQUIRED, RFC 6749 §4.4.2) + scope. No user
	// authorization step, no authorization code, no PKCE, no redirect_uri,
	// and — unlike every other grant this package performs — no
	// refresh_token in the response to persist.
	GrantClientCredentials OAuthGrant = "client_credentials"
)

type OAuthProviderConfig

type OAuthProviderConfig struct {
	// Name is the provider's config.yaml key (oauth_providers.<Name>) — the
	// same string a services.*.auth.provider entry references.
	Name string
	// TokenEndpoint is the provider's OAuth2 token endpoint (RFC 6749 §3.2),
	// e.g. https://accounts.secure.freee.co.jp/public_api/token.
	TokenEndpoint string
	// ClientID is the OAuth2 client_id. Not a secret by RFC 6749 §2.2's own
	// classification (a public identifier), so — unlike a secret_key — it
	// travels as a plain string rather than a secret-store reference.
	ClientID string
	// ClientSecretKey is a secret-store key reference (never a plaintext
	// value) for a confidential client's client_secret. Empty for a public
	// client (PKCE, no client_secret) — callRefreshTokenEndpoint simply
	// omits client_secret from the token request when this resolves to "".
	ClientSecretKey string
	// Scopes is consumed by login.go's authorization-URL construction
	// (loopback/manual flows) and device-authorization request (device
	// flow). Never consumed by this file's refresh_token grant — see
	// callRefreshTokenEndpoint's own doc comment for why.
	Scopes []string

	// Flow selects which of the three RFC-defined initial-grant flows
	// `boid secret oauth login <service>` uses for this provider:
	// LoginFlowDevice (RFC 8628 device authorization grant),
	// LoginFlowLoopback (RFC 6749 authorization code grant + PKCE, RFC
	// 8252 loopback redirect), or LoginFlowManual (authorization code
	// grant via the OOB urn:ietf:wg:oauth:2.0:oob redirect URI, no PKCE —
	// freee's shape). Empty ("") means this provider has no login flow
	// configured at all — AccessToken's refresh_token grant (this file)
	// works regardless (an operator can always seed refresh_token via
	// `boid secret set`), but login.go's LoginManager.StartLogin rejects
	// it with a clear "no flow configured" error rather than guessing.
	//
	// MUST be empty when Grant is GrantClientCredentials — client_credentials
	// has no login flow at all (no user authorization step exists to
	// select a flow for). internal/config.validateOAuthProviderConfig
	// rejects a config.yaml entry that sets both at load time; StartLogin
	// below also defensively rejects it at request time.
	Flow LoginFlow

	// Grant selects which RFC 6749 grant refresh() (this file) performs for
	// this provider: GrantAuthorizationCode (the default: a refresh_token
	// grant, that refresh_token itself obtained via one of Flow's three
	// initial flows) or GrantClientCredentials (RFC 6749 §4.4, "2-legged" /
	// app-only — no user authorization step, no refresh_token concept at
	// all). Deliberately a SEPARATE axis from Flow, not a fourth Flow
	// value — see ValidOAuthGrants' own doc comment for why conflating
	// them would break the "config load acceptance and StartLogin's switch
	// can never silently drift apart" invariant ValidLoginFlows exists to
	// protect. Empty ("") means GrantAuthorizationCode, so an existing
	// config.yaml keeps loading unmodified.
	Grant OAuthGrant

	// AuthorizationEndpoint is the provider's OAuth2 authorization endpoint
	// (RFC 6749 §3.1) — required (and only meaningful) when Flow is
	// LoginFlowLoopback or LoginFlowManual.
	AuthorizationEndpoint string

	// DeviceAuthorizationEndpoint is the provider's RFC 8628 §3.1 device
	// authorization endpoint — required (and only meaningful) when Flow is
	// LoginFlowDevice.
	DeviceAuthorizationEndpoint string

	// AuthorizeParams is a fixed set of extra parameters appended verbatim
	// to the authorization request (loopback/manual: query parameters on
	// AuthorizationEndpoint; device: form fields on
	// DeviceAuthorizationEndpoint) — an escape hatch for provider-specific
	// extensions RFC 6749/8628 don't standardize but real providers need,
	// e.g. Google's `access_type=offline`/`prompt=consent` (without which
	// Google does not reissue a refresh_token on a repeat login once the
	// user has already granted consent once). Deliberately a per-provider
	// config map rather than hardcoded Google-specific behavior in this
	// leaf package, matching this config's existing declarative style.
	// internal/config.validateOAuthProviderConfig
	// rejects any key here that collides with a protocol-reserved
	// parameter (client_id, redirect_uri, response_type, scope, state,
	// code_challenge, code_challenge_method, device_code, grant_type) —
	// this package's own login.go trusts that check and never re-validates
	// it at request time.
	AuthorizeParams map[string]string
}

OAuthProviderConfig is the resolved shape of one config.yaml oauth_providers.<name> entry (internal/config.OAuthProviderConfig, which this package deliberately does not import — see doc.go) — the token-endpoint identity an OAuth2TokenSource needs to perform a refresh_token grant for that provider.

type RedirectPolicy added in v0.5.0

type RedirectPolicy struct {
	AllowedHosts []string `yaml:"allowed_hosts,omitempty"`
}

RedirectPolicy opts one service into credential-free GET/HEAD redirects. Empty AllowedHosts preserves the upstream redirect response unchanged.

func (RedirectPolicy) Validate added in v0.5.0

func (p RedirectPolicy) Validate() error

Validate rejects ambiguous patterns: entries are DNS names or *.DNS names, never URLs, IP literals, ports, or unrestricted wildcards.

type Registry

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

Registry is the job-token → allowed-service-set store. A deliberately simple sync.RWMutex-guarded map, mirroring internal/gitgateway.Registry's own shape and lifecycle contract (dispatch-time Register, job-completion Unregister).

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty Registry.

func (*Registry) Authorize

func (r *Registry) Authorize(token, service string) (allowed, tokenValid bool)

Authorize reports whether token may reach service. tokenValid is false when the token is unknown/expired (caller should respond 401); tokenValid is true but allowed is false when the token is valid but service isn't in its enabled set (caller should respond 403).

func (*Registry) Lookup

func (r *Registry) Lookup(token string) (Entry, bool)

Lookup returns the entry for token, if any. A nil Registry behaves as an always-empty one (every token reports invalid) rather than panicking, so a Server constructed without a registry fails closed with 401s instead of crashing.

func (*Registry) Register

func (r *Registry) Register(services []string, namespace, taskID string, readOnly bool) string

Register creates a new entry with a freshly generated token, scoped to namespace and taskID, and returns the token.

func (*Registry) RegisterToken

func (r *Registry) RegisterToken(token string, services []string, namespace, taskID string, readOnly bool) string

RegisterToken creates (or replaces) an entry under an explicit token. This is useful for callers (and tests) that already have a token value to correlate with.

func (*Registry) Unregister

func (r *Registry) Unregister(token string)

Unregister revokes a token. A subsequent Lookup/Authorize for it reports the token as invalid. Unregistering an unknown token is a no-op.

type RequestRecorder

type RequestRecorder func(taskID, method, service, path string, status int)

RequestRecorder is called once per request the gateway authorizes far enough to know which service/path it targets — i.e. every request past a well-formed-route 404, whether it ultimately succeeds, is rejected (401/403/502/503), or fails upstream. Deliberately narrow: no headers, no query string, no request/response body, ever.

taskID is the originating task (Registry Entry.TaskID); empty for a taskless job, in which case a real recorder is expected to skip recording rather than attribute the request to no task (there is nothing in a task timeline to attach it to).

type SecretResolver

type SecretResolver func(namespace, key string) (string, error)

SecretResolver resolves a secret-store key reference, scoped to a namespace, to its plaintext value — the same shape as internal/gitgateway.SecretResolver (see that type's own doc comment for why this is a plain function type rather than an internal/dispatcher import: it keeps this package free of the sqlite-backed internal/db build). An empty namespace is expected to fall back to a "default" namespace, mirroring internal/dispatcher.SecretStore.Get's own normalizeNamespace.

type SecretWriter

type SecretWriter func(namespace, key, value string) error

SecretWriter persists a plaintext secret-store value scoped to namespace — the write counterpart to SecretResolver. internal/server/wire.go adapts internal/dispatcher.SecretStore.Set to this exactly the way it already adapts SecretStore.Get to SecretResolver, keeping this leaf package free of any internal/dispatcher (and therefore internal/db) import — see SecretResolver's own doc comment for the identical rationale.

type Server

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

Server is the API gateway's HTTP handler: a thin net/http/httputil. ReverseProxy wrapper that does path-based authorization (Registry) and per-service credential injection (CredentialProvider) around the standard library's streaming transport.

func NewServer

func NewServer(registry *Registry, credentials *CredentialProvider, notifier UpstreamAuthFailureNotifier, recorder RequestRecorder) *Server

NewServer builds a Server. notifier may be nil (defaults to NoopNotifier); recorder may be nil (defaults to a no-op).

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP parses the request path, authorizes it against the registry, and — if allowed — rewrites it to the configured service's base URL and proxies it with credentials injected. Unrecognized paths get 404; a well-formed path whose account qualifier fails validation gets 400 (see errInvalidAccount's own doc comment for why this is the one parsePath failure that is NOT a 404); unknown/expired tokens get 401; well-formed-but-disallowed service requests get 403; an allowed service configured with require_account: true rejects an account-less request with 400; a read-only token attempting a non-GET/HEAD method gets 403; an unconfigured (or credential-broken) service gets 502/503.

type ServiceAuth

type ServiceAuth struct {
	Kind      AuthKind
	SecretKey string
	Username  string
	Header    string
	Query     string
	Provider  string
	// UsernameSecretKey, when non-empty (kind: basic only), resolves the
	// Basic-auth username from the secret store instead of using the
	// literal Username field — account-qualified via the same
	// accountSecretKey composition SecretKey already uses. Mutually
	// exclusive with Username; config.validateServiceConfig enforces that
	// at load time. Motivating case: a Jira-Cloud-shaped service where the
	// login email differs per tenant/account, not just the token.
	UsernameSecretKey string
}

ServiceAuth is the resolved (post config-validation) shape of one service's auth block. Which fields are meaningful depends on Kind:

  • bearer: SecretKey
  • basic: Username or UsernameSecretKey, SecretKey
  • header: Header, SecretKey
  • query: Query, SecretKey
  • oauth2: Provider (names a CredentialProvider's wired OAuth2AccessTokenSource provider entry; SecretKey/Username/Header/Query unused)

type ServiceConfig

type ServiceConfig struct {
	Redirects RedirectPolicy
	Name      string
	BaseURL   string
	Auth      ServiceAuth
	// BaseURLSecretKey, when non-empty, resolves BaseURL from the secret
	// store instead of using the literal BaseURL field — account-qualified
	// via the same accountSecretKey composition auth.SecretKey already
	// uses. Mutually exclusive with BaseURL; config.validateServiceConfig
	// enforces that at load time. Motivating case: Jira Cloud, where the
	// whole upstream tenant (subdomain) differs per account, not just the
	// credential.
	BaseURLSecretKey string
	// AllowInsecure mirrors config.ServiceConfig.AllowInsecure — needed
	// here because a BaseURLSecretKey-backed base_url can only be
	// validated (https-unless-allowed, absolute URL, no query/fragment) at
	// REQUEST time, once the secret store value is known, never at
	// config-load time the way a literal BaseURL is. Unused when
	// BaseURLSecretKey is empty — the literal BaseURL path was already
	// validated by config.validateServiceConfig before this ServiceConfig
	// was ever built.
	AllowInsecure bool
	// AllowReadOnlyWrite opts this ONE service out of the ordinary
	// read-only→GET/HEAD-only gate (Server.ServeHTTP, isSafeMethod):
	// readonly job tokens still can't touch the sandbox filesystem, but
	// some services (e.g. a Slack "post completion report" webhook) are
	// safe to let a read-only job POST to even though the job can't write
	// code. This is deliberately a daemon-config-only knob — never
	// project.yaml/task_behaviors — because granting it from inside the
	// repo would let a prompt-injected agent grant itself write access to
	// any service it can already reach. Defaults to false (fail-closed): a
	// service must be explicitly opted in by whoever controls config.yaml.
	AllowReadOnlyWrite bool
	// RequireAccount is this ServiceConfig's post-validation mirror of
	// config.ServiceConfig.RequireAccount (see that field's own doc comment
	// for the full rationale) — the same relationship AllowReadOnlyWrite
	// above already has to its own config counterpart.
	RequireAccount bool
}

ServiceConfig declares one logical service the gateway can proxy to: its upstream base URL and how to authenticate requests to it.

type UpstreamAuthFailureNotifier

type UpstreamAuthFailureNotifier interface {
	NotifyUpstreamAuthFailure(service string)
	NotifyCredentialError(service string, err error)
}

UpstreamAuthFailureNotifier is invoked on two distinct failure modes so an operator can tell them apart:

  • NotifyUpstreamAuthFailure: the upstream service responded with 401 to a request that WAS sent with injected credentials — the configured secret itself is wrong/expired/revoked ("rotate it with `boid secret set`").
  • NotifyCredentialError: credential injection itself failed before the request ever reached the upstream — an unconfigured service, a missing resolver, or a secret-store lookup error ("fix config.yaml / boid secret set").

The gateway always logs a warning on either condition and additionally calls the matching hook, but never aborts serving other requests because of it.

NoopNotifier discards notifications. It is the default when a Server is constructed with a nil notifier.

Jump to

Keyboard shortcuts

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