domains

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: Apache-2.0, MIT Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

domains

Customer-owned domains for Go services: normalization, a cached resolver and middleware, DNS ownership and routing verification, a lifecycle state machine, and an on-demand TLS ask endpoint for Caddy.

import "github.com/fletchhq/domains"

resolver := domains.NewResolver(store)

mux.Handle("/_fletch/tls/ask", domains.AskHandler(resolver, domains.WithAskToken(token)))
handler := resolver.Middleware()(app)
  • Standalone: pure Go, CGO_ENABLED=0, depends only on golang.org/x/net. It works with any net/http router and is the custom-domain layer of Fletch.
  • Normalize turns user input into a canonical A-label host and rejects IPs, ports, wildcards, and bare public suffixes.
  • Resolver caches positive and negative lookups in bounded LRUs and coalesces misses.
  • Verifier and Lifecycle check the _fletch-verify TXT proof and DNS routing and move a domain through pending_dns, verified, active, degraded, and suspended.
  • AskHandler answers Caddy's on-demand TLS check and fails closed without a guard.
  • memstore and domainstest give you an in-memory store and a contract suite for your own Store.

See docs/domains.md for the guide, skills/domains/SKILL.md for agent guidance, and examples/multisite for a full Fletch app.

Development

GOWORK=off CGO_ENABLED=0 go test -race ./...
scripts/lint.sh   # golangci-lint v2.15.0

Docs & agent skills

When github.com/fletchhq/domains is in a Fletch app's go.mod, fletch ax sync and fletch docs automatically discover and sync its docs/ and skills/.

License

MIT or Apache-2.0, at your option. See LICENSE-MIT and LICENSE-APACHE.

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

View Source
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.

View Source
const AskTokenHeader = "X-Ship-Ask-Token"

AskTokenHeader is the header AskHandler reads the WithAskToken secret from. Ship's Caddy loopback site sets it.

View Source
const WellKnownPrefix = "/.well-known/fletch-domain/"

WellKnownPrefix is the path WellKnownHandler serves tokens under.

Variables

View Source
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

func AskHandler(r *Resolver, opts ...AskOption) http.Handler

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

func GenerateToken() (string, error)

GenerateToken returns a new ownership token: 128 random bits as lower-case base32 without padding.

func IsUnderZone

func IsUnderZone(host, zone string) bool

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

func Normalize(input string) (host string, apex bool, err error)

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

func WellKnownHandler(r *Resolver) http.Handler

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

func WithAllowHost(fn func(host string) bool) AskOption

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

func WithAskPeers(cidrs ...string) AskOption

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

func WithAskToken(token string) AskOption

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

func FromContext(ctx context.Context) (Domain, bool)

FromContext returns the domain Middleware attached to ctx.

func (Domain) Issuable

func (d Domain) Issuable() bool

Issuable reports whether a certificate may be issued for the domain.

func (Domain) Serving

func (d Domain) Serving() bool

Serving reports whether requests for the domain are served.

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

func (l Lifecycle) Claimed(d Domain, r Result, now time.Time) (Outcome, error)

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

func (l Lifecycle) HTTPSReady(d Domain, probeErr error, now time.Time) (Outcome, error)

HTTPSReady applies an HTTPS probe result to a verified domain: it becomes active when probeErr is nil.

func (Lifecycle) Rechecked

func (l Lifecycle) Rechecked(d Domain, r Result, now time.Time) (Outcome, error)

Rechecked applies a periodic routing check to an active or degraded domain. Only r.Routed counts.

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 Problem

type Problem struct {
	Code   string
	Detail string
}

Problem is one reason a check failed, for the tenant's setup screen.

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

func (r *Resolver) Invalidate(host string)

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

func (r *Resolver) Middleware(opts ...MiddlewareOption) func(http.Handler) http.Handler

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

func (r *Resolver) Resolve(ctx context.Context, host string) (Domain, error)

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

func DevAlwaysVerified(s Store) Store

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

func (v *Verifier) ProbeHTTPS(ctx context.Context, host string) error

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

func (v *Verifier) Verify(ctx context.Context, d Domain) Result

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.

type Writer

type Writer interface {
	Save(ctx context.Context, d Domain) error
}

Writer saves a domain, inserting or replacing the row for its Host. Jobs that verify domains need it; request serving does not.

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.

Jump to

Keyboard shortcuts

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