Skip to content

feat(token): expose source of token #32

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
Dec 28, 2024
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
5 changes: 4 additions & 1 deletion token/internal/github/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,8 @@ func (p *GHProvider) Token() (*shared.Token, error) {
return nil, fmt.Errorf("no token returned from 'gh auth token'")
}

return &shared.Token{Value: token}, nil
return &shared.Token{
Source: "gh",
Value: token,
}, nil
}
11 changes: 7 additions & 4 deletions token/internal/github/github_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ import (
"gotest.tools/v3/assert"
)

// TestGhProviderTrimsSpace ensures that the token returned by the
// ghProvider is trimmed of any leading or trailing whitespace.
func TestGhProviderTrimsSpace(t *testing.T) {
// TestTrimsSpace ensures that the token returned by the ghProvider is
// trimmed of any leading or trailing whitespace.
func TestTrimsSpace(t *testing.T) {
p := &github.GHProvider{}

cmdexec.UseMockExecutor(t, cmdexec.NewMockExecutor(&cmdexec.MockCommand{
Expand All @@ -22,5 +22,8 @@ func TestGhProviderTrimsSpace(t *testing.T) {

got, err := p.Token()
assert.NilError(t, err)
assert.DeepEqual(t, &token.Token{Value: "token"}, got)
assert.DeepEqual(t, &token.Token{
Source: "gh",
Value: "token",
}, got)
}
5 changes: 4 additions & 1 deletion token/internal/gitlab/gitlab.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,5 +74,8 @@ func (p *GlabProvider) Token() (*shared.Token, error) {
return nil, fmt.Errorf("no token returned")
}

return &shared.Token{Value: token}, nil
return &shared.Token{
Source: "glab",
Value: token,
}, nil
}
33 changes: 32 additions & 1 deletion token/internal/gitlab/gitlab_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,37 @@ package gitlab
import (
"testing"

"github.com/jaredallard/cmdexec"
"github.com/jaredallard/vcs/token/internal/shared"
"gotest.tools/v3/assert"
)

// TestTrimsSpace ensures that the token returned by the glabProvider is
// trimmed of any leading or trailing whitespace.
func TestTrimsSpace(t *testing.T) {
p := &GlabProvider{}

cmdexec.UseMockExecutor(t, cmdexec.NewMockExecutor(
&cmdexec.MockCommand{
Name: "glab",
Args: []string{"config", "get", "-g", "host"},
Stdout: []byte("gitlab.com\n"),
},
&cmdexec.MockCommand{
Name: "glab",
Args: []string{"config", "get", "-g", "token", "-h", "gitlab.com"},
Stdout: []byte(" token\n"),
},
))

got, err := p.Token()
assert.NilError(t, err)
assert.DeepEqual(t, &shared.Token{
Source: "glab",
Value: "token",
}, got)
}

// TestCanGetJobTokenFromEnv ensures that a job token can be read from
// the environment and that it has a type of TokenTypeJob.
func TestCanGetJobTokenFromEnv(t *testing.T) {
Expand All @@ -16,5 +43,9 @@ func TestCanGetJobTokenFromEnv(t *testing.T) {

got, err := p.Token()
assert.NilError(t, err, "expected no error")
assert.DeepEqual(t, &shared.Token{Value: "im-a-token", Type: TokenTypeJob}, got)
assert.DeepEqual(t, &shared.Token{
Source: "environment variable (CI_JOB_TOKEN)",
Value: "im-a-token",
Type: TokenTypeJob,
}, got)
}
5 changes: 3 additions & 2 deletions token/internal/shared/env_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ func (p *EnvProvider) Token() (*Token, error) {
for _, env := range p.EnvVars {
if token := os.Getenv(env.Name); token != "" {
return &Token{
Value: token,
Type: env.Type,
Value: token,
Source: fmt.Sprintf("environment variable (%s)", env.Name),
Type: env.Type,
}, nil
}
}
Expand Down
9 changes: 8 additions & 1 deletion token/internal/shared/shared.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,18 @@ import (
// Do not use the 'shared.Token' type, instead use [token.Token] which
// is an alias to this type.
type Token struct {
// FetchedAt is the time that the token was fetched at.
// FetchedAt is the time that the token was fetched at. This does not
// need to be set by providers as it is set by the [token.Fetch]
// function.
FetchedAt time.Time

// Value is the token value.
Value string

// Source is the source of the token, this is set depending on the
// provider that provided the token (e.g., `gh` for the Github CLI).
Source string

// Type is the type of the token, this is set depending on the
// provider that provided the token.
Type string
Expand Down Expand Up @@ -64,6 +70,7 @@ func (t *Token) String() string {
func (t *Token) Clone() *Token {
return &Token{
FetchedAt: t.FetchedAt,
Source: t.Source,
Value: t.Value,
Type: t.Type,
}
Expand Down
70 changes: 66 additions & 4 deletions token/internal/shared/shared_test.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,79 @@
package shared_test

import (
"context"
"fmt"
"testing"
"time"

"github.com/jaredallard/cmdexec"
"github.com/jaredallard/vcs"
"github.com/jaredallard/vcs/token"
"github.com/jaredallard/vcs/token/internal/shared"
"gotest.tools/v3/assert"
)

var bfalse = false

// clearHostToken clears the token for the host when fetching a Github
// token.
func clearHostToken(t *testing.T, newValue string) {
cmdexec.UseMockExecutor(t, cmdexec.NewMockExecutor(&cmdexec.MockCommand{
Name: "gh",
Args: []string{"auth", "token"},
Stdout: []byte("\n"),
}))
t.Setenv("GITHUB_TOKEN", newValue)
}

func TestEnvProviderReadsCorrectEnvVar(t *testing.T) {
t.Setenv("GITHUB_TOKEN", "token")
t.Setenv(t.Name(), "token")

p := &shared.EnvProvider{EnvVars: []shared.EnvVar{{Name: t.Name()}}}
tok, err := p.Token()
assert.NilError(t, err)
assert.DeepEqual(t, &shared.Token{
Source: fmt.Sprintf("environment variable (%s)", t.Name()),
Value: "token",
}, tok)
}

// TestCloneClonesAllAttributes ensures that Clone returns a new token
// with the same attributes as the original token.
func TestCloneClonesAllAttributes(t *testing.T) {
t.Setenv("GITHUB_TOKEN", time.Now().String())

originalToken, err := token.Fetch(context.Background(), vcs.ProviderGithub, false, &token.Options{
UseGlobalCache: &bfalse,
})
assert.NilError(t, err)
assert.Assert(t, originalToken != nil, "expected a token to be returned")

p := &shared.EnvProvider{EnvVars: []shared.EnvVar{{Name: "GITHUB_TOKEN"}}}
token, err := p.Token()
clone := originalToken.Clone()
assert.DeepEqual(t, originalToken, clone)
}

func TestStringRedacts(t *testing.T) {
clearHostToken(t, "token-xyz")

originalToken, err := token.Fetch(context.Background(), vcs.ProviderGithub, false, &token.Options{
UseGlobalCache: &bfalse,
})
assert.NilError(t, err)
assert.DeepEqual(t, &shared.Token{Value: "token"}, token)
assert.Assert(t, originalToken != nil, "expected a token to be returned")

assert.Equal(t, originalToken.String(), "toke*****", "expected token to be partially redacted")
}

func TestIsUnauthenticatedDetectsEmptyToken(t *testing.T) {
clearHostToken(t, "")

originalToken, err := token.Fetch(context.Background(), vcs.ProviderGithub, false, &token.Options{
AllowUnauthenticated: true,
UseGlobalCache: &bfalse,
})
assert.NilError(t, err)
assert.Assert(t, originalToken != nil, "expected a token to be returned")

assert.Assert(t, originalToken.IsUnauthenticated(), "expected token to be unauthenticated")
}
16 changes: 13 additions & 3 deletions token/token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ func TestCanGetToken(t *testing.T) {
authToken, err := token.Fetch(context.Background(), vcs.ProviderGithub, false)
assert.NilError(t, err)
assert.Assert(t, authToken != nil, "expected a token to be returned")
assert.DeepEqual(t, authToken, &token.Token{Value: os.Getenv("GITHUB_TOKEN")}, ignoreTime)
assert.DeepEqual(t, authToken, &token.Token{
Source: "environment variable (GITHUB_TOKEN)",
Value: os.Getenv("GITHUB_TOKEN"),
}, ignoreTime)
}

// TestCanGetCachedToken ensures that [token.Fetch] returns the same
Expand All @@ -38,12 +41,19 @@ func TestCanGetCachedToken(t *testing.T) {
originalToken, err := token.Fetch(context.Background(), vcs.ProviderGithub, false, &token.Options{UseGlobalCache: &bfalse})
assert.NilError(t, err)
assert.Assert(t, originalToken != nil, "expected a token to be returned")
assert.DeepEqual(t, originalToken, &token.Token{Value: os.Getenv("GITHUB_TOKEN")}, ignoreTime)
assert.DeepEqual(t, originalToken, &token.Token{
Source: "environment variable (GITHUB_TOKEN)",
Value: os.Getenv("GITHUB_TOKEN"),
}, ignoreTime)
assert.Equal(t, originalToken.FetchedAt.IsZero(), false) // should not be zero

// Fetch again, should return the same token.
newToken, err := token.Fetch(context.Background(), vcs.ProviderGithub, false)
assert.NilError(t, err)
assert.Assert(t, newToken != nil, "expected a token to be returned")
assert.DeepEqual(t, newToken, &token.Token{FetchedAt: originalToken.FetchedAt, Value: os.Getenv("GITHUB_TOKEN")})
assert.DeepEqual(t, newToken, &token.Token{
FetchedAt: originalToken.FetchedAt,
Source: "environment variable (GITHUB_TOKEN)",
Value: os.Getenv("GITHUB_TOKEN"),
})
}
Loading