api

package
v0.19.4 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: Apache-2.0 Imports: 70 Imported by: 0

Documentation

Overview

Package api is the generated Gin-based HTTP/WebSocket/MCP server for the apic framework, plus the hand-written wiring (server construction, OIDC, validation, listeners) around the generated code.

SECURITY: object-level authorization (BOLA) is the consumer's job

The generated request wrappers enforce only AUTHENTICATION presence (e.g. BearerAuth/OIDC scopes) — they do NOT verify that the authenticated caller is permitted to act on the specific object named in the path. Object-level endpoints such as GET/PATCH/DELETE /v1/users/{userId} will, by default, happily serve or mutate ANY user's record to ANY authenticated caller. This is a Broken Object Level Authorization gap (CWE-639 / OWASP API1:2023): without an ownership check, /v1/users/{userId} PATCH exposes a horizontal (and, via role/password fields, vertical) privilege-escalation path.

Each consumer MUST enforce object-level ownership inside its ServerInterface implementation for every owner-scoped route. The framework ships the enforcement primitive for this:

securex.RequireOwnership(secret, extractOwnerID, next)

which fails closed unless the JWT `sub` claim equals the resource-owner id extracted from the request (path param, body, or store lookup). Wire it per owner-scoped route, or perform the equivalent `sub == {ownerParam}` check in the handler before reading/writing the object.

This default-open posture is deliberate (the framework cannot know which routes are owner-scoped or how ownership is determined), but it MUST be acknowledged and closed by every downstream service (SEC-0027).

Code generated by generate_fn; DO NOT EDIT.

Code generated by apic; DO NOT EDIT.

Code generated by mcpgen; DO NOT EDIT.

Code generated by generate_noop; DO NOT EDIT.

Code generated by generate_ownerguard; DO NOT EDIT.

Package api provides primitives to interact with the openapi HTTP API.

Code generated by devnw.dev/apic version (devel) DO NOT EDIT.

Code generated by wsgen; DO NOT EDIT.

Index

Constants

View Source
const (
	BearerAuthScopes        = "bearerAuth.Scopes"
	MutualTLSAuthScopes     = "mutualTLSAuth.Scopes"
	Oauth2AuthScopes        = "oauth2Auth.Scopes"
	OpenIdConnectAuthScopes = "openIdConnectAuth.Scopes"
)
View Source
const (
	// OAuth2Scopes was intended as the context key under which per-path
	// OAuth2 scope requirements would be stashed for downstream handlers to
	// read, but nothing in this package ever sets or reads it -- the actual
	// scope/authorization enforcement lives in the OpenAPI security
	// requirements walked by specEnforcer (via oapifilter) and in
	// securex.EvalComposite for composite auth. QG-095 (#271).
	//
	// Deprecated: unused; will be removed in the next major version.
	OAuth2Scopes = "oauth2_scopes"
	// ENV names the environment variable gin itself reads to select its
	// running mode ("GIN_MODE").
	ENV = "GIN_MODE"
	// DEVENV is the ENV value ("debug") that puts gin into its verbose,
	// non-production mode.
	DEVENV = "debug"
	// INSECURE_DEV names the environment variable that, when set alongside
	// gin's debug mode on a loopback host, allows New/Serve to skip TLS and
	// OIDC configuration for local development (securex.AllowInsecureDev*).
	// It has no effect outside gin.DebugMode and is refused off loopback.
	INSECURE_DEV = "APIC_INSECURE_DEV"
)

Variables

View Source
var AuditWS = struct {
	Connect     func(path, remote string)
	AuthOK      func(path, sub string)
	AuthFail    func(path, reason string)
	RateLimited func(path string)
	Closed      func(path string, err error)
}{
	Connect:     func(path, remote string) { slog.Info("ws_connect", "path", path, "remote", remote) },
	AuthOK:      func(path, sub string) { slog.Info("ws_auth_ok", "path", path, "sub", sub) },
	AuthFail:    func(path, reason string) { slog.Warn("ws_auth_fail", "path", path, "reason", reason) },
	RateLimited: func(path string) { slog.Warn("ws_rate_limited", "path", path) },
	Closed:      func(path string, err error) { slog.Info("ws_closed", "path", path, "err", err) },
}

AuditWS is invoked by generated handlers to record auth and lifecycle events.

View Source
var ErrAPIValidation = errors.New("api validation error")
View Source
var ErrAuthHeaderMissing = errors.New("authorization header missing")

ErrAuthHeaderMissing is returned by OIDC.ExtractToken when the request carries no Authorization header at all. OIDC.JWT treats this case as a deliberate pass-through (see its doc comment) rather than aborting the request, so a route relying on this sentinel must still be paired with an enforcer (OIDC.Authenticate) to actually deny unauthenticated access.

View Source
var ErrBadRequest = errors.New("bad request") // → 400 (post-validation business 400)
View Source
var ErrClientNil = errors.New("oidc: client is nil")

ErrClientNil is returned by LoadOIDC when it is handed a nil *htpx.Client: the discovery fetch and the JWKS cache both need a transport to share, and a nil client would otherwise panic on first use.

View Source
var ErrConflict = errors.New("conflict") // → 409
View Source
var ErrDiscoveryStatus = errors.New("oidc discovery returned non-2xx status")

ErrDiscoveryStatus is returned by LoadOIDC when the discovery endpoint answers with a non-2xx HTTP status; the response body is not decoded in that case, so a 404/500/HTML error page yields this clear error instead of an opaque JSON decode failure (N-11).

View Source
var ErrEmptyAudience = errors.New("empty audience")

ErrEmptyAudience is returned by OIDC.ExtractToken when this OIDC instance's configured audience (OIDC.Aud) is empty -- a misconfiguration that would otherwise let jwt.WithAudience silently accept any audience.

View Source
var ErrForbidden = errors.New("forbidden") // → 403 (post-auth business denial)
View Source
var ErrInvalidScheme = errors.New("invalid scheme")

ErrInvalidScheme is returned by LoadOIDC when the discovery endpoint (or, in OIDC.UnmarshalJSON, one of the endpoints the discovery document advertises) is not an "https://" URL. OIDC Discovery 1.0 requires TLS on every one of these endpoints; a plaintext URL would let a network attacker forge the trust anchor used for token verification.

View Source
var ErrInvalidServerConfig = errors.New("invalid server configuration")

ErrInvalidServerConfig is returned by Serve when the assembled apiServer fails pre-flight configuration validation. QG-066 (#220): the previous struct-tag validation (`validate.Struct(s)`) was dead code — the go-playground validator skips unexported fields (PkgPath != ""), so every tag on apiServer was silently ignored. validateConfig performs the checks explicitly.

View Source
var ErrInvalidURL = errors.New("invalid url")

ErrInvalidURL is returned when a configured URL string cannot be parsed.

View Source
var ErrIssuerMismatch = errors.New("discovery issuer does not match the discovery URL")

ErrIssuerMismatch is returned by LoadOIDC when the discovery document's "issuer" does not match the discovery URL it was fetched from (OIDC Discovery 1.0 §4.3: issuer + "/.well-known/openid-configuration" MUST equal the request URL). Without this check, a discovery response could advertise an arbitrary issuer that ExtractToken would trust as the expected iss, letting a compromised or misconfigured discovery endpoint redirect trust to an issuer the operator never intended (SEC-0057, GitLab #311).

View Source
var ErrJWKSTransportWrapped = errors.New("oidc: jwks transport is a wrapped Doer (htpx.ClientWrapper), not a single-hop http.RoundTripper")

ErrJWKSTransportWrapped is returned by LoadOIDC (via jwksHTTPClient) when the client's transport is an htpx.ClientWrapper -- a whole *http.Client Do method (WithDoer, WithOAuth2, WithLimiter) masquerading as a RoundTripper. Such a transport resolves an entire redirect chain internally before oidcx's outer CheckRedirect (refuseJWKSRedirects) ever sees it, silently reopening the SEC-0057 (GitLab #311) JWKS-redirect bypass. The JWKS fetch needs a genuine single-hop RoundTripper, so this fails closed instead of guessing.

View Source
var ErrMalformedAuthHeader = errors.New("malformed authorization header")

ErrMalformedAuthHeader is returned by OIDC.ExtractToken when an Authorization header is present but does not use the "Bearer " scheme, or when the JWT's JOSE header cannot be parsed at all.

View Source
var ErrNilCatchAllHandler = errors.New("nil catch-all handler")
View Source
var ErrNotFound = errors.New("not found") // → 404
View Source
var ErrNotImplemented = errors.New("not implemented") // → 501

Generated handler error sentinels. Returning one of these from a ServerInterface method maps to the matching HTTP status code via the per-route error-mapping switch. Anything else non-nil falls through to 500. A *StatusError lets a handler carry a custom code + message while still using the generated response envelope.

A-NEW-4 (docs/GENERATOR_BUGS.md).

View Source
var ErrUnprocessable = errors.New("unprocessable") // → 422
View Source
var ErrUnsupportedJWTAlg = errors.New("unsupported jwt algorithm")

ErrUnsupportedJWTAlg is returned by ExtractToken when an inbound token declares a JWS algorithm outside the asymmetric allowlist (e.g. "none" or a symmetric HS* alg) on the OIDC/JWKS verification path. QG-060.

View Source
var RegisterWSRoutes = func(r *gin.Engine) {}

RegisterWSRoutes is assigned by generated code at init(). Default no-op.

View Source
var WSOptionsOverride func(path string, opts *wsx.Options)

WSOptionsOverride is consulted by every generated WS handler before the RFC 6455 upgrade. Assign to mutate wsx.Options at runtime -- for example to broaden the origin allowlist, toggle AllowAnyOrigin, or swap subprotocols. The LV-2026-05-22 escape valve.

Functions

func Args

func Args(app string) cli.Args

Args returns the standard set of CLI flags a binary embedding this package's server typically exposes (host, port, TLS cert/key/CA, OIDC issuer/audience, CORS origins, trusted proxies, rate limit/duration). app names the binary in each flag's generated description text. The returned cli.Args is built exactly once (sync.Once) and shared across calls, so repeated calls with different app values still describe the first caller's app name.

func AuthToken

func AuthToken(ctx context.Context) (jwt.Token, error)

AuthToken retrieves the verified JWT token that OIDC.JWT stashed in ctx (or, when Authenticate is invoked through the OpenAPI request validator, that the caller re-derived from the underlying *http.Request's own context -- see OIDC.Authenticate's doc). It returns an error if no token was ever stashed, which is the normal outcome for a public route or a route whose Authorization header was absent.

func GenerateTLSCertificate

func GenerateTLSCertificate() (tls.Certificate, error)

GenerateTLSCertificate generates a self-signed TLS certificate.

func GetSwagger

func GetSwagger() (swagger *openapi3.T, err error)

GetSwagger returns the Swagger specification corresponding to the generated code in this file. The external references of Swagger specification are resolved. The logic of resolving external references is tightly connected to "import-mapping" feature. Externally referenced files must be embedded in the corresponding golang packages. Urls can be supported but this task was out of the scope.

func Log

func Log[T any](val T) slog.Value

Log examines the fields of val (if val is a struct) and returns a slog.Value containing only those fields whose struct tag does not declare "safe-to-log:false".

Example usage:

type Foo struct {
    Password string `json:"password" safe-to-log:"false"`
    Email    string `json:"email"` // implicitly safe
}
foo := Foo{Password: "secret", Email: "foo@example.com"}
slogValue := Log(foo)
slog.Info("Logging foo", slogValue)

func MCPTools

func MCPTools() map[string]MCPTool

MCPTools returns the available tools.

func NewCreatePetRequest

func NewCreatePetRequest(server string, body CreatePetJSONRequestBody) (*http.Request, error)

NewCreatePetRequest calls the generic CreatePet builder with application/json body

func NewCreatePetRequestWithBody

func NewCreatePetRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)

NewCreatePetRequestWithBody generates requests for CreatePet with any type of body

func NewCreateUserRequest

func NewCreateUserRequest(server string, body CreateUserJSONRequestBody) (*http.Request, error)

NewCreateUserRequest calls the generic CreateUser builder with application/json body

func NewCreateUserRequestWithBody

func NewCreateUserRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)

