remote

package
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Overview

Package remote provides remote config fetch with optional authenticated decryption.

Index

Constants

View Source
const (
	// EnvelopeVersionV2 is the only supported envelope version for the v2 format.
	EnvelopeVersionV2 = "warden-remote-envelope-v2"
	// KeyAlgRSAOAEP256 identifies RSA-OAEP with SHA-256 for key wrapping.
	KeyAlgRSAOAEP256 = "RSA-OAEP-256"
	// ContentAlgA256GCM identifies AES-256-GCM for content encryption.
	ContentAlgA256GCM = "A256GCM"
)

Envelope v2 constants. The envelope is an authenticated, versioned JSON container.

Layout (JSON object, RawURL base64 for binary fields):

{
  "version":     "warden-remote-envelope-v2",
  "key_id":      "<opaque key identifier>",
  "key_alg":     "RSA-OAEP-256",
  "content_alg": "A256GCM",
  "enc_key":     "<base64url RSA-OAEP-SHA256(content_key)>",
  "nonce":       "<base64url GCM nonce>",
  "ciphertext":  "<base64url GCM seal output, ciphertext||tag>"
}

Integrity is provided by AES-256-GCM. The AAD binds the metadata (version|key_id|key_alg|content_alg) so an attacker cannot swap algorithms or key ids without invalidating the tag.

View Source
const (
	// EncryptedContentType is the Content-Type value advertised for encrypted envelopes.
	// It is used only as an additional consistency signal and NEVER to decide whether the
	// body must be treated as encrypted (that decision comes from EncryptionFormat/Required).
	EncryptedContentType = "application/x-warden-encrypted"
)

Variables

View Source
var (
	// ErrEncryptionRequired is returned when encryption is required by policy but the
	// response was not a valid v2 envelope (e.g. plaintext downgrade attempt).
	ErrEncryptionRequired = errors.New("remote: encryption required but response is not an encrypted envelope")
	// ErrUnsupportedEnvelopeVersion is returned for an unknown envelope version.
	ErrUnsupportedEnvelopeVersion = errors.New("remote: unsupported envelope version")
	// ErrUnsupportedAlgorithm is returned for an unknown key_alg or content_alg.
	ErrUnsupportedAlgorithm = errors.New("remote: unsupported envelope algorithm")
	// ErrIntegrityCheckFailed is returned when authenticated decryption fails
	// (tampered ciphertext, nonce, tag, metadata, or wrong key).
	ErrIntegrityCheckFailed = errors.New("remote: envelope integrity check failed")
	// ErrEnvelopeMalformed is returned for structurally invalid envelopes
	// (bad JSON, bad base64, oversized input, trailing data, missing fields).
	ErrEnvelopeMalformed = errors.New("remote: malformed envelope")
	// ErrPlaintextTooLarge is returned when the decrypted plaintext exceeds MAX_JSON_SIZE.
	ErrPlaintextTooLarge = errors.New("remote: decrypted plaintext exceeds size limit")
	// ErrResponseTooLarge is returned when the HTTP response exceeds the encrypted
	// envelope limit instead of silently returning a truncated prefix.
	ErrResponseTooLarge = errors.New("remote: response exceeds size limit")
)

Sentinel errors for the envelope layer. Callers use errors.Is to branch on them. None of these errors carry key material, plaintext, or the full envelope.

View Source
var ErrAddressPolicy = errors.New("remote host resolves to a prohibited address")

ErrAddressPolicy reports that the connection policy refused an address the remote host resolved to. Another attempt meets the same policy, so the error is not worth retrying until the address or REMOTE_PRIVATE_ORIGINS changes.

View Source
var LegacyEncryptionObserver func()

LegacyEncryptionObserver is invoked once (deduped) the first time the deprecated legacy encryption format is used. It lets callers (main) record a deprecation metric without this package importing the metrics package.

Functions

func AddressAllowed added in v1.6.0

func AddressAllowed(ip net.IP, allowPrivate bool) bool

AddressAllowed applies the same policy to startup validation and connections.

func AddressPolicyStopped added in v1.8.0

func AddressPolicyStopped(ctx context.Context) bool

AddressPolicyStopped reports whether the connection policy stopped a context made by WithAddressPolicyStop.

func DecryptEnvelopeV2 added in v0.14.0

func DecryptEnvelopeV2(body []byte, priv *rsa.PrivateKey) ([]byte, error)

DecryptEnvelopeV2 parses and authenticates a v2 envelope and returns the plaintext. It enforces the decrypted plaintext size limit. Errors are typed sentinels and never contain key material, plaintext, or the raw envelope.

func Encrypt added in v0.14.0

func Encrypt(plaintext []byte, pub *rsa.PublicKey, keyID string) ([]byte, error)

Encrypt builds a v2 envelope for plaintext using the recipient public key and keyID. A fresh random 32-byte content key and GCM nonce are generated per call, so encrypting the same plaintext twice yields different ciphertext and nonce. Intended for producers and round-trip tests.

func FetchDecrypted deprecated

func FetchDecrypted(ctx context.Context, url, authHeader string, decryptEnabled bool, rsaKeyPath, rsaKeyPEM string, timeout time.Duration, insecureTLS bool) ([]byte, error)

FetchDecrypted fetches url with optional auth header and optional decryption.

