forked from firebase/firebase-admin-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirebase_test.go
316 lines (276 loc) · 8.14 KB
/
firebase_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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 firebase
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"strconv"
"strings"
"testing"
"time"
"golang.org/x/oauth2/google"
"google.golang.org/api/transport"
"encoding/json"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"google.golang.org/api/option"
)
func TestServiceAcctFile(t *testing.T) {
app, err := NewApp(context.Background(), nil, option.WithCredentialsFile("testdata/service_account.json"))
if err != nil {
t.Fatal(err)
}
if app.projectID != "mock-project-id" {
t.Errorf("Project ID: %q; want: %q", app.projectID, "mock-project-id")
}
if len(app.opts) != 2 {
t.Errorf("Client opts: %d; want: 2", len(app.opts))
}
if app.creds == nil {
t.Error("Credentials: nil; want creds")
} else if len(app.creds.JSON) == 0 {
t.Error("JSON: empty; want; non-empty")
}
}
func TestClientOptions(t *testing.T) {
ts := initMockTokenServer()
defer ts.Close()
b, err := mockServiceAcct(ts.URL)
config, err := google.JWTConfigFromJSON(b)
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
app, err := NewApp(ctx, nil, option.WithTokenSource(config.TokenSource(ctx)))
if err != nil {
t.Fatal(err)
}
var bearer string
service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
bearer = r.Header.Get("Authorization")
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"output": "test"}`))
}))
defer service.Close()
client, _, err := transport.NewHTTPClient(ctx, app.opts...)
if err != nil {
t.Fatal(err)
}
resp, err := client.Get(service.URL)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != 200 {
t.Errorf("Status: %d; want: 200", resp.StatusCode)
}
if bearer != "Bearer mock-token" {
t.Errorf("Bearer token: %q; want: %q", bearer, "Bearer mock-token")
}
}
func TestRefreshTokenFile(t *testing.T) {
app, err := NewApp(context.Background(), nil, option.WithCredentialsFile("testdata/refresh_token.json"))
if err != nil {
t.Fatal(err)
}
if len(app.opts) != 2 {
t.Errorf("Client opts: %d; want: 2", len(app.opts))
}
if app.creds == nil {
t.Error("Credentials: nil; want creds")
} else if len(app.creds.JSON) == 0 {
t.Error("JSON: empty; want; non-empty")
}
}
func TestRefreshTokenFileWithConfig(t *testing.T) {
config := &Config{ProjectID: "mock-project-id"}
app, err := NewApp(context.Background(), config, option.WithCredentialsFile("testdata/refresh_token.json"))
if err != nil {
t.Fatal(err)
}
if app.projectID != "mock-project-id" {
t.Errorf("Project ID: %q; want: mock-project-id", app.projectID)
}
if len(app.opts) != 2 {
t.Errorf("Client opts: %d; want: 2", len(app.opts))
}
if app.creds == nil {
t.Error("Credentials: nil; want creds")
} else if len(app.creds.JSON) == 0 {
t.Error("JSON: empty; want; non-empty")
}
}
func TestRefreshTokenWithEnvVar(t *testing.T) {
varName := "GCLOUD_PROJECT"
current := os.Getenv(varName)
if err := os.Setenv(varName, "mock-project-id"); err != nil {
t.Fatal(err)
}
defer os.Setenv(varName, current)
app, err := NewApp(context.Background(), nil, option.WithCredentialsFile("testdata/refresh_token.json"))
if err != nil {
t.Fatal(err)
}
if app.projectID != "mock-project-id" {
t.Errorf("Project ID: %q; want: mock-project-id", app.projectID)
}
if app.creds == nil {
t.Error("Credentials: nil; want creds")
} else if len(app.creds.JSON) == 0 {
t.Error("JSON: empty; want; non-empty")
}
}
func TestAppDefault(t *testing.T) {
varName := "GOOGLE_APPLICATION_CREDENTIALS"
current := os.Getenv(varName)
if err := os.Setenv(varName, "testdata/service_account.json"); err != nil {
t.Fatal(err)
}
defer os.Setenv(varName, current)
app, err := NewApp(context.Background(), nil)
if err != nil {
t.Fatal(err)
}
if len(app.opts) != 1 {
t.Errorf("Client opts: %d; want: 1", len(app.opts))
}
if app.creds == nil {
t.Error("Credentials: nil; want creds")
} else if len(app.creds.JSON) == 0 {
t.Error("JSON: empty; want; non-empty")
}
}
func TestAppDefaultWithInvalidFile(t *testing.T) {
varName := "GOOGLE_APPLICATION_CREDENTIALS"
current := os.Getenv(varName)
if err := os.Setenv(varName, "testdata/non_existing.json"); err != nil {
t.Fatal(err)
}
defer os.Setenv(varName, current)
app, err := NewApp(context.Background(), nil)
if app != nil || err == nil {
t.Errorf("NewApp() = (%v, %v); want: (nil, error)", app, err)
}
}
func TestInvalidCredentialFile(t *testing.T) {
invalidFiles := []string{
"testdata",
"testdata/plain_text.txt",
}
ctx := context.Background()
for _, tc := range invalidFiles {
app, err := NewApp(ctx, nil, option.WithCredentialsFile(tc))
if app != nil || err == nil {
t.Errorf("NewApp(%q) = (%v, %v); want: (nil, error)", tc, app, err)
}
}
}
func TestAuth(t *testing.T) {
ctx := context.Background()
app, err := NewApp(ctx, nil, option.WithCredentialsFile("testdata/service_account.json"))
if err != nil {
t.Fatal(err)
}
if c, err := app.Auth(ctx); c == nil || err != nil {
t.Errorf("Auth() = (%v, %v); want (auth, nil)", c, err)
}
}
func TestStorage(t *testing.T) {
ctx := context.Background()
app, err := NewApp(ctx, nil, option.WithCredentialsFile("testdata/service_account.json"))
if err != nil {
t.Fatal(err)
}
if c, err := app.Storage(ctx); c == nil || err != nil {
t.Errorf("Storage() = (%v, %v); want (auth, nil)", c, err)
}
}
func TestCustomTokenSource(t *testing.T) {
ctx := context.Background()
ts := &testTokenSource{AccessToken: "mock-token-from-custom"}
app, err := NewApp(ctx, nil, option.WithTokenSource(ts))
if err != nil {
t.Fatal(err)
}
client, _, err := transport.NewHTTPClient(ctx, app.opts...)
if err != nil {
t.Fatal(err)
}
var bearer string
service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
bearer = r.Header.Get("Authorization")
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"output": "test"}`))
}))
defer service.Close()
resp, err := client.Get(service.URL)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != 200 {
t.Errorf("Status: %d; want: 200", resp.StatusCode)
}
if bearer != "Bearer "+ts.AccessToken {
t.Errorf("Bearer token: %q; want: %q", bearer, "Bearer "+ts.AccessToken)
}
}
func TestVersion(t *testing.T) {
segments := strings.Split(Version, ".")
if len(segments) != 3 {
t.Errorf("Incorrect number of segments: %d; want: 3", len(segments))
}
for _, segment := range segments {
if _, err := strconv.Atoi(segment); err != nil {
t.Errorf("Invalid segment in version number: %q; want integer", segment)
}
}
}
type testTokenSource struct {
AccessToken string
Expiry time.Time
}
func (t *testTokenSource) Token() (*oauth2.Token, error) {
return &oauth2.Token{
AccessToken: t.AccessToken,
Expiry: t.Expiry,
}, nil
}
// mockServiceAcct generates a service account configuration with the provided URL as the
// token_url value.
func mockServiceAcct(tokenURL string) ([]byte, error) {
b, err := ioutil.ReadFile("testdata/service_account.json")
if err != nil {
return nil, err
}
var parsed map[string]interface{}
if err := json.Unmarshal(b, &parsed); err != nil {
return nil, err
}
parsed["token_uri"] = tokenURL
return json.Marshal(parsed)
}
// initMockTokenServer starts a mock HTTP server that Apps can invoke during tests to obtain
// OAuth2 access tokens.
func initMockTokenServer() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{
"access_token": "mock-token",
"scope": "user",
"token_type": "bearer",
"expires_in": 3600
}`))
}))
}