Skip to content

feat: pass access_token to coder_git_auth resource #6713

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

Merged
merged 1 commit into from
Mar 22, 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
33 changes: 1 addition & 32 deletions cli/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,16 @@ import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"regexp"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"

"github.com/coder/coder/cli/clitest"
"github.com/coder/coder/coderd/coderdtest"
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/coderd/gitauth"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/provisioner/echo"
Expand Down Expand Up @@ -768,7 +765,7 @@ func TestCreateWithGitAuth(t *testing.T) {

client := coderdtest.New(t, &coderdtest.Options{
GitAuthConfigs: []*gitauth.Config{{
OAuth2Config: &oauth2Config{},
OAuth2Config: &testutil.OAuth2Config{},
ID: "github",
Regex: regexp.MustCompile(`github\.com`),
Type: codersdk.GitProviderGitHub,
Expand Down Expand Up @@ -836,31 +833,3 @@ func createTestParseResponseWithDefault(defaultValue string) []*proto.Parse_Resp
},
}}
}

type oauth2Config struct{}

func (*oauth2Config) AuthCodeURL(state string, _ ...oauth2.AuthCodeOption) string {
return "/?state=" + url.QueryEscape(state)
}

func (*oauth2Config) Exchange(context.Context, string, ...oauth2.AuthCodeOption) (*oauth2.Token, error) {
return &oauth2.Token{
AccessToken: "token",
RefreshToken: "refresh",
Expiry: database.Now().Add(time.Hour),
}, nil
}

func (*oauth2Config) TokenSource(context.Context, *oauth2.Token) oauth2.TokenSource {
return &oauth2TokenSource{}
}

type oauth2TokenSource struct{}

func (*oauth2TokenSource) Token() (*oauth2.Token, error) {
return &oauth2.Token{
AccessToken: "token",
RefreshToken: "refresh",
Expiry: database.Now().Add(time.Hour),
}, nil
}
6 changes: 1 addition & 5 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -831,18 +831,14 @@ func (api *API) CreateInMemoryProvisionerDaemon(ctx context.Context, debounce ti

mux := drpcmux.New()

gitAuthProviders := make([]string, 0, len(api.GitAuthConfigs))
for _, cfg := range api.GitAuthConfigs {
gitAuthProviders = append(gitAuthProviders, cfg.ID)
}
err = proto.DRPCRegisterProvisionerDaemon(mux, &provisionerdserver.Server{
AccessURL: api.AccessURL,
ID: daemon.ID,
OIDCConfig: api.OIDCConfig,
Database: api.Database,
Pubsub: api.Pubsub,
Provisioners: daemon.Provisioners,
GitAuthProviders: gitAuthProviders,
GitAuthConfigs: api.GitAuthConfigs,
Telemetry: api.Telemetry,
Tags: tags,
QuotaCommitter: &api.QuotaCommitter,
Expand Down
75 changes: 75 additions & 0 deletions coderd/gitauth/config.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package gitauth

import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"regexp"

"golang.org/x/oauth2"
"golang.org/x/xerrors"

"github.com/coder/coder/coderd/database"
"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/coderd/httpmw"
"github.com/coder/coder/codersdk"
Expand All @@ -34,6 +38,77 @@ type Config struct {
ValidateURL string
}

// RefreshToken automatically refreshes the token if expired and permitted.
// It returns the token and a bool indicating if the token was refreshed.
func (c *Config) RefreshToken(ctx context.Context, db database.Store, gitAuthLink database.GitAuthLink) (database.GitAuthLink, bool, error) {
// If the token is expired and refresh is disabled, we prompt
// the user to authenticate again.
if c.NoRefresh && gitAuthLink.OAuthExpiry.Before(database.Now()) {
return gitAuthLink, false, nil
}

token, err := c.TokenSource(ctx, &oauth2.Token{
AccessToken: gitAuthLink.OAuthAccessToken,
RefreshToken: gitAuthLink.OAuthRefreshToken,
Expiry: gitAuthLink.OAuthExpiry,
}).Token()
if err != nil {
// Even if the token fails to be obtained, we still return false because
// we aren't trying to surface an error, we're just trying to obtain a valid token.
return gitAuthLink, false, nil
}

if c.ValidateURL != "" {
valid, err := c.ValidateToken(ctx, token.AccessToken)
if err != nil {
return gitAuthLink, false, xerrors.Errorf("validate git auth token: %w", err)
}
if !valid {
// The token is no longer valid!
return gitAuthLink, false, nil
}
}

if token.AccessToken != gitAuthLink.OAuthAccessToken {
// Update it
gitAuthLink, err = db.UpdateGitAuthLink(ctx, database.UpdateGitAuthLinkParams{
ProviderID: c.ID,
UserID: gitAuthLink.UserID,
UpdatedAt: database.Now(),
OAuthAccessToken: token.AccessToken,
OAuthRefreshToken: token.RefreshToken,
OAuthExpiry: token.Expiry,
})
if err != nil {
return gitAuthLink, false, xerrors.Errorf("update git auth link: %w", err)
}
}
return gitAuthLink, true, nil
}

// ValidateToken ensures the Git token provided is valid!
func (c *Config) ValidateToken(ctx context.Context, token string) (bool, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.ValidateURL, nil)
if err != nil {
return false, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
res, err := http.DefaultClient.Do(req)
if err != nil {
return false, err
}
defer res.Body.Close()
if res.StatusCode == http.StatusUnauthorized {
// The token is no longer valid!
return false, nil
}
if res.StatusCode != http.StatusOK {
data, _ := io.ReadAll(res.Body)
return false, xerrors.Errorf("status %d: body: %s", res.StatusCode, data)
}
return true, nil
}

// ConvertConfig converts the SDK configuration entry format
// to the parsed and ready-to-consume in coderd provider type.
func ConvertConfig(entries []codersdk.GitAuthConfig, accessURL *url.URL) ([]*Config, error) {
Expand Down
107 changes: 107 additions & 0 deletions coderd/gitauth/config_test.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,122 @@
package gitauth_test

import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"

"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
"golang.org/x/xerrors"

"github.com/coder/coder/coderd/database"
"github.com/coder/coder/coderd/database/dbfake"
"github.com/coder/coder/coderd/database/dbgen"
"github.com/coder/coder/coderd/gitauth"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/testutil"
)

func TestRefreshToken(t *testing.T) {
t.Parallel()
t.Run("FalseIfNoRefresh", func(t *testing.T) {
t.Parallel()
config := &gitauth.Config{
NoRefresh: true,
}
_, refreshed, err := config.RefreshToken(context.Background(), nil, database.GitAuthLink{
OAuthExpiry: time.Time{},
})
require.NoError(t, err)
require.False(t, refreshed)
})
t.Run("FalseIfTokenSourceFails", func(t *testing.T) {
t.Parallel()
config := &gitauth.Config{
OAuth2Config: &testutil.OAuth2Config{
TokenSourceFunc: func() (*oauth2.Token, error) {
return nil, xerrors.New("failure")
},
},
}
_, refreshed, err := config.RefreshToken(context.Background(), nil, database.GitAuthLink{})
require.NoError(t, err)
require.False(t, refreshed)
})
t.Run("ValidateServerError", func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Failure"))
}))
config := &gitauth.Config{
OAuth2Config: &testutil.OAuth2Config{},
ValidateURL: srv.URL,
}
_, _, err := config.RefreshToken(context.Background(), nil, database.GitAuthLink{})
require.ErrorContains(t, err, "Failure")
})
t.Run("ValidateFailure", func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Not permitted"))
}))
config := &gitauth.Config{
OAuth2Config: &testutil.OAuth2Config{},
ValidateURL: srv.URL,
}
_, refreshed, err := config.RefreshToken(context.Background(), nil, database.GitAuthLink{})
require.NoError(t, err)
require.False(t, refreshed)
})
t.Run("ValidateNoUpdate", func(t *testing.T) {
t.Parallel()
validated := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
close(validated)
}))
accessToken := "testing"
config := &gitauth.Config{
OAuth2Config: &testutil.OAuth2Config{
Token: &oauth2.Token{
AccessToken: accessToken,
},
},
ValidateURL: srv.URL,
}
_, valid, err := config.RefreshToken(context.Background(), nil, database.GitAuthLink{
OAuthAccessToken: accessToken,
})
require.NoError(t, err)
require.True(t, valid)
<-validated
})
t.Run("Updates", func(t *testing.T) {
t.Parallel()
config := &gitauth.Config{
ID: "test",
OAuth2Config: &testutil.OAuth2Config{
Token: &oauth2.Token{
AccessToken: "updated",
},
},
}
db := dbfake.New()
link := dbgen.GitAuthLink(t, db, database.GitAuthLink{
ProviderID: config.ID,
OAuthAccessToken: "initial",
})
_, valid, err := config.RefreshToken(context.Background(), db, link)
require.NoError(t, err)
require.True(t, valid)
})
}

