Help us shape the future of Go! Take the 2026 Go Developer Survey

ssl

package
v1.4.13 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrSudoRequired = errors.New("sudo required")

ErrSudoRequired is returned when an operation requires elevated privileges that are not currently available.

Functions

func AddHosts

func AddHosts(hostnames []string) (int, error)

AddHosts adds the given hostnames to /etc/hosts pointing to 127.0.0.1. Existing entries (with or without the nself-managed marker) are not duplicated. Each added line is tagged with "# nself-managed".

Returns ErrSudoRequired if the file cannot be written due to permissions. Wildcard entries (e.g. *.example.com) are skipped because /etc/hosts does not support wildcards.

AddHosts is the exported form for use by the dns-setup command.

func CertPairValid added in v1.4.13

func CertPairValid(dir string) bool

CertPairValid reports whether dir holds fullchain.pem and privkey.pem as regular files and the chain has at least minCertDays days left. Generation is skipped for such a pair; the build plan mode uses the same test to decide whether it would generate one.

func CheckCertExpiry

func CheckCertExpiry(certPath string) (int, error)

CheckCertExpiry reads the PEM-encoded x509 certificate at certPath, computes the number of days until it expires, and returns that count. If the certificate is already expired, it returns 0 and an error. If fewer than 30 days remain, a WARN is written to stderr and the remaining days are returned with a nil error.

func DiskCertFor added in v1.4.13

func DiskCertFor(sslDir, certPath string) (string, bool)

DiskCertFor maps a path under nginxtopo.NginxSSLContainerPath onto the same file in the served ssl dir; ok is false outside the mount or with a `$variable`.

func DomainToDirName added in v1.3.6

func DomainToDirName(domain string) string

