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

Add auth tests #522

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
61 changes: 43 additions & 18 deletions internal/http/authenticator.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,22 @@ var (
ErrTokenExpired = errors.New("oauth2: token expired and refresh token is not set")
)

type TokenStore interface {
storeAccessToken(token *oauth2.Token) error
readAccessToken() (*oauth2.Token, error)
}

type DeviceAuthenticator interface {
DeviceAuth(ctx context.Context, opts ...oauth2.AuthCodeOption) (*oauth2.DeviceAuthResponse, error)
DeviceAccessToken(ctx context.Context, da *oauth2.DeviceAuthResponse, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error)
Client(ctx context.Context, t *oauth2.Token) *http.Client
}

type UserAuthenticator struct {
conf *oauth2.Config
autoLogin bool
conf DeviceAuthenticator
ts TokenStore
autoLogin bool
popBrowser bool
}

func NewUserAuthenticator(clientID, idpURL string, autoLogin bool) UserAuthenticator {
Expand All @@ -34,8 +47,10 @@ func NewUserAuthenticator(clientID, idpURL string, autoLogin bool) UserAuthentic
Scopes: []string{"openid profile"},
}
return UserAuthenticator{
conf: conf,
autoLogin: autoLogin,
conf: conf,
ts: newTokenStore(),
autoLogin: autoLogin,
popBrowser: true,
}
}

Expand All @@ -44,7 +59,7 @@ func (g *UserAuthenticator) Login(ctx context.Context) error {
if err != nil {
return err
}
return storeAccessToken(token)
return g.ts.storeAccessToken(token)
}

