Skip to content

Commit

Permalink
Merged from main
Browse files Browse the repository at this point in the history
  • Loading branch information
dorsha committed Dec 18, 2023
2 parents 933d72f + c174732 commit 7b57a0e
Show file tree
Hide file tree
Showing 67 changed files with 1,640 additions and 1,272 deletions.
206 changes: 110 additions & 96 deletions README.md

Large diffs are not rendered by default.

43 changes: 30 additions & 13 deletions descope/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -95,6 +96,7 @@ var (
userUpdateCustomAttribute: "mgmt/user/update/customAttribute",
userAddTenant: "mgmt/user/update/tenant/add",
userRemoveTenant: "mgmt/user/update/tenant/remove",
userSetRole: "mgmt/user/update/role/set",
userAddRole: "mgmt/user/update/role/add",
userRemoveRole: "mgmt/user/update/role/remove",
userSetPassword: "mgmt/user/password/set",
Expand Down Expand Up @@ -136,6 +138,7 @@ var (
projectImport: "mgmt/project/import",
projectUpdateName: "mgmt/project/update/name",
projectClone: "mgmt/project/clone",
projectDelete: "mgmt/project/delete",
auditSearch: "mgmt/audit/search",
authzSchemaSave: "mgmt/authz/schema/save",
authzSchemaDelete: "mgmt/authz/schema/delete",
Expand Down Expand Up @@ -243,6 +246,7 @@ type mgmtEndpoints struct {
userAddTenant string
userRemoveTenant string
userAddRole string
userSetRole string
userRemoveRole string
userSetPassword string
userExpirePassword string
Expand Down Expand Up @@ -291,6 +295,7 @@ type mgmtEndpoints struct {
projectImport string
projectUpdateName string
projectClone string
projectDelete string

auditSearch string

Expand Down Expand Up @@ -545,6 +550,10 @@ func (e *endpoints) ManagementUserRemoveTenant() string {
return path.Join(e.version, e.mgmt.userRemoveTenant)
}

func (e *endpoints) ManagementUserSetRole() string {
return path.Join(e.version, e.mgmt.userSetRole)
}

func (e *endpoints) ManagementUserAddRole() string {
return path.Join(e.version, e.mgmt.userAddRole)
}
Expand Down Expand Up @@ -709,6 +718,10 @@ func (e *endpoints) ManagementProjectClone() string {
return path.Join(e.version, e.mgmt.projectClone)
}

func (e *endpoints) ManagementProjectDelete() string {
return path.Join(e.version, e.mgmt.projectDelete)
}

func (e *endpoints) ManagementAuditSearch() string {
return path.Join(e.version, e.mgmt.auditSearch)
}
Expand Down Expand Up @@ -781,11 +794,11 @@ type sdkInfo struct {
}

type ClientParams struct {
BaseURL string
DefaultClient IHttpClient
CustomDefaultHeaders map[string]string

ProjectID string
BaseURL string
DefaultClient IHttpClient
CustomDefaultHeaders map[string]string
VerifyServerCertificate bool
ProjectID string
}

type IHttpClient interface {
Expand Down Expand Up @@ -820,7 +833,7 @@ func NewClient(conf ClientParams) *Client {
t.MaxIdleConns = 100
t.MaxConnsPerHost = 100
t.MaxIdleConnsPerHost = 100
t.TLSClientConfig.InsecureSkipVerify = true
t.TLSClientConfig.InsecureSkipVerify = !conf.VerifyServerCertificate
httpClient = &http.Client{
Timeout: time.Second * 10,
Transport: t,
Expand Down Expand Up @@ -848,15 +861,15 @@ func NewClient(conf ClientParams) *Client {
}
}

func (c *Client) DoGetRequest(uri string, options *HTTPRequest, pswd string) (*HTTPResponse, error) {
return c.DoRequest(http.MethodGet, uri, nil, options, pswd)
func (c *Client) DoGetRequest(ctx context.Context, uri string, options *HTTPRequest, pswd string) (*HTTPResponse, error) {
return c.DoRequest(ctx, http.MethodGet, uri, nil, options, pswd)
}

func (c *Client) DoDeleteRequest(uri string, options *HTTPRequest, pswd string) (*HTTPResponse, error) {
return c.DoRequest(http.MethodDelete, uri, nil, options, pswd)
func (c *Client) DoDeleteRequest(ctx context.Context, uri string, options *HTTPRequest, pswd string) (*HTTPResponse, error) {
return c.DoRequest(ctx, http.MethodDelete, uri, nil, options, pswd)
}

func (c *Client) DoPostRequest(uri string, body interface{}, options *HTTPRequest, pswd string) (*HTTPResponse, error) {
func (c *Client) DoPostRequest(ctx context.Context, uri string, body interface{}, options *HTTPRequest, pswd string) (*HTTPResponse, error) {
if options == nil {
options = &HTTPRequest{}
}
Expand All @@ -881,10 +894,10 @@ func (c *Client) DoPostRequest(uri string, body interface{}, options *HTTPReques
}
}

return c.DoRequest(http.MethodPost, uri, payload, options, pswd)
return c.DoRequest(ctx, http.MethodPost, uri, payload, options, pswd)
}

func (c *Client) DoRequest(method, uriPath string, body io.Reader, options *HTTPRequest, pswd string) (*HTTPResponse, error) {
func (c *Client) DoRequest(ctx context.Context, method, uriPath string, body io.Reader, options *HTTPRequest, pswd string) (*HTTPResponse, error) {
if options == nil {
options = &HTTPRequest{}
}
Expand Down Expand Up @@ -939,6 +952,10 @@ func (c *Client) DoRequest(method, uriPath string, body io.Reader, options *HTTP
c.addDescopeHeaders(req)

logger.LogDebug("Sending request to [%s]", url)

if ctx != nil {
req = req.WithContext(ctx)
}
response, err := c.httpClient.Do(req)
if err != nil {
logger.LogError("Failed sending request to [%s]", err, url)
Expand Down
31 changes: 16 additions & 15 deletions descope/api/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"bytes"
"context"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -45,7 +46,7 @@ func TestRequestWithDescopeHeaders(t *testing.T) {
return &http.Response{StatusCode: http.StatusOK}, nil
})})

_, err := c.DoPostRequest("path", nil, nil, "")
_, err := c.DoPostRequest(context.Background(), "path", nil, nil, "")
require.NoError(t, err)
}

Expand All @@ -60,7 +61,7 @@ func TestGetRequest(t *testing.T) {
assert.EqualValues(t, projectID, actualProject)
return &http.Response{Body: io.NopCloser(strings.NewReader(expectedResponse)), StatusCode: http.StatusOK}, nil
})})
res, err := c.DoGetRequest("path", &HTTPRequest{QueryParams: map[string]string{"test": "1"}}, "")
res, err := c.DoGetRequest(context.Background(), "path", &HTTPRequest{QueryParams: map[string]string{"test": "1"}}, "")
require.NoError(t, err)
assert.EqualValues(t, expectedResponse, res.BodyStr)
}
Expand All @@ -84,7 +85,7 @@ func TestPostRequest(t *testing.T) {
})})

actualOutput := &dummy{}
res, err := c.DoPostRequest("path", strings.NewReader("test"), &HTTPRequest{ResBodyObj: actualOutput, Headers: expectedHeaders}, "")
res, err := c.DoPostRequest(context.Background(), "path", strings.NewReader("test"), &HTTPRequest{ResBodyObj: actualOutput, Headers: expectedHeaders}, "")
require.NoError(t, err)
assert.EqualValues(t, string(outputBytes), res.BodyStr)
assert.EqualValues(t, expectedOutput, actualOutput)
Expand All @@ -101,7 +102,7 @@ func TestPostCustomHeaders(t *testing.T) {
return &http.Response{StatusCode: http.StatusOK}, nil
})})