Deprecated: prefer FetchDecryptedWithOptions. This wrapper preserves the historical signature but uses auto format and non-required semantics. Unlike the old implementation, it no longer silently returns ciphertext as plaintext when decryption is enabled: a decrypt failure returns a typed error.

func FetchDecryptedUsers deprecated

func FetchDecryptedUsers(ctx context.Context, url, authHeader string, decryptEnabled bool, rsaKeyPath, rsaKeyPEM string, timeout time.Duration, insecureTLS bool) ([]define.AllowListUser, error)

FetchDecryptedUsers fetches remote URL and returns parsed []AllowListUser.

Deprecated: prefer FetchDecryptedUsersWithOptions.

func FetchDecryptedUsersWithOptions added in v0.14.0

func FetchDecryptedUsersWithOptions(ctx context.Context, opts *FetchOptions) ([]define.AllowListUser, error)

FetchDecryptedUsersWithOptions fetches, decrypts (per opts) and parses []AllowListUser.

func FetchDecryptedWithOptions added in v0.14.0

func FetchDecryptedWithOptions(ctx context.Context, opts *FetchOptions) ([]byte, error)

FetchDecryptedWithOptions fetches opts.URL and applies the configured decryption policy. It returns typed sentinel errors (see envelope.go) and never downgrades a decrypt failure to plaintext. The Content-Type header is used only as a soft consistency check.

func NewHTTPClient added in v1.6.0

func NewHTTPClient(timeout time.Duration, insecureTLS bool) (*http.Client, error)

NewHTTPClient restricts rule-source connections to validated addresses. It ignores environment proxies, which could resolve the target outside this policy.

func NewHTTPClientWithOptions added in v1.8.0

func NewHTTPClientWithOptions(opts ClientOptions) (*http.Client, error)

NewHTTPClientWithOptions is NewHTTPClient with every setting of the client. The client keeps idle connections, so build it once and reuse it.

func PrivateOriginAllowed added in v1.6.0

func PrivateOriginAllowed(raw string) bool

PrivateOriginAllowed reports an exact, explicitly configured private source. The exception never allows loopback, link-local or metadata destinations.

func ResetLegacyDeprecationForTest added in v0.14.0

func ResetLegacyDeprecationForTest()

ResetLegacyDeprecationForTest re-arms the legacy deprecation reporter (test helper).

func ValidatePrivateOrigins added in v1.6.0

func ValidatePrivateOrigins() error

ValidatePrivateOrigins validates the explicit exception list before startup.

func ValidateSourceURL added in v1.6.0

func ValidateSourceURL(raw string, requireHTTPS bool) error

ValidateSourceURL checks source syntax and the selected transport policy. Encryption envelopes do not authenticate their publisher; production delivery requires HTTPS in addition to decryption.

func WithAddressPolicyStop added in v1.8.0

func WithAddressPolicyStop(ctx context.Context) (context.Context, context.CancelFunc)

WithAddressPolicyStop returns a context that the restricted client cancels, with ErrAddressPolicy as its cause, when the connection policy refuses the request. A caller that retries failed requests uses it to end the retries at once, and reads the refusal back with AddressPolicyStopped. The returned function releases the context.

Types

type ClientOptions added in v1.8.0

type ClientOptions struct {
	// Timeout bounds one request, including reading the body. Zero means no bound.
	Timeout time.Duration
	// InsecureTLS skips certificate verification (development only).
	InsecureTLS bool
	// MaxIdleConns is the size of the idle-connection pool. A value below one
	// selects define.DEFAULT_MAX_IDLE_CONNS.
	MaxIdleConns int
}

ClientOptions configures the restricted rule-source client.

type EncryptionFormat added in v0.14.0

type EncryptionFormat string

EncryptionFormat selects which decryption path FetchDecrypted uses.

const (
	// FormatAuto tries v2 first, then legacy (only when a private key is configured).
	// Auto never falls back to treating a decrypt failure as plaintext.
	FormatAuto EncryptionFormat = "auto"
	// FormatV2 requires the authenticated envelope v2 format.
	FormatV2 EncryptionFormat = "v2"
	// FormatLegacy requires the deprecated unauthenticated v1 hybrid format.
	FormatLegacy EncryptionFormat = "legacy"
)

func ParseEncryptionFormat added in v0.14.0

func ParseEncryptionFormat(s string) (EncryptionFormat, error)

ParseEncryptionFormat parses a format string, defaulting to FormatAuto for empty input.

type FetchOptions added in v0.14.0

type FetchOptions struct {
	// HTTPClient optionally supplies a trusted transport, for embedded callers and tests.
	// Command-line deployments always construct the restricted rule-source client.
	HTTPClient *http.Client
	// RequireHTTPS authenticates production rule delivery through verified TLS.
	RequireHTTPS bool

	URL         string
	AuthHeader  string
	RSAKeyPath  string // file path (preferred)
	RSAKeyPEM   string // inline PEM when file not set
	Timeout     time.Duration
	InsecureTLS bool

	// DecryptEnabled turns on the decryption path. When false, the body is returned as-is.
	DecryptEnabled bool
	// EncryptionRequired makes plaintext responses a hard error (fail closed).
	EncryptionRequired bool
	// Format selects the envelope format (auto|v2|legacy).
	Format EncryptionFormat
}

FetchOptions configures a remote fetch + decrypt operation.

Jump to

Keyboard shortcuts

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