tlsutils

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 21 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

go-tlsutils

CI Go Reference Go Report Card Release Go Version

import "github.com/altessa-s/go-tlsutils"

TLS certificate loading, OCSP stapling, certificate providers and SPIFFE Workload API helpers for Go services and libraries. Sources include files, S3, Vault PKI and Let's Encrypt. Keys are PKCS#8, PKCS#1 or SEC1. Server and client defaults are TLS 1.2+.

Packages read no configuration schema and report no metrics: callers configure them through options, and mapping configuration onto those options is left to the caller. OCSP refresh scheduling is the caller's job too. Register ocsp.Stapler.RefreshAllFunc and call MarkSchedulerManaged only after the scheduler accepts the task.

Requirements

Go 1.27 or later (go 1.27.0 in go.mod).

Packages

Package Description
tlsutils Certificate loading and TLS 1.2+ defaults
ocsp OCSP stapling with caching and refresh
providers Certificate provider port
providers/file File-based certificate loading
providers/letsencrypt Let's Encrypt ACME certificates
providers/s3 S3-backed certificate loading
providers/vault Vault PKI engine certificates
spiffe Rotating mTLS configs from the SPIFFE Workload API

Modules

providers/s3, providers/vault and spiffe are separate Go modules, so importing the root module never pulls in (or raises the version of) the AWS SDK, the Vault client, go-spiffe or gRPC. The import paths are unchanged; require each provider module you use alongside the root:

go get github.com/altessa-s/go-tlsutils                  # tlsutils, ocsp, providers, providers/file, providers/letsencrypt
go get github.com/altessa-s/go-tlsutils/providers/s3     # S3 provider
go get github.com/altessa-s/go-tlsutils/providers/vault  # Vault PKI provider
go get github.com/altessa-s/go-tlsutils/spiffe           # SPIFFE Workload API

Each module is tagged separately (v0.x.y for the root, providers/s3/v0.x.y, providers/vault/v0.x.y, spiffe/v0.x.y).

Functions

Function Description
LoadFromFile Load cert + key from separate files
LoadFromConcatenatedFile Load cert + key from a single PEM file
LoadFromBytes Load cert + key from PEM bytes
ParsePrivateKeyPEM Parse a standalone private signing key
ApplyMinTLSVersion Apply a YAML minVersion (1.2/1.3) to a server tls.Config; TLS 1.3 clears the 1.2 cipher list
ResolveMinTLSVersion Parse a minVersion string; ok=false for unknown input
DefaultTLSConfig Secure TLS 1.2+ server configuration
DefaultTLSConfigStrict TLS 1.3-only server configuration
DefaultClientTLSConfig Secure TLS 1.2+ client configuration
DefaultClientTLSConfigStrict TLS 1.3-only client configuration
ClientTLSConfig Strict client mTLS config presenting a cert from a provider
DialContext Dial a peer over mutual TLS using a client-cert provider
BuildCAPool Build certificate pool from CA files
CloneCertificateWithOCSPStaple Attach OCSP staple to certificate

Behaviour change: LoadFromBytes, LoadFromFile, LoadFromConcatenatedFile, and ParsePrivateKeyPEM now restrict encrypted PKCS#8 keys to the PBKDF2 and scrypt KDF allowlist. PBKDF2 allows 1 to 10,000,000 iterations; scrypt allows up to 1 GiB of memory (128*N*r). Scrypt requires power-of-two N from 2 through 1,048,576, r from 1 through 32, p from 1 through 16, and N*r*p <= 8,388,608 to bound CPU work. Unknown KDFs and excessive costs return ErrInvalidPrivateKey before decryption; keys previously accepted without these bounds may now be rejected.

Standalone signing keys

