api

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: May 15, 2026 License: BSD-2-Clause-Views Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthZENDecisionHandler

func AuthZENDecisionHandler(serverCtx *ServerContext) gin.HandlerFunc

AuthZENDecisionHandler godoc @Summary Evaluate trust decision (AuthZEN Trust Registry Profile) @Description Evaluates whether a name-to-key binding is trusted according to loaded trust registries @Description @Description This endpoint implements the AuthZEN Trust Registry Profile as specified in @Description draft-johansson-authzen-trust. It validates that a public key (in resource.key) @Description is correctly bound to a name (in subject.id) using configured trust registries @Description (ETSI TS 119612 TSLs, OpenID Federation, DID methods, etc.). @Description @Description ## Full Trust Evaluation @Description The request MUST have: @Description - subject.type = "key" and subject.id = the name to validate @Description - resource.type = "jwk" or "x5c" with resource.key containing the public key/certificates @Description - resource.id MUST equal subject.id @Description - action (optional) with name = the role being validated @Description @Description ## Resolution-Only Requests @Description When resource.type or resource.key are omitted, the request is treated as resolution-only. @Description Registries that support resolution-only mode (did:web, did:key, OpenID Federation) will @Description return decision=true with trust_metadata containing the resolved DID document or entity @Description configuration. ETSI TSL registries do not support resolution-only mode. @Tags AuthZEN @Accept json @Produce json @Param request body authzen.EvaluationRequest true "AuthZEN Trust Registry Evaluation Request" @Success 200 {object} authzen.EvaluationResponse "Trust decision (decision=true for trusted, false for untrusted)" @Failure 400 {object} map[string]string "Invalid request format or validation error" @Router /evaluation [post]

func DeprecatedTSLsHandler added in v0.4.0

func DeprecatedTSLsHandler(serverCtx *ServerContext) gin.HandlerFunc

DeprecatedTSLsHandler wraps RegistriesHandler with deprecation headers. This preserves backward compatibility for clients still using GET /tsls while signaling they should migrate to GET /registries.

func HealthHandler

func HealthHandler(serverCtx *ServerContext) gin.HandlerFunc

HealthHandler godoc @Summary Liveness check @Description Returns OK if the server is running and able to handle requests @Tags Health @Produce json @Success 200 {object} HealthResponse @Router /healthz [get]

func InfoHandler

func InfoHandler(serverCtx *ServerContext) gin.HandlerFunc

InfoHandler godoc @Summary Get registry information (DEPRECATED - use GET /registries) @Description Returns the same registry metadata as GET /registries. @Description @Description DEPRECATED: This endpoint is deprecated. Use GET /registries instead. @Description Response includes deprecation headers. @Tags Status @Deprecated true @Produce json @Success 200 {object} map[string]interface{} "registries" @Router /info [get]

func ReadinessHandler

func ReadinessHandler(serverCtx *ServerContext) gin.HandlerFunc

ReadinessHandler godoc @Summary Readiness check @Description Returns ready status if at least one healthy registry is configured @Description @Description Query Parameters: @Description - verbose=true: Include detailed registry information in the response @Tags Health @Produce json @Param verbose query bool false "Include detailed registry information" @Success 200 {object} ReadinessResponse "Service is ready" @Failure 503 {object} ReadinessResponse "Service is not ready" @Router /readyz [get]

func RegisterAPIRoutes

func RegisterAPIRoutes(r *gin.Engine, serverCtx *ServerContext)

RegisterAPIRoutes sets up all API routes on the given Gin engine.

This function registers the following API endpoints:

AuthZEN Discovery:

GET /.well-known/authzen-configuration - Returns PDP metadata for service discovery (AuthZEN spec Section 9)

AuthZEN Evaluation:

POST /evaluation - Implements the AuthZEN Trust Registry Profile for validating name-to-key bindings

This endpoint processes AuthZEN EvaluationRequest objects per draft-johansson-authzen-trust,
validating that a public key (in resource.key) is correctly bound to a name (in subject.id)
according to the trusted certificates in the pipeline context.

Registry Information:

GET /registries - Returns information about all configured trust registries

Deprecated Endpoints (will be removed in v2.0.0):

GET /tsls - DEPRECATED: Use GET /registries instead

GET /status - DEPRECATED: Use GET /readyz instead

GET /info - DEPRECATED: Use GET /registries instead

