Repository navigation
Expand file tree
/
Copy pathmain_test.go
More file actions
1401 lines (1254 loc) · 55.7 KB
/
Copy pathmain_test.go
File metadata and controls
1401 lines (1254 loc) · 55.7 KB
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2025 Nethesis S.r.l.
* http://www.nethesis.it - info@nethesis.it
*
* SPDX-License-Identifier: GPL-2.0-only
*
* author: Giacomo Sanchietti <giacomo.sanchietti@nethesis.it>
*/
package main
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
mathrand "math/rand"
"github.com/NethServer/nethsecurity-controller/api/configuration"
"github.com/NethServer/nethsecurity-controller/api/methods"
"github.com/NethServer/nethsecurity-controller/api/models"
"github.com/NethServer/nethsecurity-controller/api/storage"
"github.com/NethServer/nethsecurity-controller/api/utils"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/pquerna/otp/totp"
"github.com/stretchr/testify/assert"
)
var router *gin.Engine
// TestAESGCMEncryption tests AES-GCM encryption and decryption.
func TestAESGCMEncryption(t *testing.T) {
key := []byte("12345678901234567890123456789012") // AES-256, 32 byte
_, err := rand.Read(key)
if err != nil {
t.Fatalf("failed to generate random key: %v", err)
}
plaintext := []byte("Hello, AES-GCM encryption!")
ciphertext, err := utils.EncryptAESGCM(plaintext, key)
if err != nil {
t.Fatalf("encryption failed: %v", err)
}
if bytes.Equal(ciphertext, plaintext) {
t.Error("ciphertext should not match plaintext")
}
decrypted, err := utils.DecryptAESGCM(ciphertext, key)
if err != nil {
t.Fatalf("decryption failed: %v", err)
}
if !bytes.Equal(decrypted, plaintext) {
t.Errorf("decrypted text does not match original. got: %s, want: %s", decrypted, plaintext)
}
// Test with wrong key
wrongKey := make([]byte, 32)
_, err = rand.Read(wrongKey)
if err != nil {
t.Fatalf("failed to generate wrong key: %v", err)
}
_, err = utils.DecryptAESGCM(ciphertext, wrongKey)
if err == nil {
t.Error("decryption should fail with wrong key")
}
}
// TestAESGCMToString tests EncryptAESGCMToString and DecryptAESGCMFromString helpers.
func TestAESGCMToString(t *testing.T) {
key := []byte("12345678901234567890123456789012") // 32 bytes
plaintext := []byte("Store this in DB as base64!")
ciphertextB64, err := utils.EncryptAESGCMToString(plaintext, key)
if err != nil {
t.Fatalf("EncryptAESGCMToString failed: %v", err)
}
if ciphertextB64 == "" {
t.Error("ciphertextB64 should not be empty")
}
decrypted, err := utils.DecryptAESGCMFromString(ciphertextB64, key)
if err != nil {
t.Fatalf("DecryptAESGCMFromString failed: %v", err)
}
if !bytes.Equal(decrypted, plaintext) {
t.Errorf("decrypted text does not match original. got: %s, want: %s", decrypted, plaintext)
}
// Test with wrong key
wrongKey := []byte("abcdefghabcdefghabcdefghabcdefgh") // 32 bytes
_, err = utils.DecryptAESGCMFromString(ciphertextB64, wrongKey)
if err == nil {
t.Error("decryption should fail with wrong key")
}
}
func TestMultipleListenAddresses(t *testing.T) {
gin.SetMode(gin.TestMode)
router = setupRouter()
// Start two servers on different listeners
if len(configuration.Config.ListenAddress) < 2 {
t.Fatalf("expected at least 2 listen addresses, got %d", len(configuration.Config.ListenAddress))
}
servers := make([]*httptest.Server, 0, len(configuration.Config.ListenAddress))
for range configuration.Config.ListenAddress {
// Use httptest.Server to simulate listening on multiple addresses
ts := httptest.NewServer(router)
servers = append(servers, ts)
}
defer func() {
for _, ts := range servers {
ts.Close()
}
}()
// Test /health endpoint on all servers
for i, ts := range servers {
resp, err := http.Get(ts.URL + "/health")
if err != nil {
t.Fatalf("server %d: failed to GET /health: %v", i, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("server %d: expected status 200, got %d", i, resp.StatusCode)
}
}
}
// TestHealthEndpoint tests the /health endpoint.
func TestHealthEndpoint(t *testing.T) {
gin.SetMode(gin.TestMode)
router = setupRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/health", nil)
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
var resp map[string]interface{}
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if resp["status"] != "ok" {
t.Errorf("expected status 'ok', got %v", resp["status"])
}
}
func TestMainEndpoints(t *testing.T) {
// Tests assume to run on a clean database, otherwise 2FA tests will fail
gin.SetMode(gin.TestMode)
router = setupRouter()
var token string
t.Run("TestLoginEndpoint", func(t *testing.T) {
// Remove 2FA config from previous tests
os.RemoveAll(configuration.Config.SecretsDir + "/" + "admin")
w := httptest.NewRecorder()
var jsonResponse map[string]interface{}
body := `{"username": "admin", "password": "admin"}`
req, _ := http.NewRequest("POST", "/login", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
json.NewDecoder(w.Body).Decode(&jsonResponse)
token = jsonResponse["token"].(string)
assert.Equal(t, http.StatusOK, w.Code)
assert.NotEmpty(t, token)
assert.True(t, methods.CheckTokenValidation("admin", token))
})
t.Run("TestRefreshEndpoint", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/refresh", nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
})
t.Run("TestGet2FAStatusEndpoint", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/2fa", nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
})
t.Run("TestLogoutEndpoint", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/logout", nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.False(t, methods.CheckTokenValidation("admin", token))
})
t.Run("TestGetAccountsEndpoint", func(t *testing.T) {
// Login again
var jsonResponse map[string]interface{}
w := httptest.NewRecorder()
body := `{"username": "admin", "password": "admin"}`
req, _ := http.NewRequest("POST", "/login", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
json.NewDecoder(w.Body).Decode(&jsonResponse)
token = jsonResponse["token"].(string)
req, _ = http.NewRequest("GET", "/accounts", nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code, w.Body.String())
// response is: gin.H{"accounts": accounts, "total": len(accounts)},
json.NewDecoder(w.Body).Decode(&jsonResponse)
data := jsonResponse["data"].(map[string]interface{})
assert.Equal(t, data["accounts"].([]interface{})[0].(map[string]interface{})["username"], "admin")
assert.Equal(t, data["accounts"].([]interface{})[0].(map[string]interface{})["display_name"], "Administrator")
assert.Equal(t, data["accounts"].([]interface{})[0].(map[string]interface{})["two_fa"], false)
})
t.Run("TestAddUpdateDeleteAccount", func(t *testing.T) {
w := httptest.NewRecorder()
// Add account
addBody := `{"username": "testuser", "password": "testpass", "admin": false, "display_name": "Test User"}`
addReq, _ := http.NewRequest("POST", "/accounts", bytes.NewBuffer([]byte(addBody)))
addReq.Header.Set("Content-Type", "application/json")
addReq.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, addReq)
assert.Equal(t, http.StatusCreated, w.Code)
var addResp map[string]interface{}
json.NewDecoder(w.Body).Decode(&addResp)
id := fmt.Sprintf("%v", addResp["data"].(map[string]interface{})["id"])
assert.NotEmpty(t, id)
// Get accounts to find the new account's ID
w = httptest.NewRecorder()
getReq, _ := http.NewRequest("GET", "/accounts", nil)
getReq.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, getReq)
var getResp map[string]interface{}
json.NewDecoder(w.Body).Decode(&getResp)
accounts := getResp["data"].(map[string]interface{})["accounts"].([]interface{})
var testAccountID string
for _, acc := range accounts {
accMap := acc.(map[string]interface{})
if accMap["username"] == "testuser" {
testAccountID = fmt.Sprintf("%v", accMap["id"])
}
}
assert.NotEmpty(t, testAccountID)
// Update account display name
updateBody := `{"display_name": "Updated User", "unit_groups": [], "admin": false}`
updateReq, _ := http.NewRequest("PUT", "/accounts/"+testAccountID, bytes.NewBuffer([]byte(updateBody)))
updateReq.Header.Set("Content-Type", "application/json")
updateReq.Header.Set("Authorization", "Bearer "+token)
w = httptest.NewRecorder()
router.ServeHTTP(w, updateReq)
assert.Equal(t, http.StatusOK, w.Code)
// Get account and check display name
w = httptest.NewRecorder()
getOneReq, _ := http.NewRequest("GET", "/accounts/"+testAccountID, nil)
getOneReq.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, getOneReq)
var getOneResp map[string]interface{}
json.NewDecoder(w.Body).Decode(&getOneResp)
accData := getOneResp["data"].(map[string]interface{})["account"].(map[string]interface{})
assert.Equal(t, "Updated User", accData["display_name"])
// Delete account
w = httptest.NewRecorder()
deleteReq, _ := http.NewRequest("DELETE", "/accounts/"+testAccountID, nil)
deleteReq.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, deleteReq)
assert.Equal(t, http.StatusOK, w.Code)
// Ensure account is deleted
w = httptest.NewRecorder()
getOneReq, _ = http.NewRequest("GET", "/accounts/"+testAccountID, nil)
getOneReq.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, getOneReq)
assert.Equal(t, http.StatusNotFound, w.Code)
})
t.Run("TestRegisterUnitEndpoint", func(t *testing.T) {
// create credentials directory
if _, err := os.Stat(configuration.Config.CredentialsDir); os.IsNotExist(err) {
if err := os.MkdirAll(configuration.Config.CredentialsDir, 0755); err != nil {
t.Fatalf("failed to create directory: %v", err)
}
}
// make sure configuration.Config.OpenVPNPKIDir does not exists
os.RemoveAll(configuration.Config.OpenVPNPKIDir)
unitID := "88860838-63bd-4717-a6c3-cbc351010843"
body := `{"unit_id": "` + unitID + `", "username": "myuser", "unit_name": "myname", "password": "mypassword"}`
req, _ := http.NewRequest("POST", "/units/register", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("RegistrationToken", "1234")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusForbidden, w.Code)
// create OpenVPN directory
if _, err := os.Stat(configuration.Config.OpenVPNPKIDir + "/issued"); os.IsNotExist(err) {
if err := os.MkdirAll(configuration.Config.OpenVPNPKIDir+"/issued", 0755); err != nil {
t.Fatalf("failed to create directory: %v", err)
}
if err := os.MkdirAll(configuration.Config.OpenVPNPKIDir+"/private", 0755); err != nil {
t.Fatalf("failed to create directory: %v", err)
}
}
// create fake certificate file and key file
if _, err := os.Create(configuration.Config.OpenVPNPKIDir + "/issued/" + unitID + ".crt"); err != nil {
t.Fatalf("failed to create file: %v", err)
}
if _, err := os.Create(configuration.Config.OpenVPNPKIDir + "/private/" + unitID + ".key"); err != nil {
t.Fatalf("failed to create file: %v", err)
}
// create face ca.crt file
if _, err := os.Create(configuration.Config.OpenVPNPKIDir + "/ca.crt"); err != nil {
t.Fatalf("failed to create file: %v", err)
}
req, _ = http.NewRequest("POST", "/units/register", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("RegistrationToken", "1234")
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code, w.Body.String())
// Check password retrieval at lower level
user, pass, err := storage.GetUnitCredentials(unitID) // should return empty credentials
assert.NoError(t, err, "GetUnitCredentials should not return an error")
assert.Equal(t, "myuser", user)
assert.Equal(t, "mypassword", pass)
})
t.Run("TestRegisterUnitUsernameBinding", func(t *testing.T) {
unitID := "88860838-63bd-4717-a6c3-cbc351010843"
// a registration presenting a different username is refused
body := `{"unit_id": "` + unitID + `", "username": "otheruser", "unit_name": "myname", "password": "otherpassword"}`
req, _ := http.NewRequest("POST", "/units/register", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("RegistrationToken", "1234")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusForbidden, w.Code)
assert.NotContains(t, w.Body.String(), "key")
// the stored credentials must be left untouched
user, pass, err := storage.GetUnitCredentials(unitID)
assert.NoError(t, err)
assert.Equal(t, "myuser", user)
assert.Equal(t, "mypassword", pass)
// the bound username can still register and rotate its password
body = `{"unit_id": "` + unitID + `", "username": "myuser", "unit_name": "myname", "password": "newpassword"}`
req, _ = http.NewRequest("POST", "/units/register", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("RegistrationToken", "1234")
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code, w.Body.String())
user, pass, err = storage.GetUnitCredentials(unitID)
assert.NoError(t, err)
assert.Equal(t, "myuser", user)
assert.Equal(t, "newpassword", pass)
})
t.Run("TestRegisterUnitPerUnitToken", func(t *testing.T) {
unitID := "0d6cf6f4-2f32-4a5f-9a27-3b9a63f6a1cb"
unitToken := "a-token-of-its-own"
// a unit added with its own token only accepts that one
if err := storage.AddUnit(unitID, "172.21.0.9", unitToken); err != nil {
t.Fatalf("failed to add unit: %v", err)
}
for _, name := range []string{"/issued/" + unitID + ".crt", "/private/" + unitID + ".key"} {
if _, err := os.Create(configuration.Config.OpenVPNPKIDir + name); err != nil {
t.Fatalf("failed to create file: %v", err)
}
}
body := `{"unit_id": "` + unitID + `", "username": "myuser", "unit_name": "myname", "password": "mypassword"}`
req, _ := http.NewRequest("POST", "/units/register", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("RegistrationToken", "1234") // the fleet-wide token
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
assert.NotContains(t, w.Body.String(), "key")
// the token of another unit is not accepted either
req, _ = http.NewRequest("POST", "/units/register", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("RegistrationToken", "another-unit-token")
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
// its own token works
req, _ = http.NewRequest("POST", "/units/register", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("RegistrationToken", unitToken)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code, w.Body.String())
// the join code carries the per-unit token, not the fleet-wide one
unit, err := storage.GetUnit(unitID)
assert.NoError(t, err)
decoded, err := base64.StdEncoding.DecodeString(unit["join_code"].(string))
assert.NoError(t, err)
var joinCode map[string]interface{}
assert.NoError(t, json.Unmarshal(decoded, &joinCode))
assert.Equal(t, unitToken, joinCode["token"])
storage.DeleteUnit(unitID)
})
t.Run("TestIngestPerUnitToken", func(t *testing.T) {
unitID := "6f1f6d6a-1c7a-4a5e-9c31-0d2a1b7e4c55"
unitToken := "ingest-token-of-its-own"
if err := storage.AddUnit(unitID, "172.21.0.10", unitToken); err != nil {
t.Fatalf("failed to add unit: %v", err)
}
if _, err := os.Create(configuration.Config.OpenVPNPKIDir + "/issued/" + unitID + ".crt"); err != nil {
t.Fatalf("failed to create file: %v", err)
}
body := `{"unit_name": "myname"}`
post := func(user string, pass string) int {
req, _ := http.NewRequest("POST", "/ingest/info", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(user, pass)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
return w.Code
}
// the fleet-wide token no longer works for a unit that has its own
assert.Equal(t, http.StatusUnauthorized, post(unitID, "1234"))
// nor does the token of another unit
assert.Equal(t, http.StatusUnauthorized, post(unitID, "another-unit-token"))
// a malformed unit id is refused without reaching the database
assert.Equal(t, http.StatusUnauthorized, post("not-a-uuid", unitToken))
// its own token works
assert.Equal(t, http.StatusOK, post(unitID, unitToken))
storage.DeleteUnit(unitID)
})
t.Run("TestRegisterUnitWithoutFleetToken", func(t *testing.T) {
// a new installation ships without a fleet-wide token
original := configuration.Config.RegistrationToken
configuration.Config.RegistrationToken = ""
defer func() { configuration.Config.RegistrationToken = original }()
unitID := "3a1e3c02-9d0a-4a31-8f5e-2f7f0a1d4b77"
if err := storage.AddUnit(unitID, "172.21.0.11", ""); err != nil {
t.Fatalf("failed to add unit: %v", err)
}
if _, err := os.Create(configuration.Config.OpenVPNPKIDir + "/issued/" + unitID + ".crt"); err != nil {
t.Fatalf("failed to create file: %v", err)
}
// a unit without its own token has nothing left to fall back on
body := `{"unit_id": "` + unitID + `", "username": "myuser", "unit_name": "myname", "password": "mypassword"}`
req, _ := http.NewRequest("POST", "/units/register", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("RegistrationToken", "1234")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
assert.NotContains(t, w.Body.String(), "key")
// an empty token must not match the empty expected one either
req, _ = http.NewRequest("POST", "/units/register", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("RegistrationToken", " ")
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
// same on the ingest path
ingest, _ := http.NewRequest("POST", "/ingest/info", bytes.NewBuffer([]byte(`{"unit_name": "myname"}`)))
ingest.Header.Set("Content-Type", "application/json")
ingest.SetBasicAuth(unitID, "1234")
w = httptest.NewRecorder()
router.ServeHTTP(w, ingest)
assert.Equal(t, http.StatusUnauthorized, w.Code)
storage.DeleteUnit(unitID)
})
t.Run("TestNoRoute", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/nonexistent", nil)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusNotFound, w.Code)
})
// 2FA test: enable, verify with OTP, verify with recovery code, remove
t.Run("Test2FAEnableVerifyRemove", func(t *testing.T) {
w := httptest.NewRecorder()
// Execute login to get token
var jsonResponse map[string]interface{}
body := `{"username": "admin", "password": "admin"}`
req, _ := http.NewRequest("POST", "/login", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
json.NewDecoder(w.Body).Decode(&jsonResponse)
token = jsonResponse["token"].(string)
assert.Equal(t, http.StatusOK, w.Code)
assert.NotEmpty(t, token)
// Enable 2FA (get QR code and secret)
qrReq, _ := http.NewRequest("GET", "/2fa/qr-code", nil)
qrReq.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, qrReq)
assert.Equal(t, http.StatusOK, w.Code)
var qrResp map[string]interface{}
json.NewDecoder(w.Body).Decode(&qrResp)
secret := qrResp["data"].(map[string]interface{})["key"].(string)
assert.NotEmpty(t, secret)
otp, err := totp.GenerateCode(secret, time.Now())
assert.NoError(t, err)
assert.NotEmpty(t, otp)
// Verify 2FA login with OTP code
otpBody := map[string]string{"username": "admin", "token": token, "otp": otp}
otpBodyBytes, _ := json.Marshal(otpBody)
otpReq, _ := http.NewRequest("POST", "/2fa/otp-verify", bytes.NewBuffer(otpBodyBytes))
otpReq.Header.Set("Content-Type", "application/json")
w = httptest.NewRecorder()
router.ServeHTTP(w, otpReq)
assert.Equal(t, http.StatusOK, w.Code)
// Get recovery codes
w = httptest.NewRecorder()
statusReq, _ := http.NewRequest("GET", "/2fa", nil)
statusReq.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, statusReq)
assert.Equal(t, http.StatusOK, w.Code)
var statusResp map[string]interface{}
json.NewDecoder(w.Body).Decode(&statusResp)
recoveryCodes := statusResp["data"].(map[string]interface{})["recovery_codes"].([]interface{})
assert.NotEmpty(t, recoveryCodes)
recoveryCode := recoveryCodes[0].(string)
// Verify 2FA login with recovery code
recBody := map[string]string{"username": "admin", "token": token, "otp": recoveryCode}
recBodyBytes, _ := json.Marshal(recBody)
recReq, _ := http.NewRequest("POST", "/2fa/otp-verify", bytes.NewBuffer(recBodyBytes))
recReq.Header.Set("Content-Type", "application/json")
w = httptest.NewRecorder()
router.ServeHTTP(w, recReq)
assert.Equal(t, http.StatusOK, w.Code)
// Remove 2FA
w = httptest.NewRecorder()
delReq, _ := http.NewRequest("DELETE", "/2fa", nil)
delReq.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, delReq)
assert.Equal(t, http.StatusOK, w.Code)
// Check 2FA is disabled
w = httptest.NewRecorder()
statusReq, _ = http.NewRequest("GET", "/2fa", nil)
statusReq.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, statusReq)
assert.Equal(t, http.StatusOK, w.Code)
var statusResp2fa map[string]interface{}
json.NewDecoder(w.Body).Decode(&statusResp2fa)
assert.Equal(t, false, statusResp2fa["data"].(map[string]interface{})["status"])
// recovery codes should be empty
assert.Equal(t, []interface{}{}, statusResp2fa["data"].(map[string]interface{})["recovery_codes"])
})
// 2FA test partial setup (issue #1376)
t.Run("Test2FAPartialSetup", func(t *testing.T) {
w := httptest.NewRecorder()
// Execute login to get token
var jsonResponse map[string]interface{}
body := `{"username": "admin", "password": "admin"}`
req, _ := http.NewRequest("POST", "/login", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
json.NewDecoder(w.Body).Decode(&jsonResponse)
token = jsonResponse["token"].(string)
assert.Equal(t, http.StatusOK, w.Code)
assert.NotEmpty(t, token)
// Enable 2FA (get QR code and secret)
qrReq, _ := http.NewRequest("GET", "/2fa/qr-code", nil)
qrReq.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, qrReq)
assert.Equal(t, http.StatusOK, w.Code)
var qrResp map[string]interface{}
json.NewDecoder(w.Body).Decode(&qrResp)
secret := qrResp["data"].(map[string]interface{})["key"].(string)
assert.NotEmpty(t, secret)
otp, err := totp.GenerateCode(secret, time.Now())
assert.NoError(t, err)
assert.NotEmpty(t, otp)
// Check 2FA is disabled
w = httptest.NewRecorder()
statusReq, _ := http.NewRequest("GET", "/2fa", nil)
statusReq.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, statusReq)
assert.Equal(t, http.StatusOK, w.Code)
var statusResp2fa map[string]interface{}
json.NewDecoder(w.Body).Decode(&statusResp2fa)
assert.Equal(t, false, statusResp2fa["data"].(map[string]interface{})["status"])
// recovery codes should be empty
assert.Equal(t, []interface{}{}, statusResp2fa["data"].(map[string]interface{})["recovery_codes"])
})
}
func addUnit(t *testing.T) string {
// Generate a UUID v4 and convert it to string using the uuid package
unitID := uuid.New().String()
if _, err := os.Stat(configuration.Config.CredentialsDir); os.IsNotExist(err) {
os.MkdirAll(configuration.Config.CredentialsDir, 0755)
}
if _, err := os.Stat(configuration.Config.OpenVPNCCDDir); os.IsNotExist(err) {
os.MkdirAll(configuration.Config.OpenVPNCCDDir, 0755)
}
if _, err := os.Stat(configuration.Config.OpenVPNPKIDir); os.IsNotExist(err) {
os.MkdirAll(configuration.Config.OpenVPNPKIDir, 0755)
}
if _, err := os.Stat(configuration.Config.OpenVPNStatusDir); os.IsNotExist(err) {
os.MkdirAll(configuration.Config.OpenVPNStatusDir, 0755)
}
// Create fake credentials, ccd and cr files, otherwise GetUnit will fail
creds := map[string]string{"username": "testuser", "password": "testpass"}
credsBytes, _ := json.Marshal(creds)
werr := os.WriteFile(configuration.Config.CredentialsDir+"/"+unitID, credsBytes, 0644)
assert.NoError(t, werr, "failed to write credentials file")
assert.NoError(t, werr, "failed to write ccd file")
if _, err := os.Stat(configuration.Config.OpenVPNPKIDir + "/issued/" + unitID + ".crt"); os.IsNotExist(err) {
if _, err := os.Create(configuration.Config.OpenVPNPKIDir + "/issued/" + unitID + ".crt"); err != nil {
t.Fatalf("failed to create certificate file: %v", err)
}
}
// Manually add to the database: we can't call /units POST endpoint because
// it requires the presence of easyrsa binary and configuration files
newIp := storage.GetFreeIP()
storage.AddUnit(unitID, newIp, "")
return unitID
}
func TestAddInfoAndGetRemoteInfo(t *testing.T) {
gin.SetMode(gin.TestMode)
router = setupRouter()
// Simulate an add unit
unitID := addUnit(t)
// AddInfo: POST /ingest/info (simulate BasicAuth middleware)
w := httptest.NewRecorder()
info := models.UnitInfo{
UnitName: "my-test-unit",
Version: "1.0.0",
VersionUpdate: "1.0.1",
ScheduledUpdate: 0,
SubscriptionType: "test-subscription",
SystemID: "test-system-id",
SSHPort: 22,
FQDN: "test.example.com",
APIVersion: "v1",
}
infoBytes, _ := json.Marshal(info)
req := httptest.NewRequest("POST", "/ingest/info", bytes.NewBuffer(infoBytes))
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(unitID, "1234")
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code, "AddInfo should return 200 OK")
w = httptest.NewRecorder()
var jsonResponse map[string]interface{}
body := `{"username": "admin", "password": "admin"}`
req, _ = http.NewRequest("POST", "/login", bytes.NewBuffer([]byte(body)))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
json.NewDecoder(w.Body).Decode(&jsonResponse)
token := jsonResponse["token"].(string)
// Call /units/:unit_id to retrieve unit info
req = httptest.NewRequest("GET", "/units/"+unitID, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
json.NewDecoder(w.Body).Decode(&jsonResponse)
infoResp := jsonResponse["data"].(map[string]interface{})["info"].(map[string]interface{})
assert.Equal(t, info.UnitName, infoResp["unit_name"])
assert.Equal(t, info.Version, infoResp["version"])
assert.Equal(t, info.VersionUpdate, infoResp["version_update"])
assert.Equal(t, float64(info.ScheduledUpdate), infoResp["scheduled_update"])
assert.Equal(t, info.SubscriptionType, infoResp["subscription_type"])
assert.Equal(t, info.SystemID, infoResp["system_id"])
assert.Equal(t, float64(info.SSHPort), infoResp["ssh_port"])
assert.Equal(t, info.FQDN, infoResp["fqdn"])
assert.Equal(t, info.APIVersion, infoResp["api_version"])
ipaddress := jsonResponse["data"].(map[string]interface{})["ipaddress"].(string)
assert.True(t, strings.HasPrefix(ipaddress, "172.21.0"), "ipaddress should start with 172.21.0, got: %v", ipaddress)
netmask := jsonResponse["data"].(map[string]interface{})["netmask"].(string)
assert.Equal(t, configuration.Config.OpenVPNNetmask, netmask, "OpenVPNNetmask should match the one in configuration, got: %v", netmask)
}
func TestForwardedAuthMiddleware(t *testing.T) {
gin.SetMode(gin.TestMode)
router = setupRouter()
// Test with valid credentials
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/auth", nil)
req.SetBasicAuth("admin", "admin") // Use BasicAuth for testing
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code, w.Body.String())
// Check if X-Auth-User header is set
authUser := w.Header().Get("X-Auth-User")
assert.Equal(t, "admin", authUser, "X-Auth-User header should be set to 'admin'")
// Test with invalid credentials
w = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/auth", nil)
req.SetBasicAuth("admin", "wrongpassword") // Use BasicAuth for testing
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code, w.Body.String())
}
func TestGetPlatformInfo(t *testing.T) {
router = setupRouter()
// Step 1: Login and get token
loginBody := []byte(`{"username":"admin","password":"admin"}`)
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/login", bytes.NewBuffer(loginBody))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var loginResp map[string]interface{}
_ = json.NewDecoder(w.Body).Decode(&loginResp)
token, ok := loginResp["token"].(string)
assert.True(t, ok)
assert.NotEmpty(t, token)
// Step 2: Call GET /platform with token
w = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/platform", nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
platformInfoEnv := os.Getenv("PLATFORM_INFO")
var platformInfo map[string]interface{}
err := json.Unmarshal([]byte(platformInfoEnv), &platformInfo)
assert.NoError(t, err)
// Step 3: Check response
var resp map[string]interface{}
_ = json.NewDecoder(w.Body).Decode(&resp)
assert.Equal(t, float64(200), resp["code"])
assert.Equal(t, "success", resp["message"])
data, ok := resp["data"].(map[string]interface{})
assert.True(t, ok)
assert.Equal(t, "1194", data["vpn_port"])
assert.Equal(t, "192.168.100.0/24", data["vpn_network"])
assert.Equal(t, "1.0.0", data["controller_version"])
assert.Equal(t, float64(30), data["metrics_retention_days"])
assert.Equal(t, float64(90), data["logs_retention_days"])
}
func TestUnitGroupsAPI(t *testing.T) {
router = setupRouter()
unitId_1 := addUnit(t)
unitId_2 := addUnit(t)
randCounter := fmt.Sprintf("%d", mathrand.New(mathrand.NewSource(time.Now().UnixNano())).Intn(10000))
// Login to get token
w := httptest.NewRecorder()
loginBody := []byte(`{"username":"admin","password":"admin"}`)
req, _ := http.NewRequest("POST", "/login", bytes.NewBuffer(loginBody))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var loginResp map[string]interface{}
_ = json.NewDecoder(w.Body).Decode(&loginResp)
token, ok := loginResp["token"].(string)
assert.True(t, ok)
assert.NotEmpty(t, token)
// Create an empty unit group
w = httptest.NewRecorder()
// generate a random group name composed by testgroups + random number from 1 to 1000
groupName := fmt.Sprintf("testgroups%s", randCounter)
groupBody := []byte(`{"name":"` + groupName + `","description":"desc"}`)
req, _ = http.NewRequest("POST", "/unit_groups", bytes.NewBuffer(groupBody))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusCreated, w.Code, w.Body.String())
var groupResp map[string]interface{}
_ = json.NewDecoder(w.Body).Decode(&groupResp)
groupData := groupResp["data"].(map[string]interface{})
groupID := fmt.Sprintf("%v", groupData["id"])
assert.NotEmpty(t, groupID)
// Update the group with units
w = httptest.NewRecorder()
updateBody := []byte(`{"name":"` + groupName + `","description":"desc", "units":["` + unitId_1 + `", "` + unitId_2 + `"]}`)
req, _ = http.NewRequest("PUT", "/unit_groups/"+groupID, bytes.NewBuffer([]byte(updateBody)))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code, w.Body.String())
// List unit groups
w = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/unit_groups", nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
// Get the created unit group
w = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/unit_groups/"+groupID, nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var getGroupResp map[string]interface{}
_ = json.NewDecoder(w.Body).Decode(&getGroupResp)
groupData = getGroupResp["data"].(map[string]interface{})
assert.Equal(t, groupName, groupData["name"])
assert.Equal(t, "desc", groupData["description"])
units := groupData["units"].([]interface{})
assert.Len(t, units, 2)
assert.Contains(t, units, unitId_1)
assert.Contains(t, units, unitId_2)
// Update the unit group
w = httptest.NewRecorder()
updateBody = []byte(`{"name":"updatedgroup` + randCounter + `","description":"updated desc", "units":["` + unitId_1 + `", "` + unitId_2 + `"]}}`)
req, _ = http.NewRequest("PUT", "/unit_groups/"+groupID, bytes.NewBuffer(updateBody))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
// Get the updated unit group and check the new name and description
w = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/unit_groups/"+groupID, nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var updatedGroupResp map[string]interface{}
_ = json.NewDecoder(w.Body).Decode(&updatedGroupResp)
updatedGroupData := updatedGroupResp["data"].(map[string]interface{})
assert.Equal(t, "updatedgroup"+randCounter, updatedGroupData["name"])
assert.Equal(t, "updated desc", updatedGroupData["description"])
// Try to update the group with a non-existing unit, expect failure (400)
w = httptest.NewRecorder()
nonExistingUnitID := uuid.New().String()
updateBody = []byte(`{"name":"` + groupName + `","description":"desc", "units":["` + unitId_1 + `", "` + nonExistingUnitID + `"]}`)
req, _ = http.NewRequest("PUT", "/unit_groups/"+groupID, bytes.NewBuffer(updateBody))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code, "should fail when adding non-existing unit to group")
// Add limited user account
w = httptest.NewRecorder()
limitedUserName := fmt.Sprintf("limited%s", randCounter)
addBody := `{"username": "` + limitedUserName + `", "password": "limited", "display_name": "Limited user"}`
addReq, _ := http.NewRequest("POST", "/accounts", bytes.NewBuffer([]byte(addBody)))
addReq.Header.Set("Content-Type", "application/json")
addReq.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, addReq)
assert.Equal(t, http.StatusCreated, w.Code)
var addUserResp map[string]interface{}
json.NewDecoder(w.Body).Decode(&addUserResp)
testAccountID := fmt.Sprintf("%v", addUserResp["data"].(map[string]interface{})["id"])
assert.NotEmpty(t, testAccountID)
// Try to add a non-existing group ID to the user account, expect failure
w = httptest.NewRecorder()
nonExistingGroupID := "9999999"
addUserBody := []byte(`{"username":"` + limitedUserName + `","unit_groups":[` + nonExistingGroupID + `]}`)
req, _ = http.NewRequest("PUT", "/accounts/"+testAccountID, bytes.NewBuffer(addUserBody))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code, "should fail when adding non-existing group ID")
// Delete unitId_1, it must be removed from the group
w = httptest.NewRecorder()
req, _ = http.NewRequest("DELETE", "/units/"+unitId_1, nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code, "deleting unitId_1 should succeed")
// Get the unit group again and check that unitId_1 is removed
w = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/unit_groups/"+groupID, nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var afterDeleteUpdatedGroupResp map[string]interface{}
_ = json.NewDecoder(w.Body).Decode(&afterDeleteUpdatedGroupResp)
afterDeleteUpdatedGroupData := afterDeleteUpdatedGroupResp["data"].(map[string]interface{})
units = afterDeleteUpdatedGroupData["units"].([]interface{})
assert.Len(t, units, 1, "unitId_1 should be removed from the group")
assert.Contains(t, units, unitId_2, "unitId_2 should still be in the group")
assert.NotContains(t, units, unitId_1, "unitId_1 should not be in the group anymore")
// Add unit group to user account
w = httptest.NewRecorder()
addUserBody = []byte(`{"username":"` + limitedUserName + `","unit_groups":[` + groupID + `]}`)
req, _ = http.NewRequest("PUT", "/accounts/"+testAccountID, bytes.NewBuffer(addUserBody))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code, w.Body.String())
// Delete the unit group: should fail because it is associated with an account
w = httptest.NewRecorder()
req, _ = http.NewRequest("DELETE", "/unit_groups/"+groupID, nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.NotEqual(t, http.StatusOK, w.Code, "should not allow deleting a group associated with an account")
assert.True(t, w.Code == http.StatusBadRequest, "expected 400 when deleting a group in use")
// Remove the group from the user account's unit_groups
w = httptest.NewRecorder()
removeGroupBody := []byte(`{"username":"` + limitedUserName + `","unit_groups":[]}`)
req, _ = http.NewRequest("PUT", "/accounts/"+testAccountID, bytes.NewBuffer(removeGroupBody))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code, w.Body.String())
// Now delete the unit group again, should succeed
w = httptest.NewRecorder()
req, _ = http.NewRequest("DELETE", "/unit_groups/"+groupID, nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code, "should allow deleting a group not associated with any account")
// Get the account again and check that unit_groups does not contain groupID
w = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/accounts/"+testAccountID, nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var getAccountAfterDeleteResp map[string]interface{}
_ = json.NewDecoder(w.Body).Decode(&getAccountAfterDeleteResp)
accountAfterDeleteData := getAccountAfterDeleteResp["data"].(map[string]interface{})["account"].(map[string]interface{})
unitGroups := accountAfterDeleteData["unit_groups"].([]interface{})
for _, v := range unitGroups {
assert.NotEqual(t, groupID, fmt.Sprintf("%.0f", v), "unit_groups should not contain deleted groupID")
}
// Create a new group and add unitId_1 to it
w = httptest.NewRecorder()
groupName2 := fmt.Sprintf("group2_%s", randCounter)
groupBody2 := []byte(`{"name":"` + groupName2 + `","description":"desc2", "units":["` + unitId_1 + `"]}`)
req, _ = http.NewRequest("POST", "/unit_groups", bytes.NewBuffer(groupBody2))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusCreated, w.Code, w.Body.String())
var group2Resp map[string]interface{}
_ = json.NewDecoder(w.Body).Decode(&group2Resp)
group2Data := group2Resp["data"].(map[string]interface{})
group2ID := fmt.Sprintf("%v", group2Data["id"])
assert.NotEmpty(t, group2ID)
// Get the group and check that unitId_1 is present
w = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/unit_groups/"+group2ID, nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var getGroup3Resp map[string]interface{}
_ = json.NewDecoder(w.Body).Decode(&getGroup3Resp)
group2Data = getGroup3Resp["data"].(map[string]interface{})
units2 := group2Data["units"].([]interface{})
assert.Len(t, units2, 1, "group2 should contain exactly one unit")
assert.Equal(t, unitId_1, fmt.Sprintf("%v", units2[0]), "unitId_1 should be present in group2")