ParsePrivateKeyPEM(keyPEM, password) returns a crypto.Signer using the TLS loader's shared parsing path. It accepts PKCS#8 (RSA, ECDSA, Ed25519), PKCS#1 (RSA), SEC1 (ECDSA), encrypted PKCS#8 and legacy encrypted PEM. Use an empty password for unencrypted keys; a supplied password is ignored for those keys. Certificates and other non-key blocks are skipped. The first private key wins; an invalid first key fails even if a later key is valid.

Failures are *PrivateKeyError values. Use errors.Is with ErrInvalidPrivateKey, ErrPasswordRequired, or ErrIncorrectPassword. Incorrect-password detection follows the underlying decoders: unauthenticated encryption cannot reliably distinguish wrong passwords from corrupted ciphertext. Decrypted data that cannot be parsed returns ErrIncorrectPassword for both encryption formats. Error messages contain neither passwords nor key material.

Design principles

  • Minimal dependencies — the root module needs the Go standard library, go-atlas-core, youmark/pkcs8 (encrypted PKCS#8 keys), golang.org/x/crypto (ocsp, acme/autocert for Let's Encrypt) and fsnotify (file provider). The heavy SDKs live in their own modules: aws-sdk-go-v2 (providers/s3), hashicorp/vault/api, johanbrandhorst/certify and go-atlas-net (providers/vault), spiffe/go-spiffe/v2 and google.golang.org/grpc (spiffe).
  • No metrics, health or config schemas. Packages are configured through options; configuration mapping and telemetry belong to the caller.
  • SDKs stay inside the provider that needs them. The root package, ocsp and providers do not import AWS, Vault, ACME or SPIFFE.
  • Safe by default — DefaultTLSConfig is TLS 1.2+; the OCSP failure mode defaults to soft and hard mode is opt-in.
  • Thread-safe by default — exported functions and types are safe for concurrent use unless documented otherwise.

Development

Command Description
make test Run all tests
make lint Tidy, format and run golangci-lint with the repo config (.golangci.yml)
make generate Build the pinned optgen and golangci-lint into bin/ and run go generate
make bench Run all benchmarks

make generate builds optgen at the version pinned in devtools/go.mod into bin/optgen and runs it from there; nothing is installed into GOPATH and an optgen on PATH is not used. See CONTRIBUTING.md for every target.

Documentation

Overview

Package tlsutils provides TLS certificate loading and secure configuration utilities. Supports multiple certificate sources (file, Vault, Let's Encrypt), private key formats (PKCS#8, PKCS#1, SEC1), and enforces modern TLS 1.2+ defaults. ParsePrivateKeyPEM loads standalone signing keys using the same decryption and parsing path as TLS loading, including encrypted PKCS#8 and legacy PEM.

Example:

cert, _ := tlsutils.LoadFromFile("server.key", "server.crt", "password")
config := tlsutils.DefaultTLSConfig()
config.Certificates = []tls.Certificate{*cert}
caPool, _ := tlsutils.BuildCAPool(true, "custom-ca.crt")
config.RootCAs = caPool

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrIncorrectPassword = errors.New("incorrect private key password")

ErrIncorrectPassword indicates a decryption failure identified as an incorrect password. Unauthenticated encryption cannot distinguish all corrupt keys from incorrect passwords. It also indicates an encrypted payload that decrypts but cannot be parsed as a private key.

View Source
var ErrInvalidPrivateKey = errors.New("invalid private key")

ErrInvalidPrivateKey indicates missing, malformed, unsupported, or excessively costly private key data. For encrypted keys, a decrypted payload that cannot be parsed instead returns ErrIncorrectPassword: unauthenticated encryption cannot always distinguish a wrong password from a corrupt key.

View Source
var ErrPasswordRequired = errors.New("private key password required")

ErrPasswordRequired indicates an encrypted key was supplied without a password.

Functions

func ApplyMinTLSVersion

func ApplyMinTLSVersion(tlsConfig *tls.Config, raw string) error

ApplyMinTLSVersion resolves the YAML-supplied minVersion string into a tls.VersionTLSxx constant via ResolveMinTLSVersion and applies it to the provider-supplied tls.Config. When the operator pins TLS 1.3 the legacy 1.2 cipher list seeded by the provider is cleared so the resulting config matches DefaultTLSConfigStrict semantics — otherwise CipherSuites stays populated with 1.2-only entries that the stdlib silently ignores under TLS 1.3 and operators reading the config would assume those suites are still meaningful.

An empty minVersion (legacy callers, or YAML that omitted the field) is accepted as "leave the provider default in place"; any other unknown value is rejected so a typo (e.g. "v1.3") cannot silently fall back to the stdlib default.

func BuildCAPool

func BuildCAPool(system bool, caPath ...string) (*x509.CertPool, error)

BuildCAPool builds a certificate pool from CA certificate files. If a system is true, starts with the system's certificate pool. Additional CA certificates from caPath files are appended to the pool. Returns nil if no valid certificates are found.

Example:

pool, err := tlsutils.BuildCAPool(true, "ca1.crt", "ca2.crt")
if err != nil {
	log.Fatal(err)
}
config.RootCAs = pool

func ClientTLSConfig

func ClientTLSConfig(src clientCertificateSource, serverName string) *tls.Config

ClientTLSConfig builds a TLS 1.3 client configuration that presents a client certificate supplied by src on every handshake, for mutual TLS on outgoing connections. The certificate is pulled per handshake, so a rotating source (file watcher, Vault lease) is reflected without rebuilding the config. serverName is used for SNI and server-certificate verification against the system roots; set RootCAs on the returned config to pin a private CA.

Example:

cfg := tlsutils.ClientTLSConfig(provider, "peer.internal")
conn, err := tls.Dial("tcp", "peer.internal:8443", cfg)

func CloneCertificateWithOCSPStaple

func CloneCertificateWithOCSPStaple(cert *tls.Certificate, ocspStaple []byte) *tls.Certificate

CloneCertificateWithOCSPStaple creates a shallow copy of the certificate with the provided OCSP staple. This is useful when updating OCSP responses without modifying the original certificate.

func DefaultClientTLSConfig

func DefaultClientTLSConfig(serverName string) *tls.Config

DefaultClientTLSConfig returns a secure default TLS configuration for client connections. The configuration enforces TLS 1.2+ and sets the server name for certificate validation. The serverName parameter is used for SNI and certificate verification.

Example:

config := tlsutils.DefaultClientTLSConfig("example.com")
conn, err := tls.Dial("tcp", "example.com:443", config)

func DefaultClientTLSConfigStrict

func DefaultClientTLSConfigStrict(serverName string) *tls.Config

DefaultClientTLSConfigStrict is the client-side counterpart of DefaultTLSConfigStrict. Use when you control both endpoints and want to force TLS 1.3 across the wire.

func DefaultTLSConfig

func DefaultTLSConfig() *tls.Config

DefaultTLSConfig returns a secure default TLS configuration. The configuration enforces TLS 1.2+ and uses modern cipher suites. Suitable for most server applications requiring secure connections.

Example:

config := tlsutils.DefaultTLSConfig()
config.Certificates = []tls.Certificate{cert}
server := &http.Server{TLSConfig: config}

func DefaultTLSConfigStrict

func DefaultTLSConfigStrict() *tls.Config

DefaultTLSConfigStrict returns a server TLS configuration that requires TLS 1.3. Modern clients all support TLS 1.3; locking it as the minimum drops the long tail of weak suites the TLS 1.2 path allows and removes downgrade attack surface entirely. The CipherSuites field is intentionally left empty — for TLS 1.3 the stdlib enforces its own modern AEAD-only list and the TLS 1.2 pinned suites are ignored.

Example:

config := tlsutils.DefaultTLSConfigStrict()
config.Certificates = []tls.Certificate{cert}
server := &http.Server{TLSConfig: config}

func DialContext

func DialContext(ctx context.Context, network, addr string, src clientCertificateSource, serverName string) (net.Conn, error)

DialContext opens a mutual-TLS connection to addr, presenting the client certificate from src. It is a thin convenience over ClientTLSConfig and tls.Dialer. An empty serverName lets the dialer derive it from addr.

Example:

conn, err := tlsutils.DialContext(ctx, "tcp", "peer.internal:8443", provider, "")

func LoadFromBytes

func LoadFromBytes(certPem, keyPem []byte, keyPassword string) (*tls.Certificate, error)

LoadFromBytes loads a certificate and private key from raw PEM bytes. certPem may hold the full chain, leaf first; every certificate is kept. Certificates are read only from certPem and the private key only from keyPem. Supports multiple private key formats including PKCS#8, PKCS#1 (RSA), SEC1 (EC), and legacy-encrypted PEM formats. The keyPassword parameter is required for encrypted private keys and ignored for unencrypted keys.

Encrypted PKCS#8 keys follow the KDF allowlist and cost limits documented in ParsePrivateKeyPEM.

Example:

cert, err := tlsutils.LoadFromBytes(certPem, keyPem, "password")
if err != nil {
	log.Fatal(err)
}

func LoadFromConcatenatedFile

func LoadFromConcatenatedFile(certKeyFilePath, keyPassword string) (*tls.Certificate, error)

LoadFromConcatenatedFile loads a certificate and private key from a single file. The file should contain both the certificate and private key in PEM format; certificates after the leaf are kept as the chain. The keyPassword parameter is required for encrypted private keys.

Encrypted PKCS#8 keys follow the KDF allowlist and cost limits documented in ParsePrivateKeyPEM.

Example:

cert, err := tlsutils.LoadFromConcatenatedFile("server.pem", "password")
if err != nil {
	log.Fatal(err)
}

func LoadFromFile

func LoadFromFile(keyPath, certPath, keyPassword string) (*tls.Certificate, error)

LoadFromFile loads a certificate and private key from separate files. Supports multiple private key formats including PKCS#8, PKCS#1 (RSA), SEC1 (EC), and legacy-encrypted PEM formats. The keyPassword parameter is required for encrypted private keys and ignored for unencrypted keys.

Encrypted PKCS#8 keys follow the KDF allowlist and cost limits documented in ParsePrivateKeyPEM.

Example:

cert, err := tlsutils.LoadFromFile("server.key", "server.crt", "password")
if err != nil {
	log.Fatal(err)
}

func ParsePrivateKeyPEM added in v0.2.0

func ParsePrivateKeyPEM(pemData []byte, password string) (crypto.Signer, error)

ParsePrivateKeyPEM parses the first private key PEM block as a crypto.Signer. Certificates and other non-key blocks are skipped; missing or invalid keys return a *PrivateKeyError. Supported keys are Ed25519, ECDSA, and RSA in PKCS#8, PKCS#1, or SEC1 format, matching the TLS loading path. Password decrypts encrypted PKCS#8 and legacy encrypted PEM; it is ignored for unencrypted keys. An empty password is for unencrypted keys.

Encrypted PKCS#8 keys allow only PBKDF2 (1 to 10,000,000 iterations) and scrypt (128*N*r <= 1 GiB). Scrypt requires power-of-two N from 2 to 1,048,576, r from 1 to 32, p from 1 to 16, and N*r*p <= 8,388,608. Unsupported KDFs or excessive costs return ErrInvalidPrivateKey before decryption. These limits also apply to TLS loading and reject keys previously accepted without bounds.

Example
package main

import (
	"crypto/ed25519"
	"crypto/rand"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"log"

	tlsutils "github.com/altessa-s/go-tlsutils"
)

func main() {
	_, key, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		log.Fatal(err)
	}

	der, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		log.Fatal(err)
	}

	data := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der})

	signer, err := tlsutils.ParsePrivateKeyPEM(data, "")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%T\n", signer)
}
Output:
ed25519.PrivateKey