_, err := c.DoPostRequest("path", nil, nil, "")
_, err := c.DoPostRequest(context.Background(), "path", nil, nil, "")
require.NoError(t, err)
}

Expand All @@ -115,7 +116,7 @@ func TestPostCustomCookies(t *testing.T) {
return &http.Response{StatusCode: http.StatusOK}, nil
})})

_, err := c.DoPostRequest("path", nil, &HTTPRequest{Cookies: []*http.Cookie{expectedCookie}}, "")
_, err := c.DoPostRequest(context.Background(), "path", nil, &HTTPRequest{Cookies: []*http.Cookie{expectedCookie}}, "")
require.NoError(t, err)
}

Expand All @@ -134,7 +135,7 @@ func TestPostCustomURL(t *testing.T) {

req, err := http.NewRequest(http.MethodPost, "hello.com/path?test=1", bytes.NewBufferString(body))
require.NoError(t, err)
res, err := c.DoPostRequest("path", nil, &HTTPRequest{Request: req, BaseURL: "https://overriden.com"}, "")
res, err := c.DoPostRequest(context.Background(), "path", nil, &HTTPRequest{Request: req, BaseURL: "https://overriden.com"}, "")
require.NoError(t, err)
assert.EqualValues(t, http.StatusOK, res.Res.StatusCode)
}
Expand All @@ -147,7 +148,7 @@ func TestPostCustomBaseURL(t *testing.T) {
return &http.Response{StatusCode: http.StatusOK}, nil
})})

