request

package
v0.0.18 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package request signs and verifies HTTP requests with RFC 9421 HTTP Message Signatures (Ed25519). The keyid is the installation fingerprint; the public key comes from the machine's metadata.

Client side:

key, _ := installation.NewKey()
client := &http.Client{
    Transport: request.NewTransport(http.DefaultTransport, key),
}
// All requests through client are now signed.

Server side (ConnectRPC & plain HTTP):

auth, err := request.NewAuthenticator(licensingClient, request.AuthOptions{...})
mux := http.NewServeMux()
mux.Handle("/", auth.Middleware(handler))

Or in a handler:

inst, err := auth.Authenticate(r)

The Authenticator calls the licensing client to look up the machine by fingerprint, extracts and verifies the public key, checks the signature, created window, nonce uniqueness, and license validity. The result is cached for a configurable TTL.

ConnectRPC handlers are http.Handler implementations, so Middleware covers them directly — no separate interceptor is needed.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidOptions reports a negative AuthOptions bound.
	ErrInvalidOptions = errors.New("request: authenticator options must not be negative")

	// ErrSignatureMissing reports a missing or unparsable Signature or
	// Signature-Input header, or missing signature parameters required
	// by this package (keyid, created, nonce).
	ErrSignatureMissing = errors.New("signature is missing")

	// ErrSignatureInvalid reports a signature that does not verify:
	// a malformed keyid, uncovered required components, a disallowed
	// algorithm, or a failing Ed25519 verification.
	ErrSignatureInvalid = errors.New("signature is invalid")

	// ErrDigestMismatch reports a Content-Digest that does not match the body.
	ErrDigestMismatch = errors.New("content-digest does not match request body")

	// ErrDigestRequired reports a missing Content-Digest on a request with a body.
	ErrDigestRequired = errors.New("content-digest is required for requests with a body")

	// ErrBodyTooLarge reports a request body larger than the configured maximum.
	ErrBodyTooLarge = errors.New("request body exceeds the maximum size")

	// ErrCreatedExpired reports a created timestamp outside the allowed window.
	ErrCreatedExpired = errors.New("signature created timestamp is outside the allowed window")

	// ErrCreatedMissing reports a missing created parameter.
	ErrCreatedMissing = errors.New("signature created parameter is missing")

	// ErrNonceReplayed reports a nonce that was already seen.
	ErrNonceReplayed = errors.New("nonce has already been used")

	// ErrNonceMissing reports a missing nonce parameter.
	ErrNonceMissing = errors.New("signature nonce parameter is missing")

	// ErrUnknownKey reports a fingerprint that does not match any machine.
	ErrUnknownKey = errors.New("signing key is not a known machine fingerprint")

	// ErrKeyMismatch reports a machine whose metadata publicKey does not
	// hash to the fingerprint.
	ErrKeyMismatch = errors.New("machine public key does not match its fingerprint")

	// ErrLicenseInvalid reports that the machine's license is not valid.
	// Refusals that carry a Keygen validation code are *LicenseError,
	// which matches this sentinel.
	ErrLicenseInvalid = errors.New("machine license is not valid")

	// ErrUpstreamUnavailable reports that the licensing API is unreachable.
	ErrUpstreamUnavailable = errors.New("licensing API is unavailable")
)

Authentication outcomes matched with errors.Is. Callers can branch on these codes to map to HTTP 401/403/503 responses.

Functions

This section is empty.

Types

type AuthOptions

type AuthOptions struct {
	// MaxAge is the maximum age of the created signature parameter.
	// Zero means 5 minutes; negative is rejected.
	MaxAge time.Duration

	// FutureSkew is how far a created timestamp may be in the future
	// (clock skew). Zero means 30 seconds; negative is rejected.
	FutureSkew time.Duration

	// CacheTTL is how long authenticated installations are cached.
	// The cache only skips the licensing API lookup; digest, created,
	// nonce and signature checks run on every request. Zero means
	// 1 minute; negative disables caching.
	CacheTTL time.Duration

	// NegativeTTL is how long a stable refusal (an unknown key, an
	// invalid license) is cached; key mismatches and upstream failures
	// are looked up again on the next request. Zero means 2 seconds;
	// negative disables negative caching.
	NegativeTTL time.Duration

	// LookupRate and LookupBurst bound the licensing API lookups (the
	// requests the cache cannot answer): past them a request is refused
	// as UPSTREAM_UNAVAILABLE instead of reaching the licensing API, so
	// forged keyids cannot flood it. Zero means 20 per second and a burst
	// of 50; negative is rejected.
	LookupRate  float64
	LookupBurst int

	// LookupTimeout bounds one licensing API lookup. Zero means
	// 10 seconds; negative is rejected.
	LookupTimeout time.Duration

	// MaxBodySize caps the request body read for digest validation.
	// Zero means 4 MiB; negative is rejected.
	MaxBodySize int64

	// SchemeFromRequest overrides the @scheme used to reconstruct
	// @target-uri during verification, e.g. by reading
	// X-Forwarded-Proto behind a TLS-terminating proxy. Nil means
	// derive it from the request's TLS state.
	SchemeFromRequest func(*http.Request) string

	// ReplayGuard rejects replayed nonces. When nil, an in-memory
	// guard with a bounded map is used whose TTL covers at least
	// 2×MaxAge and MaxAge+FutureSkew.
	ReplayGuard ReplayGuard
}

AuthOptions configures an Authenticator.

type Authenticator