DomainToDirName converts a domain to a directory-safe name by replacing dots with dashes. Exported so callers outside this package (cmd/commands' ssl_add.go) can assert their own domain-to-directory conversion agrees with this one instead of duplicating the literal replacement rule, which could silently diverge.

func IsCAInstalled

func IsCAInstalled(caPath string) (bool, error)

IsCAInstalled checks whether the mkcert CA certificate at caPath is already trusted by the OS trust store.

On macOS: queries the system keychain via `security find-certificate`. On Linux: checks whether the cert file is present in the system CA bundle dir. On Windows: queries certutil -store Root. Returns (false, nil) when caPath does not exist.

func ManualInstallCommand

func ManualInstallCommand(caPath string) string

ManualInstallCommand returns the platform-specific command string that the user can run manually to trust the CA, for use in fallback messages.

func MkcertCACertPath

func MkcertCACertPath() (string, error)

MkcertCACertPath returns the expected path to the mkcert root CA certificate.

func NeedsCerts added in v1.4.13

func NeedsCerts(sslMode string) bool

NeedsCerts reports whether sslMode makes nself generate local certificates. letsencrypt (certbot after first start), custom (user-supplied files) and none (HTTP only) skip generation. ssl.Generator and the build plan mode (internal/build planSSL) both call it so the skip rule lives once.

func PlanHostsEntries added in v1.4.13

func PlanHostsEntries(env, baseDomain string, explicitHosts bool, domains []string) []string

PlanHostsEntries returns the hostnames a build would ensure in /etc/hosts for the given domains, or nil when the gate vetoes hosts management.

Inputs: the resolved env, base domain, the --hosts opt-in and the collected certificate domains. Outputs: the filtered hostnames (what the generator would add or confirm). Constraints: pure, no filesystem or process access; plan mode (internal/build) uses it to record a hosts effect without touching the file.

func ServedAddr added in v1.4.13

func ServedAddr(env map[string]string) string

ServedAddr returns the "host:port" the served nginx accepts TLS on: port NGINX_HTTPS_PORT, else NGINX_SSL_PORT, else 443; host NGINX_BIND_IP unless empty or a wildcard address (0.0.0.0, ::), then 127.0.0.1.

func ServedEnv added in v1.4.13

func ServedEnv(root, fallbackEnv string) (map[string]string, error)

ServedEnv reads <root>/.env, then <root>/.env.<ENV> over it (ENV from that .env, else fallbackEnv, aliases applied) without touching the process environment. Missing files are fine; an unparsable one is an error.

func ServedHosts added in v1.4.13

func ServedHosts(nginxDir string) (map[string]string, error)

ServedHosts returns each host the nginx under nginxDir terminates TLS for, mapped to the ssl_certificate path of the SAME 443 server block ("" when it names none, e.g. via `include`; an http- or file-level one is inherited). Only sites/*.conf and conf.d/*.conf are read (SAN-only names land on the default server). Wildcards, regexes, IPs, localhost, `_` and .local, .localhost, .test names are dropped; the first block wins a duplicate. An unreadable file does not hide the others: hosts found come back with the joined read errors.

Types

type CertStatus added in v1.4.13

type CertStatus string

CertStatus is the verdict for a certificate's remaining lifetime.

const (
	// CertOK means the certificate has at least 21 days left.
	CertOK CertStatus = "ok"
	// CertWarn means fewer than 21 and at least 7 days are left.
	CertWarn CertStatus = "warn"
	// CertFail means fewer than 7 days are left, or the certificate expired.
	CertFail CertStatus = "fail"
)

CertStatus values returned by Classify.

func Classify added in v1.4.13

func Classify(days int) CertStatus

Classify maps whole days until expiry (negative once expired) to a status: CertFail when days < 7, CertWarn when days < 21, otherwise CertOK.

type GenerateResult

type GenerateResult struct {
	// Count is the number of certificate sets generated.
	Count int
	// CAInstalled is true when the mkcert CA was already trusted or was
	// successfully installed during this call.
	CAInstalled bool
	// CAManualCmd is non-empty when the CA could not be installed automatically.
	// It holds the command the user should run manually.
	CAManualCmd string
	// HostsAdded is the number of new /etc/hosts entries written.
	HostsAdded int
	// HostsManualNote is non-empty when the hosts file could not be written.
	HostsManualNote string
}

GenerateResult holds the output of a Generate call including trust/hosts status.

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator creates SSL certificates for all domains in the project configuration.

func NewGenerator

func NewGenerator(cfg *config.Config) *Generator

NewGenerator creates an SSL Generator from the given config.

func (*Generator) CollectDomains

func (g *Generator) CollectDomains() []string

CollectDomains gathers all Subject Alternative Names (SANs) needed for the project's SSL certificate. The list is deduplicated. It is exported for use by the dns-setup command.

func (*Generator) Generate

func (g *Generator) Generate(outputDir string) (int, error)

Generate creates SSL certificates for all collected domains. Certificates are written to outputDir/certificates/{dir}/fullchain.pem and privkey.pem. Returns the count of certificate sets generated.

func (*Generator) GenerateWithResult

func (g *Generator) GenerateWithResult(outputDir string) (*GenerateResult, error)

GenerateWithResult creates SSL certificates and returns detailed results including the CA trust and /etc/hosts steps.

When SSL_MODE is "letsencrypt", "custom", or "none", local certificate generation is skipped. In letsencrypt mode, certbot provisions the real certs after the stack starts. In custom mode, the user supplies their own certs. In none mode, SSL is disabled entirely. Nginx must be configured to start without SSL cert references in these modes — see nginx/generator.go.

func (*Generator) WithExplicitHosts added in v1.4.4

func (g *Generator) WithExplicitHosts(v bool) *Generator

WithExplicitHosts marks that the operator explicitly requested /etc/hosts management for this build (the --hosts flag), overriding shouldManageHosts's local-dev-domain heuristic for an unrecognized domain shape. It never overrides the cfg.Env=="prod" veto. Returns g for chaining, matching the WithWorkDir convention used elsewhere in this CLI (e.g. compose.NewGeneratorWithProfile(...).WithWorkDir(...)).

type KnownCert added in v1.4.13

type KnownCert struct {
	Path     string
	NotAfter time.Time
	SHA256   string
	// contains filtered or unexported fields
}

KnownCert is the leaf of a certificate file: its path, expiry and DER SHA-256 (hex).

func NewestKnownCert added in v1.4.13

func NewestKnownCert(sslDir, host, letsencryptDir string) (KnownCert, bool)

NewestKnownCert returns the certificate covering host (SANs, wildcards included; expiry ignored) with the latest expiry among <sslDir>/.acme/certificates/*.crt and <letsencryptDir>/live/*/cert.pem. Unreadable files (certbot's live dir is often root-only) are skipped.

func ReadDiskCert added in v1.4.13

func ReadDiskCert(p string) (KnownCert, error)

ReadDiskCert reads the leaf (first certificate) of the PEM file p.

type ServedCert added in v1.4.13

type ServedCert struct {
	// Host is the name the probe asked for: sni, or the host of addr when sni is empty.
	Host string
	// IssuerCN is the leaf's issuer common name.
	IssuerCN string
	// NotAfter is the leaf's expiry instant.
	NotAfter time.Time
	// SHA256 is the lowercase hex SHA-256 of the leaf's DER bytes.
	SHA256 string
	// DNSNames are the leaf's subject alternative DNS names.
	DNSNames []string
	// ChainErr is the chain/hostname verification error, "" when the leaf
	// verified against the system roots for sni.
	ChainErr string
}

ServedCert describes the leaf certificate an endpoint served for one SNI.

func ProbeServed added in v1.4.13

func ProbeServed(ctx context.Context, addr, sni string, timeout time.Duration) (ServedCert, error)

ProbeServed dials addr, presents sni, and returns the leaf certificate the endpoint serves. The handshake uses InsecureSkipVerify so the leaf can be inspected even when it is untrusted or expired; the chain is then verified separately against the system roots (x509.VerifyOptions{DNSName: sni, Intermediates: the rest of the served chain}) and any failure, hostname mismatch included, is returned in ServedCert.ChainErr. A dial, handshake or empty-chain failure returns an error.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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