Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions README/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion codegen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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-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
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -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-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=
Expand Down
50 changes: 50 additions & 0 deletions ir/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})
}
}
19 changes: 19 additions & 0 deletions ir/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 ""
}
Expand Down
13 changes: 12 additions & 1 deletion ir/ir.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand Down
53 changes: 52 additions & 1 deletion render/templates/client.gen.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -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 . }}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand All @@ -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)
}
Expand All @@ -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 -}}
Expand Down Expand Up @@ -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. */}}
Expand All @@ -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 -}}
Expand Down Expand Up @@ -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 }})) }()
Expand Down Expand Up @@ -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()
Expand Down
9 changes: 9 additions & 0 deletions render/templates/client.gen_test.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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")}

Expand Down
23 changes: 23 additions & 0 deletions testdata/apikey/api/openapi.json
Original file line number Diff line number Diff line change
@@ -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."}}}
}
}
}
Loading
Loading