security

package
v0.3.0-alpha.1 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 10 Imported by: 8

README

gokit/security

TLS configuration, secure header policies, and test helpers for secure transport across gokit modules.

Overview

The security package provides:

  • TLSConfig for TLS 1.2+ transport policy, CA bundles, and mTLS
  • HeadersConfig for secure-by-default HTTP response headers

Configuration fields are tagged for YAML and mapstructure, so they integrate directly with gokit's config loading.

The locked transport policy is explicit:

  • minimum supported floor: TLS 1.2
  • default negotiation outcome: TLS 1.3 whenever both peers support it
  • explicit floors below TLS 1.2 are rejected during validation
  • secure headers default-on: HSTS, CSP, X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy

The companion tlstest sub-package generates self-signed certificates for integration tests — no external tools or fixtures required.

Installation

go get github.com/kbukum/gokit

security is part of the core module — no separate go get needed.

Quick Start

package main

import (
	"crypto/tls"
	"fmt"

	"github.com/kbukum/gokit/security"
)

func main() {
	cfg := security.TLSConfig{
		CAFile:     "/etc/certs/ca.pem",
		CertFile:   "/etc/certs/client.pem",
		KeyFile:    "/etc/certs/client-key.pem",
		ServerName: "api.example.com",
		MinVersion: tls.VersionTLS13,
	}

	if err := cfg.Validate(); err != nil {
		panic(err)
	}

	tlsConfig, err := cfg.Build()
	if err != nil {
		panic(err)
	}

	fmt.Println(tlsConfig != nil) // true
}

API Reference

TLSConfig
Field Type Description
SkipVerify bool Disable server certificate verification (not for production)
CAFile string Path to CA certificate PEM file
CertFile string Path to client certificate PEM (for mTLS)
KeyFile string Path to client private key PEM (for mTLS)
ServerName string Override server name for certificate verification (SNI)
MinVersion uint16 Minimum TLS version; defaults to TLS 1.2
HeadersConfig
Field Type Description
Disabled bool Disable response-header injection entirely
HSTSMaxAge time.Duration Strict-Transport-Security max-age
DisableHSTSIncludeSubdomains bool Omit includeSubDomains
DisableHSTSPreload bool Omit preload
ContentSecurityPolicy string Content-Security-Policy value
ReferrerPolicy string Referrer-Policy value
PermissionsPolicy string Permissions-Policy value
XFrameOptions string DENY or SAMEORIGIN
Methods
Method Description
Build() (*tls.Config, error) Creates a *tls.Config; returns nil if no settings are configured
Validate() error Checks that CertFile and KeyFile are both set or both empty
IsEnabled() bool Returns true if any TLS setting is configured
HeaderMap() (map[string]string, error) Builds the response-header policy
Apply(http.Header) error Applies headers to an HTTP response

Advanced Usage

Mutual TLS (mTLS)
cfg := security.TLSConfig{
	CAFile:   "/etc/certs/ca.pem",
	CertFile: "/etc/certs/client.pem",
	KeyFile:  "/etc/certs/client-key.pem",
}

tlsCfg, _ := cfg.Build()
// tlsCfg.Certificates contains the client cert
// tlsCfg.RootCAs contains the CA for server verification
Embedding in Service Config
tls:
  ca_file: /etc/certs/ca.pem
  cert_file: /etc/certs/client.pem
  key_file: /etc/certs/client-key.pem
  server_name: api.example.com
  min_version: 772  # tls.VersionTLS13
type KafkaConfig struct {
	Brokers []string          `yaml:"brokers"`
	TLS     security.TLSConfig `yaml:"tls"`
}
Testing with tlstest

The tlstest package generates ephemeral self-signed certificates for tests.

import "github.com/kbukum/gokit/security/tlstest"

func TestMTLS(t *testing.T) {
	certs := tlstest.GenerateTLSCerts(t)

	// Use generated file paths
	cfg := security.TLSConfig{
		CAFile:   certs.CAFile,
		CertFile: certs.CertFile,
		KeyFile:  certs.KeyFile,
	}

	tlsCfg, err := cfg.Build()
	require.NoError(t, err)
	require.NotNil(t, tlsCfg)

	// Or use the pre-built objects directly
	_ = certs.ServerTLS  // tls.Certificate
	_ = certs.CertPool   // *x509.CertPool
}

GenerateTLSCerts creates an ECDSA P-256 CA and server certificate valid for localhost, 127.0.0.1, and ::1. Files are written to t.TempDir() and cleaned up automatically.

Use WriteInvalidPEM(t, "bad.pem") to generate invalid certificate files for error-path testing.

Testing

cd security
go test -race ./...

Contributing

Please refer to the root CONTRIBUTING.md for guidelines.

Documentation

Overview

Package security provides shared security primitives for gokit modules.

It includes TLS configuration, certificate handling, and secure-by-default HTTP response header policies that can be reused across transports.

TLS Configuration

cfg := security.TLSConfig{
    CAFile:   "/path/to/ca.pem",
    CertFile: "/path/to/cert.pem",
    KeyFile:  "/path/to/key.pem",
}

tlsConfig, err := cfg.Build()