If a RateLimiter is configured in the ServerContext, it will be applied to all routes.

func RegisterHealthEndpoints

func RegisterHealthEndpoints(r *gin.Engine, serverCtx *ServerContext)

RegisterHealthEndpoints registers health check endpoints on the given Gin router. These endpoints are useful for Kubernetes liveness and readiness probes, load balancers, and monitoring systems.

Endpoints:

GET /healthz      - Liveness probe: returns 200 if the server is running
GET /readyz       - Readiness probe: returns 200 if server is ready to accept traffic
                    Supports ?verbose=true query parameter for detailed TSL information

The /healthz endpoint always returns 200 OK if the server is running, indicating that the process is alive and can handle requests.

The /readyz endpoint checks whether the service has:

  • At least one registry configured
  • At least one registry reporting healthy

If these conditions are not met, it returns 503 Service Unavailable.

Use ?verbose=true on /readyz to include detailed registry information in the response.

func RegisterMetricsEndpoint

func RegisterMetricsEndpoint(r *gin.Engine, metrics *Metrics)

RegisterMetricsEndpoint registers the /metrics endpoint with the Gin router

func RegistriesHandler added in v0.4.0

func RegistriesHandler(serverCtx *ServerContext) gin.HandlerFunc

RegistriesHandler godoc @Summary List Trust Registries @Description Returns comprehensive information about all configured trust registries @Description @Description This is the primary endpoint for retrieving registry metadata including: @Description - Registry names and types @Description - Supported resource types @Description - Health status @Tags Registries @Produce json @Success 200 {object} map[string]interface{} "count, registries" @Router /registries [get]

func StatusHandler

func StatusHandler(serverCtx *ServerContext) gin.HandlerFunc

StatusHandler godoc @Summary Get server status (DEPRECATED - use GET /readyz) @Description Returns the current server status including TSL count and last processing time @Description @Description DEPRECATED: This endpoint is deprecated. Use GET /readyz for health checks. @Tags Status @Deprecated true @Produce json @Success 200 {object} map[string]interface{} "tsl_count, last_processed" @Router /status [get]

func TestShutdownHandler

func TestShutdownHandler(serverCtx *ServerContext) gin.HandlerFunc

TestShutdownHandler godoc (test mode only)

func WellKnownHandler

func WellKnownHandler(baseURL string) gin.HandlerFunc

WellKnownHandler godoc @Summary AuthZEN PDP discovery endpoint @Description Returns Policy Decision Point metadata according to Section 9 of the AuthZEN specification @Description This endpoint provides service discovery information including supported endpoints and capabilities @Description per RFC 8615 well-known URI registration @Tags AuthZEN @Produce json @Success 200 {object} authzen.PDPMetadata "PDP metadata" @Router /.well-known/authzen-configuration [get]

Types

type HealthResponse

type HealthResponse struct {
	Status    string    `json:"status"`
	Timestamp time.Time `json:"timestamp"`
}

HealthResponse represents the response from health check endpoints

type Metrics

type Metrics struct {

	// Registry refresh metrics
	RefreshExecutionDuration prometheus.Histogram
	RefreshExecutionTotal    prometheus.Counter
	RefreshExecutionErrors   prometheus.Counter
	TSLCount                 prometheus.Gauge
	TSLProcessingDuration    prometheus.Histogram

	// API request metrics
	APIRequestsTotal    *prometheus.CounterVec
	APIRequestDuration  *prometheus.HistogramVec
	APIRequestsInFlight prometheus.Gauge

	// Error metrics
	ErrorsTotal *prometheus.CounterVec

	// Certificate validation metrics
	CertValidationTotal    *prometheus.CounterVec
	CertValidationDuration prometheus.Histogram
	// contains filtered or unexported fields
}

Metrics holds all Prometheus metrics for the API server

func NewMetrics

func NewMetrics() *Metrics

NewMetrics creates and registers all Prometheus metrics

func (*Metrics) MetricsMiddleware

func (m *Metrics) MetricsMiddleware() gin.HandlerFunc

MetricsMiddleware creates a Gin middleware that records API metrics

func (*Metrics) RecordCertValidation

func (m *Metrics) RecordCertValidation(duration time.Duration, success bool)

RecordCertValidation records certificate validation metrics

func (*Metrics) RecordError

func (m *Metrics) RecordError(errorType, operation string)

RecordError records an error metric

func (*Metrics) RecordRefreshExecution

