-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathe2e_test.go
More file actions
686 lines (622 loc) · 23.1 KB
/
Copy pathe2e_test.go
File metadata and controls
686 lines (622 loc) · 23.1 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
//go:build e2e
// End-to-end tests that spawn the real maSSO binary and exercise it over HTTP.
// These are excluded from the default `go test ./...` run because they build a
// binary, bind real ports, and (for SAML) spawn Node.js. Run them with:
//
// make test-e2e
// # or: go build -o masso . && go test -tags e2e -run TestE2E -v .
//
// They cover the wiring that in-process handler tests cannot: flag parsing,
// port binding, the bootstrap/runOIDC/runSAML paths, and real end-to-end HTTP.
package main
import (
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"syscall"
"testing"
"time"
)
// freePort asks the OS for an unused TCP port.
func freePort(t *testing.T) string {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("freePort: %v", err)
}
defer l.Close()
return strconv.Itoa(l.Addr().(*net.TCPAddr).Port)
}
// runMASSO starts the compiled ./masso binary with args and returns a stop func.
func runMASSO(t *testing.T, logPath string, args ...string) func() {
t.Helper()
bin := "./masso"
if _, err := os.Stat(bin); err != nil {
t.Fatalf("binary %s not found — run `make build` first: %v", bin, err)
}
logf, err := os.Create(logPath)
if err != nil {
t.Fatalf("create log: %v", err)
}
cmd := exec.Command(bin, args...)
cmd.Stdout = logf
cmd.Stderr = logf
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} // own process group so we can kill children (Node)
if err := cmd.Start(); err != nil {
t.Fatalf("start masso: %v", err)
}
return func() {
// Kill the whole process group (covers spawned Node engines).
syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
cmd.Wait()
logf.Close()
}
}
// waitReady polls url until it returns 2xx or the timeout elapses.
func waitReady(t *testing.T, url string, timeout time.Duration) bool {
t.Helper()
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
resp, err := http.Get(url)
if err == nil {
resp.Body.Close()
if resp.StatusCode < 300 {
return true
}
}
time.Sleep(200 * time.Millisecond)
}
return false
}
func getJSON(t *testing.T, url string, into interface{}) {
t.Helper()
resp, err := http.Get(url)
if err != nil {
t.Fatalf("GET %s: %v", url, err)
}
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(into); err != nil {
t.Fatalf("decode %s: %v", url, err)
}
}
func postJSON(t *testing.T, url, body string) int {
t.Helper()
resp, err := http.Post(url, "application/json", stringReader(body))
if err != nil {
t.Fatalf("POST %s: %v", url, err)
}
defer resp.Body.Close()
io.Copy(io.Discard, resp.Body)
return resp.StatusCode
}
// postJSONResult POSTs body and decodes the JSON response into `into` (if
// non-nil), returning the HTTP status code.
func postJSONResult(t *testing.T, url, body string, into interface{}) int {
t.Helper()
resp, err := http.Post(url, "application/json", stringReader(body))
if err != nil {
t.Fatalf("POST %s: %v", url, err)
}
defer resp.Body.Close()
if into != nil {
json.NewDecoder(resp.Body).Decode(into)
} else {
io.Copy(io.Discard, resp.Body)
}
return resp.StatusCode
}
// doReq issues an arbitrary-method request and returns the status code and body.
func doReq(t *testing.T, method, url, body string) (int, string) {
t.Helper()
var rdr io.Reader
if body != "" {
rdr = stringReader(body)
}
req, err := http.NewRequest(method, url, rdr)
if err != nil {
t.Fatalf("new %s %s: %v", method, url, err)
}
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("%s %s: %v", method, url, err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, string(b)
}
// hasPrefix reports whether s begins with prefix (avoids a strings import).
func hasPrefix(s, prefix string) bool {
return len(s) >= len(prefix) && s[:len(prefix)] == prefix
}
func stringReader(s string) io.Reader { return &sr{s: s} }
type sr struct {
s string
i int
}
func (r *sr) Read(p []byte) (int, error) {
if r.i >= len(r.s) {
return 0, io.EOF
}
n := copy(p, r.s[r.i:])
r.i += n
return n, nil
}
// ─── Single OIDC ─────────────────────────────────────────────────────────────
func TestE2E_SingleOIDC(t *testing.T) {
dir := t.TempDir()
port, dash := freePort(t), freePort(t)
stop := runMASSO(t, filepath.Join(dir, "single.log"),
"oidc", "--port", port, "--dash-port", dash, "--db", filepath.Join(dir, "s.db"))
defer stop()
base := "http://127.0.0.1:" + port
dashBase := "http://127.0.0.1:" + dash + "/dashboard/api"
if !waitReady(t, dashBase+"/info", 20*time.Second) {
t.Fatal("dashboard did not become ready")
}
// Discovery reports the right issuer.
var disc struct {
Issuer string `json:"issuer"`
JWKSURI string `json:"jwks_uri"`
}
getJSON(t, base+"/.well-known/openid-configuration", &disc)
// Default issuer is http://localhost:<port>/ (localhost or 127.0.0.1 both fine).
wantLocalhost := "http://localhost:" + port + "/"
if disc.Issuer != base+"/" && disc.Issuer != wantLocalhost {
t.Errorf("issuer = %q, want %q or %q", disc.Issuer, base+"/", wantLocalhost)
}
if disc.JWKSURI == "" {
t.Error("empty jwks_uri in discovery")
}
// JWKS serves a key.
var jwks struct {
Keys []json.RawMessage `json:"keys"`
}
getJSON(t, base+"/keys", &jwks)
if len(jwks.Keys) == 0 {
t.Error("expected at least one JWKS key")
}
// Info reports single mode.
var info map[string]interface{}
getJSON(t, dashBase+"/info", &info)
if info["duo"] != false {
t.Errorf("expected duo=false, got %v", info["duo"])
}
}
// ─── Duo OIDC ────────────────────────────────────────────────────────────────
func TestE2E_DuoOIDC(t *testing.T) {
dir := t.TempDir()
portA, portB, dash := freePort(t), freePort(t), freePort(t)
stop := runMASSO(t, filepath.Join(dir, "duo.log"),
"oidc", "--duo", "--port", portA, "--port-b", portB, "--dash-port", dash,
"--db", filepath.Join(dir, "d.db"))
defer stop()
dashBase := "http://127.0.0.1:" + dash + "/dashboard/api"
if !waitReady(t, dashBase+"/info", 20*time.Second) {
t.Fatal("dashboard did not become ready")
}
// Both IdP ports serve their own discovery.
for _, p := range []string{portA, portB} {
var disc struct {
Issuer string `json:"issuer"`
}
getJSON(t, "http://127.0.0.1:"+p+"/.well-known/openid-configuration", &disc)
if disc.Issuer != "http://127.0.0.1:"+p+"/" && disc.Issuer != "http://localhost:"+p+"/" {
t.Errorf("port %s issuer = %q", p, disc.Issuer)
}
}
// Info reports two instances.
var info struct {
Duo bool `json:"duo"`
Instances []struct {
Index int `json:"index"`
Name string `json:"name"`
} `json:"instances"`
}
getJSON(t, dashBase+"/info", &info)
if !info.Duo || len(info.Instances) != 2 {
t.Fatalf("expected duo with 2 instances, got %+v", info)
}
if info.Instances[0].Name != "IdP A" || info.Instances[1].Name != "IdP B" {
t.Errorf("default names wrong: %+v", info.Instances)
}
// Per-instance isolation: set A mock, B intercept; neither clobbers the other.
if c := postJSON(t, dashBase+"/instances/0/config", `{"path":"/oauth/token","mode":"mock","mock_response":"{}"}`); c != 200 {
t.Fatalf("set A: %d", c)
}
if c := postJSON(t, dashBase+"/instances/1/config", `{"path":"/oauth/token","mode":"intercept"}`); c != 200 {
t.Fatalf("set B: %d", c)
}
if m := instanceEndpointMode(t, dashBase, 0, "/oauth/token"); m != "mock" {
t.Errorf("instance 0 = %q, want mock", m)
}
if m := instanceEndpointMode(t, dashBase, 1, "/oauth/token"); m != "intercept" {
t.Errorf("instance 1 = %q, want intercept", m)
}
}
// ─── Dynamic client registration (RFC 7591 + 7592) ──────────────────────────
// TestE2E_DynamicClientRegistration exercises the full RFC 7591 registration and
// RFC 7592 management lifecycle in single OIDC mode.
func TestE2E_DynamicClientRegistration(t *testing.T) {
dir := t.TempDir()
port, dash := freePort(t), freePort(t)
stop := runMASSO(t, filepath.Join(dir, "dynreg.log"),
"oidc", "--port", port, "--dash-port", dash, "--db", filepath.Join(dir, "dr.db"))
defer stop()
base := "http://127.0.0.1:" + port
dashBase := "http://127.0.0.1:" + dash + "/dashboard/api"
if !waitReady(t, dashBase+"/info", 20*time.Second) {
t.Fatal("dashboard did not become ready")
}
// Register (RFC 7591).
var reg struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
}
if code := postJSONResult(t, base+"/register",
`{"redirect_uris":["http://localhost:9999/callback"],"client_name":"e2e"}`, ®); code != 201 {
t.Fatalf("register status = %d, want 201", code)
}
if !hasPrefix(reg.ClientID, "dyn-") || reg.ClientSecret == "" {
t.Fatalf("unexpected registration result: %+v", reg)
}
// Missing redirect_uris must be rejected.
if code := postJSONResult(t, base+"/register", `{"client_name":"bad"}`, nil); code != 400 {
t.Errorf("register without redirect_uris = %d, want 400", code)
}
// Read back (RFC 7592).
if code, _ := doReq(t, "GET", base+"/register/"+reg.ClientID, ""); code != 200 {
t.Errorf("GET registered client = %d, want 200", code)
}
// Update redirect URIs.
if code, _ := doReq(t, "PUT", base+"/register/"+reg.ClientID,
`{"redirect_uris":["http://localhost:8888/cb"]}`); code != 200 {
t.Errorf("PUT client = %d, want 200", code)
}
// Delete.
if code, _ := doReq(t, "DELETE", base+"/register/"+reg.ClientID, ""); code != 204 {
t.Errorf("DELETE client = %d, want 204", code)
}
// Gone.
if code, _ := doReq(t, "GET", base+"/register/"+reg.ClientID, ""); code != 404 {
t.Errorf("GET deleted client = %d, want 404", code)
}
}
// TestE2E_DuoDynamicClientRegistration verifies dynamic registration works on
// BOTH duo instances and that each instance keeps its own dynamic-client store:
// a client registered on IdP B must not resolve on IdP A, and vice versa.
func TestE2E_DuoDynamicClientRegistration(t *testing.T) {
dir := t.TempDir()
portA, portB, dash := freePort(t), freePort(t), freePort(t)
stop := runMASSO(t, filepath.Join(dir, "duodynreg.log"),
"oidc", "--duo", "--port", portA, "--port-b", portB, "--dash-port", dash,
"--db", filepath.Join(dir, "ddr.db"))
defer stop()
dashBase := "http://127.0.0.1:" + dash + "/dashboard/api"
if !waitReady(t, dashBase+"/info", 20*time.Second) {
t.Fatal("dashboard did not become ready")
}
baseA := "http://127.0.0.1:" + portA
baseB := "http://127.0.0.1:" + portB
// Register a client on IdP B.
var regB struct {
ClientID string `json:"client_id"`
}
if code := postJSONResult(t, baseB+"/register",
`{"redirect_uris":["http://localhost:9999/callback"]}`, ®B); code != 201 {
t.Fatalf("register on B = %d, want 201", code)
}
if !hasPrefix(regB.ClientID, "dyn-") {
t.Fatalf("bad client_id from B: %q", regB.ClientID)
}
// Retrievable on B.
if code, _ := doReq(t, "GET", baseB+"/register/"+regB.ClientID, ""); code != 200 {
t.Errorf("GET B's client on B = %d, want 200", code)
}
// NOT on A — instances keep independent dynamic-client stores.
if code, _ := doReq(t, "GET", baseA+"/register/"+regB.ClientID, ""); code != 404 {
t.Errorf("B's client visible on A = %d, want 404 (must be isolated)", code)
}
// Register independently on A → distinct client_id, isolated from B.
var regA struct {
ClientID string `json:"client_id"`
}
if code := postJSONResult(t, baseA+"/register",
`{"redirect_uris":["http://localhost:9999/callback"]}`, ®A); code != 201 {
t.Fatalf("register on A = %d, want 201", code)
}
if regA.ClientID == regB.ClientID {
t.Errorf("A and B produced the same client_id %q", regA.ClientID)
}
if code, _ := doReq(t, "GET", baseA+"/register/"+regA.ClientID, ""); code != 200 {
t.Errorf("GET A's client on A = %d, want 200", code)
}
if code, _ := doReq(t, "GET", baseB+"/register/"+regA.ClientID, ""); code != 404 {
t.Errorf("A's client visible on B = %d, want 404 (must be isolated)", code)
}
}
// ─── Port collision guard ────────────────────────────────────────────────────
func TestE2E_DuoPortCollisionRefused(t *testing.T) {
dir := t.TempDir()
p := freePort(t)
// --port-b == --dash-port must be rejected at startup.
bin := "./masso"
cmd := exec.Command(bin, "oidc", "--duo", "--port", freePort(t),
"--port-b", p, "--dash-port", p, "--db", filepath.Join(dir, "c.db"))
out, _ := cmd.CombinedOutput()
if cmd.ProcessState.Success() {
t.Fatalf("expected non-zero exit on port collision, got success. output:\n%s", out)
}
if !contains(string(out), "collides") && !contains(string(out), "must differ") {
t.Errorf("expected collision message, got:\n%s", out)
}
}
// ─── Duo + cloudflared: both IdPs get their own public tunnel ────────────────
// TestE2E_DuoCloudflaredBothTunneled asserts that `--duo --cloudflared` gives
// EACH IdP its own public trycloudflare issuer (not just IdP A, with B left on
// localhost). Skips when cloudflared is unavailable or a quick tunnel cannot be
// established, since that depends on outbound reachability to Cloudflare's edge
// that CI may not have.
func TestE2E_DuoCloudflaredBothTunneled(t *testing.T) {
if _, err := exec.LookPath("cloudflared"); err != nil {
t.Skip("cloudflared not installed; skipping duo tunnel e2e")
}
dir := t.TempDir()
portA, portB, dash := freePort(t), freePort(t), freePort(t)
stop := runMASSO(t, filepath.Join(dir, "duocf.log"),
"oidc", "--duo", "--cloudflared", "--port", portA, "--port-b", portB,
"--dash-port", dash, "--db", filepath.Join(dir, "dcf.db"))
defer stop()
dashBase := "http://127.0.0.1:" + dash + "/dashboard/api"
// Two tunnels are established sequentially (~5-8s each), so allow generous time.
if !waitReady(t, dashBase+"/info", 60*time.Second) {
t.Skip("dashboard not ready — cloudflared quick tunnel could not be established (no edge reachability?)")
}
// IdP A must be tunnel-sourced and served over a trycloudflare URL.
var info struct {
IssuerSource string `json:"issuer_source"`
Issuer string `json:"issuer"`
}
getJSON(t, dashBase+"/info", &info)
if info.IssuerSource != "cloudflared" {
t.Skip("issuer_source != cloudflared — tunnel not active in this environment")
}
// Each IdP's own discovery issuer must be a distinct public trycloudflare URL.
issuerOf := func(port string) string {
var disc struct {
Issuer string `json:"issuer"`
}
getJSON(t, "http://127.0.0.1:"+port+"/.well-known/openid-configuration", &disc)
return disc.Issuer
}
issA, issB := issuerOf(portA), issuerOf(portB)
t.Logf("IdP A issuer=%s IdP B issuer=%s", issA, issB)
if !contains(issA, "trycloudflare.com") {
t.Errorf("IdP A issuer is not a public tunnel: %q", issA)
}
if !contains(issB, "trycloudflare.com") {
t.Errorf("IdP B issuer is not a public tunnel (should be tunneled, not localhost): %q", issB)
}
if issA == issB {
t.Errorf("IdP A and IdP B share the same tunnel URL %q; each must have its own", issA)
}
}
// ─── SAML (skips if Node.js unavailable) ─────────────────────────────────────
func TestE2E_SingleSAML(t *testing.T) {
if _, err := exec.LookPath("node"); err != nil {
t.Skip("node not installed; skipping SAML e2e")
}
if _, err := os.Stat("saml-engine/node_modules"); err != nil {
t.Skip("saml-engine/node_modules missing; run npm install")
}
dir := t.TempDir()
port, dash, nodePort := freePort(t), freePort(t), freePort(t)
stop := runMASSO(t, filepath.Join(dir, "saml.log"),
"saml", "--acs", "https://sp.example.com/acs", "--audience", "https://sp.example.com",
"--port", port, "--dash-port", dash, "--node-port", nodePort, "--db", filepath.Join(dir, "sm.db"))
defer stop()
dashBase := "http://127.0.0.1:" + dash + "/dashboard/api"
if !waitReady(t, dashBase+"/info", 30*time.Second) {
t.Fatal("SAML dashboard did not become ready")
}
// Metadata is proxied from the Node engine through the Go server.
resp, err := http.Get("http://127.0.0.1:" + port + "/metadata")
if err != nil {
t.Fatalf("GET /metadata: %v", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != 200 || !contains(string(body), "EntityDescriptor") {
t.Errorf("metadata not served: status=%d body=%.120s", resp.StatusCode, body)
}
var info map[string]interface{}
getJSON(t, dashBase+"/info", &info)
if info["duo"] != false {
t.Errorf("expected duo=false, got %v", info["duo"])
}
}
// TestE2E_DuoSAML guards the duo-mode SAML wiring: BOTH Node engines must come
// up and serve metadata, each with its OWN signing certificate. This regression-
// tests a bug where IdP B's Node engine crashed (ENOENT) because it received a
// cert path relative to maSSO's cwd instead of an absolute one (it runs in
// saml-engine/). The OIDC duo tests never exercised the Node engines.
func TestE2E_DuoSAML(t *testing.T) {
if _, err := exec.LookPath("node"); err != nil {
t.Skip("node not installed; skipping SAML e2e")
}
if _, err := os.Stat("saml-engine/node_modules"); err != nil {
t.Skip("saml-engine/node_modules missing; run npm install")
}
dir := t.TempDir()
portA, portB, dash, nodePort := freePort(t), freePort(t), freePort(t), freePort(t)
// --acs/--audience are no longer accepted with --duo (see bootstrap()'s
// duo-mode flag rejection): each IdP's ACS/audience is configured via the
// dashboard's Settings tab instead. Neither is needed for the assertions below.
stop := runMASSO(t, filepath.Join(dir, "duosaml.log"),
"saml", "--duo",
"--port", portA, "--port-b", portB, "--dash-port", dash, "--node-port", nodePort,
"--db", filepath.Join(dir, "dsm.db"))
defer stop()
dashBase := "http://127.0.0.1:" + dash + "/dashboard/api"
if !waitReady(t, dashBase+"/info", 30*time.Second) {
t.Fatal("SAML duo dashboard did not become ready")
}
// Both Node engines must serve metadata (B is the one that used to crash).
metaA := waitMetadata(t, portA, 30*time.Second)
metaB := waitMetadata(t, portB, 30*time.Second)
if metaA == "" {
t.Fatalf("IdP A metadata never served")
}
if metaB == "" {
t.Fatalf("IdP B metadata never served (Node engine B likely crashed)")
}
// Each instance must advertise its OWN distinct signing certificate.
certA, certB := firstX509Cert(metaA), firstX509Cert(metaB)
if certA == "" || certB == "" {
t.Fatalf("missing signing cert: A=%d bytes B=%d bytes", len(certA), len(certB))
}
if certA == certB {
t.Errorf("IdP A and IdP B share the same SAML signing certificate; each must have its own")
}
}
// TestE2E_DuoSAMLCloudflared is the last mode combination: SAML + duo +
// cloudflared. It asserts both Node engines come up behind their OWN public
// tunnel, so each IdP's metadata advertises a distinct trycloudflare entityID and
// a distinct signing cert. Skips when cloudflared/node are unavailable or the
// quick tunnel cannot reach Cloudflare's edge.
func TestE2E_DuoSAMLCloudflared(t *testing.T) {
if _, err := exec.LookPath("cloudflared"); err != nil {
t.Skip("cloudflared not installed; skipping SAML duo tunnel e2e")
}
if _, err := exec.LookPath("node"); err != nil {
t.Skip("node not installed; skipping SAML e2e")
}
if _, err := os.Stat("saml-engine/node_modules"); err != nil {
t.Skip("saml-engine/node_modules missing; run npm install")
}
dir := t.TempDir()
portA, portB, dash, nodePort := freePort(t), freePort(t), freePort(t), freePort(t)
// --acs/--audience are no longer accepted with --duo (see bootstrap()'s
// duo-mode flag rejection): each IdP's ACS/audience is configured via the
// dashboard's Settings tab instead. Neither is needed for the assertions below.
stop := runMASSO(t, filepath.Join(dir, "duosamlcf.log"),
"saml", "--duo", "--cloudflared",
"--port", portA, "--port-b", portB, "--dash-port", dash, "--node-port", nodePort,
"--db", filepath.Join(dir, "dscf.db"))
defer stop()
dashBase := "http://127.0.0.1:" + dash + "/dashboard/api"
// Two tunnels + two Node engines — allow generous time.
if !waitReady(t, dashBase+"/info", 70*time.Second) {
t.Skip("dashboard not ready — cloudflared quick tunnel could not be established")
}
var info struct {
IssuerSource string `json:"issuer_source"`
}
getJSON(t, dashBase+"/info", &info)
if info.IssuerSource != "cloudflared" {
t.Skip("issuer_source != cloudflared — tunnel not active in this environment")
}
metaA := waitMetadata(t, portA, 40*time.Second)
metaB := waitMetadata(t, portB, 40*time.Second)
if metaA == "" || metaB == "" {
t.Fatalf("metadata not served: A=%d bytes B=%d bytes", len(metaA), len(metaB))
}
eidA, eidB := entityID(metaA), entityID(metaB)
t.Logf("entityID A=%s B=%s", eidA, eidB)
if !contains(eidA, "trycloudflare.com") {
t.Errorf("IdP A entityID is not a public tunnel URL: %q", eidA)
}
if !contains(eidB, "trycloudflare.com") {
t.Errorf("IdP B entityID is not a public tunnel URL (should be tunneled): %q", eidB)
}
if eidA == eidB {
t.Errorf("IdP A and IdP B share entityID %q; each must have its own tunnel", eidA)
}
if a, b := firstX509Cert(metaA), firstX509Cert(metaB); a == "" || b == "" || a == b {
t.Errorf("IdP A/B must advertise distinct signing certs (A=%d B=%d equal=%v)", len(a), len(b), a == b)
}
}
// entityID extracts the entityID attribute from SAML metadata.
func entityID(metadataXML string) string {
const marker = `entityID="`
i := indexOf(metadataXML, marker)
if i < 0 {
return ""
}
rest := metadataXML[i+len(marker):]
j := indexOf(rest, `"`)
if j < 0 {
return ""
}
return rest[:j]
}
// waitMetadata polls an IdP's /metadata until it returns 200 with an
// EntityDescriptor, returning the body (or "" on timeout).
func waitMetadata(t *testing.T, port string, timeout time.Duration) string {
t.Helper()
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
resp, err := http.Get("http://127.0.0.1:" + port + "/metadata")
if err == nil {
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode == 200 && contains(string(body), "EntityDescriptor") {
return string(body)
}
}
time.Sleep(300 * time.Millisecond)
}
return ""
}
// firstX509Cert extracts the first (whitespace-stripped) X509Certificate from
// SAML metadata, ignoring XML namespace prefixes.
func firstX509Cert(metadataXML string) string {
i := indexOf(metadataXML, "X509Certificate>")
if i < 0 {
return ""
}
rest := metadataXML[i+len("X509Certificate>"):]
j := indexOf(rest, "<")
if j < 0 {
return ""
}
var b []byte
for _, c := range rest[:j] {
if c != ' ' && c != '\n' && c != '\t' && c != '\r' {
b = append(b, byte(c))
}
}
return string(b)
}
func indexOf(s, sub string) int {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return i
}
}
return -1
}
func instanceEndpointMode(t *testing.T, dashBase string, idx int, path string) string {
t.Helper()
var cfg map[string]struct {
Mode string `json:"mode"`
}
getJSON(t, fmt.Sprintf("%s/instances/%d/config", dashBase, idx), &cfg)
return cfg[path].Mode
}
func contains(s, sub string) bool {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
}