tls

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 5 Imported by: 0

README

tls

Hardened, opinionated TLS plumbing for Go — a curated default config, typed cert pairs, and server/client builders

Go Reference Pipeline Coverage phpboyscout Go toolkit

Part of the phpboyscout Go toolkit — small, framework-free Go modules extracted from go-tool-base. Docs: tls.go.phpboyscout.uk


gitlab.com/phpboyscout/go/tls — small, hardened TLS plumbing for Go servers and clients. It gives you one opinionated, secure *crypto/tls.Config (TLS 1.2 floor, AEAD-only cipher suites, modern curve preferences), a typed Pair for the enabled/cert/key triple, ServerConfig/ClientConfig builders, and a CertPool helper for trusting private CAs.

It is the same TLS posture behind go-tool-base's HTTP, gRPC and gateway transports, extracted so any project can adopt it without pulling in the framework.

Design

  • Framework-free. The only external dependency is cockroachdb/errors. No config framework, no TUI, no OpenTelemetry, no go-tool-base. A depfootprint_test.go guard enforces it.
  • Typed values in, hardened config out. The package works entirely from typed Pair values — you own how those are sourced (flags, env, a config file). ResolvePair merges a shared pair against per-transport overrides so one certificate can serve many listeners.
  • Secure by default. DefaultConfig fixes a TLS 1.2 minimum, six curated ECDHE-AEAD cipher suites, and X25519/P-256 curve preferences — the same config underpins both the server and client builders.

Install

go get gitlab.com/phpboyscout/go/tls

Quick start

package main

import (
	"net/http"

	"gitlab.com/phpboyscout/go/tls"
)

func main() {
	pair := tls.Pair{Enabled: true, Cert: "/etc/certs/server.pem", Key: "/etc/certs/server-key.pem"}

	cfg, err := pair.ServerConfig("h2", "http/1.1") // hardened defaults + ALPN
	if err != nil {
		panic(err)
	}

	srv := &http.Server{Addr: ":8443", TLSConfig: cfg}
	_ = srv.ListenAndServeTLS("", "") // certs already loaded into TLSConfig
}

Client side, trusting a private CA:

clientCfg, err := tls.ClientConfig("/etc/certs/ca.pem") // or no args to trust system roots

Key concepts

  • DefaultConfig — the shared hardened *crypto/tls.Config (TLS 1.2 floor, AEAD cipher suites, modern curves). The foundation for both builders.
  • Pair — the typed {Enabled, Cert, Key} triple. Valid reports whether TLS is on and both paths are set; Certificate loads the X509 key pair; ServerConfig returns the hardened config with the certificate loaded (optionally advertising ALPN protocols).
  • ResolvePair — pure per-field merge of a shared Pair with a per-transport Pair, driven by a PairOverrides mask. Lets one cert serve multiple transports with targeted overrides, with no dependency on any config lookup interface.
  • ClientConfig / CertPool — a hardened client config trusting either the system roots or an explicit set of PEM CA files.

Documentation

Full guides and the security threat model: tls.go.phpboyscout.uk. API reference: pkg.go.dev.

License

See LICENSE.

Documentation

Overview

Package tls provides hardened, opinionated TLS plumbing for Go servers and clients: a curated default crypto/tls.Config (TLS 1.2 floor, AEAD cipher suites, modern curve preferences), the typed Pair shape (enabled/cert/key plus the client-CA fields for server-side mTLS) with a pure per-field merge (ResolvePair), the Pair.ServerConfig and ClientConfig builders, the Pair.ApplyTo merge into a caller-owned config, and the CertPool helper for trusting private CAs.

The package is framework-free: it works entirely from typed Pair values, so callers own how those values are sourced (flags, environment, a config file). A single certificate can serve multiple transports by resolving a shared Pair against per-transport overrides with ResolvePair.

Index

Examples

Constants

View Source
const (
	// ClientAuthRequest asks the client for a certificate but neither
	// requires nor verifies one (tls.RequestClientCert).
	ClientAuthRequest = "request"

	// ClientAuthVerifyIfGiven does not require a client certificate, but
	// verifies any that is presented against ClientCAs
	// (tls.VerifyClientCertIfGiven) — useful for mixed-auth listeners.
	ClientAuthVerifyIfGiven = "verify-if-given"

	// ClientAuthRequireVerify requires a client certificate chaining to
	// ClientCAs (tls.RequireAndVerifyClientCert). This is the mode implied
	// when ClientCAs is set and ClientAuth is empty.
	ClientAuthRequireVerify = "require-verify"
)

Client-certificate enforcement modes accepted by Pair.ClientAuth. Any other non-empty value is rejected (fail closed).

Variables

This section is empty.

Functions

func CertPool

