netsec

package
v0.81.12 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 15 Imported by: 3 modules, 21 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 netsec provides centralized network security primitives used by every HTTP-based provider in SpeechKit (STT, TTS, LLM, downloads).

It addresses the audit findings S1-S5 (2026-04-16):

  • SSRF via unvalidated user-supplied BaseURL configuration
  • Missing TLS hardening on HTTP clients
  • Bearer tokens leaking through default loggers

All HTTP provider constructors MUST route user-supplied URLs through ValidateProviderURL and MUST obtain their *http.Client via NewSafeHTTPClient.

Stability: Stable — no breaking change without a minor version bump and a changelog callout.

Index

Constants

View Source
const RedactedHeadersKey ctxKey = 1

RedactedHeadersKey is the context key used to store redacted headers.

Variables

View Source
var (
	ErrEmptyURL          = errors.New("netsec: empty URL")
	ErrInvalidURL        = errors.New("netsec: URL could not be parsed")
	ErrMissingScheme     = errors.New("netsec: URL must have a scheme")
	ErrMissingHost       = errors.New("netsec: URL must have a host")
	ErrUnsupportedScheme = errors.New("netsec: scheme must be http or https")
	ErrInsecureHTTP      = errors.New("netsec: plain http:// not allowed for this host")
	ErrLoopbackBlocked   = errors.New("netsec: loopback addresses not allowed")
	ErrPrivateBlocked    = errors.New("netsec: private / link-local / ULA addresses not allowed")
	ErrPublicBlocked     = errors.New("netsec: public addresses not allowed for a local-only endpoint")
	ErrInvalidHost       = errors.New("netsec: URL host could not be resolved as a literal IP or name")
	ErrUserInfoForbidden = errors.New("netsec: URL user-info (user:pass@) is not permitted")
)

Validation errors. Callers can match on these with errors.Is for UX.

Functions

func BindBootProfile added in v0.78.4

func BindBootProfile() error

BindBootProfile resolves the canonical edition/profile once, before credentials, clients or probes. A bad explicit edition is an error even though the canonical legacy Resolve helper defaults unknown editions to OSS. A failed bind stays failed for the process lifetime; changing the environment cannot loosen it.

func BuildEndpoint

func BuildEndpoint(baseURL, path string, opts ValidationOptions) (string, error)

BuildEndpoint validates baseURL and joins path safely. It prevents a malicious baseURL like "https://legit.example.com/.." from escaping the host, and normalises trailing slashes.

func Configure added in v0.76.6

func Configure(p Policy)

Configure installs the process-wide egress policy. The host calls it at start and again whenever the network scope changes; guarded clients built earlier pick the new policy up on their next dial. Configure(Policy{}) restores the unrestricted default.

func DataProfileEU added in v0.79.15

func DataProfileEU(ctx context.Context) bool

func Default added in v0.76.6

func Default() *http.Client

Default returns the shared guarded client (30 second timeout). Callers must not modify it; use NewClient for a different timeout.

func DialContext added in v0.76.6

func DialContext(ctx context.Context, network, address string) (net.Conn, error)

DialContext opens a raw connection through the same guard as the HTTP clients: the address is validated under the active Policy before the socket opens, and a refused address returns a netsec error without dialing.

func EUVoiceClient added in v0.79.15

func EUVoiceClient(client *http.Client) *http.Client

func EUVoiceProfileError added in v0.79.15

func EUVoiceProfileError(ctx context.Context) error

func FullLocal added in v0.78.4

func FullLocal() bool

FullLocal reports the bound ceiling. It never rereads mutable environment or configuration. SDK users that do not bind a deployment profile retain their existing network policy.

func NewClient added in v0.76.6

func NewClient(opts ClientOptions) *http.Client

NewClient returns an *http.Client with explicit TLS 1.2+ minimum, sensible timeouts, dial-target validation, and a transport wrapper that stores redacted request headers in context for logging paths that opt in.

