1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package idtoken
16
17 import (
18 "context"
19 "net/http"
20 "net/http/httptest"
21 "strings"
22 "testing"
23 )
24
25 const metadataHostEnv = "GCE_METADATA_HOST"
26
27 func TestComputeCredentials(t *testing.T) {
28 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
29 if !strings.Contains(r.URL.Path, identitySuffix) {
30 t.Errorf("got %q, want contains %q", r.URL.Path, identitySuffix)
31 }
32 if got, want := r.URL.Query().Get("audience"), "aud"; got != want {
33 t.Errorf("got %q, want %q", got, want)
34 }
35 if got, want := r.URL.Query().Get("format"), "full"; got != want {
36 t.Errorf("got %q, want %q", got, want)
37 }
38 if got, want := r.URL.Query().Get("licenses"), "TRUE"; got != want {
39 t.Errorf("got %q, want %q", got, want)
40 }
41 w.Write([]byte(`fake_token`))
42 }))
43 defer ts.Close()
44 t.Setenv(metadataHostEnv, strings.TrimPrefix(ts.URL, "http://"))
45 tp, err := computeCredentials(&Options{
46 Audience: "aud",
47 ComputeTokenFormat: ComputeTokenFormatFullWithLicense,
48 })
49 if err != nil {
50 t.Fatalf("computeCredentials() = %v", err)
51 }
52 tok, err := tp.Token(context.Background())
53 if err != nil {
54 t.Fatalf("tp.Token() = %v", err)
55 }
56 if want := "fake_token"; tok.Value != want {
57 t.Errorf("got %q, want %q", tok.Value, want)
58 }
59 }
60
61 func TestComputeCredentials_Standard(t *testing.T) {
62 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
63 if !strings.Contains(r.URL.Path, identitySuffix) {
64 t.Errorf("got %q, want contains %q", r.URL.Path, identitySuffix)
65 }
66 if got, want := r.URL.Query().Get("audience"), "aud"; got != want {
67 t.Errorf("got %q, want %q", got, want)
68 }
69 if got, want := r.URL.Query().Get("format"), ""; got != want {
70 t.Errorf("got %q, want %q", got, want)
71 }
72 if got, want := r.URL.Query().Get("licenses"), ""; got != want {
73 t.Errorf("got %q, want %q", got, want)
74 }
75 w.Write([]byte(`fake_token`))
76 }))
77 defer ts.Close()
78 t.Setenv(metadataHostEnv, strings.TrimPrefix(ts.URL, "http://"))
79 tp, err := computeCredentials(&Options{
80 Audience: "aud",
81 ComputeTokenFormat: ComputeTokenFormatStandard,
82 })
83 if err != nil {
84 t.Fatalf("computeCredentials() = %v", err)
85 }
86 tok, err := tp.Token(context.Background())
87 if err != nil {
88 t.Fatalf("tp.Token() = %v", err)
89 }
90 if want := "fake_token"; tok.Value != want {
91 t.Errorf("got %q, want %q", tok.Value, want)
92 }
93 }
94
95 func TestComputeCredentials_Invalid(t *testing.T) {
96 if _, err := computeCredentials(&Options{
97 Audience: "aud",
98 CustomClaims: map[string]interface{}{"foo": "bar"},
99 }); err == nil {
100 t.Fatal("computeCredentials() = nil, expected non-nil error", err)
101 }
102 }
103
View as plain text