-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathauthentication_handlers_test.go
823 lines (683 loc) · 20.7 KB
/
authentication_handlers_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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"testing"
"github.com/RedHatInsights/sources-api-go/config"
"github.com/RedHatInsights/sources-api-go/dao"
"github.com/RedHatInsights/sources-api-go/internal/testutils"
"github.com/RedHatInsights/sources-api-go/internal/testutils/fixtures"
"github.com/RedHatInsights/sources-api-go/internal/testutils/mocks"
"github.com/RedHatInsights/sources-api-go/internal/testutils/parser"
"github.com/RedHatInsights/sources-api-go/internal/testutils/request"
"github.com/RedHatInsights/sources-api-go/internal/testutils/templates"
"github.com/RedHatInsights/sources-api-go/middleware"
h "github.com/RedHatInsights/sources-api-go/middleware/headers"
m "github.com/RedHatInsights/sources-api-go/model"
"github.com/RedHatInsights/sources-api-go/service"
"github.com/RedHatInsights/sources-api-go/util"
"github.com/google/go-cmp/cmp"
"github.com/redhatinsights/platform-go-middlewares/identity"
)
func TestAuthenticationList(t *testing.T) {
tenantId := int64(1)
c, rec := request.CreateTestContext(
http.MethodGet,
"/api/sources/v3.1/authentications",
nil,
map[string]interface{}{
"limit": 100,
"offset": 0,
"filters": []util.Filter{},
"tenantID": tenantId,
},
)
err := AuthenticationList(c)
if err != nil {
t.Error(err)
}
if rec.Code != http.StatusOK {
t.Error("Did not return 200")
}
var out util.Collection
err = json.Unmarshal(rec.Body.Bytes(), &out)
if err != nil {
t.Error("Failed unmarshaling output")
}
if out.Meta.Limit != 100 {
t.Error("limit not set correctly")
}
if out.Meta.Offset != 0 {
t.Error("offset not set correctly")
}
var wantCount int
for _, a := range fixtures.TestAuthenticationData {
if a.TenantID == tenantId {
wantCount++
}
}
if out.Meta.Count != wantCount {
t.Error("not enough objects passed back from DB")
}
if len(out.Data) != wantCount {
t.Error("not enough objects passed back from DB")
}
auth1, ok := out.Data[0].(map[string]interface{})
if !ok {
t.Error("model did not deserialize as a source")
}
if config.IsVaultOn() {
if auth1["id"] != fixtures.TestAuthenticationData[0].ID {
t.Errorf(`wrong authentication list fetched. Want authentications from the fixtures, got: %s`, auth1)
}
} else {
outIdStr, ok := auth1["id"].(string)
if !ok {
t.Errorf(`Want "string", got "%s"`, auth1)
}
outId, err := strconv.ParseInt(outIdStr, 10, 64)
if err != nil {
t.Errorf(`The ID of the payload could not be converted to int64: %s`, err)
}
if fixtures.TestAuthenticationData[0].DbID != outId {
t.Errorf(`wrong authentication list fetched. Want authentications from the fixtures, got: %s`, auth1)
}
}
err = checkAllAuthenticationsBelongToTenant(tenantId, out.Data)
if err != nil {
t.Error(err)
}
testutils.AssertLinks(t, c.Request().RequestURI, out.Links, 100, 0)
}
// TestAuthenticationTenantNotExist tests that empty list is returned
// for not existing tenant
func TestAuthenticationTenantNotExist(t *testing.T) {
testutils.SkipIfNotRunningIntegrationTests(t)
tenantId := fixtures.NotExistingTenantId
c, rec := request.CreateTestContext(
http.MethodGet,
"/api/sources/v3.1/authentications",
nil,
map[string]interface{}{
"limit": 100,
"offset": 0,
"filters": []util.Filter{},
"tenantID": tenantId,
},
)
err := AuthenticationList(c)
if err != nil {
t.Error(err)
}
templates.EmptySubcollectionListTest(t, c, rec)
}
// TestAuthenticationTenantWithoutAuthentications tests that empty list is returned
// for a tenant without authentications
func TestAuthenticationTenantWithoutAuthentications(t *testing.T) {
testutils.SkipIfNotRunningIntegrationTests(t)
tenantId := int64(3)
c, rec := request.CreateTestContext(
http.MethodGet,
"/api/sources/v3.1/authentications",
nil,
map[string]interface{}{
"limit": 100,
"offset": 0,
"filters": []util.Filter{},
"tenantID": tenantId,
},
)
err := AuthenticationList(c)
if err != nil {
t.Error(err)
}
templates.EmptySubcollectionListTest(t, c, rec)
}
func TestAuthenticationListBadRequestInvalidFilter(t *testing.T) {
testutils.SkipIfNotRunningIntegrationTests(t)
tenantId := int64(1)
c, rec := request.CreateTestContext(
http.MethodGet,
"/api/sources/v3.1/authentications",
nil,
map[string]interface{}{
"limit": 100,
"offset": 0,
"filters": []util.Filter{
{Name: "wrongName", Value: []string{"wrongValue"}},
},
"tenantID": tenantId,
},
)
badRequestAuthenticationList := ErrorHandlingContext(AuthenticationList)
err := badRequestAuthenticationList(c)
if err != nil {
t.Error(err)
}
templates.BadRequestTest(t, rec)
}
func TestAuthenticationGet(t *testing.T) {
tenantId := int64(1)
originalSecretStore := conf.SecretStore
// Run this test for secret store = [vault, database]
for _, s := range []string{"vault", "database"} {
conf.SecretStore = s
var id string
if config.IsVaultOn() {
conf.SecretStore = "vault"
id = fixtures.TestAuthenticationData[0].ID
} else {
id = strconv.FormatInt(fixtures.TestAuthenticationData[0].DbID, 10)
}
c, rec := request.CreateTestContext(
http.MethodGet,
"/api/sources/v3.1/authentications/"+id,
nil,
map[string]interface{}{
"tenantID": tenantId,
},
)
c.SetParamNames("uid")
c.SetParamValues(id)
err := AuthenticationGet(c)
if err != nil {
t.Error(err)
}
if rec.Code != http.StatusOK {
t.Error("Did not return 200")
}
var outAuthentication m.AuthenticationResponse
err = json.Unmarshal(rec.Body.Bytes(), &outAuthentication)
if err != nil {
t.Error("Failed unmarshaling output")
}
if outAuthentication.ID != id {
t.Errorf(`wrong authentication fetched. Want "%s", got "%s"`, id, outAuthentication.ID)
}
// Check the tenancy of returned authentication
for _, a := range fixtures.TestAuthenticationData {
var fixturesAuthId string
if config.IsVaultOn() {
fixturesAuthId = a.ID
} else {
fixturesAuthId = strconv.FormatInt(a.DbID, 10)
}
if fixturesAuthId == id {
if a.TenantID != tenantId {
t.Error("ghosts infected the return")
}
break
}
}
}
conf.SecretStore = originalSecretStore
}
func TestAuthenticationGetTenantNotExist(t *testing.T) {
testutils.SkipIfNotRunningIntegrationTests(t)
tenantId := fixtures.NotExistingTenantId
uid := strconv.FormatInt(fixtures.TestAuthenticationData[0].DbID, 10)
c, rec := request.CreateTestContext(
http.MethodGet,
"/api/sources/v3.1/authentications/"+uid,
nil,
map[string]interface{}{
"tenantID": tenantId,
},
)
c.SetParamNames("uid")
c.SetParamValues(uid)
notFoundAuthenticationGet := ErrorHandlingContext(AuthenticationGet)
err := notFoundAuthenticationGet(c)
if err != nil {
t.Error(err)
}
templates.NotFoundTest(t, rec)
}
func TestAuthenticationGetNotFound(t *testing.T) {
uid := "abcdefg"
c, rec := request.CreateTestContext(
http.MethodGet,
"/api/sources/v3.1/authentications/"+uid,
nil,
map[string]interface{}{
"tenantID": int64(1),
},
)
c.SetParamNames("uid")
c.SetParamValues(uid)
notFoundAuthenticationGet := ErrorHandlingContext(AuthenticationGet)
err := notFoundAuthenticationGet(c)
if err != nil {
t.Error(err)
}
templates.NotFoundTest(t, rec)
}
func TestAuthenticationCreate(t *testing.T) {
tenantId := int64(1)
// Set the encryption key
util.OverrideEncryptionKey(strings.Repeat("test", 8))
// Test the creation of authentication for an application, fpr an endpoint
// and for a source
for _, resourceType := range []string{"Application", "Endpoint", "Source"} {
requestBody := m.AuthenticationCreateRequest{
Name: util.StringRef("TestRequest"),
AuthType: "test",
Username: util.StringRef("testUser"),
Password: util.StringRef("123456"),
ResourceType: resourceType,
ResourceIDRaw: 1,
}
body, err := json.Marshal(requestBody)
if err != nil {
t.Error("Could not marshal JSON")
}
c, rec := request.CreateTestContext(
http.MethodPost,
"/api/sources/v3.1/authentications",
bytes.NewReader(body),
map[string]interface{}{
"tenantID": tenantId,
},
)
c.Request().Header.Add("Content-Type", "application/json;charset=utf-8")
err = AuthenticationCreate(c)
if err != nil {
t.Error(err)
}
if rec.Code != http.StatusCreated {
t.Errorf("Did not return 201. Body: %s", rec.Body.String())
}
auth := m.AuthenticationResponse{}
raw, _ := io.ReadAll(rec.Body)
err = json.Unmarshal(raw, &auth)
if err != nil {
t.Errorf("Failed to unmarshal application from response: %v", err)
}
if auth.ResourceType != resourceType {
t.Errorf("Wrong resource type, wanted %v got %v", "Application", auth.ResourceType)
}
if auth.Username != "testUser" {
t.Errorf("Wrong user name, wanted %v got %v", "testUser", auth.Username)
}
if auth.ResourceID != "1" {
t.Errorf("Wrong resource ID, wanted %v got %v", 1, auth.ResourceID)
}
// Check the tenancy (only for integration tests)
// and
// Delete created authentication (it makes sense only for integration tests, in case of unit tests
// the mock for auth create doesn't create new auth in the memory)
if parser.RunningIntegrationTests {
requestParams := dao.RequestParams{TenantID: &tenantId}
authenticationDao := dao.GetAuthenticationDao(&requestParams)
authOut, err := authenticationDao.GetById(auth.ID)
if err != nil {
t.Error(err)
}
if authOut.TenantID != tenantId {
t.Errorf("authentication's tenant id = %d, expected %d", authOut.TenantID, tenantId)
}
_, err = authenticationDao.Delete(auth.ID)
if err != nil {
t.Error(err)
}
}
}
}
func TestAuthenticationCreateBadRequestInvalidResourceType(t *testing.T) {
requestBody := m.AuthenticationCreateRequest{
Username: util.StringRef("testUser"),
Password: util.StringRef("123456"),
ResourceType: "InvalidType",
ResourceIDRaw: 1,
}
body, err := json.Marshal(requestBody)
if err != nil {
t.Error("Could not marshal JSON")
}
c, rec := request.CreateTestContext(
http.MethodPost,
"/api/sources/v3.1/authentications",
bytes.NewReader(body),
map[string]interface{}{
"tenantID": int64(1),
},
)
c.Request().Header.Add("Content-Type", "application/json;charset=utf-8")
badRequestAuthenticationCreate := ErrorHandlingContext(AuthenticationCreate)
err = badRequestAuthenticationCreate(c)
if err != nil {
t.Error(err)
}
templates.BadRequestTest(t, rec)
}
// TestAuthenticationCreateResourceNotFound tests that bad request is returned when
// you try to create authentication for not existing resource
func TestAuthenticationCreateResourceNotFound(t *testing.T) {
testutils.SkipIfNotRunningIntegrationTests(t)
tenantId := int64(1)
for _, resourceType := range []string{"Application", "Endpoint", "Source"} {
requestBody := m.AuthenticationCreateRequest{
Username: util.StringRef("testUser"),
Password: util.StringRef("123456"),
ResourceType: resourceType,
ResourceIDRaw: 54321,
}
body, err := json.Marshal(requestBody)
if err != nil {
t.Error("Could not marshal JSON")
}
c, rec := request.CreateTestContext(
http.MethodPost,
"/api/sources/v3.1/authentications",
bytes.NewReader(body),
map[string]interface{}{
"tenantID": tenantId,
},
)
c.Request().Header.Add("Content-Type", "application/json;charset=utf-8")
badRequestAuthenticationCreate := ErrorHandlingContext(AuthenticationCreate)
err = badRequestAuthenticationCreate(c)
if err != nil {
t.Error(err)
}
templates.BadRequestTest(t, rec)
}
}
func TestAuthenticationEdit(t *testing.T) {
testutils.SkipIfNotRunningIntegrationTests(t)
tenantId := int64(1)
var uid string
if config.IsVaultOn() {
uid = fixtures.TestAuthenticationData[0].ID
} else {
uid = strconv.FormatInt(fixtures.TestAuthenticationData[0].DbID, 10)
}
backupNotificationProducer := service.NotificationProducer
service.NotificationProducer = &mocks.MockAvailabilityStatusNotificationProducer{}
newAvailabilityStatus := m.Unavailable
requestBody := m.AuthenticationEditRequest{
AvailabilityStatus: &newAvailabilityStatus,
}
body, err := json.Marshal(requestBody)
if err != nil {
t.Error("Could not marshal JSON")
}
c, rec := request.CreateTestContext(
http.MethodPatch,
"/api/sources/v3.1/authentications/1",
bytes.NewReader(body),
map[string]interface{}{
"tenantID": tenantId,
},
)
c.SetParamNames("uid")
c.SetParamValues(uid)
c.Request().Header.Add("Content-Type", "application/json;charset=utf-8")
c.Set(h.ParsedIdentity, &identity.XRHID{Identity: identity.Identity{AccountNumber: fixtures.TestTenantData[0].ExternalTenant}})
authEditHandlerWithNotifier := middleware.Notifier(AuthenticationEdit)
err = authEditHandlerWithNotifier(c)
if err != nil {
t.Error(err)
}
if rec.Code != http.StatusOK {
t.Errorf("Did not return 200. Body: %s", rec.Body.String())
}
auth := m.AuthenticationResponse{}
raw, _ := io.ReadAll(rec.Body)
err = json.Unmarshal(raw, &auth)
if err != nil {
t.Errorf("Failed to unmarshal application from response: %v", err)
}
if auth.AvailabilityStatus != newAvailabilityStatus {
t.Errorf("Wrong availability status, wanted %v got %v", newAvailabilityStatus, auth.AvailabilityStatus)
}
notificationProducer, ok := service.NotificationProducer.(*mocks.MockAvailabilityStatusNotificationProducer)
if !ok {
t.Errorf("unable to cast notification producer")
}
emailNotificationInfo := &m.EmailNotificationInfo{ResourceDisplayName: "Authentication",
CurrentAvailabilityStatus: newAvailabilityStatus,
PreviousAvailabilityStatus: "available",
SourceName: fixtures.TestSourceData[0].Name,
SourceID: strconv.FormatInt(fixtures.TestSourceData[0].ID, 10),
TenantID: strconv.FormatInt(fixtures.TestSourceData[0].TenantID, 10),
}
if !cmp.Equal(emailNotificationInfo, notificationProducer.EmailNotificationInfo) {
t.Errorf("Invalid email notification data:")
t.Errorf("Expected: %v Obtained: %v", emailNotificationInfo, notificationProducer.EmailNotificationInfo)
}
// Check the tenancy of edited authentication
requestParams := dao.RequestParams{TenantID: &tenantId}
authDao := dao.GetAuthenticationDao(&requestParams)
authOut, err := authDao.GetById(uid)
if err != nil {
t.Error(err)
}
if authOut.TenantID != tenantId {
t.Errorf("for authentication with DbID %d was expected tenant id %d, but got %d", authOut.DbID, tenantId, authOut.TenantID)
}
service.NotificationProducer = backupNotificationProducer
}
// TestAuthenticationEditInvalidTenant tests situation when the tenant tries to
// edit existing not owned authentication
func TestAuthenticationEditInvalidTenant(t *testing.T) {
testutils.SkipIfNotRunningIntegrationTests(t)
tenantId := int64(2)
uid := "1"
requestBody := m.AuthenticationEditRequest{
AvailabilityStatus: util.StringRef(m.InProgress),
}
body, err := json.Marshal(requestBody)
if err != nil {
t.Error("Could not marshal JSON")
}
c, rec := request.CreateTestContext(
http.MethodPatch,
"/api/sources/v3.1/authentications/1",
bytes.NewReader(body),
map[string]interface{}{
"tenantID": tenantId,
},
)
c.SetParamNames("uid")
c.SetParamValues(uid)
c.Request().Header.Add("Content-Type", "application/json;charset=utf-8")
notFoundAuthenticationEdit := ErrorHandlingContext(AuthenticationEdit)
err = notFoundAuthenticationEdit(c)
if err != nil {
t.Error(err)
}
templates.NotFoundTest(t, rec)
}
func TestAuthenticationEditNotFound(t *testing.T) {
newAvailabilityStatus := m.Available
requestBody := m.AuthenticationEditRequest{
AvailabilityStatus: &newAvailabilityStatus,
}
body, err := json.Marshal(requestBody)
if err != nil {
t.Error("Could not marshal JSON")
}
c, rec := request.CreateTestContext(
http.MethodPatch,
"/api/sources/v3.1/authentications/1",
bytes.NewReader(body),
map[string]interface{}{
"tenantID": int64(1),
},
)
c.SetParamNames("uid")
c.SetParamValues("not existing uid")
c.Request().Header.Add("Content-Type", "application/json;charset=utf-8")
notFoundAuthenticationEdit := ErrorHandlingContext(AuthenticationEdit)
err = notFoundAuthenticationEdit(c)
if err != nil {
t.Error(err)
}
templates.NotFoundTest(t, rec)
}
func TestAuthenticationEditBadRequest(t *testing.T) {
requestBody :=
`{
"name": 10
}`
body, err := json.Marshal(requestBody)
if err != nil {
t.Error("Could not marshal JSON")
}
c, rec := request.CreateTestContext(
http.MethodPatch,
"/api/sources/v3.1/authentications/1",
bytes.NewReader(body),
map[string]interface{}{
"tenantID": int64(1),
},
)
c.SetParamNames("uid")
c.SetParamValues(fixtures.TestAuthenticationData[0].ID)
c.Request().Header.Add("Content-Type", "application/json;charset=utf-8")
badRequestAuthenticationEdit := ErrorHandlingContext(AuthenticationEdit)
err = badRequestAuthenticationEdit(c)
if err != nil {
t.Error(err)
}
templates.BadRequestTest(t, rec)
}
func TestAuthenticationDelete(t *testing.T) {
testutils.SkipIfNotRunningIntegrationTests(t)
testutils.SkipIfNotSecretStoreDatabase(t)
tenantId := int64(1)
// Create new test data (source + authentication) for the test
// Create a source
requestParams := dao.RequestParams{TenantID: &tenantId}
sourceDao := dao.GetSourceDao(&requestParams)
src := m.Source{
Name: "Source for TestAuthenticationDelete()",
SourceTypeID: 1,
Uid: util.StringRef("b5cff4f3-4b1a-4f8d-b51a-5c8217ebc23b"),
}
err := sourceDao.Create(&src)
if err != nil {
t.Errorf("source not created correctly: %s", err)
}
// Create an authentication for the source
authenticationDao := dao.GetAuthenticationDao(&requestParams)
auth := m.Authentication{
Name: util.StringRef("authentication for source"),
ResourceType: "Source",
ResourceID: src.ID,
TenantID: tenantId,
SourceID: src.ID,
}
err = authenticationDao.Create(&auth)
if err != nil {
t.Errorf("authentication for source not created correctly: %s", err)
}
var uid string
if config.IsVaultOn() {
uid = auth.ID
} else {
uid = strconv.FormatInt(auth.DbID, 10)
}
c, rec := request.CreateTestContext(
http.MethodDelete,
"/api/sources/v3.1/authentications/"+uid,
nil,
map[string]interface{}{
"tenantID": tenantId,
},
)
c.SetParamNames("uid")
c.SetParamValues(uid)
c.Request().Header.Add("Content-Type", "application/json;charset=utf-8")
err = AuthenticationDelete(c)
if err != nil {
t.Error(err)
}
if rec.Code != http.StatusNoContent {
t.Errorf("Did not return 204. Body: %s", rec.Body.String())
}
if rec.Body.Len() != 0 {
t.Errorf("Response body is not nil")
}
// Check that the authentication is deleted
_, err = authenticationDao.GetById(uid)
if !errors.As(err, &util.ErrNotFound{}) {
t.Errorf("expected 'authentication not found', got %s", err)
}
// Delete created source
_, err = sourceDao.Delete(&src.ID)
if err != nil {
t.Error(err)
}
}
// TestAuthenticationDeleteInvalidTenant tests that not found is returned
// for tenant who doesn't own the authentication
func TestAuthenticationDeleteInvalidTenant(t *testing.T) {
testutils.SkipIfNotRunningIntegrationTests(t)
tenantId := int64(2)
var uid string
if config.IsVaultOn() {
uid = fixtures.TestAuthenticationData[0].ID
} else {
uid = strconv.FormatInt(fixtures.TestAuthenticationData[0].DbID, 10)
}
c, rec := request.CreateTestContext(
http.MethodDelete,
"/api/sources/v3.1/authentications/1",
nil,
map[string]interface{}{
"tenantID": tenantId,
},
)
c.SetParamNames("uid")
c.SetParamValues(uid)
c.Request().Header.Add("Content-Type", "application/json;charset=utf-8")
notFoundAuthenticationDelete := ErrorHandlingContext(AuthenticationDelete)
err := notFoundAuthenticationDelete(c)
if err != nil {
t.Error(err)
}
templates.NotFoundTest(t, rec)
}
func TestAuthenticationDeleteNotFound(t *testing.T) {
c, rec := request.CreateTestContext(
http.MethodDelete,
"/api/sources/v3.1/authentications/1",
nil,
map[string]interface{}{
"tenantID": int64(1),
},
)
c.SetParamNames("uid")
c.SetParamValues("not existing uid")
c.Request().Header.Add("Content-Type", "application/json;charset=utf-8")
notFoundAuthenticationDelete := ErrorHandlingContext(AuthenticationDelete)
err := notFoundAuthenticationDelete(c)
if err != nil {
t.Error(err)
}
templates.NotFoundTest(t, rec)
}
// HELPERS:
// checkAllAuthenticationsBelongToTenant checks that all returned authentications belong to given tenant
func checkAllAuthenticationsBelongToTenant(tenantId int64, authentications []interface{}) error {
for _, authOut := range authentications {
authOutId := authOut.(map[string]interface{})["id"].(string)
// find authentication in fixtures and check the tenant id
for _, auth := range fixtures.TestAuthenticationData {
if authOutId == auth.ID {
if auth.TenantID != tenantId {
return fmt.Errorf("expected tenant id = %d, got %d", tenantId, auth.TenantID)
}
}
}
}
return nil
}