devtls

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0, MIT Imports: 38 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.

Documentation

Overview

Package devtls is Fletch's local HTTPS for development: a local root CA and leaf certificates minted on demand, OS trust-store setup, a loopback DNS responder for a development TLD, a registry of linked sites, and an HTTPS reverse proxy in front of them. It uses only the standard library.

Nothing here is for production: the CA key lives unencrypted in the store's directory, readable only by its owner.

Index

Constants

View Source
const CAOrganization = "Fletch development CA"

CAOrganization names the CA's subject organization; trust-store tools find the CA by it.

View Source
const DashboardPrefix = "dashboard."

DashboardPrefix names a site's dev dashboard: dashboard.<site host>.

View Source
const DefaultDNSPort = 53535

DefaultDNSPort is where the fletch proxy's DNS responder listens.

View Source
const SystemKeychain = "/Library/Keychains/System.keychain"

SystemKeychain is the macOS keychain Fletch installs its CA in. Chromium reads local roots only from the admin and user trust-settings domains, so the certificate has to sit next to its admin trust settings here.

Variables

View Source
var ErrNeedsRoot = errors.New("devtls: root is needed")

ErrNeedsRoot is wrapped by DNSSetup errors for a file only root can write; the error text names the command to rerun with sudo.

Functions

func Answer

func Answer(query []byte, tld string, ttl uint32) []byte

Answer builds the response to one DNS query message, or returns nil for a message too short to answer. Names under tld get 127.0.0.1 for A and ::1 for AAAA (both for ANY) and an empty answer for other types; other names get REFUSED, since the OS sends only tld here.

func AppHosts

func AppHosts(app string) []string

AppHosts are the names a leaf for app covers: app.localhost and its subdomains, app.test and its subdomains, localhost, and the loopback addresses.

func CAFingerprint

func CAFingerprint(c *x509.Certificate) string

CAFingerprint is the CA certificate's SHA-1 in upper-case hex, as the macOS security tool prints it.

func DefaultDir

func DefaultDir() (string, error)

DefaultDir is $FLETCH_HOME, else ~/.fletch.

Types

type CommandRunner

type CommandRunner interface {
	Run(ctx context.Context, name string, args ...string) ([]byte, error)
}

CommandRunner runs one OS command and returns its combined output.

type DNSChange

type DNSChange struct {
	// Path is the file written or removed.
	Path string `json:"path"`
	// Content is the file's new content; empty when it is removed.
	Content string `json:"content,omitempty"`
	Removed bool   `json:"removed,omitempty"`
	// Changed is false when the file already said this.
	Changed bool `json:"changed"`
	DryRun  bool `json:"dry_run,omitempty"`
}

DNSChange is what Setup or Teardown changed, or would change.

type DNSServer

type DNSServer struct {
	// Addr is the UDP address to listen on, such as 127.0.0.1:53535.
	Addr string
	// TLD is the zone it answers for; empty means "test".
	TLD string
	// TTL of the answers in seconds; zero means 5.
	TTL uint32
	// contains filtered or unexported fields
}

DNSServer answers A and AAAA queries for every name under TLD with the loopback addresses, and refuses names outside it. It is a UDP server.

func (*DNSServer) Close

func (s *DNSServer) Close() error

Close stops the server.

func (*DNSServer) Start

func (s *DNSServer) Start() (net.Addr, error)

Start listens and answers in the background. It returns the address it listens on, so Addr may use port 0.

type DNSSetup

type DNSSetup struct {
	// GOOS picks the method; empty means runtime.GOOS.
	GOOS string
	// TLD is the development TLD; empty means "test".
	TLD string
	// Port is the DNS responder's port; zero means DefaultDNSPort.
	Port int
	// ResolverDir is macOS's resolver directory; empty means /etc/resolver.
	ResolverDir string
	// HostsFile is the hosts file; empty means the OS's own.
	HostsFile string
	// DryRun returns the change without writing it.
	DryRun bool
	// SudoCommand is the command a user reruns with sudo when a file
	// needs root, such as "fletch dns setup".
	SudoCommand string
}

DNSSetup points a development TLD at loopback. On macOS it writes /etc/resolver/<tld>, sending every name under the TLD to the DNS responder; elsewhere it keeps a fenced block of the linked sites in the hosts file, since a hosts file has no wildcards.

func (DNSSetup) Hosts

func (d DNSSetup) Hosts() string

Hosts is the hosts file Setup edits off macOS.

func (DNSSetup) ResolverFile

func (d DNSSetup) ResolverFile() string