NewCreateUserRequestWithBody generates requests for CreateUser with any type of body

func NewDeleteUserRequest

func NewDeleteUserRequest(server string, userId ID) (*http.Request, error)

NewDeleteUserRequest generates requests for DeleteUser

func NewEchoRequest

func NewEchoRequest(server string, body EchoJSONRequestBody) (*http.Request, error)

NewEchoRequest calls the generic Echo builder with application/json body

func NewEchoRequestWithBody

func NewEchoRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)

NewEchoRequestWithBody generates requests for Echo with any type of body

func NewGetCurrentUserRequest

func NewGetCurrentUserRequest(server string) (*http.Request, error)

NewGetCurrentUserRequest generates requests for GetCurrentUser

func NewGetUserByIdRequest

func NewGetUserByIdRequest(server string, userId ID) (*http.Request, error)

NewGetUserByIdRequest generates requests for GetUserById

func NewListPetsRequest

func NewListPetsRequest(server string) (*http.Request, error)

NewListPetsRequest generates requests for ListPets

func NewListUsersRequest

func NewListUsersRequest(server string) (*http.Request, error)

NewListUsersRequest generates requests for ListUsers

func NewLoginUserRequest

func NewLoginUserRequest(server string, body LoginUserJSONRequestBody) (*http.Request, error)

NewLoginUserRequest calls the generic LoginUser builder with application/json body

func NewLoginUserRequestWithBody

func NewLoginUserRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)

NewLoginUserRequestWithBody generates requests for LoginUser with any type of body

func NewLogoutUserRequest

func NewLogoutUserRequest(server string) (*http.Request, error)

NewLogoutUserRequest generates requests for LogoutUser

func NewMCPEngine added in v0.19.2

func NewMCPEngine(opts ...mcpx.Option) (*mcpx.Engine, error)

NewMCPEngine builds this package's MCP engine: tools, descriptors, server identity, rate buckets, body cap and WS origin policy, all owned by the returned *mcpx.Engine. Mount it with eng.HandleHTTP / eng.ServeWS, or run eng.ServeSTDIO(ctx) for the stdio transport.

It replaces the package init() that mutated process-wide mcpx state at import time, which made a process importing both devnw.dev/apic/api and a generated mcp package depend on init-vs-constructor ordering (ENG-4634 / GitLab #364). Caller options are applied AFTER the generated defaults, so a later option wins -- pass mcpx.WithAuthVerifier to authenticate the HTTP and WS transports (without one they fail closed with HTTP 401).

func NewRefreshTokenRequest

func NewRefreshTokenRequest(server string, body RefreshTokenJSONRequestBody) (*http.Request, error)

NewRefreshTokenRequest calls the generic RefreshToken builder with application/json body

func NewRefreshTokenRequestWithBody

func NewRefreshTokenRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)

NewRefreshTokenRequestWithBody generates requests for RefreshToken with any type of body

func NewRegisterUserRequest

func NewRegisterUserRequest(server string, body RegisterUserJSONRequestBody) (*http.Request, error)

NewRegisterUserRequest calls the generic RegisterUser builder with application/json body

func NewRegisterUserRequestWithBody

func NewRegisterUserRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)

NewRegisterUserRequestWithBody generates requests for RegisterUser with any type of body

func NewShowPetByIdRequest

func NewShowPetByIdRequest(server string, petId ID) (*http.Request, error)

NewShowPetByIdRequest generates requests for ShowPetById

func NewTestHTPXClient

func NewTestHTPXClient(t *testing.T, listener *TestListener) *htpx.Client

NewTestHTPXClient builds an *htpx.Client that dials directly into listener's in-memory TestConn for requests to 127.0.0.1:443 (matching NewTestInMemoryServer's fixed baseURL) and falls back to a real dial for any other address. Its TLS config verifies against listener's pinned self-signed CertPool (listener.ServerRootCAs) rather than skipping verification, so tests exercise the same certificate-validation path production traffic does (SEC-0016 / CWE-295).

func NewUpdateUserRequest

func NewUpdateUserRequest(server string, userId ID, body UpdateUserJSONRequestBody) (*http.Request, error)

NewUpdateUserRequest calls the generic UpdateUser builder with application/json body

func NewUpdateUserRequestWithBody

func NewUpdateUserRequestWithBody(server string, userId ID, contentType string, body io.Reader) (*http.Request, error)

NewUpdateUserRequestWithBody generates requests for UpdateUser with any type of body

func OwnershipGuard

func OwnershipGuard() gin.HandlerFunc

OwnershipGuard returns gin middleware enforcing object-level ownership (SEC-0027 / OWASP API1:2023 BOLA) for every route annotated with x-apic-owner-param. For a guarded route it reads the verified OIDC token stashed by the JWT middleware, allows callers holding a configured bypass role, and otherwise requires the token subject to equal the routed owner path parameter. The owner id is read ONLY from c.Param (the routed path), never from the request body, so it cannot be spoofed independently of the route. Unguarded routes pass through untouched.

func PathToRawSpec

func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error)

Constructs a synthetic filesystem for resolving external references when loading openapi specifications.

func RegisterGeneratedAPI

func RegisterGeneratedAPI(mux *http.ServeMux, srv GeneratedServerInterface, opts APIOptions)

RegisterGeneratedAPI registers generated HTTP routes with validation and middleware.

GAP-0076: when the configuration declares at least one route with auth: "jwt" but the caller supplied a nil opts.AuthJWT, this function panics with securex.ErrAuthVerifierRequired BEFORE any route is registered. The same guard fires for auth: "api_key" + nil opts.Auth via securex.ErrAuthAPIKeyRequired. Use securex.NewTestVerifier() as the unit-test escape hatch.

func RegisterHandlers

func RegisterHandlers(router gin.IRouter, si ServerInterface)

RegisterHandlers creates http.Handler with routing matching OpenAPI spec.

func RegisterHandlersWithOptions

func RegisterHandlersWithOptions(router gin.IRouter, si ServerInterface, options GinServerOptions)

RegisterHandlersWithOptions creates http.Handler with additional options

func WsValidateEchoDocs

func WsValidateEchoDocs(payload []byte) error

WsValidateEchoDocs validates text JSON messages for /ws/echo-docs.

func WsValidateFeed

func WsValidateFeed(payload []byte) error

WsValidateFeed validates text JSON messages for /ws/users/{userId}/feed.

Types

type APIOptions

type APIOptions struct {
	// Ctx bounds the lifetime of everything RegisterGeneratedAPI starts in
	// the background -- today the CSRF mint endpoint's per-client
	// httpx.PeerLimiter sweeper (PERF-0128). When non-nil, its
	// cancellation stops those goroutines exactly as httpx.WrapHandlerCtx
	// releases the global limiter's on the same context; the generated
	// Serve passes its own ctx, and the generated tests pass t.Context().
	// nil keeps the historical behaviour (nothing is ever stopped), which
	// is harmless for a process-lifetime server but leaks one goroutine
	// per RegisterGeneratedAPI call in a long-lived test binary.
	Ctx     context.Context
	Auth    func(*http.Request) error
	AuthJWT func(*http.Request) error
	// AuthMTLS is invoked for routes whose config declared auth: "mtls"
	// AFTER the basic securex.VerifyMTLS gate has accepted the request.
	// Use this hook to enforce deployment-specific issuer-label policy
	// (PIV/CAC/custom) using policy.SupportedIssuers. Returning a non-nil
	// error rejects the request with 401.
	AuthMTLS func(*http.Request, securex.MTLSPolicy) error
	// MTLSRuntimes holds the boot-constructed CRL/OCSP revocation checkers
	// and CAC/PIV certificate-policy verifier for every mtls route whose
	// config declares crl/ocsp/cac_piv/principal_mapping (L-51), keyed by
	// "METHOD /path". server_lib.go.tmpl's Serve constructs this map ONCE
	// at boot (mtlsx.CRLChecker/OCSPChecker hold response caches and make
	// network calls, so they must never be rebuilt per request) and passes
	// it straight through here. A nil map, or a route missing from it, is
	// the zero securex.MTLSRuntime{} -- "no CRL/OCSP/CAC-PIV enforcement
	// for this route" -- which is exactly pre-L-51 behavior, so this field
	// is fully backward compatible with hand-built APIOptions literals
	// (tests, custom entrypoints) that never set it.
	MTLSRuntimes map[string]securex.MTLSRuntime
	// AuthWebhook resolves a per-route HMAC secret keyed on the
	// WebhookPolicy.Name supplied at codegen. Returning (nil, err)
	// rejects the request with a generic 401 envelope before any
	// signature check. The generator wires server.go.tmpl to populate
	// this from rc.Security.Webhooks; consumers that supply their own
	// resolver (e.g. a Vault-backed lookup) pass it via
	// APIOptions{AuthWebhook: myFunc}.
	AuthWebhook func(name string) ([]byte, error)
	// CookieName is the name of the HttpOnly cookie carrying the session JWT
	// for routes with auth: "cookie". Empty falls back to "session" at
	// request time. Wired by server_lib from security.auth.cookie_name.
	CookieName string
	// CSRF, when non-nil, enforces signed double-submit CSRF tokens on
	// cookie-authenticated state-changing requests and powers the issuance
	// endpoint. Wired by server_lib from security.csrf.
	CSRF           *csrfx.Signer
	CSRFCookieName string
	CSRFHeaderName string
	// CSRFSessionID extracts the session identifier a token is bound to
	// (default: verified claims Subject).
	CSRFSessionID func(*http.Request) string
	// CSRFMintPerIPSource + CSRFMintTrustedProxyCIDRs key the CSRF mint
	// endpoint's per-client rate limiter (SEC-0060/0061) EXACTLY like the
	// server's global per-IP limiter -- server_lib wires both straight from
	// security.rate_limit.per_ip_source / trusted_proxy_cidrs, the same
	// values httpx.WrapHandlerCtx's Config uses, so a forwarded header
	// (X-Forwarded-For / X-Real-IP) is honored, or ignored, identically at
	// every layer. Zero value (IPSourceRemoteAddr, no trusted proxies) is
	// safe: it keys on the TCP peer address and never trusts a header.
	CSRFMintPerIPSource       httpx.IPSource
	CSRFMintTrustedProxyCIDRs []string
	GlobalRate                float64
	GlobalBurst               float64
}

APIOptions configures cross-cutting concerns for generated routes.

type BadRequest

type BadRequest = Error

BadRequest Error response

type CatchAllServerInterface

