1// Copyright 2021 MongoDB Inc
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package mongodbatlas
16
17import (
18	"encoding/json"
19	"fmt"
20	"net/http"
21	"testing"
22
23	"github.com/go-test/deep"
24)
25
26func TestAPIKeys_ListAPIKeys(t *testing.T) {
27	client, mux, teardown := setup()
28	defer teardown()
29
30	mux.HandleFunc("/orgs/1/apiKeys", func(w http.ResponseWriter, r *http.Request) {
31		testMethod(t, r, http.MethodGet)
32		fmt.Fprint(w, `{
33			"results": [
34				{
35					"desc": "test-apikey",
36					"id": "5c47503320eef5699e1cce8d",
37					"privateKey": "********-****-****-db2c132ca78d",
38					"publicKey": "ewmaqvdo",
39					"roles": [
40						{
41							"groupId": "1",
42							"roleName": "GROUP_OWNER"
43						},
44						{
45							"orgId": "1",
46							"roleName": "ORG_MEMBER"
47						}
48					]
49				},
50				{
51					"desc": "test-apikey-2",
52					"id": "5c47503320eef5699e1cce8f",
53					"privateKey": "********-****-****-db2c132ca78f",
54					"publicKey": "ewmaqvde",
55					"roles": [
56						{
57							"groupId": "1",
58							"roleName": "GROUP_OWNER"
59						},
60						{
61							"orgId": "1",
62							"roleName": "ORG_MEMBER"
63						}
64					]
65				}
66			],
67			"totalCount": 2
68		}`)
69	})
70
71	apiKeys, _, err := client.APIKeys.List(ctx, "1", nil)
72
73	if err != nil {
74		t.Fatalf("APIKeys.List returned error: %v", err)
75	}
76
77	expected := []APIKey{
78		{
79			ID:         "5c47503320eef5699e1cce8d",
80			Desc:       "test-apikey",
81			PrivateKey: "********-****-****-db2c132ca78d",
82			PublicKey:  "ewmaqvdo",
83			Roles: []AtlasRole{
84				{
85					GroupID:  "1",
86					RoleName: "GROUP_OWNER",
87				},
88				{
89					OrgID:    "1",
90					RoleName: "ORG_MEMBER",
91				},
92			},
93		},
94		{
95			ID:         "5c47503320eef5699e1cce8f",
96			Desc:       "test-apikey-2",
97			PrivateKey: "********-****-****-db2c132ca78f",
98			PublicKey:  "ewmaqvde",
99			Roles: []AtlasRole{
100				{
101					GroupID:  "1",
102					RoleName: "GROUP_OWNER",
103				},
104				{
105					OrgID:    "1",
106					RoleName: "ORG_MEMBER",
107				},
108			},
109		},
110	}
111	if diff := deep.Equal(apiKeys, expected); diff != nil {
112		t.Error(diff)
113	}
114}
115
116func TestAPIKeys_ListAPIKeysMultiplePages(t *testing.T) {
117	client, mux, teardown := setup()
118	defer teardown()
119
120	mux.HandleFunc("/orgs/1/apiKeys", func(w http.ResponseWriter, r *http.Request) {
121		testMethod(t, r, http.MethodGet)
122
123		dr := apiKeysResponse{
124			Results: []APIKey{
125				{
126					ID:         "5c47503320eef5699e1cce8d",
127					Desc:       "test-apikey",
128					PrivateKey: "********-****-****-db2c132ca78d",
129					PublicKey:  "ewmaqvdo",
130					Roles: []AtlasRole{
131						{
132							GroupID:  "1",
133							RoleName: "GROUP_OWNER",
134						},
135						{
136							OrgID:    "1",
137							RoleName: "ORG_MEMBER",
138						},
139					},
140				},
141				{
142					ID:         "5c47503320eef5699e1cce8f",
143					Desc:       "test-apikey-2",
144					PrivateKey: "********-****-****-db2c132ca78f",
145					PublicKey:  "ewmaqvde",
146					Roles: []AtlasRole{
147						{
148							GroupID:  "1",
149							RoleName: "GROUP_OWNER",
150						},
151						{
152							OrgID:    "1",
153							RoleName: "ORG_MEMBER",
154						},
155					},
156				},
157			},
158			Links: []*Link{
159				{Href: "http://example.com/api/atlas/v1.0/orgs/1/apiKeys?pageNum=2&itemsPerPage=2", Rel: "self"},
160				{Href: "http://example.com/api/atlas/v1.0/orgs/1/apiKeys?pageNum=2&itemsPerPage=2", Rel: "previous"},
161			},
162		}
163
164		b, err := json.Marshal(dr)
165		if err != nil {
166			t.Fatal(err)
167		}
168		fmt.Fprint(w, string(b))
169	})
170
171	_, resp, err := client.APIKeys.List(ctx, "1", nil)
172	if err != nil {
173		t.Fatal(err)
174	}
175
176	checkCurrentPage(t, resp, 2)
177}
178
179func TestAPIKeys_RetrievePageByNumber(t *testing.T) {
180	client, mux, teardown := setup()
181	defer teardown()
182
183	jBlob := `
184	{
185		"links": [
186			{
187				"href": "http://example.com/api/atlas/v1.0/orgs/1/apikeys?pageNum=1&itemsPerPage=1",
188				"rel": "previous"
189			},
190			{
191				"href": "http://example.com/api/atlas/v1.0/orgs/1/apikeys?pageNum=2&itemsPerPage=1",
192				"rel": "self"
193			},
194			{
195				"href": "http://example.com/api/atlas/v1.0/orgs/1/apikeys?itemsPerPage=3&pageNum=2",
196				"rel": "next"
197			}
198		],
199		"results": [
200			{
201				"desc": "test-apikey",
202				"id": "5c47503320eef5699e1cce8d",
203				"privateKey": "********-****-****-db2c132ca78d",
204				"publicKey": "ewmaqvdo",
205				"roles": [
206					{
207						"groupId": "1",
208						"roleName": "GROUP_OWNER"
209					},
210					{
211						"orgId": "1",
212						"roleName": "ORG_MEMBER"
213					}
214				]
215			}
216		],
217		"totalCount": 3
218	}`
219
220	mux.HandleFunc("/orgs/1/apiKeys", func(w http.ResponseWriter, r *http.Request) {
221		testMethod(t, r, http.MethodGet)
222		fmt.Fprint(w, jBlob)
223	})
224
225	opt := &ListOptions{PageNum: 2}
226	_, resp, err := client.APIKeys.List(ctx, "1", opt)
227	if err != nil {
228		t.Fatal(err)
229	}
230
231	checkCurrentPage(t, resp, 2)
232}
233
234func TestAPIKeys_Create(t *testing.T) {
235	client, mux, teardown := setup()
236	defer teardown()
237
238	orgID := "1"
239
240	createRequest := &APIKeyInput{
241		Desc:  "test-apiKey",
242		Roles: []string{"GROUP_OWNER"},
243	}
244
245	mux.HandleFunc(fmt.Sprintf("/orgs/%s/apiKeys", orgID), func(w http.ResponseWriter, r *http.Request) {
246		expected := map[string]interface{}{
247			"desc":  "test-apiKey",
248			"roles": []interface{}{"GROUP_OWNER"},
249		}
250
251		jsonBlob := `
252		{
253			"desc": "test-apikey",
254			"id": "5c47503320eef5699e1cce8d",
255			"privateKey": "********-****-****-db2c132ca78d",
256			"publicKey": "ewmaqvdo",
257			"roles": [
258				{
259					"groupId": "1",
260					"roleName": "GROUP_OWNER"
261				},
262				{
263					"orgId": "1",
264					"roleName": "ORG_MEMBER"
265				}
266			]
267		}
268		`
269
270		var v map[string]interface{}
271		err := json.NewDecoder(r.Body).Decode(&v)
272		if err != nil {
273			t.Fatalf("decode json: %v", err)
274		}
275
276		if diff := deep.Equal(v, expected); diff != nil {
277			t.Error(diff)
278		}
279
280		fmt.Fprint(w, jsonBlob)
281	})
282
283	apiKey, _, err := client.APIKeys.Create(ctx, orgID, createRequest)
284	if err != nil {
285		t.Errorf("APIKeys.Create returned error: %v", err)
286	}
287
288	if desc := apiKey.Desc; desc != "test-apikey" {
289		t.Errorf("expected username '%s', received '%s'", "test-apikeye", desc)
290	}
291
292	if pk := apiKey.PublicKey; pk != "ewmaqvdo" {
293		t.Errorf("expected publicKey '%s', received '%s'", orgID, pk)
294	}
295}
296
297func TestAPIKeys_GetAPIKey(t *testing.T) {
298	client, mux, teardown := setup()
299	defer teardown()
300
301	mux.HandleFunc("/orgs/1/apiKeys/5c47503320eef5699e1cce8d", func(w http.ResponseWriter, r *http.Request) {
302		testMethod(t, r, http.MethodGet)
303		fmt.Fprint(w, `{"desc":"test-desc"}`)
304	})
305
306	apiKeys, _, err := client.APIKeys.Get(ctx, "1", "5c47503320eef5699e1cce8d")
307	if err != nil {
308		t.Errorf("APIKey.Get returned error: %v", err)
309	}
310
311	expected := &APIKey{Desc: "test-desc"}
312
313	if diff := deep.Equal(apiKeys, expected); diff != nil {
314		t.Errorf("Clusters.Get = %v", diff)
315	}
316}
317
318func TestAPIKeys_Update(t *testing.T) {
319	client, mux, teardown := setup()
320	defer teardown()
321
322	orgID := "1"
323
324	updateRequest := &APIKeyInput{
325		Desc:  "test-apiKey",
326		Roles: []string{"GROUP_OWNER"},
327	}
328
329	mux.HandleFunc(fmt.Sprintf("/orgs/%s/apiKeys/%s", orgID, "5c47503320eef5699e1cce8d"), func(w http.ResponseWriter, r *http.Request) {
330		expected := map[string]interface{}{
331			"desc":  "test-apiKey",
332			"roles": []interface{}{"GROUP_OWNER"},
333		}
334
335		jsonBlob := `
336		{
337			"desc": "test-apikey",
338			"id": "5c47503320eef5699e1cce8d",
339			"privateKey": "********-****-****-db2c132ca78d",
340			"publicKey": "ewmaqvdo",
341			"roles": [
342				{
343					"groupId": "1",
344					"roleName": "GROUP_OWNER"
345				},
346				{
347					"orgId": "1",
348					"roleName": "ORG_MEMBER"
349				}
350			]
351		}
352		`
353
354		var v map[string]interface{}
355		err := json.NewDecoder(r.Body).Decode(&v)
356		if err != nil {
357			t.Fatalf("decode json: %v", err)
358		}
359
360		if diff := deep.Equal(v, expected); diff != nil {
361			t.Error(diff)
362		}
363
364		fmt.Fprint(w, jsonBlob)
365	})
366
367	apiKey, _, err := client.APIKeys.Update(ctx, orgID, "5c47503320eef5699e1cce8d", updateRequest)
368	if err != nil {
369		t.Fatalf("APIKeys.Create returned error: %v", err)
370	}
371
372	if desc := apiKey.Desc; desc != "test-apikey" {
373		t.Errorf("expected username '%s', received '%s'", "test-apikeye", desc)
374	}
375
376	if pk := apiKey.PublicKey; pk != "ewmaqvdo" {
377		t.Errorf("expected publicKey '%s', received '%s'", orgID, pk)
378	}
379}
380
381func TestAPIKeys_Delete(t *testing.T) {
382	client, mux, teardown := setup()
383	defer teardown()
384
385	orgID := "1"
386	apiKeyID := "5c47503320eef5699e1cce8d"
387
388	mux.HandleFunc(fmt.Sprintf("/orgs/%s/apiKeys/%s", orgID, apiKeyID), func(w http.ResponseWriter, r *http.Request) {
389		testMethod(t, r, http.MethodDelete)
390	})
391
392	_, err := client.APIKeys.Delete(ctx, orgID, apiKeyID)
393	if err != nil {
394		t.Errorf("APIKey.Delete returned error: %v", err)
395	}
396}
397