ResolverFile is the macOS resolver file of the TLD.

func (DNSSetup) Setup

func (d DNSSetup) Setup(sites []Site) (DNSChange, error)

Setup points the TLD at loopback. sites are the hosts a hosts file lists; with a resolver they are not needed.

func (DNSSetup) Teardown

func (d DNSSetup) Teardown() (DNSChange, error)

Teardown undoes Setup: it removes the resolver file or the hosts-file block.

func (DNSSetup) UsesResolver

func (d DNSSetup) UsesResolver() bool

UsesResolver reports whether the OS takes a per-TLD resolver, so every name under the TLD works without listing sites.

type ExecRunner

type ExecRunner struct{}

ExecRunner runs commands with os/exec. Stdin is the terminal's, and sudo writes its password prompt to /dev/tty rather than stderr, so capturing the output for error messages does not hide the prompt.

func (ExecRunner) Run

func (ExecRunner) Run(ctx context.Context, name string, args ...string) ([]byte, error)

Run runs name with args and returns its combined output.

type ProxyAddrs

type ProxyAddrs struct {
	HTTP  net.Addr
	HTTPS net.Addr
	DNS   net.Addr
}

ProxyAddrs are the addresses a started proxy listens on.

type ProxyServer

type ProxyServer struct {
	Store *Store
	Sites SiteLookup
	// TLD of the sites; empty means "test".
	TLD string
	// HTTPAddr, HTTPSAddr, and DNSAddr are where to listen, such as 127.0.0.1:80,
	// 127.0.0.1:443, and 127.0.0.1:53535; port 0 picks a free port. An empty
	// HTTPAddr or DNSAddr turns that listener off.
	HTTPAddr  string
	HTTPSAddr string
	DNSAddr   string
	// ErrorLog receives proxy errors; nil means the log package.
	ErrorLog *log.Logger
	// contains filtered or unexported fields
}

ProxyServer is the local HTTPS front of linked sites: https://<name>.<tld> goes to the site's app and https://dashboard.<name>.<tld> to its dev dashboard, over TLS from Store. Plain HTTP is redirected to HTTPS, and a loopback DNS responder answers for the TLD.

func (*ProxyServer) Close

func (p *ProxyServer) Close() error

Close stops every listener and open connection.

func (*ProxyServer) Handler

func (p *ProxyServer) Handler() http.Handler

Handler routes HTTPS requests to linked sites. The app sees the public Host; the dashboard sees its own loopback Host, which its DNS-rebinding check needs, with the public one in X-Forwarded-Host. WebSocket upgrades pass through and responses stream unbuffered for server-sent events.

func (*ProxyServer) RedirectHandler

func (p *ProxyServer) RedirectHandler() http.Handler

RedirectHandler sends every plain HTTP request to the same host and path over HTTPS with 308, which keeps the method and body.

func (*ProxyServer) Start

func (p *ProxyServer) Start(ctx context.Context) (ProxyAddrs, error)

Start listens and serves in the background until ctx is done or Close.

func (*ProxyServer) URL

func (p *ProxyServer) URL(host string) string

URL is the public URL of host on this proxy.

type Registry

type Registry struct {
	Path string
	// TLD of the sites' hosts; empty means "test".
	TLD string
	// contains filtered or unexported fields
}

Registry is the JSON file of linked sites, <dir>/sites.json.

func NewRegistry

func NewRegistry(dir, tld string) *Registry

NewRegistry returns the registry in dir. It does no I/O.

func (r *Registry) Link(s Site) (Site, error)

Link adds s, or replaces the site with its name. Name must be one DNS label and the addresses loopback; Host is set from Name and the TLD.

func (*Registry) List

func (r *Registry) List() ([]Site, error)

List returns the linked sites sorted by name.

func (*Registry) Lookup

func (r *Registry) Lookup(host string) (Site, Target, bool)

Lookup finds the site a request host names: <name>.<tld> routes to the app and dashboard.<name>.<tld> to its dashboard. A host under a site, such as tenant.<name>.<tld>, routes to the site's app. A port is ignored.

func (r *Registry) Unlink(name string) (bool, error)

Unlink removes the named site and reports whether it was linked.

type Site

type Site struct {
	Name string `json:"name"`
	// Host is Name under the registry's TLD, such as shop.test.
	Host string `json:"host"`
	Dir  string `json:"dir,omitempty"`
	// AppAddr and DashAddr are the loopback host:port of the app and its
	// dev dashboard.
	AppAddr  string `json:"app_addr"`
	DashAddr string `json:"dash_addr,omitempty"`
	TLS      bool   `json:"tls"`
}

