Documentation
¶
Overview ¶
Package gitgateway implements the authenticating reverse proxy that sits between a sandbox's credential-less git and the real upstream forge (GitHub / Bitbucket).
The package purposefully avoids importing internal/dispatcher or internal/db so it can build and test standalone; secret resolution and notification are expressed as small function-typed seams (SecretResolver, UpstreamAuthFailureNotifier) that callers adapt to the real internal/dispatcher.SecretStore and internal/notify.
Index ¶
- Constants
- func GenerateToken() string
- func SandboxURL(opts SandboxURLOptions) string
- type Backend
- type CredentialProvider
- func (c *CredentialProvider) Configured() bool
- func (c *CredentialProvider) Inject(req *http.Request, host, namespace string) error
- func (c *CredentialProvider) KnowsHost(host string) bool
- func (c *CredentialProvider) Resolve(host, namespace string) (username, token string, err error)
- func (c *CredentialProvider) SchemeFor(host string) string
- type Entry
- type Forge
- type HostForgeConfig
- type NotifierFuncs
- type Operation
- type Permission
- type Registry
- func (r *Registry) Authorize(token string, repo RepoKey, op Operation) (allowed, tokenValid bool)
- func (r *Registry) Lookup(token string) (Entry, bool)
- func (r *Registry) Register(repos map[RepoKey]Permission, namespace string) string
- func (r *Registry) RegisterToken(token string, repos map[RepoKey]Permission, namespace string)
- func (r *Registry) Unregister(token string)
- type RepoKey
- type SandboxURLOptions
- type SecretResolver
- type Server
- type UpstreamAuthFailureNotifier
Constants ¶
const ( EndpointInfoRefs = "info/refs" EndpointUploadPack = "git-upload-pack" EndpointReceivePack = "git-receive-pack" )
Smart HTTP endpoint names (git-http-backend(1)). These are the only endpoints the gateway forwards.
const PathPrefix = "/j/"
PathPrefix is the fixed prefix every gateway route starts with: /j/<job-token>/<host>/<owner>/<repo>[.git]/<endpoint>.
Variables ¶
This section is empty.
Functions ¶
func GenerateToken ¶
func GenerateToken() string
GenerateToken returns a random hex-encoded job token, using the same crypto/rand + 16-byte scheme as internal/sandbox's broker token registry.
func SandboxURL ¶ added in v0.1.0
func SandboxURL(opts SandboxURLOptions) string
SandboxURL builds the base URL a sandbox should use to reach a daemon-side listener, given opts.Backend. BackendUserns (and the zero value) reproduces the loopback-projection URL; BackendContainer produces a compose-service-name URL over TLS.
Types ¶
type Backend ¶ added in v0.1.0
type Backend string
Backend identifies which sandbox execution backend a set of sandbox-facing URLs (gateway, and eventually broker/dockerproxy) must be reachable from.
Defined locally rather than pulled from internal/sandbox/backend: this package stays a leaf (no internal/... imports).
const ( // BackendUserns identifies the former userns backend (pasta slirp NAT, // host loopback projected at 10.0.2.2). No longer used in production — // retained only as a test-DI seam / SandboxURLOptions.Backend's zero // value. BackendUserns Backend = "userns" // BackendContainer is the container backend, the sole backend used in // production: daemon and job share a compose network, so the gateway // is reached by its compose service name over DNS instead of a // loopback projection. BackendContainer Backend = "container" )
type CredentialProvider ¶
type CredentialProvider struct {
// contains filtered or unexported fields
}
CredentialProvider injects forge-appropriate Basic auth into upstream requests, resolving the actual token value through a SecretResolver.
func NewCredentialProvider ¶
func NewCredentialProvider(hosts []HostForgeConfig, resolver SecretResolver) *CredentialProvider
NewCredentialProvider builds a CredentialProvider from a list of per-host forge configs and the resolver used to fetch each config's secret value.
func (*CredentialProvider) Configured ¶
func (c *CredentialProvider) Configured() bool
Configured reports whether c has any secret resolver wired at all. It distinguishes two failure modes at the caller (Server.ServeHTTP):
- resolver == nil: no secret store configured at all — a systemic "credentials aren't set up yet" state, true for every host/request.
- resolver present but errors for a specific key: an ordinary per-key miss (e.g. a HostForgeConfig.SecretKey reference that was never `boid secret set`), which Inject still surfaces per-request via its usual error return.
This lets ServeHTTP fail fast for the former without spamming NotifyCredentialError on every request, leaving the latter's existing fail-open + notify behavior unchanged.
func (*CredentialProvider) Inject ¶
func (c *CredentialProvider) Inject(req *http.Request, host, namespace string) error
Inject resolves host's configured secret, scoped to namespace, and sets Basic auth on req using the forge's username convention. It returns an error (and leaves req unmodified) if host has no configured forge, no resolver is set, or the secret can't be resolved — callers log this rather than fail the request outright, since a misconfigured host is a config problem, not grounds to crash the gateway.
Inject is a thin wrapper over Resolve. Callers that only need to know whether resolution would succeed — without holding an outbound request to modify — should call Resolve directly.
func (*CredentialProvider) KnowsHost ¶ added in v0.0.11
func (c *CredentialProvider) KnowsHost(host string) bool
KnowsHost reports whether c has a HostForgeConfig entry for host — i.e. whether host is in the gateway's allowlist of forges the daemon is configured to authenticate. Server.ServeHTTP's fail-fast pre-check uses this to distinguish "host we have no opinion on" (e.g. test upstreams; forwarded unauthenticated, as before) from "host we're configured for but whose secret fails to resolve" (502, no forwarding).
A nil *CredentialProvider knows no hosts, matching the fail-closed behavior of Inject/Resolve above.
func (*CredentialProvider) Resolve ¶ added in v0.0.11
func (c *CredentialProvider) Resolve(host, namespace string) (username, token string, err error)
Resolve looks up host's forge config, resolves its secret key against namespace, and returns the Basic-auth username / token pair the gateway would use for outbound requests to that host. It returns an error (leaving both strings empty) if host has no configured forge, no resolver is set, or the secret can't be resolved.
Server.ServeHTTP calls Resolve before proxying so it can 502 without ever contacting the upstream when credentials fail to resolve, avoiding the sandbox-side git credential prompt that upstream 401s cause. Inject below is a thin wrapper for the Rewrite callback path that still needs to SetBasicAuth on an outbound *http.Request.
func (*CredentialProvider) SchemeFor ¶
func (c *CredentialProvider) SchemeFor(host string) string
SchemeFor returns the upstream request scheme for host: the configured override if present, otherwise "https".
type Entry ¶
type Entry struct {
Token string
Namespace string
Repos map[RepoKey]Permission
}
Entry is one job token's authorization: which repos it may reach and at what permission level, plus the secret-store namespace credential resolution should use for this token. The caller builds Repos and Namespace at Register time — Registry itself doesn't know their shape, and just carries Namespace alongside Repos for Server.ServeHTTP to pass through to CredentialProvider.Inject.
type Forge ¶
type Forge string
Forge identifies which upstream git host convention to use for Basic auth.
type HostForgeConfig ¶
type HostForgeConfig struct {
// Host is the upstream host as it appears in the gateway route path
// (e.g. "github.com"), used as the lookup key.
Host string `yaml:"host"`
// Forge selects the Basic-auth username convention and (in future
// callers) any forge-specific behavior.
Forge Forge `yaml:"forge"`
// SecretKey is a reference into the secret store
// (internal/dispatcher/secret_store.go); never a plaintext token.
SecretKey string `yaml:"secret_key"`
// Scheme overrides the upstream request scheme; empty means "https".
// Production forge hosts always use https — this only exists so tests
// can point a HostForgeConfig at a plaintext httptest upstream.
Scheme string `yaml:"-"`
}
HostForgeConfig declares how the gateway authenticates requests to one upstream host: which forge convention to use and which secret-store key holds the token.
type NotifierFuncs ¶
type NotifierFuncs struct {
UpstreamAuthFailure func(host string, repo RepoKey)
CredentialError func(host string, repo RepoKey, err error)
}
NotifierFuncs adapts plain functions to UpstreamAuthFailureNotifier. Either field may be left nil, in which case the corresponding notification is a no-op — callers that only care about one of the two failure modes (e.g. tests) do not need to stub both.
func (NotifierFuncs) NotifyCredentialError ¶
func (f NotifierFuncs) NotifyCredentialError(host string, repo RepoKey, err error)
NotifyCredentialError implements UpstreamAuthFailureNotifier.
func (NotifierFuncs) NotifyUpstreamAuthFailure ¶
func (f NotifierFuncs) NotifyUpstreamAuthFailure(host string, repo RepoKey)
NotifyUpstreamAuthFailure implements UpstreamAuthFailureNotifier.
type Operation ¶
type Operation string
Operation is the git operation implied by a request, derived from the endpoint name (and, for info/refs, the ?service= query parameter) rather than the HTTP method.
type Permission ¶
type Permission int
Permission is the access level a job token has on one repo.
const ( // PermFetch allows git-upload-pack only (read/clone/fetch). PermFetch Permission = iota + 1 // PermFetchPush allows both git-upload-pack and git-receive-pack. PermFetchPush )
func (Permission) Allows ¶
func (p Permission) Allows(op Operation) bool
Allows reports whether this permission covers the given operation.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry is the job-token → allowed-repo-set store: a sync.RWMutex-guarded map[token]*Entry.
func (*Registry) Authorize ¶
Authorize reports whether token may perform op against repo. 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 the repo/operation isn't in its allowed set (caller should respond 403).
func (*Registry) Lookup ¶
Lookup returns the entry for token, if any — including Entry.Namespace, which Server.ServeHTTP reads after a successful Authorize to pass the right namespace into CredentialProvider.Inject. 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(repos map[RepoKey]Permission, namespace string) string
Register creates a new entry with a freshly generated token, scoped to namespace, and returns the token.
func (*Registry) RegisterToken ¶
func (r *Registry) RegisterToken(token string, repos map[RepoKey]Permission, namespace string)
RegisterToken creates (or replaces) an entry under an explicit token, scoped to namespace — useful for callers (and tests) that already have a token value to correlate with (e.g. alongside a job id in logs).
func (*Registry) Unregister ¶
Unregister revokes a token. A subsequent Lookup/Authorize for it reports the token as invalid. Unregistering an unknown token is a no-op.
type RepoKey ¶
type RepoKey string
RepoKey identifies a repo by its normalized "<host>/<owner>/<repo>" form — always suffix-free, absorbing the ".git"-suffix asymmetry between HTTPS and SSH origin URLs. Both Registry.Register and parsePath (lookup) route through NewRepoKey to keep that normalization in one place.
func NewRepoKey ¶
NewRepoKey builds a normalized RepoKey from path components, stripping a ".git" suffix from repo if present.
type SandboxURLOptions ¶ added in v0.1.0
type SandboxURLOptions struct {
// Backend selects the addressing scheme. The zero value ("") behaves
// like BackendUserns, so existing callers that don't set this field
// keep today's http://10.0.2.2:<port> behavior unchanged.
Backend Backend
// Port is the TCP port the target listener is bound to. Consulted by
// both backends.
Port int
// ServiceName is the compose network DNS name of the daemon's
// service (e.g. "boid-daemon"). Only consulted when Backend ==
// BackendContainer. Defaults to "boid-gateway" when left empty under
// BackendContainer.
ServiceName string
}
SandboxURLOptions carries the backend-specific addressing info needed to build a URL that reaches a daemon-side listener (e.g. the git gateway) from inside a sandbox.
type SecretResolver ¶
SecretResolver resolves a secret-store key reference, scoped to a namespace, to its plaintext value. config.yaml carries only the key reference, never the plaintext token. This is a plain function type, mirroring internal/sandbox.SecretResolver's shape, so callers can adapt internal/dispatcher.SecretStore.Get to it with a one-line closure instead of gitgateway importing the dispatcher package. namespace is the job token's Registry-recorded namespace (Entry.Namespace); an empty namespace is expected to fall back to a "default" namespace (mirroring internal/dispatcher.SecretStore.Get's own normalizeNamespace).
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the git gateway's HTTP handler: a thin net/http/httputil. ReverseProxy wrapper that does path-based authorization (Registry) and forge credential injection (CredentialProvider) around the standard library's streaming transport. It never buffers request bodies — packfile POSTs stream straight through to the upstream forge.
func NewServer ¶
func NewServer(registry *Registry, credentials *CredentialProvider, notifier UpstreamAuthFailureNotifier) *Server
NewServer builds a Server. credentials may be nil (requests are proxied without auth injection — useful for tests against an upstream that doesn't require it); notifier may be nil (defaults to NoopNotifier).
func (*Server) CloseTLS ¶ added in v0.1.0
CloseTLS gracefully shuts down the http.Server bound by ListenTLS: it stops accepting new connections (like ln.Close() alone would) and also closes idle keep-alive connections, waiting up to ctx's deadline for in-flight requests to finish before returning. A no-op (nil error) if ListenTLS was never called.
func (*Server) ListenTLS ¶ added in v0.1.0
ListenTLS binds a TCP+mTLS listener at addr and serves s on it in a background goroutine, returning immediately once the listener is bound. tlsConfig is expected to require and verify a client certificate (see internal/mtls.CA.ServerTLSConfig).
The caller owns the returned listener's lifecycle. Closing the bare net.Listener alone stops new connections but leaves already-accepted keep-alive connections open (they're owned by the *http.Server driving Serve, not the listener); call CloseTLS instead to also close those (e.g. on daemon shutdown).
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 upstream forge URL and proxies it with credentials injected. Unrecognized paths get 404; unknown/expired tokens get 401; well-formed-but-disallowed repo/operation combinations get 403; anything else about the request shape (missing/bad ?service=, wrong method) gets 400/405.
type UpstreamAuthFailureNotifier ¶
type UpstreamAuthFailureNotifier interface {
NotifyUpstreamAuthFailure(host string, repo RepoKey)
NotifyCredentialError(host string, repo RepoKey, err error)
}
UpstreamAuthFailureNotifier is invoked on two distinct failure modes so an operator can tell them apart:
- NotifyUpstreamAuthFailure: the upstream forge responded with 401 to a request that WAS sent with injected credentials — the token itself is wrong/expired/revoked ("rotate the token").
- NotifyCredentialError: credential injection itself failed before the request ever reached the upstream — an unconfigured host, a missing resolver, or a secret-store lookup error ("fix the gateway config").
The gateway always logs a warning on either condition and additionally calls the matching hook, but never aborts serving other requests because of it.
var NoopNotifier UpstreamAuthFailureNotifier = NotifierFuncs{}
NoopNotifier discards notifications. It is the default when a Server is constructed with a nil notifier.