Index

Constants

View Source
const (
	// BasicAuthScheme is the HTTP "Basic" authentication scheme name.
	BasicAuthScheme = "Basic"

	// BearerAuthScheme is the HTTP "Bearer" authentication scheme name.
	BearerAuthScheme = "Bearer"
)

Shared HTTP authentication scheme names. These are the canonical spellings used in the Authorization / WWW-Authenticate headers, exposed here so transport middleware references one vocabulary instead of scattering string literals (e.g. server/middleware auth defaults to BearerAuthScheme).

Variables

This section is empty.

Functions

func EnforcePayloadLimit

func EnforcePayloadLimit(w http.ResponseWriter, r *http.Request, maxBytes int64) error

func ValidateLocalBind

func ValidateLocalBind(addr string) error

func ValidateOrigin

func ValidateOrigin(r *http.Request, allowed []string) error

Types

type HeadersConfig

type HeadersConfig struct {
	// Disabled turns off header injection entirely.
	Disabled bool `yaml:"disabled" mapstructure:"disabled"`

	// HSTSMaxAge controls the Strict-Transport-Security max-age value.
	HSTSMaxAge time.Duration `yaml:"hsts_max_age" mapstructure:"hsts_max_age"`

	// DisableHSTSIncludeSubdomains suppresses the includeSubDomains directive.
	DisableHSTSIncludeSubdomains bool `yaml:"disable_hsts_include_subdomains" mapstructure:"disable_hsts_include_subdomains"`

	// DisableHSTSPreload suppresses the preload directive.
	DisableHSTSPreload bool `yaml:"disable_hsts_preload" mapstructure:"disable_hsts_preload"`

	// ContentSecurityPolicy is written to the Content-Security-Policy header.
	ContentSecurityPolicy string `yaml:"content_security_policy" mapstructure:"content_security_policy"`

	// ReferrerPolicy is written to the Referrer-Policy header.
	ReferrerPolicy string `yaml:"referrer_policy" mapstructure:"referrer_policy"`

	// PermissionsPolicy is written to the Permissions-Policy header.
	PermissionsPolicy string `yaml:"permissions_policy" mapstructure:"permissions_policy"`

	// XFrameOptions is written to the X-Frame-Options header.
	XFrameOptions string `yaml:"x_frame_options" mapstructure:"x_frame_options"`
}

HeadersConfig configures secure-by-default HTTP response headers.

func (*HeadersConfig) Apply

func (c *HeadersConfig) Apply(header http.Header) error

Apply writes the configured security headers onto the provided response header map.

func (*HeadersConfig) ApplyDefaults

func (c *HeadersConfig) ApplyDefaults()

ApplyDefaults populates secure defaults.

func (*HeadersConfig) HeaderMap

func (c *HeadersConfig) HeaderMap() (map[string]string, error)

HeaderMap returns the configured security headers.

func (*HeadersConfig) Validate

func (c *HeadersConfig) Validate() error

Validate checks configuration consistency.

type TLSConfig

type TLSConfig struct {
	// SkipVerify disables server certificate verification. Not recommended for production.
	SkipVerify bool `yaml:"skip_verify" mapstructure:"skip_verify"`

	// CAFile is the path to the CA certificate file for verifying the server.
	CAFile string `yaml:"ca_file" mapstructure:"ca_file"`

	// CertFile is the path to the client TLS certificate file (for mTLS).
	CertFile string `yaml:"cert_file" mapstructure:"cert_file"`

	// KeyFile is the path to the client TLS key file (for mTLS).
	KeyFile string `yaml:"key_file" mapstructure:"key_file"`

	// ServerName overrides the server name used for certificate verification.
	ServerName string `yaml:"server_name" mapstructure:"server_name"`

	// MinVersion is the minimum TLS version (e.g., tls.VersionTLS12).
	// Defaults to a TLS 1.2 floor while allowing the runtime to negotiate TLS 1.3.
	MinVersion uint16 `yaml:"min_version" mapstructure:"min_version"`
}

TLSConfig holds TLS settings shared across gokit modules. Used by httpclient, grpc, kafka, discovery, and other transport layers.

func (*TLSConfig) Build

func (c *TLSConfig) Build() (*tls.Config, error)

Build creates a *tls.Config from the configuration. Returns (nil, nil) if no TLS settings are configured (all fields are zero values) — callers treat that as "no TLS" rather than a typed error.

this builder; making it a sentinel error would force every transport setup site to errors.Is for a non-error condition.

func (*TLSConfig) IsEnabled

func (c *TLSConfig) IsEnabled() bool

IsEnabled returns true if any TLS setting is configured.

func (*TLSConfig) Validate

func (c *TLSConfig) Validate() error

Validate checks that the TLS configuration is consistent.

type Verifier

type Verifier interface {
	Verify(ctx context.Context, payload []byte, signature []byte) error
}

type WarnOnlyVerifier

type WarnOnlyVerifier struct{}

func (WarnOnlyVerifier) Verify

Directories

Path Synopsis
Package tlstest generates throwaway TLS material for tests.
Package tlstest generates throwaway TLS material for tests.

Jump to

Keyboard shortcuts

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