res, err := c.DoPostRequest("path", nil, &HTTPRequest{BaseURL: url}, "")
res, err := c.DoPostRequest(context.Background(), "path", nil, &HTTPRequest{BaseURL: url}, "")
require.NoError(t, err)
assert.EqualValues(t, http.StatusOK, res.Res.StatusCode)
}
Expand All @@ -159,7 +160,7 @@ func TestPostUnauthorized(t *testing.T) {
return &http.Response{StatusCode: http.StatusUnauthorized}, nil
})})

_, err := c.DoPostRequest("path", nil, nil, "")
_, err := c.DoPostRequest(context.Background(), "path", nil, nil, "")
require.Error(t, err)
assert.ErrorIs(t, err, descope.ErrInvalidResponse)
assert.True(t, descope.IsUnauthorizedError(err))
Expand All @@ -170,15 +171,15 @@ func TestPostRateLimitExceeded(t *testing.T) {
return &http.Response{StatusCode: http.StatusTooManyRequests, Body: io.NopCloser(strings.NewReader(`{"errorCode":"E130429"}`))}, nil
})})

_, err := c.DoPostRequest("path", nil, nil, "")
_, err := c.DoPostRequest(context.Background(), "path", nil, nil, "")
require.ErrorIs(t, err, descope.ErrRateLimitExceeded)
require.Nil(t, err.(*descope.Error).Info[descope.ErrorInfoKeys.RateLimitExceededRetryAfter])

c = NewClient(ClientParams{ProjectID: "test", DefaultClient: mocks.NewTestClient(func(r *http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusTooManyRequests, Header: http.Header{"Retry-After": []string{"10"}}, Body: io.NopCloser(strings.NewReader(`{"errorCode":"E130429"}`))}, nil
})})

_, err = c.DoPostRequest("path", nil, nil, "")
_, err = c.DoPostRequest(context.Background(), "path", nil, nil, "")
require.ErrorIs(t, err, descope.ErrRateLimitExceeded)
require.Equal(t, 10, err.(*descope.Error).Info[descope.ErrorInfoKeys.RateLimitExceededRetryAfter])
}
Expand All @@ -191,7 +192,7 @@ func TestPostDescopeError(t *testing.T) {
return &http.Response{StatusCode: http.StatusBadRequest, Body: io.NopCloser(strings.NewReader(fmt.Sprintf(`{ "errorCode": "%s" }`, code)))}, nil
})})

_, err := c.DoPostRequest("path", nil, nil, "")
_, err := c.DoPostRequest(context.Background(), "path", nil, nil, "")
require.Error(t, err)
assert.EqualValues(t, code, err.(*descope.Error).Code)
}
Expand All @@ -204,7 +205,7 @@ func TestPostError(t *testing.T) {
return nil, fmt.Errorf(expectedErr)
})})

_, err := c.DoPostRequest("path", nil, nil, "")
_, err := c.DoPostRequest(context.Background(), "path", nil, nil, "")
require.Error(t, err)
assert.Contains(t, err.Error(), expectedErr)
}
Expand All @@ -217,7 +218,7 @@ func TestPostUnknownError(t *testing.T) {
return &http.Response{StatusCode: http.StatusBadRequest, Body: io.NopCloser(strings.NewReader(code))}, nil
})})

_, err := c.DoPostRequest("path", nil, nil, "")
_, err := c.DoPostRequest(context.Background(), "path", nil, nil, "")
require.Error(t, err)
assert.ErrorIs(t, err, descope.ErrInvalidResponse)
}
Expand All @@ -229,7 +230,7 @@ func TestPostNotFoundError(t *testing.T) {
return &http.Response{StatusCode: http.StatusNotFound, Request: r}, nil
})})

_, err := c.DoPostRequest("path", nil, nil, "")
_, err := c.DoPostRequest(context.Background(), "path", nil, nil, "")
require.Error(t, err)
assert.ErrorIs(t, err, descope.ErrInvalidResponse)
assert.True(t, descope.IsNotFoundError(err))
Expand All @@ -242,7 +243,7 @@ func TestDoRequestDefault(t *testing.T) {
return &http.Response{StatusCode: http.StatusOK}, nil
})})