type CatchAllServerInterface interface {
	HandleRoute(w http.ResponseWriter, r *http.Request, route RouteInfo, req any) (any, error)
}

CatchAllServerInterface adapts one generic handler to the generated ServerInterface. Return the generated response type for the route or write directly to w and return nil.

type Claims

type Claims struct {
	// AdditionalData Any extra claim data
	AdditionalData *map[string]interface{} `json:"additionalData,omitempty"`
	Roles          *[]Role                 `json:"roles,omitempty"`
}

Claims Additional claims for extended user profile or permissions

func (*Claims) Valid

func (x *Claims) Valid() error

Validate Claims using the specified tags

type Client

type Client struct {
	// The endpoint of the server conforming to this interface, with scheme,
	// https://api.deepmap.com for example. This can contain a path relative
	// to the server, such as https://api.deepmap.com/dev-test, and all the
	// paths in the swagger spec will be appended to the server.
	Server string

	// Doer for performing requests, typically a *http.Client with any
	// customized settings, such as certificate chains.
	Client HttpRequestDoer

	// A list of callbacks for modifying requests which are generated before sending over
	// the network.
	RequestEditors []RequestEditorFn
}

Client which conforms to the OpenAPI3 specification for this service.

func NewClient

func NewClient(server string, opts ...ClientOption) (*Client, error)

Creates a new Client, with reasonable defaults

func (*Client) CreatePet

func (c *Client) CreatePet(ctx context.Context, body CreatePetJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) CreatePetWithBody

func (c *Client) CreatePetWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) CreateUser

func (c *Client) CreateUser(ctx context.Context, body CreateUserJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) CreateUserWithBody

func (c *Client) CreateUserWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) DeleteUser

func (c *Client) DeleteUser(ctx context.Context, userId ID, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) Echo

func (c *Client) Echo(ctx context.Context, body EchoJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) EchoWithBody

func (c *Client) EchoWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) GetCurrentUser

func (c *Client) GetCurrentUser(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) GetUserById

func (c *Client) GetUserById(ctx context.Context, userId ID, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) ListPets

func (c *Client) ListPets(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) ListUsers

func (c *Client) ListUsers(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) LoginUser

func (c *Client) LoginUser(ctx context.Context, body LoginUserJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) LoginUserWithBody

func (c *Client) LoginUserWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) LogoutUser

func (c *Client) LogoutUser(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) RefreshToken

func (c *Client) RefreshToken(ctx context.Context, body RefreshTokenJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) RefreshTokenWithBody

func (c *Client) RefreshTokenWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) RegisterUser

func (c *Client) RegisterUser(ctx context.Context, body RegisterUserJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) RegisterUserWithBody

func (c *Client) RegisterUserWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) ShowPetById

func (c *Client) ShowPetById(ctx context.Context, petId ID, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) UpdateUser

func (c *Client) UpdateUser(ctx context.Context, userId ID, body UpdateUserJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) UpdateUserWithBody

func (c *Client) UpdateUserWithBody(ctx context.Context, userId ID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) Valid

func (x *Client) Valid() error

Validate Client using the specified tags

type ClientInterface

type ClientInterface interface {
	// LoginUserWithBody request with any body
	LoginUserWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

	LoginUser(ctx context.Context, body LoginUserJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

	// LogoutUser request
	LogoutUser(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

	// GetCurrentUser request
	GetCurrentUser(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

	// RefreshTokenWithBody request with any body
	RefreshTokenWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

	RefreshToken(ctx context.Context, body RefreshTokenJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

	// RegisterUserWithBody request with any body
	RegisterUserWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

	RegisterUser(ctx context.Context, body RegisterUserJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

	// EchoWithBody request with any body
	EchoWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

	Echo(ctx context.Context, body EchoJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

	// ListPets request
	ListPets(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

	// CreatePetWithBody request with any body
	CreatePetWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

	CreatePet(ctx context.Context, body CreatePetJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

	// ShowPetById request
	ShowPetById(ctx context.Context, petId ID, reqEditors ...RequestEditorFn) (*http.Response, error)

	// ListUsers request
	ListUsers(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

	// CreateUserWithBody request with any body
	CreateUserWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

	CreateUser(ctx context.Context, body CreateUserJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

	// DeleteUser request
	DeleteUser(ctx context.Context, userId ID, reqEditors ...RequestEditorFn) (*http.Response, error)

	// GetUserById request
	GetUserById(ctx context.Context, userId ID, reqEditors ...RequestEditorFn) (*http.Response, error)

	// UpdateUserWithBody request with any body
	UpdateUserWithBody(ctx context.Context, userId ID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

	UpdateUser(ctx context.Context, userId ID, body UpdateUserJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)
}

The interface specification for the client above.

type ClientOption

type ClientOption func(*Client) error

ClientOption allows setting custom parameters during construction

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL overrides the baseURL.

func WithHTTPClient

func WithHTTPClient(doer HttpRequestDoer) ClientOption

WithHTTPClient allows overriding the default Doer, which is automatically created using http.Client. This is useful for tests.

func WithRequestEditorFn

func WithRequestEditorFn(fn RequestEditorFn) ClientOption

WithRequestEditorFn allows setting up a callback function, which will be called right before sending the request. This can be used to mutate the request.

type ClientWithResponses

type ClientWithResponses struct {
	ClientInterface
}

ClientWithResponses builds on ClientInterface to offer response payloads

func NewClientWithResponses

func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error)

NewClientWithResponses creates a new ClientWithResponses, which wraps Client with return type handling

func (*ClientWithResponses) CreatePetWithBodyWithResponse

func (c *ClientWithResponses) CreatePetWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreatePetResponse, error)

CreatePetWithBodyWithResponse request with arbitrary body returning *CreatePetResponse

func (*ClientWithResponses) CreatePetWithResponse

func (c *ClientWithResponses) CreatePetWithResponse(ctx context.Context, body CreatePetJSONRequestBody, reqEditors ...RequestEditorFn) (*CreatePetResponse, error)

func (*ClientWithResponses) CreateUserWithBodyWithResponse

func (c *ClientWithResponses) CreateUserWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateUserResponse, error)

CreateUserWithBodyWithResponse request with arbitrary body returning *CreateUserResponse

func (*ClientWithResponses) CreateUserWithResponse

func (c *ClientWithResponses) CreateUserWithResponse(ctx context.Context, body CreateUserJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateUserResponse, error)

func (*ClientWithResponses) DeleteUserWithResponse

func (c *ClientWithResponses) DeleteUserWithResponse(ctx context.Context, userId ID, reqEditors ...RequestEditorFn) (*DeleteUserResponse, error)

DeleteUserWithResponse request returning *DeleteUserResponse

func (*ClientWithResponses) EchoWithBodyWithResponse

func (c *ClientWithResponses) EchoWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*EchoResponse, error)

EchoWithBodyWithResponse request with arbitrary body returning *EchoResponse

func (*ClientWithResponses) EchoWithResponse

func (c *ClientWithResponses) EchoWithResponse(ctx context.Context, body EchoJSONRequestBody, reqEditors ...RequestEditorFn) (*EchoResponse, error)

func (*ClientWithResponses) GetCurrentUserWithResponse

func (c *ClientWithResponses) GetCurrentUserWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetCurrentUserResponse, error)

GetCurrentUserWithResponse request returning *GetCurrentUserResponse

func (*ClientWithResponses) GetUserByIdWithResponse

func (c *ClientWithResponses) GetUserByIdWithResponse(ctx context.Context, userId ID, reqEditors ...RequestEditorFn) (*GetUserByIdResponse, error)

GetUserByIdWithResponse request returning *GetUserByIdResponse

func (*ClientWithResponses) ListPetsWithResponse

func (c *ClientWithResponses) ListPetsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListPetsResponse, error)

ListPetsWithResponse request returning *ListPetsResponse

func (*ClientWithResponses) ListUsersWithResponse

func (c *ClientWithResponses) ListUsersWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListUsersResponse, error)

ListUsersWithResponse request returning *ListUsersResponse

func (*ClientWithResponses) LoginUserWithBodyWithResponse

func (c *ClientWithResponses) LoginUserWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*LoginUserResponse, error)

LoginUserWithBodyWithResponse request with arbitrary body returning *LoginUserResponse

func (*ClientWithResponses) LoginUserWithResponse

func (c *ClientWithResponses) LoginUserWithResponse(ctx context.Context, body LoginUserJSONRequestBody, reqEditors ...RequestEditorFn) (*LoginUserResponse, error)

func (*ClientWithResponses) LogoutUserWithResponse

func (c *ClientWithResponses) LogoutUserWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*LogoutUserResponse, error)

LogoutUserWithResponse request returning *LogoutUserResponse

func (*ClientWithResponses) RefreshTokenWithBodyWithResponse

func (c *ClientWithResponses) RefreshTokenWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RefreshTokenResponse, error)

RefreshTokenWithBodyWithResponse request with arbitrary body returning *RefreshTokenResponse

func (*ClientWithResponses) RefreshTokenWithResponse

func (c *ClientWithResponses) RefreshTokenWithResponse(ctx context.Context, body RefreshTokenJSONRequestBody, reqEditors ...RequestEditorFn) (*RefreshTokenResponse, error)

func (*ClientWithResponses) RegisterUserWithBodyWithResponse

func (c *ClientWithResponses) RegisterUserWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RegisterUserResponse, error)

RegisterUserWithBodyWithResponse request with arbitrary body returning *RegisterUserResponse

func (*ClientWithResponses) RegisterUserWithResponse

func (c *ClientWithResponses) RegisterUserWithResponse(ctx context.Context, body RegisterUserJSONRequestBody, reqEditors ...RequestEditorFn) (*RegisterUserResponse, error)

func (*ClientWithResponses) ShowPetByIdWithResponse

func (c *ClientWithResponses) ShowPetByIdWithResponse(ctx context.Context, petId ID, reqEditors ...RequestEditorFn) (*ShowPetByIdResponse, error)

ShowPetByIdWithResponse request returning *ShowPetByIdResponse

func (*ClientWithResponses) UpdateUserWithBodyWithResponse

func (c *ClientWithResponses) UpdateUserWithBodyWithResponse(ctx context.Context, userId ID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateUserResponse, error)

UpdateUserWithBodyWithResponse request with arbitrary body returning *UpdateUserResponse

func (*ClientWithResponses) UpdateUserWithResponse

func (c *ClientWithResponses) UpdateUserWithResponse(ctx context.Context, userId ID, body UpdateUserJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateUserResponse, error)

func (*ClientWithResponses) Valid

func (x *ClientWithResponses) Valid() error

Validate ClientWithResponses using the specified tags

type ClientWithResponsesInterface

