Skip to content
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

feat(auth): add universe domain support to idtoken #11059

Merged
merged 30 commits into from
Jan 7, 2025
Merged
Show file tree
Hide file tree
Changes from 29 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
260aaaa
feat(auth): add universe domain support to idtoken
quartzmo Oct 29, 2024
06969bb
Merge branch 'main' into auth-idtoken-universe-domain
quartzmo Oct 30, 2024
2a8bf0b
use base creds universe_domain instead of UseIAMEndpoint flag
quartzmo Oct 30, 2024
285045c
add impersonate.IDTokenOptions.UniverseDomain
quartzmo Oct 30, 2024
5ec1a27
Merge branch 'main' into auth-idtoken-universe-domain
quartzmo Oct 30, 2024
17a8752
add universe domain tests to impersonate/idtoken_test.go
quartzmo Oct 30, 2024
8baddf9
fix idtoken_test
quartzmo Oct 30, 2024
599a9ce
Add idtoken.Options.UniverseDomain
quartzmo Oct 30, 2024
4bdb8fc
fix test error handling
quartzmo Oct 30, 2024
6af13c6
refactor idtoken_test.go
quartzmo Oct 31, 2024
3a4a039
fix idtoken_test.go
quartzmo Oct 31, 2024
eb264ce
update idtoken/idtoken_test.go
quartzmo Oct 31, 2024
111992e
refactor JSON request handling to internal
quartzmo Oct 31, 2024
00a963e
Merge branch 'main' into auth-idtoken-universe-domain
quartzmo Oct 31, 2024
11139ff
small fixes per codyoss
quartzmo Oct 31, 2024
95ebfa9
refactor idtoken RPC duplication to internal
quartzmo Oct 31, 2024
8da4df3
fix vet
quartzmo Oct 31, 2024
f35e9ee
Merge branch 'main' into auth-idtoken-universe-domain
quartzmo Oct 31, 2024
3be9480
fix docs for vet
quartzmo Oct 31, 2024
bfce866
Merge branch 'main' into auth-idtoken-universe-domain
quartzmo Nov 6, 2024
24f58a4
fix credentials/idtoken/file.go
quartzmo Nov 7, 2024
e44f7ba
Merge branch 'main' into auth-idtoken-universe-domain
quartzmo Jan 3, 2025
3e5e31e
add logging support
quartzmo Jan 3, 2025
deefd9d
fix header year
quartzmo Jan 3, 2025
4d0a43a
Merge branch 'main' into auth-idtoken-universe-domain
quartzmo Jan 3, 2025
050fffc
Merge branch 'main' into auth-idtoken-universe-domain
quartzmo Jan 6, 2025
8a5c39c
remove unused func
quartzmo Jan 6, 2025
221739c
rename IDTokenOptions to IDTokenIAMOptions
quartzmo Jan 6, 2025
0e67649
Merge branch 'main' into auth-idtoken-universe-domain
quartzmo Jan 6, 2025
80f0aa4
refactor to IDTokenIAMOptions as TokenProvider
quartzmo Jan 6, 2025
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
81 changes: 54 additions & 27 deletions auth/credentials/idtoken/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,38 +44,29 @@ func credsFromDefault(creds *auth.Credentials, opts *Options) (*auth.Credentials
if err != nil {
return nil, err
}
opts2LO := &auth.Options2LO{
Email: f.ClientEmail,
PrivateKey: []byte(f.PrivateKey),
PrivateKeyID: f.PrivateKeyID,
TokenURL: f.TokenURL,
UseIDToken: true,
Logger: internallog.New(opts.Logger),
}
if opts2LO.TokenURL == "" {
opts2LO.TokenURL = jwtTokenURL
}

var customClaims map[string]interface{}
if opts != nil {
customClaims = opts.CustomClaims
}
if customClaims == nil {
customClaims = make(map[string]interface{})
}
customClaims["target_audience"] = opts.Audience

opts2LO.PrivateClaims = customClaims
tp, err := auth.New2LOTokenProvider(opts2LO)
if err != nil {
return nil, err
var tp auth.TokenProvider
if resolveUniverseDomain(f) == internal.DefaultUniverseDomain {
tp, err = new2LOTokenProvider(f, opts)
if err != nil {
return nil, err
}
} else {
// In case of non-GDU universe domain, use IAM.
tp = iamIDTokenProvider{
client: opts.client(),
// Pass the credentials universe domain to configure the endpoint.
universeDomain: auth.CredentialsPropertyFunc(creds.UniverseDomain),
signerEmail: f.ClientEmail,
audience: opts.Audience,
logger: internallog.New(opts.Logger),
}
}
tp = auth.NewCachedTokenProvider(tp, nil)
return auth.NewCredentials(&auth.CredentialsOptions{
TokenProvider: tp,
JSON: b,
ProjectIDProvider: internal.StaticCredentialsProperty(f.ProjectID),
UniverseDomainProvider: internal.StaticCredentialsProperty(f.UniverseDomain),
ProjectIDProvider: auth.CredentialsPropertyFunc(creds.ProjectID),
UniverseDomainProvider: auth.CredentialsPropertyFunc(creds.UniverseDomain),
}), nil
case credsfile.ImpersonatedServiceAccountKey, credsfile.ExternalAccountKey:
type url struct {
Expand Down Expand Up @@ -110,3 +101,39 @@ func credsFromDefault(creds *auth.Credentials, opts *Options) (*auth.Credentials
return nil, fmt.Errorf("idtoken: unsupported credentials type: %v", t)
}
}

func new2LOTokenProvider(f *credsfile.ServiceAccountFile, opts *Options) (auth.TokenProvider, error) {
opts2LO := &auth.Options2LO{
Email: f.ClientEmail,
PrivateKey: []byte(f.PrivateKey),
PrivateKeyID: f.PrivateKeyID,
TokenURL: f.TokenURL,
UseIDToken: true,
Logger: internallog.New(opts.Logger),
}
if opts2LO.TokenURL == "" {
opts2LO.TokenURL = jwtTokenURL
}

var customClaims map[string]interface{}
if opts != nil {
customClaims = opts.CustomClaims
}
if customClaims == nil {
customClaims = make(map[string]interface{})
}
customClaims["target_audience"] = opts.Audience

opts2LO.PrivateClaims = customClaims
return auth.New2LOTokenProvider(opts2LO)
}

// resolveUniverseDomain returns the default service domain for a given
// Cloud universe. This is the universe domain configured for the credentials,
// which will be used in endpoint.
func resolveUniverseDomain(f *credsfile.ServiceAccountFile) string {
codyoss marked this conversation as resolved.
Show resolved Hide resolved
if f.UniverseDomain != "" {
return f.UniverseDomain
}
return internal.DefaultUniverseDomain
}
55 changes: 55 additions & 0 deletions auth/credentials/idtoken/iam.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2025 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 idtoken

import (
"context"
"log/slog"
"net/http"

"cloud.google.com/go/auth"
"cloud.google.com/go/auth/credentials/internal/impersonate"
)

// iamIDTokenProvider performs an authenticated RPC with the IAM service to
// obtain an ID token. The provided client must be fully authenticated and
// authorized with the iam.serviceAccountTokenCreator role.
//
// This TokenProvider is primarily intended for use in non-GDU universes, which
// do not have access to the oauth2.googleapis.com/token endpoint, and thus must
// use IAM generateIdToken instead.
type iamIDTokenProvider struct {
quartzmo marked this conversation as resolved.
Show resolved Hide resolved
quartzmo marked this conversation as resolved.
Show resolved Hide resolved
client *http.Client
// universeDomain is used for endpoint construction.
universeDomain auth.CredentialsPropertyProvider
// signerEmail is the service account client email used to form the IAM generateIdToken endpoint.
signerEmail string
audience string
logger *slog.Logger
}

func (i iamIDTokenProvider) Token(ctx context.Context) (*auth.Token, error) {
opts := impersonate.IDTokenIAMOptions{
Client: i.client,
UniverseDomain: i.universeDomain,
ServiceAccountEmail: i.signerEmail,
Logger: i.logger,
GenerateIDTokenRequest: impersonate.GenerateIDTokenRequest{
Audience: i.audience,
IncludeEmail: true,
},
}
return opts.Token(ctx)
}
5 changes: 5 additions & 0 deletions auth/credentials/idtoken/idtoken.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ type Options struct {
// when fetching tokens. If provided this should be a fully-authenticated
// client. Optional.
Client *http.Client
// UniverseDomain is the default service domain for a given Cloud universe.
// The default value is "googleapis.com". This is the universe domain
// configured for the client, which will be compared to the universe domain
// that is separately configured for the credentials. Optional.
UniverseDomain string
// Logger is used for debug logging. If provided, logging will be enabled
// at the loggers configured level. By default logging is disabled unless
// enabled by setting GOOGLE_SDK_GO_LOGGING_LEVEL in which case a default
Expand Down
108 changes: 106 additions & 2 deletions auth/credentials/idtoken/idtoken_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,19 @@
package idtoken

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"

"cloud.google.com/go/auth/credentials/internal/impersonate"
"cloud.google.com/go/auth/internal"
"cloud.google.com/go/auth/internal/credsfile"
)
Expand Down Expand Up @@ -66,7 +71,8 @@ func TestNewCredentials_Validate(t *testing.T) {
}
}

func TestNewCredentials_ServiceAccount_NoClient(t *testing.T) {
func TestNewCredentials_ServiceAccount(t *testing.T) {
ctx := context.Background()
wantTok, _ := createRS256JWT(t)
b, err := os.ReadFile("../../internal/testdata/sa.json")
if err != nil {
Expand Down Expand Up @@ -97,13 +103,110 @@ func TestNewCredentials_ServiceAccount_NoClient(t *testing.T) {
if err != nil {
t.Fatal(err)
}
tok, err := creds.Token(context.Background())
tok, err := creds.Token(ctx)
if err != nil {
t.Fatalf("tp.Token() = %v", err)
}
if tok.Value != wantTok {
t.Errorf("got %q, want %q", tok.Value, wantTok)
}
if got, _ := creds.UniverseDomain(ctx); got != internal.DefaultUniverseDomain {
t.Errorf("got %q, want %q", got, internal.DefaultUniverseDomain)
}
}

func TestNewCredentials_ServiceAccount_UniverseDomain(t *testing.T) {
wantAudience := "aud"
wantClientEmail := "gopher@fake_project.iam.gserviceaccount.com"
wantUniverseDomain := "example.com"
wantTok := "id-token"
client := &http.Client{
Transport: RoundTripFn(func(req *http.Request) *http.Response {
defer req.Body.Close()
b, err := io.ReadAll(req.Body)
if err != nil {
t.Error(err)
}
var r impersonate.GenerateIDTokenRequest
if err := json.Unmarshal(b, &r); err != nil {
t.Error(err)
}
if r.Audience != wantAudience {
t.Errorf("got %q, want %q", r.Audience, wantAudience)
}
if !r.IncludeEmail {
t.Errorf("got %t, want %t", r.IncludeEmail, false)
}
if !strings.Contains(req.URL.Path, wantClientEmail) {
t.Errorf("got %q, want %q", req.URL.Path, wantClientEmail)
}
if !strings.Contains(req.URL.Hostname(), wantUniverseDomain) {
t.Errorf("got %q, want %q", req.URL.Hostname(), wantUniverseDomain)
}
if !strings.Contains(req.URL.Path, "generateIdToken") {
t.Fatal("path must contain 'generateIdToken'")
}

resp := impersonate.GenerateIDTokenResponse{
Token: wantTok,
}
b, err = json.Marshal(&resp)
if err != nil {
t.Fatalf("unable to marshal response: %v", err)
}
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader(b)),
Header: http.Header{},
}
}),
}

ctx := context.Background()
creds, err := NewCredentials(&Options{
Audience: wantAudience,
CredentialsFile: "../../internal/testdata/sa_universe_domain.json",
Client: client,
UniverseDomain: wantUniverseDomain,
})
if err != nil {
t.Fatal(err)
}
tok, err := creds.Token(ctx)
if err != nil {
t.Fatalf("tp.Token() = %v", err)
}
if tok.Value != wantTok {
t.Errorf("got %q, want %q", tok.Value, wantTok)
}
if got, _ := creds.UniverseDomain(ctx); got != wantUniverseDomain {
t.Errorf("got %q, want %q", got, wantUniverseDomain)
}
}

func TestNewCredentials_ServiceAccount_UniverseDomain_NoClient(t *testing.T) {
wantUniverseDomain := "example.com"
ctx := context.Background()
creds, err := NewCredentials(&Options{
Audience: "aud",
CredentialsFile: "../../internal/testdata/sa_universe_domain.json",
UniverseDomain: wantUniverseDomain,
})
if err != nil {
t.Fatal(err)
}
// To test client creation and usage without a mock client, we must expect a failed token request.
_, err = creds.Token(ctx)
if err == nil {
t.Fatal("token call to example.com did not fail")
}
// Assert that the failed token request targeted the universe domain.
if !strings.Contains(err.Error(), wantUniverseDomain) {
t.Errorf("got %q, want %q", err.Error(), wantUniverseDomain)
}
if got, _ := creds.UniverseDomain(ctx); got != wantUniverseDomain {
t.Errorf("got %q, want %q", got, wantUniverseDomain)
}
}

type mockTransport struct {
Expand Down Expand Up @@ -147,6 +250,7 @@ func TestNewCredentials_ImpersonatedAndExternal(t *testing.T) {
"foo": "bar",
},
Client: client,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
}
if tt.file != "" {
opts.CredentialsFile = tt.file
Expand Down
Loading
Loading