_, err := c.DoRequest(http.MethodGet, "path", nil, nil, "")
_, err := c.DoRequest(context.Background(), http.MethodGet, "path", nil, nil, "")
require.NoError(t, err)
}

Expand Down
2 changes: 1 addition & 1 deletion descope/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func NewWithConfig(config *Config) (*DescopeClient, error) {
}
config.setManagementKey()

c := api.NewClient(api.ClientParams{BaseURL: config.DescopeBaseURL, CustomDefaultHeaders: config.CustomDefaultHeaders, DefaultClient: config.DefaultClient, ProjectID: config.ProjectID})
c := api.NewClient(api.ClientParams{BaseURL: config.DescopeBaseURL, CustomDefaultHeaders: config.CustomDefaultHeaders, DefaultClient: config.DefaultClient, ProjectID: config.ProjectID, VerifyServerCertificate: config.VerifyServerCertificate})

authService, err := auth.NewAuth(auth.AuthParams{
ProjectID: config.ProjectID,
Expand Down
6 changes: 4 additions & 2 deletions descope/client/client_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package client

import (
"context"
"os"
"testing"

Expand Down Expand Up @@ -70,7 +71,7 @@ func TestConcurrentClients(t *testing.T) {

// SignUpOrIn is called to trigger logging, to ensure it is safe
// during a concurrent creation of another client
_, _ = c.Auth.OTP().SignUpOrIn(descope.MethodEmail, "[email protected]")
_, _ = c.Auth.OTP().SignUpOrIn(context.Background(), descope.MethodEmail, "[email protected]")
}

func TestEmptyProjectID(t *testing.T) {
Expand Down Expand Up @@ -107,13 +108,14 @@ func TestDescopeSDKMock(t *testing.T) {
},
},
}
ctx := context.Background()
ok, info, err := api.Auth.ValidateAndRefreshSessionWithRequest(nil, nil)
assert.False(t, ok)
assert.NotEmpty(t, info)
assert.EqualValues(t, validateSessionResponse, info.JWT)
assert.ErrorIs(t, err, descope.ErrPublicKey)

res, err := api.Management.JWT().UpdateJWTWithCustomClaims("some jwt", nil)
res, err := api.Management.JWT().UpdateJWTWithCustomClaims(ctx, "some jwt", nil)
require.NoError(t, err)
assert.True(t, updateJWTWithCustomClaimsCalled)
assert.EqualValues(t, updateJWTWithCustomClaimsResponse, res)
Expand Down
2 changes: 2 additions & 0 deletions descope/client/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ type Config struct {
DescopeBaseURL string
// DefaultClient (optional, http.DefaultClient) - override the default client used to Do the actual http request.
DefaultClient api.IHttpClient
// VerifyServerCertificate (optional) - verify the server certificate
VerifyServerCertificate bool
// CustomDefaultHeaders (optional, nil) - add custom headers to all requests used to communicate with descope services.
CustomDefaultHeaders map[string]string
// LogLevel (optional, LogNone) - set a log level (Debug/Info/None) for the sdk to use when logging.
Expand Down
12 changes: 6 additions & 6 deletions descope/gin/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/descope/go-sdk/descope/gin
go 1.18

require (
github.com/descope/go-sdk v1.5.5
github.com/descope/go-sdk v1.5.7
github.com/gin-gonic/gin v1.9.1
)

Expand All @@ -20,11 +20,11 @@ require (
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/lestrrat-go/blackmagic v1.0.1 // indirect
github.com/lestrrat-go/blackmagic v1.0.2 // indirect
github.com/lestrrat-go/httpcc v1.0.1 // indirect
github.com/lestrrat-go/httprc v1.0.4 // indirect
github.com/lestrrat-go/iter v1.0.2 // indirect
github.com/lestrrat-go/jwx/v2 v2.0.11 // indirect
github.com/lestrrat-go/jwx/v2 v2.0.17 // indirect
github.com/lestrrat-go/option v1.0.1 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
Expand All @@ -34,11 +34,11 @@ require (
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/crypto v0.14.0 // indirect
golang.org/x/crypto v0.15.0 // indirect
golang.org/x/exp v0.0.0-20220921023135-46d9e7742f1e // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
golang.org/x/sys v0.14.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
Expand Down
Loading

0 comments on commit 7b57a0e

Please sign in to comment.