...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package impersonate
16
17 import (
18 "bytes"
19 "context"
20 "encoding/json"
21 "io"
22 "net/http"
23 "testing"
24 )
25
26 func TestNewIDTokenCredentials(t *testing.T) {
27 ctx := context.Background()
28 tests := []struct {
29 name string
30 aud string
31 targetPrincipal string
32 wantErr bool
33 }{
34 {
35 name: "missing aud",
36 targetPrincipal: "foo@project-id.iam.gserviceaccount.com",
37 wantErr: true,
38 },
39 {
40 name: "missing targetPrincipal",
41 aud: "http://example.com/",
42 wantErr: true,
43 },
44 {
45 name: "works",
46 aud: "http://example.com/",
47 targetPrincipal: "foo@project-id.iam.gserviceaccount.com",
48 wantErr: false,
49 },
50 }
51
52 for _, tt := range tests {
53 name := tt.name
54 t.Run(name, func(t *testing.T) {
55 idTok := "id-token"
56 client := &http.Client{
57 Transport: RoundTripFn(func(req *http.Request) *http.Response {
58 defer req.Body.Close()
59 b, err := io.ReadAll(req.Body)
60 if err != nil {
61 t.Error(err)
62 }
63 var r generateIDTokenRequest
64 if err := json.Unmarshal(b, &r); err != nil {
65 t.Error(err)
66 }
67 if r.Audience != tt.aud {
68 t.Errorf("got %q, want %q", r.Audience, tt.aud)
69 }
70
71 resp := generateIDTokenResponse{
72 Token: idTok,
73 }
74 b, err = json.Marshal(&resp)
75 if err != nil {
76 t.Fatalf("unable to marshal response: %v", err)
77 }
78 return &http.Response{
79 StatusCode: 200,
80 Body: io.NopCloser(bytes.NewReader(b)),
81 Header: make(http.Header),
82 }
83 }),
84 }
85 creds, err := NewIDTokenCredentials(&IDTokenOptions{
86 Audience: tt.aud,
87 TargetPrincipal: tt.targetPrincipal,
88 Client: client,
89 },
90 )
91 if tt.wantErr && err != nil {
92 return
93 }
94 if err != nil {
95 t.Fatal(err)
96 }
97 tok, err := creds.Token(ctx)
98 if err != nil {
99 t.Fatal(err)
100 }
101 if tok.Value != idTok {
102 t.Fatalf("got %q, want %q", tok.Value, idTok)
103 }
104 })
105 }
106 }
107
View as plain text