middleware

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2026 License: MIT Imports: 17 Imported by: 0

README

middleware

HTTP middleware for the hypeman API.

Authentication

JWT bearer token validation for protected endpoints. Extracts user identity and adds it to the request context.

Resource Resolution

Automatically resolves user-provided identifiers (IDs, names, or prefixes) to full resource objects before handlers run. This enables:

  • Flexible lookups: Users can reference resources by full ID, name, or ID prefix
  • Consistent error handling: Returns 404 for not-found, handles ambiguous matches
  • Automatic logging enrichment: The resolved resource ID is added to the request logger

Handlers can trust that if they're called, the resource exists and is available via mw.GetResolvedInstance[T](ctx) etc.

Observability

OpenTelemetry instrumentation for HTTP requests, including request counts, latencies, and status codes.

Documentation

Overview

Package middleware provides HTTP middleware for the hypeman API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AccessLogger

func AccessLogger(log *slog.Logger) func(http.Handler) http.Handler

AccessLogger returns a middleware that logs HTTP requests using slog with trace context. This replaces chi's middleware.Logger to get logs into OTel/Loki with trace correlation.

func GetResolvedID

func GetResolvedID(ctx context.Context, resourceType string) string

GetResolvedID retrieves just the resolved ID for a resource type.

func GetResolvedImage

func GetResolvedImage[T any](ctx context.Context) *T

GetResolvedImage retrieves the resolved image from context. Returns nil if not found or wrong type.

func GetResolvedIngress

func GetResolvedIngress[T any](ctx context.Context) *T

GetResolvedIngress retrieves the resolved ingress from context. Returns nil if not found or wrong type.

func GetResolvedInstance

func GetResolvedInstance[T any](ctx context.Context) *T

GetResolvedInstance retrieves the resolved instance from context. Returns nil if not found or wrong type.

func GetResolvedVolume

func GetResolvedVolume[T any](ctx context.Context) *T

GetResolvedVolume retrieves the resolved volume from context. Returns nil if not found or wrong type.

func GetUserIDFromContext

func GetUserIDFromContext(ctx context.Context) string

GetUserIDFromContext extracts the user ID from context

func InjectLogger

func InjectLogger(log *slog.Logger) func(http.Handler) http.Handler

InjectLogger returns middleware that adds the logger to the request context. This enables handlers to use logger.FromContext(ctx) with trace correlation.

func JwtAuth

func JwtAuth(jwtSecret string) func(http.Handler) http.Handler

JwtAuth creates a chi middleware that validates JWT bearer tokens

func NewAccessLogger

func NewAccessLogger(otelHandler slog.Handler) *slog.Logger

NewAccessLogger creates an access logger with OTel handler if available.

func NoopHTTPMetrics

func NoopHTTPMetrics() func(http.Handler) http.Handler

NoopHTTPMetrics returns a middleware that does nothing (for when OTel is disabled).

func OapiAuthenticationFunc

func OapiAuthenticationFunc(jwtSecret string) openapi3filter.AuthenticationFunc

OapiAuthenticationFunc creates an AuthenticationFunc compatible with nethttp-middleware that validates JWT bearer tokens for endpoints with security requirements.

func OapiErrorHandler

func OapiErrorHandler(w http.ResponseWriter, message string, statusCode int)

OapiErrorHandler creates a custom error handler for nethttp-middleware that returns consistent error responses.

func ResolveResource

func ResolveResource(resolvers Resolvers, errResponder ErrorResponder) func(http.Handler) http.Handler

ResolveResource creates middleware that resolves resource IDs before handlers run. It detects the resource type from the URL path and uses the appropriate resolver. The resolved resource is stored in context and the logger is enriched with the ID.

Supported paths:

  • /instances/{id}/* -> uses Instance resolver
  • /volumes/{id}/* -> uses Volume resolver
  • /ingresses/{id}/* -> uses Ingress resolver
  • /images/{name}/* -> uses Image resolver (by name, not ID)

func WithResolvedImage

func WithResolvedImage(ctx context.Context, id string, img any) context.Context

WithResolvedImage returns a context with the given image set as resolved.

func WithResolvedIngress

func WithResolvedIngress(ctx context.Context, id string, ing any) context.Context

WithResolvedIngress returns a context with the given ingress set as resolved.

func WithResolvedInstance

func WithResolvedInstance(ctx context.Context, id string, inst any) context.Context

WithResolvedInstance returns a context with the given instance set as resolved.

func WithResolvedVolume

func WithResolvedVolume(ctx context.Context, id string, vol any) context.Context

WithResolvedVolume returns a context with the given volume set as resolved.

Types

type ErrorResponder

type ErrorResponder func(w http.ResponseWriter, err error, lookup string)

ErrorResponder handles resolver errors by writing HTTP responses.

type HTTPMetrics

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

HTTPMetrics holds the OTel metrics for HTTP requests.

func NewHTTPMetrics

func NewHTTPMetrics(meter metric.Meter) (*HTTPMetrics, error)

NewHTTPMetrics creates new HTTP metrics instruments.

func (*HTTPMetrics) Middleware

func (m *HTTPMetrics) Middleware(next http.Handler) http.Handler

Middleware returns an HTTP middleware that records metrics.

type HypervisorTyper

type HypervisorTyper interface {
	GetHypervisorType() string
}

HypervisorTyper is implemented by resources that have a hypervisor type. This allows the middleware to enrich logs/traces without importing the instances package.

type RegistryTokenClaims

type RegistryTokenClaims struct {
	jwt.RegisteredClaims
	BuildID      string   `json:"build_id"`
	Repositories []string `json:"repos"`
	Scope        string   `json:"scope"`
}

RegistryTokenClaims contains the claims for a scoped registry access token. This mirrors the type in lib/builds/registry_token.go to avoid circular imports.

type ResolvedResource

type ResolvedResource struct {
	ID       string
	Resource any
}

ResolvedResource holds the resolved resource ID and value.

type Resolvers

type Resolvers struct {
	Instance ResourceResolver
	Volume   ResourceResolver
	Ingress  ResourceResolver
	Image    ResourceResolver
}

Resolvers holds resolvers for different resource types.

type ResourceResolver

type ResourceResolver interface {
	// Resolve looks up a resource by ID, name, or ID prefix.
	// Returns the resolved ID, the resource, and any error.
	// Should return ErrNotFound if not found, ErrAmbiguousName if prefix matches multiple.
	Resolve(ctx context.Context, idOrName string) (id string, resource any, err error)
}

ResourceResolver is implemented by managers that support lookup by ID, name, or prefix.

Jump to

Keyboard shortcuts

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