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
- Variables
- func Args(app string) cli.Args
- func AuthToken(ctx context.Context) (jwt.Token, error)
- func GenerateTLSCertificate() (tls.Certificate, error)
- func GetSwagger() (swagger *openapi3.T, err error)
- func Log[T any](val T) slog.Value
- func MCPSTDIO() error
- func MCPTools() map[string]MCPTool
- func NewCreatePetRequest(server string, body CreatePetJSONRequestBody) (*http.Request, error)
- func NewCreatePetRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)
- func NewCreateUserRequest(server string, body CreateUserJSONRequestBody) (*http.Request, error)
- func NewCreateUserRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)
- func NewDeleteUserRequest(server string, userId ID) (*http.Request, error)
- func NewEchoRequest(server string, body EchoJSONRequestBody) (*http.Request, error)
- func NewEchoRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)
- func NewGetCurrentUserRequest(server string) (*http.Request, error)
- func NewGetUserByIdRequest(server string, userId ID) (*http.Request, error)
- func NewListPetsRequest(server string) (*http.Request, error)
- func NewListUsersRequest(server string) (*http.Request, error)
- func NewLoginUserRequest(server string, body LoginUserJSONRequestBody) (*http.Request, error)
- func NewLoginUserRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)
- func NewLogoutUserRequest(server string) (*http.Request, error)
- func NewRefreshTokenRequest(server string, body RefreshTokenJSONRequestBody) (*http.Request, error)
- func NewRefreshTokenRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)
- func NewRegisterUserRequest(server string, body RegisterUserJSONRequestBody) (*http.Request, error)
- func NewRegisterUserRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)
- func NewShowPetByIdRequest(server string, petId ID) (*http.Request, error)
- func NewTestHTPXClient(t *testing.T, listener *TestListener) *htpx.Client
- func NewUpdateUserRequest(server string, userId ID, body UpdateUserJSONRequestBody) (*http.Request, error)
- func NewUpdateUserRequestWithBody(server string, userId ID, contentType string, body io.Reader) (*http.Request, error)
- func OwnershipGuard() gin.HandlerFunc
- func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error)
- func RegisterGeneratedAPI(mux *http.ServeMux, srv GeneratedServerInterface, opts APIOptions)
- func RegisterHandlers(router gin.IRouter, si ServerInterface)
- func RegisterHandlersWithOptions(router gin.IRouter, si ServerInterface, options GinServerOptions)
- func WsValidateEchoDocs(payload []byte) error
- func WsValidateFeed(payload []byte) error
- type APIOptions
- type BadRequest
- type CatchAllServerInterface
- type Claims
- type Client
- func (c *Client) CreatePet(ctx context.Context, body CreatePetJSONRequestBody, ...) (*http.Response, error)
- func (c *Client) CreatePetWithBody(ctx context.Context, contentType string, body io.Reader, ...) (*http.Response, error)
- func (c *Client) CreateUser(ctx context.Context, body CreateUserJSONRequestBody, ...) (*http.Response, error)
- func (c *Client) CreateUserWithBody(ctx context.Context, contentType string, body io.Reader, ...) (*http.Response, error)
- func (c *Client) DeleteUser(ctx context.Context, userId ID, reqEditors ...RequestEditorFn) (*http.Response, error)
- func (c *Client) Echo(ctx context.Context, body EchoJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)
- func (c *Client) EchoWithBody(ctx context.Context, contentType string, body io.Reader, ...) (*http.Response, error)
- func (c *Client) GetCurrentUser(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)
- func (c *Client) GetUserById(ctx context.Context, userId ID, reqEditors ...RequestEditorFn) (*http.Response, error)
- func (c *Client) ListPets(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)
- func (c *Client) ListUsers(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)
- func (c *Client) LoginUser(ctx context.Context, body LoginUserJSONRequestBody, ...) (*http.Response, error)
- func (c *Client) LoginUserWithBody(ctx context.Context, contentType string, body io.Reader, ...) (*http.Response, error)
- func (c *Client) LogoutUser(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)
- func (c *Client) RefreshToken(ctx context.Context, body RefreshTokenJSONRequestBody, ...) (*http.Response, error)
- func (c *Client) RefreshTokenWithBody(ctx context.Context, contentType string, body io.Reader, ...) (*http.Response, error)
- func (c *Client) RegisterUser(ctx context.Context, body RegisterUserJSONRequestBody, ...) (*http.Response, error)
- func (c *Client) RegisterUserWithBody(ctx context.Context, contentType string, body io.Reader, ...) (*http.Response, error)
- func (c *Client) ShowPetById(ctx context.Context, petId ID, reqEditors ...RequestEditorFn) (*http.Response, error)
- func (c *Client) UpdateUser(ctx context.Context, userId ID, body UpdateUserJSONRequestBody, ...) (*http.Response, error)
- func (c *Client) UpdateUserWithBody(ctx context.Context, userId ID, contentType string, body io.Reader, ...) (*http.Response, error)
- func (x *Client) Valid() error
- type ClientInterface
- type ClientOption
- type ClientWithResponses
- func (c *ClientWithResponses) CreatePetWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, ...) (*CreatePetResponse, error)
- func (c *ClientWithResponses) CreatePetWithResponse(ctx context.Context, body CreatePetJSONRequestBody, ...) (*CreatePetResponse, error)
- func (c *ClientWithResponses) CreateUserWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, ...) (*CreateUserResponse, error)
- func (c *ClientWithResponses) CreateUserWithResponse(ctx context.Context, body CreateUserJSONRequestBody, ...) (*CreateUserResponse, error)
- func (c *ClientWithResponses) DeleteUserWithResponse(ctx context.Context, userId ID, reqEditors ...RequestEditorFn) (*DeleteUserResponse, error)
- func (c *ClientWithResponses) EchoWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, ...) (*EchoResponse, error)
- func (c *ClientWithResponses) EchoWithResponse(ctx context.Context, body EchoJSONRequestBody, reqEditors ...RequestEditorFn) (*EchoResponse, error)
- func (c *ClientWithResponses) GetCurrentUserWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetCurrentUserResponse, error)
- func (c *ClientWithResponses) GetUserByIdWithResponse(ctx context.Context, userId ID, reqEditors ...RequestEditorFn) (*GetUserByIdResponse, error)
- func (c *ClientWithResponses) ListPetsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListPetsResponse, error)
- func (c *ClientWithResponses) ListUsersWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListUsersResponse, error)
- func (c *ClientWithResponses) LoginUserWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, ...) (*LoginUserResponse, error)
- func (c *ClientWithResponses) LoginUserWithResponse(ctx context.Context, body LoginUserJSONRequestBody, ...) (*LoginUserResponse, error)
- func (c *ClientWithResponses) LogoutUserWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*LogoutUserResponse, error)
- func (c *ClientWithResponses) RefreshTokenWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, ...) (*RefreshTokenResponse, error)
- func (c *ClientWithResponses) RefreshTokenWithResponse(ctx context.Context, body RefreshTokenJSONRequestBody, ...) (*RefreshTokenResponse, error)
- func (c *ClientWithResponses) RegisterUserWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, ...) (*RegisterUserResponse, error)
- func (c *ClientWithResponses) RegisterUserWithResponse(ctx context.Context, body RegisterUserJSONRequestBody, ...) (*RegisterUserResponse, error)
- func (c *ClientWithResponses) ShowPetByIdWithResponse(ctx context.Context, petId ID, reqEditors ...RequestEditorFn) (*ShowPetByIdResponse, error)
- func (c *ClientWithResponses) UpdateUserWithBodyWithResponse(ctx context.Context, userId ID, contentType string, body io.Reader, ...) (*UpdateUserResponse, error)
- func (c *ClientWithResponses) UpdateUserWithResponse(ctx context.Context, userId ID, body UpdateUserJSONRequestBody, ...) (*UpdateUserResponse, error)
- func (x *ClientWithResponses) Valid() error
- type ClientWithResponsesInterface
- type Conflict
- type CreatePetJSONRequestBody
- type CreatePetResponse
- type CreateUserJSONRequestBody
- type CreateUserResponse
- type DeleteUserResponse
- type EchoJSONRequestBody
- type EchoMsg
- type EchoReq
- type EchoResp
- type EchoResponse
- type Error
- type Forbidden
- type GeneratedServerInterface
- type GetCurrentUserResponse
- type GetUserByIdResponse
- type GinServerOptions
- type HttpRequestDoer
- type ID
- type InternalServerError
- type ListPetsResponse
- type ListUsersResponse
- type Login
- type LoginUserJSONRequestBody
- type LoginUserResponse
- type LogoutUserResponse
- type MCPParams
- type MCPResult
- type MCPTool
- type MiddlewareFunc
- type NOOPHandlers
- func (n *NOOPHandlers) CreatePet(c *gin.Context)
- func (n *NOOPHandlers) CreateUser(c *gin.Context)
- func (n *NOOPHandlers) DeleteUser(c *gin.Context, userId ID)
- func (n *NOOPHandlers) Echo(c *gin.Context)
- func (n *NOOPHandlers) GetCurrentUser(c *gin.Context)
- func (n *NOOPHandlers) GetUserById(c *gin.Context, userId ID)
- func (n *NOOPHandlers) ListPets(c *gin.Context)
- func (n *NOOPHandlers) ListUsers(c *gin.Context)
- func (n *NOOPHandlers) LoginUser(c *gin.Context)
- func (n *NOOPHandlers) LogoutUser(c *gin.Context)
- func (n *NOOPHandlers) RefreshToken(c *gin.Context)
- func (n *NOOPHandlers) RegisterUser(c *gin.Context)
- func (n *NOOPHandlers) ShowPetById(c *gin.Context, petId ID)
- func (n *NOOPHandlers) UpdateUser(c *gin.Context, userId ID)
- type NotFound
- type OAuth2Error
- type OIDC
- type Option
- func Host(host string) Option
- func Port(port int) Option
- func RateLimit(limit int, duration time.Duration) Option
- func WithCORS(allowedOrigins []string, methods ...string) Option
- func WithCorrelation(header string) Option
- func WithErrorHandler(handler func(ctx *gin.Context, err error, i int)) Option
- func WithImpl(impl any) Optiondeprecated
- func WithLogFile(cfg obsx.LogFileConfig) Option
- func WithLogger(logger log.Logger) Option
- func WithMTLS(caBundlePath string) Option
- func WithMaxBodyBytes(n int64) Option
- func WithMetrics(m obsx.MetricsProvider) Option
- func WithMiddleware(middleware ...gin.HandlerFunc) Option
- func WithOTEL(ctx context.Context, cfg ...otelx.Config) Option
- func WithObservability() Option
- func WithPeerRateLimit(rate, burst float64, src httpx.IPSource) Option
- func WithPrometheus(auth func(*http.Request) bool, cfg ...promx.Config) Option
- func WithShutdownTimeout(d time.Duration) Option
- func WithSigner(backendName string, cfg signerx.BackendConfig, ref signerx.KeyRef) Option
- func WithSwaggerSpec(spec *openapi3.T) Option
- func WithTLS(cert, key string) Option
- func WithTelemetry(tp *obsx.TelemetryProvider) Option
- func WithTracing() Option
- func WithTrustedProxies(proxies []string) Option
- func WithValidation(ctx context.Context, oidc string, audience string) Option
- type Password
- type Pet
- type RefreshTokenJSONBody
- type RefreshTokenJSONRequestBody
- type RefreshTokenResponse
- type Register
- type RegisterUserJSONRequestBody
- type RegisterUserResponse
- type Registration
- type RequestEditorFn
- type RequestResponsePair
- type Role
- type RouteInfo
- type Server
- type ServerInterface
- type ServerInterfaceWrapper
- func (siw *ServerInterfaceWrapper) CreatePet(c *gin.Context)
- func (siw *ServerInterfaceWrapper) CreateUser(c *gin.Context)
- func (siw *ServerInterfaceWrapper) DeleteUser(c *gin.Context)
- func (siw *ServerInterfaceWrapper) Echo(c *gin.Context)
- func (siw *ServerInterfaceWrapper) GetCurrentUser(c *gin.Context)
- func (siw *ServerInterfaceWrapper) GetUserById(c *gin.Context)
- func (siw *ServerInterfaceWrapper) ListPets(c *gin.Context)
- func (siw *ServerInterfaceWrapper) ListUsers(c *gin.Context)
- func (siw *ServerInterfaceWrapper) LoginUser(c *gin.Context)
- func (siw *ServerInterfaceWrapper) LogoutUser(c *gin.Context)
- func (siw *ServerInterfaceWrapper) RefreshToken(c *gin.Context)
- func (siw *ServerInterfaceWrapper) RegisterUser(c *gin.Context)
- func (siw *ServerInterfaceWrapper) ShowPetById(c *gin.Context)
- func (siw *ServerInterfaceWrapper) UpdateUser(c *gin.Context)
- func (x *ServerInterfaceWrapper) Valid() error
- type ShowPetByIdResponse
- type StatusError
- type TOKEN
- type TestConn
- func (c *TestConn) Close() error
- func (c *TestConn) LocalAddr() net.Addr
- func (c *TestConn) Read(_ []byte) (int, error)
- func (c *TestConn) RemoteAddr() net.Addr
- func (c *TestConn) SetDeadline(_ time.Time) error
- func (c *TestConn) SetReadDeadline(_ time.Time) error
- func (c *TestConn) SetWriteDeadline(_ time.Time) error
- func (c *TestConn) Write(b []byte) (int, error)
- type TestListener
- func (l *TestListener) Accept() (net.Conn, error)
- func (l *TestListener) Addr() net.Addr
- func (l *TestListener) Close() error
- func (l *TestListener) Dial() (net.Conn, error)
- func (l *TestListener) ServerRootCAs() *x509.CertPool
- func (l *TestListener) SetPairs(pairs []RequestResponsePair)
- func (l *TestListener) SetServerCAs(pool *x509.CertPool)
- type Token
- type TooManyRequests
- type Unauthorized
- type UnexpectedError
- type UnimplementedServer
- func (UnimplementedServer) Action(_ http.ResponseWriter, _ *http.Request, _ *types.AdminActionReq) (*types.AdminActionResp, error)
- func (UnimplementedServer) Create(_ http.ResponseWriter, _ *http.Request, _ *types.PostCreateReq) (*types.PostCreateResp, error)
- func (UnimplementedServer) Metrics(_ http.ResponseWriter, _ *http.Request, _ *types.AdminMetricsReq) (*types.AdminMetricsResp, error)
- func (UnimplementedServer) Register(_ http.ResponseWriter, _ *http.Request, _ *types.RegisterReq) (*types.RegisterResp, error)
- func (UnimplementedServer) Search(_ http.ResponseWriter, _ *http.Request, _ *types.PostSearchReq) (*types.PostSearchResp, error)
- func (UnimplementedServer) Update(_ http.ResponseWriter, _ *http.Request, _ *types.UserUpdateReq) (*types.UserUpdateResp, error)
- type UpdateUserJSONBody
- type UpdateUserJSONRequestBody
- type UpdateUserResponse
- type User
- type Username
- type Validator
- type WebauthnInfo
Constants ¶
const ( BearerAuthScopes = "bearerAuth.Scopes" MutualTLSAuthScopes = "mutualTLSAuth.Scopes" Oauth2AuthScopes = "oauth2Auth.Scopes" OpenIdConnectAuthScopes = "openIdConnectAuth.Scopes" )
const ( // AuthScopes is the context key for the authentication scopes that are defined // for a specific API path that must be present in the JWT token in order to // access the path. OAuth2Scopes = "oauth2_scopes" ENV = "GIN_MODE" // runnning environment DEVENV = "debug" // development environment INSECURE_DEV = "APIC_INSECURE_DEV" )
Variables ¶
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.
var ErrAPIValidation = errors.New("api validation error")
var ErrAuthHeaderMissing = errors.New("authorization header missing")
var ErrBadRequest = errors.New("bad request") // → 400 (post-validation business 400)
var ErrConflict = errors.New("conflict") // → 409
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).
var ErrEmptyAudience = errors.New("empty audience")
var ErrForbidden = errors.New("forbidden") // → 403 (post-auth business denial)
var ErrInvalidScheme = errors.New("invalid scheme")
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.
var ErrInvalidURL = errors.New("invalid url")
var ErrMalformedAuthHeader = errors.New("malformed authorization header")
var ErrNilCatchAllHandler = errors.New("nil catch-all handler")
var ErrNotFound = errors.New("not found") // → 404
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).
var ErrUnprocessable = errors.New("unprocessable") // → 422
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.
var MCPAllowAnyOrigin bool
MCPAllowAnyOrigin opts the MCP WS surface into the legacy fail-open Origin policy. Default false: only origins listed in MCPOrigins (or *) are accepted. APPSEC-2 / SEC-0008.
var MCPBurst float64 = 50
var MCPHandler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotImplemented) })
MCPHandler is assigned by generated code at init().
var MCPMaxBodyBytes int64 = 1048576
MCPMaxBodyBytes is the per-request HTTP body cap applied by the generated MCPHandler. APPSEC-1: prevents an unbounded io.ReadAll DoS surface. Default 1048576 bytes; override via x-mcp-maxBodyBytes in the OpenAPI spec or via MCPOptionsOverride at startup.
var MCPOptionsOverride func()
MCPOptionsOverride is consulted by the generated init() right after the spec-derived MCP* vars are populated. Assign to mutate MCPMaxBodyBytes / MCPRate / MCPBurst / MCPOrigins / MCPAllowAnyOrigin (and similar) at startup -- the LV-2026-05-22 escape valve. Runs once per process under init() ordering.
var MCPOrigins = []string{}
MCPOrigins is the WebSocket OriginAllowlist applied to the generated MCPWSHandler. LV-2026-05-22: when empty and MCPAllowAnyOrigin is false, wsx.UpgradeStrict fails closed (HTTP 403) for every WS upgrade. Configure via x-mcp-origins in the OpenAPI spec or via MCPOptionsOverride.
var MCPRate float64 = 100
MCPRate and MCPBurst configure the per-tool token-bucket rate limiter installed by the generated init(). Defaults match the pre-LV-2026-05-22 hardcoded constants; override via x-mcp-rate / x-mcp-burst in the OpenAPI spec or via MCPOptionsOverride.
var MCPWSHandler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotImplemented) })
MCPWSHandler serves MCP over WebSocket. Assigned by generated code.
var RegisterWSRoutes = func(r *gin.Engine) {}
RegisterWSRoutes is assigned by generated code at init(). Default no-op.
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 GenerateTLSCertificate ¶
func GenerateTLSCertificate() (tls.Certificate, error)
GenerateTLSCertificate generates a self-signed TLS certificate.
func GetSwagger ¶
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 ¶
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 MCPSTDIO ¶
func MCPSTDIO() error
MCPSTDIO starts the MCP stdio JSON-RPC loop using generated 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 ¶
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 ¶
NewGetCurrentUserRequest generates requests for GetCurrentUser
func NewGetUserByIdRequest ¶
NewGetUserByIdRequest generates requests for GetUserById
func NewListPetsRequest ¶
NewListPetsRequest generates requests for ListPets
func NewListUsersRequest ¶
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 ¶
NewLogoutUserRequest generates requests for LogoutUser
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 ¶
NewShowPetByIdRequest generates requests for ShowPetById
func NewTestHTPXClient ¶
func NewTestHTPXClient(t *testing.T, listener *TestListener) *htpx.Client
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 ¶
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 ¶
WsValidateEchoDocs validates text JSON messages for /ws/echo-docs.
func WsValidateFeed ¶
WsValidateFeed validates text JSON messages for /ws/users/{userId}/feed.
Types ¶
type APIOptions ¶
type APIOptions struct {
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
GlobalRate float64
GlobalBurst float64
}
APIOptions configures cross-cutting concerns for generated routes.
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
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 (*Client) CreateUser ¶
func (c *Client) CreateUser(ctx context.Context, body CreateUserJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)
func (*Client) CreateUserWithBody ¶
func (*Client) DeleteUser ¶
func (*Client) Echo ¶
func (c *Client) Echo(ctx context.Context, body EchoJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)
func (*Client) EchoWithBody ¶
func (*Client) GetCurrentUser ¶
func (*Client) GetUserById ¶
func (*Client) LoginUser ¶
func (c *Client) LoginUser(ctx context.Context, body LoginUserJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)
func (*Client) LoginUserWithBody ¶
func (*Client) LogoutUser ¶
func (*Client) RefreshToken ¶
func (c *Client) RefreshToken(ctx context.Context, body RefreshTokenJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)
func (*Client) RefreshTokenWithBody ¶
func (*Client) RegisterUser ¶
func (c *Client) RegisterUser(ctx context.Context, body RegisterUserJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)
func (*Client) RegisterUserWithBody ¶
func (*Client) ShowPetById ¶
func (*Client) UpdateUser ¶
func (c *Client) UpdateUser(ctx context.Context, userId ID, body UpdateUserJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)
func (*Client) UpdateUserWithBody ¶
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 ¶
ClientOption allows setting custom parameters during construction
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 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
type EchoReq ¶
type EchoReq struct {
Msg string `json:"msg"`
}
EchoReq Schema for the echo endpoint request body
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
type GeneratedServerInterface ¶
type GeneratedServerInterface interface {
Action(w http.ResponseWriter, r *http.Request, req *types.AdminActionReq) (*types.AdminActionResp, error)
Metrics(w http.ResponseWriter, r *http.Request, req *types.AdminMetricsReq) (*types.AdminMetricsResp, error)
Create(w http.ResponseWriter, r *http.Request, req *types.PostCreateReq) (*types.PostCreateResp, error)
Search(w http.ResponseWriter, r *http.Request, req *types.PostSearchReq) (*types.PostSearchResp, error)
Register(w http.ResponseWriter, r *http.Request, req *types.RegisterReq) (*types.RegisterResp, error)
Update(w http.ResponseWriter, r *http.Request, req *types.UserUpdateReq) (*types.UserUpdateResp, error)
}
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 ¶
Doer performs HTTP requests.
The standard http.Client implements this interface.
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
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 MiddlewareFunc ¶
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 OAuth2Error ¶
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
}
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
ValidateToken middleware verifies a valid Auth0 JWT token being present in the request.
func (*OIDC) ExtractToken ¶
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 ¶
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 ¶
type Option ¶
type Option func(*apiServer) error
func WithCorrelation ¶ added in v0.15.1
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 WithImpl
deprecated
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.1
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.
func WithLogger ¶
func WithMTLS ¶
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 ¶
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.1
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
func WithOTEL ¶ added in v0.15.1
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 ¶
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.1
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
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 ¶
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 WithTelemetry ¶ added in v0.15.1
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.1
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 ¶
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
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 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 ¶
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 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 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 ¶
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 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 ¶
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
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) Action(_ http.ResponseWriter, _ *http.Request, _ *types.AdminActionReq) (*types.AdminActionResp, error)
func (UnimplementedServer) Create ¶
func (UnimplementedServer) Create(_ http.ResponseWriter, _ *http.Request, _ *types.PostCreateReq) (*types.PostCreateResp, error)
func (UnimplementedServer) Metrics ¶
func (UnimplementedServer) Metrics(_ http.ResponseWriter, _ *http.Request, _ *types.AdminMetricsReq) (*types.AdminMetricsResp, error)
func (UnimplementedServer) Register ¶
func (UnimplementedServer) Register(_ http.ResponseWriter, _ *http.Request, _ *types.RegisterReq) (*types.RegisterResp, error)
func (UnimplementedServer) Search ¶
func (UnimplementedServer) Search(_ http.ResponseWriter, _ *http.Request, _ *types.PostSearchReq) (*types.PostSearchResp, error)
func (UnimplementedServer) Update ¶
func (UnimplementedServer) Update(_ http.ResponseWriter, _ *http.Request, _ *types.UserUpdateReq) (*types.UserUpdateResp, error)
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