-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(auth): add detect package (#8491)
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
Showing
38 changed files
with
2,741 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |
Oops, something went wrong.