apigateway

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package apigateway implements the authenticating reverse proxy that lets a sandboxed job reach arbitrary configured HTTP APIs without ever holding the credential itself — the generalization of internal/gitgateway from git smart HTTP alone to any HTTP API, per docs/plans/api-gateway.md ("汎用 API gateway (認証注入リバースプロキシ) + OAuth2 対応 計画").

PR1 added static credential injection (bearer / basic / header / query auth kinds). PR2 (this state) adds the oauth2 AuthKind's actual TokenSource (oauth2.go, OAuth2TokenSource): a daemon-single-refresher, proactively-refreshing (margin-before-expiry), singleflight-coalesced access-token supplier, wired into a CredentialProvider via SetOAuth2TokenSource. PR3 adds the `boid secret oauth login` flow that performs the initial grant; PR2's own dogfood path is a manually `boid secret set` refresh_token.

Like internal/gitgateway, this package is self-contained: it does not import internal/dispatcher, internal/db, internal/api, internal/server, or internal/sandbox, so it (and a sandbox test run, which cannot build the sqlite-backed internal/db layers) can build and test on its own. Secret resolution and notification/recording are expressed as small function-typed seams (SecretResolver, UpstreamAuthFailureNotifier, RequestRecorder) that internal/server/internal/dispatcher 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 (docs/plans/api-gateway.md §6: "expires_at より margin 手前で更新"). 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...> — docs/plans/api-gateway.md §1 ("ルーティングと sandbox からの見え方"). Mirrors gitgateway.PathPrefix's role for the sibling git gateway, using a distinct prefix so both gateways can share a single listener, dispatching on this prefix (docs/plans/api-gateway.md 論点1: "同居 (path prefix /j/ と /api/ で分岐)").

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, using the same crypto/rand + 16-byte scheme as internal/gitgateway.GenerateToken (and, beneath that, internal/sandbox's broker token registry). Duplicated rather than imported: apigateway is a leaf package, kept independent of internal/gitgateway on purpose so neither gateway package's tests (in particular a sandbox test run, which cannot build the sqlite-backed internal/db layers either package might otherwise be one import hop from) depend on the other's presence.

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 (docs/plans/api-gateway.md PR2 scope note: "初回 grant は当面 boid secret set で refresh_token を手動投入して動作確認でき る形にする") 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.

Types

type AuthKind

type AuthKind string

AuthKind selects how the gateway injects credentials into a proxied request. docs/plans/api-gateway.md §4 ("credential 注入: CredentialProvider → TokenSource 一般化"): bearer/basic/header/query are static SecretStore wrappers implemented in PR1; oauth2 (PR2) resolves its access token through an OAuth2AccessTokenSource (oauth2.go) 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 (docs/plans/api-gateway.md §6/PR2). A
	// CredentialProvider constructed without SetOAuth2TokenSource ever
	// being called (every call site before PR2, and any test that doesn't
	// opt in) 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. Mirrors internal/gitgateway.CredentialProvider's role, generalized from a single Basic-auth shape to the four static AuthKind variants plus oauth2 (docs/plans/api-gateway.md §4/§6, PR2) — the static kinds 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 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, matching internal/config.GatewayConfig.HostConfigs's own "already validated" invariant note.

func (*CredentialProvider) BaseURLFor

func (c *CredentialProvider) BaseURLFor(name string) (u *url.URL, ok bool)

BaseURLFor returns the parsed upstream base URL for name, or ok=false when name is unknown (or c is nil).

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, name, namespace string) error