type ClientWithResponsesInterface interface {
	// LoginUserWithBodyWithResponse request with any body
	LoginUserWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*LoginUserResponse, error)

	LoginUserWithResponse(ctx context.Context, body LoginUserJSONRequestBody, reqEditors ...RequestEditorFn) (*LoginUserResponse, error)

	// LogoutUserWithResponse request
	LogoutUserWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*LogoutUserResponse, error)

	// GetCurrentUserWithResponse request
	GetCurrentUserWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetCurrentUserResponse, error)

	// RefreshTokenWithBodyWithResponse request with any body
	RefreshTokenWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RefreshTokenResponse, error)

	RefreshTokenWithResponse(ctx context.Context, body RefreshTokenJSONRequestBody, reqEditors ...RequestEditorFn) (*RefreshTokenResponse, error)

	// RegisterUserWithBodyWithResponse request with any body
	RegisterUserWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RegisterUserResponse, error)

	RegisterUserWithResponse(ctx context.Context, body RegisterUserJSONRequestBody, reqEditors ...RequestEditorFn) (*RegisterUserResponse, error)

	// EchoWithBodyWithResponse request with any body
	EchoWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*EchoResponse, error)

	EchoWithResponse(ctx context.Context, body EchoJSONRequestBody, reqEditors ...RequestEditorFn) (*EchoResponse, error)

	// ListPetsWithResponse request
	ListPetsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListPetsResponse, error)

	// CreatePetWithBodyWithResponse request with any body
	CreatePetWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreatePetResponse, error)

	CreatePetWithResponse(ctx context.Context, body CreatePetJSONRequestBody, reqEditors ...RequestEditorFn) (*CreatePetResponse, error)

	// ShowPetByIdWithResponse request
	ShowPetByIdWithResponse(ctx context.Context, petId ID, reqEditors ...RequestEditorFn) (*ShowPetByIdResponse, error)

	// ListUsersWithResponse request
	ListUsersWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListUsersResponse, error)

	// CreateUserWithBodyWithResponse request with any body
	CreateUserWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateUserResponse, error)

	CreateUserWithResponse(ctx context.Context, body CreateUserJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateUserResponse, error)

	// DeleteUserWithResponse request
	DeleteUserWithResponse(ctx context.Context, userId ID, reqEditors ...RequestEditorFn) (*DeleteUserResponse, error)

	// GetUserByIdWithResponse request
	GetUserByIdWithResponse(ctx context.Context, userId ID, reqEditors ...RequestEditorFn) (*GetUserByIdResponse, error)

	// UpdateUserWithBodyWithResponse request with any body
	UpdateUserWithBodyWithResponse(ctx context.Context, userId ID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateUserResponse, error)

	UpdateUserWithResponse(ctx context.Context, userId ID, body UpdateUserJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateUserResponse, error)
}

ClientWithResponsesInterface is the interface specification for the client with responses above.

type Conflict

type Conflict = Error

Conflict Error response

type CreatePetJSONRequestBody

type CreatePetJSONRequestBody = Pet

CreatePetJSONRequestBody defines body for CreatePet for application/json ContentType.

type CreatePetResponse

type CreatePetResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON201      *Pet
	JSON400      *BadRequest
	JSON401      *Unauthorized
	JSON403      *Forbidden
	JSON404      *NotFound
	JSON429      *TooManyRequests
	JSON500      *InternalServerError
	JSONDefault  *UnexpectedError
}

func ParseCreatePetResponse

func ParseCreatePetResponse(rsp *http.Response) (*CreatePetResponse, error)

ParseCreatePetResponse parses an HTTP response from a CreatePetWithResponse call

func (CreatePetResponse) Status

func (r CreatePetResponse) Status() string

Status returns HTTPResponse.Status

func (CreatePetResponse) StatusCode

func (r CreatePetResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*CreatePetResponse) Valid

func (x *CreatePetResponse) Valid() error

Validate CreatePetResponse using the specified tags

type CreateUserJSONRequestBody

type CreateUserJSONRequestBody = Registration

CreateUserJSONRequestBody defines body for CreateUser for application/json ContentType.

type CreateUserResponse

type CreateUserResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON201      *User
	JSON400      *BadRequest
	JSON401      *Unauthorized
	JSON403      *Forbidden
	JSON409      *Conflict
	JSON429      *TooManyRequests
	JSON500      *InternalServerError
	JSONDefault  *UnexpectedError
}

func ParseCreateUserResponse

func ParseCreateUserResponse(rsp *http.Response) (*CreateUserResponse, error)

ParseCreateUserResponse parses an HTTP response from a CreateUserWithResponse call

func (CreateUserResponse) Status

func (r CreateUserResponse) Status() string

Status returns HTTPResponse.Status

func (CreateUserResponse) StatusCode

func (r CreateUserResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*CreateUserResponse) Valid

func (x *CreateUserResponse) Valid() error

Validate CreateUserResponse using the specified tags

type DeleteUserResponse

type DeleteUserResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON400      *BadRequest
	JSON401      *Unauthorized
	JSON403      *Forbidden
	JSON404      *NotFound
	JSON429      *TooManyRequests
	JSON500      *InternalServerError
	JSONDefault  *UnexpectedError
}

func ParseDeleteUserResponse

func ParseDeleteUserResponse(rsp *http.Response) (*DeleteUserResponse, error)

ParseDeleteUserResponse parses an HTTP response from a DeleteUserWithResponse call

func (DeleteUserResponse) Status

func (r DeleteUserResponse) Status() string

Status returns HTTPResponse.Status

func (DeleteUserResponse) StatusCode

func (r DeleteUserResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*DeleteUserResponse) Valid

func (x *DeleteUserResponse) Valid() error

Validate DeleteUserResponse using the specified tags

type EchoJSONRequestBody

type EchoJSONRequestBody = EchoReq

EchoJSONRequestBody defines body for Echo for application/json ContentType.

type EchoMsg

type EchoMsg struct {
	Msg string `json:"msg"`
}

EchoMsg WebSocket echo message payload

func (*EchoMsg) Valid

func (x *EchoMsg) Valid() error

Validate EchoMsg using the specified tags

type EchoReq

type EchoReq struct {
	Msg string `json:"msg"`
}

EchoReq Schema for the echo endpoint request body

func (*EchoReq) Valid

func (x *EchoReq) Valid() error

Validate EchoReq using the specified tags

type EchoResp

type EchoResp struct {
	Msg string `json:"msg"`
}

EchoResp Echo response payload

func (*EchoResp) Valid

func (x *EchoResp) Valid() error

Validate EchoResp using the specified tags

type EchoResponse

type EchoResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *EchoResp
	JSON400      *BadRequest
	JSON401      *Unauthorized
	JSON429      *TooManyRequests
	JSON500      *InternalServerError
}

func ParseEchoResponse

func ParseEchoResponse(rsp *http.Response) (*EchoResponse, error)

ParseEchoResponse parses an HTTP response from a EchoWithResponse call

func (EchoResponse) Status

func (r EchoResponse) Status() string

Status returns HTTPResponse.Status

func (EchoResponse) StatusCode

func (r EchoResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*EchoResponse) Valid

func (x *EchoResponse) Valid() error

Validate EchoResponse using the specified tags

type Error

type Error struct {
	// Error Error code
	Error string `json:"error"`

	// Id id for the Record
	Id *ID `json:"id,omitempty"`

	// Message Error message
	Message string `json:"message"`
}

Error Error response

func (*Error) Valid

func (x *Error) Valid() error

Validate Error using the specified tags

type Forbidden

type Forbidden = Error

Forbidden Error response

type GeneratedServerInterface

ServerInterface defines the business logic contract for generated HTTP endpoints. Embed UnimplementedServer and override only the methods you need.

Streaming endpoints (route declared "streaming": true in the apic config) use a different method contract: func(http.ResponseWriter, *http.Request, *ReqType) error. For those the generated wrapper still performs every pre-handler concern -- auth/role/scope checks, rate limiting, body size limits, request parsing and validation, the standard JSON error envelope for *pre-handler* failures -- and then hands control to the user handler, which owns the entire 200 response: it must write its own status line, Content-Type, and body, flushing as it goes via http.Flusher.

Streaming-handler error contract: if the handler returns a non-nil error *before writing any bytes*, the wrapper emits the standard error envelope (500, or 501 for ErrNotImplemented). If the handler has *already written bytes* and then returns an error, the response headers are already on the wire -- the wrapper logs the error (http_handler_err audit event) but cannot change the status; the handler is responsible for signalling the failure in-band (e.g. truncating the stream / writing an error chunk). The cleanest discipline is: a streaming handler never returns an error after it has written anything.

func NewCatchAllServer

func NewCatchAllServer(handler CatchAllServerInterface) GeneratedServerInterface

NewCatchAllServer wraps a generic route handler so it satisfies ServerInterface.

type GetCurrentUserResponse

type GetCurrentUserResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *User
	JSON400      *BadRequest
	JSON401      *Unauthorized
	JSON403      *Forbidden
	JSON429      *TooManyRequests
	JSON500      *InternalServerError
	JSONDefault  *UnexpectedError
}

func ParseGetCurrentUserResponse

func ParseGetCurrentUserResponse(rsp *http.Response) (*GetCurrentUserResponse, error)

ParseGetCurrentUserResponse parses an HTTP response from a GetCurrentUserWithResponse call

func (GetCurrentUserResponse) Status

func (r GetCurrentUserResponse) Status() string

Status returns HTTPResponse.Status

func (GetCurrentUserResponse) StatusCode

func (r GetCurrentUserResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*GetCurrentUserResponse) Valid

func (x *GetCurrentUserResponse) Valid() error

Validate GetCurrentUserResponse using the specified tags

type GetUserByIdResponse

type GetUserByIdResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *User
	JSON400      *BadRequest
	JSON401      *Unauthorized
	JSON403      *Forbidden
	JSON404      *NotFound
	JSON429      *TooManyRequests
	JSON500      *InternalServerError
	JSONDefault  *UnexpectedError
}

func ParseGetUserByIdResponse

func ParseGetUserByIdResponse(rsp *http.Response) (*GetUserByIdResponse, error)

ParseGetUserByIdResponse parses an HTTP response from a GetUserByIdWithResponse call

func (GetUserByIdResponse) Status

func (r GetUserByIdResponse) Status() string

Status returns HTTPResponse.Status

func (GetUserByIdResponse) StatusCode

func (r GetUserByIdResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*GetUserByIdResponse) Valid

func (x *GetUserByIdResponse) Valid() error

Validate GetUserByIdResponse using the specified tags

type GinServerOptions

type GinServerOptions struct {
	BaseURL      string
	Middlewares  []MiddlewareFunc
	ErrorHandler func(*gin.Context, error, int)
}

GinServerOptions provides options for the Gin server.

func (*GinServerOptions) Valid

func (x *GinServerOptions) Valid() error

Validate GinServerOptions using the specified tags

type HttpRequestDoer

type HttpRequestDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

Doer performs HTTP requests.

The standard http.Client implements this interface.

type ID

type ID = uuid.UUID

ID id for the Record

type InternalServerError

type InternalServerError = Error

InternalServerError Error response

type ListPetsResponse

type ListPetsResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *[]Pet
	JSON400      *BadRequest
	JSON401      *Unauthorized
	JSON403      *Forbidden
	JSON404      *NotFound
	JSON429      *TooManyRequests
	JSON500      *InternalServerError
	JSONDefault  *UnexpectedError
}

func ParseListPetsResponse

func ParseListPetsResponse(rsp *http.Response) (*ListPetsResponse, error)

ParseListPetsResponse parses an HTTP response from a ListPetsWithResponse call

func (ListPetsResponse) Status

func (r ListPetsResponse) Status() string

Status returns HTTPResponse.Status

func (ListPetsResponse) StatusCode

func (r ListPetsResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*ListPetsResponse) Valid

func (x *ListPetsResponse) Valid() error

Validate ListPetsResponse using the specified tags

type ListUsersResponse

type ListUsersResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *[]User
	JSON400      *BadRequest
	JSON401      *Unauthorized
	JSON403      *Forbidden
	JSON429      *TooManyRequests
	JSON500      *InternalServerError
	JSONDefault  *UnexpectedError
}

func ParseListUsersResponse

func ParseListUsersResponse(rsp *http.Response) (*ListUsersResponse, error)

ParseListUsersResponse parses an HTTP response from a ListUsersWithResponse call

func (ListUsersResponse) Status

func (r ListUsersResponse) Status() string

Status returns HTTPResponse.Status

func (ListUsersResponse) StatusCode

func (r ListUsersResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*ListUsersResponse) Valid

func (x *ListUsersResponse) Valid() error

Validate ListUsersResponse using the specified tags

type Login

type Login struct {
	// Password Password for authentication
	Password Password `` /* 137-byte string literal not displayed */

	// Username Username for authentication
	Username Username `json:"username" safe-to-log:"true" validate:"required,min=10,max=50,regexp=^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{10,50}$"`
}

Login Login object containing username and password

func (*Login) Valid

func (x *Login) Valid() error

Validate Login using the specified tags

type LoginUserJSONRequestBody

type LoginUserJSONRequestBody = Login

LoginUserJSONRequestBody defines body for LoginUser for application/json ContentType.

type LoginUserResponse

type LoginUserResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *Token
	JSON400      *BadRequest
	JSON401      *Unauthorized
	JSON429      *TooManyRequests
	JSON500      *InternalServerError
	JSONDefault  *UnexpectedError
}

func ParseLoginUserResponse

func ParseLoginUserResponse(rsp *http.Response) (*LoginUserResponse, error)

ParseLoginUserResponse parses an HTTP response from a LoginUserWithResponse call

func (LoginUserResponse) Status

func (r LoginUserResponse) Status() string

Status returns HTTPResponse.Status

func (LoginUserResponse) StatusCode

func (r LoginUserResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*LoginUserResponse) Valid

func (x *LoginUserResponse) Valid() error

Validate LoginUserResponse using the specified tags

type LogoutUserResponse

type LogoutUserResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *struct {
		Message *string `json:"message,omitempty"`
	}
	JSON400     *BadRequest
	JSON401     *Unauthorized
	JSON429     *TooManyRequests
	JSON500     *InternalServerError
	JSONDefault *UnexpectedError
}

func ParseLogoutUserResponse

func ParseLogoutUserResponse(rsp *http.Response) (*LogoutUserResponse, error)

ParseLogoutUserResponse parses an HTTP response from a LogoutUserWithResponse call

func (LogoutUserResponse) Status

func (r LogoutUserResponse) Status() string

Status returns HTTPResponse.Status

func (LogoutUserResponse) StatusCode

func (r LogoutUserResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*LogoutUserResponse) Valid

func (x *LogoutUserResponse) Valid() error

Validate LogoutUserResponse using the specified tags

type MCPParams

type MCPParams struct {
	Msg string `json:"msg"`
}

type MCPResult

type MCPResult struct {
	Msg string `json:"msg"`
}

type MCPTool

type MCPTool func(ctx context.Context, params jsontext.Value) (jsontext.Value, error)

type MiddlewareFunc

type MiddlewareFunc func(c *gin.Context)

type NOOPHandlers

type NOOPHandlers struct{}

func (*NOOPHandlers) CreatePet

func (n *NOOPHandlers) CreatePet(c *gin.Context)

func (*NOOPHandlers) CreateUser

func (n *NOOPHandlers) CreateUser(c *gin.Context)

func (*NOOPHandlers) DeleteUser

func (n *NOOPHandlers) DeleteUser(c *gin.Context, userId ID)

func (*NOOPHandlers) Echo

func (n *NOOPHandlers) Echo(c *gin.Context)

func (*NOOPHandlers) GetCurrentUser

func (n *NOOPHandlers) GetCurrentUser(c *gin.Context)

func (*NOOPHandlers) GetUserById

func (n *NOOPHandlers) GetUserById(c *gin.Context, userId ID)

func (*NOOPHandlers) ListPets

func (n *NOOPHandlers) ListPets(c *gin.Context)

func (*NOOPHandlers) ListUsers

func (n *NOOPHandlers) ListUsers(c *gin.Context)

func (*NOOPHandlers) LoginUser

func (n *NOOPHandlers) LoginUser(c *gin.Context)

func (*NOOPHandlers) LogoutUser

func (n *NOOPHandlers) LogoutUser(c *gin.Context)

func (*NOOPHandlers) RefreshToken

func (n *NOOPHandlers) RefreshToken(c *gin.Context)

func (*NOOPHandlers) RegisterUser

func (n *NOOPHandlers) RegisterUser(c *gin.Context)

func (*NOOPHandlers) ShowPetById

func (n *NOOPHandlers) ShowPetById(c *gin.Context, petId ID)

func (*NOOPHandlers) UpdateUser

func (n *NOOPHandlers) UpdateUser(c *gin.Context, userId ID)

type NotFound

type NotFound = Error

NotFound Error response

type OAuth2Error

type OAuth2Error struct {
	Code        string
	Description string
	URI         string
	Status      int
	Err         error
}

OAuth2Error is the RFC 6749 §5.2 error response shape, used for OIDC / OAuth2 protocol routes (oidc_token, oidc_authorize, oidc_userinfo, oidc_revoke, oidc_introspect, etc.). Returning it from a ServerInterface method causes the generated wrapper to render {"error": Code, "error_description": Description, "error_uri": URI} with Cache-Control: no-store and Pragma: no-cache per RFC 6749 §5.1.

Status defaults to 400 when zero — use 401 for invalid_client per §5.2.

A-NEW-5 (docs/GENERATOR_BUGS.md).

func (*OAuth2Error) Error

func (e *OAuth2Error) Error() string

func (*OAuth2Error) Unwrap

func (e *OAuth2Error) Unwrap() error

type OIDC

type OIDC struct {
	Issuer string `json:"issuer" validate:"required,url,max=255"`

	AuthZURL *url.URL
	TokenURL *url.URL
	UserURL  *url.URL

	LogoutURL      *url.URL
	IntrospectURL  *url.URL
	RevocationURL  *url.URL
	DeviceAuthzURL *url.URL

	JWKsURL *url.URL
	// JWKs holds the cold-start key set so legacy callers continue to
	// observe a non-nil reference. The authoritative, auto-refreshing
	// view lives behind jwkCache and is consulted on every JWT
	// validation path so IdP key rotation is picked up without a host
	// process restart (PERF-0043, SEC #150).
	JWKs jwk.Set

	Aud string

	ResponseTypes [][]string
	ResponseModes []string `json:"response_modes_supported"`
	GrantTypes    []string `json:"grant_types_supported"`

	SigningAlgos         []string `json:"id_token_signing_alg_values_supported"`
	SubjectTypes         []string `json:"subject_types_supported"`
	AuthMethods          []string `json:"token_endpoint_auth_methods_supported"`
	AcrValues            []string `json:"acr_values_supported"`
	Scopes               []string `json:"scopes_supported"`
	Claims               []string `json:"claims_supported"`
	CodeChallengeMethods []string `json:"code_challenge_methods_supported"`

	ClaimsParameters bool `json:"claims_parameter_supported"`
	RequestParameter bool `json:"request_parameter_supported"`
	// contains filtered or unexported fields
}