func (g *UserAuthenticator) login(ctx context.Context) (*oauth2.Token, error) {
Expand All @@ -53,23 +68,24 @@ func (g *UserAuthenticator) login(ctx context.Context) (*oauth2.Token, error) {
return nil, err
}
fmt.Printf("please enter code %s at %s\n", response.UserCode, response.VerificationURIComplete)
err = browser.OpenURL(response.VerificationURIComplete)
if err != nil {
return nil, err
if g.popBrowser {
err = browser.OpenURL(response.VerificationURIComplete)
if err != nil {
return nil, err
}
}

return g.conf.DeviceAccessToken(ctx, response)
}

func (g *UserAuthenticator) Access(ctx context.Context) (*http.Client, error) {
token, err := readAccessToken()
token, err := g.ts.readAccessToken()
if err != nil {
if g.autoLogin {
token, err = g.login(ctx)
if err != nil {
return nil, fmt.Errorf("auto login failed: %w: %w", ErrLoginRequired, err)
}
err = storeAccessToken(token)
err = g.ts.storeAccessToken(token)
if err != nil {
return nil, err
}
Expand All @@ -82,7 +98,7 @@ func (g *UserAuthenticator) Access(ctx context.Context) (*http.Client, error) {
if err != nil {
return nil, fmt.Errorf("auto login failed: %w: %w", ErrLoginRequired, err)
}
err = storeAccessToken(token)
err = g.ts.storeAccessToken(token)
if err != nil {
return nil, err
}
Expand All @@ -96,8 +112,18 @@ func tokenFilePath() string {
return filepath.Join(os.Getenv("HOME"), tokenFile)
}

func readAccessToken() (*oauth2.Token, error) {
data, err := os.ReadFile(tokenFilePath())
type tokenStore struct {
tokenFilePath string
}

func newTokenStore() *tokenStore {
return &tokenStore{
tokenFilePath: tokenFilePath(),
}
}

func (ts *tokenStore) readAccessToken() (*oauth2.Token, error) {
data, err := os.ReadFile(ts.tokenFilePath)
if err != nil {
return nil, err
}
Expand All @@ -109,17 +135,16 @@ func readAccessToken() (*oauth2.Token, error) {
return &token, nil
}

func storeAccessToken(token *oauth2.Token) error {
func (ts *tokenStore) storeAccessToken(token *oauth2.Token) error {
accessToken, err := json.Marshal(token)
if err != nil {
return err
}
p := tokenFilePath()
dir := filepath.Dir(p)
dir := filepath.Dir(ts.tokenFilePath)
if err := os.MkdirAll(dir, 0700); err != nil {
return err
}
f, err := os.Create(p)
f, err := os.Create(ts.tokenFilePath)
if err != nil {
return err
}
Expand Down
152 changes: 152 additions & 0 deletions internal/http/authenticator_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package http

import (
"context"
"fmt"
"net/http"
"testing"
"time"

"golang.org/x/oauth2"
)

func TestAccessNoTokenCallsLoginAndStoresToken(t *testing.T) {
httpAuth := HttpAuth{
DeviceResp: &oauth2.DeviceAuthResponse{
UserCode: "YOLO",
VerificationURIComplete: "localhost",
},
}
dummyStore := DummyStore{
token: nil,
}
ua := UserAuthenticator{
conf: &httpAuth,
ts: &dummyStore,
autoLogin: true,
popBrowser: false,
}

client, err := ua.Access(context.Background())
if err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd recommend to use require.NoError instead with a msg if wanted.

t.Fatal(err)
}
if client == nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and assert.NotNil etc for the tests below

t.Fatal("client is nil")
}
if dummyStore.tokenRead == false {
t.Fatal("expected a read of the token")
}
if dummyStore.tokenStored == false {
t.Fatal("expected the token to be stored")
}
}

func TestAccessInvalidTokenCallsLoginAndStoresToken(t *testing.T) {
httpAuth := HttpAuth{
DeviceResp: &oauth2.DeviceAuthResponse{
UserCode: "YOLO",
VerificationURIComplete: "localhost",
},
}
dummyStore := DummyStore{
token: &oauth2.Token{
AccessToken: "",
},
}
ua := UserAuthenticator{
conf: &httpAuth,
ts: &dummyStore,
autoLogin: true,
popBrowser: false,
}

client, err := ua.Access(context.Background())
if err != nil {
t.Fatal(err)
}
if client == nil {
t.Fatal("client is nil")
}
if dummyStore.tokenRead == false {
t.Fatal("expected a read of the token")
}
if dummyStore.tokenStored == false {
t.Fatal("expected the token to be stored")
}
}

func TestAccessValidTokenNoLogin(t *testing.T) {
httpAuth := HttpAuth{
DeviceResp: &oauth2.DeviceAuthResponse{
UserCode: "YOLO",
VerificationURIComplete: "localhost",
},
}
dummyStore := DummyStore{
token: &oauth2.Token{
AccessToken: "ACCESSTOKEN",
Expiry: time.Now().Add(1000 * time.Minute),
},
}
ua := UserAuthenticator{
conf: &httpAuth,
ts: &dummyStore,
autoLogin: true,
popBrowser: false,
}

client, err := ua.Access(context.Background())
if err != nil {
t.Fatal(err)
}
if client == nil {
t.Fatal("client is nil")
}
if !dummyStore.tokenRead {
t.Fatal("expected a read of the token")
}
if dummyStore.tokenStored {
t.Fatal("did not expect the token to be stored")
}
if httpAuth.loginCalled {
t.Fatal("did not expect login to be called")
}
}

type HttpAuth struct {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason you're using a mocking framework?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you prefer this approach then I am fine xD

DeviceResp *oauth2.DeviceAuthResponse
token *oauth2.Token
loginCalled bool
}

func (ha *HttpAuth) DeviceAuth(ctx context.Context, opts ...oauth2.AuthCodeOption) (*oauth2.DeviceAuthResponse, error) {
ha.loginCalled = true
return ha.DeviceResp, nil
}

func (ha *HttpAuth) DeviceAccessToken(ctx context.Context, da *oauth2.DeviceAuthResponse, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error) {
return ha.token, nil
}

func (ha *HttpAuth) Client(ctx context.Context, t *oauth2.Token) *http.Client {
return http.DefaultClient
}

type DummyStore struct {
token *oauth2.Token
tokenStored bool
tokenRead bool
}

func (ds *DummyStore) storeAccessToken(token *oauth2.Token) error {
ds.tokenStored = true
return nil
}
func (ds *DummyStore) readAccessToken() (*oauth2.Token, error) {
ds.tokenRead = true
if ds.token == nil {
return nil, fmt.Errorf("no token found")
}
return ds.token, nil
}
Loading