api

package
v0.0.0-...-01c3d73 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2025 License: BSD-2-Clause-Views Imports: 17 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 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 TSL information (DEPRECATED - use GET /tsls) @Description Returns detailed summaries of all loaded Trust Status Lists @Description @Description DEPRECATED: This endpoint is deprecated. Use GET /tsls instead. @Description @Description This endpoint provides comprehensive information about each TSL including: @Description - Territory code @Description - Sequence number @Description - Issue date @Description - Next update date @Description - Number of services @Tags Status @Deprecated true @Produce json @Success 200 {object} map[string]interface{} "tsl_summaries" @Router /info [get]

func ReadinessHandler

func ReadinessHandler(serverCtx *ServerContext) gin.HandlerFunc

ReadinessHandler godoc @Summary Readiness check @Description Returns ready status if pipeline has been processed and TSLs are loaded @Description @Description Query Parameters: @Description - verbose=true: Include detailed TSL information in the response @Tags Health @Produce json @Param verbose query bool false "Include detailed TSL 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.

TSL Information:

GET /tsls - Returns detailed information about all loaded Trust Status Lists

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

GET /status - DEPRECATED: Use GET /readyz instead

GET /info - DEPRECATED: Use GET /tsls 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:

  • Successfully loaded at least one TSL
  • Processed the pipeline at least once

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

Use ?verbose=true on /readyz to include detailed TSL summaries in the response.

func RegisterMetricsEndpoint

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

RegisterMetricsEndpoint registers the /metrics endpoint with the Gin router

func StartBackgroundUpdater

func StartBackgroundUpdater(pl *pipeline.Pipeline, serverCtx *ServerContext, freq time.Duration) error

StartBackgroundUpdater runs the pipeline at regular intervals and updates the server context. This function starts a goroutine that processes the pipeline at the specified frequency and updates the ServerContext with the new pipeline results. The updated context is then used by API handlers to respond to requests with fresh data.

The pipeline is processed immediately upon calling this function, before starting the background updates. This ensures TSLs are available as soon as the server starts.

Success and failure events are logged using the ServerContext's structured logger: - On success: An info-level message with the update frequency - On failure: An error-level message with the error details and frequency

Parameters:

  • pl: The pipeline to process periodically
  • serverCtx: The server context to update with pipeline results (must have a valid logger)
  • freq: The frequency at which to process the pipeline (e.g., 5m for every 5 minutes)

This function is typically called at server startup to ensure TSLs are kept up-to-date.

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 TSLsHandler

func TSLsHandler(serverCtx *ServerContext) gin.HandlerFunc

TSLsHandler godoc @Summary List Trust Status Lists @Description Returns comprehensive information about all loaded Trust Status Lists @Description @Description This is the primary endpoint for retrieving TSL metadata including: @Description - Territory codes @Description - Sequence numbers @Description - Issue and next update dates @Description - Service counts per TSL @Description - Last processing timestamp @Tags TSLs @Produce json @Success 200 {object} map[string]interface{} "count, last_updated, tsls" @Router /tsls [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 {

	// Pipeline metrics
	PipelineExecutionDuration prometheus.Histogram
	PipelineExecutionTotal    prometheus.Counter
	PipelineExecutionErrors   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) RecordPipelineExecution

func (m *Metrics) RecordPipelineExecution(duration time.Duration, tslCount int, err error)

RecordPipelineExecution records metrics for a pipeline 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()

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

Note: This is a simple implementation. For production use with many clients, consider using a more sophisticated cleanup strategy or a library like github.com/ulule/limiter with Redis backend.

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())

type ReadinessResponse

type ReadinessResponse struct {
	Status        string                   `json:"status"`
	Timestamp     time.Time                `json:"timestamp"`
	TSLCount      int                      `json:"tsl_count"`
	LastProcessed string                   `json:"last_processed,omitempty"`
	Ready         bool                     `json:"ready"`
	Message       string                   `json:"message,omitempty"`
	TSLs          []map[string]interface{} `json:"tsls,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 (new architecture)
	PipelineContext *pipeline.Context         // Legacy pipeline context (for backward compatibility)
	LastProcessed   time.Time                 // Timestamp when data was last processed
	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 and tracks when data was last processed. This struct is used by API handlers to access the current state of trust registries for making trust decisions.

The ServerContext supports both the new RegistryManager architecture and the legacy PipelineContext for backward compatibility during migration.

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