Site is one linked app.

type SiteLookup

type SiteLookup interface {
	Lookup(host string) (Site, Target, bool)
	List() ([]Site, error)
}

SiteLookup finds the site a request host names; *Registry implements it.

type Step

type Step struct {
	Name string   `json:"name"`
	Args []string `json:"args"`
	Sudo bool     `json:"sudo,omitempty"`
}

Step is one command of a plan. Sudo marks a command that needs root and is prefixed with sudo when the process is not root.

func (Step) String

func (s Step) String() string

String is the step as a shell command line.

type Store

type Store struct {
	Dir string
	// Now is the clock for validity windows; nil means time.Now.
	Now func() time.Time
	// contains filtered or unexported fields
}

Store keeps the local CA and the leaf certificates minted from it under Dir: ca/rootCA.pem, ca/rootCA-key.pem, and certs/.

func NewStore

func NewStore(dir string) *Store

NewStore returns a store rooted at dir. It does no I/O.

func (*Store) CAFile

func (s *Store) CAFile() string

CAFile is the path of the CA certificate in PEM.

func (*Store) CAKeyFile

func (s *Store) CAKeyFile() string

CAKeyFile is the path of the CA's private key in PEM.

func (*Store) EnsureCA

func (s *Store) EnsureCA() (*x509.Certificate, error)

EnsureCA loads the CA, creating it on first use. It is safe to call often.

func (*Store) MintCert

func (s *Store) MintCert(hosts ...string) (*tls.Certificate, error)

MintCert returns a leaf certificate for hosts signed by the CA, from the in-memory cache, then certs/ on disk, else newly minted and saved. A cached leaf is replaced when it is near expiry or was signed by another CA.

func (*Store) TLSConfig

func (s *Store) TLSConfig(defaultHosts ...string) *tls.Config

TLSConfig serves a leaf for each TLS server name: the defaultHosts leaf when a client sends none or a name it covers, else a leaf minted for that name. It mints only for localhost, *.localhost, *.test, loopback addresses, and names that defaultHosts covers, so a stray client cannot fill the store.

type Target

type Target string

Target is what a host routes to.

const (
	TargetApp       Target = "app"
	TargetDashboard Target = "dashboard"
)

The targets a linked host can route to.

type TrustStatus

type TrustStatus struct {
	Trusted bool   `json:"trusted"`
	Store   string `json:"store"`
	Detail  string `json:"detail,omitempty"`
}

TrustStatus says whether the CA is in the OS trust store.

type Truster

type Truster struct {
	Store *Store
	// GOOS picks the OS; empty means runtime.GOOS.
	GOOS string
	// Runner runs the commands; nil means ExecRunner.
	Runner CommandRunner
	// DryRun returns the plan without running it.
	DryRun bool
	// Root reports whether the process may change system files; nil means
	// the effective user is root.
	Root func() bool
	// Home is the user's home directory; empty means os.UserHomeDir.
	Home string
	// Exists reports whether a path exists; nil means os.Stat. Linux uses it
	// to tell Debian's anchor directory from Fedora's.
	Exists func(string) bool
}

Truster installs the store's CA in the OS trust store. Every OS change is a command run through Runner, so a test can record the commands of every OS without touching the machine it runs on.

func (*Truster) Status

func (t *Truster) Status(ctx context.Context) (TrustStatus, error)

Status reports whether the CA is in the trust store. It only reads.

func (*Truster) Trust

func (t *Truster) Trust(ctx context.Context) ([]Step, error)

Trust installs the CA, or with DryRun only returns the commands it would run. Commands that need root get a sudo prefix when the process is not root.

func (*Truster) TrustPlan

func (t *Truster) TrustPlan() ([]Step, error)

TrustPlan is the commands Trust runs on this OS. With DryRun it creates no CA: the plan names the file the CA would be written to.

func (*Truster) Untrust

func (t *Truster) Untrust(ctx context.Context) ([]Step, error)

Untrust removes the CA from the trust store, or plans it with DryRun.

func (*Truster) UntrustPlan

func (t *Truster) UntrustPlan(ctx context.Context) ([]Step, error)

UntrustPlan is the commands Untrust runs on this OS. It creates no CA; without one there is nothing of Fletch's to remove, except on Linux, where the anchor file is found by name. On macOS it first reads, without changing anything, which keychains hold the CA, so a CA left only in the login keychain by an older Fletch is removed without touching System.keychain.

Jump to

Keyboard shortcuts

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