OIDC holds a fetched and validated OpenID Connect discovery document (RFC/OIDC Discovery 1.0's "https://issuer/.well-known/openid-configuration" response) plus the runtime state needed to verify bearer tokens against it: an auto-refreshing JWKS cache (jwkCache) so IdP key rotation is picked up without a host restart, and a bounded cache of already-verified tokens (tokenCache) so a byte-identical Authorization header does not re-run asymmetric signature verification on every request. Construct one via LoadOIDC; OIDC.JWT is the gin middleware that extracts and verifies bearer tokens, and OIDC.Authenticate is the AuthenticationFunc the OpenAPI request validator invokes to enforce `security: bearerAuth` routes.

func LoadOIDC

func LoadOIDC(
	ctx context.Context,
	log log.Logger,
	client *htpx.Client,
	oidcURL string,
	aud string,
) (*OIDC, error)

LoadOIDC loads the OpenID Connect configuration from the given URL. @client: HTTP client to use for the request. @url: URL of the OpenID Connect configuration endpoint. @aud: Audience of the OpenID Connect configuration endpoint (usually the client ID of the application). @return: OpenID Connect configuration.

func (*OIDC) Authenticate

func (o *OIDC) Authenticate(
	ctx context.Context, input *oapifilter.AuthenticationInput,
) error

Authenticate is the oapi-codegen AuthenticationFunc for this OIDC instance: it requires a verified JWT on the request and enforces every OAuth2 scope the OpenAPI security scheme declared for the operation. The token itself is verified upstream by the JWT extractor middleware; this function only reads the verified token off the context and checks scopes.

func (*OIDC) ExtractToken

func (o *OIDC) ExtractToken(ctx *gin.Context) (jwt.Token, error)

ExtractToken parses the Authorization HTTP header for valid JWT token and validates it with the JWK keys. Also verifies if the audience present in the token matches with the designated audience as per current configuration.

PERF-0021 (#156): successful verifications are memoized in a bounded per-OIDC LRU keyed by the SHA-256 of the raw compact token, for at most min(token exp, 60s). A byte-identical bearer within that window skips the asymmetric signature verification; the cache read path still enforces current-time expiry, and failures are never cached. The audience/issuer binding is configuration on this OIDC instance, so a hit can never cross aud/iss boundaries.

func (*OIDC) JWT

func (o *OIDC) JWT(ctx *gin.Context)

JWT is the token EXTRACTOR middleware — not an enforcer. It verifies a Bearer token when one is present and stashes it in the gin context (under ctxTokenKey) for the downstream consumers that DO enforce: the OpenAPI request validator's AuthenticationFunc (OIDC.Authenticate) and OwnershipGuard. The contract (QG-070, #227):

  • Authorization header absent -> pass through WITHOUT aborting and WITHOUT recording any token. Routes that require auth still fail later in OIDC.Authenticate (no token in context -> AuthToken returns an error -> denied); public routes proceed unauthenticated.
  • Header present but invalid (malformed, bad signature/audience, unsupported algorithm, ...) -> abort 401 immediately.

The missing-header sentinel is matched with errors.Is so a wrapped ErrAuthHeaderMissing still routes to the pass-through branch.

A-02 (appsec 2026-06-15): because the absent-header branch is a deliberate non-terminal pass-through, JWT is SAFE ONLY when paired with an enforcer. Every NON-PUBLIC route MUST also run OIDC.Authenticate (mounted via the openapi3filter validator's AuthenticationFunc) — a route that inherits JWT but never Authenticate is unenforced and will serve unauthenticated callers. JWT never stashes a token on the no-credential path, so a missing-Authenticate route can never mistake a pass-through for a validated request; it simply has no credential. The fail-closed contract is pinned by TestJWT_MissingAuthHeader_FailClosedContract.

func (*OIDC) UnmarshalJSON

func (o *OIDC) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes an OIDC discovery document (the JSON body LoadOIDC fetched from the provider's "/.well-known/openid-configuration" endpoint) into o. Beyond a plain field-by-field decode it: validates the document's required fields and URL shapes via the shared go-playground validator, rejects any endpoint URL that is not https (ErrInvalidScheme), checks the advertised issuer against the discovery URL o.discoveryURL was fetched from when one was set (ErrIssuerMismatch, OIDC Discovery 1.0 §4.3), and -- on success -- builds the auto-refreshing JWKS cache (o.jwkCache) and primes the legacy o.JWKs field from it. Called internally by LoadOIDC via json.UnmarshalRead; not normally invoked directly.

type Option

type Option func(*apiServer) error

Option configures the apiServer New builds, applied in the order passed to New. Every Option returns an error so a caller-supplied setting can be rejected (e.g. RateLimit's bounds check) instead of silently ignored.

func Host

func Host(host string) Option

Host sets the address the server's listener binds to (default "localhost"). Pass an empty string or "0.0.0.0" to bind every interface.

func Port

func Port(port int) Option

Port sets the TCP port the server's listener binds to (default 8443). Port 0 selects an OS-assigned ephemeral port.

func RateLimit

func RateLimit(limit int, duration time.Duration) Option

RateLimit configures a global request-count limit over duration; limit must fall within [rateLimitMin, rateLimitMax] (100-1000) and duration within [rateMinDuration, rateMaxDuration] (1s-24h), matching the same bounds validateConfig enforces at startup. Values outside either range are rejected here at option-application time rather than deferred to Serve.

func WithCORS

func WithCORS(allowedOrigins []string, methods ...string) Option

WithCORS installs gin-contrib/cors middleware allowing the given origins and HTTP methods. An empty allowedOrigins defaults to "<defaultHost>:<defaultPort>" and logs a warning; an empty methods defaults to GET/POST/PUT/DELETE. In APIC_INSECURE_DEV mode (gin debug mode plus the env var, on loopback) every origin is allowed regardless of allowedOrigins, to ease local development. Omitting WithCORS entirely means no CORS headers are sent at all -- same-origin requests still work; the browser's default same-origin policy blocks the rest, which is the secure default.

func WithCorrelation added in v0.15.0

func WithCorrelation(header string) Option

WithCorrelation mounts the correlation-id middleware: it honors a valid inbound header, otherwise generates a fresh id, echoes it on the response, and stores it in the request context. header == "" uses obsx.DefaultCorrelationHeader. A non-empty header is validated against obsx.ValidCorrelationHeaderName (the same grammar+reserved-list check cmd/apic's config validator and the generated server's Serve-time resolution use); an invalid or reserved name (e.g. "Authorization") fails fast here, since Option already returns error, rather than silently mounting a header that could leak or clobber a security-sensitive header. Recommended order: pass after WithTracing/WithOTEL/WithTelemetry so tracing stays outermost.

func WithErrorHandler

func WithErrorHandler(handler func(ctx *gin.Context, err error, i int)) Option

WithErrorHandler stores a (ctx, error, HTTP status) callback on the apiServer for error rendering. A nil handler is replaced with a default that writes `{"error": "<message>"}` at the given status.

Note: nothing in this package currently reads apiServer.errorHandler back out again -- specEnforcer renders its own inline gin.H{"error":...} responses directly rather than calling it. WithErrorHandler is kept for source compatibility with callers that already set it; it has no observable effect on request handling today.

func WithImpl deprecated

func WithImpl(impl any) Option

WithImpl is retained only for source compatibility.

Deprecated: WithImpl has never had any effect — it only logged its argument. The ServerInterface implementation is registered through the Register callback passed to New (e.g. api.RegisterHandlers(engine, impl) inside reg(); see cmd/api/main.go). Wiring this option would duplicate that registration path for zero existing callers, so it is deprecated instead and will be removed in the next major version. QG-071 (#228). (The WithImpl in generated server packages — gen/*/server — is a different, functional option and is unaffected.)

func WithLogFile added in v0.15.0

func WithLogFile(cfg obsx.LogFileConfig) Option

WithLogFile enables rotating on-disk log delivery (lumberjack): structured log records are fanned into a size-rotated file IN ADDITION to stdout, INSIDE the same redaction wrapper so on-disk lines are redacted like every other sink. Zero size/backup/age members inherit the auditx defaults (100 MiB / 7 backups / 365 days). It is fail-closed: an unwritable path surfaces as an error from New() rather than silently dropping logs. The file closer is registered on the shutdown chain so buffered records flush on exit. Combinations with WithOTEL now compose automatically — New() fans every log-sink option into a single redacted logger after the options loop, so ordering relative to WithOTEL does not matter.

cfg.AsyncQueueSize is the code-level twin of the generated server's observability.logs.file.async_queue_size knob (SEC-0079 / PERF-0123): zero inherits the 1024-record default; an explicit value below configx.MinLogFileAsyncQueueSize (64) or above configx.MaxLogFileAsyncQueueSize (2^20 -- the queue grows lazily, so the ceiling bounds peak queued-record memory under a stalled disk, not a boot allocation) is rejected here exactly as the generator rejects it in config, so a hand-wired api.New() service cannot end up with a queue that sheds records under ordinary burst, or with an unbounded stall backlog.

func WithLogger

func WithLogger(logger log.Logger) Option

WithLogger configures the devnw.dev/log.Logger used for this server's own startup/handler-level messages (s.log) -- a distinct abstraction from obsx's request_start/request_end structured logging. It does NOT change the base *slog.Handler obsx.SetLogger installs -- New builds that as a plain slog.NewJSONHandler over obsx.TSKeyWriter(os.Stdout) with NIL options, the writer-side rename that preserves request logs' "ts" field. Do not reintroduce slog.HandlerOptions{ReplaceAttr: obsx.ReplaceAttrTS} here or at the construction site: PERF-0132 (#393) removed that hook precisely because it put every record on the JSON handler's slow path, 18 allocations against TSKeyWriter's 12 -- see TSKeyWriter's doc. There is currently no Option to override that base handler directly.

func WithMTLS

func WithMTLS(caBundlePath string) Option

WithMTLS configures the TLS listener to require and verify client certificates against the CA bundle at path. Per-route mTLS policy (issuer allow-list, CRL/OCSP, EKU) is enforced by generated handlers via mtlsx.Verifier; this option only seeds the listener's tls.Config.ClientCAs trust pool.

func WithMaxBodyBytes

func WithMaxBodyBytes(n int64) Option

WithMaxBodyBytes overrides the request-body size limit (PERF-0036). The default is defaultMaxBodyBytes (10 MiB); pass a larger value for routes that accept big uploads, or 0 to disable bounding entirely (e.g. fully streaming endpoints). The limit is enforced by http.MaxBytesReader before any handler or the OpenAPI request validator reads the body.

func WithMetrics added in v0.15.0

func WithMetrics(m obsx.MetricsProvider) Option

WithMetrics injects a custom obsx.MetricsProvider (no scrape endpoint — pair with WithPrometheus or your own exposition). When combined with WithPrometheus in the same New() call, WithMetrics must come first: WithPrometheus then wins as the global sink and stays wired to the /metrics endpoint it mounts. Passing WithMetrics after WithPrometheus is rejected — see WithPrometheus.

func WithMiddleware

func WithMiddleware(middleware ...gin.HandlerFunc) Option

WithMiddleware appends caller-supplied gin.HandlerFuncs to the engine's middleware chain, after the always-on base chain (request logging, panic recovery, body-size limiting) and after any middleware added by other Options (e.g. WithValidation's JWT extractor/spec enforcer), but before the caller's own routes are registered. May be passed more than once; each call appends rather than replaces.

func WithOTEL added in v0.15.0

func WithOTEL(ctx context.Context, cfg ...otelx.Config) Option

WithOTEL bootstraps OpenTelemetry from the standard OTEL_* env vars, optionally overridden field-by-field by cfg (code wins over env — see otelx.Config). When active it wires the W3C trace-context middleware, registers the OTLP exporters (traces/metrics, and log delivery when the logs signal is active), and installs a shutdown flush hook. When the merged config is inactive (no endpoint, not enabled, or disabled) the option is a no-op, so it is safe to pass unconditionally.

func WithObservability

func WithObservability() Option

WithObservability wires the obsx request middleware (structured request logging + request IDs + latency/status metrics) into the Gin middleware chain. Off unless called, so the default wire shape is unchanged (GAP-0072 / QG-044).

func WithPeerRateLimit

func WithPeerRateLimit(rate, burst float64, src httpx.IPSource) Option

WithPeerRateLimit installs a per-IP token-bucket rate limiter in front of every route. rate is tokens/second and burst the bucket size; src selects the client-key extractor ("remote_addr" is the safe default — see httpx.IPSource). A rate <= 0 is the disabled signal and the option becomes a no-op, preserving the current default (no limiter). On rejection the limiter emits 429 with Retry-After and a JSON envelope. The limiter holds a background sweeper goroutine for the life of the server. GAP-0072.

func WithPrometheus added in v0.15.0

func WithPrometheus(auth func(*http.Request) bool, cfg ...promx.Config) Option

WithPrometheus installs a label-preserving Prometheus metrics provider as the global obsx metrics sink and mounts GET /metrics guarded by auth, serving that same provider's registry. auth is REQUIRED (fail closed): metrics leak route names, latencies, and traffic shape, so the endpoint is never exposed unauthenticated. Wire auth to your bearer-token or mTLS check; it runs before the scrape handler on every request. A later WithMetrics in the same New() call is rejected, since it would silently disconnect /metrics from the active provider.

func WithShutdownTimeout added in v0.17.0

func WithShutdownTimeout(d time.Duration) Option

WithShutdownTimeout overrides the graceful http.Server.Shutdown budget Serve applies once ctx is cancelled (default 30s, matching the generated server's healthx.Manager.ShutdownTimeout default). A non-positive d is ignored (the default is kept). N-19.

func WithSigner

func WithSigner(backendName string, cfg signerx.BackendConfig, ref signerx.KeyRef) Option

WithSigner configures the TLS listener to obtain its server leaf certificate from a signerx Backend (PKCS#11 HSM, AWS KMS, Azure Key Vault, or the dev-only softfile) instead of loading a PEM keypair from disk. The private key never enters the process as raw bytes -- every TLS handshake signature is produced by the backend (NIST 800-53 SC-12).

backendName is the registered signerx backend ("pkcs11", "awskms", "azurekv", "softfile"); cfg is that backend's raw configuration (library_path/token_label, region, vault_url, path, ...); ref selects the key (and, for backends that expose CKO_CERTIFICATE, its leaf) plus any activation PIN.

The backend's leaf certificate MUST be retrievable via Backend.Open (SignerHandle.Cert); WithSigner fails the first handshake otherwise. WithSigner composes with WithMTLS: supplying both yields an HSM-backed server certificate that also requires and verifies client certs.

func WithSwaggerSpec

func WithSwaggerSpec(spec *openapi3.T) Option

WithSwaggerSpec supplies the parsed OpenAPI 3 document New's request validator enforces (parameter/body shape and, when OIDC is configured via WithValidation, the `security` requirements on each route). Callers that never supply one and also configure OIDC fall back to the spec embedded in this package (GetSwagger); if neither is available, New fails closed rather than serve secured routes unvalidated.

func WithTLS

func WithTLS(cert, key string) Option

WithTLS sets the filesystem paths to the PEM certificate and private key New's listener loads for TLS. Both must be supplied together (an empty cert with a non-empty key, or vice versa, fails validateConfig); leaving both empty is only accepted in APIC_INSECURE_DEV mode.

func WithTelemetry added in v0.15.0

func WithTelemetry(tp *obsx.TelemetryProvider) Option

WithTelemetry injects a pre-built OTEL provider pair (advanced: custom exporters, alternate SDKs). Most callers want WithOTEL. Also mounts the trace-context middleware.

func WithTracing added in v0.15.0

func WithTracing() Option

WithTracing enables W3C trace-context propagation (headers-only when no exporter is configured; full spans when WithOTEL/WithTelemetry is also active) by mounting the tracing middleware and turning propagation-only mode on. Safe to combine with WithOTEL/WithTelemetry — the middleware is mounted at most once regardless of call order, guarded by an internal flag. Recommended order: pass WithTracing (or WithOTEL/WithTelemetry) before WithCorrelation so the trace-context span wraps the correlation-id middleware (outermost-first mounting).

func WithTrustedProxies

func WithTrustedProxies(proxies []string) Option

WithTrustedProxies configures gin's trusted-proxy CIDR list (gin.Engine.SetTrustedProxies), which controls which upstream addresses New's engine trusts to set client-IP-bearing headers such as X-Forwarded-For. A nil slice leaves gin's own default trusted-proxy configuration in place and logs a warning; New returns an error if the supplied list fails gin's own CIDR validation.

func WithValidation

func WithValidation(
	ctx context.Context,
	oidc string,
	audience string,
) Option

WithValidation wires OIDC-backed request authentication and OpenAPI request validation into New. When oidc is a non-empty discovery URL, it loads the provider's configuration (LoadOIDC), prepends the resulting OIDC.JWT bearer-token extractor to the middleware chain, and mounts the OpenAPI request validator (specEnforcer) with OIDC.Authenticate as its AuthenticationFunc against either the spec from WithSwaggerSpec or, if none was supplied, this package's embedded spec (GetSwagger) -- New fails if OIDC is configured but no spec can be resolved. When oidc is empty, WithValidation fails unless APIC_INSECURE_DEV mode is active (gin debug mode plus the env var, on loopback); even then the request validator is mounted only if a spec is separately supplied via WithSwaggerSpec, and no security requirements are enforced against it (the AuthenticationFunc is a no-op). audience is the JWT "aud" claim OIDC.ExtractToken requires a token to carry.

type Password

type Password = string

Password Password for authentication

type Pet

type Pet struct {
	// Id id for the Record
	Id *ID `json:"id,omitempty"`

	// Name Name of the pet
	Name string `json:"name"`

	// Tag Tag or label for the pet
	Tag *string `json:"tag,omitempty"`
}

Pet A pet entity

func (*Pet) Valid

func (x *Pet) Valid() error

Validate Pet using the specified tags

type RefreshTokenJSONBody

type RefreshTokenJSONBody struct {
	// RefreshToken JWT or similar token for refresh
	RefreshToken *string `json:"refreshToken,omitempty"`
}

RefreshTokenJSONBody defines parameters for RefreshToken.

func (*RefreshTokenJSONBody) Valid

func (x *RefreshTokenJSONBody) Valid() error

Validate RefreshTokenJSONBody using the specified tags

type RefreshTokenJSONRequestBody

type RefreshTokenJSONRequestBody RefreshTokenJSONBody

RefreshTokenJSONRequestBody defines body for RefreshToken for application/json ContentType.

type RefreshTokenResponse

type RefreshTokenResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *Token
	JSON400      *BadRequest
	JSON401      *Unauthorized
	JSON429      *TooManyRequests
	JSON500      *InternalServerError
	JSONDefault  *UnexpectedError
}

func ParseRefreshTokenResponse

func ParseRefreshTokenResponse(rsp *http.Response) (*RefreshTokenResponse, error)

ParseRefreshTokenResponse parses an HTTP response from a RefreshTokenWithResponse call

func (RefreshTokenResponse) Status

func (r RefreshTokenResponse) Status() string

Status returns HTTPResponse.Status

func (RefreshTokenResponse) StatusCode

func (r RefreshTokenResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*RefreshTokenResponse) Valid

func (x *RefreshTokenResponse) Valid() error

Validate RefreshTokenResponse using the specified tags

type Register

type Register func(*gin.Engine) error

Register is the caller-supplied callback New invokes to attach routes to the gin.Engine it built -- typically the generated ServerInterface's RegisterHandlers, e.g. `func(r *gin.Engine) error { api.RegisterHandlers(r, impl); return nil }` (RegisterHandlers itself returns nothing, so the Register callback calls it and then returns nil). It runs after every always-on and Option-installed middleware is mounted but before Option-provided extra routes (e.g. WithPrometheus's /metrics), so user-registered routes can never be shadowed by them.

type RegisterUserJSONRequestBody

type RegisterUserJSONRequestBody = Registration

RegisterUserJSONRequestBody defines body for RegisterUser for application/json ContentType.

type RegisterUserResponse

type RegisterUserResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON201      *User
	JSON400      *BadRequest
	JSON401      *Unauthorized
	JSON409      *Conflict
	JSON429      *TooManyRequests
	JSON500      *InternalServerError
	JSONDefault  *UnexpectedError
}

func ParseRegisterUserResponse

func ParseRegisterUserResponse(rsp *http.Response) (*RegisterUserResponse, error)

ParseRegisterUserResponse parses an HTTP response from a RegisterUserWithResponse call

func (RegisterUserResponse) Status

func (r RegisterUserResponse) Status() string

Status returns HTTPResponse.Status

func (RegisterUserResponse) StatusCode

func (r RegisterUserResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*RegisterUserResponse) Valid

func (x *RegisterUserResponse) Valid() error

Validate RegisterUserResponse using the specified tags

type Registration

type Registration struct {
	// Password Password for authentication
	Password Password `` /* 137-byte string literal not displayed */

	// Username Username for authentication
	Username Username `json:"username" safe-to-log:"true" validate:"required,min=10,max=50,regexp=^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{10,50}$"`
}

Registration Registration object containing username and password

func (*Registration) Valid

func (x *Registration) Valid() error

Validate Registration using the specified tags

type RequestEditorFn

type RequestEditorFn func(ctx context.Context, req *http.Request) error

RequestEditorFn is the function signature for the RequestEditor callback function

type RequestResponsePair

type RequestResponsePair struct {
	// In a simple scenario, you can store literal bytes to compare against the read.
	// For real HTTP testing, you might parse or only compare a portion of the request.
	Request  []byte
	Response []byte
}

RequestResponsePair holds a single request pattern and a corresponding response.

type Role

type Role string

Role User role for RBAC

const (
	RoleAdmin   Role = "admin"
	RoleManager Role = "manager"
	RoleUser    Role = "user"
)

Defines values for Role.

type RouteInfo

type RouteInfo struct {
	Method             string
	Path               string
	MuxPattern         string
	MethodName         string
	BodyMode           string
	Auth               string
	Surface            string
	Sensitivity        string
	Profile            string
	RequestType        string
	ResponseType       string
	RequestSchema      string
	ResponseSchema     string
	HasTypedRequest    bool
	HasTypedResponse   bool
	PathParams         []string
	RequiredRoles      []string
	RequiredScopes     []string
	RequiredAttributes map[string]string
	// APPSEC-Gen-F-006: surface the per-route WebAuthn ceremony policy
	// (ceremony, phase, attestation, user_verification, discoverable)
	// so catch-all handlers can read it without re-parsing the config.
	Webauthn *WebauthnInfo
	// APPSEC-15 (Plan 02 follow-up): per-route mTLS CA bundle path so
	// catch-all handlers can construct their own per-route
	// mtlsx.Verifier. Empty when the operation declares no mtls block
	// or no ca_bundle_path. Server-construction-time wiring still
	// goes through api.WithMTLS for the listener.
	MTLSCABundlePath string
}

RouteInfo describes one generated HTTP route for catch-all handlers.

type Server

type Server interface {
	Serve(context.Context) error
}

Server is the interface New returns: a configured, listener-bound HTTP(S) server ready to run. The only externally visible operation is Serve, which blocks until ctx is cancelled or the listener stops.

func New

func New(reg Register, opts ...Option) (_ Server, err error)

New assembles an apiServer from the given options and Register callback, then binds its TCP listener (returning before Serve is called). It builds the gin engine, wires the always-on middleware chain (request logging, panic recovery, body-size limiting, security response headers, object-ownership guard) plus whatever Options add, invokes reg to register the caller's routes, mounts any Option-provided extra routes, and finally resolves the TLS listener -- HSM/KMS-signed (WithSigner), mutual-TLS (WithMTLS), or a plain cert/key pair, in that precedence order. reg must not be nil.

type ServerInterface

type ServerInterface interface {
	// User login
	// (POST /v1/auth/login)
	LoginUser(c *gin.Context)
	// Logout user
	// (POST /v1/auth/logout)
	LogoutUser(c *gin.Context)
	// Get current user info
	// (GET /v1/auth/me)
	GetCurrentUser(c *gin.Context)
	// Refresh user token
	// (POST /v1/auth/refresh)
	RefreshToken(c *gin.Context)
	// User registration
	// (POST /v1/auth/register)
	RegisterUser(c *gin.Context)
	// Echo
	// (POST /v1/echo)
	Echo(c *gin.Context)
	// List all pets
	// (GET /v1/pets)
	ListPets(c *gin.Context)
	// Create a pet
	// (POST /v1/pets)
	CreatePet(c *gin.Context)
	// Show a specific pet
	// (GET /v1/pets/{petId})
	ShowPetById(c *gin.Context, petId ID)
	// List all users
	// (GET /v1/users)
	ListUsers(c *gin.Context)
	// Create a user
	// (POST /v1/users)
	CreateUser(c *gin.Context)
	// Delete a user
	// (DELETE /v1/users/{userId})
	DeleteUser(c *gin.Context, userId ID)
	// Get a specific user
	// (GET /v1/users/{userId})
	GetUserById(c *gin.Context, userId ID)
	// Update a specific user
	// (PATCH /v1/users/{userId})
	UpdateUser(c *gin.Context, userId ID)
}

ServerInterface represents all server handlers.

type ServerInterfaceWrapper

type ServerInterfaceWrapper struct {
	Handler            ServerInterface
	HandlerMiddlewares []MiddlewareFunc
	ErrorHandler       func(*gin.Context, error, int)
}

ServerInterfaceWrapper converts contexts to parameters.

func (*ServerInterfaceWrapper) CreatePet

func (siw *ServerInterfaceWrapper) CreatePet(c *gin.Context)

CreatePet operation middleware

func (*ServerInterfaceWrapper) CreateUser

func (siw *ServerInterfaceWrapper) CreateUser(c *gin.Context)

CreateUser operation middleware

func (*ServerInterfaceWrapper) DeleteUser

func (siw *ServerInterfaceWrapper) DeleteUser(c *gin.Context)

DeleteUser operation middleware

func (*ServerInterfaceWrapper) Echo

func (siw *ServerInterfaceWrapper) Echo(c *gin.Context)

Echo operation middleware

func (*ServerInterfaceWrapper) GetCurrentUser

func (siw *ServerInterfaceWrapper) GetCurrentUser(c *gin.Context)

GetCurrentUser operation middleware

func (*ServerInterfaceWrapper) GetUserById

func (siw *ServerInterfaceWrapper) GetUserById(c *gin.Context)

GetUserById operation middleware

func (*ServerInterfaceWrapper) ListPets

func (siw *ServerInterfaceWrapper) ListPets(c *gin.Context)

ListPets operation middleware

func (*ServerInterfaceWrapper) ListUsers

func (siw *ServerInterfaceWrapper) ListUsers(c *gin.Context)

ListUsers operation middleware

func (*ServerInterfaceWrapper) LoginUser

func (siw *ServerInterfaceWrapper) LoginUser(c *gin.Context)

LoginUser operation middleware

func (*ServerInterfaceWrapper) LogoutUser

func (siw *ServerInterfaceWrapper) LogoutUser(c *gin.Context)

LogoutUser operation middleware

func (*ServerInterfaceWrapper) RefreshToken

func (siw *ServerInterfaceWrapper) RefreshToken(c *gin.Context)

RefreshToken operation middleware

func (*ServerInterfaceWrapper) RegisterUser

func (siw *ServerInterfaceWrapper) RegisterUser(c *gin.Context)

RegisterUser operation middleware

func (*ServerInterfaceWrapper) ShowPetById

func (siw *ServerInterfaceWrapper) ShowPetById(c *gin.Context)

ShowPetById operation middleware

func (*ServerInterfaceWrapper) UpdateUser

func (siw *ServerInterfaceWrapper) UpdateUser(c *gin.Context)

UpdateUser operation middleware

func (*ServerInterfaceWrapper) Valid

func (x *ServerInterfaceWrapper) Valid() error

Validate ServerInterfaceWrapper using the specified tags

type ShowPetByIdResponse

type ShowPetByIdResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *Pet
	JSON201      *Pet
	JSON400      *BadRequest
	JSON401      *Unauthorized
	JSON403      *Forbidden
	JSON404      *NotFound
	JSON429      *TooManyRequests
	JSON500      *InternalServerError
	JSONDefault  *UnexpectedError
}

func ParseShowPetByIdResponse

func ParseShowPetByIdResponse(rsp *http.Response) (*ShowPetByIdResponse, error)

ParseShowPetByIdResponse parses an HTTP response from a ShowPetByIdWithResponse call

func (ShowPetByIdResponse) Status

func (r ShowPetByIdResponse) Status() string

Status returns HTTPResponse.Status

func (ShowPetByIdResponse) StatusCode

func (r ShowPetByIdResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*ShowPetByIdResponse) Valid

func (x *ShowPetByIdResponse) Valid() error

Validate ShowPetByIdResponse using the specified tags

type StatusError

type StatusError struct {
	Code    int
	Message string
	Err     error
}

StatusError lets a handler return a custom HTTP status code + message while still using the standard JSON error envelope. Use this for codes the sentinel set does not cover (410 Gone, 423 Locked, etc.) or when the message needs to be more specific than the sentinel's default text. Optionally wrap a sentinel via Err for callers that errors.Is them.

func (*StatusError) Error

func (e *StatusError) Error() string

func (*StatusError) Unwrap

func (e *StatusError) Unwrap() error

type TOKEN

type TOKEN string

TOKEN is the type of the request-context key under which OIDC.JWT stashes a verified JWT token (see ctxTokenKey). It exists as a distinct string type, rather than a bare string, so the key can never collide with an unrelated string-keyed context value set by other middleware.

type TestConn

type TestConn struct{}

TestConn is a no-op net.Conn double: every read/write/deadline call succeeds trivially without touching any real socket. It backs TestListener's Accept/Dial pair so tests can drive an in-memory HTTP(S) server (see NewTestInMemoryServer in fn.go) without binding a real port.

func (*TestConn) Close

func (c *TestConn) Close() error

Close is a no-op; it always succeeds.

func (*TestConn) LocalAddr

func (c *TestConn) LocalAddr() net.Addr

LocalAddr returns a fixed 127.0.0.1:443 address, satisfying net.Conn without a real bound socket.

func (*TestConn) Read

func (c *TestConn) Read(_ []byte) (int, error)

Read always reports zero bytes read and a nil error.

func (*TestConn) RemoteAddr

func (c *TestConn) RemoteAddr() net.Addr

RemoteAddr returns a fixed 127.0.0.1:53299 address, satisfying net.Conn without a real connected peer.

func (*TestConn) SetDeadline

func (c *TestConn) SetDeadline(_ time.Time) error

SetDeadline is a no-op; it always succeeds.

func (*TestConn) SetReadDeadline

func (c *TestConn) SetReadDeadline(_ time.Time) error

SetReadDeadline is a no-op; it always succeeds.

func (*TestConn) SetWriteDeadline

func (c *TestConn) SetWriteDeadline(_ time.Time) error

SetWriteDeadline is a no-op; it always succeeds.

func (*TestConn) Write

func (c *TestConn) Write(b []byte) (int, error)

Write reports every byte in b as written and never errors.

type TestListener

type TestListener struct {

	// Host and Port are just informational/logging in Addr().
	Host string
	Port uint16
	// contains filtered or unexported fields
}

TestListener is a net.Listener replacement for in-memory testing. It can optionally handle a list of pre-defined requests and responses in order.

func NewTestInMemoryServer

func NewTestInMemoryServer(
	t *testing.T, handler http.Handler,
) (string, *TestListener, func())

NewTestInMemoryServer launches an HTTPS server in memory using TestListener.

func NewTestListener

func NewTestListener(
	ctx context.Context,
	t *testing.T,
	logger log.Logger,
	host string,
	port uint16,
) *TestListener

NewTestListener creates a new in-memory listener that never binds a real port.

func (*TestListener) Accept

func (l *TestListener) Accept() (net.Conn, error)

Accept implements net.Listener. It blocks, waiting for a connection from Dial(), or until the context or listener is closed. Once a connection is accepted, this code immediately spins up a goroutine to read from that connection and write the corresponding response (if any).

func (*TestListener) Addr

func (l *TestListener) Addr() net.Addr

Addr implements net.Listener. It returns a TCPAddr with Host/Port for logging.

func (*TestListener) Close

func (l *TestListener) Close() error

Close signals that the listener should no longer accept new connections. Note that we do not close(l.conns), to avoid racing with sends from Dial().

func (*TestListener) Dial

func (l *TestListener) Dial() (net.Conn, error)

Dial returns the client side of a net.Pipe, which is “connected” to the server side that Accept() will receive. This never binds a real port.

func (*TestListener) ServerRootCAs

func (l *TestListener) ServerRootCAs() *x509.CertPool

ServerRootCAs returns the pinned certificate pool for the in-memory test server, or nil if none was set.

func (*TestListener) SetPairs

func (l *TestListener) SetPairs(pairs []RequestResponsePair)

SetPairs sets (or replaces) the pre-defined request/response pairs the listener will use.

func (*TestListener) SetServerCAs

func (l *TestListener) SetServerCAs(pool *x509.CertPool)

SetServerCAs pins the certificate pool the in-memory test server presents, so a client can verify the TLS chain rather than skip verification (SEC-0016).

type Token

type Token struct {
	// ExpiresIn Token expiration in seconds
	ExpiresIn *int64 `json:"expiresIn,omitempty"`

	// Token JWT or OAuth2 access token
	Token *string `json:"token,omitempty"`
}

Token Token object containing JWT or OAuth2 access token

func (*Token) Valid

func (x *Token) Valid() error

Validate Token using the specified tags

type TooManyRequests

type TooManyRequests = Error

TooManyRequests Error response

type Unauthorized

type Unauthorized = Error

Unauthorized Error response

type UnexpectedError

type UnexpectedError = Error

UnexpectedError Error response

type UnimplementedServer

type UnimplementedServer struct{}

UnimplementedServer returns 501 Not Implemented for every endpoint. Embed it in your server struct and override the methods you implement.

Task 4.2 (GENWA-R1/C1): for the four webauthn_* profiles the body is specialized to dispatch the ceremony into the package-level webAuthnSrv (built by RegisterGeneratedAPI from security.webauthn). Consumers that embed UnimplementedServer inherit a working ceremony out of the box; consumers that override the method on their own ServerInterface impl still own the dispatch (Pattern A — preserves the override surface).

func (UnimplementedServer) Action

func (UnimplementedServer) Create

func (UnimplementedServer) Metrics

func (UnimplementedServer) Register

func (UnimplementedServer) Search

func (UnimplementedServer) Update

type UpdateUserJSONBody

type UpdateUserJSONBody struct {
	// Password Password for authentication
	Password *Password `` /* 147-byte string literal not displayed */

	// Roles New roles to assign
	Roles *[]Role `json:"roles,omitempty"`
}

UpdateUserJSONBody defines parameters for UpdateUser.

func (*UpdateUserJSONBody) Valid

func (x *UpdateUserJSONBody) Valid() error

Validate UpdateUserJSONBody using the specified tags

type UpdateUserJSONRequestBody

type UpdateUserJSONRequestBody UpdateUserJSONBody

UpdateUserJSONRequestBody defines body for UpdateUser for application/json ContentType.

type UpdateUserResponse

type UpdateUserResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *User
	JSON400      *BadRequest
	JSON401      *Unauthorized
	JSON403      *Forbidden
	JSON404      *NotFound
	JSON429      *TooManyRequests
	JSON500      *InternalServerError
	JSONDefault  *UnexpectedError
}

func ParseUpdateUserResponse

func ParseUpdateUserResponse(rsp *http.Response) (*UpdateUserResponse, error)

ParseUpdateUserResponse parses an HTTP response from a UpdateUserWithResponse call

func (UpdateUserResponse) Status

func (r UpdateUserResponse) Status() string

Status returns HTTPResponse.Status

func (UpdateUserResponse) StatusCode

func (r UpdateUserResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

func (*UpdateUserResponse) Valid

func (x *UpdateUserResponse) Valid() error

Validate UpdateUserResponse using the specified tags

type User

type User struct {
	// Claims Additional claims for extended user profile or permissions
	Claims *Claims `json:"claims,omitempty"`

	// CreatedAt When the user was created
	CreatedAt time.Time `json:"createdAt"`

	// Id id for the Record
	Id    *ID    `json:"id,omitempty"`
	Roles []Role `json:"roles"`

	// UpdatedAt When the user was last updated
	UpdatedAt time.Time `json:"updatedAt"`

	// Username Username for authentication
	Username Username `json:"username" safe-to-log:"true" validate:"required,min=10,max=50,regexp=^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{10,50}$"`
}

User Complete user record with roles and claims

func (*User) Valid

func (x *User) Valid() error

Validate User using the specified tags

type Username

type Username = string

Username Username for authentication

type Validator

type Validator interface {
	Valid() error
}

Validator is implemented by any generated request/response struct that carries `validate` struct tags and wants custom validation logic beyond what go-playground/validator's struct tags express. When a type bound by gin implements Validator, apiValidator.ValidateStruct calls its Valid method instead of running the generic tag-based validator, so hand-written invariants (cross-field checks, conditional requirements) can live next to the type they validate.

type WebauthnInfo

type WebauthnInfo struct {
	Ceremony                string
	Phase                   string
	Attestation             string
	AuthenticatorAttachment string
	UserVerification        string
	Discoverable            bool
}

WebauthnInfo mirrors the per-route webauthn block (cmd/apic WebauthnContract). Nil when the route does not declare any ceremony.

Jump to

Keyboard shortcuts

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