func TestConvertYAML(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
Expand Down
29 changes: 3 additions & 26 deletions coderd/httpmw/apikey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/coder/coder/coderd/httpmw"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/cryptorand"
"github.com/coder/coder/testutil"
)

func randomAPIKeyParts() (id string, secret string) {
Expand Down Expand Up @@ -462,10 +463,8 @@ func TestAPIKey(t *testing.T) {
httpmw.ExtractAPIKeyMW(httpmw.ExtractAPIKeyConfig{
DB: db,
OAuth2Configs: &httpmw.OAuth2Configs{
Github: &oauth2Config{
tokenSource: oauth2TokenSource(func() (*oauth2.Token, error) {
return oauthToken, nil
}),
Github: &testutil.OAuth2Config{
Token: oauthToken,
},
},
RedirectToLogin: false,
Expand Down Expand Up @@ -597,25 +596,3 @@ func TestAPIKey(t *testing.T) {
require.Equal(t, sentAPIKey.LoginType, gotAPIKey.LoginType)
})
}

type oauth2Config struct {
tokenSource oauth2TokenSource
}

func (o *oauth2Config) TokenSource(context.Context, *oauth2.Token) oauth2.TokenSource {
return o.tokenSource
}

func (*oauth2Config) AuthCodeURL(string, ...oauth2.AuthCodeOption) string {
return ""
}

func (*oauth2Config) Exchange(context.Context, string, ...oauth2.AuthCodeOption) (*oauth2.Token, error) {
return &oauth2.Token{}, nil
}

type oauth2TokenSource func() (*oauth2.Token, error)

func (o oauth2TokenSource) Token() (*oauth2.Token, error) {
return o()
}
Loading