func (m *Metrics) RecordRefreshExecution(duration time.Duration, registryCount int, err error)

RecordRefreshExecution records metrics for a registry refresh execution

func (*Metrics) RecordTSLProcessing

func (m *Metrics) RecordTSLProcessing(duration time.Duration)

RecordTSLProcessing records metrics for TSL processing

type RateLimiter

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

RateLimiter provides per-IP rate limiting for API endpoints. It uses the token bucket algorithm from golang.org/x/time/rate to limit the number of requests per second from each IP address.

func NewRateLimiter

func NewRateLimiter(rps, burst int) *RateLimiter

NewRateLimiter creates a new rate limiter with the specified requests per second. The burst parameter allows temporary exceeding of the rate limit.

Parameters:

  • rps: Maximum requests per second allowed per IP address
  • burst: Maximum burst size (number of requests that can be made in a burst)

Example:

limiter := NewRateLimiter(100, 10) // Allow 100 req/sec with bursts up to 10

func (*RateLimiter) CleanupOldLimiters

func (rl *RateLimiter) CleanupOldLimiters(maxAge time.Duration)

CleanupOldLimiters removes rate limiters for IPs that haven't made requests within the specified maxAge duration. This prevents the limiters map from growing unbounded over time. This function should be called periodically (e.g., every hour) by a background goroutine.

func (*RateLimiter) Middleware

func (rl *RateLimiter) Middleware() gin.HandlerFunc

Middleware returns a Gin middleware function that enforces rate limiting. Requests that exceed the rate limit receive a 429 Too Many Requests response.

Example usage:

limiter := NewRateLimiter(100, 10)
router.Use(limiter.Middleware())

func (*RateLimiter) StartCleanupLoop

func (rl *RateLimiter) StartCleanupLoop(interval, maxAge time.Duration, done <-chan struct{})

StartCleanupLoop runs CleanupOldLimiters periodically in a background goroutine. The goroutine stops when the provided done channel is closed.

type ReadinessResponse

type ReadinessResponse struct {
	Status        string                   `json:"status"`
	Timestamp     time.Time                `json:"timestamp"`
	RegistryCount int                      `json:"registry_count"`
	HealthyCount  int                      `json:"healthy_count"`
	Ready         bool                     `json:"ready"`
	Message       string                   `json:"message,omitempty"`
	Registries    []map[string]interface{} `json:"registries,omitempty"` // Only included with ?verbose=true
}

ReadinessResponse represents the response from the readiness endpoint

type ServerContext

type ServerContext struct {
	RegistryManager *registry.RegistryManager // Multi-registry manager
	Logger          logging.Logger            // Logger for API operations (never nil)
	RateLimiter     *RateLimiter              // Rate limiter for API endpoints (optional)
	Metrics         *Metrics                  // Prometheus metrics (optional)
	BaseURL         string                    // Base URL for the PDP (e.g., "https://pdp.example.com") for .well-known discovery
	// contains filtered or unexported fields
}

ServerContext holds the shared state for the API server, including the registry manager. It provides thread-safe access to trust registries. This struct is used by API handlers to access the current state of trust registries for making trust decisions.

The ServerContext always has a configured Logger for API operations. If none is provided during initialization, a default logger is used.

func NewServerContext

func NewServerContext(logger logging.Logger) *ServerContext

NewServerContext creates a new ServerContext with a configured logger. The ServerContext will always have a valid logger - if none is provided, it will use the DefaultLogger.

func (*ServerContext) Lock

func (s *ServerContext) Lock()

Lock locks the ServerContext for writing.

func (*ServerContext) RLock

func (s *ServerContext) RLock()

RLock locks the ServerContext for reading.

func (*ServerContext) RUnlock

func (s *ServerContext) RUnlock()

RUnlock unlocks the ServerContext after reading.

func (*ServerContext) Unlock

func (s *ServerContext) Unlock()

Unlock unlocks the ServerContext after writing.

func (*ServerContext) WithLogger

func (s *ServerContext) WithLogger(logger logging.Logger) *ServerContext

WithLogger returns a copy of the ServerContext with the specified logger. This allows for easy reconfiguration of the logger while preserving the rest of the ServerContext's state.

Parameters:

  • logger: The new logger to use for the ServerContext

Returns:

  • A new ServerContext instance with the same state but using the specified logger

Jump to

Keyboard shortcuts

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