Inject resolves name'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 — see internal/gitgateway.CredentialProvider.Inject's own doc comment for why this thin-wrapper-over-Resolve shape is deliberate (Server.ServeHTTP's Resolve pre-check and this Inject call are two independent SecretStore reads, cheap in the common case).

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 — the service->provider lookup `boid secret oauth login <service>` (PR3, docs/plans/api-gateway.md §7) needs to hand LoginManager.StartLogin the provider name it actually operates on (login.go's own methods take a provider, never a service — see LoginManager's own doc comment). ok is false when service is unknown OR is configured with any auth.kind OTHER than oauth2 — `boid secret oauth login` has nothing useful to do for a bearer/basic/header/query service (there is no OAuth2 grant to obtain).

func (*CredentialProvider) Resolve

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

Resolve validates that credential injection for name 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 the fail-fast pattern docs/plans/gitgateway-credential-fail-fast.md established for the sibling git gateway: Server.ServeHTTP calls Resolve before proxying so it can 502 without ever contacting the upstream when credentials fail to resolve.

func (*CredentialProvider) SetOAuth2TokenSource

func (c *CredentialProvider) SetOAuth2TokenSource(oauth OAuth2AccessTokenSource)

SetOAuth2TokenSource wires the OAuth2 access-token supplier oauth2-kind services resolve through (docs/plans/api-gateway.md §6, PR2). A CredentialProvider built via NewCredentialProvider alone — every call site before this PR, and any test that doesn't opt in — has oauth == nil, which keeps the pre-PR2 CONTRACT (not the exact error text — that changed to name SetOAuth2TokenSource explicitly): 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 new NewCredentialProvider parameter) avoids touching every existing call site: production wiring (internal/server/wire.go) calls this once, right after construction, and every apigateway/server test that doesn't care about oauth2 is unaffected.

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 (floor ∪ workspace) enabled-service set for the registering job's workspace (docs/plans/api-gateway.md §3 "workspace 単位の service 有効化") — the caller (dispatcher) computes this union before calling Register; Registry itself has no notion of a floor or a workspace.

ReadOnly mirrors task.readonly / command.readonly (docs/plans/api-gateway.md 前提となる決定事項: "task.readonly を HTTP メソッドに写像する") — 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 (docs/plans/api-gateway.md §論点3) — 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 docs/plans/api-gateway.md §7 describes a provider uses for `boid secret oauth login <service>` (PR3).

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
	// (docs/plans/api-gateway.md §7 flow table: Microsoft/GitHub).
	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 (docs/plans/api-gateway.md §7 flow table: Google/
	// Atlassian).
	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 (docs/plans/
	// api-gateway.md §7: "PKCE 非対応プロバイダ (freee) では...confidential
	// client の client_secret を daemon 側にのみ置くことで同等の性質を担保
	// する" — 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>` (docs/plans/api-gateway.md §7, PR3), 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) for loopback (docs/plans/api-gateway.md §7: "state 検証は daemon 側の pending login session と突き合わせる (CSRF 対策)"); 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 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).

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

	// 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, provider string) (string, error)
}

OAuth2AccessTokenSource resolves a currently-valid access token for a (namespace, provider) 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 (docs/plans/ api-gateway.md §6 "daemon 単一リフレッシャの原則"): 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, provider string) (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 (docs/plans/api-gateway.md §6 "先回りリフレッシュ"). "No cached access_token yet" is the expected PR2 dogfood starting state right after an operator seeds only a refresh_token via `boid secret set` (docs/plans/api-gateway.md PR分割 PR2) — 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 (codex review round 2, Major finding): 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 (docs/plans/api-gateway.md §6-補). 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 this package supported before §6-補: 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 (docs/plans/api-gateway.md
	// §6-補: "refresh_token という概念が無い").
	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 (docs/plans/
	// api-gateway.md §7: "confidential client の client_secret を daemon 側
	// にのみ置く"). 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) — docs/plans/api-gateway.md §7 "flow の三段構え", PR3. 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
	// (docs/plans/api-gateway.md §7 "flow の三段構え", PR3) `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`, PR2's
	// own documented fallback), 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
	// (§6-補) 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 — every flow this
	// file supported before §6-補: 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; see docs/plans/
	// api-gateway.md §6-補). 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, for the same "an existing PR2/PR3 config.yaml
	// must keep loading unmodified" reason Flow's own zero value does.
	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 — docs/plans/api-gateway.md's
	// own "Google の device flow は認可可能な scope がかなり絞られている"
	// note is the same class of Google-specific quirk). 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's "self-contained leaf package" rationale) — the token-endpoint identity an OAuth2TokenSource needs to perform a refresh_token grant for that provider (docs/plans/api-gateway.md §論点4/§6: "config.yaml の oauth_providers: ブロック。client_secret のみ SecretStore 参照").

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. docs/plans/api-gateway.md §論点3 ("確定: method + service + path + status を timeline に。body は記録しない") — 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 — the same shape as internal/gitgateway.Server, generalized from git smart HTTP to arbitrary HTTP APIs (docs/plans/api-gateway.md PR1).

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; unknown/expired tokens get 401; well-formed-but-disallowed service requests get 403; 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
}

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, 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 {
	Name    string
	BaseURL string
	Auth    ServiceAuth
}

ServiceConfig declares one logical service the gateway can proxy to: its upstream base URL and how to authenticate requests to it. docs/plans/api-gateway.md §2 ("service registry (config.yaml)").

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 — mirrors internal/gitgateway.UpstreamAuthFailureNotifier's rationale exactly (docs/plans/api-gateway.md §5 "upstream 401 の notify"):

  • 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