* feat: GCP authentication
Add authentication support for:
- authentication with service account key
- authentication with impersonating service account key
- authentication with application default credentials which are read from the environment
A HTTP client with a token set will be returned and used for authentication with all clients. for example
```
gcpClient, err := gcpConfig.GetClient(ctx)
if err != nil {
log.Fatalf("Failed to get client: %v", err)
}
client, err := computeCloud.NewInstancesRESTClient(ctx, option.WithHTTPClient(gcpClient))
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
```
80 lines
1.7 KiB
Go
80 lines
1.7 KiB
Go
// Copyright (c) HashiCorp, Inc.
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
package credential
|
|
|
|
import (
|
|
"errors"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestNewGCPCredentialPersistedState(t *testing.T) {
|
|
staticTime := time.Now()
|
|
|
|
cases := []struct {
|
|
name string
|
|
opts []Option
|
|
expected *PersistedState
|
|
expectedErr string
|
|
}{
|
|
{
|
|
name: "error",
|
|
opts: []Option{
|
|
func(s *Options) error {
|
|
return errors.New("option error")
|
|
},
|
|
},
|
|
expectedErr: "option error",
|
|
},
|
|
{
|
|
name: "with credentials config",
|
|
opts: []Option{
|
|
WithCredentialsConfig(
|
|
&Config{
|
|
ProjectId: "test-project",
|
|
ClientEmail: "test-email",
|
|
},
|
|
),
|
|
},
|
|
expected: &PersistedState{
|
|
CredentialsConfig: &Config{
|
|
ProjectId: "test-project",
|
|
ClientEmail: "test-email",
|
|
},
|
|
},
|
|
},
|
|
{
|
|
name: "rotation time",
|
|
opts: []Option{
|
|
WithCredsLastRotatedTime(staticTime),
|
|
},
|
|
expected: &PersistedState{
|
|
CredsLastRotatedTime: staticTime,
|
|
},
|
|
},
|
|
}
|
|
|
|
for _, tc := range cases {
|
|
tc := tc
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
require := require.New(t)
|
|
actual, err := NewPersistedState(tc.opts...)
|
|
if tc.expectedErr != "" {
|
|
require.EqualError(err, tc.expectedErr)
|
|
return
|
|
}
|
|
|
|
require.NoError(err)
|
|
require.Equal(tc.expected.CredsLastRotatedTime, actual.CredsLastRotatedTime)
|
|
if tc.expected.CredentialsConfig != nil {
|
|
require.NotNil(actual.CredentialsConfig)
|
|
require.Equal(tc.expected.CredentialsConfig.ProjectId, actual.CredentialsConfig.ProjectId)
|
|
require.Equal(tc.expected.CredentialsConfig.ClientEmail, actual.CredentialsConfig.ClientEmail)
|
|
}
|
|
})
|
|
}
|
|
}
|