Skip to content

Commit

Permalink
sdk: Move to go-swagger SDK code generation
Browse files Browse the repository at this point in the history
Closes #165

Signed-off-by: aeneasr <aeneas@ory.sh>
  • Loading branch information
aeneasr committed Apr 6, 2019
1 parent 4fc579c commit 2d853aa
Show file tree
Hide file tree
Showing 356 changed files with 21,285 additions and 3,630 deletions.
19 changes: 10 additions & 9 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,23 @@ gen-mocks:
mockgen -package proxy -destination proxy/authenticator_oauth2_introspection_mock.go -source ./proxy/authenticator_oauth2_introspection.go authenticatorOAuth2IntrospectionHelper

.PHONY: gen
gen: gen-mocks gen-sdk
gen: gen-mocks sdk

.PHONY: gen-sdk
gen-sdk:
swagger generate spec -m -o ./docs/api.swagger.json
swagger validate ./docs/api.swagger.json
.PHONY: sdk
sdk:
GO111MODULE=on go mod tidy
GO111MODULE=on go mod vendor
GO111MODULE=off swagger generate spec -m -o ./docs/api.swagger.json
GO111MODULE=off swagger validate ./docs/api.swagger.json

rm -rf ./sdk/go/oathkeeper/swagger
rm -rf ./sdk/go/oathkeeper/*
rm -rf ./sdk/js/swagger

java -jar scripts/swagger-codegen-cli-2.2.3.jar generate -i ./docs/api.swagger.json -l go -o ./sdk/go/oathkeeper/swagger
GO111MODULE=off swagger generate client -f ./docs/api.swagger.json -t sdk/go/oathkeeper -A Ory_Oathkeeper

java -jar scripts/swagger-codegen-cli-2.2.3.jar generate -i ./docs/api.swagger.json -l javascript -o ./sdk/js/swagger

cd sdk/go; goreturns -w -i -local github.com/ory $$(listx .)

git checkout HEAD -- sdk/go/oathkeeper/swagger/rule_handler.go

rm -f ./sdk/js/swagger/package.json
rm -rf ./sdk/js/swagger/test
7 changes: 7 additions & 0 deletions UPGRADE.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ before finalizing the upgrade process.

## master

## v0.15.0+oryOS.10

### New Go SDK Generator

The ORY Oathkeeper Go SDK is no being generated using [`go-swagger`](https://github.com/go-swagger/go-swagger) instead of
[`swagger-codegen`](https://github.com/go-swagger/go-swagger). If you have questions regarding upgrading, please open an issue.

## v0.14.0+oryOS.10

### Changes to the ORY Keto Authorizer
Expand Down
47 changes: 47 additions & 0 deletions cmd/helper_client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright © 2017-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Aeneas Rekkas <aeneas+oss@aeneas.io>
* @copyright 2017-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
* @license Apache-2.0
*/

package cmd

import (
"net/url"

"github.com/spf13/cobra"

"github.com/ory/oathkeeper/sdk/go/oathkeeper/client"
"github.com/ory/x/cmdx"
"github.com/ory/x/flagx"
)

func newClient(cmd *cobra.Command) *client.OryOathkeeper {
endpoint := flagx.MustGetString(cmd, "endpoint")
if endpoint == "" {
fatalf("Please specify the endpoint url using the --endpoint flag, for more information use `oathkeeper help rules`")
}

u, err := url.ParseRequestURI(endpoint)
cmdx.Must(err, `Unable to parse endpoint URL "%s": %s`, endpoint, err)

return client.NewHTTPClientWithConfig(nil, &client.TransportConfig{
Host: u.Host,
BasePath: u.Path,
Schemes: []string{u.Scheme},
})
}
12 changes: 0 additions & 12 deletions cmd/helper_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,8 @@ import (
"encoding/json"
"fmt"
"os"

"github.com/ory/oathkeeper/sdk/go/oathkeeper/swagger"
)

func checkResponse(response *swagger.APIResponse, err error, expectedStatusCode int) {
must(err, "A network error occurred: %s", err)

if response.StatusCode != expectedStatusCode {
fmt.Printf("Command failed because status code %d was expected but code %d was received", expectedStatusCode, response.StatusCode)
os.Exit(1)
return
}
}