Every dial is checked at dial time against the process-wide Policy installed by Configure (so a client built before Configure is still bound by it) and, when set, against opts.DialValidation as well; both must pass. While either is active the environment proxy is ignored, because a proxy resolves the target outside this process.

The client is safe to share across goroutines.

func NewSafeHTTPClient

func NewSafeHTTPClient(opts ClientOptions) *http.Client

NewSafeHTTPClient is the original name of NewClient and behaves the same.

func ProviderStatusError

func ProviderStatusError(provider string, status int, body []byte) error

ProviderStatusError returns a user-safe upstream provider error. It keeps the provider name and HTTP status, but never includes the raw response body.

func RedactBearer

func RedactBearer(value string) string

RedactBearer returns a safe rendering of an "Authorization: Bearer xxx" header value for logs. It always returns "Bearer [REDACTED]" when the input is non-empty, and "" otherwise.

func RedactHeaders

func RedactHeaders(h http.Header) http.Header

RedactHeaders returns a copy of h where sensitive header values are replaced with the literal "[REDACTED]". Safe for logging.

func RedactURLError added in v0.74.0

func RedactURLError(err error) error

RedactURLError scrubs credentials from URLs carried by err so the error can be logged or shown to a user. net/http strips a userinfo password from a *url.Error, but not a query parameter such as ?key=, ?sig= or ?access_token=.

Every *url.Error reachable through Unwrap() error / Unwrap() []error has its URL rewritten in place (http.Client returns a fresh one per request, so the caller owns it). Wrappers created with fmt.Errorf have already rendered their message, so when err.Error() still contains a URL query, fragment or userinfo, the result is a wrapper whose Error() is scrubbed and whose Unwrap() returns err, keeping errors.Is and errors.As working. Scheme, host and path stay for diagnostics.

func RegisterPolicyGuard added in v0.78.4

func RegisterPolicyGuard(f func(Policy))

RegisterPolicyGuard installs an in-process kernel-policy consumer. Guards run synchronously before Configure publishes the policy to network clients.

func SafeProviderErrorReason

func SafeProviderErrorReason(status int, body []byte) string

SafeProviderErrorReason classifies a provider response body without exposing body contents to UI, logs, or higher-level error messages.

func ValidateProviderURL

func ValidateProviderURL(raw string, opts ValidationOptions) error

ValidateProviderURL parses raw and rejects URLs that would expose the caller to SSRF. It does not make network calls — hostnames that are not IP literals are checked by NewSafeHTTPClient when DialValidation is set. Provider, download and update clients should combine URL validation with resolve-time dial validation.

func ValidateResolvedIP

func ValidateResolvedIP(ip net.IP, opts ValidationOptions) error

ValidateResolvedIP applies SSRF range restrictions to a concrete IP address returned by DNS resolution or visible on a dial target.

func WithPolicy added in v0.78.4

func WithPolicy(f func(Policy) error) error

WithPolicy serializes a native launch with policy changes. The callback must not call Configure. It receives the same policy the next Go dial will use.

Types

type BootFacts added in v0.78.4

type BootFacts struct {
	Edition string              `json:"edition"`
	Profile dataprofile.Profile `json:"data_profile"`
}

BootFacts is the immutable process profile, suitable for configuration readback.

func BoundBootFacts added in v0.78.4

func BoundBootFacts() (BootFacts, error)

BoundBootFacts returns a value copy, never the binding itself.

type ClientOptions

