From 0e1aa473131ec396812956660494e32d6b0c14d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:33:31 +0000 Subject: [PATCH 1/2] feat: an apiKey security scheme's key, sent where the scheme says openapi-codegen read only http schemes, bearer and basic, so a client of an API that declares an apiKey scheme, such as Finnhub's, never sent its key and every call was refused. An apiKey scheme now gives the client an API key, read from {TITLE}_KEY or given with WithAPIKey, which every operation that takes it sends in the header, query parameter or cookie the scheme names, and an operation that requires it fails without it, before sending. Debug mode masks the key in each call it records, with cassette's new Interaction.Mask, so no recording holds it. A scheme replaces an X-Api-Key header parameter, so a client never has two keys. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- README.md | 5 + README/features.md | 5 + codegen_test.go | 2 +- go.mod | 2 +- go.sum | 4 +- ir/auth_test.go | 50 +++ ir/document.go | 19 ++ ir/ir.go | 13 +- render/templates/client.gen.go.tmpl | 53 +++- render/templates/client.gen_test.go.tmpl | 9 + testdata/apikey/api/openapi.json | 23 ++ testdata/apikey/pkg/apikey/api.js | 100 ++++++ testdata/apikey/pkg/apikey/apikey_test.go | 155 +++++++++ testdata/apikey/pkg/apikey/client.gen.go | 298 ++++++++++++++++++ testdata/apikey/pkg/apikey/client.gen_test.go | 267 ++++++++++++++++ testdata/apikey/pkg/apikey/ir.json | 98 ++++++ testdata/apikey/pkg/apikey/server.gen.go | 135 ++++++++ testdata/apikey/pkg/apikey/types.gen.go | 23 ++ .../MarkRosemaker/cassette/README.md | 4 +- .../cassette/interactions_json.go | 12 +- .../github.com/MarkRosemaker/cassette/mask.go | 26 ++ vendor/modules.txt | 2 +- 22 files changed, 1291 insertions(+), 14 deletions(-) create mode 100644 testdata/apikey/api/openapi.json create mode 100644 testdata/apikey/pkg/apikey/api.js create mode 100644 testdata/apikey/pkg/apikey/apikey_test.go create mode 100644 testdata/apikey/pkg/apikey/client.gen.go create mode 100644 testdata/apikey/pkg/apikey/client.gen_test.go create mode 100644 testdata/apikey/pkg/apikey/ir.json create mode 100644 testdata/apikey/pkg/apikey/server.gen.go create mode 100644 testdata/apikey/pkg/apikey/types.gen.go diff --git a/README.md b/README.md index 4baebdf1..49d54453 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,11 @@ How the specification maps onto Go: each operation fails before sending if its own is missing. An operation whose credentials are optional (`{}` beside a scheme) sends them all the same, and its replay test accepts a recording made without them. + An API key of an `apiKey` scheme is read from `{TITLE}_KEY`, as + `FINNHUB_API_KEY` for the title "Finnhub API", or given with `WithAPIKey`, and + sent in the header, query parameter or cookie the scheme names, only where an + operation takes it. Debug mode masks it the moment it records a call, so no + recording holds it. A scheme replaces an `X-Api-Key` header parameter. - **Success responses** — an operation returns its success body as `*T`, or as `T` where `T` is already nilable: a slice, a map, or a named type of either. An operation whose success body is an empty object returns just `error`, and the diff --git a/README/features.md b/README/features.md index 62fd4e03..e3760e3e 100644 --- a/README/features.md +++ b/README/features.md @@ -176,6 +176,11 @@ How the specification maps onto Go: each operation fails before sending if its own is missing. An operation whose credentials are optional (`{}` beside a scheme) sends them all the same, and its replay test accepts a recording made without them. + An API key of an `apiKey` scheme is read from `{TITLE}_KEY`, as + `FINNHUB_API_KEY` for the title "Finnhub API", or given with `WithAPIKey`, and + sent in the header, query parameter or cookie the scheme names, only where an + operation takes it. Debug mode masks it the moment it records a call, so no + recording holds it. A scheme replaces an `X-Api-Key` header parameter. - **Success responses** — an operation returns its success body as `*T`, or as `T` where `T` is already nilable: a slice, a map, or a named type of either. An operation whose success body is an empty object returns just `error`, and the diff --git a/codegen_test.go b/codegen_test.go index fc9b7ee8..f2cf696e 100644 --- a/codegen_test.go +++ b/codegen_test.go @@ -62,7 +62,7 @@ func TestCodegen_TestData(t *testing.T) { t.Fatal(err) } - debug := debugMode || name == "debug" + debug := debugMode || name == "debug" || name == "apikey" // apikey checks what debug mode records irDoc, err := ir.FromDocument(doc, name, "", production, debug) if err != nil { diff --git a/go.mod b/go.mod index f4b47668..005ca15d 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/MarkRosemaker/openapi-codegen go 1.27 require ( - github.com/MarkRosemaker/cassette v0.0.0-20261118230554-38092db8e666 + github.com/MarkRosemaker/cassette v0.0.0-20261124002840-63d2bfa6e316 github.com/MarkRosemaker/errpath v0.0.0-20261118230255-99e20cb3445a github.com/MarkRosemaker/openapi v0.0.0-20261121170220-f57f1b068362 github.com/MarkRosemaker/openapi-compress v0.0.0-20261121170447-b733218e4f67 diff --git a/go.sum b/go.sum index 458c76c1..5ab14c38 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= -github.com/MarkRosemaker/cassette v0.0.0-20261118230554-38092db8e666 h1:uXP3WGfOEsynglAAZAKPtGaWvMx8aWe7TfnsTH9eP0I= -github.com/MarkRosemaker/cassette v0.0.0-20261118230554-38092db8e666/go.mod h1:mIy1SlNqKDRALYBqZGjj+MWPU9dASkyP1d1X+I1HP6k= +github.com/MarkRosemaker/cassette v0.0.0-20261124002840-63d2bfa6e316 h1:vSfOg4aRF7yR5nS1m/0VdXPuV03X8SHqHTB8fvlgtSs= +github.com/MarkRosemaker/cassette v0.0.0-20261124002840-63d2bfa6e316/go.mod h1:mIy1SlNqKDRALYBqZGjj+MWPU9dASkyP1d1X+I1HP6k= github.com/MarkRosemaker/errpath v0.0.0-20261118230255-99e20cb3445a h1:C7Oyg94gPC6/nfCR8ev9FqyxQb5d+GEpU4Oz+rGcoww= github.com/MarkRosemaker/errpath v0.0.0-20261118230255-99e20cb3445a/go.mod h1:VnXpUlsS3n1gSToedcQl2FCARGoA16CyitbCanUIv+I= github.com/MarkRosemaker/json2yaml v0.0.0-20261118230255-853c75cf2bf9 h1:NVTLiOVHTQ/PSq3ihG3kT/P1UqNjJiBHHCGbgNq2rP8= diff --git a/ir/auth_test.go b/ir/auth_test.go index b134679c..5072a7e1 100644 --- a/ir/auth_test.go +++ b/ir/auth_test.go @@ -52,3 +52,53 @@ func TestFromDocument_AuthPerOperation(t *testing.T) { } } } + +// TestFromDocument_APIKey reads an apiKey security scheme, in a header, a query parameter or a cookie, as the key the +// client sends there on each operation that requires it, read from the environment variable named after the API. +// Where a spec also has an X-Api-Key header parameter, the scheme wins: a client has one API key. +func TestFromDocument_APIKey(t *testing.T) { + t.Parallel() + + for _, in := range []string{"header", "query", "cookie"} { + t.Run(in, func(t *testing.T) { + t.Parallel() + + doc, err := openapi.LoadFromDataJSON([]byte(`{ + "openapi": "3.1.0", + "info": {"title": "Finnhub API", "version": "1"}, + "security": [{"api_key": []}], + "paths": { + "/quote": {"get": {"operationId": "quote", "parameters": [{"name": "X-Api-Key", "in": "header", "required": true, "schema": {"type": "string"}}], "responses": {"204": {"description": "ok"}}}}, + "/health": {"get": {"operationId": "health", "security": [], "responses": {"204": {"description": "ok"}}}} + }, + "components": {"securitySchemes": {"api_key": {"type": "apiKey", "in": "` + in + `", "name": "X-Finnhub-Token"}}} +}`)) + if err != nil { + t.Fatal(err) + } + + irDoc, err := ir.FromDocument(doc, "finnhub", "", false, false) + if err != nil { + t.Fatal(err) + } + + if want := (ir.APIKey{In: in, Name: "X-Finnhub-Token", EnvName: "FINNHUB_API_KEY"}); irDoc.Auth.APIKey != want { + t.Errorf("API key is %+v, want %+v", irDoc.Auth.APIKey, want) + } + + if irDoc.Auth.Default != ir.AuthAPIKey { + t.Errorf("default auth is %q, want apiKey", irDoc.Auth.Default) + } + + for _, op := range irDoc.Operations { + if want := map[string]ir.AuthScheme{"Quote": ir.AuthAPIKey}[op.Name]; op.Auth != want { + t.Errorf("%s sends %q, want %q", op.Name, op.Auth, want) + } + } + + if p := irDoc.APIKey(); p != nil { + t.Errorf("the X-Api-Key parameter is an API key too: %+v", p) + } + }) + } +} diff --git a/ir/document.go b/ir/document.go index aa13b564..da84c710 100644 --- a/ir/document.go +++ b/ir/document.go @@ -94,6 +94,12 @@ func FromDocument(doc *openapi.Document, packageName, userAgent string, producti globalParams := make(Params, 0, len(globalParamsMap)) for _, p := range globalParamsMap.ByIndex() { + // an API key a security scheme declares is the client's, sent where the scheme says, not a header parameter + // besides it, so a client never has two + if p.GlobalType == GlobalAPIKey && auth.APIKey.Name != "" { + continue + } + globalParams = append(globalParams, p) } @@ -218,6 +224,17 @@ func fromSecurity(schemes openapi.SecuritySchemes, apiTitle string) (Auth, map[o for name, sec := range schemes { v := sec.Value + if v.Type == openapi.SecuritySchemeTypeAPIKey { + byName[name] = AuthAPIKey + s.APIKey = APIKey{In: string(v.In), Name: v.Name} + + if apiTitle != "" { + s.APIKey.EnvName = strcase.ToSNAKE(fmt.Sprintf("%s_KEY", apiTitle)) + } + + continue + } + switch v.Scheme { case openapi.SecuritySchemeBearer: byName[name] = AuthBearer @@ -252,6 +269,8 @@ func defaultAuth(security openapi.SecurityRequirements, schemes map[openapi.Secu return AuthBearer case auth.Basic.UsernameEnvName != "": return AuthBasic + case auth.APIKey.Name != "": + return AuthAPIKey default: return "" } diff --git a/ir/ir.go b/ir/ir.go index 9bf6e9cd..fc626789 100644 --- a/ir/ir.go +++ b/ir/ir.go @@ -686,16 +686,19 @@ type ReqBody struct { type Auth struct { Bearer Bearer `json:"bearer,omitzero"` Basic Basic `json:"basic,omitzero"` + APIKey APIKey `json:"apiKey,omitzero"` // Default is the scheme operations use unless they name their own, so the client requires its credential. Default AuthScheme `json:"default,omitzero"` } -// AuthScheme names the credential an operation sends in its Authorization header. +// AuthScheme names the credential an operation sends: in its Authorization header, or an API key where its scheme +// says. type AuthScheme string const ( AuthBearer AuthScheme = "bearer" AuthBasic AuthScheme = "basic" + AuthAPIKey AuthScheme = "apiKey" ) type Bearer struct { @@ -707,6 +710,14 @@ type Basic struct { PasswordEnvName string `json:"passwordEnvName,omitzero"` } +// APIKey is an API key a security scheme of type apiKey declares: sent in the header, the query parameter or the +// cookie In says, named Name, and read from the environment variable EnvName. +type APIKey struct { + In string `json:"in,omitzero"` + Name string `json:"name,omitzero"` + EnvName string `json:"envName,omitzero"` +} + // BaseURLExpr returns the Go expression for the URL an operation builds its // request path on: the client's, or serverURL with the server the path item // named for itself. The latter stays overridable -- WithBaseURL has to reach diff --git a/render/templates/client.gen.go.tmpl b/render/templates/client.gen.go.tmpl index b55c81a7..1efe28bd 100644 --- a/render/templates/client.gen.go.tmpl +++ b/render/templates/client.gen.go.tmpl @@ -33,6 +33,10 @@ type Client struct { {{ end -}} {{ .VarName }} string {{ end -}} + {{ with .Auth.APIKey.Name -}} + // The API key, sent in the {{ $.Auth.APIKey.In }} {{ . }} + apiKey string + {{ end -}} {{ with .Client -}} {{ with or .Description "The client parameter" -}} {{ toGoComment . }} @@ -104,6 +108,13 @@ func WithAPIKey({{ .VarName }} string) ClientOption { } {{ end }} +{{ with .Auth.APIKey.Name }} +// WithAPIKey returns a [ClientOption] that sets the API key, sent in the {{ $.Auth.APIKey.In }} {{ . }}. +func WithAPIKey(apiKey string) ClientOption { + return func(c *Client) { c.apiKey = apiKey } +} +{{ end }} + {{ with .Client }} // WithClient returns a [ClientOption] that sets a custom client parameter. func WithClient({{ .VarName }} string) ClientOption { @@ -144,7 +155,7 @@ func (c *Client) serverURL(server *url.URL) *url.URL { } {{ end }} -// NewClient creates a new Client{{ with .Auth.Bearer.Name }}, reading the bearer token from [os.Getenv]("{{ . }}"){{ end }}{{ with .Auth.Basic.UsernameEnvName }}, reading the basic auth username and password from [os.Getenv]("{{ . }}") and [os.Getenv]("{{ $.Auth.Basic.PasswordEnvName }}"){{ end }}. +// NewClient creates a new Client{{ with .Auth.Bearer.Name }}, reading the bearer token from [os.Getenv]("{{ . }}"){{ end }}{{ with .Auth.Basic.UsernameEnvName }}, reading the basic auth username and password from [os.Getenv]("{{ . }}") and [os.Getenv]("{{ $.Auth.Basic.PasswordEnvName }}"){{ end }}{{ with .Auth.APIKey.EnvName }}, reading the API key from [os.Getenv]("{{ . }}"){{ end }}. func NewClient(opts ...ClientOption) (*Client, error) { c := &Client{ cli: http.DefaultClient, @@ -167,6 +178,10 @@ func NewClient(opts ...ClientOption) (*Client, error) { {{ .FormatExpr }} = os.Getenv("{{ .EnvName }}") {{ end }}{{ end }} + {{ with .Auth.APIKey.EnvName }} + c.apiKey = os.Getenv("{{ . }}") + {{ end }} + for _, opt := range opts { opt(c) } @@ -190,6 +205,12 @@ func NewClient(opts ...ClientOption) (*Client, error) { {{ end }}{{ end }} {{ end }} + {{ if eq .Auth.Default "apiKey" }}{{ with .Auth.APIKey }} + if c.apiKey == "" { + return nil, errors.New("API key {{ or .EnvName .Name }} not provided") + } + {{ end }}{{ end }} + {{ with .APIKey }} if {{ .FormatExpr }} == "" { {{ with .EnvName -}} @@ -252,6 +273,11 @@ func (c *Client) {{.Name}}(ctx context.Context{{range .PathParams}}, {{.GoName}} } {{ end }} {{- end }} +{{- if and (eq .Auth "apiKey") (ne $.Auth.Default "apiKey") (not .AuthOptional) }} + if c.apiKey == "" { + return {{if .SuccessReturn}}nil, {{end}}errors.New("API key {{ or $.Auth.APIKey.EnvName $.Auth.APIKey.Name }} not provided") + } +{{ end }} {{/* Always declared: the request below uses u whether or not the operation adds path segments. JoinPath returns a copy, so assigning c.baseURL directly would let a query string mutate the client's base URL. */}} @@ -278,6 +304,15 @@ func (c *Client) {{.Name}}(ctx context.Context{{range .PathParams}}, {{.GoName}} u.RawQuery = {{ printf "%q" . }} {{- end }} {{ end }} +{{- if and (eq .Auth "apiKey") (eq $.Auth.APIKey.In "query") }} + if c.apiKey != "" { + if u.RawQuery != "" { + u.RawQuery += "&" + } + + u.RawQuery += {{ printf "%q" (print $.Auth.APIKey.Name "=") }} + url.QueryEscape(c.apiKey) + } +{{ end }} {{ if and .RequestBody .RequestBody.Required -}} pr, pw := io.Pipe() {{ end -}} @@ -313,6 +348,17 @@ func (c *Client) {{.Name}}(ctx context.Context{{range .PathParams}}, {{.GoName}} ContentLength: -1, {{ end -}} }).WithContext(ctx) +{{- if eq .Auth "apiKey" }}{{ if eq $.Auth.APIKey.In "header" }} + + if c.apiKey != "" { + req.Header.Set({{ printf "%q" $.Auth.APIKey.Name }}, c.apiKey) + } +{{- else if eq $.Auth.APIKey.In "cookie" }} + + if c.apiKey != "" { + req.AddCookie(&http.Cookie{Name: {{ printf "%q" $.Auth.APIKey.Name }}, Value: c.apiKey}) + } +{{- end }}{{ end }} {{ if .RequestBody }}{{ if .RequestBody.Required }} go func() { pw.CloseWithError(json.MarshalWrite(pw, body, {{ if $.HasReadOnly }}jsonOptsRequest{{ else }}jsonOpts{{ end }})) }() @@ -573,6 +619,11 @@ func (c *Client) do(req *http.Request) (*http.Response, *cassette.Interaction, e } ia := &cassette.Interaction{Request: recReq, Response: recRsp} + {{- with .Auth.APIKey.Name }}{{ if ne $.Auth.APIKey.In "cookie" }} + + // masked now, as the key the specification names is no credential cassette knows, so nothing writes it + ia.Mask(cassette.Mask{{ if eq $.Auth.APIKey.In "header" }}Headers{{ else }}Keys{{ end }}({{ printf "%q" . }})) + {{- end }}{{ end }} if c.record { if err := c.keep(ia); err != nil { rsp.Body.Close() diff --git a/render/templates/client.gen_test.go.tmpl b/render/templates/client.gen_test.go.tmpl index 93219a7f..83247833 100644 --- a/render/templates/client.gen_test.go.tmpl +++ b/render/templates/client.gen_test.go.tmpl @@ -18,6 +18,9 @@ func TestClient_Error(t *testing.T) { {{- with $.APIKey }} t.Setenv({{printf "%q" .EnvName }}, {{ or .Example `"**************************************************"` }}) {{end}} + {{- with $.Auth.APIKey.EnvName }} + t.Setenv({{printf "%q" . }}, "**************************************************") + {{end}} t.Run("transport error", func(t *testing.T) { c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, @@ -407,6 +410,9 @@ func TestClient_Params(t *testing.T) { {{- with $.APIKey }} t.Setenv({{printf "%q" .EnvName }}, {{ or .Example `"**************************************************"` }}) {{end}} + {{- with $.Auth.APIKey.EnvName }} + t.Setenv({{printf "%q" . }}, "**************************************************") + {{end}} var got *http.Request c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( @@ -457,6 +463,9 @@ func TestClient_Interactions(t *testing.T) { {{- with $.APIKey }} t.Setenv({{printf "%q" .EnvName }}, {{ or .Example `"**************************************************"` }}) {{end}} + {{- with $.Auth.APIKey.EnvName }} + t.Setenv({{printf "%q" . }}, "**************************************************") + {{end}} last := &apitest.LastBody{Next: apitest.Replay(t, "../../api/interactions.json")} diff --git a/testdata/apikey/api/openapi.json b/testdata/apikey/api/openapi.json new file mode 100644 index 00000000..cadd0807 --- /dev/null +++ b/testdata/apikey/api/openapi.json @@ -0,0 +1,23 @@ +{ + "openapi": "3.1.0", + "info": {"title": "Quotes API", "version": "1", "description": "An API key a security scheme declares, sent in the header it names. TestCodegen_TestData generates pkg/apikey from it, in debug mode, and apikey_test.go there checks the key is sent where the scheme says, only there, and never recorded. Edit them by hand."}, + "servers": [{"url": "https://api.example.com"}], + "security": [{"apiKey": []}], + "paths": { + "/quote": {"get": {"operationId": "getQuote", "description": "Requires the key.", "responses": { + "200": {"description": "ok", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Quote"}}}} + }}}, + "/status": {"get": {"operationId": "getStatus", "description": "Takes the key if there is one.", "security": [{}, {"apiKey": []}], "responses": { + "204": {"description": "ok"} + }}}, + "/health": {"get": {"operationId": "health", "description": "Never takes the key.", "security": [], "responses": { + "204": {"description": "ok"} + }}} + }, + "components": { + "securitySchemes": {"apiKey": {"type": "apiKey", "in": "header", "name": "X-Quotes-Token", "description": "The API key, from the dashboard."}}, + "schemas": { + "Quote": {"type": "object", "required": ["c"], "properties": {"c": {"type": "number", "format": "double", "description": "The current price."}}} + } + } +} diff --git a/testdata/apikey/pkg/apikey/api.js b/testdata/apikey/pkg/apikey/api.js new file mode 100644 index 00000000..e288579a --- /dev/null +++ b/testdata/apikey/pkg/apikey/api.js @@ -0,0 +1,100 @@ +// Code generated by MarkRosemaker/openapi-codegen. DO NOT EDIT. + +/** + * Quotes API Client + * ========================= + * + * Matches the OpenAPI specification. All functions are async and return + * data or `null` on failure. + * + * Usage: + * import './api.js'; // or + * const result = await window.API.getQuote(); + * window.API.getStatus(); + * window.API.health(); + **/ + +const API_BASE = "https://api.example.com"; +const TIMEOUT = 4000; + +// ====================== ENVIRONMENT ====================== +window.ENV = "production"; + +// reportApiError broadcasts a failed API call as a "apikey:ws-message" +// CustomEvent, the same channel server-pushed notifications use, so a single +// listener can surface both origins uniformly. +function reportApiError(operationId, status, message) { + window.dispatchEvent(new CustomEvent("apikey:ws-message", { + detail: { + level: "error", + persistent: true, + title: `${operationId} failed`, + meta: [`Status ${status}`, message], + }, + })); +} + +async function apiFetch(path, options = {}) { + const { + method = "GET", operationId = "Request" + } = options; + const ctrl = new AbortController(); + const timeoutId = setTimeout(() => ctrl.abort(), TIMEOUT); + + try { + const res = await fetch(API_BASE + path, { + ...options, + signal: ctrl.signal, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + + clearTimeout(timeoutId); + + if (!res.ok) { + console.warn(`API Error: ${res.status} ${method} ${path}`); + let message = res.statusText || "Request failed"; + try { + const body = await res.clone().json(); + message = body?.message || body?.error || message; + } catch {} + reportApiError(operationId, res.status, message); + return null; + } + + // JSON is parsed, text is returned as it is, and anything else, such as a zip or an image, as a Blob + const type = res.headers.get("Content-Type") || ""; + if (type.includes("json")) return await res.json(); + if (type.startsWith("text/")) return await res.text(); + return await res.blob(); + } catch (err) { + clearTimeout(timeoutId); + if (err.name === "AbortError") { + console.error(`Request timeout: ${path}`); + reportApiError(operationId, "timeout", `${path} did not respond in time`); + } else { + console.error(`Request failed: ${path}`, err); + reportApiError(operationId, "network", err.message || "Network error"); + } + return null; + } +} + +// ====================== PUBLIC API ====================== + +window.API = { + // GET /quote + getQuote: () => apiFetch("/quote", { + operationId: "GetQuote", + }), + // GET /status + getStatus: () => apiFetch("/status", { + operationId: "GetStatus", + }), + // GET /health + health: () => apiFetch("/health", { + operationId: "Health", + }), +}; diff --git a/testdata/apikey/pkg/apikey/apikey_test.go b/testdata/apikey/pkg/apikey/apikey_test.go new file mode 100644 index 00000000..1a37a163 --- /dev/null +++ b/testdata/apikey/pkg/apikey/apikey_test.go @@ -0,0 +1,155 @@ +// This file is written by hand, not by the generator. +// +// It pins how a client sends an API key a security scheme declares: read from the environment or given with +// WithAPIKey, sent in the header the scheme names on every operation that takes it, and only there, and never written +// to what debug mode records. + +package apikey + +import ( + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "testing" +) + +const key = "k3y-of-the-quotes" + +// fakeQuotes answers every request, the quote with a member the specification does not know where unknown, which +// debug mode records, and keeps what each path was sent. +func fakeQuotes(t *testing.T, unknown bool) (*url.URL, func(path string) *http.Request) { + t.Helper() + + var ( + mu sync.Mutex + sent = map[string]*http.Request{} + ) + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + sent[r.URL.Path] = r + mu.Unlock() + + if r.URL.Path != "/quote" { + w.WriteHeader(http.StatusNoContent) + return + } + + body := `{"c": 12.3}` + if unknown { + body = `{"c": 12.3, "t": 1700000000}` + } + + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + + u, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + return u, func(path string) *http.Request { + mu.Lock() + defer mu.Unlock() + + return sent[path] + } +} + +func TestNewClient_NoKey(t *testing.T) { + t.Setenv("QUOTES_API_KEY", "") + + if _, err := NewClient(); err == nil || !strings.Contains(err.Error(), "QUOTES_API_KEY") { + t.Fatalf("got %v, want an error naming QUOTES_API_KEY", err) + } +} + +func TestAPIKey_SentWhereTheSchemeSays(t *testing.T) { + for name, opts := range map[string][]ClientOption{ + "from the environment": nil, + "given": {WithAPIKey(key)}, + } { + t.Run(name, func(t *testing.T) { + if opts == nil { + t.Setenv("QUOTES_API_KEY", key) + } else { + t.Setenv("QUOTES_API_KEY", "") + } + + u, sent := fakeQuotes(t, false) + + c, err := NewClient(append(opts, WithBaseURL(u))...) + if err != nil { + t.Fatal(err) + } + + if q, err := c.GetQuote(t.Context()); err != nil { + t.Fatal(err) + } else if q.C != 12.3 { + t.Errorf("price %v, want 12.3", q.C) + } + + if err := c.GetStatus(t.Context()); err != nil { + t.Fatal(err) + } + + if err := c.Health(t.Context()); err != nil { + t.Fatal(err) + } + + for path, want := range map[string]string{"/quote": key, "/status": key, "/health": ""} { + r := sent(path) + if got := r.Header.Get("X-Quotes-Token"); got != want { + t.Errorf("%s: X-Quotes-Token %q, want %q", path, got, want) + } + + if strings.Contains(r.URL.RawQuery, key) { + t.Errorf("%s: the key is in the query too: %s", path, r.URL.RawQuery) + } + } + }) + } +} + +func TestAPIKey_NeverRecorded(t *testing.T) { + t.Setenv("QUOTES_API_KEY", "") + + for name, opt := range map[string]func(path string) ClientOption{ + // the quote holds a member the specification does not know, which debug mode records + "debug": WithDebugFile, + "recording": func(path string) ClientOption { return func(c *Client) { WithRecording(c); WithDebugFile(path)(c) } }, + } { + t.Run(name, func(t *testing.T) { + u, _ := fakeQuotes(t, true) + path := filepath.Join(t.TempDir(), "interactions.json") + + c, err := NewClient(WithAPIKey(key), WithBaseURL(u), opt(path)) + if err != nil { + t.Fatal(err) + } + + if _, err := c.GetQuote(t.Context()); err != nil { + t.Fatal(err) + } + + b, err := os.ReadFile(path) + if err != nil { + t.Fatalf("nothing recorded: %v", err) + } + + if strings.Contains(string(b), key) { + t.Errorf("the key is recorded:\n%s", b) + } + + if !strings.Contains(string(b), "X-Quotes-Token") { + t.Errorf("the header is not recorded at all, masked:\n%s", b) + } + }) + } +} diff --git a/testdata/apikey/pkg/apikey/client.gen.go b/testdata/apikey/pkg/apikey/client.gen.go new file mode 100644 index 00000000..4f434e26 --- /dev/null +++ b/testdata/apikey/pkg/apikey/client.gen.go @@ -0,0 +1,298 @@ +// This file provides a client with methods as well as functions to interact with the HTTP API. +// +// Code generated by MarkRosemaker/openapi-codegen. DO NOT EDIT. + +package apikey + +import ( + "cmp" + "context" + "encoding/json/v2" + "errors" + "fmt" + "net/http" + "net/url" + "os" + "strings" + + "github.com/MarkRosemaker/cassette" + "github.com/go-api-libs/api" +) + +const defaultUserAgent = "Quotes API" + +var defaultBaseURL = &url.URL{ + Scheme: "https", + Host: "api.example.com", + Path: "/", +} + +// Client is an HTTP client for the apikey API. +type Client struct { + // The HTTP client to use for requests. + cli *http.Client + // The API key, sent in the header X-Quotes-Token + apiKey string + // The base URL + baseURL *url.URL + // The user agent + userAgent string + // Enable debug mode + debug bool + // In debug mode, add every call to the debug file, not only those the client cannot decode + record bool + // The file debug mode adds the calls it cannot decode to, defaultDebugFile if empty + debugFile string +} + +// ClientOption configures a [Client]. +type ClientOption func(*Client) + +// WithBaseURL returns a [ClientOption] that overrides the default base URL. +// It will prefix a leading slash to the path if there is none. +func WithBaseURL(baseURL *url.URL) ClientOption { + if !strings.HasPrefix(baseURL.Path, "/") { + baseURL.Path = "/" + baseURL.Path + } + + return func(c *Client) { c.baseURL = baseURL } +} + +// WithHTTPClient returns a [ClientOption] that sets a custom HTTP client. +// +// To mock the client in tests, pass one whose Transport is cassette.Replay(interactions), from +// github.com/MarkRosemaker/cassette: it answers each request from the recorded interaction it matches, +// and fails any other, without the network. +func WithHTTPClient(cli *http.Client) ClientOption { + return func(c *Client) { c.cli = cli } +} + +// WithAPIKey returns a [ClientOption] that sets the API key, sent in the header X-Quotes-Token. +func WithAPIKey(apiKey string) ClientOption { + return func(c *Client) { c.apiKey = apiKey } +} + +// defaultDebugFile is where debug mode adds the calls it cannot decode, unless [WithDebugFile] says otherwise. +const defaultDebugFile = "api/interactions.json" + +// WithDebug is a [ClientOption] that sets the debug mode to true: a response the client cannot decode is added, masked +// and once, to the interactions in "api/interactions.json", for openapi-enrich to learn from, and decoded leniently. +func WithDebug(c *Client) { c.debug = true } + +// WithDebugFile returns a [ClientOption] that sets the debug mode to true, adding to the interactions in the file at +// path, see [WithDebug]. +func WithDebugFile(path string) ClientOption { + return func(c *Client) { c.debug, c.debugFile = true, path } +} + +// WithRecording is a [ClientOption] that sets the debug mode to true, see [WithDebug], and adds every call to the +// interactions, masked and once, whether the client can decode its response or not: a way to record what the API +// really sends. As each call reads and rewrites the file, it is for recording, not for everyday use. +func WithRecording(c *Client) { c.debug, c.record = true, true } + +// NewClient creates a new Client, reading the API key from [os.Getenv]("QUOTES_API_KEY"). +func NewClient(opts ...ClientOption) (*Client, error) { + c := &Client{ + cli: http.DefaultClient, + baseURL: defaultBaseURL, + userAgent: defaultUserAgent, + } + + c.apiKey = os.Getenv("QUOTES_API_KEY") + + for _, opt := range opts { + opt(c) + } + + if c.apiKey == "" { + return nil, errors.New("API key QUOTES_API_KEY not provided") + } + + return c, nil +} + +// Requires the key. +// +// GET /quote +func (c *Client) GetQuote(ctx context.Context) (*Quote, error) { + u := c.baseURL.JoinPath("quote") + req := (&http.Request{ + Header: http.Header{ + "User-Agent": []string{c.userAgent}, + }, + Host: u.Host, + Method: http.MethodGet, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + URL: u, + }).WithContext(ctx) + + if c.apiKey != "" { + req.Header.Set("X-Quotes-Token", c.apiKey) + } + + rsp, ia, err := c.do(req) + if err != nil { + return nil, err + } + defer rsp.Body.Close() + + switch rsp.StatusCode { + case http.StatusOK: + // ok + switch mt, _, _ := strings.Cut(rsp.Header.Get("Content-Type"), ";"); mt { + case "application/json": + var out Quote + if err := json.UnmarshalRead(rsp.Body, &out, jsonOpts); err != nil { + if err := api.DecodeLenient(rsp, err, ia, cmp.Or(c.debugFile, defaultDebugFile), &out, jsonOpts); err != nil { + return nil, err + } + } + + return &out, nil + default: + return nil, c.failed(ia, api.NewErrUnknownContentType(rsp)) + } + default: + return nil, c.failed(ia, api.NewErrUnknownStatusCode(rsp)) + } +} + +// Takes the key if there is one. +// +// GET /status +func (c *Client) GetStatus(ctx context.Context) error { + u := c.baseURL.JoinPath("status") + req := (&http.Request{ + Header: http.Header{ + "User-Agent": []string{c.userAgent}, + }, + Host: u.Host, + Method: http.MethodGet, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + URL: u, + }).WithContext(ctx) + + if c.apiKey != "" { + req.Header.Set("X-Quotes-Token", c.apiKey) + } + + rsp, ia, err := c.do(req) + if err != nil { + return err + } + defer rsp.Body.Close() + + switch rsp.StatusCode { + case http.StatusNoContent: + // ok + switch mt, _, _ := strings.Cut(rsp.Header.Get("Content-Type"), ";"); mt { + case "": + + return nil + default: + return c.failed(ia, api.NewErrUnknownContentType(rsp)) + } + default: + return c.failed(ia, api.NewErrUnknownStatusCode(rsp)) + } +} + +// Never takes the key. +// +// GET /health +func (c *Client) Health(ctx context.Context) error { + u := c.baseURL.JoinPath("health") + req := (&http.Request{ + Header: http.Header{ + "User-Agent": []string{c.userAgent}, + }, + Host: u.Host, + Method: http.MethodGet, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + URL: u, + }).WithContext(ctx) + + rsp, ia, err := c.do(req) + if err != nil { + return err + } + defer rsp.Body.Close() + + switch rsp.StatusCode { + case http.StatusNoContent: + // ok + switch mt, _, _ := strings.Cut(rsp.Header.Get("Content-Type"), ";"); mt { + case "": + + return nil + default: + return c.failed(ia, api.NewErrUnknownContentType(rsp)) + } + default: + return c.failed(ia, api.NewErrUnknownStatusCode(rsp)) + } +} + +// do sends req and, in debug mode, records the call: to add it to the debug file right away with [WithRecording], or +// for [Client.keep] to add should the client not decode the response. +func (c *Client) do(req *http.Request) (*http.Response, *cassette.Interaction, error) { + if !c.debug { + rsp, err := c.cli.Do(req) + return rsp, nil, err + } + + recReq, err := cassette.NewRequest(req) + if err != nil { + return nil, nil, fmt.Errorf("recording request: %w", err) + } + + rsp, err := c.cli.Do(req) + if err != nil { + return nil, nil, err + } + + recRsp, err := cassette.NewResponse(rsp) + if err != nil { + rsp.Body.Close() + return nil, nil, fmt.Errorf("recording response: %w", err) + } + + ia := &cassette.Interaction{Request: recReq, Response: recRsp} + + // masked now, as the key the specification names is no credential cassette knows, so nothing writes it + ia.Mask(cassette.MaskHeaders("X-Quotes-Token")) + if c.record { + if err := c.keep(ia); err != nil { + rsp.Body.Close() + return nil, nil, fmt.Errorf("recording the call: %w", err) + } + } + + return rsp, ia, nil +} + +// keep adds ia, a call the client could not decode, to the interactions in the debug file right away: masked, and +// once, however often the call fails. Outside debug mode, ia is nil, and there is nothing to add. +func (c *Client) keep(ia *cassette.Interaction) error { + if ia == nil { + return nil + } + + return cassette.AddInteraction(cmp.Or(c.debugFile, defaultDebugFile), ia) +} + +// failed is err, the error of the call ia records, which it adds to the debug file, see [Client.keep]; joined with +// any error doing so. +func (c *Client) failed(ia *cassette.Interaction, err error) error { + if kerr := c.keep(ia); kerr != nil { + return errors.Join(err, kerr) + } + + return err +} diff --git a/testdata/apikey/pkg/apikey/client.gen_test.go b/testdata/apikey/pkg/apikey/client.gen_test.go new file mode 100644 index 00000000..3997a4ee --- /dev/null +++ b/testdata/apikey/pkg/apikey/client.gen_test.go @@ -0,0 +1,267 @@ +// This file provides tests for the client. +// +// Code generated by MarkRosemaker/openapi-codegen. DO NOT EDIT. + +package apikey + +import ( + "encoding/json/jsontext" + "errors" + "io" + "io/fs" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "testing" + + "github.com/MarkRosemaker/cassette" + "github.com/go-api-libs/api" + "github.com/go-api-libs/api/apitest" +) + +func TestClient_Error(t *testing.T) { + t.Run("GetQuote", func(t *testing.T) { + t.Setenv("QUOTES_API_KEY", "**************************************************") + + t.Run("transport error", func(t *testing.T) { + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( + func(*http.Request) (*http.Response, error) { return nil, io.EOF }, + )})) + if err != nil { + t.Fatal(err) + } + + if _, err := c.GetQuote(t.Context()); err == nil { + t.Fatal("expected error") + } else if !errors.Is(err, io.EOF) { + t.Fatalf("want: %v, got: %v", io.EOF, err) + } + }) + + t.Run("unknown status code", func(t *testing.T) { + srv := apitest.NewServer(t, http.StatusTeapot) + + baseURL, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(baseURL)) + if err != nil { + t.Fatal(err) + } + + if _, err := c.GetQuote(t.Context()); err == nil { + t.Fatal("expected error") + } else if apiErr, ok := errors.AsType[*api.Error](err); !ok { + t.Fatalf("got: %T, want: *api.Error", err) + } else if apiErr.Err != api.ErrUnknownStatusCode { + t.Fatalf("got: %v, want: %v", apiErr.Err, api.ErrUnknownStatusCode) + } else if apiErr.Response.StatusCode != http.StatusTeapot { + t.Fatalf("got: %v, want: %v", apiErr.Response.StatusCode, http.StatusTeapot) + } + }) + + t.Run("unknown content type", func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "foo") + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + + baseURL, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(baseURL)) + if err != nil { + t.Fatal(err) + } + + if _, err := c.GetQuote(t.Context()); err == nil { + t.Fatal("expected error") + } else if !errors.Is(err, api.ErrUnknownContentType) { + t.Fatalf("want: %v, got: %v", api.ErrUnknownContentType, err) + } + }) + + t.Run("decoding error", func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("invalid json")) + })) + t.Cleanup(srv.Close) + + baseURL, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(baseURL)) + if err != nil { + t.Fatal(err) + } + + if _, err := c.GetQuote(t.Context()); err == nil { + t.Fatal("expected error") + } else if decErr, ok := errors.AsType[*api.DecodingError](err); !ok { + t.Fatalf("got: %T, want: *api.DecodingError", err) + } else if _, ok := errors.AsType[*jsontext.SyntacticError](decErr.Err); !ok { + t.Fatalf("got: %T, want: *jsontext.SyntacticError", decErr.Err) + } + }) + + t.Run("debug mode keeps an unknown member", func(t *testing.T) { + file := filepath.Join(t.TempDir(), "interactions.json") + + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", apitest.WithUnknownMember(t, Quote{}, jsonOpts))), WithDebugFile(file)) + if err != nil { + t.Fatal(err) + } + + for range 2 { + if _, err := c.GetQuote(t.Context()); err != nil { + t.Fatalf("debug mode decodes leniently: %v", err) + } + } + + if ias, err := cassette.InteractionsReadFile(file); err != nil { + t.Fatal(err) + } else if len(ias) != 1 { + t.Fatalf("the debug file holds %d calls, want the one that failed to decode, once", len(ias)) + } + }) + + t.Run("debug mode keeps a body it cannot decode", func(t *testing.T) { + file := filepath.Join(t.TempDir(), "interactions.json") + + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(file)) + if err != nil { + t.Fatal(err) + } + + if _, err := c.GetQuote(t.Context()); err == nil { + t.Fatal("expected error") + } else if _, ok := errors.AsType[*api.DecodingError](err); !ok { + t.Fatalf("got: %T, want: *api.DecodingError", err) + } + + if ias, err := cassette.InteractionsReadFile(file); err != nil { + t.Fatal(err) + } else if len(ias) != 1 { + t.Fatalf("the debug file holds %d calls, want the one that failed to decode", len(ias)) + } + }) + + t.Run("debug mode reports a debug file it cannot write", func(t *testing.T) { + // a file where the debug file's directory would be + blocker := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(blocker, nil, 0o600); err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(filepath.Join(blocker, "interactions.json"))) + if err != nil { + t.Fatal(err) + } + + if _, err := c.GetQuote(t.Context()); err == nil { + t.Fatal("expected error") + } else if _, ok := errors.AsType[*api.DecodingError](err); !ok { + t.Fatalf("got: %T, want the *api.DecodingError", err) + } else if _, ok := errors.AsType[*fs.PathError](err); !ok { + t.Fatalf("got: %v, want the failure to write the debug file beside it", err) + } + }) + }) + + t.Run("GetStatus", func(t *testing.T) { + t.Setenv("QUOTES_API_KEY", "**************************************************") + + t.Run("transport error", func(t *testing.T) { + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( + func(*http.Request) (*http.Response, error) { return nil, io.EOF }, + )})) + if err != nil { + t.Fatal(err) + } + + if err := c.GetStatus(t.Context()); err == nil { + t.Fatal("expected error") + } else if !errors.Is(err, io.EOF) { + t.Fatalf("want: %v, got: %v", io.EOF, err) + } + }) + + t.Run("unknown status code", func(t *testing.T) { + srv := apitest.NewServer(t, http.StatusTeapot) + + baseURL, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(baseURL)) + if err != nil { + t.Fatal(err) + } + + if err := c.GetStatus(t.Context()); err == nil { + t.Fatal("expected error") + } else if apiErr, ok := errors.AsType[*api.Error](err); !ok { + t.Fatalf("got: %T, want: *api.Error", err) + } else if apiErr.Err != api.ErrUnknownStatusCode { + t.Fatalf("got: %v, want: %v", apiErr.Err, api.ErrUnknownStatusCode) + } else if apiErr.Response.StatusCode != http.StatusTeapot { + t.Fatalf("got: %v, want: %v", apiErr.Response.StatusCode, http.StatusTeapot) + } + }) + }) + + t.Run("Health", func(t *testing.T) { + t.Setenv("QUOTES_API_KEY", "**************************************************") + + t.Run("transport error", func(t *testing.T) { + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( + func(*http.Request) (*http.Response, error) { return nil, io.EOF }, + )})) + if err != nil { + t.Fatal(err) + } + + if err := c.Health(t.Context()); err == nil { + t.Fatal("expected error") + } else if !errors.Is(err, io.EOF) { + t.Fatalf("want: %v, got: %v", io.EOF, err) + } + }) + + t.Run("unknown status code", func(t *testing.T) { + srv := apitest.NewServer(t, http.StatusTeapot) + + baseURL, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(baseURL)) + if err != nil { + t.Fatal(err) + } + + if err := c.Health(t.Context()); err == nil { + t.Fatal("expected error") + } else if apiErr, ok := errors.AsType[*api.Error](err); !ok { + t.Fatalf("got: %T, want: *api.Error", err) + } else if apiErr.Err != api.ErrUnknownStatusCode { + t.Fatalf("got: %v, want: %v", apiErr.Err, api.ErrUnknownStatusCode) + } else if apiErr.Response.StatusCode != http.StatusTeapot { + t.Fatalf("got: %v, want: %v", apiErr.Response.StatusCode, http.StatusTeapot) + } + }) + }) +} diff --git a/testdata/apikey/pkg/apikey/ir.json b/testdata/apikey/pkg/apikey/ir.json new file mode 100644 index 00000000..f392a609 --- /dev/null +++ b/testdata/apikey/pkg/apikey/ir.json @@ -0,0 +1,98 @@ +{ + "debug": true, + "title": "Quotes API", + "production": true, + "packageName": "apikey", + "baseURL": { + "scheme": "https", + "host": "api.example.com" + }, + "userAgent": "Quotes API", + "operations": [ + { + "auth": "apiKey", + "name": "GetQuote", + "description": "Requires the key.", + "method": "GET", + "pathTemplate": "/quote", + "joinPathArgs": [ + "\"quote\"" + ], + "responses": [ + { + "statusCode": "200", + "goConstant": "http.StatusOK", + "description": "ok", + "contentType": "application/json", + "goType": { + "name": "Quote" + }, + "isSuccess": true + } + ], + "successReturn": { + "name": "Quote" + } + }, + { + "auth": "apiKey", + "authOptional": true, + "name": "GetStatus", + "description": "Takes the key if there is one.", + "method": "GET", + "pathTemplate": "/status", + "joinPathArgs": [ + "\"status\"" + ], + "responses": [ + { + "statusCode": "204", + "goConstant": "http.StatusNoContent", + "description": "ok", + "isSuccess": true + } + ] + }, + { + "name": "Health", + "description": "Never takes the key.", + "method": "GET", + "pathTemplate": "/health", + "joinPathArgs": [ + "\"health\"" + ], + "responses": [ + { + "statusCode": "204", + "goConstant": "http.StatusNoContent", + "description": "ok", + "isSuccess": true + } + ] + } + ], + "schemas": [ + { + "name": "Quote", + "description": "Quote defines a model", + "fields": [ + { + "name": "C", + "jsonName": "c", + "type": "float64", + "jsonTag": "json:\"c\"", + "description": "The current price.", + "required": true + } + ] + } + ], + "security": { + "apiKey": { + "in": "header", + "name": "X-Quotes-Token", + "envName": "QUOTES_API_KEY" + }, + "default": "apiKey" + } +} \ No newline at end of file diff --git a/testdata/apikey/pkg/apikey/server.gen.go b/testdata/apikey/pkg/apikey/server.gen.go new file mode 100644 index 00000000..0197eb13 --- /dev/null +++ b/testdata/apikey/pkg/apikey/server.gen.go @@ -0,0 +1,135 @@ +// Code generated by MarkRosemaker/openapi-codegen. DO NOT EDIT. + +package apikey + +import ( + "context" + "encoding/json/v2" + "errors" + "fmt" + "log/slog" + "net/http" + + "github.com/go-api-libs/api/server" +) + +// Service defines the operations the server must implement. +type Service interface { + GetQuote(ctx context.Context) (*Quote, error) + GetStatus(ctx context.Context) error + Health(ctx context.Context) error +} + +// RegisterService registers a [Service] with an [*http.ServeMux]. +// Optionally, a path prefix may be provided. +func RegisterService(svc Service, mux *http.ServeMux, pathPrefix string) { + { + path := fmt.Sprintf("%s%s", pathPrefix, "/quote") + l := slog.Default().With(slog.String("method", "GET"), slog.String("path", path), slog.String("function", "GetQuote")) + + mux.HandleFunc(fmt.Sprintf("GET %s", path), func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + l.DebugContext(ctx, "called") + + res, err := svc.GetQuote(ctx) + if err != nil { + sErr, ok := errors.AsType[*server.Error](err) + if !ok { + l.ErrorContext(ctx, "Internal Server Error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + l.DebugContext(ctx, "graceful error", slog.String("error", err.Error())) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(sErr.Code) + + if err := json.MarshalWrite(w, err); err != nil { + l.ErrorContext(ctx, "marshal error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } + return + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + if err := json.MarshalWrite(w, res, jsonOpts); err != nil { + l.ErrorContext(ctx, "marshal error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + l.DebugContext(ctx, "success") + }) + } + + { + path := fmt.Sprintf("%s%s", pathPrefix, "/status") + l := slog.Default().With(slog.String("method", "GET"), slog.String("path", path), slog.String("function", "GetStatus")) + + mux.HandleFunc(fmt.Sprintf("GET %s", path), func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + l.DebugContext(ctx, "called") + + if err := svc.GetStatus(ctx); err != nil { + sErr, ok := errors.AsType[*server.Error](err) + if !ok { + l.ErrorContext(ctx, "Internal Server Error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + l.DebugContext(ctx, "graceful error", slog.String("error", err.Error())) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(sErr.Code) + + if err := json.MarshalWrite(w, err); err != nil { + l.ErrorContext(ctx, "marshal error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } + return + } + + w.WriteHeader(http.StatusNoContent) + + l.DebugContext(ctx, "success") + }) + } + + { + path := fmt.Sprintf("%s%s", pathPrefix, "/health") + l := slog.Default().With(slog.String("method", "GET"), slog.String("path", path), slog.String("function", "Health")) + + mux.HandleFunc(fmt.Sprintf("GET %s", path), func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + l.DebugContext(ctx, "called") + + if err := svc.Health(ctx); err != nil { + sErr, ok := errors.AsType[*server.Error](err) + if !ok { + l.ErrorContext(ctx, "Internal Server Error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + l.DebugContext(ctx, "graceful error", slog.String("error", err.Error())) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(sErr.Code) + + if err := json.MarshalWrite(w, err); err != nil { + l.ErrorContext(ctx, "marshal error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } + return + } + + w.WriteHeader(http.StatusNoContent) + + l.DebugContext(ctx, "success") + }) + } +} diff --git a/testdata/apikey/pkg/apikey/types.gen.go b/testdata/apikey/pkg/apikey/types.gen.go new file mode 100644 index 00000000..bc38c186 --- /dev/null +++ b/testdata/apikey/pkg/apikey/types.gen.go @@ -0,0 +1,23 @@ +// This file provides types for the API. +// +// Code generated by MarkRosemaker/openapi-codegen. DO NOT EDIT. + +package apikey + +import ( + "encoding/json/v2" +) + +var jsonOpts = json.JoinOptions( + json.RejectUnknownMembers(true), +) + +// jsonOptsLenient is jsonOpts accepting members the specification does not know, as debug mode decodes once a strict +// decoding failed. +var jsonOptsLenient = json.JoinOptions(jsonOpts, json.RejectUnknownMembers(false)) + +// Quote defines a model +type Quote struct { + // The current price. + C float64 `json:"c"` +} diff --git a/vendor/github.com/MarkRosemaker/cassette/README.md b/vendor/github.com/MarkRosemaker/cassette/README.md index 30ab57c1..b42237cd 100644 --- a/vendor/github.com/MarkRosemaker/cassette/README.md +++ b/vendor/github.com/MarkRosemaker/cassette/README.md @@ -30,7 +30,9 @@ on it, and offer it to its users, at no cost. every call must match the next recording, headers included, and `Recorder.Unused` tells which recordings were never called. - **Masking**: writing a file always masks credentials first, in headers, bodies - and query values, as `Interactions.Mask` does. + and query values, as `Interactions.Mask` does. `AddInteraction` and + `Interaction.Mask` also mask the headers `MaskHeaders` names and the keys + `MaskKeys` names, as the one an API names to carry its key. - **Once per call**: `AddInteraction` writes a call to a file only if it is not in it yet, so a failure that recurs is recorded once. - **Large bodies**: a body that is not text is never read or written, only diff --git a/vendor/github.com/MarkRosemaker/cassette/interactions_json.go b/vendor/github.com/MarkRosemaker/cassette/interactions_json.go index 4657dd0b..a11237f8 100644 --- a/vendor/github.com/MarkRosemaker/cassette/interactions_json.go +++ b/vendor/github.com/MarkRosemaker/cassette/interactions_json.go @@ -64,14 +64,14 @@ func (ias Interactions) MarshalWrite(w io.Writer) error { var mu sync.Mutex -// AddInteraction adds ia to the interactions in the file at path, masked as [Interactions.Mask] does and with its bodies trimmed as -// [Interactions.TrimBodies] does with [MaxStringLen], writing the file right away; ia is left as it is. A call the -// file holds already, the same request answered with the same status and body, is not added again: a client retrying -// a call, or polling one, records it once. -func AddInteraction(path string, ia *Interaction) error { +// AddInteraction adds ia to the interactions in the file at path, masked as [Interactions.Mask] does, and as opts say +// besides, and with its bodies trimmed as [Interactions.TrimBodies] does with [MaxStringLen], writing the file right +// away; ia is left as it is. A call the file holds already, the same request answered with the same status and body, is +// not added again: a client retrying a call, or polling one, records it once. +func AddInteraction(path string, ia *Interaction, opts ...MaskOption) error { ia = ia.clone() ia.trimBodies(MaxStringLen) - ia.maskWith(defaultMasker()) + ia.Mask(opts...) mu.Lock() defer mu.Unlock() diff --git a/vendor/github.com/MarkRosemaker/cassette/mask.go b/vendor/github.com/MarkRosemaker/cassette/mask.go index 220e6d09..81fe07a4 100644 --- a/vendor/github.com/MarkRosemaker/cassette/mask.go +++ b/vendor/github.com/MarkRosemaker/cassette/mask.go @@ -120,6 +120,21 @@ func defaultMasker() masker { } } +// MaskOption makes [AddInteraction] or [Interaction.Mask] redact more than they always do. +type MaskOption func(*masker) + +// MaskHeaders makes [AddInteraction] or [Interaction.Mask] redact the values of the headers named, in requests and responses alike, as one +// an API names to carry its key, such as X-Finnhub-Token. Matching is case-insensitive. +func MaskHeaders(names ...string) MaskOption { + return func(m *masker) { m.HeaderKeys = append(m.HeaderKeys, names...) } +} + +// MaskKeys makes [AddInteraction] or [Interaction.Mask] redact the values of the query parameters and body members named, as a query +// parameter an API names to carry its key. Matching is case-insensitive. +func MaskKeys(names ...string) MaskOption { + return func(m *masker) { m.BodyKeys = append(m.BodyKeys, names...) } +} + // rules is the compiled form of a [masker]: key sets rather than slices. type rules struct { headers, keys, ids, names, usernames map[string]bool @@ -141,6 +156,17 @@ func (ia *Interaction) maskWith(m masker) { // Mask redacts credentials in place: in headers, in bodies and in query values. func (ias Interactions) Mask() { ias.maskWith(defaultMasker()) } +// Mask redacts credentials in ia in place, as [Interactions.Mask] does, and what opts name besides: a client masks the +// call it records as soon as it records it, so that whatever writes it later, and however, never writes its key. +func (ia *Interaction) Mask(opts ...MaskOption) { + m := defaultMasker() + for _, opt := range opts { + opt(&m) + } + + ia.maskWith(m) +} + // maskWith redacts sensitive values in place according to m. func (ias Interactions) maskWith(m masker) { r := m.rules() diff --git a/vendor/modules.txt b/vendor/modules.txt index 8547cdc8..e89bd032 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,7 +1,7 @@ # cloud.google.com/go v0.123.0 ## explicit; go 1.24.0 cloud.google.com/go/civil -# github.com/MarkRosemaker/cassette v0.0.0-20261118230554-38092db8e666 +# github.com/MarkRosemaker/cassette v0.0.0-20261124002840-63d2bfa6e316 ## explicit; go 1.27 github.com/MarkRosemaker/cassette # github.com/MarkRosemaker/errpath v0.0.0-20261118230255-99e20cb3445a From f68dd5b89b9777eeb681522fcafa73e0c31e3fa0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:54:01 +0000 Subject: [PATCH 2/2] chore: bump cassette to main, with Interaction.Mask merged Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- go.mod | 2 +- go.sum | 4 ++-- vendor/modules.txt | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 005ca15d..51b4d8fb 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/MarkRosemaker/openapi-codegen go 1.27 require ( - github.com/MarkRosemaker/cassette v0.0.0-20261124002840-63d2bfa6e316 + github.com/MarkRosemaker/cassette v0.0.0-20261124005255-dfc1563db595 github.com/MarkRosemaker/errpath v0.0.0-20261118230255-99e20cb3445a github.com/MarkRosemaker/openapi v0.0.0-20261121170220-f57f1b068362 github.com/MarkRosemaker/openapi-compress v0.0.0-20261121170447-b733218e4f67 diff --git a/go.sum b/go.sum index 5ab14c38..ec54c2e4 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= -github.com/MarkRosemaker/cassette v0.0.0-20261124002840-63d2bfa6e316 h1:vSfOg4aRF7yR5nS1m/0VdXPuV03X8SHqHTB8fvlgtSs= -github.com/MarkRosemaker/cassette v0.0.0-20261124002840-63d2bfa6e316/go.mod h1:mIy1SlNqKDRALYBqZGjj+MWPU9dASkyP1d1X+I1HP6k= +github.com/MarkRosemaker/cassette v0.0.0-20261124005255-dfc1563db595 h1:08PzAZnvkGwBGEqOC5QJO+UP6xuRpSj208Kf0/GDsP4= +github.com/MarkRosemaker/cassette v0.0.0-20261124005255-dfc1563db595/go.mod h1:mIy1SlNqKDRALYBqZGjj+MWPU9dASkyP1d1X+I1HP6k= github.com/MarkRosemaker/errpath v0.0.0-20261118230255-99e20cb3445a h1:C7Oyg94gPC6/nfCR8ev9FqyxQb5d+GEpU4Oz+rGcoww= github.com/MarkRosemaker/errpath v0.0.0-20261118230255-99e20cb3445a/go.mod h1:VnXpUlsS3n1gSToedcQl2FCARGoA16CyitbCanUIv+I= github.com/MarkRosemaker/json2yaml v0.0.0-20261118230255-853c75cf2bf9 h1:NVTLiOVHTQ/PSq3ihG3kT/P1UqNjJiBHHCGbgNq2rP8= diff --git a/vendor/modules.txt b/vendor/modules.txt index e89bd032..ff8ad5a9 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,7 +1,7 @@ # cloud.google.com/go v0.123.0 ## explicit; go 1.24.0 cloud.google.com/go/civil -# github.com/MarkRosemaker/cassette v0.0.0-20261124002840-63d2bfa6e316 +# github.com/MarkRosemaker/cassette v0.0.0-20261124005255-dfc1563db595 ## explicit; go 1.27 github.com/MarkRosemaker/cassette # github.com/MarkRosemaker/errpath v0.0.0-20261118230255-99e20cb3445a