Documentation
¶
Overview ¶
Package domains serves customer-owned hosts attached at runtime: it normalizes what a tenant types, resolves request hosts to domains through a bounded cache, answers Caddy's on-demand TLS ask, verifies DNS ownership and routing, and steps each domain through its lifecycle.
Persistence is the app's: implement Store (and Writer for jobs), or use memstore. The package depends on no other Fletch module.
Index ¶
- Constants
- Variables
- func AskHandler(r *Resolver, opts ...AskOption) http.Handler
- func GenerateToken() (string, error)
- func IsUnderZone(host, zone string) bool
- func Normalize(input string) (host string, apex bool, err error)
- func WellKnownHandler(r *Resolver) http.Handler
- type AskOption
- type Checker
- type Domain
- type Lifecycle
- func (l Lifecycle) Advance(ctx context.Context, c Checker, d Domain, now time.Time) (Outcome, error)
- func (l Lifecycle) Claimed(d Domain, r Result, now time.Time) (Outcome, error)
- func (l Lifecycle) HTTPSReady(d Domain, probeErr error, now time.Time) (Outcome, error)
- func (l Lifecycle) Rechecked(d Domain, r Result, now time.Time) (Outcome, error)
- type MiddlewareOption
- type Outcome
- type Problem
- type Resolver
- type ResolverOption
- type Result
- type State
- type Store
- type Verifier
- type Writer
Constants ¶
const ( ProblemTXTMissing = "txt_missing" ProblemCNAMEMismatch = "cname_mismatch" ProblemAMismatch = "a_mismatch" ProblemAAAAElsewhere = "aaaa_elsewhere" ProblemNoAddress = "no_address" ProblemDNSError = "dns_error" ProblemHTTPProbeFailed = "http_probe_failed" )
The Problem codes Verify reports.
const AskTokenHeader = "X-Ship-Ask-Token"
AskTokenHeader is the header AskHandler reads the WithAskToken secret from. Ship's Caddy loopback site sets it.
const WellKnownPrefix = "/.well-known/fletch-domain/"
WellKnownPrefix is the path WellKnownHandler serves tokens under.
Variables ¶
var ( // ErrNotFound is returned by Store.Lookup for an unknown host. ErrNotFound = errors.New("domains: not found") // ErrInvalidHost is returned for input that is not a claimable host name. ErrInvalidHost = errors.New("domains: invalid host") // ErrInvalidState is returned by a Lifecycle step called on a domain in // a state that step does not leave. ErrInvalidState = errors.New("domains: invalid state transition") )
Functions ¶
func AskHandler ¶
AskHandler answers Caddy's on-demand TLS ask: GET ?domain=<name> gets an empty 200 when a certificate may be issued for name, and an empty 403 or 404 otherwise.
Every configured guard must pass, or the answer is 403. With neither WithAskToken nor WithAskPeers the answer is always 403 unless WithInsecureNoGuard is set.
A name is approved when WithAllowHost approves it, or when it resolves to a verified, active, or degraded domain. IP literals, names that are not valid DNS host names, unknown names, and pending or suspended domains get 404; a Store failure gets 503. Lookups go through r, so a scan of random names costs one Store query per name per negative TTL.
func GenerateToken ¶
GenerateToken returns a new ownership token: 128 random bits as lower-case base32 without padding.
func IsUnderZone ¶
IsUnderZone reports whether host is zone or a name under it, comparing case-insensitively and ignoring one trailing dot on either. Apps use it to refuse tenant claims on the platform's own zone.
func Normalize ¶
Normalize turns what a tenant typed into the host to store: it trims space, drops a pasted scheme, path, query, or fragment, converts to an A-label (IDNA lookup profile), lower-cases it, and strips one trailing dot. apex reports whether the host is its own eTLD+1.
It rejects, with an error wrapping ErrInvalidHost: empty input, user info, ports, wildcards, IP literals, single-label names, and bare public suffixes such as "com" or "co.uk".
func WellKnownHandler ¶
WellKnownHandler serves GET /.well-known/fletch-domain/<token> for the Verifier's HTTP probe: 200 with the token as the body when the request Host is a known domain (any state) with that token, and 404 otherwise. Mount it where every host reaches it, outside Resolver.Middleware, which would hide pending domains.
Types ¶
type AskOption ¶
type AskOption func(*ask)
AskOption configures AskHandler.
func WithAllowHost ¶
WithAllowHost approves hosts fn returns true for, such as the platform's static hosts, in addition to store-backed domains. It approves names; it does not authenticate the caller, so it is not a guard.
func WithAskPeers ¶
WithAskPeers requires the caller's address (RemoteAddr) to be in one of cidrs. An invalid CIDR panics. IPv4-mapped IPv6 addresses are compared as IPv4.
func WithAskToken ¶
WithAskToken requires the X-Ship-Ask-Token header to equal token, compared in constant time. An empty token panics.
func WithInsecureNoGuard ¶
func WithInsecureNoGuard() AskOption
WithInsecureNoGuard lets AskHandler answer callers with neither WithAskToken nor WithAskPeers configured. Use it in local development only.
type Checker ¶
type Checker interface {
Verify(ctx context.Context, d Domain) Result
ProbeHTTPS(ctx context.Context, host string) error
}
Checker is what Advance needs from a Verifier.
type Domain ¶
type Domain struct {
// Host is the normalized A-label, as Normalize returns it.
Host string
TenantID string
State State
// Apex reports whether Host is a registrable domain (its eTLD+1), which
// cannot carry a CNAME.
Apex bool
// Token is the ownership token the tenant publishes in DNS.
Token string
CreatedAt time.Time
VerifiedAt time.Time
CheckedAt time.Time
DegradedAt time.Time
Failures int
LastProblem string
}
Domain is a host attached to a tenant.
func FromContext ¶
FromContext returns the domain Middleware attached to ctx.
type Lifecycle ¶
type Lifecycle struct {
// FailureThreshold is how many consecutive failed rechecks move an
// active domain to degraded. Default 3.
FailureThreshold int
// DegradedGrace is how long a domain stays degraded before it is
// suspended. Default 7 days.
DegradedGrace time.Duration
// PendingExpiry is how long a domain may stay pending_dns before it
// expires. Default 14 days.
PendingExpiry time.Duration
}
Lifecycle holds the thresholds of the domain state machine:
pending_dns --(owned && routed)--> verified verified --(HTTPS probe ok)---> active active --(FailureThreshold consecutive failed rechecks)--> degraded degraded --(routed)-----------> active degraded --(DegradedGrace)----> suspended suspended --(owned && routed)--> verified pending_dns --(PendingExpiry)----> expired: delete the row
Ownership is checked only when a domain is claimed or re-claimed (pending_dns and suspended); rechecks of active and degraded domains look at routing only. The zero value uses the defaults.
func (Lifecycle) Advance ¶
func (l Lifecycle) Advance(ctx context.Context, c Checker, d Domain, now time.Time) (Outcome, error)
Advance runs the check d's state calls for and applies it: Verify for pending_dns and suspended, ProbeHTTPS for verified, a routing Verify for active and degraded.
func (Lifecycle) Claimed ¶
Claimed applies a Verify result to a pending_dns or suspended domain: it becomes verified when it is owned and routed. A pending_dns domain that is not, and is older than PendingExpiry, is reported Expired.
func (Lifecycle) HTTPSReady ¶
HTTPSReady applies an HTTPS probe result to a verified domain: it becomes active when probeErr is nil.
type MiddlewareOption ¶
type MiddlewareOption func(*middleware)
MiddlewareOption configures Resolver.Middleware.
func WithNotFound ¶
func WithNotFound(h http.Handler) MiddlewareOption
WithNotFound sets the handler for requests whose host is not a serving domain. Default: a plain 404.
type Outcome ¶
type Outcome struct {
// Domain is the domain after the step; save it.
Domain Domain
// Changed reports whether the state changed; publish the change so
// resolvers invalidate their caches.
Changed bool
// Expired reports that a pending_dns domain passed PendingExpiry; delete
// it instead of saving it.
Expired bool
}
Outcome is the result of one Lifecycle step.
type Resolver ¶
type Resolver struct {
// contains filtered or unexported fields
}
Resolver looks hosts up in a Store through two bounded caches: found domains (any state) and unknown hosts. They are separate so that a scan of random names fills only the negative cache and never evicts a real domain. Concurrent misses for one host share one Store.Lookup.
func NewResolver ¶
func NewResolver(s Store, opts ...ResolverOption) *Resolver
NewResolver returns a Resolver over s.
func (*Resolver) Invalidate ¶
Invalidate drops host from both caches. Wire it to the event a domain change publishes so every replica sees the change before the TTL ends.
func (*Resolver) Middleware ¶
Middleware serves a request only when its Host is an active or degraded domain, which it attaches to the request context (see FromContext). Invalid, unknown, and non-serving hosts get the WithNotFound handler; a Store failure gets a 503.
func (*Resolver) Resolve ¶
Resolve returns the domain for host in any state, or ErrNotFound. host is lower-cased and one trailing dot is dropped; a name that is not a valid DNS host or is an IP literal returns ErrInvalidHost without a Store lookup. Store errors other than ErrNotFound are returned and not cached.
type ResolverOption ¶
type ResolverOption func(*Resolver)
ResolverOption configures a Resolver.
func WithClock ¶
func WithClock(now func() time.Time) ResolverOption
WithClock sets the clock the caches expire by, for tests.
func WithMaxEntries ¶
func WithMaxEntries(pos, neg int) ResolverOption
WithMaxEntries bounds the found and unknown caches. Default 100,000 and 10,000. Zero disables that cache.
func WithNegativeTTL ¶
func WithNegativeTTL(d time.Duration) ResolverOption
WithNegativeTTL sets how long an unknown host is cached. Default 30s.
func WithPositiveTTL ¶
func WithPositiveTTL(d time.Duration) ResolverOption
WithPositiveTTL sets how long a found domain is cached. Default 60s.
type Result ¶
type Result struct {
// Owned: the ownership TXT record carries the domain's token.
Owned bool
// Routed: the host reaches the platform's ingress.
Routed bool
Problems []Problem
}
Result is what Verify found.
type State ¶
type State string
State is where a domain is in its lifecycle.
const ( StatePendingDNS State = "pending_dns" StateVerified State = "verified" StateActive State = "active" StateDegraded State = "degraded" StateSuspended State = "suspended" )
The lifecycle states. Requests are served for StateActive and StateDegraded; certificates may be issued for those and StateVerified.
type Store ¶
type Store interface {
// Lookup returns the domain for host, or ErrNotFound.
Lookup(ctx context.Context, host string) (Domain, error)
}
Store looks domains up by normalized host.
func DevAlwaysVerified ¶
DevAlwaysVerified wraps s for local development: every host Normalize accepts resolves as an active domain, so custom-domain flows work on names such as brand-a.shop.localhost with no DNS. Rows s holds keep their fields but read as active. Never use it in production.
type Verifier ¶
type Verifier struct {
// Resolver does the lookups. Nil uses net.DefaultResolver; set PreferGo
// and a Dial to a public resolver to skip stale local caches.
Resolver *net.Resolver
// Target is the name tenants CNAME subdomains to, such as
// "sites.platform.com".
Target string
// IPv4 and IPv6 are the ingress addresses apex records must point at,
// and the fallback for subdomains whose CNAME is flattened.
IPv4 []netip.Addr
IPv6 []netip.Addr
// TXTLabel is the label the ownership record lives under. Default
// "_fletch-verify".
TXTLabel string
// HTTPProbe, when set, fetches
// http://<host>/.well-known/fletch-domain/<token> when DNS does not
// prove routing; a 200 whose body holds the token proves it. It also
// makes ProbeHTTPS's requests.
HTTPProbe *http.Client
}
Verifier checks a domain's DNS with a pure-Go resolver, so it works with CGO_ENABLED=0.
func (*Verifier) ProbeHTTPS ¶
ProbeHTTPS reports whether https://<host>/ completes a TLS handshake with a certificate the client trusts. Any HTTP status counts; redirects are not followed. A job calls it to move a verified domain to active once the ingress has a certificate.
func (*Verifier) Verify ¶
Verify checks ownership and routing of d.Host.
Ownership: a TXT record at TXTLabel.<host> contains d.Token.
Routing: for a subdomain, its CNAME resolves to Target, or else every A and AAAA address is an ingress address; for an apex, every A and AAAA address is an ingress address. Either way at least one address must exist. A stray AAAA (aaaa_elsewhere) fails routing even when the HTTP probe succeeds, because ACME validators prefer IPv6.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package domainstest is the conformance suite for domains.Store and domains.Writer implementations.
|
Package domainstest is the conformance suite for domains.Store and domains.Writer implementations. |
|
Package memstore is an in-memory domains.Store and domains.Writer, for tests, development, and single-process apps that load domains at boot.
|
Package memstore is an in-memory domains.Store and domains.Writer, for tests, development, and single-process apps that load domains at boot. |