-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_test.go
More file actions
891 lines (797 loc) · 22.4 KB
/
client_test.go
File metadata and controls
891 lines (797 loc) · 22.4 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
package domainconnect
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
)
func TestIdentifyDomainRoot(t *testing.T) {
// Test cases from Python test_get_domain_root
tests := []struct {
domain string
expected string
wantErr bool
}{
{"example.com", "example.com", false},
{"www.example.com", "example.com", false},
{"sub.www.example.com", "example.com", false},
{"example.co.uk", "example.co.uk", false},
{"www.example.co.uk", "example.co.uk", false},
{"sub.www.example.co.uk", "example.co.uk", false},
{"example.com.au", "example.com.au", false},
{"www.example.com.au", "example.com.au", false},
{"example.org", "example.org", false},
{"deep.sub.example.org", "example.org", false},
{"Example.COM", "example.com", false},
{".example.com", "example.com", false},
{"example.com.", "example.com", false},
{".example.com.", "example.com", false},
// Public suffix list special cases
{"example.blogspot.com", "example.blogspot.com", false},
{"www.example.blogspot.com", "example.blogspot.com", false},
{"example.github.io", "example.github.io", false},
{"app.example.github.io", "example.github.io", false},
// Error cases
{"com", "", true},
{"", "", true},
{"co.uk", "", true},
}
for _, tt := range tests {
t.Run(tt.domain, func(t *testing.T) {
result, err := IdentifyDomainRoot(tt.domain)
if tt.wantErr {
if err == nil {
t.Errorf("expected error for %q, got nil", tt.domain)
}
return
}
if err != nil {
t.Errorf("unexpected error for %q: %v", tt.domain, err)
return
}
if result != tt.expected {
t.Errorf("IdentifyDomainRoot(%q) = %q, want %q", tt.domain, result, tt.expected)
}
})
}
}
func TestGenerateSignature(t *testing.T) {
privateKey, err := os.ReadFile("testdata/private_key.pem")
if err != nil {
t.Fatalf("failed to read private key: %v", err)
}
params := map[string]string{
"IP": "192.168.1.1",
"RANDOMID": "abc123",
}
result, err := generateSignature("example.com", "www", params, privateKey, "key1")
if err != nil {
t.Fatalf("generateSignature failed: %v", err)
}
if result["sig"] == "" {
t.Error("expected non-empty signature")
}
if result["key"] != "key1" {
t.Errorf("expected key=key1, got %q", result["key"])
}
// Verify signature is base64url encoded (no +, /, or padding =)
if strings.ContainsAny(result["sig"], "+/=") {
t.Error("signature should be base64url encoded (no +, /, or =)")
}
}
func TestGenerateSignature_NoHost(t *testing.T) {
privateKey, err := os.ReadFile("testdata/private_key.pem")
if err != nil {
t.Fatalf("failed to read private key: %v", err)
}
params := map[string]string{"IP": "1.2.3.4"}
result, err := generateSignature("example.com", "", params, privateKey, "")
if err != nil {
t.Fatalf("generateSignature failed: %v", err)
}
if result["sig"] == "" {
t.Error("expected non-empty signature")
}
}
func TestGetSyncURL_InvalidDomain(t *testing.T) {
client := New()
_, err := client.GetSyncURL(context.Background(), SyncURLOptions{
Config: nil,
ProviderID: "test",
ServiceID: "test",
})
if err == nil {
t.Error("expected error for nil config")
}
}
func TestGetSyncURL(t *testing.T) {
// Test cases inspired by Python test_get_domain_connect_template_sync_url
tests := []struct {
name string
opts SyncURLOptions
contains []string
}{
{
name: "basic",
opts: SyncURLOptions{
Config: &Config{
DomainRoot: "example.com",
URLSyncUX: "connect.provider.com",
},
ProviderID: "exampleservice",
ServiceID: "template1",
},
contains: []string{
"https://connect.provider.com/v2/domainTemplates/providers/exampleservice/services/template1/apply",
"domain=example.com",
},
},
{
name: "with_host",
opts: SyncURLOptions{
Config: &Config{
DomainRoot: "example.com",
Host: "www",
URLSyncUX: "connect.provider.com",
},
ProviderID: "provider1",
ServiceID: "svc1",
},
contains: []string{
"domain=example.com",
"host=www",
},
},
{
name: "with_params",
opts: SyncURLOptions{
Config: &Config{
DomainRoot: "example.com",
URLSyncUX: "connect.provider.com",
},
ProviderID: "provider1",
ServiceID: "svc1",
Params: map[string]string{
"IP": "1.2.3.4",
"name": "test",
},
},
contains: []string{
"IP=1.2.3.4",
"name=test",
},
},
{
name: "with_redirect",
opts: SyncURLOptions{
Config: &Config{
DomainRoot: "example.com",
URLSyncUX: "connect.provider.com",
},
ProviderID: "provider1",
ServiceID: "svc1",
RedirectURL: "https://myapp.com/callback",
State: "mystate123",
},
contains: []string{
"redirect_uri=https",
"state=mystate123",
},
},
{
name: "with_group_ids",
opts: SyncURLOptions{
Config: &Config{
DomainRoot: "example.com",
URLSyncUX: "connect.provider.com",
},
ProviderID: "provider1",
ServiceID: "svc1",
GroupIDs: []string{"group1", "group2"},
},
contains: []string{
"groupId=group1",
"groupId=group2",
},
},
}
client := New()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
url, err := client.GetSyncURL(context.Background(), tt.opts)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
for _, substr := range tt.contains {
if !strings.Contains(url, substr) {
t.Errorf("URL %q should contain %q", url, substr)
}
}
})
}
}
func TestGetSyncURL_WithSignature(t *testing.T) {
privateKey, err := os.ReadFile("testdata/private_key.pem")
if err != nil {
t.Fatalf("failed to read private key: %v", err)
}
client := New()
url, err := client.GetSyncURL(context.Background(), SyncURLOptions{
Config: &Config{
DomainRoot: "example.com",
Host: "mail",
URLSyncUX: "connect.provider.com",
},
ProviderID: "provider1",
ServiceID: "svc1",
Params: map[string]string{"IP": "1.2.3.4"},
PrivateKey: privateKey,
KeyID: "1",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !strings.Contains(url, "sig=") {
t.Error("URL should contain sig parameter")
}
if !strings.Contains(url, "key=1") {
t.Error("URL should contain key parameter")
}
}
// Integration test - tests against real Domain Connect enabled domains
func TestGetDomainConfig(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
client := New()
ctx := context.Background()
// diabtrack.com is the official Domain Connect test domain
cfg, err := client.GetDomainConfig(ctx, "diabtrack.com")
if err != nil {
t.Fatalf("GetDomainConfig failed: %v", err)
}
if cfg.ProviderID == "" {
t.Error("expected non-empty provider ID")
}
if cfg.DomainRoot != "diabtrack.com" {
t.Errorf("DomainRoot = %q, want %q", cfg.DomainRoot, "diabtrack.com")
}
if cfg.URLSyncUX == "" && cfg.URLAsyncUX == "" {
t.Error("expected at least one UX URL")
}
t.Logf("Provider: %s (%s)", cfg.ProviderName, cfg.ProviderID)
t.Logf("SyncUX: %s", cfg.URLSyncUX)
t.Logf("AsyncUX: %s", cfg.URLAsyncUX)
t.Logf("API: %s", cfg.URLAPI)
}
func TestGetDomainConfig_WithHost(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
client := New()
ctx := context.Background()
// Test subdomain extraction
cfg, err := client.GetDomainConfig(ctx, "www.diabtrack.com")
if err != nil {
t.Fatalf("GetDomainConfig failed: %v", err)
}
if cfg.DomainRoot != "diabtrack.com" {
t.Errorf("DomainRoot = %q, want %q", cfg.DomainRoot, "diabtrack.com")
}
if cfg.Host != "www" {
t.Errorf("Host = %q, want %q", cfg.Host, "www")
}
}
func TestGetDomainConfig_InvalidDomain(t *testing.T) {
client := New()
ctx := context.Background()
// Domain that doesn't support Domain Connect
_, err := client.GetDomainConfig(ctx, "google.com")
if err == nil {
t.Error("expected error for domain without Domain Connect")
}
}
func TestGetAsyncContext(t *testing.T) {
client := New()
asyncCtx, err := client.GetAsyncContext(context.Background(), AsyncContextOptions{
Config: &Config{
DomainRoot: "example.com",
Host: "www",
URLAsyncUX: "async.provider.com",
},
ProviderID: "provider1",
ServiceID: "svc1",
RedirectURL: "https://myapp.com/callback",
State: "state123",
Params: map[string]string{
"IP": "1.2.3.4",
},
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if asyncCtx.ProviderID != "provider1" {
t.Errorf("expected providerID=provider1, got %q", asyncCtx.ProviderID)
}
if asyncCtx.ServiceID != "svc1" {
t.Errorf("expected serviceID=svc1, got %q", asyncCtx.ServiceID)
}
url := asyncCtx.AsyncConsentURL
if !strings.Contains(url, "https://async.provider.com/v2/domainTemplates/providers/provider1") {
t.Errorf("unexpected consent URL: %s", url)
}
if !strings.Contains(url, "domain=example.com") {
t.Error("consent URL should contain domain")
}
if !strings.Contains(url, "host=www") {
t.Error("consent URL should contain host")
}
if !strings.Contains(url, "redirect_uri=") {
t.Error("consent URL should contain redirect_uri")
}
if !strings.Contains(url, "state=state123") {
t.Error("consent URL should contain state")
}
}
func TestGetAsyncContext_NoHost(t *testing.T) {
client := New()
asyncCtx, err := client.GetAsyncContext(context.Background(), AsyncContextOptions{
Config: &Config{
DomainRoot: "example.com",
URLAsyncUX: "async.provider.com",
},
ProviderID: "provider1",
ServiceID: "svc1",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
url := asyncCtx.AsyncConsentURL
if strings.Contains(url, "host=") {
t.Error("consent URL should not contain host when empty")
}
}
func TestGetAsyncContext_NoAsyncURL(t *testing.T) {
client := New()
_, err := client.GetAsyncContext(context.Background(), AsyncContextOptions{
Config: &Config{
DomainRoot: "example.com",
URLSyncUX: "sync.provider.com",
// URLAsyncUX is empty
},
ProviderID: "provider1",
ServiceID: "svc1",
})
if err == nil {
t.Error("expected error when URLAsyncUX is empty")
}
}
func TestParseCallbackURL(t *testing.T) {
tests := []struct {
name string
url string
wantCode string
wantState string
wantErr bool
}{
{
name: "success",
url: "https://myapp.com/callback?code=abc123&state=mystate",
wantCode: "abc123",
wantState: "mystate",
},
{
name: "code_only",
url: "https://myapp.com/callback?code=xyz789",
wantCode: "xyz789",
wantState: "",
},
{
name: "error_response",
url: "https://myapp.com/callback?error=access_denied&error_description=User%20denied",
wantErr: true,
},
{
name: "missing_code",
url: "https://myapp.com/callback?state=mystate",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
code, state, err := ParseCallbackURL(tt.url)
if tt.wantErr {
if err == nil {
t.Error("expected error")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if code != tt.wantCode {
t.Errorf("code = %q, want %q", code, tt.wantCode)
}
if state != tt.wantState {
t.Errorf("state = %q, want %q", state, tt.wantState)
}
})
}
}
func TestServiceIDsFromCallback(t *testing.T) {
tests := []struct {
name string
url string
want []string
wantNil bool
}{
{
name: "single",
url: "https://app.com/callback?code=abc&granted=svc1",
want: []string{"svc1"},
},
{
name: "multiple",
url: "https://app.com/callback?code=abc&granted=svc1,svc2,svc3",
want: []string{"svc1", "svc2", "svc3"},
},
{
name: "none",
url: "https://app.com/callback?code=abc",
wantNil: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := ServiceIDsFromCallback(tt.url)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if tt.wantNil {
if result != nil {
t.Errorf("expected nil, got %v", result)
}
return
}
if len(result) != len(tt.want) {
t.Errorf("len = %d, want %d", len(result), len(tt.want))
return
}
for i, v := range tt.want {
if result[i] != v {
t.Errorf("result[%d] = %q, want %q", i, result[i], v)
}
}
})
}
}
func TestAsyncContext_TokenValid(t *testing.T) {
tests := []struct {
name string
ctx AsyncContext
valid bool
}{
{
name: "no_token",
ctx: AsyncContext{},
valid: false,
},
{
name: "no_expiry",
ctx: AsyncContext{
AccessToken: "token123",
},
valid: true,
},
{
name: "not_expired",
ctx: AsyncContext{
AccessToken: "token123",
AccessTokenExpiresIn: 3600,
IssuedAt: 9999999999, // far future
},
valid: true,
},
{
name: "expired",
ctx: AsyncContext{
AccessToken: "token123",
AccessTokenExpiresIn: 3600,
IssuedAt: 0, // epoch
},
valid: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.ctx.TokenValid(); got != tt.valid {
t.Errorf("TokenValid() = %v, want %v", got, tt.valid)
}
})
}
}
func TestAsyncContext_BuildAsyncConsentURL(t *testing.T) {
ctx := &AsyncContext{
AsyncConsentURL: "https://provider.com/auth?domain=example.com",
}
url := ctx.BuildAsyncConsentURL("myclient", "dns")
if !strings.Contains(url, "client_id=myclient") {
t.Error("URL should contain client_id")
}
if !strings.Contains(url, "scope=dns") {
t.Error("URL should contain scope")
}
if !strings.Contains(url, "domain=example.com") {
t.Error("URL should preserve existing params")
}
}
func TestAsyncContext_SetCodeFromCallback(t *testing.T) {
ctx := &AsyncContext{}
err := ctx.SetCodeFromCallback("https://app.com/callback?code=authcode123&state=mystate")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if ctx.Code != "authcode123" {
t.Errorf("Code = %q, want %q", ctx.Code, "authcode123")
}
}
// Integration test - check template support against real provider
func TestCheckTemplateSupported(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
client := New()
ctx := context.Background()
// First get config
cfg, err := client.GetDomainConfig(ctx, "diabtrack.com")
if err != nil {
t.Fatalf("GetDomainConfig failed: %v", err)
}
// Check a known template - exampleservice.domainconnect.org/template1 is the test template
err = client.CheckTemplateSupported(ctx, cfg, "exampleservice.domainconnect.org", []string{"template1"})
if err != nil {
t.Logf("Template check failed (may be expected if provider doesn't support this template): %v", err)
}
}
func TestGenerateSignature_ExactMatch(t *testing.T) {
privateKey, err := os.ReadFile("testdata/private_key.pem")
if err != nil {
t.Fatalf("failed to read private key: %v", err)
}
domain := "example.com"
host := "www"
params := map[string]string{"IP": "132.148.25.185", "RANDOMTEXT": "shm:1531371203:Hejo"}
keyID := "_dck1"
result, err := generateSignature(domain, host, params, privateKey, keyID)
if err != nil {
t.Fatalf("generateSignature failed: %v", err)
}
// sig is deterministic (RSA-SHA256 PKCS1v15), sigts varies by time
expected := "VB1WAw1rLGyT7Q7UHMe_OPwSZ2HKj7r7rXN6FK22oWbHK7ATug4ZRHyVmnSWL_8r3brhi21_yJ0lH0me63gyPd74biDHCIRnCdYtyik6pankjXjDvF65uBUiZViRza9RhThFCxzCxdUH1ZNJcDL9LUFqC7cMVXvU-1dtn02KdUwViwSJDGWIAMkgLE92jC7aPWVzfA30pSPSCr__hwcJtydGVeFs5pQ-mAjYARP3w_9aWja3k9tMMk5CpFK8zeLIX6rbrHdhmfI9U0AJkRVBpfgmrjDp_TeHFZHPXWgwWg6ZjouQ_mSkaO9i9gBZP8YcT-m9gvRPqlzOViEdlRI1Ug"
if result["sig"] != expected {
t.Errorf("sig mismatch:\ngot %s\nwant %s", result["sig"], expected)
}
if result["key"] != "_dck1" {
t.Errorf("key = %q, want %q", result["key"], "_dck1")
}
if result["sigts"] == "" {
t.Error("missing sigts")
}
}
func TestGetDomainConfig_NoDomainConnectRecord(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
client := New()
_, err := client.GetDomainConfig(context.Background(), "randomnonexistent.bike")
if !errors.Is(err, ErrNoDomainConnectRecord) {
t.Errorf("expected ErrNoDomainConnectRecord, got %v", err)
}
}
func TestCheckTemplateSupported_NotSupported(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
client := New()
cfg, err := client.GetDomainConfig(context.Background(), "diabtrack.com")
if err != nil {
t.Fatalf("GetDomainConfig failed: %v", err)
}
err = client.CheckTemplateSupported(context.Background(), cfg,
"exampleservice.domainconnect.org", []string{"template_not_exists"})
if !errors.Is(err, ErrTemplateNotSupported) {
t.Errorf("expected ErrTemplateNotSupported, got %v", err)
}
}
func TestGetAsyncToken(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v2/oauth/access_token" {
t.Errorf("wrong path: %s", r.URL.Path)
}
if r.Method != "POST" {
t.Errorf("wrong method: %s", r.Method)
}
q := r.URL.Query()
if q.Get("grant_type") != "authorization_code" {
t.Errorf("wrong grant_type: %s", q.Get("grant_type"))
}
if q.Get("code") != "testcode" {
t.Errorf("wrong code: %s", q.Get("code"))
}
json.NewEncoder(w).Encode(map[string]any{
"access_token": "test_access_token",
"refresh_token": "test_refresh_token",
"expires_in": 3600,
})
}))
defer srv.Close()
client := New()
asyncCtx := &AsyncContext{
Code: "testcode",
Config: &Config{URLAPI: srv.URL},
}
result, err := client.GetAsyncToken(context.Background(), asyncCtx, AsyncCredentials{
ClientID: "myclient", ClientSecret: "mysecret", APIURL: srv.URL,
})
if err != nil {
t.Fatal(err)
}
if result.AccessToken != "test_access_token" {
t.Errorf("AccessToken = %q, want %q", result.AccessToken, "test_access_token")
}
if result.RefreshToken != "test_refresh_token" {
t.Errorf("RefreshToken = %q, want %q", result.RefreshToken, "test_refresh_token")
}
if result.AccessTokenExpiresIn != 3600 {
t.Errorf("AccessTokenExpiresIn = %d, want %d", result.AccessTokenExpiresIn, 3600)
}
if result.IssuedAt == 0 {
t.Error("IssuedAt not set")
}
}
func TestGetAsyncToken_Error(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "invalid_grant"})
}))
defer srv.Close()
client := New()
asyncCtx := &AsyncContext{Code: "badcode", Config: &Config{URLAPI: srv.URL}}
_, err := client.GetAsyncToken(context.Background(), asyncCtx, AsyncCredentials{
ClientID: "x", ClientSecret: "x", APIURL: srv.URL,
})
if !errors.Is(err, ErrAsyncToken) {
t.Errorf("expected ErrAsyncToken, got %v", err)
}
}
func TestRefreshAsyncToken(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if q.Get("grant_type") != "refresh_token" {
t.Errorf("wrong grant_type: %s", q.Get("grant_type"))
}
if q.Get("refresh_token") != "oldrefresh" {
t.Errorf("wrong refresh_token: %s", q.Get("refresh_token"))
}
json.NewEncoder(w).Encode(map[string]any{
"access_token": "new_access_token",
"refresh_token": "new_refresh_token",
"expires_in": 7200,
})
}))
defer srv.Close()
client := New()
asyncCtx := &AsyncContext{
RefreshToken: "oldrefresh",
Config: &Config{URLAPI: srv.URL},
}
result, err := client.RefreshAsyncToken(context.Background(), asyncCtx, AsyncCredentials{
ClientID: "x", ClientSecret: "x", APIURL: srv.URL,
})
if err != nil {
t.Fatal(err)
}
if result.AccessToken != "new_access_token" {
t.Errorf("AccessToken = %q, want %q", result.AccessToken, "new_access_token")
}
if result.RefreshToken != "new_refresh_token" {
t.Errorf("RefreshToken = %q, want %q", result.RefreshToken, "new_refresh_token")
}
}
func TestApplyAsync(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
t.Errorf("wrong method: %s", r.Method)
}
if r.Header.Get("Authorization") != "Bearer mytoken" {
t.Errorf("wrong auth: %s", r.Header.Get("Authorization"))
}
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
client := New()
asyncCtx := &AsyncContext{
AccessToken: "mytoken",
ProviderID: "provider",
ServiceID: "svc",
Config: &Config{DomainRoot: "example.com", URLAPI: srv.URL},
}
err := client.ApplyAsync(context.Background(), asyncCtx, ApplyAsyncOptions{})
if err != nil {
t.Fatal(err)
}
}
func TestApplyAsync_Conflict(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusConflict)
}))
defer srv.Close()
client := New()
asyncCtx := &AsyncContext{
AccessToken: "mytoken",
ProviderID: "provider",
ServiceID: "svc",
Config: &Config{DomainRoot: "example.com", URLAPI: srv.URL},
}
err := client.ApplyAsync(context.Background(), asyncCtx, ApplyAsyncOptions{})
if !errors.Is(err, ErrConflictOnApply) {
t.Errorf("expected ErrConflictOnApply, got %v", err)
}
}
func TestGetSyncURL_SigIsLast(t *testing.T) {
privateKey, err := os.ReadFile("testdata/private_key.pem")
if err != nil {
t.Fatalf("failed to read private key: %v", err)
}
client := New()
u, err := client.GetSyncURL(context.Background(), SyncURLOptions{
Config: &Config{
DomainRoot: "example.com",
Host: "www",
URLSyncUX: "connect.provider.com",
},
ProviderID: "provider1",
ServiceID: "svc1",
Params: map[string]string{"IP": "1.2.3.4", "RANDOMTEXT": "hello"},
PrivateKey: privateKey,
KeyID: "key1",
GroupIDs: []string{"g1"},
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Extract raw query string and verify sig is the last parameter
parts := strings.SplitN(u, "?", 2)
if len(parts) != 2 {
t.Fatalf("expected query string in URL %q", u)
}
params := strings.Split(parts[1], "&")
last := params[len(params)-1]
if !strings.HasPrefix(last, "sig=") {
t.Errorf("expected sig as last param, got %q (full query: %s)", last, parts[1])
}
}
func TestDeleteAsync(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "DELETE" {
t.Errorf("wrong method: %s", r.Method)
}
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
client := New()
asyncCtx := &AsyncContext{
AccessToken: "mytoken",
ProviderID: "provider",
ServiceID: "svc",
Config: &Config{DomainRoot: "example.com", URLAPI: srv.URL},
}
err := client.DeleteAsync(context.Background(), asyncCtx, "")
if err != nil {
t.Fatal(err)
}
}