type ClientOptions struct {
	// Timeout is the per-request timeout. Zero disables it (discouraged).
	Timeout time.Duration

	// TLSMinVersion pins the minimum TLS version (default: tls.VersionTLS12).
	TLSMinVersion uint16

	// TLSConfig supplies caller-owned CA and client certificates. The transport
	// clones it before applying the default minimum TLS version.
	TLSConfig *tls.Config

	// InnerTransport, if non-nil, is wrapped by the RedactingRoundTripper.
	// Normally nil — the function constructs a hardened *http.Transport.
	// Full Local additionally guards a clone of a concrete *http.Transport
	// and refuses opaque transports whose dial cannot be admitted.
	InnerTransport http.RoundTripper

	// DisableKeepAlives turns off connection reuse. Leave false for best perf.
	DisableKeepAlives bool

	// DialValidation, when non-nil, validates the actual resolved target IP
	// before opening a TCP connection. Use this for any client that might reach
	// user-configurable provider, model download, or update URLs.
	DialValidation *ValidationOptions

	// SetupTraffic marks a client that carries only setup traffic (model
	// downloads and update checks; no audio, transcripts, prompts or
	// credentials). While [Policy.AllowSetupTraffic] is true such a client is
	// not bound by [Policy.Validation]; DialValidation still applies.
	// The immutable Full Local ceiling has no setup-traffic exception.
	SetupTraffic bool
}

ClientOptions configures a SpeechKit HTTP client.

type Policy added in v0.76.6

type Policy struct {
	// Validation, when non-nil, must pass for every dialed IP and every
	// redirect target of every guarded client. A host derives it from its
	// resolved network scope (see speechkit.NetworkScope.EgressPolicy).
	Validation *ValidationOptions

	// AllowSetupTraffic lets clients marked [ClientOptions.SetupTraffic] (model
	// downloads, update checks) skip Validation. A host sets it from the
	// scope's explicit setup-traffic opt-in.
	AllowSetupTraffic bool
}

Policy is the process-wide egress rule every client from NewClient and every DialContext dial is bound by. The zero value is unrestricted (the open network scope): call sites keep their own endpoint validation.

func CurrentPolicy added in v0.76.6

func CurrentPolicy() Policy

CurrentPolicy returns the policy installed by Configure.

func (Policy) AllowsPublicEgress added in v0.76.6

func (p Policy) AllowsPublicEgress() bool

AllowsPublicEgress reports whether a dial to a public address can succeed under this policy. A host uses it to skip work that only makes sense with internet access, such as a connectivity probe.

type RedactingRoundTripper

type RedactingRoundTripper struct {
	Base http.RoundTripper
}

RedactingRoundTripper is an http.RoundTripper that records redacted copies of the outgoing request header set on the *http.Request context so that downstream logging middleware can inspect non-sensitive headers only.

It does NOT rewrite the outgoing request — the real Authorization header is sent over TLS as expected. Redaction applies only to what observability paths can access via ctx.Value(RedactedHeadersKey).

func (*RedactingRoundTripper) RoundTrip

func (r *RedactingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type ValidationOptions

type ValidationOptions struct {
	// AllowLoopback permits http:// and https:// URLs whose host is a
	// literal loopback address (127.0.0.0/8, ::1, or the name "localhost").
	// Enable for local whisper-server / Ollama / dev endpoints.
	AllowLoopback bool

	// AllowPrivate permits URLs whose host is in RFC1918 / RFC6598 /
	// link-local / unique-local IPv6 ranges. Enable only for self-hosted
	// VPS scenarios where the user explicitly opts in.
	AllowPrivate bool

	// AllowHTTP permits http:// for non-loopback hosts. Leave false unless
	// an operator has a documented reason (e.g. test harness).
	AllowHTTP bool

	// RequireLocal rejects every public IP address, including public
	// addresses returned by DNS after the URL passed syntactic validation.
	// Combine it with AllowLoopback, AllowPrivate, and (when needed) AllowHTTP
	// for LAN-only bridges such as a local Home Assistant instance. The zero
	// value remains provider-oriented and permits public HTTPS endpoints.
	RequireLocal bool
}

ValidationOptions controls how strict URL validation behaves. The zero value is the safe default: HTTPS-only, no loopback, no private IPs.

Jump to

Keyboard shortcuts

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