func formatResponse(response interface{}) string {
out, err := json.MarshalIndent(response, "", "\t")
must(err, `Command failed because an error ("%s") occurred while prettifying output.`, err)
Expand Down
2 changes: 1 addition & 1 deletion cmd/helper_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func refreshRules(m rule.Refresher, duration time.Duration) {
if err := m.Refresh(); err != nil {
logger.WithError(err).WithField("retry", fails).Errorln("Unable to refresh rules")
if fails > 15 {
logger.WithError(err).WithField("retry", fails).Fatalf("Terminating after retry %d\n", fails)
logger.WithError(err).WithField("retry", fails).Fatalf("Terminating after retry %d", fails)
}

time.Sleep(time.Second * time.Duration(fails+1))
Expand Down
15 changes: 6 additions & 9 deletions cmd/rules_delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ package cmd

import (
"fmt"
"net/http"

"github.com/spf13/cobra"

"github.com/ory/oathkeeper/sdk/go/oathkeeper"
"github.com/ory/oathkeeper/sdk/go/oathkeeper/client/rule"
"github.com/ory/x/cmdx"
)

// deleteCmd represents the delete command
Expand All @@ -38,16 +38,13 @@ var deleteCmd = &cobra.Command{
oathkeeper rules --endpoint=http://localhost:4456/ delete rule-1
`,
Run: func(cmd *cobra.Command, args []string) {
endpoint, _ := cmd.Flags().GetString("endpoint")
if endpoint == "" {
fatalf("Please specify the endpoint url using the --endpoint flag, for more information use `oathkeeper help rules`")
} else if len(args) != 1 {
if len(args) != 1 {
fatalf("Please specify the rule id, for more information use `oathkeeper help rules delete`")
}

client := oathkeeper.NewSDK(endpoint)
response, err := client.DeleteRule(args[0])
checkResponse(response, err, http.StatusNoContent)
client := newClient(cmd)
_, err := client.Rule.DeleteRule(rule.NewDeleteRuleParams().WithID(args[0]))
cmdx.Must(err, "%s", err)
fmt.Printf("Successfully deleted rule %s\n", args[0])
},
}
Expand Down
12 changes: 6 additions & 6 deletions cmd/rules_get.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ package cmd

import (
"fmt"
"net/http"

"github.com/spf13/cobra"

"github.com/ory/oathkeeper/sdk/go/oathkeeper"
"github.com/ory/oathkeeper/sdk/go/oathkeeper/client/rule"
"github.com/ory/x/cmdx"
)

// getCmd represents the get command
Expand All @@ -45,10 +45,10 @@ var getCmd = &cobra.Command{
fatalf("Please specify the rule id, for more information use `oathkeeper help rules get`")
}

client := oathkeeper.NewSDK(endpoint)
rule, response, err := client.GetRule(args[0])
checkResponse(response, err, http.StatusOK)
fmt.Println(formatResponse(rule))
client := newClient(cmd)
r, err := client.Rule.GetRule(rule.NewGetRuleParams().WithID(args[0]))
cmdx.Must(err, "%s", err)
fmt.Println(formatResponse(r))
},
}

Expand Down
49 changes: 24 additions & 25 deletions cmd/rules_import.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,14 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"

swaggerRule "github.com/ory/oathkeeper/sdk/go/oathkeeper/client/rule"
"github.com/ory/oathkeeper/sdk/go/oathkeeper/models"
"github.com/ory/x/cmdx"

"github.com/spf13/cobra"

"github.com/ory/oathkeeper/rule"
"github.com/ory/oathkeeper/sdk/go/oathkeeper"
"github.com/ory/oathkeeper/sdk/go/oathkeeper/swagger"
)

// importCmd represents the import command
Expand Down Expand Up @@ -70,51 +71,49 @@ Usage example:

for _, r := range rules {
fmt.Printf("Importing rule %s...\n", r.ID)
client := oathkeeper.NewSDK(endpoint)
client := newClient(cmd)

shouldUpdate := false
if _, response, err := client.GetRule(r.ID); err != nil {
must(err, "Unable to call endpoint %s because %s", endpoint, err)
} else if response.StatusCode == http.StatusOK {
if _, err := client.Rule.GetRule(swaggerRule.NewGetRuleParams().WithID(r.ID)); err == nil {
shouldUpdate = true
}

rh := make([]swagger.RuleHandler, len(r.Authenticators))
rh := make([]*models.SwaggerRuleHandler, len(r.Authenticators))
for k, authn := range r.Authenticators {
rh[k] = swagger.RuleHandler{
rh[k] = &models.SwaggerRuleHandler{
Handler: authn.Handler,
Config: []byte(authn.Config),
Config: json.RawMessage(authn.Config),
}
}

sr := swagger.Rule{
Id: r.ID,
sr := models.SwaggerRule{
ID: r.ID,
Description: r.Description,
Match: swagger.RuleMatch{Methods: r.Match.Methods, Url: r.Match.URL},
Authorizer: swagger.RuleHandler{
Match: &models.SwaggerRuleMatch{Methods: r.Match.Methods, URL: r.Match.URL},
Authorizer: &models.SwaggerRuleHandler{
Handler: r.Authorizer.Handler,
Config: []byte(r.Authorizer.Config),
Config: models.RawMessage(r.Authorizer.Config),
},
Authenticators: rh,
CredentialsIssuer: swagger.RuleHandler{
CredentialsIssuer: &models.SwaggerRuleHandler{
Handler: r.CredentialsIssuer.Handler,
Config: []byte(r.CredentialsIssuer.Config),
Config: models.RawMessage(r.CredentialsIssuer.Config),
},
Upstream: swagger.Upstream{
Url: r.Upstream.URL,
Upstream: &models.Upstream{
URL: r.Upstream.URL,
PreserveHost: r.Upstream.PreserveHost,
StripPath: r.Upstream.StripPath,
},
}

if shouldUpdate {
out, response, err := client.UpdateRule(r.ID, sr)
checkResponse(response, err, http.StatusOK)
fmt.Printf("Successfully imported rule %s...\n", out.Id)
response, err := client.Rule.UpdateRule(swaggerRule.NewUpdateRuleParams().WithID(r.ID).WithBody(&sr))
cmdx.Must(err, "%s", err)
fmt.Printf("Successfully imported rule %s...\n", response.Payload.ID)
} else {
out, response, err := client.CreateRule(sr)
checkResponse(response, err, http.StatusCreated)
fmt.Printf("Successfully imported rule %s...\n", out.Id)
response, err := client.Rule.CreateRule(swaggerRule.NewCreateRuleParams().WithBody(&sr))
cmdx.Must(err, "%s", err)
fmt.Printf("Successfully imported rule %s...\n", response.Payload.ID)
}
}
fmt.Printf("Successfully imported all rules from %s", args[0])
Expand Down
14 changes: 8 additions & 6 deletions cmd/rules_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@ package cmd

import (
"fmt"
"net/http"

"github.com/spf13/cobra"

"github.com/ory/oathkeeper/sdk/go/oathkeeper/client/rule"
"github.com/ory/x/cmdx"

"github.com/ory/oathkeeper/pkg"
"github.com/ory/oathkeeper/sdk/go/oathkeeper"
)

// listCmd represents the list command
Expand All @@ -44,10 +45,11 @@ var listCmd = &cobra.Command{
fatalf("Please specify the endpoint url using the --endpoint flag, for more information use `oathkeeper help rules`")
}

client := oathkeeper.NewSDK(endpoint)
rules, response, err := client.ListRules(pkg.RulesUpperLimit, 0)
checkResponse(response, err, http.StatusOK)
fmt.Println(formatResponse(rules))
limit := int64(pkg.RulesUpperLimit)
client := newClient(cmd)
r, err := client.Rule.ListRules(rule.NewListRulesParams().WithLimit(&limit))
cmdx.Must(err, "%s", err)
fmt.Println(formatResponse(r))
},
}

Expand Down
6 changes: 3 additions & 3 deletions cmd/serve_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,13 @@ HTTP CONTROLS

if err := graceful.Graceful(func() error {
if cert != nil {
logger.Printf("Listening on https://%s.\n", addr)
logger.Printf("Listening on https://%s", addr)
return server.ListenAndServeTLS("", "")
}
logger.Printf("Listening on http://%s.\n", addr)
logger.Printf("Listening on http://%s", addr)
return server.ListenAndServe()
}, server.Shutdown); err != nil {
logger.Fatalf("Unable to gracefully shutdown HTTP(s) server because %v.\n", err)
logger.Fatalf("Unable to gracefully shutdown HTTP(s) server because %v", err)
return
}
logger.Println("HTTP server was shutdown gracefully")
Expand Down
16 changes: 10 additions & 6 deletions cmd/serve_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"

"github.com/meatballhat/negroni-logrus"
negronilogrus "github.com/meatballhat/negroni-logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand All @@ -35,7 +37,6 @@ import (
"github.com/ory/keto/sdk/go/keto"
"github.com/ory/oathkeeper/proxy"
"github.com/ory/oathkeeper/rule"
"github.com/ory/oathkeeper/sdk/go/oathkeeper"
"github.com/ory/x/corsx"
"github.com/ory/x/metricsx"
)
Expand Down Expand Up @@ -181,9 +182,12 @@ OTHER CONTROLS
` + corsMessage,
Run: func(cmd *cobra.Command, args []string) {
oathkeeperSdk := oathkeeper.NewSDK(viper.GetString("OATHKEEPER_API_URL"))
u, err := url.ParseRequestURI(viper.GetString("OATHKEEPER_API_URL"))
if err != nil {
logger.WithError(err).Fatalf(`Value from environment variable "OATHKEEPER_API_URL" is not a valid URL: %s`, err)
}

matcher := rule.NewHTTPMatcher(oathkeeperSdk)
matcher := rule.NewHTTPMatcher(u)
if err := matcher.Refresh(); err != nil {
logger.WithError(err).Fatalln("Unable to refresh rules")
}
Expand Down Expand Up @@ -263,13 +267,13 @@ OTHER CONTROLS

if err := graceful.Graceful(func() error {
if cert != nil {
logger.Printf("Listening on https://%s.\n", addr)
logger.Printf("Listening on https://%s", addr)
return server.ListenAndServeTLS("", "")
}
logger.Printf("Listening on http://%s.\n", addr)
logger.Printf("Listening on http://%s", addr)
return server.ListenAndServe()
}, server.Shutdown); err != nil {
logger.Fatalf("Unable to gracefully shutdown HTTP(s) server because %v.\n", err)
logger.Fatalf("Unable to gracefully shutdown HTTP(s) server because %v", err)
return
}
logger.Println("HTTP(s) server was shutdown gracefully")
Expand Down
Loading

0 comments on commit 2d853aa

Please sign in to comment.