Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: passaccess_token tocoder_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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
kylecarbs merged 1 commit intomainfromaccessgitauth
Mar 22, 2023
Merged
Show file tree
Hide file tree
Changes fromall 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 deletionscli/create_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand Up@@ -836,31 +833,3 @@ func createTestParseResponseWithDefault(defaultValue string) []*proto.Parse_Resp
},
}}
}

typeoauth2Configstruct{}

func (*oauth2Config)AuthCodeURL(statestring,_...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{}
}

typeoauth2TokenSourcestruct{}

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 deletionscoderd/coderd.go
View file
Open in desktop
Original file line numberDiff line numberDiff 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:=rangeapi.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 deletionscoderd/gitauth/config.go
View file
Open in desktop
Original file line numberDiff line numberDiff 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 {
ValidateURLstring
}

// 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.
ifc.NoRefresh&&gitAuthLink.OAuthExpiry.Before(database.Now()) {
returngitAuthLink,false,nil
}

token,err:=c.TokenSource(ctx,&oauth2.Token{
AccessToken:gitAuthLink.OAuthAccessToken,
RefreshToken:gitAuthLink.OAuthRefreshToken,
Expiry:gitAuthLink.OAuthExpiry,
}).Token()
iferr!=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.
returngitAuthLink,false,nil
}

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

iftoken.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,
})
iferr!=nil {
returngitAuthLink,false,xerrors.Errorf("update git auth link: %w",err)
}
}
returngitAuthLink,true,nil
}

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

// ConvertConfig converts the SDK configuration entry format
// to the parsed and ready-to-consume in coderd provider type.
funcConvertConfig(entries []codersdk.GitAuthConfig,accessURL*url.URL) ([]*Config,error) {
Expand Down
107 changes: 107 additions & 0 deletionscoderd/gitauth/config_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff 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"
)

funcTestRefreshToken(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) {
returnnil,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(chanstruct{})
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)
})
}

funcTestConvertYAML(t*testing.T) {
t.Parallel()
for_,tc:=range []struct {
Expand Down
29 changes: 3 additions & 26 deletionscoderd/httpmw/apikey_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff 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"
)

funcrandomAPIKeyParts() (idstring,secretstring) {
Expand DownExpand 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) {
returnoauthToken,nil
}),
Github:&testutil.OAuth2Config{
Token:oauthToken,
},
},
RedirectToLogin:false,
Expand DownExpand Up@@ -597,25 +596,3 @@ func TestAPIKey(t *testing.T) {
require.Equal(t,sentAPIKey.LoginType,gotAPIKey.LoginType)
})
}

typeoauth2Configstruct {
tokenSourceoauth2TokenSource
}

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

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

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

typeoauth2TokenSourcefunc() (*oauth2.Token,error)

func (ooauth2TokenSource)Token() (*oauth2.Token,error) {
returno()
}
Loading

[8]ページ先頭

©2009-2025 Movatter.jp