...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package impersonate
16
17 import (
18 "context"
19 "encoding/json"
20 "net/http"
21 "net/http/httptest"
22 "testing"
23
24 "cloud.google.com/go/auth"
25 "cloud.google.com/go/auth/internal"
26 )
27
28 type mockProvider string
29
30 func (tp mockProvider) Token(context.Context) (*auth.Token, error) {
31 return &auth.Token{
32 Value: string(tp),
33 }, nil
34 }
35
36 func TestNewImpersonatedTokenProvider_Validation(t *testing.T) {
37 tests := []struct {
38 name string
39 opt *Options
40 }{
41 {
42 name: "missing source creds",
43 opt: &Options{
44 URL: "some-url",
45 },
46 },
47 {
48 name: "missing url",
49 opt: &Options{
50 Tp: &Options{},
51 },
52 },
53 }
54 for _, tt := range tests {
55 t.Run(tt.name, func(t *testing.T) {
56 _, err := NewTokenProvider(tt.opt)
57 if err == nil {
58 t.Errorf("got nil, want an error")
59 }
60 })
61 }
62 }
63
64 func TestNewImpersonatedTokenProvider(t *testing.T) {
65 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
66 if got, want := r.Header.Get("Authorization"), "Bearer fake_token_base"; got != want {
67 t.Errorf("got %q; want %q", got, want)
68 }
69 resp := &struct {
70 AccessToken string `json:"accessToken"`
71 ExpireTime string `json:"expireTime"`
72 }{
73 AccessToken: "a_fake_token",
74 ExpireTime: "2006-01-02T15:04:05Z",
75 }
76 if err := json.NewEncoder(w).Encode(&resp); err != nil {
77 t.Fatal(err)
78 }
79 }))
80
81 creds, err := NewTokenProvider(&Options{
82 Tp: mockProvider("fake_token_base"),
83 URL: ts.URL,
84 Delegates: []string{"sa1@developer.gserviceaccount.com", "sa2@developer.gserviceaccount.com"},
85 Scopes: []string{"https://www.googleapis.com/auth/cloud-platform"},
86 Client: internal.CloneDefaultClient(),
87 })
88 if err != nil {
89 t.Fatal(err)
90 }
91 tok, err := creds.Token(context.Background())
92 if err != nil {
93 t.Fatalf("creds.Token() = %v", err)
94 }
95 if want := "a_fake_token"; tok.Value != want {
96 t.Fatalf("got %q, want %q", tok.Value, want)
97 }
98 if want := internal.TokenTypeBearer; tok.Type != want {
99 t.Fatalf("got %q, want %q", tok.Type, want)
100 }
101 }
102
View as plain text