routepolicy

package
v3.0.0 Latest Latest
Warning

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

Go to latest
Published: May 17, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package routepolicy derives opt-in runtime middleware from route contracts.

The package is stable core API. It connects specs.Operation metadata to middleware decisions without owning storage, identity providers, quota stores, or route registration. Use New to construct a Policy and pass it to routecontracts.NewRegistryWithOptions when a service wants route metadata to drive deprecation headers, content negotiation, auth, idempotency, or rate-limit middleware.

The primary abstractions are Config, Policy, AuthPolicyFunc, IdempotencyPolicyFunc, RateLimitPolicyFunc, and ProblemCatalogPolicy. Application code supplies the factories that enforce auth, idempotency, and quota decisions. routepolicy only decides when those factories should be applied based on the operation contract.

Metadata helpers such as WithAuth, WithDeprecated, WithSunset, WithTenantRequired, WithIdempotencyRequired, WithRateLimit, WithAdminPolicy, and WithProblemResponses keep route contracts code-first without relying on raw OpenAPI extension maps at call sites. Typed readers such as AuthPolicyFromOperation, TenantPolicyFromOperation, IdempotencyPolicyFromOperation, RateLimitPolicyFromOperation, DeprecationPolicyFromOperation, AdminPolicyFromOperation, and ProblemResponseStatuses let contract tooling inspect the same metadata without ad hoc map parsing.

LintOperations provides release and CI checks for operation IDs, unique operation identity, security metadata, Problem Details responses, unsafe-write tenant/idempotency/rate-limit/request/response policies, and admin-only system routes.

ObservabilityLabelsFromOperation and ObservabilityMiddleware expose only bounded route-policy labels for request logs and metrics. They intentionally collapse raw scopes, tenant sources, rate-limit names, and admin policy names into small enums.

Policies fail closed by returning errors from Apply. EmitPolicyExtension output only when the generated OpenAPI document should expose x-api-toolkit-policy metadata. For examples, see docs/cookbook.md.

Index

Constants

View Source
const (
	// ExtensionTenant describes tenant requirements for route contract tooling.
	ExtensionTenant = "x-tenant"
	// ExtensionIdempotencyKey describes idempotency-key requirements for unsafe write routes.
	ExtensionIdempotencyKey = "x-idempotency-key"
	// ExtensionRateLimit describes rate-limit policy metadata for route tooling.
	ExtensionRateLimit = "x-rate-limit"
	// ExtensionAdminPolicy marks an operator-only route as intentionally protected.
	ExtensionAdminPolicy = "x-admin-policy"
)

Variables

View Source
var ErrUnsupportedPolicy = errors.New("routepolicy: unsupported policy")

ErrUnsupportedPolicy reports metadata the configured policy cannot enforce.

Functions

func AdminPolicyFromOperation

func AdminPolicyFromOperation(operation specs.Operation) (string, bool)

AdminPolicyFromOperation returns the named admin policy from an operation.

func ApplyMetadata

func ApplyMetadata(operation specs.Operation, opts ...MetadataOption) specs.Operation

ApplyMetadata applies stable metadata options to an operation.

func ObservabilityMiddleware

func ObservabilityMiddleware(operation specs.Operation) func(http.Handler) http.Handler

ObservabilityMiddleware annotates a request with bounded labels derived from the route operation. It is primarily installed by routecontracts.

func ProblemResponseStatuses

func ProblemResponseStatuses(operation specs.Operation) []int

ProblemResponseStatuses returns documented Problem Details response statuses.

func RateLimitPolicyFromOperation

func RateLimitPolicyFromOperation(operation specs.Operation) (string, bool)

RateLimitPolicyFromOperation returns the named rate-limit policy from an operation.

func SeedObservabilityContext

func SeedObservabilityContext(ctx context.Context) context.Context

SeedObservabilityContext installs the mutable request-scoped label carrier used by outer logging and metrics middleware. It is safe to call repeatedly.

Types

type AuthPolicy

type AuthPolicy struct {
	Security []specs.SecurityRequirement
	Scopes   []string
}

AuthPolicy describes security metadata attached to an operation.

func AuthPolicyFromOperation

func AuthPolicyFromOperation(operation specs.Operation) (AuthPolicy, bool)

AuthPolicyFromOperation returns typed auth metadata from an operation.

type AuthPolicyFunc

type AuthPolicyFunc func(specs.Operation) (func(http.Handler) http.Handler, error)

AuthPolicyFunc builds auth middleware from operation security and scopes.

type Config

type Config struct {
	EnableDeprecation   bool
	EnableNegotiation   bool
	EmitPolicyExtension bool
	Auth                AuthPolicyFunc
	Idempotency         IdempotencyPolicyFunc
	RateLimit           RateLimitPolicyFunc
	ProblemCatalog      ProblemCatalogPolicy
}

Config configures policy derivation.

type DeprecationPolicy

type DeprecationPolicy struct {
	Deprecated bool
	Sunset     string
}

DeprecationPolicy describes deprecation metadata attached to an operation.

func DeprecationPolicyFromOperation

func DeprecationPolicyFromOperation(operation specs.Operation) (DeprecationPolicy, bool)

