...

Source file src/google.golang.org/api/impersonate/idtoken_test.go

Documentation: google.golang.org/api/impersonate

     1  // Copyright 2021 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package impersonate
     6  
     7  import (
     8  	"bytes"
     9  	"context"
    10  	"encoding/json"
    11  	"io"
    12  	"net/http"
    13  	"testing"
    14  
    15  	"google.golang.org/api/option"
    16  )
    17  
    18  func TestIDTokenSource(t *testing.T) {
    19  	ctx := context.Background()
    20  	tests := []struct {
    21  		name            string
    22  		aud             string
    23  		targetPrincipal string
    24  		wantErr         bool
    25  	}{
    26  		{
    27  			name:            "missing aud",
    28  			targetPrincipal: "foo@project-id.iam.gserviceaccount.com",
    29  			wantErr:         true,
    30  		},
    31  		{
    32  			name:    "missing targetPrincipal",
    33  			aud:     "http://example.com/",
    34  			wantErr: true,
    35  		},
    36  		{
    37  			name:            "works",
    38  			aud:             "http://example.com/",
    39  			targetPrincipal: "foo@project-id.iam.gserviceaccount.com",
    40  			wantErr:         false,
    41  		},
    42  	}
    43  
    44  	for _, tt := range tests {
    45  		name := tt.name
    46  		t.Run(name, func(t *testing.T) {
    47  			idTok := "id-token"
    48  			client := &http.Client{
    49  				Transport: RoundTripFn(func(req *http.Request) *http.Response {
    50  					resp := generateIDTokenResponse{
    51  						Token: idTok,
    52  					}
    53  					b, err := json.Marshal(&resp)
    54  					if err != nil {
    55  						t.Fatalf("unable to marshal response: %v", err)
    56  					}
    57  					return &http.Response{
    58  						StatusCode: 200,
    59  						Body:       io.NopCloser(bytes.NewReader(b)),
    60  						Header:     make(http.Header),
    61  					}
    62  				}),
    63  			}
    64  			ts, err := IDTokenSource(ctx, IDTokenConfig{
    65  				Audience:        tt.aud,
    66  				TargetPrincipal: tt.targetPrincipal,
    67  			}, option.WithHTTPClient(client))
    68  			if tt.wantErr && err != nil {
    69  				return
    70  			}
    71  			if err != nil {
    72  				t.Fatal(err)
    73  			}
    74  			tok, err := ts.Token()
    75  			if err != nil {
    76  				t.Fatal(err)
    77  			}
    78  			if tok.AccessToken != idTok {
    79  				t.Fatalf("got %q, want %q", tok.AccessToken, idTok)
    80  			}
    81  		})
    82  	}
    83  }
    84  

View as plain text