Documentation
¶
Overview ¶
Package proxyroutes writes and maintains route files in an external reverse proxy's watched configuration directory (Traefik's file provider), so domains reach this instance through a proxy that owns ports 80 and 443.
Index ¶
- Constants
- Variables
- func ACMEFailure(logs, domain string) string
- func ACMEFailureSince(logs, domain string, since time.Time) string
- func ClassifyCert(issuerCN, issuerOrg, subjectCN string, selfSigned, trusted bool) string
- func IsACMERateLimit(line string) bool
- func KnownResolvers(ctx context.Context, base string, timeout time.Duration) ([]string, error)
- func Managed(p Provider) bool
- func NginxConfPath(c Container) (string, bool)
- func ProxiedByCDN(ips []string) bool
- func RecordRetry(domain string, at time.Time)
- func RetriedAt(domain string) time.Time
- func RouterLoaded(ctx context.Context, base, router string, timeout time.Duration) (bool, error)
- func StaticConfigCandidates(c Container) []string
- func UntrustedMessage(class, issuer string) string
- func ValidateDomain(domain string) (string, error)
- func ValidateName(kind, name string) error
- func ValidateNginxPath(kind, p string) error
- func ValidateUpstream(hostport string) error
- func ValidateUpstreamHost(host string) error
- type ApplyResult
- type Container
- type DNSFacts
- type Detection
- type DiagnoseInput
- type Diagnosis
- type Dir
- type Exec
- type ExecError
- type File
- type Item
- type Listener
- type Marker
- type Mount
- type Namespace
- func (n Namespace) FileName(domain string) (string, error)
- func (n Namespace) FileNameExt(domain, ext string) (string, error)
- func (n Namespace) FilePrefix() string
- func (n Namespace) Header() string
- func (n Namespace) Render(r Route) ([]byte, error)
- func (n Namespace) RenderUnrouted(r Route) ([]byte, error)
- func (n Namespace) RouterName(domain string) string
- func (n Namespace) UnroutedFileName(ext string) string
- type NotWritableError
- type Outcome
- type Plan
- type PortMap
- type ProbeResult
- type ProbeTarget
- type Provider
- type RedirectLister
- type RejectedError
- type Removal
- type Report
- type Route
- type RouterTLS
- type StandaloneLister
- type SyncStore
- type Syncer
- type Target
- type UnreachableError
- type UpstreamPath
Constants ¶
const ( KeyUnroutedToLevelrail = "proxy.unrouted_to_levelrail" EnvUnroutedToLevelrail = "LEVELRAIL_PROXY_UNROUTED_TO_LEVELRAIL" // DefaultUnroutedPriority sits above the front proxy's own noop catch-all // and below every host router, so it never overrides another router. DefaultUnroutedPriority = -500 )
Runtime setting key and env seed; the catch-all is opt in and off by default.
const ( ClassTrusted = "trusted" ClassProxyDefault = "proxy_default" ClassOriginCA = "origin_ca" ClassPrivateCA = "private_ca" )
Certificate classes a probe can report.
const ( KindTraefik = "traefik" KindNginx = "nginx" KindCaddy = "caddy" KindNone = "none" )
Proxy kinds Detection.Kind reports.
const ( DiagNone = "" DiagCertExpired = "cert_expired" DiagOriginCert = "origin_cert" DiagPrivateCA = "private_ca" DiagNoTLS = "router_no_tls" DiagNoResolver = "no_cert_resolver" DiagDNSMismatch = "dns_mismatch" DiagPortUnreachable = "port_unreachable" DiagACMEPending = "acme_pending" DiagACMEStuck = "acme_stuck" DiagACMEFailed = "acme_failed" DiagACMERateLimited = "acme_rate_limited" )
Diagnosis codes, stable for the API, CLI and dashboard.
const ( DefaultRouterPriority = 100000 MaxRouterPriority = 1000000000 )
Router priorities. Traefik defaults a router's priority to its rule length, so a label router such as Host(x) && PathPrefix(/) would beat a bare Host(x). The cap stays below the priorities Traefik reserves for its own routers.
const ( TargetApp = "app" TargetDashboard = "dashboard" TargetStandalone = "standalone" )
Route targets.
const ( StateMissing = "missing" StateWritten = "written" StateStale = "stale" StateError = "error" )
Per-domain file states.
const DefaultFileExt = ".yaml"
DefaultFileExt is the extension of Traefik route files.
const HostDockerInternal = "host.docker.internal"
HostDockerInternal is the name Docker resolves to the host when the container was started with host.docker.internal:host-gateway.
const KindHAProxy = "haproxy"
KindHAProxy is the proxy kind of an HAProxy container.
const NotWritableCode = "not_writable"
NotWritableCode is the error code reported when the directory cannot be written by this process.
const UpstreamUnreachableCode = "upstream_unreachable"
UpstreamUnreachableCode is the error code reported when a listener cannot be reached from the proxy container.
const WaitingForRoute = "waiting for the proxy to load the route"
WaitingForRoute is the pending message recorded when the proxy had not loaded a written route file within the verify window.
Variables ¶
var ErrForeignFile = errors.New("file was not written by this instance")
ErrForeignFile is returned when a file with a managed name was not written by this package (no header, not a regular file).
var ErrRetryUnsupported = errors.New("retrying a certificate request is only supported for Traefik file routes")
ErrRetryUnsupported is returned for providers where a file change does not make the proxy re-attempt a certificate request.
Functions ¶
func ACMEFailure ¶
ACMEFailure returns the most recent proxy log line that reports a failed certificate request for domain. Lines are matched case-insensitively and the result is cut to a readable length; callers mask secrets before storing.
func ACMEFailureSince ¶
ACMEFailureSince is ACMEFailure ignoring lines stamped before since; lines without a readable timestamp are kept because their age is unknown.
func ClassifyCert ¶
ClassifyCert sorts a presented certificate. A self-signed certificate for localhost is the nginx default; any other untrusted issuer is a private CA.
func IsACMERateLimit ¶
IsACMERateLimit reports whether a failure line is a CA rate limit.
func KnownResolvers ¶
KnownResolvers lists the certResolver names other routers on this Traefik use, most used first, so a hint can name a resolver that exists.
func NginxConfPath ¶
NginxConfPath is the host path of nginx.conf when it is on a mount.
func ProxiedByCDN ¶
ProxiedByCDN reports whether any address sits in a CDN proxy range.
func RecordRetry ¶
RecordRetry marks now as the moment a retry was requested for domain.
func RouterLoaded ¶
RouterLoaded asks Traefik's API at base (http://127.0.0.1:8080) whether router is loaded and enabled. Only used when the API is insecure and local.
func StaticConfigCandidates ¶
StaticConfigCandidates lists host paths that may hold the container's static configuration file, in Traefik's own search order. Only mounted paths are returned, since an unmounted file cannot be read from the host.
func UntrustedMessage ¶
UntrustedMessage is the short probe error for a reachable route whose certificate does not verify; the full diagnosis comes from Diagnose.
func ValidateDomain ¶
ValidateDomain returns domain lowercased when it is a plain hostname that is safe to embed in a file name and a Traefik rule. Wildcards, ports, paths and anything that would need rewriting are rejected.
func ValidateName ¶
ValidateName checks an entrypoint or resolver name before it is written into YAML.
func ValidateNginxPath ¶
ValidateNginxPath checks a certificate directory or webroot before it is written into a configuration file.
func ValidateUpstream ¶
ValidateUpstream checks host:port before it is written into a URL.
func ValidateUpstreamHost ¶
ValidateUpstreamHost accepts an IP address or a hostname, including a single label such as "host.docker.internal" or "localhost".
Types ¶
type ApplyResult ¶
ApplyResult is the outcome of one Apply pass.
type Container ¶
type Container struct {
Name string
Image string
Kind string
Args []string
Mounts []Mount
ExtraHosts []string
NetworkMode string
// Gateway is the host side of the container's first network.
Gateway string
Mappings []PortMap
// HostGatewayIP is what Docker's "host-gateway" alias resolves to.
HostGatewayIP string
// StaticFile and StaticConfig are the static configuration file read
// from the host, when one exists (see StaticConfigCandidates).
StaticFile string
StaticConfig []byte
// NginxConf is the host copy of nginx.conf when it could be read.
NginxConf []byte
}
Container is the Docker data detection reads from a proxy container.
type DNSFacts ¶
type DNSFacts struct {
IPs []string
// ServerIPs are the addresses of the host the probe dials; empty when unknown.
ServerIPs []string
Err string
}
DNSFacts is what the control plane resolver says about the domain.
type Detection ¶
type Detection struct {
Kind string `json:"kind"`
Container string `json:"container"`
Image string `json:"image"`
PublishedPorts []int `json:"published_ports"`
DynamicDir string `json:"dynamic_dir"`
EntrypointHTTP string `json:"entrypoint_http"`
EntrypointHTTPS string `json:"entrypoint_https"`
CertResolver string `json:"cert_resolver"`
UpstreamHost string `json:"upstream_host"`
CertDir string `json:"cert_dir,omitempty"`
Webroot string `json:"webroot,omitempty"`
Complete bool `json:"complete"`
Missing []string `json:"missing"`
ContainerDir string `json:"-"`
CertResolvers []string `json:"-"`
UpstreamIP string `json:"-"`
HostNetwork bool `json:"-"`
PublicHTTPPort int `json:"-"`
PublicHTTPSPort int `json:"-"`
// APIPort is the host port of Traefik's unauthenticated API, 0 if none.
APIPort int `json:"-"`
// contains filtered or unexported fields
}
Detection is what was learned about the proxy container. Missing lists, in plain language, everything that could not be determined.
func Detect ¶
Detect reads a proxy container's arguments, mounts, ports and extra hosts. It never guesses: anything it cannot determine is listed in Missing.
func None ¶
func None() Detection
None is the detection result when no container holds the web ports.
func (*Detection) OverrideCertDir ¶
OverrideCertDir uses dir, given by the operator, as the in-container certificate directory and drops the gaps it resolves.
func (*Detection) OverrideDir ¶
OverrideDir uses dir, given by the operator, as the host directory and drops the gaps it resolves.
type DiagnoseInput ¶
type DiagnoseInput struct {
Domain string
Class string
Issuer string
NotAfter time.Time
Now time.Time
FirstSeen time.Time
// Budget is how long a missing certificate is treated as "still being requested".
Budget time.Duration
RouterName string
// Router is nil when Traefik's API could not be read.
Router *RouterTLS
// Resolvers are the certResolver names other routers use.
Resolvers []string
ConfiguredResolver string
DNS *DNSFacts
// Port80Open is nil when not checked.
Port80Open *bool
// ACMELog is the proxy's own failure line for this domain, already masked.
ACMELog string
}
DiagnoseInput is every fact Diagnose needs, collected by the caller so the decision stays a pure function.
type Diagnosis ¶
Diagnosis explains why a reachable route has no usable certificate.
func Diagnose ¶
func Diagnose(in DiagnoseInput) Diagnosis
Diagnose returns the most likely cause, or a zero Diagnosis when the certificate is fine. For a fallback certificate the order is: router has no resolver, DNS points elsewhere, port 80 closed, then ACME pending or stuck.
type Dir ¶
type Dir struct {
// contains filtered or unexported fields
}
Dir is a proxy configuration directory, resolved once to its real path and re-checked before every change.
func OpenDir ¶
OpenDir resolves path. It must be absolute and an existing directory. If the last component is a symlink it must resolve inside the same parent.
func OpenDirExt ¶
OpenDirExt is OpenDir for a provider whose files use another extension.
func (*Dir) CheckWritable ¶
CheckWritable creates and removes a probe file in the directory, the only reliable test under a sandbox, a read-only mount or another user.
func (*Dir) Managed ¶
Managed lists the managed files currently in the directory by name, and separately the names that carry the prefix but are not ours.
type Exec ¶
Exec runs a command inside a proxy container through the Docker Engine API and returns its standard output. A non-zero exit is an *ExecError.
type ExecError ¶
ExecError is a command that ran and exited non-zero; Output is what it printed, verbatim.
type Listener ¶
type Listener struct {
// Label names it in messages, e.g. "ingress" or "dashboard".
Label string
Addr string
// EnvVar is the variable that moves it, e.g. APP_INGRESS_HTTP_ADDR.
EnvVar string
}
Listener is one of this instance's HTTP listeners the proxy forwards to.
type Marker ¶
Marker is a request header only this server's ingress replies to, with a reply value the app behind it cannot know.
type Namespace ¶
type Namespace string
Namespace scopes every file name and Traefik object this package owns. It is the lowercased brand short name, never a literal.
func (Namespace) FileName ¶
FileName is the file domain's route lives in. domain must already be validated; anything that would sanitise to a different name is refused.
func (Namespace) FileNameExt ¶
FileNameExt is FileName with the provider's file extension.
func (Namespace) FilePrefix ¶
FilePrefix is the name prefix of every file this package may touch.
func (Namespace) Header ¶
Header is the first line of every file this package writes. A file without it is never modified or removed, whatever its name.
func (Namespace) Render ¶
Render returns the Traefik dynamic configuration file for r: an HTTPS router, an HTTP router that redirects to HTTPS, and one service.
func (Namespace) RenderUnrouted ¶
RenderUnrouted returns a Traefik file that sends any request no other router claimed to Levelrail's ingress, so it can show the diagnostic page.
func (Namespace) RouterName ¶
RouterName is the Traefik name of domain's HTTPS router, as the Traefik API lists it (with the @file provider suffix).
func (Namespace) UnroutedFileName ¶
UnroutedFileName is the managed catch-all file for the provider extension.
type NotWritableError ¶
NotWritableError explains why this process cannot write the directory.
func (*NotWritableError) Error ¶
func (e *NotWritableError) Error() string
type Outcome ¶
type Outcome struct {
Domain string
Name string
// Changed is true when the file was created or its content replaced.
Changed bool
Err error
}
Outcome is what happened to one desired file.
type Plan ¶
type Plan struct {
Settings store.ProxyIntegrationSettings
Provider Provider
Dir *Dir
DirErr error
Items []Item
}
Plan is what the directory should hold under the current settings.
type ProbeResult ¶
type ProbeResult struct {
Reachable bool
StatusCode int
CertIssuer string
CertNotAfter time.Time
CertTrusted bool
// CertClass says what kind of certificate was presented (see ClassifyCert).
CertClass string
// NoRoute is true when the proxy answered with its own "no router matched" 404.
NoRoute bool
// Delivered is true when the Marker reply came back: the proxy handed
// the request to the built-in ingress.
Delivered bool
Err string
}
ProbeResult is the outcome of Probe.
func Probe ¶
func Probe(ctx context.Context, t ProbeTarget) ProbeResult
Probe dials Address (never what DNS says) so a rebinding answer cannot point the probe elsewhere, and records the certificate even when it is not trusted yet, which is the normal state while ACME is still issuing.
type ProbeTarget ¶
type ProbeTarget struct {
Domain string
Address string
Path string
Timeout time.Duration
// Roots overrides the system roots, for tests.
Roots *x509.CertPool
// Marker, when set, is sent so only the built-in ingress can answer it.
Marker *Marker
}
ProbeTarget is one end to end check: a TLS handshake to Address with SNI Domain, then GET Path with the Host header.
type Provider ¶
type Provider interface {
Kind() string
// Mode is the saved integration mode that turns the provider on, or ""
// for a provider that only generates a snippet to apply by hand.
Mode() string
// Ext is the extension of the files the provider writes.
Ext() string
Detect(c Container) Detection
Render(ns Namespace, r Route) ([]byte, error)
// Validate asks the proxy to check the files on disk before it loads them.
Validate(ctx context.Context, ex Exec, container string) error
// Reload makes the proxy load files that passed Validate.
Reload(ctx context.Context, ex Exec, container string) error
}
Provider is one kind of external proxy: how to read it, what route file to write for a domain, and how to make the proxy load the files.
func ProviderFor ¶
ProviderFor returns the provider for a proxy kind.
func ProviderForMode ¶
ProviderForMode returns the managed provider a saved mode selects.
type RedirectLister ¶
type RedirectLister interface {
ListDomainRedirects(ctx context.Context) ([]store.DomainRedirect, error)
}
RedirectLister is optional on SyncStore: domains with a redirect skip the http to https hop so the visitor gets a single redirect.
type RejectedError ¶
type RejectedError struct{ Err error }
RejectedError is a proxy refusing the files that were written; they have been rolled back. Its message is the proxy's own.
func (*RejectedError) Error ¶
func (e *RejectedError) Error() string
func (*RejectedError) Unwrap ¶
func (e *RejectedError) Unwrap() error
type Route ¶
type Route struct {
Domain string
EntrypointHTTP string
EntrypointHTTPS string
// CertResolver empty means Traefik serves its default certificate.
CertResolver string
// Upstream is host:port of this instance's listener for the domain.
Upstream string
// Priority 0 means DefaultRouterPriority.
Priority int
// CertDir is the in-container directory holding <domain>/fullchain.pem
// and privkey.pem (nginx). Webroot, when set, serves ACME challenges.
CertDir string
Webroot string
// Redirect marks a domain with a configured redirect: plain http goes
// straight to the upstream so it answers with one hop, not two.
Redirect bool
}
Route is one domain's desired proxy route.
type StandaloneLister ¶
type StandaloneLister interface {
ListStandaloneDomains(ctx context.Context) ([]store.StandaloneDomain, error)
}
StandaloneLister is optional on SyncStore: standalone domains reach the ingress through the managing proxy like app domains do.
type SyncStore ¶
type SyncStore interface {
GetProxyIntegrationSettings(ctx context.Context) (store.ProxyIntegrationSettings, error)
GetIngressSettings(ctx context.Context) (store.IngressSettings, error)
ListDesiredServices(ctx context.Context) ([]store.DesiredService, error)
ListStaticSites(ctx context.Context) ([]store.StaticSite, error)
ListProxyRouteStatus(ctx context.Context) ([]store.ProxyRouteStatus, error)
MarkProxyRouteWritten(ctx context.Context, domain, target, fileName string, at time.Time, changed bool) error
MarkProxyRouteFailed(ctx context.Context, domain, target, lastError string) error
DeleteProxyRouteStatus(ctx context.Context, domain string) error
SaveAuditEntry(ctx context.Context, e store.AuditEntry) error
}
SyncStore is the persistence the syncer reads and writes.
type Syncer ¶
type Syncer struct {
Store SyncStore
NS Namespace
Ingress Listener
Dashboard Listener
// Unit is the systemd unit named in upstream drop-in fixes.
Unit string
// RouterPriority 0 means DefaultRouterPriority.
RouterPriority int
// Unrouted reports whether the opt in catch-all file is wanted; nil is off.
Unrouted func(context.Context) bool
UnroutedPriority int
Logger *slog.Logger
// Exec validates and reloads a managed proxy that needs it (nginx); nil
// makes such a provider refuse to write anything.
Exec Exec
// RetryGap is how long Retry leaves the nudged file in place before
// restoring it, so the proxy sees two distinct configurations.
RetryGap time.Duration
// contains filtered or unexported fields
}
Syncer converges the proxy's directory on the domains this instance serves.
func (*Syncer) PlanFor ¶
func (s *Syncer) PlanFor(ctx context.Context, settings store.ProxyIntegrationSettings, prov Provider) (Plan, error)
PlanFor renders every routed domain with prov under settings, without saving anything.
func (*Syncer) Retry ¶
Retry makes Traefik re-attempt a failed certificate request for domain. It rewrites the route file with a router priority one higher, waits RetryGap, then restores the normal file. Traefik ignores a reload whose parsed configuration is unchanged, so a comment would not work; a priority change does, and the restore leaves the stored route state untouched.
type Target ¶
type Target struct {
Domain string
Kind string
App string
// Redirect is set from the domain's redirect state on every plan.
Redirect bool
}
Target is one domain this instance serves and where it goes.
func Targets ¶
func Targets(services []store.DesiredService, sites []store.StaticSite, primary string) []Target
Targets lists every domain routed by this instance: app and static site domains, then the primary domain to the dashboard. First claim wins.
func WithStandalone ¶
func WithStandalone(targets []Target, domains []store.StandaloneDomain) []Target
WithStandalone appends standalone domains not already listed, sorted.
type UnreachableError ¶
UnreachableError says a listener is bound where the proxy cannot reach it, with the exact drop-in that fixes it.
func (*UnreachableError) Error ¶
func (e *UnreachableError) Error() string
type UpstreamPath ¶
type UpstreamPath struct {
// Host is written into the route (a name or an address).
Host string
// IP is what Host resolves to inside the proxy container.
IP string
HostNetwork bool
// Unit is the systemd unit the drop-in fix targets.
Unit string
}
UpstreamPath is how the proxy reaches this host.
func PathFromSettings ¶
func PathFromSettings(host, unit string) UpstreamPath
PathFromSettings is the upstream path implied by a saved upstream host.