func ResolveMinTLSVersion

func ResolveMinTLSVersion(s string) (uint16, bool)

ResolveMinTLSVersion translates a human-readable version string ("1.2" / "1.3") into the corresponding tls.VersionTLSxx constant. Empty or unrecognized inputs return the safe default (tls.VersionTLS12) and report ok=false so callers can reject the config rather than silently accept a typo that would otherwise be ignored. Mirrors the project's safety-mode pattern of fail-safe-on-unknown.

Recognized values (case-insensitive, leading/trailing space trimmed):

Types

type OCSPStapler

type OCSPStapler interface {
	// GetOCSPStaple returns the OCSP staple for the given certificate.
	// The context controls the HTTP request timeout and cancellation.
	GetOCSPStaple(ctx context.Context, cert *tls.Certificate) ([]byte, error)
	// RunRefreshAll refreshes all OCSP responses in the cache that need it.
	// This method is designed to be called periodically via an external scheduler.
	RunRefreshAll(ctx context.Context) error
}

OCSPStapler defines the interface for OCSP stapling functionality. OCSP stapling improves TLS handshake performance by including certificate revocation status in the TLS handshake, reducing client-side OCSP requests.

type PrivateKeyError added in v0.2.0

type PrivateKeyError struct {
	Err error
}

PrivateKeyError describes a private key parsing failure. Unwrap exposes its sentinel cause for errors.Is: ErrInvalidPrivateKey, ErrIncorrectPassword, or ErrPasswordRequired. Messages never include key data or passwords.

