From 32a4f3721b8e0d605c29cf5fb31e4afa5a96d4d3 Mon Sep 17 00:00:00 2001 From: Slavek Kabrda Date: Tue, 17 Mar 2020 14:40:45 +0100 Subject: [PATCH 1/2] [go-experimental][go][client] Remove unreachable code in go client API methods --- .../openapitools/codegen/CodegenResponse.java | 5 + .../openapitools/codegen/DefaultCodegen.java | 7 + .../resources/go-experimental/api.mustache | 4 + .../src/main/resources/go/api.mustache | 4 + .../go-petstore/api_another_fake.go | 9 - .../go-experimental/go-petstore/api_fake.go | 45 -- .../go-petstore/api_fake_classname_tags123.go | 9 - .../go-experimental/go-petstore/api_pet.go | 48 -- .../go-experimental/go-petstore/api_store.go | 29 - .../go-experimental/go-petstore/api_user.go | 20 - .../go/go-petstore/api_another_fake.go | 9 - .../petstore/go/go-petstore/api_fake.go | 45 -- .../go-petstore/api_fake_classname_tags123.go | 9 - .../client/petstore/go/go-petstore/api_pet.go | 48 -- .../petstore/go/go-petstore/api_store.go | 29 - .../petstore/go/go-petstore/api_user.go | 20 - .../go-petstore/api_another_fake.go | 9 - .../go-experimental/go-petstore/api_fake.go | 54 -- .../go-petstore/api_fake_classname_tags123.go | 9 - .../go-experimental/go-petstore/api_pet.go | 48 -- .../go-experimental/go-petstore/api_store.go | 29 - .../go-experimental/go-petstore/api_user.go | 20 - .../go-petstore/http_signature_test.go | 728 ++++++++++++++++++ .../go/go-petstore/api_another_fake.go | 9 - .../petstore/go/go-petstore/api_fake.go | 54 -- .../go-petstore/api_fake_classname_tags123.go | 9 - .../client/petstore/go/go-petstore/api_pet.go | 48 -- .../petstore/go/go-petstore/api_store.go | 29 - .../petstore/go/go-petstore/api_user.go | 20 - 29 files changed, 748 insertions(+), 658 deletions(-) create mode 100644 samples/openapi3/client/petstore/go-experimental/go-petstore/http_signature_test.go diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java index 29429c073b7e..1edad97316f6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java @@ -22,6 +22,11 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { public final List headers = new ArrayList(); public String code; + public boolean is1xx; + public boolean is2xx; + public boolean is3xx; + public boolean is4xx; + public boolean is5xx; public String message; public boolean hasMore; public List> examples; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 2e5f4f405366..5cc75dab96da 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -3272,6 +3272,13 @@ public CodegenResponse fromResponse(String responseCode, ApiResponse response) { r.code = "0"; } else { r.code = responseCode; + switch(r.code.charAt(0)) { + case '1': r.is1xx = true; break; + case '2': r.is2xx = true; break; + case '3': r.is3xx = true; break; + case '4': r.is4xx = true; break; + case '5': r.is5xx = true; break; + } } Schema responseSchema; if (this.openAPI != null && this.openAPI.getComponents() != null) { diff --git a/modules/openapi-generator/src/main/resources/go-experimental/api.mustache b/modules/openapi-generator/src/main/resources/go-experimental/api.mustache index 96ac8f2d4a60..32bfc5a13367 100644 --- a/modules/openapi-generator/src/main/resources/go-experimental/api.mustache +++ b/modules/openapi-generator/src/main/resources/go-experimental/api.mustache @@ -286,6 +286,8 @@ func (r api{{operationId}}Request) Execute() ({{#returnType}}{{{.}}}, {{/returnT } {{#responses}} {{#dataType}} + {{^is1xx}} + {{^is2xx}} {{^wildcard}} if localVarHTTPResponse.StatusCode == {{{code}}} { {{/wildcard}} @@ -302,6 +304,8 @@ func (r api{{operationId}}Request) Execute() ({{#returnType}}{{{.}}}, {{/returnT {{^wildcard}} } {{/wildcard}} + {{/is2xx}} + {{/is1xx}} {{/dataType}} {{/responses}} return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr diff --git a/modules/openapi-generator/src/main/resources/go/api.mustache b/modules/openapi-generator/src/main/resources/go/api.mustache index d241805b54f7..7805eaae6895 100644 --- a/modules/openapi-generator/src/main/resources/go/api.mustache +++ b/modules/openapi-generator/src/main/resources/go/api.mustache @@ -320,6 +320,8 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams } {{#responses}} {{#dataType}} + {{^is1xx}} + {{^is2xx}} {{^wildcard}} if localVarHTTPResponse.StatusCode == {{{code}}} { {{/wildcard}} @@ -336,6 +338,8 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams {{^wildcard}} } {{/wildcard}} + {{/is2xx}} + {{/is1xx}} {{/dataType}} {{/responses}} return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr diff --git a/samples/client/petstore/go-experimental/go-petstore/api_another_fake.go b/samples/client/petstore/go-experimental/go-petstore/api_another_fake.go index f58c0d405f35..486ec52d3e3b 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_another_fake.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_another_fake.go @@ -118,15 +118,6 @@ func (r apiCall123TestSpecialTagsRequest) Execute() (Client, *_nethttp.Response, body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go-experimental/go-petstore/api_fake.go b/samples/client/petstore/go-experimental/go-petstore/api_fake.go index 6a39cfa04ce1..2466fa119afc 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_fake.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_fake.go @@ -216,15 +216,6 @@ func (r apiFakeOuterBooleanSerializeRequest) Execute() (bool, *_nethttp.Response body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v bool - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -329,15 +320,6 @@ func (r apiFakeOuterCompositeSerializeRequest) Execute() (OuterComposite, *_neth body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v OuterComposite - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -442,15 +424,6 @@ func (r apiFakeOuterNumberSerializeRequest) Execute() (float32, *_nethttp.Respon body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v float32 - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -555,15 +528,6 @@ func (r apiFakeOuterStringSerializeRequest) Execute() (string, *_nethttp.Respons body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v string - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -880,15 +844,6 @@ func (r apiTestClientModelRequest) Execute() (Client, *_nethttp.Response, error) body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go b/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go index e8d6b3687975..070e9c3294f5 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go @@ -132,15 +132,6 @@ func (r apiTestClassnameRequest) Execute() (Client, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go-experimental/go-petstore/api_pet.go b/samples/client/petstore/go-experimental/go-petstore/api_pet.go index 94f6e4fa9d8d..23fceb74703d 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_pet.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_pet.go @@ -317,16 +317,6 @@ func (r apiFindPetsByStatusRequest) Execute() ([]Pet, *_nethttp.Response, error) body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v []Pet - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -434,16 +424,6 @@ func (r apiFindPetsByTagsRequest) Execute() ([]Pet, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v []Pet - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -559,16 +539,6 @@ func (r apiGetPetByIdRequest) Execute() (Pet, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Pet - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -902,15 +872,6 @@ func (r apiUploadFileRequest) Execute() (ApiResponse, *_nethttp.Response, error) body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v ApiResponse - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -1038,15 +999,6 @@ func (r apiUploadFileWithRequiredFileRequest) Execute() (ApiResponse, *_nethttp. body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v ApiResponse - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go-experimental/go-petstore/api_store.go b/samples/client/petstore/go-experimental/go-petstore/api_store.go index cea4e105c204..8aa77c5689d7 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_store.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_store.go @@ -213,15 +213,6 @@ func (r apiGetInventoryRequest) Execute() (map[string]int32, *_nethttp.Response, body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v map[string]int32 - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -329,16 +320,6 @@ func (r apiGetOrderByIdRequest) Execute() (Order, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Order - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -446,16 +427,6 @@ func (r apiPlaceOrderRequest) Execute() (Order, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Order - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go-experimental/go-petstore/api_user.go b/samples/client/petstore/go-experimental/go-petstore/api_user.go index 1af43a5acb9b..899dbb68b3f1 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_user.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_user.go @@ -498,16 +498,6 @@ func (r apiGetUserByNameRequest) Execute() (User, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v User - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -625,16 +615,6 @@ func (r apiLoginUserRequest) Execute() (string, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v string - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go/go-petstore/api_another_fake.go b/samples/client/petstore/go/go-petstore/api_another_fake.go index 44a84210ab25..0f39ec09f580 100644 --- a/samples/client/petstore/go/go-petstore/api_another_fake.go +++ b/samples/client/petstore/go/go-petstore/api_another_fake.go @@ -87,15 +87,6 @@ func (a *AnotherFakeApiService) Call123TestSpecialTags(ctx _context.Context, bod body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go/go-petstore/api_fake.go b/samples/client/petstore/go/go-petstore/api_fake.go index 61f9d2ed9ec5..ac3402fe4e4a 100644 --- a/samples/client/petstore/go/go-petstore/api_fake.go +++ b/samples/client/petstore/go/go-petstore/api_fake.go @@ -166,15 +166,6 @@ func (a *FakeApiService) FakeOuterBooleanSerialize(ctx _context.Context, localVa body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v bool - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -266,15 +257,6 @@ func (a *FakeApiService) FakeOuterCompositeSerialize(ctx _context.Context, local body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v OuterComposite - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -362,15 +344,6 @@ func (a *FakeApiService) FakeOuterNumberSerialize(ctx _context.Context, localVar body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v float32 - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -458,15 +431,6 @@ func (a *FakeApiService) FakeOuterStringSerialize(ctx _context.Context, localVar body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v string - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -680,15 +644,6 @@ func (a *FakeApiService) TestClientModel(ctx _context.Context, body Client) (Cli body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go/go-petstore/api_fake_classname_tags123.go b/samples/client/petstore/go/go-petstore/api_fake_classname_tags123.go index 7bd5e4b54e38..30a0fc5b514f 100644 --- a/samples/client/petstore/go/go-petstore/api_fake_classname_tags123.go +++ b/samples/client/petstore/go/go-petstore/api_fake_classname_tags123.go @@ -99,15 +99,6 @@ func (a *FakeClassnameTags123ApiService) TestClassname(ctx _context.Context, bod body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go/go-petstore/api_pet.go b/samples/client/petstore/go/go-petstore/api_pet.go index 6aea88752101..6f7892f21879 100644 --- a/samples/client/petstore/go/go-petstore/api_pet.go +++ b/samples/client/petstore/go/go-petstore/api_pet.go @@ -231,16 +231,6 @@ func (a *PetApiService) FindPetsByStatus(ctx _context.Context, status []string) body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v []Pet - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -318,16 +308,6 @@ func (a *PetApiService) FindPetsByTags(ctx _context.Context, tags []string) ([]P body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v []Pet - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -418,16 +398,6 @@ func (a *PetApiService) GetPetById(ctx _context.Context, petId int64) (Pet, *_ne body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Pet - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -679,15 +649,6 @@ func (a *PetApiService) UploadFile(ctx _context.Context, petId int64, localVarOp body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v ApiResponse - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -784,15 +745,6 @@ func (a *PetApiService) UploadFileWithRequiredFile(ctx _context.Context, petId i body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v ApiResponse - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go/go-petstore/api_store.go b/samples/client/petstore/go/go-petstore/api_store.go index a480157234a1..c061e263fd81 100644 --- a/samples/client/petstore/go/go-petstore/api_store.go +++ b/samples/client/petstore/go/go-petstore/api_store.go @@ -164,15 +164,6 @@ func (a *StoreApiService) GetInventory(ctx _context.Context) (map[string]int32, body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v map[string]int32 - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -257,16 +248,6 @@ func (a *StoreApiService) GetOrderById(ctx _context.Context, orderId int64) (Ord body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Order - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -344,16 +325,6 @@ func (a *StoreApiService) PlaceOrder(ctx _context.Context, body Order) (Order, * body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Order - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go/go-petstore/api_user.go b/samples/client/petstore/go/go-petstore/api_user.go index 154fc0962da3..6388ba4c3385 100644 --- a/samples/client/petstore/go/go-petstore/api_user.go +++ b/samples/client/petstore/go/go-petstore/api_user.go @@ -353,16 +353,6 @@ func (a *UserApiService) GetUserByName(ctx _context.Context, username string) (U body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v User - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -441,16 +431,6 @@ func (a *UserApiService) LoginUser(ctx _context.Context, username string, passwo body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v string - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_another_fake.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_another_fake.go index c9d4a11585e5..23be2a656db9 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_another_fake.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_another_fake.go @@ -118,15 +118,6 @@ func (r apiCall123TestSpecialTagsRequest) Execute() (Client, *_nethttp.Response, body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake.go index a0fd91dcc8db..25f70dafb543 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake.go @@ -108,15 +108,6 @@ func (r apiFakeHealthGetRequest) Execute() (HealthCheckResult, *_nethttp.Respons body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v HealthCheckResult - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -221,15 +212,6 @@ func (r apiFakeOuterBooleanSerializeRequest) Execute() (bool, *_nethttp.Response body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v bool - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -334,15 +316,6 @@ func (r apiFakeOuterCompositeSerializeRequest) Execute() (OuterComposite, *_neth body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v OuterComposite - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -447,15 +420,6 @@ func (r apiFakeOuterNumberSerializeRequest) Execute() (float32, *_nethttp.Respon body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v float32 - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -560,15 +524,6 @@ func (r apiFakeOuterStringSerializeRequest) Execute() (string, *_nethttp.Respons body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v string - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -885,15 +840,6 @@ func (r apiTestClientModelRequest) Execute() (Client, *_nethttp.Response, error) body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go index aa8378a85e42..04ba7468f354 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go @@ -132,15 +132,6 @@ func (r apiTestClassnameRequest) Execute() (Client, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go index 664c9f0df4c9..4031a35683a6 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go @@ -317,16 +317,6 @@ func (r apiFindPetsByStatusRequest) Execute() ([]Pet, *_nethttp.Response, error) body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v []Pet - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -434,16 +424,6 @@ func (r apiFindPetsByTagsRequest) Execute() ([]Pet, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v []Pet - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -559,16 +539,6 @@ func (r apiGetPetByIdRequest) Execute() (Pet, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Pet - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -902,15 +872,6 @@ func (r apiUploadFileRequest) Execute() (ApiResponse, *_nethttp.Response, error) body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v ApiResponse - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -1038,15 +999,6 @@ func (r apiUploadFileWithRequiredFileRequest) Execute() (ApiResponse, *_nethttp. body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v ApiResponse - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go index 3b29aa697304..b953699dcc97 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go @@ -213,15 +213,6 @@ func (r apiGetInventoryRequest) Execute() (map[string]int32, *_nethttp.Response, body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v map[string]int32 - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -329,16 +320,6 @@ func (r apiGetOrderByIdRequest) Execute() (Order, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Order - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -446,16 +427,6 @@ func (r apiPlaceOrderRequest) Execute() (Order, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Order - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_user.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_user.go index e877bf7d2651..aac20879b628 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_user.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_user.go @@ -498,16 +498,6 @@ func (r apiGetUserByNameRequest) Execute() (User, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v User - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -625,16 +615,6 @@ func (r apiLoginUserRequest) Execute() (string, *_nethttp.Response, error) { body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v string - err = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/http_signature_test.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/http_signature_test.go new file mode 100644 index 000000000000..f5f08b2ae6ef --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/http_signature_test.go @@ -0,0 +1,728 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstore + +import ( + "bytes" + "context" + "crypto" + "crypto/ecdsa" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/asn1" + "encoding/base64" + "encoding/pem" + "fmt" + "io/ioutil" + "math/big" + "net/http" + "net/http/httputil" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + "time" +) + +// Test RSA private key as published in Appendix C 'Test Values' of +// https://www.ietf.org/id/draft-cavage-http-signatures-12.txt +const rsaTestPrivateKey string = `-----BEGIN RSA PRIVATE KEY----- +MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF +NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F +UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB +AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA +QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK +kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg +f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u +412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc +mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 +kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA +gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW +G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI +7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== +-----END RSA PRIVATE KEY-----` + +func writeTestRsaPemKey(t *testing.T, filePath string) { + err := ioutil.WriteFile(filePath, []byte(rsaTestPrivateKey), 0644) + if err != nil { + t.Fatalf("Error writing private key: %v", err) + } +} + +type keyFormat int // The serialization format of the private key. + +const ( + keyFormatPem keyFormat = iota // Private key is serialized in PEM format. + keyFormatPkcs8Pem // Private key is serialized as PKCS#8 encoded in PEM format. + keyFormatPkcs8Der // Private key is serialized as PKCS#8 encoded in DER format. +) + +func writeRandomTestRsaPemKey(t *testing.T, filePath string, bits int, format keyFormat, passphrase string, alg *x509.PEMCipher) { + key, err := rsa.GenerateKey(rand.Reader, bits) + if err != nil { + t.Fatalf("Error generating RSA private key file: %v", err) + } + var outFile *os.File + outFile, err = os.Create(filePath) + if err != nil { + t.Fatalf("Error creating RSA private key file: %v", err) + } + defer outFile.Close() + var privKeyBytes []byte + switch format { + case keyFormatPem: + if passphrase != "" { + t.Fatalf("Encrypting PKCS#1-encoded private key with passphrase is not supported") + } + privKeyBytes = x509.MarshalPKCS1PrivateKey(key) + case keyFormatPkcs8Pem: + privKeyBytes, err = x509.MarshalPKCS8PrivateKey(key) + if err != nil { + t.Fatalf("Error writing private key: %v", err) + } + case keyFormatPkcs8Der: + if passphrase != "" { + t.Fatalf("Encrypting DER-encoded private key with passphrase is not supported") + } + privKeyBytes, err = x509.MarshalPKCS8PrivateKey(key) + if err != nil { + t.Fatalf("Error writing private key: %v", err) + } + _, err = outFile.Write(privKeyBytes) + if err != nil { + t.Fatalf("Error writing DER-encoded private key: %v", err) + } + default: + t.Fatalf("Unsupported key format: %v", format) + } + + switch format { + case keyFormatPem, keyFormatPkcs8Der: + var pemBlock *pem.Block + if passphrase == "" { + pemBlock = &pem.Block{ + Type: "RSA PRIVATE KEY", + Bytes: privKeyBytes, + } + } else { + pemBlock, err = x509.EncryptPEMBlock(rand.Reader, "ENCRYPTED PRIVATE KEY", privKeyBytes, []byte(passphrase), *alg) + if err != nil { + t.Fatalf("Error encoding RSA private key: %v", err) + } + } + err = pem.Encode(outFile, pemBlock) + if err != nil { + t.Fatalf("Error encoding RSA private key: %v", err) + } + } + fmt.Printf("Wrote private key '%s'\n", filePath) +} + +/* +Commented out because OpenAPITools is configured to use golang 1.8 at build time +x509.MarshalPKCS8PrivateKey is not present. +func writeRandomTestEcdsaPemKey(t *testing.T, filePath string) { + key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) + if err != nil { + t.Fatalf("Error generating ECDSA private key file: %v", err) + } + var outFile *os.File + outFile, err = os.Create(filePath) + if err != nil { + t.Fatalf("Error creating ECDSA private key file: %v", err) + } + defer outFile.Close() + + var keybytes []byte + keybytes, err = x509.MarshalPKCS8PrivateKey(key) + if err != nil { + t.Fatalf("Error marshaling ECDSA private key: %v", err) + } + var privateKey = &pem.Block{ + Type: "PRIVATE KEY", + Bytes: keybytes, + } + + err = pem.Encode(outFile, privateKey) + if err != nil { + t.Fatalf("Error encoding ECDSA private key: %v", err) + } +} +*/ + +// TestHttpSignaturePrivateKeys creates private keys of various sizes, serialization format, +// clear-text and password encrypted. +// Test unmarshaling of the private key. +func TestHttpSignaturePrivateKeys(t *testing.T) { + var err error + var dir string + dir, err = ioutil.TempDir("", "go-http-sign") + if err != nil { + t.Fatalf("Failed to create temporary directory") + } + defer os.RemoveAll(dir) + + pemCiphers := []x509.PEMCipher{ + x509.PEMCipherDES, + x509.PEMCipher3DES, + x509.PEMCipherAES128, + x509.PEMCipherAES192, + x509.PEMCipherAES256, + } + // Test RSA private keys with various key lengths. + for _, bits := range []int{1024, 2048, 3072, 4096} { + + for _, format := range []keyFormat{keyFormatPem, keyFormatPkcs8Pem, keyFormatPkcs8Der} { + // Generate test private key. + var privateKeyPath string + switch format { + case keyFormatPem, keyFormatPkcs8Pem: + privateKeyPath = "privatekey.pem" + case keyFormatPkcs8Der: + privateKeyPath = "privatekey.der" + default: + t.Fatalf("Unsupported private key format: %v", format) + } + privateKeyPath = filepath.Join(dir, privateKeyPath) + // Generate keys in PEM format. + writeRandomTestRsaPemKey(t, privateKeyPath, bits, format, "", nil) + + authConfig := HttpSignatureAuth{ + KeyId: "my-key-id", + PrivateKeyPath: privateKeyPath, + Passphrase: "", + SigningScheme: "hs2019", + SignedHeaders: []string{"Content-Type"}, + } + + // Create a context with the HTTP signature configuration parameters. + _, err = authConfig.ContextWithValue(context.Background()) + if err != nil { + t.Fatalf("Error loading private key '%s': %v", privateKeyPath, err) + } + + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + PrivateKeyPath: privateKeyPath, + Passphrase: "my-secret-passphrase", + SigningScheme: "hs2019", + SignedHeaders: []string{"Content-Type"}, + } + switch format { + case keyFormatPem: + // Do nothing. Keys cannot be encrypted when using PKCS#1. + case keyFormatPkcs8Pem: + for _, alg := range pemCiphers { + writeRandomTestRsaPemKey(t, privateKeyPath, bits, format, authConfig.Passphrase, &alg) + _, err := authConfig.ContextWithValue(context.Background()) + if err != nil { + t.Fatalf("Error loading private key '%s': %v", privateKeyPath, err) + } + } + } + } + } + + /* + Unfortunately, currently the build environment for OpenAPITools is using an old version + of golang that does not support ECDSA keys. + { + privateKeyPath := "privatekey.pem" + authConfig := HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: "hs2019", + SignedHeaders: []string{"Content-Type"}, + } + // Generate test private key. + writeRandomTestEcdsaPemKey(t, privateKeyPath) + err := authConfig.LoadPrivateKey(privateKeyPath) + if err != nil { + t.Fatalf("Error loading private key '%s': %v", privateKeyPath, err) + } + } + */ +} + +const testHost = "petstore.swagger.io:80" +const testScheme = "http" + +func executeHttpSignatureAuth(t *testing.T, authConfig *HttpSignatureAuth, expectSuccess bool) string { + var err error + var dir string + dir, err = ioutil.TempDir("", "go-http-sign") + if err != nil { + t.Fatalf("Failed to create temporary directory") + } + defer os.RemoveAll(dir) + + cfg := NewConfiguration() + cfg.AddDefaultHeader("testheader", "testvalue") + cfg.AddDefaultHeader("Content-Type", "application/json") + cfg.Host = testHost + cfg.Scheme = testScheme + apiClient := NewAPIClient(cfg) + + privateKeyPath := filepath.Join(dir, "rsa.pem") + writeTestRsaPemKey(t, privateKeyPath) + authConfig.PrivateKeyPath = privateKeyPath + var authCtx context.Context + authCtx, err = authConfig.ContextWithValue(context.Background()) + if expectSuccess && err != nil { + t.Fatalf("Error validating HTTP signature configuration: %v", err) + } + if !expectSuccess && err != nil { + // Do not continue. Error is expected. + return "" + } + newPet := (Pet{Id: PtrInt64(12992), Name: "gopher", + PhotoUrls: []string{"http://1.com", "http://2.com"}, + Status: PtrString("pending"), + Tags: &[]Tag{Tag{Id: PtrInt64(1), Name: PtrString("tag2")}}}) + + fmt.Printf("Request with HTTP signature. Scheme: '%s'. Algorithm: '%s'. MaxValidity: %v. Headers: '%v'\n", + authConfig.SigningScheme, authConfig.SigningAlgorithm, authConfig.SignatureMaxValidity, authConfig.SignedHeaders) + + r, err2 := apiClient.PetApi.AddPet(authCtx).Pet(newPet).Execute() + if expectSuccess && err2 != nil { + t.Fatalf("Error while adding pet: %v", err2) + } + if !expectSuccess { + if err2 == nil { + t.Fatalf("Error was expected, but no error was generated") + } else { + // Do not continue. Error is expected. + return "" + } + } + if r.StatusCode != 200 { + t.Log(r) + } + + _, r, err = apiClient.PetApi.GetPetById(authCtx, 12992).Execute() + if expectSuccess && err != nil { + t.Fatalf("Error while deleting pet by id: %v", err) + } + + // The request should look like this: + // + // GET /v2/pet/12992 HTTP/1.1 + // Host: petstore.swagger.io:80 + // Accept: application/json + // Authorization: Signature keyId="my-key-id",algorithm="hs2019",created=1579033245,headers="(request-target) date host digest content-type",signature="RMJZjVVxzlH02wlxiQgUYDe4QxZaI5IJNIfB2BK8Dhbv3WQ2gw0xyqC+5HiKUmT/cfchhhkUNNsUtiVRnjZmFwtSfYxHfiQvH3KWXlLCMwKGNQC3YzD9lnoWdx0pA5Kxbr0/ygmr3+lTyuN2PJg4IS7Ji/AaKAqIZx7RsHS8Bxw=" + // Date: Tue, 14 Jan 2020 06:41:22 GMT + // Digest: SHA-512=z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXcg/SpIdNs6c5H0NE8XYXysP+DGNKHfuwvY7kxvUdBeoGlODJ6+SfaPg== + // Testheader: testvalue + // User-Agent: OpenAPI-Generator/1.0.0/go + reqb, _ := httputil.DumpRequest(r.Request, true) + reqt := (string)(reqb) + fmt.Printf("REQUEST:\n%v\n", reqt) + var sb bytes.Buffer + fmt.Fprintf(&sb, `Signature keyId="%s",algorithm="%s",`, + authConfig.KeyId, authConfig.SigningScheme) + if len(authConfig.SignedHeaders) == 0 { + fmt.Fprintf(&sb, `created=[0-9]+,`) + } else { + for _, header := range authConfig.SignedHeaders { + header = strings.ToLower(header) + if header == HttpSignatureParameterCreated { + fmt.Fprintf(&sb, `created=[0-9]+,`) + } + if header == HttpSignatureParameterExpires { + fmt.Fprintf(&sb, `expires=[0-9]+\.[0-9]{3},`) + } + } + } + fmt.Fprintf(&sb, `headers="`) + for i, header := range authConfig.SignedHeaders { + header = strings.ToLower(header) + if i > 0 { + fmt.Fprintf(&sb, " ") + } + fmt.Fprintf(&sb, regexp.QuoteMeta(header)) + switch header { + case "date": + if !strings.Contains(reqt, "Date: ") { + t.Errorf("Date header is incorrect") + } + case "digest": + var prefix string + switch authConfig.SigningScheme { + case HttpSigningSchemeRsaSha256: + prefix = "SHA-256=" + default: + prefix = "SHA-512=" + } + if !strings.Contains(reqt, fmt.Sprintf("Digest: %s", prefix)) { + t.Errorf("Digest header is incorrect") + } + } + } + if len(authConfig.SignedHeaders) == 0 { + fmt.Fprintf(&sb, regexp.QuoteMeta(HttpSignatureParameterCreated)) + } + fmt.Fprintf(&sb, `",signature="[a-zA-Z0-9+/]+="`) + re := regexp.MustCompile(sb.String()) + actual := r.Request.Header.Get("Authorization") + if !re.MatchString(actual) { + t.Errorf("Authorization header is incorrect. Expected regex\n'%s'\nbut got\n'%s'", sb.String(), actual) + } + + validateHttpAuthorizationSignature(t, authConfig, r) + return r.Request.Header.Get("Authorization") +} + +var ( + // signatureRe is a regular expression to capture the fields from the signature. + signatureRe = regexp.MustCompile( + `Signature keyId="(?P[^"]+)",algorithm="(?P[^"]+)"` + + `(,created=(?P[0-9]+))?(,expires=(?P[0-9.]+))?,headers="(?P[^"]+)",signature="(?P[^"]+)"`) +) + +// validateHttpAuthorizationSignature validates the HTTP signature in the HTTP request. +// The signature verification would normally be done by the server. +// Note: this is NOT a complete implementation of the HTTP signature validation. This code is for unit test purpose, do not use +// it for server side implementation. +// In particular, this code does not validate the calculation of the HTTP body digest. +func validateHttpAuthorizationSignature(t *testing.T, authConfig *HttpSignatureAuth, r *http.Response) { + authHeader := r.Request.Header.Get("Authorization") + match := signatureRe.FindStringSubmatch(authHeader) + if len(match) < 3 { + t.Fatalf("Unexpected Authorization header: %s", authHeader) + } + result := make(map[string]string) + for i, name := range signatureRe.SubexpNames() { + if i != 0 && name != "" { + result[name] = match[i] + } + } + b64signature := result["signature"] + fmt.Printf("Algorithm: '%s' Headers: '%s' b64signature: '%s'\n", result["algorithm"], result["headers"], b64signature) + var sb bytes.Buffer + fmt.Fprintf(&sb, "%s %s", strings.ToLower(r.Request.Method), r.Request.URL.EscapedPath()) + if r.Request.URL.RawQuery != "" { + // The ":path" pseudo-header field includes the path and query parts + // of the target URI (the "path-absolute" production and optionally a + // '?' character followed by the "query" production (see Sections 3.3 + // and 3.4 of [RFC3986] + fmt.Fprintf(&sb, "?%s", r.Request.URL.RawQuery) + } + requestTarget := sb.String() + + var signedHeaderKvs []string + signedHeaders := strings.Split(result["headers"], " ") + for _, h := range signedHeaders { + var value string + switch h { + case HttpSignatureParameterRequestTarget: + value = requestTarget + case HttpSignatureParameterCreated: + value = result["created"] + case HttpSignatureParameterExpires: + value = result["expires"] + default: + value = r.Request.Header.Get(h) + } + signedHeaderKvs = append(signedHeaderKvs, fmt.Sprintf("%s: %s", h, value)) + } + stringToSign := strings.Join(signedHeaderKvs, "\n") + + var h crypto.Hash + switch result["algorithm"] { + case HttpSigningSchemeHs2019, HttpSigningSchemeRsaSha512: + h = crypto.SHA512 + case HttpSigningSchemeRsaSha256: + h = crypto.SHA256 + default: + t.Fatalf("Unexpected signing algorithm: %s", result["algorithm"]) + } + msgHash := h.New() + if _, err := msgHash.Write([]byte(stringToSign)); err != nil { + t.Fatalf("Unable to compute hash: %v", err) + } + d := msgHash.Sum(nil) + var pub crypto.PublicKey + var err error + if pub, err = authConfig.GetPublicKey(); err != nil { + t.Fatalf("Unable to get public key: %v", err) + } + if pub == nil { + t.Fatalf("Public key is nil") + } + var signature []byte + if signature, err = base64.StdEncoding.DecodeString(b64signature); err != nil { + t.Fatalf("Failed to decode signature: %v", err) + } + switch publicKey := pub.(type) { + case *rsa.PublicKey: + // It could be PKCS1v15 or PSS signature + var errPKCS1v15, errPSS error + // In a server-side implementation, we wouldn't try to validate both signatures. The specific + // signature algorithm would be derived from the key id. But here we just want to validate for unit test purpose. + errPKCS1v15 = rsa.VerifyPKCS1v15(publicKey, h, d, signature) + errPSS = rsa.VerifyPSS(publicKey, h, d, signature, nil) + if errPKCS1v15 != nil && errPSS != nil { + t.Fatalf("RSA Signature verification failed: %v. %v", errPKCS1v15, errPSS) + } + case *ecdsa.PublicKey: + type ecdsaSignature struct { + R, S *big.Int + } + var lEcdsa ecdsaSignature + if _, err = asn1.Unmarshal(signature, &lEcdsa); err != nil { + t.Fatalf("Unable to parse ECDSA signature: %v", err) + } + if !ecdsa.Verify(publicKey, d, lEcdsa.R, lEcdsa.S) { + t.Fatalf("ECDSA Signature verification failed") + } + default: + t.Fatalf("Unsupported public key: %T", pub) + } +} + +func TestHttpSignatureAuth(t *testing.T) { + // Test with 'hs2019' signature scheme, and default signature algorithm (RSA SSA PKCS1.5) + authConfig := HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: HttpSigningSchemeHs2019, + SignedHeaders: []string{ + HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. + HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. + "Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number. + "Date", // The date and time at which the message was originated. + "Content-Type", // The Media type of the body of the request. + "Digest", // A cryptographic digest of the request body. + }, + } + executeHttpSignatureAuth(t, &authConfig, true) + + // Test with duplicate headers. This is invalid and should be rejected. + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: HttpSigningSchemeHs2019, + SignedHeaders: []string{"Host", "Date", "Host"}, + } + executeHttpSignatureAuth(t, &authConfig, false) + + // Test with non-existent header. This is invalid and should be rejected. + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: HttpSigningSchemeHs2019, + SignedHeaders: []string{"Host", "Date", "Garbage-HeaderDoesNotExist"}, + } + executeHttpSignatureAuth(t, &authConfig, false) + + // Test with 'Authorization' header in the signed headers. This is invalid and should be rejected. + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: HttpSigningSchemeHs2019, + SignedHeaders: []string{"Host", "Authorization"}, + } + executeHttpSignatureAuth(t, &authConfig, false) + + // Specify signature max validity, but '(expires)' parameter is missing. This should cause an error. + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: HttpSigningSchemeHs2019, + SignatureMaxValidity: 7 * time.Minute, + } + executeHttpSignatureAuth(t, &authConfig, false) + + // Specify invalid signature max validity. This should cause an error. + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: HttpSigningSchemeHs2019, + SignatureMaxValidity: -3 * time.Minute, + } + executeHttpSignatureAuth(t, &authConfig, false) + + // Specify signature max validity and '(expires)' parameter. + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: HttpSigningSchemeHs2019, + SignatureMaxValidity: time.Minute, + SignedHeaders: []string{ + HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. + HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. + HttpSignatureParameterExpires, // Time when signature expires. + }, + } + executeHttpSignatureAuth(t, &authConfig, true) + + // Specify '(expires)' parameter but no signature max validity. + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: HttpSigningSchemeHs2019, + SignedHeaders: []string{ + HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. + HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. + HttpSignatureParameterExpires, // Time when signature expires. + }, + } + executeHttpSignatureAuth(t, &authConfig, false) + + // Test with empty signed headers. The client should automatically add the "(created)" parameter by default. + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: HttpSigningSchemeHs2019, + SignedHeaders: []string{}, + } + executeHttpSignatureAuth(t, &authConfig, true) + + // Test with deprecated RSA-SHA512, some servers may still support it. + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: HttpSigningSchemeRsaSha512, + SignedHeaders: []string{ + HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. + HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. + "Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number. + "Date", // The date and time at which the message was originated. + "Content-Type", // The Media type of the body of the request. + "Digest", // A cryptographic digest of the request body. + }, + } + executeHttpSignatureAuth(t, &authConfig, true) + + // Test with deprecated RSA-SHA256, some servers may still support it. + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: HttpSigningSchemeRsaSha256, + SignedHeaders: []string{ + HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. + HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. + "Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number. + "Date", // The date and time at which the message was originated. + "Content-Type", // The Media type of the body of the request. + "Digest", // A cryptographic digest of the request body. + }, + } + executeHttpSignatureAuth(t, &authConfig, true) + + // Test with headers without date. This makes it possible to get a fixed signature, used for unit test purpose. + // This should not be used in production code as it could potentially allow replay attacks. + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: HttpSigningSchemeHs2019, + SigningAlgorithm: HttpSigningAlgorithmRsaPKCS1v15, + SignedHeaders: []string{ + HttpSignatureParameterRequestTarget, + "Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number. + "Content-Type", // The Media type of the body of the request. + "Digest", // A cryptographic digest of the request body. + }, + } + authorizationHeaderValue := executeHttpSignatureAuth(t, &authConfig, true) + expectedSignature := "sXE2MDeW8os6ywv1oUWaFEPFcSPCEb/msQ/NZGKNA9Emm/e42axaAPojzfkZ9Hacyw/iS/5nH4YIkczMgXu3z5fAwFjumxtf3OxbqvUcQ80wvw2/7B5aQmsF6ZwrCFHZ+L/cj9/bg7L1EGUGtdyDzoRKti4zf9QF/03OsP7QljI=" + expectedAuthorizationHeader := fmt.Sprintf( + `Signature keyId="my-key-id",`+ + `algorithm="hs2019",headers="(request-target) host content-type digest",`+ + `signature="%s"`, expectedSignature) + if authorizationHeaderValue != expectedAuthorizationHeader { + t.Errorf("Authorization header value is incorrect. Got\n'%s'\nbut expected\n'%s'", authorizationHeaderValue, expectedAuthorizationHeader) + } + + // Test with PSS signature. The PSS signature creates a new signature every time it is invoked. + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + SigningScheme: HttpSigningSchemeHs2019, + SigningAlgorithm: HttpSigningAlgorithmRsaPSS, + SignedHeaders: []string{ + HttpSignatureParameterRequestTarget, + "Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number. + "Content-Type", // The Media type of the body of the request. + "Digest", // A cryptographic digest of the request body. + }, + } + authorizationHeaderValue = executeHttpSignatureAuth(t, &authConfig, true) + expectedSignature = `[a-zA-Z0-9+/]+=` + expectedAuthorizationHeader = fmt.Sprintf( + `Signature keyId="my-key-id",`+ + `algorithm="hs2019",headers="\(request-target\) host content-type digest",`+ + `signature="%s"`, expectedSignature) + re := regexp.MustCompile(expectedAuthorizationHeader) + if !re.MatchString(authorizationHeaderValue) { + t.Errorf("Authorization header value is incorrect. Got\n'%s'\nbut expected\n'%s'", authorizationHeaderValue, expectedAuthorizationHeader) + } +} + +func TestInvalidHttpSignatureConfiguration(t *testing.T) { + var err error + var authConfig HttpSignatureAuth + + authConfig = HttpSignatureAuth{ + } + _, err = authConfig.ContextWithValue(context.Background()) + if err == nil || !strings.Contains(err.Error(), "Key ID must be specified") { + t.Fatalf("Invalid configuration: %v", err) + } + + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + } + _, err = authConfig.ContextWithValue(context.Background()) + if err == nil || !strings.Contains(err.Error(), "Private key path must be specified") { + t.Fatalf("Invalid configuration: %v", err) + } + + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + PrivateKeyPath: "test.pem", + } + _, err = authConfig.ContextWithValue(context.Background()) + if err == nil || !strings.Contains(err.Error(), "Invalid signing scheme") { + t.Fatalf("Invalid configuration: %v", err) + } + + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + PrivateKeyPath: "test.pem", + SigningScheme: "garbage", + } + _, err = authConfig.ContextWithValue(context.Background()) + if err == nil || !strings.Contains(err.Error(), "Invalid signing scheme") { + t.Fatalf("Invalid configuration: %v", err) + } + + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + PrivateKeyPath: "test.pem", + SigningScheme: HttpSigningSchemeHs2019, + SignedHeaders: []string{"foo", "bar", "foo"}, + } + _, err = authConfig.ContextWithValue(context.Background()) + if err == nil || !strings.Contains(err.Error(), "cannot have duplicate names") { + t.Fatalf("Invalid configuration: %v", err) + } + + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + PrivateKeyPath: "test.pem", + SigningScheme: HttpSigningSchemeHs2019, + SignedHeaders: []string{"foo", "bar", "Authorization"}, + } + _, err = authConfig.ContextWithValue(context.Background()) + if err == nil || !strings.Contains(err.Error(), "Signed headers cannot include the 'Authorization' header") { + t.Fatalf("Invalid configuration: %v", err) + } + + authConfig = HttpSignatureAuth{ + KeyId: "my-key-id", + PrivateKeyPath: "test.pem", + SigningScheme: HttpSigningSchemeHs2019, + SignedHeaders: []string{"foo", "bar"}, + SignatureMaxValidity: -7 * time.Minute, + } + _, err = authConfig.ContextWithValue(context.Background()) + if err == nil || !strings.Contains(err.Error(), "Signature max validity must be a positive value") { + t.Fatalf("Invalid configuration: %v", err) + } +} \ No newline at end of file diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_another_fake.go b/samples/openapi3/client/petstore/go/go-petstore/api_another_fake.go index 9340243f47d3..faf303d47c7c 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_another_fake.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_another_fake.go @@ -87,15 +87,6 @@ func (a *AnotherFakeApiService) Call123TestSpecialTags(ctx _context.Context, cli body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_fake.go b/samples/openapi3/client/petstore/go/go-petstore/api_fake.go index 387dda7fee6e..c47eeaebb186 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_fake.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_fake.go @@ -86,15 +86,6 @@ func (a *FakeApiService) FakeHealthGet(ctx _context.Context) (HealthCheckResult, body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v HealthCheckResult - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -182,15 +173,6 @@ func (a *FakeApiService) FakeOuterBooleanSerialize(ctx _context.Context, localVa body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v bool - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -282,15 +264,6 @@ func (a *FakeApiService) FakeOuterCompositeSerialize(ctx _context.Context, local body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v OuterComposite - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -378,15 +351,6 @@ func (a *FakeApiService) FakeOuterNumberSerialize(ctx _context.Context, localVar body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v float32 - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -474,15 +438,6 @@ func (a *FakeApiService) FakeOuterStringSerialize(ctx _context.Context, localVar body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v string - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -696,15 +651,6 @@ func (a *FakeApiService) TestClientModel(ctx _context.Context, client Client) (C body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_fake_classname_tags123.go b/samples/openapi3/client/petstore/go/go-petstore/api_fake_classname_tags123.go index c27046f4ab43..c4fa14dcde36 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_fake_classname_tags123.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_fake_classname_tags123.go @@ -99,15 +99,6 @@ func (a *FakeClassnameTags123ApiService) TestClassname(ctx _context.Context, cli body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_pet.go b/samples/openapi3/client/petstore/go/go-petstore/api_pet.go index 948315ce4399..a494c12b5c45 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_pet.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_pet.go @@ -231,16 +231,6 @@ func (a *PetApiService) FindPetsByStatus(ctx _context.Context, status []string) body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v []Pet - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -318,16 +308,6 @@ func (a *PetApiService) FindPetsByTags(ctx _context.Context, tags []string) ([]P body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v []Pet - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -418,16 +398,6 @@ func (a *PetApiService) GetPetById(ctx _context.Context, petId int64) (Pet, *_ne body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Pet - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -679,15 +649,6 @@ func (a *PetApiService) UploadFile(ctx _context.Context, petId int64, localVarOp body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v ApiResponse - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -784,15 +745,6 @@ func (a *PetApiService) UploadFileWithRequiredFile(ctx _context.Context, petId i body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v ApiResponse - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_store.go b/samples/openapi3/client/petstore/go/go-petstore/api_store.go index 2ff59f98fedb..3f122ef01286 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_store.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_store.go @@ -164,15 +164,6 @@ func (a *StoreApiService) GetInventory(ctx _context.Context) (map[string]int32, body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v map[string]int32 - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -257,16 +248,6 @@ func (a *StoreApiService) GetOrderById(ctx _context.Context, orderId int64) (Ord body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Order - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -344,16 +325,6 @@ func (a *StoreApiService) PlaceOrder(ctx _context.Context, order Order) (Order, body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Order - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_user.go b/samples/openapi3/client/petstore/go/go-petstore/api_user.go index 83f8f02f52bb..9b2caa40deb9 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_user.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_user.go @@ -353,16 +353,6 @@ func (a *UserApiService) GetUserByName(ctx _context.Context, username string) (U body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v User - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -441,16 +431,6 @@ func (a *UserApiService) LoginUser(ctx _context.Context, username string, passwo body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v string - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } From 6a2ead15f1ad9cf163f915483f14a4bf9a760bab Mon Sep 17 00:00:00 2001 From: Slavek Kabrda Date: Tue, 17 Mar 2020 15:57:52 +0100 Subject: [PATCH 2/2] Properly regenerate all samples --- .../go-petstore-withXml/api_another_fake.go | 9 - .../go/go-petstore-withXml/api_fake.go | 45 -- .../api_fake_classname_tags123.go | 9 - .../go/go-petstore-withXml/api_pet.go | 48 -- .../go/go-petstore-withXml/api_store.go | 29 - .../go/go-petstore-withXml/api_user.go | 20 - .../go-petstore/http_signature_test.go | 728 ------------------ 7 files changed, 888 deletions(-) delete mode 100644 samples/openapi3/client/petstore/go-experimental/go-petstore/http_signature_test.go diff --git a/samples/client/petstore/go/go-petstore-withXml/api_another_fake.go b/samples/client/petstore/go/go-petstore-withXml/api_another_fake.go index dbb36217de0d..a0b8106196a6 100644 --- a/samples/client/petstore/go/go-petstore-withXml/api_another_fake.go +++ b/samples/client/petstore/go/go-petstore-withXml/api_another_fake.go @@ -88,15 +88,6 @@ func (a *AnotherFakeApiService) Call123TestSpecialTags(ctx _context.Context, bod body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go/go-petstore-withXml/api_fake.go b/samples/client/petstore/go/go-petstore-withXml/api_fake.go index bad36447bd8e..5d60b36436c9 100644 --- a/samples/client/petstore/go/go-petstore-withXml/api_fake.go +++ b/samples/client/petstore/go/go-petstore-withXml/api_fake.go @@ -167,15 +167,6 @@ func (a *FakeApiService) FakeOuterBooleanSerialize(ctx _context.Context, localVa body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v bool - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -267,15 +258,6 @@ func (a *FakeApiService) FakeOuterCompositeSerialize(ctx _context.Context, local body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v OuterComposite - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -363,15 +345,6 @@ func (a *FakeApiService) FakeOuterNumberSerialize(ctx _context.Context, localVar body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v float32 - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -459,15 +432,6 @@ func (a *FakeApiService) FakeOuterStringSerialize(ctx _context.Context, localVar body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v string - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -681,15 +645,6 @@ func (a *FakeApiService) TestClientModel(ctx _context.Context, body Client) (Cli body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go/go-petstore-withXml/api_fake_classname_tags123.go b/samples/client/petstore/go/go-petstore-withXml/api_fake_classname_tags123.go index b02c47d4c9d4..6284b28ee8de 100644 --- a/samples/client/petstore/go/go-petstore-withXml/api_fake_classname_tags123.go +++ b/samples/client/petstore/go/go-petstore-withXml/api_fake_classname_tags123.go @@ -100,15 +100,6 @@ func (a *FakeClassnameTags123ApiService) TestClassname(ctx _context.Context, bod body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Client - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go/go-petstore-withXml/api_pet.go b/samples/client/petstore/go/go-petstore-withXml/api_pet.go index 20a6c92965b6..d64b54c6c5b3 100644 --- a/samples/client/petstore/go/go-petstore-withXml/api_pet.go +++ b/samples/client/petstore/go/go-petstore-withXml/api_pet.go @@ -232,16 +232,6 @@ func (a *PetApiService) FindPetsByStatus(ctx _context.Context, status []string) body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v []Pet - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -319,16 +309,6 @@ func (a *PetApiService) FindPetsByTags(ctx _context.Context, tags []string) ([]P body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v []Pet - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -419,16 +399,6 @@ func (a *PetApiService) GetPetById(ctx _context.Context, petId int64) (Pet, *_ne body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Pet - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -680,15 +650,6 @@ func (a *PetApiService) UploadFile(ctx _context.Context, petId int64, localVarOp body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v ApiResponse - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -785,15 +746,6 @@ func (a *PetApiService) UploadFileWithRequiredFile(ctx _context.Context, petId i body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v ApiResponse - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go/go-petstore-withXml/api_store.go b/samples/client/petstore/go/go-petstore-withXml/api_store.go index 47faea8586b1..feab7bf82e2b 100644 --- a/samples/client/petstore/go/go-petstore-withXml/api_store.go +++ b/samples/client/petstore/go/go-petstore-withXml/api_store.go @@ -165,15 +165,6 @@ func (a *StoreApiService) GetInventory(ctx _context.Context) (map[string]int32, body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v map[string]int32 - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -258,16 +249,6 @@ func (a *StoreApiService) GetOrderById(ctx _context.Context, orderId int64) (Ord body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Order - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -345,16 +326,6 @@ func (a *StoreApiService) PlaceOrder(ctx _context.Context, body Order) (Order, * body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v Order - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/client/petstore/go/go-petstore-withXml/api_user.go b/samples/client/petstore/go/go-petstore-withXml/api_user.go index 56bd4d3fc193..924258a7148f 100644 --- a/samples/client/petstore/go/go-petstore-withXml/api_user.go +++ b/samples/client/petstore/go/go-petstore-withXml/api_user.go @@ -354,16 +354,6 @@ func (a *UserApiService) GetUserByName(ctx _context.Context, username string) (U body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v User - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } @@ -442,16 +432,6 @@ func (a *UserApiService) LoginUser(ctx _context.Context, username string, passwo body: localVarBody, error: localVarHTTPResponse.Status, } - if localVarHTTPResponse.StatusCode == 200 { - var v string - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHTTPResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHTTPResponse, newErr - } return localVarReturnValue, localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/http_signature_test.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/http_signature_test.go deleted file mode 100644 index f5f08b2ae6ef..000000000000 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/http_signature_test.go +++ /dev/null @@ -1,728 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * API version: 1.0.0 - * Generated by: OpenAPI Generator (https://openapi-generator.tech) - */ - -package petstore - -import ( - "bytes" - "context" - "crypto" - "crypto/ecdsa" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/asn1" - "encoding/base64" - "encoding/pem" - "fmt" - "io/ioutil" - "math/big" - "net/http" - "net/http/httputil" - "os" - "path/filepath" - "regexp" - "strings" - "testing" - "time" -) - -// Test RSA private key as published in Appendix C 'Test Values' of -// https://www.ietf.org/id/draft-cavage-http-signatures-12.txt -const rsaTestPrivateKey string = `-----BEGIN RSA PRIVATE KEY----- -MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF -NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F -UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB -AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA -QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK -kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg -f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u -412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc -mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 -kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA -gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW -G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI -7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== ------END RSA PRIVATE KEY-----` - -func writeTestRsaPemKey(t *testing.T, filePath string) { - err := ioutil.WriteFile(filePath, []byte(rsaTestPrivateKey), 0644) - if err != nil { - t.Fatalf("Error writing private key: %v", err) - } -} - -type keyFormat int // The serialization format of the private key. - -const ( - keyFormatPem keyFormat = iota // Private key is serialized in PEM format. - keyFormatPkcs8Pem // Private key is serialized as PKCS#8 encoded in PEM format. - keyFormatPkcs8Der // Private key is serialized as PKCS#8 encoded in DER format. -) - -func writeRandomTestRsaPemKey(t *testing.T, filePath string, bits int, format keyFormat, passphrase string, alg *x509.PEMCipher) { - key, err := rsa.GenerateKey(rand.Reader, bits) - if err != nil { - t.Fatalf("Error generating RSA private key file: %v", err) - } - var outFile *os.File - outFile, err = os.Create(filePath) - if err != nil { - t.Fatalf("Error creating RSA private key file: %v", err) - } - defer outFile.Close() - var privKeyBytes []byte - switch format { - case keyFormatPem: - if passphrase != "" { - t.Fatalf("Encrypting PKCS#1-encoded private key with passphrase is not supported") - } - privKeyBytes = x509.MarshalPKCS1PrivateKey(key) - case keyFormatPkcs8Pem: - privKeyBytes, err = x509.MarshalPKCS8PrivateKey(key) - if err != nil { - t.Fatalf("Error writing private key: %v", err) - } - case keyFormatPkcs8Der: - if passphrase != "" { - t.Fatalf("Encrypting DER-encoded private key with passphrase is not supported") - } - privKeyBytes, err = x509.MarshalPKCS8PrivateKey(key) - if err != nil { - t.Fatalf("Error writing private key: %v", err) - } - _, err = outFile.Write(privKeyBytes) - if err != nil { - t.Fatalf("Error writing DER-encoded private key: %v", err) - } - default: - t.Fatalf("Unsupported key format: %v", format) - } - - switch format { - case keyFormatPem, keyFormatPkcs8Der: - var pemBlock *pem.Block - if passphrase == "" { - pemBlock = &pem.Block{ - Type: "RSA PRIVATE KEY", - Bytes: privKeyBytes, - } - } else { - pemBlock, err = x509.EncryptPEMBlock(rand.Reader, "ENCRYPTED PRIVATE KEY", privKeyBytes, []byte(passphrase), *alg) - if err != nil { - t.Fatalf("Error encoding RSA private key: %v", err) - } - } - err = pem.Encode(outFile, pemBlock) - if err != nil { - t.Fatalf("Error encoding RSA private key: %v", err) - } - } - fmt.Printf("Wrote private key '%s'\n", filePath) -} - -/* -Commented out because OpenAPITools is configured to use golang 1.8 at build time -x509.MarshalPKCS8PrivateKey is not present. -func writeRandomTestEcdsaPemKey(t *testing.T, filePath string) { - key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) - if err != nil { - t.Fatalf("Error generating ECDSA private key file: %v", err) - } - var outFile *os.File - outFile, err = os.Create(filePath) - if err != nil { - t.Fatalf("Error creating ECDSA private key file: %v", err) - } - defer outFile.Close() - - var keybytes []byte - keybytes, err = x509.MarshalPKCS8PrivateKey(key) - if err != nil { - t.Fatalf("Error marshaling ECDSA private key: %v", err) - } - var privateKey = &pem.Block{ - Type: "PRIVATE KEY", - Bytes: keybytes, - } - - err = pem.Encode(outFile, privateKey) - if err != nil { - t.Fatalf("Error encoding ECDSA private key: %v", err) - } -} -*/ - -// TestHttpSignaturePrivateKeys creates private keys of various sizes, serialization format, -// clear-text and password encrypted. -// Test unmarshaling of the private key. -func TestHttpSignaturePrivateKeys(t *testing.T) { - var err error - var dir string - dir, err = ioutil.TempDir("", "go-http-sign") - if err != nil { - t.Fatalf("Failed to create temporary directory") - } - defer os.RemoveAll(dir) - - pemCiphers := []x509.PEMCipher{ - x509.PEMCipherDES, - x509.PEMCipher3DES, - x509.PEMCipherAES128, - x509.PEMCipherAES192, - x509.PEMCipherAES256, - } - // Test RSA private keys with various key lengths. - for _, bits := range []int{1024, 2048, 3072, 4096} { - - for _, format := range []keyFormat{keyFormatPem, keyFormatPkcs8Pem, keyFormatPkcs8Der} { - // Generate test private key. - var privateKeyPath string - switch format { - case keyFormatPem, keyFormatPkcs8Pem: - privateKeyPath = "privatekey.pem" - case keyFormatPkcs8Der: - privateKeyPath = "privatekey.der" - default: - t.Fatalf("Unsupported private key format: %v", format) - } - privateKeyPath = filepath.Join(dir, privateKeyPath) - // Generate keys in PEM format. - writeRandomTestRsaPemKey(t, privateKeyPath, bits, format, "", nil) - - authConfig := HttpSignatureAuth{ - KeyId: "my-key-id", - PrivateKeyPath: privateKeyPath, - Passphrase: "", - SigningScheme: "hs2019", - SignedHeaders: []string{"Content-Type"}, - } - - // Create a context with the HTTP signature configuration parameters. - _, err = authConfig.ContextWithValue(context.Background()) - if err != nil { - t.Fatalf("Error loading private key '%s': %v", privateKeyPath, err) - } - - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - PrivateKeyPath: privateKeyPath, - Passphrase: "my-secret-passphrase", - SigningScheme: "hs2019", - SignedHeaders: []string{"Content-Type"}, - } - switch format { - case keyFormatPem: - // Do nothing. Keys cannot be encrypted when using PKCS#1. - case keyFormatPkcs8Pem: - for _, alg := range pemCiphers { - writeRandomTestRsaPemKey(t, privateKeyPath, bits, format, authConfig.Passphrase, &alg) - _, err := authConfig.ContextWithValue(context.Background()) - if err != nil { - t.Fatalf("Error loading private key '%s': %v", privateKeyPath, err) - } - } - } - } - } - - /* - Unfortunately, currently the build environment for OpenAPITools is using an old version - of golang that does not support ECDSA keys. - { - privateKeyPath := "privatekey.pem" - authConfig := HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: "hs2019", - SignedHeaders: []string{"Content-Type"}, - } - // Generate test private key. - writeRandomTestEcdsaPemKey(t, privateKeyPath) - err := authConfig.LoadPrivateKey(privateKeyPath) - if err != nil { - t.Fatalf("Error loading private key '%s': %v", privateKeyPath, err) - } - } - */ -} - -const testHost = "petstore.swagger.io:80" -const testScheme = "http" - -func executeHttpSignatureAuth(t *testing.T, authConfig *HttpSignatureAuth, expectSuccess bool) string { - var err error - var dir string - dir, err = ioutil.TempDir("", "go-http-sign") - if err != nil { - t.Fatalf("Failed to create temporary directory") - } - defer os.RemoveAll(dir) - - cfg := NewConfiguration() - cfg.AddDefaultHeader("testheader", "testvalue") - cfg.AddDefaultHeader("Content-Type", "application/json") - cfg.Host = testHost - cfg.Scheme = testScheme - apiClient := NewAPIClient(cfg) - - privateKeyPath := filepath.Join(dir, "rsa.pem") - writeTestRsaPemKey(t, privateKeyPath) - authConfig.PrivateKeyPath = privateKeyPath - var authCtx context.Context - authCtx, err = authConfig.ContextWithValue(context.Background()) - if expectSuccess && err != nil { - t.Fatalf("Error validating HTTP signature configuration: %v", err) - } - if !expectSuccess && err != nil { - // Do not continue. Error is expected. - return "" - } - newPet := (Pet{Id: PtrInt64(12992), Name: "gopher", - PhotoUrls: []string{"http://1.com", "http://2.com"}, - Status: PtrString("pending"), - Tags: &[]Tag{Tag{Id: PtrInt64(1), Name: PtrString("tag2")}}}) - - fmt.Printf("Request with HTTP signature. Scheme: '%s'. Algorithm: '%s'. MaxValidity: %v. Headers: '%v'\n", - authConfig.SigningScheme, authConfig.SigningAlgorithm, authConfig.SignatureMaxValidity, authConfig.SignedHeaders) - - r, err2 := apiClient.PetApi.AddPet(authCtx).Pet(newPet).Execute() - if expectSuccess && err2 != nil { - t.Fatalf("Error while adding pet: %v", err2) - } - if !expectSuccess { - if err2 == nil { - t.Fatalf("Error was expected, but no error was generated") - } else { - // Do not continue. Error is expected. - return "" - } - } - if r.StatusCode != 200 { - t.Log(r) - } - - _, r, err = apiClient.PetApi.GetPetById(authCtx, 12992).Execute() - if expectSuccess && err != nil { - t.Fatalf("Error while deleting pet by id: %v", err) - } - - // The request should look like this: - // - // GET /v2/pet/12992 HTTP/1.1 - // Host: petstore.swagger.io:80 - // Accept: application/json - // Authorization: Signature keyId="my-key-id",algorithm="hs2019",created=1579033245,headers="(request-target) date host digest content-type",signature="RMJZjVVxzlH02wlxiQgUYDe4QxZaI5IJNIfB2BK8Dhbv3WQ2gw0xyqC+5HiKUmT/cfchhhkUNNsUtiVRnjZmFwtSfYxHfiQvH3KWXlLCMwKGNQC3YzD9lnoWdx0pA5Kxbr0/ygmr3+lTyuN2PJg4IS7Ji/AaKAqIZx7RsHS8Bxw=" - // Date: Tue, 14 Jan 2020 06:41:22 GMT - // Digest: SHA-512=z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXcg/SpIdNs6c5H0NE8XYXysP+DGNKHfuwvY7kxvUdBeoGlODJ6+SfaPg== - // Testheader: testvalue - // User-Agent: OpenAPI-Generator/1.0.0/go - reqb, _ := httputil.DumpRequest(r.Request, true) - reqt := (string)(reqb) - fmt.Printf("REQUEST:\n%v\n", reqt) - var sb bytes.Buffer - fmt.Fprintf(&sb, `Signature keyId="%s",algorithm="%s",`, - authConfig.KeyId, authConfig.SigningScheme) - if len(authConfig.SignedHeaders) == 0 { - fmt.Fprintf(&sb, `created=[0-9]+,`) - } else { - for _, header := range authConfig.SignedHeaders { - header = strings.ToLower(header) - if header == HttpSignatureParameterCreated { - fmt.Fprintf(&sb, `created=[0-9]+,`) - } - if header == HttpSignatureParameterExpires { - fmt.Fprintf(&sb, `expires=[0-9]+\.[0-9]{3},`) - } - } - } - fmt.Fprintf(&sb, `headers="`) - for i, header := range authConfig.SignedHeaders { - header = strings.ToLower(header) - if i > 0 { - fmt.Fprintf(&sb, " ") - } - fmt.Fprintf(&sb, regexp.QuoteMeta(header)) - switch header { - case "date": - if !strings.Contains(reqt, "Date: ") { - t.Errorf("Date header is incorrect") - } - case "digest": - var prefix string - switch authConfig.SigningScheme { - case HttpSigningSchemeRsaSha256: - prefix = "SHA-256=" - default: - prefix = "SHA-512=" - } - if !strings.Contains(reqt, fmt.Sprintf("Digest: %s", prefix)) { - t.Errorf("Digest header is incorrect") - } - } - } - if len(authConfig.SignedHeaders) == 0 { - fmt.Fprintf(&sb, regexp.QuoteMeta(HttpSignatureParameterCreated)) - } - fmt.Fprintf(&sb, `",signature="[a-zA-Z0-9+/]+="`) - re := regexp.MustCompile(sb.String()) - actual := r.Request.Header.Get("Authorization") - if !re.MatchString(actual) { - t.Errorf("Authorization header is incorrect. Expected regex\n'%s'\nbut got\n'%s'", sb.String(), actual) - } - - validateHttpAuthorizationSignature(t, authConfig, r) - return r.Request.Header.Get("Authorization") -} - -var ( - // signatureRe is a regular expression to capture the fields from the signature. - signatureRe = regexp.MustCompile( - `Signature keyId="(?P[^"]+)",algorithm="(?P[^"]+)"` + - `(,created=(?P[0-9]+))?(,expires=(?P[0-9.]+))?,headers="(?P[^"]+)",signature="(?P[^"]+)"`) -) - -// validateHttpAuthorizationSignature validates the HTTP signature in the HTTP request. -// The signature verification would normally be done by the server. -// Note: this is NOT a complete implementation of the HTTP signature validation. This code is for unit test purpose, do not use -// it for server side implementation. -// In particular, this code does not validate the calculation of the HTTP body digest. -func validateHttpAuthorizationSignature(t *testing.T, authConfig *HttpSignatureAuth, r *http.Response) { - authHeader := r.Request.Header.Get("Authorization") - match := signatureRe.FindStringSubmatch(authHeader) - if len(match) < 3 { - t.Fatalf("Unexpected Authorization header: %s", authHeader) - } - result := make(map[string]string) - for i, name := range signatureRe.SubexpNames() { - if i != 0 && name != "" { - result[name] = match[i] - } - } - b64signature := result["signature"] - fmt.Printf("Algorithm: '%s' Headers: '%s' b64signature: '%s'\n", result["algorithm"], result["headers"], b64signature) - var sb bytes.Buffer - fmt.Fprintf(&sb, "%s %s", strings.ToLower(r.Request.Method), r.Request.URL.EscapedPath()) - if r.Request.URL.RawQuery != "" { - // The ":path" pseudo-header field includes the path and query parts - // of the target URI (the "path-absolute" production and optionally a - // '?' character followed by the "query" production (see Sections 3.3 - // and 3.4 of [RFC3986] - fmt.Fprintf(&sb, "?%s", r.Request.URL.RawQuery) - } - requestTarget := sb.String() - - var signedHeaderKvs []string - signedHeaders := strings.Split(result["headers"], " ") - for _, h := range signedHeaders { - var value string - switch h { - case HttpSignatureParameterRequestTarget: - value = requestTarget - case HttpSignatureParameterCreated: - value = result["created"] - case HttpSignatureParameterExpires: - value = result["expires"] - default: - value = r.Request.Header.Get(h) - } - signedHeaderKvs = append(signedHeaderKvs, fmt.Sprintf("%s: %s", h, value)) - } - stringToSign := strings.Join(signedHeaderKvs, "\n") - - var h crypto.Hash - switch result["algorithm"] { - case HttpSigningSchemeHs2019, HttpSigningSchemeRsaSha512: - h = crypto.SHA512 - case HttpSigningSchemeRsaSha256: - h = crypto.SHA256 - default: - t.Fatalf("Unexpected signing algorithm: %s", result["algorithm"]) - } - msgHash := h.New() - if _, err := msgHash.Write([]byte(stringToSign)); err != nil { - t.Fatalf("Unable to compute hash: %v", err) - } - d := msgHash.Sum(nil) - var pub crypto.PublicKey - var err error - if pub, err = authConfig.GetPublicKey(); err != nil { - t.Fatalf("Unable to get public key: %v", err) - } - if pub == nil { - t.Fatalf("Public key is nil") - } - var signature []byte - if signature, err = base64.StdEncoding.DecodeString(b64signature); err != nil { - t.Fatalf("Failed to decode signature: %v", err) - } - switch publicKey := pub.(type) { - case *rsa.PublicKey: - // It could be PKCS1v15 or PSS signature - var errPKCS1v15, errPSS error - // In a server-side implementation, we wouldn't try to validate both signatures. The specific - // signature algorithm would be derived from the key id. But here we just want to validate for unit test purpose. - errPKCS1v15 = rsa.VerifyPKCS1v15(publicKey, h, d, signature) - errPSS = rsa.VerifyPSS(publicKey, h, d, signature, nil) - if errPKCS1v15 != nil && errPSS != nil { - t.Fatalf("RSA Signature verification failed: %v. %v", errPKCS1v15, errPSS) - } - case *ecdsa.PublicKey: - type ecdsaSignature struct { - R, S *big.Int - } - var lEcdsa ecdsaSignature - if _, err = asn1.Unmarshal(signature, &lEcdsa); err != nil { - t.Fatalf("Unable to parse ECDSA signature: %v", err) - } - if !ecdsa.Verify(publicKey, d, lEcdsa.R, lEcdsa.S) { - t.Fatalf("ECDSA Signature verification failed") - } - default: - t.Fatalf("Unsupported public key: %T", pub) - } -} - -func TestHttpSignatureAuth(t *testing.T) { - // Test with 'hs2019' signature scheme, and default signature algorithm (RSA SSA PKCS1.5) - authConfig := HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: HttpSigningSchemeHs2019, - SignedHeaders: []string{ - HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. - HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. - "Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number. - "Date", // The date and time at which the message was originated. - "Content-Type", // The Media type of the body of the request. - "Digest", // A cryptographic digest of the request body. - }, - } - executeHttpSignatureAuth(t, &authConfig, true) - - // Test with duplicate headers. This is invalid and should be rejected. - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: HttpSigningSchemeHs2019, - SignedHeaders: []string{"Host", "Date", "Host"}, - } - executeHttpSignatureAuth(t, &authConfig, false) - - // Test with non-existent header. This is invalid and should be rejected. - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: HttpSigningSchemeHs2019, - SignedHeaders: []string{"Host", "Date", "Garbage-HeaderDoesNotExist"}, - } - executeHttpSignatureAuth(t, &authConfig, false) - - // Test with 'Authorization' header in the signed headers. This is invalid and should be rejected. - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: HttpSigningSchemeHs2019, - SignedHeaders: []string{"Host", "Authorization"}, - } - executeHttpSignatureAuth(t, &authConfig, false) - - // Specify signature max validity, but '(expires)' parameter is missing. This should cause an error. - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: HttpSigningSchemeHs2019, - SignatureMaxValidity: 7 * time.Minute, - } - executeHttpSignatureAuth(t, &authConfig, false) - - // Specify invalid signature max validity. This should cause an error. - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: HttpSigningSchemeHs2019, - SignatureMaxValidity: -3 * time.Minute, - } - executeHttpSignatureAuth(t, &authConfig, false) - - // Specify signature max validity and '(expires)' parameter. - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: HttpSigningSchemeHs2019, - SignatureMaxValidity: time.Minute, - SignedHeaders: []string{ - HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. - HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. - HttpSignatureParameterExpires, // Time when signature expires. - }, - } - executeHttpSignatureAuth(t, &authConfig, true) - - // Specify '(expires)' parameter but no signature max validity. - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: HttpSigningSchemeHs2019, - SignedHeaders: []string{ - HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. - HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. - HttpSignatureParameterExpires, // Time when signature expires. - }, - } - executeHttpSignatureAuth(t, &authConfig, false) - - // Test with empty signed headers. The client should automatically add the "(created)" parameter by default. - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: HttpSigningSchemeHs2019, - SignedHeaders: []string{}, - } - executeHttpSignatureAuth(t, &authConfig, true) - - // Test with deprecated RSA-SHA512, some servers may still support it. - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: HttpSigningSchemeRsaSha512, - SignedHeaders: []string{ - HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. - HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. - "Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number. - "Date", // The date and time at which the message was originated. - "Content-Type", // The Media type of the body of the request. - "Digest", // A cryptographic digest of the request body. - }, - } - executeHttpSignatureAuth(t, &authConfig, true) - - // Test with deprecated RSA-SHA256, some servers may still support it. - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: HttpSigningSchemeRsaSha256, - SignedHeaders: []string{ - HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. - HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. - "Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number. - "Date", // The date and time at which the message was originated. - "Content-Type", // The Media type of the body of the request. - "Digest", // A cryptographic digest of the request body. - }, - } - executeHttpSignatureAuth(t, &authConfig, true) - - // Test with headers without date. This makes it possible to get a fixed signature, used for unit test purpose. - // This should not be used in production code as it could potentially allow replay attacks. - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: HttpSigningSchemeHs2019, - SigningAlgorithm: HttpSigningAlgorithmRsaPKCS1v15, - SignedHeaders: []string{ - HttpSignatureParameterRequestTarget, - "Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number. - "Content-Type", // The Media type of the body of the request. - "Digest", // A cryptographic digest of the request body. - }, - } - authorizationHeaderValue := executeHttpSignatureAuth(t, &authConfig, true) - expectedSignature := "sXE2MDeW8os6ywv1oUWaFEPFcSPCEb/msQ/NZGKNA9Emm/e42axaAPojzfkZ9Hacyw/iS/5nH4YIkczMgXu3z5fAwFjumxtf3OxbqvUcQ80wvw2/7B5aQmsF6ZwrCFHZ+L/cj9/bg7L1EGUGtdyDzoRKti4zf9QF/03OsP7QljI=" - expectedAuthorizationHeader := fmt.Sprintf( - `Signature keyId="my-key-id",`+ - `algorithm="hs2019",headers="(request-target) host content-type digest",`+ - `signature="%s"`, expectedSignature) - if authorizationHeaderValue != expectedAuthorizationHeader { - t.Errorf("Authorization header value is incorrect. Got\n'%s'\nbut expected\n'%s'", authorizationHeaderValue, expectedAuthorizationHeader) - } - - // Test with PSS signature. The PSS signature creates a new signature every time it is invoked. - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - SigningScheme: HttpSigningSchemeHs2019, - SigningAlgorithm: HttpSigningAlgorithmRsaPSS, - SignedHeaders: []string{ - HttpSignatureParameterRequestTarget, - "Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number. - "Content-Type", // The Media type of the body of the request. - "Digest", // A cryptographic digest of the request body. - }, - } - authorizationHeaderValue = executeHttpSignatureAuth(t, &authConfig, true) - expectedSignature = `[a-zA-Z0-9+/]+=` - expectedAuthorizationHeader = fmt.Sprintf( - `Signature keyId="my-key-id",`+ - `algorithm="hs2019",headers="\(request-target\) host content-type digest",`+ - `signature="%s"`, expectedSignature) - re := regexp.MustCompile(expectedAuthorizationHeader) - if !re.MatchString(authorizationHeaderValue) { - t.Errorf("Authorization header value is incorrect. Got\n'%s'\nbut expected\n'%s'", authorizationHeaderValue, expectedAuthorizationHeader) - } -} - -func TestInvalidHttpSignatureConfiguration(t *testing.T) { - var err error - var authConfig HttpSignatureAuth - - authConfig = HttpSignatureAuth{ - } - _, err = authConfig.ContextWithValue(context.Background()) - if err == nil || !strings.Contains(err.Error(), "Key ID must be specified") { - t.Fatalf("Invalid configuration: %v", err) - } - - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - } - _, err = authConfig.ContextWithValue(context.Background()) - if err == nil || !strings.Contains(err.Error(), "Private key path must be specified") { - t.Fatalf("Invalid configuration: %v", err) - } - - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - PrivateKeyPath: "test.pem", - } - _, err = authConfig.ContextWithValue(context.Background()) - if err == nil || !strings.Contains(err.Error(), "Invalid signing scheme") { - t.Fatalf("Invalid configuration: %v", err) - } - - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - PrivateKeyPath: "test.pem", - SigningScheme: "garbage", - } - _, err = authConfig.ContextWithValue(context.Background()) - if err == nil || !strings.Contains(err.Error(), "Invalid signing scheme") { - t.Fatalf("Invalid configuration: %v", err) - } - - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - PrivateKeyPath: "test.pem", - SigningScheme: HttpSigningSchemeHs2019, - SignedHeaders: []string{"foo", "bar", "foo"}, - } - _, err = authConfig.ContextWithValue(context.Background()) - if err == nil || !strings.Contains(err.Error(), "cannot have duplicate names") { - t.Fatalf("Invalid configuration: %v", err) - } - - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - PrivateKeyPath: "test.pem", - SigningScheme: HttpSigningSchemeHs2019, - SignedHeaders: []string{"foo", "bar", "Authorization"}, - } - _, err = authConfig.ContextWithValue(context.Background()) - if err == nil || !strings.Contains(err.Error(), "Signed headers cannot include the 'Authorization' header") { - t.Fatalf("Invalid configuration: %v", err) - } - - authConfig = HttpSignatureAuth{ - KeyId: "my-key-id", - PrivateKeyPath: "test.pem", - SigningScheme: HttpSigningSchemeHs2019, - SignedHeaders: []string{"foo", "bar"}, - SignatureMaxValidity: -7 * time.Minute, - } - _, err = authConfig.ContextWithValue(context.Background()) - if err == nil || !strings.Contains(err.Error(), "Signature max validity must be a positive value") { - t.Fatalf("Invalid configuration: %v", err) - } -} \ No newline at end of file