Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: cognito consent #1332

Merged
merged 2 commits into from
Jun 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions component/wallet-cli/pkg/walletrunner/consent/cognito.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
Copyright Avast Software. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package consent

import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)

type Cognito struct {
httpClient httpClient
url string
password string
login string
existingCookies map[string]*http.Cookie
}

func NewCognito(client httpClient, cookies []*http.Cookie, url string, login string, password string) *Cognito {
existing := map[string]*http.Cookie{}
for _, c := range cookies {
existing[c.Name] = c
}

return &Cognito{
url: url,
existingCookies: existing,
httpClient: client,
login: login,
password: password,
}
}

func (c *Cognito) Execute() error {
getReq, err := http.NewRequest(http.MethodGet, c.url, nil)
if err != nil {
return err
}

getResp, err := c.httpClient.Do(getReq)
if err != nil {
return err
}

data := url.Values{}
data.Set("username", c.login)
data.Set("password", c.password)
data.Add("signInSubmitButton", "Sign in")

for _, cookie := range getResp.Cookies() {
c.existingCookies[cookie.Name] = cookie
}

xsrf, ok := c.existingCookies["XSRF-TOKEN"]
if !ok {
return errors.New("XSRF-TOKEN cookie not found")
}

data.Add("_csrf", xsrf.Value)

postReq, err := http.NewRequest(http.MethodPost, c.url, strings.NewReader(data.Encode()))
if err != nil {
return err
}
for _, cookie := range c.existingCookies {
postReq.AddCookie(cookie)
}

postReq.Header.Add("Content-Type", "application/x-www-form-urlencoded")

postResp, postErr := c.httpClient.Do(postReq)
if postErr != nil {
return postErr
}

if postResp.StatusCode != http.StatusFound {
var body []byte
if postResp.Body != nil {
body, _ = io.ReadAll(postResp.Body)
defer func() {
_ = postResp.Body.Close()
}()
}

return fmt.Errorf("unexpected status code from post cognito. %v with body %s",
postResp.StatusCode, body)
}

return nil
}
191 changes: 191 additions & 0 deletions component/wallet-cli/pkg/walletrunner/consent/cognito_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
/*
Copyright Avast Software. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package consent_test

import (
"errors"
"io"
"net/http"
"strings"
"testing"

"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"

"github.com/trustbloc/vcs/component/wallet-cli/pkg/walletrunner/consent"
)

func TestCognitoConsent(t *testing.T) {
t.Run("success", func(t *testing.T) {
cl := NewMockhttpClient(gomock.NewController(t))

targetURL := "https://example.auth.us-east-2.amazoncognito.com/login?client_id=example&redirect_uri=" +
"https%3A%2F%2Fexample-redirect.com%2Fvcs%2Foidc%2Fredirect&response_type=code&" +
"state=9bc93ec1-7bdd-4084-8948-299ef35adab8"

ct := consent.NewCognito(
cl,
[]*http.Cookie{
{
Name: "XSRF-TOKEN",
Value: "abcd",
},
},
targetURL,
"some-login",
"some-password",
)

cl.EXPECT().Do(gomock.Any()).DoAndReturn(func(request *http.Request) (*http.Response, error) {
assert.Equal(t, http.MethodGet, request.Method)
assert.Equal(t, targetURL, request.URL.String())

return &http.Response{
Header: map[string][]string{
"Set-Cookie": {
"XSRF-TOKEN=8f6cafbe-34c3-4c96-b53b-47c798297e79; Path=/; Secure; HttpOnly; SameSite=Lax",
},
},
}, nil
})

cl.EXPECT().Do(gomock.Any()).DoAndReturn(func(request *http.Request) (*http.Response, error) {
assert.Equal(t, http.MethodPost, request.Method)
assert.Equal(t, targetURL, request.URL.String())
assert.Equal(t, "XSRF-TOKEN", request.Cookies()[0].Name)
assert.Equal(t, "8f6cafbe-34c3-4c96-b53b-47c798297e79", request.Cookies()[0].Value)
assert.NoError(t, request.ParseForm())

assert.Equal(t, "some-login", request.Form.Get("username"))
assert.Equal(t, "Sign in", request.Form.Get("signInSubmitButton"))
assert.Equal(t, "some-password", request.Form.Get("password"))
assert.Equal(t, "8f6cafbe-34c3-4c96-b53b-47c798297e79", request.Form.Get("_csrf"))
return &http.Response{
StatusCode: http.StatusFound,
}, nil
})

assert.NoError(t, ct.Execute())
})

t.Run("fail get", func(t *testing.T) {
cl := NewMockhttpClient(gomock.NewController(t))

targetURL := "https://example.auth.us-east-2.amazoncognito.com/login?client_id=example&redirect_uri=https%3A%" +
"2F%2Fexample-redirect.com%2Fvcs%2Foidc%2Fredirect&response_type=code&" +
"state=9bc93ec1-7bdd-4084-8948-299ef35adab8"

ct := consent.NewCognito(
cl,
[]*http.Cookie{
{
Name: "XSRF-TOKEN",
Value: "abcd",
},
},
targetURL,
"some-login",
"some-password",
)

cl.EXPECT().Do(gomock.Any()).DoAndReturn(func(request *http.Request) (*http.Response, error) {
assert.Equal(t, http.MethodGet, request.Method)
assert.Equal(t, targetURL, request.URL.String())

return nil, errors.New("some error")
})

assert.ErrorContains(t, ct.Execute(), "some error")
})

t.Run("missing csrf", func(t *testing.T) {
cl := NewMockhttpClient(gomock.NewController(t))

targetURL := "https://example.auth.us-east-2.amazoncognito.com/login?client_id=example&redirect_uri=https%3A%" +
"2F%2Fexample-redirect.com%2Fvcs%2Foidc%2Fredirect&response_type=code&" +
"state=9bc93ec1-7bdd-4084-8948-299ef35adab8"

ct := consent.NewCognito(
cl,
nil,
targetURL,
"some-login",
"some-password",
)

cl.EXPECT().Do(gomock.Any()).DoAndReturn(func(request *http.Request) (*http.Response, error) {
return &http.Response{}, nil
})

assert.ErrorContains(t, ct.Execute(), "XSRF-TOKEN cookie not found")
})

t.Run("fail post", func(t *testing.T) {
cl := NewMockhttpClient(gomock.NewController(t))

targetURL := "https://example.auth.us-east-2.amazoncognito.com/login?client_id=example&redirect_uri=https%3A%" +
"2F%2Fexample-redirect.com%2Fvcs%2Foidc%2Fredirect&response_type=code&" +
"state=9bc93ec1-7bdd-4084-8948-299ef35adab8"

ct := consent.NewCognito(
cl,
[]*http.Cookie{
{
Name: "XSRF-TOKEN",
Value: "abcd",
},
},
targetURL,
"some-login",
"some-password",
)

cl.EXPECT().Do(gomock.Any()).DoAndReturn(func(request *http.Request) (*http.Response, error) {
return &http.Response{}, nil
})

cl.EXPECT().Do(gomock.Any()).DoAndReturn(func(request *http.Request) (*http.Response, error) {
return nil, errors.New("post failed")
})

assert.ErrorContains(t, ct.Execute(), "post failed")
})

t.Run("fail invalid status code", func(t *testing.T) {
cl := NewMockhttpClient(gomock.NewController(t))

targetURL := "https://example.auth.us-east-2.amazoncognito.com/login?client_id=example&redirect_uri=https%3A%" +
"2F%2Fexample-redirect.com%2Fvcs%2Foidc%2Fredirect&response_type=code&" +
"state=9bc93ec1-7bdd-4084-8948-299ef35adab8"

ct := consent.NewCognito(
cl,
[]*http.Cookie{
{
Name: "XSRF-TOKEN",
Value: "abcd",
},
},
targetURL,
"some-login",
"some-password",
)

cl.EXPECT().Do(gomock.Any()).DoAndReturn(func(request *http.Request) (*http.Response, error) {
return &http.Response{}, nil
})

cl.EXPECT().Do(gomock.Any()).DoAndReturn(func(request *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusMultiStatus,
Body: io.NopCloser(strings.NewReader(`some random text`)),
}, nil
})

assert.ErrorContains(t, ct.Execute(), "unexpected status code from post cognito. 207 with body some random text")
})
}
14 changes: 14 additions & 0 deletions component/wallet-cli/pkg/walletrunner/consent/interfaces.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
Copyright Avast Software. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package consent

import "net/http"

//go:generate mockgen -destination interfaces_mocks_test.go -package consent_test -source=interfaces.go
type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}
Loading