func CertPool(caFiles ...string) (*x509.CertPool, error)

CertPool builds an x509 certificate pool seeded with the given PEM CA/cert files, so clients can trust certificates that are not in the system roots (self-signed or private CA). Pass the same cert files the servers present to share one trust anchor across gRPC, HTTP and the gateway.

func ClientConfig

func ClientConfig(caFiles ...string) (*cryptotls.Config, error)

ClientConfig returns a hardened client TLS config (DefaultConfig) that trusts the given CA/cert files via a custom pool. With no files it returns the default config, which trusts the system roots.

func DefaultConfig

func DefaultConfig() *cryptotls.Config

DefaultConfig returns the hardened TLS configuration shared across HTTP and gRPC servers and the HTTP client. It enforces TLS 1.2 minimum with curated AEAD cipher suites and modern curve preferences.

Example
package main

import (
	"fmt"

	"gitlab.com/phpboyscout/go/tls"
)

func main() {
	// DefaultConfig returns the shared hardened TLS configuration used by the
	// HTTP, gRPC and gateway transports.
	cfg := tls.DefaultConfig()

	fmt.Println("Min TLS version:", cfg.MinVersion)
	fmt.Println("Cipher suites:", len(cfg.CipherSuites))
}
Output:
Min TLS version: 771
Cipher suites: 6

Types

type Pair

type Pair struct {
	Enabled bool   `mapstructure:"enabled" yaml:"enabled" json:"enabled"`
	Cert    string `mapstructure:"cert"    yaml:"cert"    json:"cert"`
	Key     string `mapstructure:"key"     yaml:"key"     json:"key"`

	// ClientCAs lists PEM CA/cert files client certificates must chain to.
	// Empty means no client-certificate auth (unless ClientAuth is set).
	ClientCAs []string `mapstructure:"client_cas" yaml:"client_cas" json:"client_cas"`

	// ClientAuth selects the client-certificate mode: "" (none, unless
	// ClientCAs is set — then require-verify), "request", "verify-if-given"
	// or "require-verify". Any other value is a hard error (fail closed).
	ClientAuth string `mapstructure:"client_auth" yaml:"client_auth" json:"client_auth"`
}

Pair is the typed TLS settings block used to configure TLS for any transport. It carries struct tags so the same shape marshals to and from config consistently wherever it is used.

Beyond the enabled/cert/key triple, the optional client-CA fields drive server-side mTLS: ClientCAs lists PEM CA files that client certificates must chain to, and ClientAuth selects the enforcement mode (see the ClientAuth* constants). Both are consumed by ServerConfig/ApplyTo; an empty ClientCAs with an empty ClientAuth means no client-certificate auth, preserving the zero-value behaviour.

func ResolvePair

func ResolvePair(shared Pair, transport Pair, overrides PairOverrides) Pair

ResolvePair resolves TLS settings from already-materialised typed values. It starts from the shared pair and overrides individual fields when the transport section explicitly supplied them.

func (Pair) ApplyTo added in v0.1.2

func (p Pair) ApplyTo(cfg *cryptotls.Config, nextProtos ...string) error

ApplyTo merges this pair into a caller-supplied server TLS config instead of replacing it: the pair's certificate is appended to cfg.Certificates, each of nextProtos is appended to cfg.NextProtos unless already advertised, and the pair's client-CA policy (ClientCAs/ClientAuth) is applied only when cfg does not already carry one.

Precedence: everything the caller set on cfg survives. In particular, when cfg already has a non-nil ClientCAs pool or a ClientAuth other than tls.NoClientCert, the caller's client-certificate policy wins and the pair's ClientCAs/ClientAuth fields are ignored — though an invalid ClientAuth value still errors, so a typo never silently disables mTLS.

func (Pair) Certificate

func (p Pair) Certificate() (cryptotls.Certificate, error)

Certificate loads the X509 key pair described by the pair.

func (Pair) ServerConfig

func (p Pair) ServerConfig(nextProtos ...string) (*cryptotls.Config, error)

ServerConfig returns the hardened DefaultConfig with this pair's certificate loaded and its client-CA policy (if any) applied. Pass nextProtos to advertise ALPN protocols (e.g. "h2" for a raw gRPC TLS listener); when empty the config's defaults are left as-is.

func (Pair) Valid

func (p Pair) Valid() bool

Valid reports whether TLS is enabled and both certificate paths are present.

type PairOverrides

type PairOverrides struct {
	Enabled    bool
	Cert       bool
	Key        bool
	ClientCAs  bool
	ClientAuth bool
}

PairOverrides records which fields a transport-specific TLS section set. ResolvePair uses it to merge per-transport config without requiring a config lookup interface.

Jump to

Keyboard shortcuts

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