Repository navigation
Expand file tree
/
Copy pathapi_test.go
More file actions
1675 lines (1496 loc) · 63.8 KB
/
Copy pathapi_test.go
File metadata and controls
1675 lines (1496 loc) · 63.8 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
package main
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/tracyhatemice/who/internal/auth"
"github.com/tracyhatemice/who/internal/storage"
)
const (
testAdminSub = "sub-owner-1"
testAdminEmail = "owner@example.org"
testAdminName = "Site Owner"
testSessionRaw = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
)
type apiTestHarness struct {
t *testing.T
db *storage.DB
srv *Server
logger *AccessLogger
mux *http.ServeMux
sessCookie *http.Cookie
sessHash string
}
func newAPITestHarness(t *testing.T, basePath, ddnsEndpoint string) *apiTestHarness {
t.Helper()
ctx := context.Background()
db, _ := openAccessLogTestDB(t)
logger := NewAccessLogger(db)
t.Cleanup(func() {
_ = logger.Close(ctx)
})
mgr, err := auth.NewManager(auth.Config{
Issuer: "https://idp.example.org",
ClientID: "who-admin",
BasePath: basePath,
AllowedEmails: []string{testAdminEmail},
}, db, getClientIP)
if err != nil {
t.Fatalf("auth.NewManager: %v", err)
}
sessHash := sha256Hex(testSessionRaw)
now := time.Now().Unix()
if sessErr := db.CreateSession(ctx, storage.Session{
TokenHash: sessHash,
Sub: testAdminSub,
Email: testAdminEmail,
EmailVerified: true,
Name: testAdminName,
IP: "198.51.100.42",
UserAgent: "who-api-test/1.0",
CreatedAt: now - 120,
LastSeenAt: now - 10,
ExpiresAt: now + 86400,
}); sessErr != nil {
t.Fatalf("CreateSession: %v", sessErr)
}
srv := &Server{
db: db,
store: NewStore(),
accessLog: logger,
auth: mgr,
ddnsEndpoint: ddnsEndpoint,
}
if reloadErr := srv.ReloadFromDB(ctx); reloadErr != nil {
t.Fatalf("ReloadFromDB: %v", reloadErr)
}
mux := http.NewServeMux()
mux.HandleFunc("GET /whoami", srv.WrapPublic("whoami", srv.whoamiHandler))
mux.HandleFunc("GET /whoami/headers", srv.WrapPublic("whoami_headers", srv.whoamiHeadersHandler))
mux.HandleFunc("GET /iam/{name}", srv.WrapPublic("iam", srv.iamHandler))
mux.HandleFunc("GET /iam/{name}/{ip}", srv.WrapPublic("iam", srv.iamHandler))
mux.HandleFunc("GET /whois/{name}", srv.WrapPublic("whois", srv.whoisHandler))
apiPrefix := "/api/v1/"
if basePath != "" && basePath != "/" {
apiPrefix = strings.TrimRight(basePath, "/") + "/api/v1/"
}
mux.Handle(apiPrefix, srv.AdminAPIHandler(basePath))
return &apiTestHarness{
t: t,
db: db,
srv: srv,
logger: logger,
mux: mux,
sessCookie: &http.Cookie{
Name: "who_session",
Value: testSessionRaw,
},
sessHash: sessHash,
}
}
func (h *apiTestHarness) doJSON(method, target string, body any) *httptest.ResponseRecorder {
h.t.Helper()
return h.doJSONWithHeaders(method, target, body, nil)
}
func (h *apiTestHarness) doJSONWithHeaders(
method, target string,
body any,
headers map[string]string,
) *httptest.ResponseRecorder {
h.t.Helper()
var reader io.Reader
if body != nil {
raw, err := json.Marshal(body)
if err != nil {
h.t.Fatalf("marshal request body: %v", err)
}
reader = bytes.NewReader(raw)
}
req := httptest.NewRequest(method, target, reader)
req.AddCookie(h.sessCookie)
req.Header.Set("X-Forwarded-For", "198.51.100.42")
req.Header.Set("User-Agent", "who-api-test/1.0")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if method != http.MethodGet && method != http.MethodHead {
req.Header.Set(auth.CSRFHeader, "1")
}
for k, v := range headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
h.mux.ServeHTTP(rec, req)
return rec
}
func assertAPIStatus(t *testing.T, rec *httptest.ResponseRecorder, want int, label string) {
t.Helper()
if rec.Code != want {
t.Fatalf("%s: status = %d, want %d (body: %s)", label, rec.Code, want, rec.Body.String())
}
}
func decodeAPIJSON(t *testing.T, rec *httptest.ResponseRecorder, dst any, label string) {
t.Helper()
if err := json.Unmarshal(rec.Body.Bytes(), dst); err != nil {
t.Fatalf("%s: decode JSON: %v (body: %s)", label, err, rec.Body.String())
}
}
func verifyRoute53SigV4(r *http.Request, payload []byte, wantAccessKey, wantSecretKey string) bool {
amzDate := r.Header.Get("X-Amz-Date")
if len(amzDate) < 8 {
return false
}
dateStamp := amzDate[:8]
sumPayload := sha256.Sum256(payload)
payloadHash := hex.EncodeToString(sumPayload[:])
canonicalHeaders := fmt.Sprintf("content-type:%s\nhost:%s\nx-amz-date:%s\n",
r.Header.Get("Content-Type"), r.Host, amzDate)
const signedHeaders = "content-type;host;x-amz-date"
canonicalReq := fmt.Sprintf("%s\n%s\n\n%s\n%s\n%s",
r.Method, r.URL.Path, canonicalHeaders, signedHeaders, payloadHash)
sumCanon := sha256.Sum256([]byte(canonicalReq))
scope := dateStamp + "/us-east-1/route53/aws4_request"
stringToSign := "AWS4-HMAC-SHA256\n" + amzDate + "\n" + scope + "\n" + hex.EncodeToString(sumCanon[:])
hmacBytes := func(key, data []byte) []byte {
mac := hmac.New(sha256.New, key)
mac.Write(data)
return mac.Sum(nil)
}
kDate := hmacBytes([]byte("AWS4"+wantSecretKey), []byte(dateStamp))
kRegion := hmacBytes(kDate, []byte("us-east-1"))
kService := hmacBytes(kRegion, []byte("route53"))
kSigning := hmacBytes(kService, []byte("aws4_request"))
sig := hex.EncodeToString(hmacBytes(kSigning, []byte(stringToSign)))
wantAuth := fmt.Sprintf("AWS4-HMAC-SHA256 Credential=%s/%s, SignedHeaders=%s, Signature=%s",
wantAccessKey, scope, signedHeaders, sig)
return r.Header.Get("Authorization") == wantAuth
}
type recordItemResp struct {
IAM string `json:"iam"`
IP string `json:"ip"`
IPs []string `json:"ips"`
IsAlias bool `json:"isAlias"`
Alias []string `json:"alias"`
Ephemeral bool `json:"ephemeral"`
HasToken bool `json:"hasToken"`
LastUpdate int64 `json:"lastUpdate"`
DDNSCount int `json:"ddnsCount"`
WebhookCount int `json:"webhookCount"`
TouchCount int `json:"touchCount"`
}
type recordListResp struct {
Items []recordItemResp `json:"items"`
}
func findRecordByIAM(items []recordItemResp, iam string) (recordItemResp, bool) {
for _, it := range items {
if it.IAM == iam {
return it, true
}
}
return recordItemResp{}, false
}
func TestRecordsCRUDPersistTokenRotateAndSync(t *testing.T) {
r53Srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintln(w, `<ChangeResourceRecordSetsResponse/>`)
}))
defer r53Srv.Close()
whSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer whSrv.Close()
h := newAPITestHarness(t, "", r53Srv.URL)
// Validation errors on POST /records.
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/records", map[string]any{"iam": ""}), http.StatusBadRequest, "empty iam")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/records", map[string]any{"iam": "alice", "ip": "not-an-ip"}), http.StatusBadRequest, "invalid ip")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/records", map[string]any{"iam": "selfalias", "alias": []string{"selfalias"}}), http.StatusBadRequest, "self alias")
// Create plain record alice + alias cluster referencing alice + ephemeral ephem1.
createAlice := h.doJSON(http.MethodPost, "/api/v1/records", map[string]any{
"iam": "alice",
"ip": "203.0.113.10",
})
assertAPIStatus(t, createAlice, http.StatusCreated, "create alice")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/records", map[string]any{"iam": "alice"}), http.StatusConflict, "duplicate alice")
createCluster := h.doJSON(http.MethodPost, "/api/v1/records", map[string]any{
"iam": "cluster",
"alias": []string{"alice", "ephem1"},
})
assertAPIStatus(t, createCluster, http.StatusCreated, "create cluster alias")
// Alias referencing another alias or converting referenced member to alias must fail with 400.
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/records", map[string]any{
"iam": "nested",
"alias": []string{"cluster"},
}), http.StatusBadRequest, "alias referencing alias")
assertAPIStatus(t, h.doJSON(http.MethodPut, "/api/v1/records/alice", map[string]any{
"alias": []string{"ephem1"},
}), http.StatusBadRequest, "member referenced by alias cannot become alias")
// Register an ephemeral record via public /iam/ephem1/198.51.100.88.
ephemRec := httptest.NewRecorder()
h.mux.ServeHTTP(ephemRec, httptest.NewRequest(http.MethodGet, "/iam/ephem1/198.51.100.88", nil))
assertAPIStatus(t, ephemRec, http.StatusOK, "public /iam/ephem1")
verifyMergedAndPromoteEphemeral(t, h)
verifyPutStoreSyncAndDelete(t, h)
verifyTokenRotateAndClear(t, h)
verifyManualSyncAndHistory(t, h, whSrv.URL)
}
func verifyMergedAndPromoteEphemeral(t *testing.T, h *apiTestHarness) {
t.Helper()
listRec := h.doJSON(http.MethodGet, "/api/v1/records", nil)
assertAPIStatus(t, listRec, http.StatusOK, "GET /records")
var list recordListResp
decodeAPIJSON(t, listRec, &list, "decode records")
ephem, ok := findRecordByIAM(list.Items, "ephem1")
if !ok || !ephem.Ephemeral || ephem.IP != "198.51.100.88" {
t.Fatalf("expected ephemeral ephem1 in GET /records, got %+v (ok=%v)", ephem, ok)
}
cluster, ok := findRecordByIAM(list.Items, "cluster")
if !ok || !cluster.IsAlias || len(cluster.IPs) != 2 || cluster.IPs[0] != "203.0.113.10" || cluster.IPs[1] != "198.51.100.88" {
t.Fatalf("expected resolved alias IPs on cluster, got %+v", cluster)
}
// Promote ephem1 via POST /records/ephem1/persist.
persistRec := h.doJSON(http.MethodPost, "/api/v1/records/ephem1/persist", nil)
assertAPIStatus(t, persistRec, http.StatusOK, "persist ephem1")
var persisted recordItemResp
decodeAPIJSON(t, persistRec, &persisted, "decode persisted ephem1")
if persisted.Ephemeral || persisted.IP != "198.51.100.88" {
t.Fatalf("expected ephem1 promoted to persisted record, got %+v", persisted)
}
if _, err := h.db.GetWhoRecord(context.Background(), "ephem1"); err != nil {
t.Fatalf("expected ephem1 in who_entries after persist: %v", err)
}
}
func verifyPutStoreSyncAndDelete(t *testing.T, h *apiTestHarness) {
t.Helper()
// PUT /records/alice updates in-memory Store immediately (even though ReloadFromDB uses LoadIfAbsent).
putAlice := h.doJSON(http.MethodPut, "/api/v1/records/alice", map[string]any{
"ip": "203.0.113.11",
})
assertAPIStatus(t, putAlice, http.StatusOK, "PUT /records/alice")
if gotIP, ok := h.srv.store.Get("alice"); !ok || gotIP != "203.0.113.11" {
t.Fatalf("Store.Get(alice) after PUT = (%q, %v), want (203.0.113.11, true)", gotIP, ok)
}
// Create temporary record tempdel, verify PUT ip="" clears Store, and DELETE removes from DB + Store.
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/records", map[string]any{
"iam": "tempdel",
"ip": "192.0.2.50",
}), http.StatusCreated, "create tempdel")
assertAPIStatus(t, h.doJSON(http.MethodPut, "/api/v1/records/tempdel", map[string]any{
"ip": "",
}), http.StatusOK, "clear tempdel ip")
if _, ok := h.srv.store.Get("tempdel"); ok {
t.Fatal("expected tempdel removed from Store when PUT sets ip=\"\"")
}
assertAPIStatus(t, h.doJSON(http.MethodPut, "/api/v1/records/tempdel", map[string]any{
"ip": "192.0.2.51",
}), http.StatusOK, "re-set tempdel ip")
assertAPIStatus(t, h.doJSON(http.MethodDelete, "/api/v1/records/tempdel", nil), http.StatusOK, "delete tempdel")
if _, ok := h.srv.store.Get("tempdel"); ok {
t.Fatal("expected tempdel removed from Store after DELETE /records/tempdel")
}
}
func verifyTokenRotateAndClear(t *testing.T, h *apiTestHarness) {
t.Helper()
rotRec := h.doJSON(http.MethodPost, "/api/v1/records/alice/token", nil)
assertAPIStatus(t, rotRec, http.StatusOK, "rotate alice token")
var tokResp struct {
Token string `json:"token"`
HasToken bool `json:"hasToken"`
}
decodeAPIJSON(t, rotRec, &tokResp, "decode token rotate")
if tokResp.Token == "" || !tokResp.HasToken {
t.Fatalf("expected non-empty one-time token and hasToken=true, got %+v", tokResp)
}
// Subsequent GET /records returns hasToken=true and never leaks raw token.
listRec := h.doJSON(http.MethodGet, "/api/v1/records", nil)
assertAPIStatus(t, listRec, http.StatusOK, "GET /records after token rotate")
if strings.Contains(listRec.Body.String(), tokResp.Token) {
t.Fatalf("GET /records leaked raw token %q", tokResp.Token)
}
var list recordListResp
decodeAPIJSON(t, listRec, &list, "decode records after token")
alice, ok := findRecordByIAM(list.Items, "alice")
if !ok || !alice.HasToken {
t.Fatalf("expected alice.HasToken == true, got %+v", alice)
}
// Public /iam/alice rejects unauthenticated updates and accepts rotated token.
unauthIam := httptest.NewRecorder()
h.mux.ServeHTTP(unauthIam, httptest.NewRequest(http.MethodGet, "/iam/alice/203.0.113.12", nil))
assertAPIStatus(t, unauthIam, http.StatusUnauthorized, "/iam/alice without token")
authReq := httptest.NewRequest(http.MethodGet, "/iam/alice/203.0.113.12", nil)
authReq.Header.Set("X-Who-Token", tokResp.Token)
authIam := httptest.NewRecorder()
h.mux.ServeHTTP(authIam, authReq)
assertAPIStatus(t, authIam, http.StatusOK, "/iam/alice with rotated token")
// Clear token via {"clear": true}, re-rotate, and clear via DELETE /records/alice/token.
clearRec := h.doJSON(http.MethodPost, "/api/v1/records/alice/token", map[string]any{"clear": true})
assertAPIStatus(t, clearRec, http.StatusOK, "clear alice token via POST")
var clearBody map[string]any
decodeAPIJSON(t, clearRec, &clearBody, "decode clear token")
if clearBody["hasToken"] != false {
t.Fatalf("expected hasToken=false after clear, got %+v", clearBody)
}
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/records/alice/token", nil), http.StatusOK, "re-rotate alice token")
assertAPIStatus(t, h.doJSON(http.MethodDelete, "/api/v1/records/alice/token", nil), http.StatusOK, "DELETE /records/alice/token")
}
func verifyManualSyncAndHistory(t *testing.T, h *apiTestHarness, whURL string) {
t.Helper()
touchPath := filepath.Join(t.TempDir(), "alice-sync.json")
syncSecRec := h.doJSON(http.MethodPost, "/api/v1/secrets", map[string]any{
"name": "aws-sync",
"provider": "route53",
"credentials": map[string]string{
"access_key": "AKIASYNCTEST",
"secret_key": "secretsync",
},
})
assertAPIStatus(t, syncSecRec, http.StatusCreated, "create secret for sync")
var syncSec testSecretDTO
decodeAPIJSON(t, syncSecRec, &syncSec, "decode sync secret")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/ddns", map[string]any{
"iam": "alice",
"provider": "route53",
"secretId": syncSec.ID,
"domain": "alice.example.com",
"ip_version": "ipv4",
"zone_id": "ZSYNC1",
"ttl": 120,
}), http.StatusCreated, "create ddns for sync")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/webhooks", map[string]any{
"iam": "alice",
"url": whURL,
"method": "POST",
}), http.StatusCreated, "create webhook for sync")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/touch", map[string]any{
"iam": "alice",
"path": touchPath,
}), http.StatusCreated, "create touch for sync")
syncRec := h.doJSON(http.MethodPost, "/api/v1/records/alice/sync", nil)
assertAPIStatus(t, syncRec, http.StatusOK, "POST /records/alice/sync")
type histItem struct {
ID int64 `json:"id"`
IAM string `json:"iam"`
OldIP string `json:"oldIp"`
NewIP string `json:"newIp"`
Source string `json:"source"`
Deliveries []struct {
Kind string `json:"kind"`
Status string `json:"status"`
} `json:"deliveries"`
}
type histPage struct {
Items []histItem `json:"items"`
NextCursor int64 `json:"nextCursor"`
}
var aliceHist histPage
ok := waitFor(t, 3*time.Second, func() bool {
rec := h.doJSON(http.MethodGet, "/api/v1/records/alice/history", nil)
if rec.Code != http.StatusOK {
return false
}
decodeAPIJSON(t, rec, &aliceHist, "decode alice history")
return len(aliceHist.Items) >= 3 && len(aliceHist.Items[0].Deliveries) == 3
})
if !ok {
t.Fatalf("timed out waiting for alice sync deliveries, got %+v", aliceHist)
}
if aliceHist.Items[0].Source != "sync" {
t.Fatalf("expected newest history source=sync, got %+v", aliceHist.Items[0])
}
// Alias history aggregates member transitions (alice + ephem1).
clusterHistRec := h.doJSON(http.MethodGet, "/api/v1/records/cluster/history", nil)
assertAPIStatus(t, clusterHistRec, http.StatusOK, "GET /records/cluster/history")
var clusterHist histPage
decodeAPIJSON(t, clusterHistRec, &clusterHist, "decode cluster history")
seenMembers := map[string]bool{}
for _, item := range clusterHist.Items {
seenMembers[item.IAM] = true
}
if !seenMembers["alice"] || !seenMembers["ephem1"] {
t.Fatalf("expected alias history to include both alice and ephem1, got %+v", seenMembers)
}
}
func TestDDNSAndWebhooksMaskSecretsAndPreserveOnPut(t *testing.T) {
var r53Mu sync.Mutex
var lastR53Body string
wantSecretKey := "topsecret"
r53Srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
r53Mu.Lock()
expectedKey := wantSecretKey
r53Mu.Unlock()
if !verifyRoute53SigV4(r, body, "AKIATESTKEY", expectedKey) {
http.Error(w, "SignatureDoesNotMatch", http.StatusForbidden)
return
}
r53Mu.Lock()
lastR53Body = string(body)
r53Mu.Unlock()
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintln(w, `<ChangeResourceRecordSetsResponse/>`)
}))
defer r53Srv.Close()
var whMu sync.Mutex
gotWHHeaders := map[string]string{}
whSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
whMu.Lock()
gotWHHeaders["Authorization"] = r.Header.Get("Authorization")
gotWHHeaders["X-Env"] = r.Header.Get("X-Env")
whMu.Unlock()
w.WriteHeader(http.StatusAccepted)
}))
defer whSrv.Close()
h := newAPITestHarness(t, "", r53Srv.URL)
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/records", map[string]any{
"iam": "alice",
"ip": "198.51.100.25",
}), http.StatusCreated, "seed alice")
verifyDDNSMaskAndSecretPreserve(t, h, &r53Mu, &lastR53Body, &wantSecretKey)
verifyWebhookMaskAndHeaderPreserve(t, h, whSrv.URL, &whMu, gotWHHeaders)
}
type testSecretDTO struct {
ID int64 `json:"id"`
Name string `json:"name"`
Provider string `json:"provider"`
Credentials map[string]string `json:"credentials"`
UsageCount int `json:"usageCount"`
}
func createAndVerifyProviderSecret(t *testing.T, h *apiTestHarness) testSecretDTO {
t.Helper()
// Duplicate, unknown provider, unknown credential key, and masked required key checks.
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/secrets", map[string]any{
"name": "bad-prov",
"provider": "cloudflare",
"credentials": map[string]string{"api_token": "tok"},
}), http.StatusBadRequest, "unsupported secret provider")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/secrets", map[string]any{
"name": "bad-key",
"provider": "route53",
"credentials": map[string]string{"access_key": "AKIA1", "secret_key": "s1", "extra": "nope"},
}), http.StatusBadRequest, "unknown credential key")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/secrets", map[string]any{
"name": "masked-create",
"provider": "route53",
"credentials": map[string]string{"access_key": "AKIA1", "secret_key": storage.SecretMask},
}), http.StatusBadRequest, "masked required secret on create")
secRec := h.doJSON(http.MethodPost, "/api/v1/secrets", map[string]any{
"name": "aws-test",
"provider": "route53",
"credentials": map[string]string{
"access_key": "AKIATESTKEY",
"secret_key": "topsecret",
},
})
assertAPIStatus(t, secRec, http.StatusCreated, "POST /secrets")
if strings.Contains(secRec.Body.String(), "topsecret") {
t.Fatalf("POST /secrets leaked secret_key: %s", secRec.Body.String())
}
var sec testSecretDTO
decodeAPIJSON(t, secRec, &sec, "decode created secret")
if sec.Credentials["access_key"] != "AKIATESTKEY" || sec.Credentials["secret_key"] != storage.SecretMask || sec.UsageCount != 0 {
t.Fatalf("unexpected created secret DTO: %+v", sec)
}
// Duplicate name returns 409 Conflict.
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/secrets", map[string]any{
"name": "aws-test",
"provider": "route53",
"credentials": map[string]string{"access_key": "AKIA2", "secret_key": "other"},
}), http.StatusConflict, "duplicate secret name")
return sec
}
func verifyDDNSMaskAndSecretPreserve(
t *testing.T,
h *apiTestHarness,
r53Mu *sync.Mutex,
lastR53Body *string,
wantSecretKey *string,
) {
t.Helper()
sec := createAndVerifyProviderSecret(t, h)
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/ddns", map[string]any{
"iam": "alice",
"provider": "cloudflare",
"secretId": sec.ID,
"domain": "alice.example.com",
"zone_id": "Z123",
}), http.StatusBadRequest, "invalid ddns provider")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/ddns", map[string]any{
"iam": "alice",
"provider": "route53",
"secretId": 99999,
"domain": "alice.example.com",
"zone_id": "Z123",
}), http.StatusBadRequest, "missing ddns secretId")
createRec := h.doJSON(http.MethodPost, "/api/v1/ddns", map[string]any{
"iam": "alice",
"provider": "route53",
"secretId": sec.ID,
"domain": "alice.example.com",
"ip_version": "ipv4",
"zone_id": "Z123456",
"ttl": 300,
})
assertAPIStatus(t, createRec, http.StatusCreated, "POST /ddns")
type ddnsDTO struct {
ID int64 `json:"id"`
SecretID int64 `json:"secretId"`
SecretName string `json:"secretName"`
TTL int `json:"ttl"`
LastDelivery *struct {
Status string `json:"status"`
} `json:"lastDelivery"`
}
var created ddnsDTO
decodeAPIJSON(t, createRec, &created, "decode created ddns")
if created.SecretID != sec.ID || created.SecretName != "aws-test" {
t.Fatalf("created ddns = %+v, want secretId=%d secretName=aws-test", created, sec.ID)
}
// Deleting in-use secret returns 409 Conflict; GET /secrets shows usageCount=1.
assertAPIStatus(t, h.doJSON(http.MethodDelete, fmt.Sprintf("/api/v1/secrets/%d", sec.ID), nil), http.StatusConflict, "DELETE in-use secret")
secListRec := h.doJSON(http.MethodGet, "/api/v1/secrets", nil)
assertAPIStatus(t, secListRec, http.StatusOK, "GET /secrets")
var secList struct {
Items []testSecretDTO `json:"items"`
}
decodeAPIJSON(t, secListRec, &secList, "decode GET /secrets")
if len(secList.Items) != 1 || secList.Items[0].UsageCount != 1 || secList.Items[0].Credentials["secret_key"] != storage.SecretMask {
t.Fatalf("unexpected GET /secrets items: %+v", secList.Items)
}
// Updating secret with SecretMask preserves topsecret; updating DDNS TTL to 60 and testing succeeds.
assertAPIStatus(t, h.doJSON(http.MethodPut, fmt.Sprintf("/api/v1/secrets/%d", sec.ID), map[string]any{
"name": "aws-test",
"provider": "route53",
"credentials": map[string]string{
"access_key": "AKIATESTKEY",
"secret_key": storage.SecretMask,
},
}), http.StatusOK, "PUT /secrets/{id} preserve masked")
assertAPIStatus(t, h.doJSON(http.MethodPut, fmt.Sprintf("/api/v1/secrets/%d", sec.ID), map[string]any{
"name": "aws-test",
"provider": "cloudflare",
"credentials": map[string]string{"access_key": "AKIATESTKEY"},
}), http.StatusBadRequest, "PUT /secrets/{id} provider change rejected")
putRec := h.doJSON(http.MethodPut, fmt.Sprintf("/api/v1/ddns/%d", created.ID), map[string]any{
"iam": "alice",
"provider": "route53",
"secretId": sec.ID,
"domain": "alice.example.com",
"ip_version": "ipv4",
"zone_id": "Z123456",
"ttl": 60,
"enabled": true,
})
assertAPIStatus(t, putRec, http.StatusOK, "PUT /ddns/{id}")
verifyDDNSLiveSecretRotation(t, h, sec.ID, created.ID, r53Mu, lastR53Body, wantSecretKey)
assertAPIStatus(t, h.doJSON(http.MethodDelete, fmt.Sprintf("/api/v1/ddns/%d", created.ID), nil), http.StatusOK, "DELETE /ddns/{id}")
assertAPIStatus(t, h.doJSON(http.MethodDelete, fmt.Sprintf("/api/v1/secrets/%d", sec.ID), nil), http.StatusOK, "DELETE /secrets/{id}")
}
func verifyDDNSLiveSecretRotation(
t *testing.T,
h *apiTestHarness,
secretID, ddnsID int64,
r53Mu *sync.Mutex,
lastR53Body *string,
wantSecretKey *string,
) {
t.Helper()
testRec := h.doJSON(http.MethodPost, fmt.Sprintf("/api/v1/ddns/%d/test", ddnsID), nil)
assertAPIStatus(t, testRec, http.StatusOK, "POST /ddns/{id}/test")
var testRes map[string]any
decodeAPIJSON(t, testRec, &testRes, "decode ddns test")
if testRes["status"] != "ok" {
t.Fatalf("expected ddns test status=ok using preserved topsecret, got %+v", testRes)
}
r53Mu.Lock()
gotXML := *lastR53Body
*wantSecretKey = "rotated-secret-key"
r53Mu.Unlock()
if !strings.Contains(gotXML, "<TTL>60</TTL>") {
t.Fatalf("expected updated TTL=60 in Route53 XML, got %s", gotXML)
}
// Rotate secret via PUT /api/v1/secrets/{id} without touching DDNS rule -> must reload dispatcher immediately.
assertAPIStatus(t, h.doJSON(http.MethodPut, fmt.Sprintf("/api/v1/secrets/%d", secretID), map[string]any{
"name": "aws-test",
"provider": "route53",
"credentials": map[string]string{
"access_key": "AKIATESTKEY",
"secret_key": "rotated-secret-key",
},
}), http.StatusOK, "PUT /secrets/{id} rotate")
rotTestRec := h.doJSON(http.MethodPost, fmt.Sprintf("/api/v1/ddns/%d/test", ddnsID), nil)
assertAPIStatus(t, rotTestRec, http.StatusOK, "POST /ddns/{id}/test after secret rotation")
var rotRes map[string]any
decodeAPIJSON(t, rotTestRec, &rotRes, "decode rotated ddns test")
if rotRes["status"] != "ok" {
t.Fatalf("expected rotated secret key to take effect immediately, got %+v", rotRes)
}
}
func verifyWebhookMaskAndHeaderPreserve(
t *testing.T,
h *apiTestHarness,
whURL string,
whMu *sync.Mutex,
gotWHHeaders map[string]string,
) {
t.Helper()
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/webhooks", map[string]any{
"iam": "alice",
"url": "ftp://invalid.example.com/hook",
}), http.StatusBadRequest, "invalid webhook scheme")
createRec := h.doJSON(http.MethodPost, "/api/v1/webhooks", map[string]any{
"iam": "alice",
"url": whURL,
"method": "POST",
"headers": map[string]string{
"Authorization": "Bearer super-wh-secret",
"X-Env": "prod",
},
})
assertAPIStatus(t, createRec, http.StatusCreated, "POST /webhooks")
if strings.Contains(createRec.Body.String(), "super-wh-secret") {
t.Fatalf("POST /webhooks leaked secret header: %s", createRec.Body.String())
}
type webhookDTO struct {
ID int64 `json:"id"`
Headers map[string]string `json:"headers"`
LastDelivery *struct {
Status string `json:"status"`
} `json:"lastDelivery"`
}
var created webhookDTO
decodeAPIJSON(t, createRec, &created, "decode created webhook")
getRec := h.doJSON(http.MethodGet, "/api/v1/webhooks", nil)
assertAPIStatus(t, getRec, http.StatusOK, "GET /webhooks")
if strings.Contains(getRec.Body.String(), "super-wh-secret") || strings.Contains(getRec.Body.String(), "prod") {
t.Fatalf("GET /webhooks leaked header values: %s", getRec.Body.String())
}
var list struct {
Items []webhookDTO `json:"items"`
}
decodeAPIJSON(t, getRec, &list, "decode GET /webhooks")
if len(list.Items) != 1 || list.Items[0].Headers["Authorization"] != storage.SecretMask || list.Items[0].Headers["X-Env"] != storage.SecretMask {
t.Fatalf("expected masked headers in GET /webhooks, got %+v", list.Items)
}
putRec := h.doJSON(http.MethodPut, fmt.Sprintf("/api/v1/webhooks/%d", created.ID), map[string]any{
"iam": "alice",
"url": whURL,
"method": "POST",
"headers": map[string]string{
"Authorization": storage.SecretMask,
"X-Env": "staging",
},
"enabled": true,
})
assertAPIStatus(t, putRec, http.StatusOK, "PUT /webhooks/{id}")
// Omitting headers on PUT preserves existing headers without wiping them.
assertAPIStatus(t, h.doJSON(http.MethodPut, fmt.Sprintf("/api/v1/webhooks/%d", created.ID), map[string]any{
"iam": "alice",
"url": whURL,
"method": "POST",
"enabled": false,
}), http.StatusOK, "PUT /webhooks/{id} without headers")
testRec := h.doJSON(http.MethodPost, fmt.Sprintf("/api/v1/webhooks/%d/test", created.ID), map[string]any{
"ip": "198.51.100.99",
})
assertAPIStatus(t, testRec, http.StatusOK, "POST /webhooks/{id}/test")
var testRes map[string]any
decodeAPIJSON(t, testRec, &testRes, "decode webhook test")
if testRes["status"] != "ok" {
t.Fatalf("expected webhook test status=ok, got %+v", testRes)
}
whMu.Lock()
gotAuth := gotWHHeaders["Authorization"]
gotEnv := gotWHHeaders["X-Env"]
whMu.Unlock()
if gotAuth != "Bearer super-wh-secret" || gotEnv != "staging" {
t.Fatalf("webhook headers sent = (%q, %q), want (\"Bearer super-wh-secret\", \"staging\")", gotAuth, gotEnv)
}
assertAPIStatus(t, h.doJSON(http.MethodDelete, fmt.Sprintf("/api/v1/webhooks/%d", created.ID), nil), http.StatusOK, "DELETE /webhooks/{id}")
}
func TestTouchCRUDPreviewAndWriteNow(t *testing.T) {
h := newAPITestHarness(t, "", "")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/records", map[string]any{
"iam": "alice",
"ip": "203.0.113.77",
}), http.StatusCreated, "seed alice")
dir := t.TempDir()
path1 := filepath.Join(dir, "alice-1.json")
path2 := filepath.Join(dir, "alice-2.json")
createRec := h.doJSON(http.MethodPost, "/api/v1/touch", map[string]any{
"iam": "alice",
"path": path1,
})
assertAPIStatus(t, createRec, http.StatusCreated, "POST /touch")
// POST /touch writes file immediately.
onDisk := readTouchRecord(t, path1)
if onDisk.IAM != "alice" || len(onDisk.IP) != 1 || onDisk.IP[0] != "203.0.113.77" {
t.Fatalf("unexpected touch file after POST /touch: %+v", onDisk)
}
type touchDTO struct {
ID int64 `json:"id"`
IAM string `json:"iam"`
Path string `json:"path"`
Enabled bool `json:"enabled"`
Preview TouchRecord `json:"preview"`
LastDelivery *struct {
Status string `json:"status"`
} `json:"lastDelivery"`
}
getRec := h.doJSON(http.MethodGet, "/api/v1/touch", nil)
assertAPIStatus(t, getRec, http.StatusOK, "GET /touch")
var list struct {
Items []touchDTO `json:"items"`
}
decodeAPIJSON(t, getRec, &list, "decode GET /touch")
if len(list.Items) != 1 || list.Items[0].Preview.IAM != "alice" || len(list.Items[0].Preview.IP) != 1 || list.Items[0].Preview.IP[0] != "203.0.113.77" {
t.Fatalf("expected live TouchRecord preview in GET /touch, got %+v", list.Items)
}
if list.Items[0].LastDelivery == nil || list.Items[0].LastDelivery.Status != "ok" {
t.Fatalf("expected lastDelivery.status=ok in GET /touch, got %+v", list.Items[0])
}
id := list.Items[0].ID
putRec := h.doJSON(http.MethodPut, fmt.Sprintf("/api/v1/touch/%d", id), map[string]any{
"iam": "ghost",
"path": path2,
"enabled": false,
})
assertAPIStatus(t, putRec, http.StatusOK, "PUT /touch/{id}")
// POST /touch/{id}/write works even when disabled and when IAM has no IP.
writeRec := h.doJSON(http.MethodPost, fmt.Sprintf("/api/v1/touch/%d/write", id), nil)
assertAPIStatus(t, writeRec, http.StatusOK, "POST /touch/{id}/write")
ghostDisk := readTouchRecord(t, path2)
if ghostDisk.IAM != "ghost" || len(ghostDisk.IP) != 0 {
t.Fatalf("expected empty IP array written for ghost, got %+v", ghostDisk)
}
assertAPIStatus(t, h.doJSON(http.MethodDelete, fmt.Sprintf("/api/v1/touch/%d", id), nil), http.StatusOK, "DELETE /touch/{id}")
}
func TestLogsSettingsSessionsAndBackupEndpoints(t *testing.T) {
r53Srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintln(w, `<ChangeResourceRecordSetsResponse/>`)
}))
defer r53Srv.Close()
whSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "upstream failure", http.StatusBadGateway)
}))
defer whSrv.Close()
h := newAPITestHarness(t, "", r53Srv.URL)
dir := t.TempDir()
touchPath := filepath.Join(dir, "backup-touch.json")
// Seed records, integrations, and public endpoint traffic.
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/records", map[string]any{
"iam": "router",
"ip": "198.51.100.1",
}), http.StatusCreated, "create router")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/records", map[string]any{
"iam": "home",
"alias": []string{"router"},
}), http.StatusCreated, "create home alias")
bkSecRec := h.doJSON(http.MethodPost, "/api/v1/secrets", map[string]any{
"name": "aws-bk",
"provider": "route53",
"credentials": map[string]string{
"access_key": "AKIABK",
"secret_key": "bk-secret-key",
},
})
assertAPIStatus(t, bkSecRec, http.StatusCreated, "create backup secret")
var bkSec testSecretDTO
decodeAPIJSON(t, bkSecRec, &bkSec, "decode backup secret")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/ddns", map[string]any{
"iam": "router",
"provider": "route53",
"secretId": bkSec.ID,
"domain": "router.example.com",
"ip_version": "ipv4",
"zone_id": "ZBK1",
"ttl": 300,
}), http.StatusCreated, "create ddns")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/webhooks", map[string]any{
"iam": "router",
"url": whSrv.URL + "/notify",
"method": "POST",
"headers": map[string]string{
"X-Webhook-Key": "wh-secret-val",
},
}), http.StatusCreated, "create webhook")
assertAPIStatus(t, h.doJSON(http.MethodPost, "/api/v1/touch", map[string]any{
"iam": "router",
"path": touchPath,
}), http.StatusCreated, "create touch")
// Generate public access logs and wait for async deliveries + flush AccessLogger.
for _, target := range []string{"/whoami", "/whois/router", "/iam/router/198.51.100.2"} {
req := httptest.NewRequest(http.MethodGet, target, nil)
req.Header.Set("X-Forwarded-For", "203.0.113.99")
rec := httptest.NewRecorder()
h.mux.ServeHTTP(rec, req)
assertAPIStatus(t, rec, http.StatusOK, "public "+target)
}
if err := h.logger.Close(context.Background()); err != nil {
t.Fatalf("logger.Close: %v", err)
}
waitFor(t, 2*time.Second, func() bool {
latest, err := h.db.LatestDeliveriesByTarget(context.Background())
return err == nil && len(latest) >= 3
})
verifyOverviewAccessAndIPHistory(t, h)
verifySettingsPruneAndSessions(t, h)
verifyBackupExport(t, h)
verifyBackupImport(t, h, dir)
verifyAuditTrail(t, h)
}
func verifyOverviewAccessAndIPHistory(t *testing.T, h *apiTestHarness) {
t.Helper()
ovRec := h.doJSON(http.MethodGet, "/api/v1/overview", nil)
assertAPIStatus(t, ovRec, http.StatusOK, "GET /overview")
var ov struct {
TotalRecords int `json:"totalRecords"`
AliasCount int `json:"aliasCount"`
DDNSCount int `json:"ddnsCount"`
WebhookCount int `json:"webhookCount"`
TouchCount int `json:"touchCount"`
IAMHits24h int64 `json:"iamHits24h"`
WhoisHits24h int64 `json:"whoisHits24h"`
WhoamiHits24h int64 `json:"whoamiHits24h"`
Changes24h int64 `json:"changes24h"`
DeliveryErrors24h int64 `json:"deliveryErrors24h"`
}
decodeAPIJSON(t, ovRec, &ov, "decode overview")
if ov.TotalRecords != 2 || ov.AliasCount != 1 || ov.DDNSCount != 1 || ov.WebhookCount != 1 || ov.TouchCount != 1 {
t.Fatalf("unexpected overview counts: %+v", ov)
}
if ov.IAMHits24h < 1 || ov.WhoisHits24h < 1 || ov.WhoamiHits24h < 1 || ov.Changes24h < 2 || ov.DeliveryErrors24h < 1 {
t.Fatalf("unexpected overview traffic/change/error stats: %+v", ov)
}
accRec := h.doJSON(http.MethodGet, "/api/v1/access-logs?range=24h&changed=1", nil)
assertAPIStatus(t, accRec, http.StatusOK, "GET /access-logs")
var accPage struct {
Items []struct {
IAM string `json:"iam"`
Changed bool `json:"changed"`
} `json:"items"`
Histogram []struct {
BucketStartMs int64 `json:"bucketStartMs"`
IAM int64 `json:"iam"`
} `json:"histogram"`
}
decodeAPIJSON(t, accRec, &accPage, "decode access-logs")