DeprecationPolicyFromOperation returns typed deprecation metadata from an operation.

type IdempotencyPolicy

type IdempotencyPolicy struct {
	Required bool
	Header   string
}

IdempotencyPolicy describes idempotency-key metadata attached to an operation.

func IdempotencyPolicyFromOperation

func IdempotencyPolicyFromOperation(operation specs.Operation) (IdempotencyPolicy, bool)

IdempotencyPolicyFromOperation returns typed idempotency metadata from an operation.

type IdempotencyPolicyFunc

type IdempotencyPolicyFunc func(specs.Operation) (func(http.Handler) http.Handler, error)

IdempotencyPolicyFunc builds idempotency middleware from operation metadata.

type LintFinding

type LintFinding struct {
	Method  string
	Path    string
	Code    string
	Message string
}

LintFinding describes one route contract lint finding.

func LintOperations

func LintOperations(operations []specs.Operation, opts LintOptions) []LintFinding

LintOperations validates operation metadata needed for production API contracts.

func (LintFinding) Error

func (f LintFinding) Error() string

Error returns a stable human-readable finding string.

type LintOptions

type LintOptions struct {
	RequireOperationID                bool
	RequireUniqueOperationID          bool
	RequireSecurity                   bool
	RequireProblemResponse            bool
	RequireUnsafeWriteAuth            bool
	RequireUnsafeWriteTenant          bool
	RequireUnsafeWriteIdempotency     bool
	RequireUnsafeWriteRateLimit       bool
	RequireUnsafeWriteRequestBody     bool
	RequireUnsafeWriteSuccessResponse bool
	RequireUnsafeWriteProblemResponse bool
	PublicPaths                       []string
	AdminPaths                        []string
}

LintOptions configures route contract linting.

type MetadataOption

type MetadataOption func(*specs.Operation)

MetadataOption mutates an operation with stable api-toolkit policy metadata.

func WithAdminPolicy

func WithAdminPolicy(policy string) MetadataOption

WithAdminPolicy marks an operator-only route as protected by the named policy.

func WithAuth

func WithAuth(scheme string, scopes ...string) MetadataOption

WithAuth appends a security requirement and mirrors scopes onto the operation.

func WithDeprecated

func WithDeprecated() MetadataOption

WithDeprecated marks a route as deprecated in generated OpenAPI.

func WithIdempotencyRequired

func WithIdempotencyRequired() MetadataOption

WithIdempotencyRequired marks a write route as requiring an idempotency key.

func WithOperationID

func WithOperationID(id string) MetadataOption

WithOperationID sets the OpenAPI operationId.

func WithProblemResponses

func WithProblemResponses(statuses ...int) MetadataOption

WithProblemResponses registers standard Problem Details responses for statuses.

func WithRateLimit

func WithRateLimit(policy string) MetadataOption

WithRateLimit records the named rate-limit policy for a route.

func WithSunset

func WithSunset(sunset string) MetadataOption

WithSunset records the route sunset value and marks the route as deprecated.

func WithTenantRequired

func WithTenantRequired(source string) MetadataOption

WithTenantRequired marks a route as tenant-scoped.

type ObservabilityLabels

type ObservabilityLabels struct {
	Auth        string
	Tenant      string
	Idempotency string
	RateLimit   string
	Admin       string
	Deprecated  string
}

ObservabilityLabels is the bounded route-policy label set intended for request logs and metrics. It does not include raw policy names, scopes, tenants, users, request data, or provider identifiers.

func ObservabilityLabelsFromOperation

func ObservabilityLabelsFromOperation(operation specs.Operation) ObservabilityLabels

ObservabilityLabelsFromOperation returns bounded labels for an operation's policy metadata.

func ObservabilityLabelsFromRequest

func ObservabilityLabelsFromRequest(r *http.Request) (ObservabilityLabels, bool)

ObservabilityLabelsFromRequest returns labels attached to the current route.

func (ObservabilityLabels) Map

func (labels ObservabilityLabels) Map() map[string]string

Map returns labels using stable key names.

type Policy

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

Policy derives middleware and operation metadata from specs.Operation.

func New

func New(config Config) *Policy

New constructs a route policy.

func (*Policy) Apply

func (policy *Policy) Apply(operation specs.Operation) (specs.Operation, []func(http.Handler) http.Handler, error)

Apply derives middleware and optional deterministic policy extensions.

type ProblemCatalogPolicy

type ProblemCatalogPolicy func(specs.Operation) error

ProblemCatalogPolicy validates or enriches operation problem-response policy.

type RateLimitPolicyFunc

type RateLimitPolicyFunc func(specs.Operation) (func(http.Handler) http.Handler, error)

RateLimitPolicyFunc builds rate-limit middleware from operation metadata.

type TenantPolicy

type TenantPolicy struct {
	Required bool
	Source   string
}

TenantPolicy describes tenant metadata attached to an operation.

func TenantPolicyFromOperation

func TenantPolicyFromOperation(operation specs.Operation) (TenantPolicy, bool)

TenantPolicyFromOperation returns typed tenant metadata from an operation.

Jump to

Keyboard shortcuts

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