Skip to content

Commit

Permalink
feat(auth): add detect package (#8491)
Browse files Browse the repository at this point in the history
The purpose of this package is to source credentials via ADC. It
is analogous to the oauth2/google package but is more limited,
currently. It does not provide helper constructors for creating
things like a compute credential and instead has a single
constructor that does it all. Because of this it is more has more
extensible options.

Purposefully missing from this package is support for external
accounts, but some documentation is there. This will come up in a
separate PR as that has a lot of extra code to review and I tried
to shrink the size of this commit as much as possible.

There are some TODOs in this commit that will be cleaned up in a
future commit that requires more refactoring.
  • Loading branch information
codyoss committed Aug 29, 2023
1 parent 48b08bf commit d977419
Show file tree
Hide file tree
Showing 38 changed files with 2,741 additions and 20 deletions.
3 changes: 1 addition & 2 deletions auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
Expand Down Expand Up @@ -300,7 +299,7 @@ func (tp tokenProvider2LO) Token(ctx context.Context) (*Token, error) {
return nil, fmt.Errorf("auth: cannot fetch token: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
body, err := internal.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("auth: cannot fetch token: %w", err)
}
Expand Down
4 changes: 2 additions & 2 deletions auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"

"cloud.google.com/go/auth/internal/jwt"
"github.com/google/go-cmp/cmp"
)

var fakePrivateKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
Expand Down Expand Up @@ -427,7 +427,7 @@ func TestConfigJWT2LO_AssertionPayload(t *testing.T) {
}
m := got.(map[string]interface{})
for v, k := range opts.PrivateClaims {
if !reflect.DeepEqual(m[v], k) {
if !cmp.Equal(m[v], k) {
t.Errorf("payload private claims key = %q: got %#v; want %#v", v, m[v], k)
}
}
Expand Down
87 changes: 87 additions & 0 deletions auth/detect/compute.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package detect

import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"strings"
"time"

"cloud.google.com/go/auth"
"cloud.google.com/go/compute/metadata"
)

var (
computeTokenMetadata = map[string]interface{}{
"auth.google.tokenSource": "compute-metadata",
"auth.google.serviceAccount": "default",
}
computeTokenURI = "instance/service-accounts/default/token"
)

// computeTokenProvider creates a [cloud.google.com/go/auth.TokenProvider] that
// uses the metadata service to retrieve tokens.
func computeTokenProvider(earlyExpiry time.Duration, scope ...string) auth.TokenProvider {
return auth.NewCachedTokenProvider(computeProvider{scopes: scope}, &auth.CachedTokenProviderOptions{
ExpireEarly: earlyExpiry,
})
}

// computeProvider fetches tokens from the google cloud metadata service.
type computeProvider struct {
scopes []string
}

type metadataTokenResp struct {
AccessToken string `json:"access_token"`
ExpiresInSec int `json:"expires_in"`
TokenType string `json:"token_type"`
}

func (cs computeProvider) Token(ctx context.Context) (*auth.Token, error) {
// TODO(codyoss): account may need to be configurable if we have a constructor for
// the provider.
tokenURI, err := url.Parse(computeTokenURI)
if err != nil {
return nil, err
}
if len(cs.scopes) > 0 {
v := url.Values{}
v.Set("scopes", strings.Join(cs.scopes, ","))
tokenURI.RawQuery = v.Encode()
}
tokenJSON, err := metadata.Get(tokenURI.String())
if err != nil {
return nil, err
}
var res metadataTokenResp
if err := json.NewDecoder(strings.NewReader(tokenJSON)).Decode(&res); err != nil {
return nil, fmt.Errorf("detect: invalid token JSON from metadata: %w", err)
}
if res.ExpiresInSec == 0 || res.AccessToken == "" {
return nil, errors.New("detect: incomplete token received from metadata")
}
return &auth.Token{
Value: res.AccessToken,
Type: res.TokenType,
Expiry: time.Now().Add(time.Duration(res.ExpiresInSec) * time.Second),
Metadata: computeTokenMetadata,
}, nil

}
51 changes: 51 additions & 0 deletions auth/detect/compute_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package detect

import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

const computeMetadataEnvVar = "GCE_METADATA_HOST"

func TestComputeTokenProvider(t *testing.T) {
scope := "https://www.googleapis.com/auth/bigquery"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.String(), computeTokenURI) {
t.Errorf("got %q, want %q", r.URL.String(), computeTokenURI)
}
if r.URL.Query().Get("scopes") != scope {
t.Errorf("got %q, want %q", r.URL.Query().Get("scopes"), scope)
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "token_type": "bearer", "expires_in": 86400}`))
}))
t.Setenv(computeMetadataEnvVar, strings.TrimPrefix(ts.URL, "http://"))
tp := computeTokenProvider(0, scope)
tok, err := tp.Token(context.Background())
if err != nil {
t.Fatal(err)
}
if want := "90d64460d14870c08c81352a05dedd3465940a7c"; tok.Value != want {
t.Errorf("got %q, want %q", tok.Value, want)
}
if want := "bearer"; tok.Type != want {
t.Errorf("got %q, want %q", tok.Value, want)
}
}

0 comments on commit d977419

Please sign in to comment.