func (*PrivateKeyError) Error added in v0.2.0

func (e *PrivateKeyError) Error() string

Error returns "parse private key", followed by the cause when there is one.

func (*PrivateKeyError) Unwrap added in v0.2.0

func (e *PrivateKeyError) Unwrap() error

Unwrap returns the parsing failure's cause.

Directories

Path Synopsis
internal
testhelpers
Package testhelpers holds the TLS test fixtures shared by the go-tlsutils packages: key generation, self-signed certificates, a test CA that signs leaves, and temporary PEM files.
Package testhelpers holds the TLS test fixtures shared by the go-tlsutils packages: key generation, self-signed certificates, a test CA that signs leaves, and temporary PEM files.
Package ocsp provides OCSP stapling for TLS certificates with caching.
Package ocsp provides OCSP stapling for TLS certificates with caching.
Package tlsproviders defines interfaces for TLS certificate providers.
Package tlsproviders defines interfaces for TLS certificate providers.
file
Package tlsfile provides file-based TLS certificate provider with optional automatic reloading.
Package tlsfile provides file-based TLS certificate provider with optional automatic reloading.
internal/certconfig
Package certconfig holds the reload steps shared by the TLS providers that load a certificate and republish it on change (file, S3): Build turns the loaded certificate into the server config to publish, with OCSP stapling installed before publication, and Notify signals a reload without blocking.
Package certconfig holds the reload steps shared by the TLS providers that load a certificate and republish it on change (file, S3): Build turns the loaded certificate into the server config to publish, with OCSP stapling installed before publication, and Notify signals a reload without blocking.
internal/staplertest
Package staplertest holds test doubles shared by the TLS provider tests: a CountingStapler that records OCSP staple requests and Handshake, which drives one in-memory TLS handshake against a server config so the config's GetCertificate callback runs with a real handshake context.
Package staplertest holds test doubles shared by the TLS provider tests: a CountingStapler that records OCSP staple requests and Handshake, which drives one in-memory TLS handshake against a server config so the config's GetCertificate callback runs with a real handshake context.
letsencrypt
Package tlsletsencrypt provides Let's Encrypt TLS certificate provider using HTTP-01 ACME challenges.
Package tlsletsencrypt provides Let's Encrypt TLS certificate provider using HTTP-01 ACME challenges.
s3 module
vault module
spiffe module

Jump to

Keyboard shortcuts

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