type Authenticator struct {
	// contains filtered or unexported fields
}

Authenticator verifies RFC 9421 signed requests against the Keygen licensing API. It is safe for concurrent use.

func NewAuthenticator

func NewAuthenticator(client *licensing.Client, opts AuthOptions) (*Authenticator, error)

NewAuthenticator builds an Authenticator with client and opts. The client must be authenticated with a product or admin token (not a license key). A negative MaxAge, FutureSkew, LookupTimeout, MaxBodySize, LookupRate or LookupBurst is ErrInvalidOptions: they must not silently weaken verification.

func (*Authenticator) Authenticate

func (a *Authenticator) Authenticate(r *http.Request) (Installation, error)

Authenticate verifies the request's signature and returns the authenticated Installation. It is safe for concurrent use.

On every request the following are always checked, cache or no cache: the signature parameters (keyid, created, nonce), the created window (past and future), the content-digest against the body, the nonce uniqueness (replay guard), and the Ed25519 signature against the machine's public key. The cache only avoids re-fetching the machine, its public key and the license state from the licensing API.

func (*Authenticator) Middleware

func (a *Authenticator) Middleware(next http.Handler) http.Handler

Middleware returns an http.Handler that authenticates every request before delegating to next. Authenticated installations are stored in the request context, accessible via FromContext. Refusals are answered with a JSON body {"error":{"code":…,"message":…}} and the mapped status (401/403/413/503, 500 for internal failures).

type InMemoryGuard

type InMemoryGuard struct {
	// contains filtered or unexported fields
}

InMemoryGuard is a ReplayGuard backed by a bounded in-memory map. Nonces expire after ttl. Every entry lives exactly ttl, so insertion order is expiry order: a FIFO queue lets each call drop the expired head in amortized O(1), with no background goroutine. When the map is full of unexpired entries, CheckAndRemember fails closed and refuses the nonce.

func NewInMemoryReplayGuard

func NewInMemoryReplayGuard(ttl time.Duration, maxSize int) (*InMemoryGuard, error)

NewInMemoryReplayGuard returns an InMemoryGuard. Entries expire after ttl; maxSize limits the total number of entries. Both must be positive (ErrInvalidOptions otherwise).

func (*InMemoryGuard) CheckAndRemember

func (g *InMemoryGuard) CheckAndRemember(fingerprint, nonce string) bool

CheckAndRemember implements ReplayGuard.

type Installation

type Installation struct {
	// Fingerprint is the installation fingerprint that signed the
	// request (the keyid signature parameter).
	Fingerprint string

	// MachineID is the machine UUID.
	MachineID string

	// LicenseID is the license UUID the machine belongs to.
	LicenseID string

	// PublicKey is the machine's raw 32-byte Ed25519 public key,
	// verified to hash to Fingerprint.
	PublicKey ed25519.PublicKey

	// LicenseCode is the licensing API's validation code for the
	// machine's license ("VALID" for an authenticated request).
	LicenseCode string
}

Installation is a machine resolved from a verified request signature.

func FromContext

func FromContext(ctx context.Context) (Installation, bool)

FromContext returns the Installation stored by Middleware; ok is false for a request that was not authenticated.

type LicenseError

type LicenseError struct {
	// Code is the Keygen validation code, e.g. EXPIRED. It is empty
	// when the validation result was missing entirely.
	Code licensing.ValidationCode

	// Detail is the Keygen human-readable explanation.
	Detail string
	// contains filtered or unexported fields
}

LicenseError is a license refusal that carries the Keygen validation code. It matches ErrLicenseInvalid via errors.Is and unwraps to the licensing client's error (so errors.Is also matches licensing sentinels such as licensing.ErrExpired) when one caused the refusal.

func (*LicenseError) Error

func (e *LicenseError) Error() string

Error implements the error interface.

func (*LicenseError) Is

func (e *LicenseError) Is(target error) bool

Is reports whether target is ErrLicenseInvalid, so errors.Is matches the sentinel for every coded refusal.

func (*LicenseError) Unwrap

func (e *LicenseError) Unwrap() error

Unwrap returns the licensing client error that caused the refusal.

type ReplayGuard

type ReplayGuard interface {
	// CheckAndRemember reports whether nonce is new for fingerprint
	// and atomically records it when it is. Implementations must
	// remember a nonce at least as long as a request stays
	// acceptable, i.e. for the authenticator's MaxAge plus its
	// future skew.
	CheckAndRemember(fingerprint, nonce string) (ok bool)
}

ReplayGuard rejects nonces that have already been seen.

type Transport

type Transport struct {
	// contains filtered or unexported fields
}

Transport is an http.RoundTripper that signs every outgoing request with RFC 9421 HTTP Message Signatures (Ed25519) via github.com/yaronf/httpsign. It wraps a base transport — http.DefaultTransport when nil.

Signed requests carry the Signature and Signature-Input headers with the label "sig1"; requests with a body also carry a sha-256 Content-Digest header, which is covered by the signature.

func NewTransport

func NewTransport(base http.RoundTripper, key installation.Key, opts ...TransportOption) *Transport

NewTransport returns a Transport that signs requests with key. The keyid signature parameter is the key's fingerprint.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type TransportOption

type TransportOption func(*Transport)

TransportOption configures a Transport.

func WithMaxBodySize

func WithMaxBodySize(maxBytes int64) TransportOption

WithMaxBodySize caps the request body the Transport buffers to compute the Content-Digest header. Zero or negative means no limit.

Jump to

Keyboard shortcuts

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