-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.go
More file actions
2075 lines (1897 loc) · 83 KB
/
Copy pathmain.go
File metadata and controls
2075 lines (1897 loc) · 83 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 (
"bufio"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/hex"
"encoding/json"
"encoding/pem"
"flag"
"fmt"
"html/template"
"log"
"log/slog"
"math/big"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/httprate"
"github.com/google/uuid"
"golang.org/x/text/language"
"masso/dashboard"
"masso/interceptor"
"masso/oidcmeta"
massoSCIM "masso/scim"
"masso/storage"
"github.com/zitadel/oidc/v3/pkg/oidc"
"github.com/zitadel/oidc/v3/pkg/op"
)
var loginTemplate = template.Must(template.New("login").Parse(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign In - maSSO</title>
<link rel="icon" type="image/png" href="/masso-logo.png">
<link rel="apple-touch-icon" href="/masso-logo.png">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:system-ui,-apple-system,sans-serif;background:#0d0b08;color:#fcf3e2;display:flex;justify-content:center;align-items:center;min-height:100vh}
.card{background:#1a1710;padding:40px;border-radius:16px;width:400px;box-shadow:0 20px 60px rgba(0,0,0,.6);border:1px solid #35302a;border-top:3px solid var(--accent,#fe9832)}
.idp-name{text-align:center;font-size:14px;font-weight:800;letter-spacing:.6px;text-transform:uppercase;color:var(--accent,#fe9832);margin-bottom:12px}
.logo{text-align:center;margin-bottom:10px}
.logo img{display:block;max-width:200px;width:100%;height:auto;margin:0 auto}
.sub{text-align:center;color:#a39a8b;font-size:13px;margin-bottom:28px}
label{display:block;font-size:13px;color:#a39a8b;margin-bottom:6px;margin-top:16px}
input[type=text],input[type=password]{width:100%;padding:12px 14px;background:#242019;border:1px solid #35302a;color:#fcf3e2;border-radius:8px;font-size:15px;outline:none;transition:border .2s}
input:focus{border-color:var(--accent,#fe9832)}
button[type=submit]{width:100%;padding:14px;margin-top:24px;background:var(--accent,#fe9832);color:#0d0b08;border:none;border-radius:8px;font-size:16px;font-weight:700;cursor:pointer;transition:opacity .2s}
button[type=submit]:hover{opacity:.85}
.error{background:#e0525220;color:#e05252;padding:10px 14px;border-radius:8px;text-align:center;margin-bottom:16px;font-size:14px}
.acct-pick{position:relative}
.acct-pick-toggle{width:100%;padding:13px;margin:0;background:#242019;color:#fcf3e2;border:1px solid var(--accent,#fe9832);border-radius:8px;font-size:14px;font-weight:700;cursor:pointer;transition:opacity .2s}
.acct-pick-toggle:hover{opacity:.82}
.acct-pick-list{position:absolute;left:0;right:0;top:100%;margin-top:6px;background:#242019;border:1px solid #35302a;border-radius:8px;overflow:hidden;z-index:10;max-height:220px;overflow-y:auto;box-shadow:0 12px 32px rgba(0,0,0,.45)}
.acct-pick-item{display:block;width:100%;padding:10px 14px;margin:0;background:transparent;color:#fcf3e2;border:none;border-bottom:1px solid #35302a;border-radius:0;font-size:14px;font-weight:400;text-align:left;cursor:pointer}
.acct-pick-item:last-child{border-bottom:none}
.acct-pick-item:hover{background:#35302a}
.or-divider{display:flex;align-items:center;text-align:center;color:#6f6656;font-size:12px;font-weight:700;letter-spacing:1px;margin:18px 0}
.or-divider::before,.or-divider::after{content:"";flex:1;border-bottom:1px solid #35302a}
.or-divider::before{margin-right:12px}
.or-divider::after{margin-left:12px}
</style>
</head>
<body>
<div class="card" id="login-card" data-accent="{{.Accent}}">
{{if .IdPName}}<div class="idp-name">{{.IdPNameLead}}{{if .IdPNameTag}}<b>{{.IdPNameTag}}</b>{{end}}</div>{{end}}
<div class="logo"><img src="/masso-logo.png" alt="maSSO" width="200" /></div>
<div class="sub">{{.Protocol}} IdP - Sign in to continue</div>
{{if .Error}}<div class="error">{{.Error}}</div>{{end}}
{{if .Users}}
<div class="acct-pick">
<button type="button" class="acct-pick-toggle" id="acct-pick-btn">Pick test account</button>
<div class="acct-pick-list" id="acct-pick-list" hidden>
{{range .Users}}
<button type="button" class="acct-pick-item" data-user="{{.Username}}" data-pass="{{.Password}}">{{.Label}}</button>
{{end}}
</div>
</div>
<div class="or-divider">OR</div>
{{end}}
<form method="POST" action="/login/username">
<input type="hidden" name="authRequestID" value="{{.ID}}">
<label>Username</label>
<input type="text" name="username" placeholder="testing@example.com" autofocus required>
<label>Password</label>
<input type="password" name="password" placeholder="••••••••" required>
<button type="submit">Sign In</button>
</form>
<script>
(function(){
var card=document.getElementById('login-card');
if(card&&card.dataset.accent){card.style.setProperty('--accent',card.dataset.accent);}
var btn=document.getElementById('acct-pick-btn'),list=document.getElementById('acct-pick-list');
if(!btn||!list)return;
var userInp=document.querySelector('input[name="username"]'),passInp=document.querySelector('input[name="password"]');
btn.addEventListener('click',function(e){e.stopPropagation();list.hidden=!list.hidden;});
list.querySelectorAll('.acct-pick-item').forEach(function(el){
el.addEventListener('click',function(){
userInp.value=el.dataset.user||'';
passInp.value=el.dataset.pass||'';
list.hidden=true;
userInp.focus();
});
});
document.addEventListener('click',function(){list.hidden=true;});
list.addEventListener('click',function(e){e.stopPropagation();});
})();
</script>
</div>
</body>
</html>`))
type loginPageUser struct {
Username string
Password string
Label string
}
type loginPageData struct {
ID string
Error string
Protocol string
IdPName string // duo mode: the IdP being signed into; empty in single mode
IdPNameLead string // IdPName minus a trailing single-char token (e.g. "IdP ")
IdPNameTag string // trailing single-char token, bolded in the UI (e.g. "A")
Accent string // accent hex color for theming (per-IdP in duo mode)
Users []loginPageUser
}
// splitTrailingTag separates a trailing single-character token (like the "A" in
// "IdP A") from the rest of the name so the UI can render it in bold. Returns the
// leading part (including the separating space) and the tag, or (name, "") if the
// name does not end in a lone character.
func splitTrailingTag(name string) (lead, tag string) {
trimmed := strings.TrimRight(name, " ")
if idx := strings.LastIndex(trimmed, " "); idx >= 0 {
if last := trimmed[idx+1:]; len([]rune(last)) == 1 {
return trimmed[:idx+1], last
}
}
return name, ""
}
func renderLogin(w http.ResponseWriter, users storage.UserStore, id, errMsg, protocol, idpName, accent string) {
if accent == "" {
accent = "#fe9832"
}
lead, tag := splitTrailingTag(idpName)
data := loginPageData{ID: id, Error: errMsg, Protocol: protocol, IdPName: idpName, IdPNameLead: lead, IdPNameTag: tag, Accent: accent}
for _, u := range users.ListUsers() {
label := u.Username
if u.FirstName != "" || u.LastName != "" {
label = strings.TrimSpace(u.Username + ", " + strings.TrimSpace(u.FirstName+" "+u.LastName))
}
data.Users = append(data.Users, loginPageUser{
Username: u.Username,
Password: u.Password,
Label: label,
})
}
loginTemplate.Execute(w, data)
}
// deviceTemplate is the RFC 8628 user-facing approval form served at the
// device flow's UserFormPath ("/device", set in the op.Config below). Without
// this page the flow could start (/device_authorization) and poll
// (/oauth/token), but a user had no way to actually enter their user_code and
// approve/deny the request - the library only uses UserFormPath to build the
// verification_uri it returns; it does not serve this page itself.
var deviceTemplate = template.Must(template.New("device").Parse(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Device Sign In - maSSO</title>
<link rel="icon" type="image/png" href="/masso-logo.png">
<link rel="apple-touch-icon" href="/masso-logo.png">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:system-ui,-apple-system,sans-serif;background:#0d0b08;color:#fcf3e2;display:flex;justify-content:center;align-items:center;min-height:100vh}
.card{background:#1a1710;padding:40px;border-radius:16px;width:400px;box-shadow:0 20px 60px rgba(0,0,0,.6);border:1px solid #35302a;border-top:3px solid var(--accent,#fe9832)}
.idp-name{text-align:center;font-size:14px;font-weight:800;letter-spacing:.6px;text-transform:uppercase;color:var(--accent,#fe9832);margin-bottom:12px}
.logo{text-align:center;margin-bottom:10px}
.logo img{display:block;max-width:200px;width:100%;height:auto;margin:0 auto}
.sub{text-align:center;color:#a39a8b;font-size:13px;margin-bottom:28px}
label{display:block;font-size:13px;color:#a39a8b;margin-bottom:6px;margin-top:16px}
input[type=text],input[type=password]{width:100%;padding:12px 14px;background:#242019;border:1px solid #35302a;color:#fcf3e2;border-radius:8px;font-size:15px;outline:none;transition:border .2s}
input[type=text]#user_code{text-align:center;letter-spacing:2px;font-weight:700;text-transform:uppercase}
input:focus{border-color:var(--accent,#fe9832)}
.btn-row{display:flex;gap:10px;margin-top:24px}
button{flex:1;padding:14px;background:var(--accent,#fe9832);color:#0d0b08;border:none;border-radius:8px;font-size:16px;font-weight:700;cursor:pointer;transition:opacity .2s}
button:hover{opacity:.85}
button.deny{background:transparent;color:#a39a8b;border:1px solid #35302a}
.error{background:#e0525220;color:#e05252;padding:10px 14px;border-radius:8px;text-align:center;margin-bottom:16px;font-size:14px}
.success{background:#4ec36f20;color:#4ec36f;padding:14px;border-radius:8px;text-align:center;font-size:14px}
</style>
</head>
<body>
<div class="card" id="device-card" data-accent="{{.Accent}}">
{{if .IdPName}}<div class="idp-name">{{.IdPNameLead}}{{if .IdPNameTag}}<b>{{.IdPNameTag}}</b>{{end}}</div>{{end}}
<div class="logo"><img src="/masso-logo.png" alt="maSSO" width="200" /></div>
<div class="sub">{{.Protocol}} Device Sign In</div>
{{if .Error}}<div class="error">{{.Error}}</div>{{end}}
{{if .Success}}
<div class="success">{{.Success}}</div>
{{else}}
<form method="POST" action="/device">
<label>Device Code</label>
<input type="text" id="user_code" name="user_code" value="{{.UserCode}}" placeholder="XXXX-XXXX" required autofocus>
<label>Username</label>
<input type="text" name="username" placeholder="testing@example.com" required>
<label>Password</label>
<input type="password" name="password" placeholder="••••••••" required>
<div class="btn-row">
<button type="submit" name="action" value="approve">Approve</button>
<button type="submit" name="action" value="deny" class="deny">Deny</button>
</div>
</form>
{{end}}
<script>
(function(){
var card=document.getElementById('device-card');
if(card&&card.dataset.accent){card.style.setProperty('--accent',card.dataset.accent);}
})();
</script>
</div>
</body>
</html>`))
type devicePageData struct {
UserCode string
Error string
Success string
Protocol string
IdPName string
IdPNameLead string
IdPNameTag string
Accent string
}
func renderDevicePage(w http.ResponseWriter, userCode, errMsg, successMsg, protocol, idpName, accent string) {
if accent == "" {
accent = "#fe9832"
}
lead, tag := splitTrailingTag(idpName)
deviceTemplate.Execute(w, devicePageData{
UserCode: userCode, Error: errMsg, Success: successMsg, Protocol: protocol,
IdPName: idpName, IdPNameLead: lead, IdPNameTag: tag, Accent: accent,
})
}
// normalizeUserCode uppercases and re-inserts the dash RFC 8628 device codes
// use (op.UserCodeBase20: 8 chars, dash every 4, e.g. "VMWT-WRLG"), so a user
// typing the code back lowercase or without the dash still matches the exact
// string StoreDeviceAuthorization indexed it under.
func normalizeUserCode(raw string) string {
var b strings.Builder
for _, r := range strings.ToUpper(raw) {
if r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' {
b.WriteRune(r)
}
}
s := b.String()
if len(s) != 8 {
return strings.ToUpper(strings.TrimSpace(raw)) // let the lookup fail naturally
}
return s[:4] + "-" + s[4:]
}
// handleDeviceApproval serves the RFC 8628 user-facing approval page for one
// IdP instance. stor is that instance's own Storage (holds the pending device
// codes to approve/deny); users is the shared user database (sqliteStore) used
// to check the submitted username/password, matching renderLogin's pattern.
func handleDeviceApproval(stor *storage.Storage, users storage.UserStore, protocol, idpName, accent string) (get, post http.HandlerFunc) {
get = func(w http.ResponseWriter, r *http.Request) {
renderDevicePage(w, r.URL.Query().Get("user_code"), "", "", protocol, idpName, accent)
}
post = func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
userCode := normalizeUserCode(r.FormValue("user_code"))
if userCode == "" {
renderDevicePage(w, "", "Device code is required", "", protocol, idpName, accent)
return
}
if _, err := stor.GetDeviceAuthorizationByUserCode(r.Context(), userCode); err != nil {
renderDevicePage(w, r.FormValue("user_code"), "Invalid or expired device code", "", protocol, idpName, accent)
return
}
if r.FormValue("action") == "deny" {
stor.DenyDeviceAuthorization(r.Context(), userCode)
renderDevicePage(w, "", "", "Request denied. You can close this window.", protocol, idpName, accent)
return
}
username, password := r.FormValue("username"), r.FormValue("password")
user := users.GetUserByUsername(username)
if user == nil || user.Password != password {
renderDevicePage(w, r.FormValue("user_code"), "Invalid username or password", "", protocol, idpName, accent)
return
}
if err := stor.CompleteDeviceAuthorization(r.Context(), userCode, user.ID); err != nil {
renderDevicePage(w, r.FormValue("user_code"), err.Error(), "", protocol, idpName, accent)
return
}
renderDevicePage(w, "", "", "Device authorized! You can close this window and return to your device.", protocol, idpName, accent)
}
return get, post
}
func main() {
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, "Usage: masso <oidc|saml> [flags]")
fmt.Fprintln(os.Stderr, " oidc Start as OIDC Identity Provider")
fmt.Fprintln(os.Stderr, " saml Start as SAML Identity Provider")
os.Exit(1)
}
mode := os.Args[1]
os.Args = append(os.Args[:1], os.Args[2:]...)
switch mode {
case "oidc":
runOIDC()
case "saml":
runSAML()
default:
fmt.Fprintf(os.Stderr, "Unknown mode %q - use 'oidc' or 'saml'\n", mode)
os.Exit(1)
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Shared bootstrap
// ─────────────────────────────────────────────────────────────────────────────
type sharedState struct {
port string
dashPort string
dashHost string
dbPath string
issuer string
issuerSource string // "cloudflared", "flag", or "default"
logger *slog.Logger
sqliteStore *storage.SQLiteStore
engine *interceptor.Engine
dash *dashboard.Dashboard
router chi.Router
dashRouter chi.Router
scimClient *massoSCIM.Client
cfTunnelCmd *exec.Cmd
cfTunnelCmdB *exec.Cmd // duo mode: IdP B's cloudflared tunnel (nil if none)
// Duo mode fields
duoMode bool
portB string
issuerB string // duo mode: IdP B public issuer (tunnel URL; empty ⇒ localhost)
nameA string
nameB string
colorA string
colorB string
}
// aName returns the label for IdP A on the login page: the configured name in
// duo mode, or empty in single mode (where no per-IdP label is shown).
func (s *sharedState) aName() string {
if s.duoMode {
return s.nameA
}
return ""
}
// killTunnels terminates any running cloudflared tunnels — IdP A's and, in duo
// mode, IdP B's. Safe to call when no tunnels were started (both fields nil).
func (s *sharedState) killTunnels() {
for _, c := range []*exec.Cmd{s.cfTunnelCmd, s.cfTunnelCmdB} {
if c != nil && c.Process != nil {
s.logger.Info("Shutting down, killing Cloudflare Tunnel", "pid", c.Process.Pid)
c.Process.Kill()
}
}
}
// startQuickTunnel launches a cloudflared quick tunnel for the given local port
// and returns the public trycloudflare URL and the running process. It returns an
// error (rather than exiting) so callers can decide whether a failure is fatal
// (IdP A) or should fall back to a localhost issuer (IdP B in duo mode).
func startQuickTunnel(port string) (string, *exec.Cmd, error) {
// We read stderr because cloudflared prints its logs (and the URL) there.
cmd := exec.Command("cloudflared", "tunnel", "--url", "http://localhost:"+port)
stderr, err := cmd.StderrPipe()
if err != nil {
return "", nil, fmt.Errorf("create stderr pipe for cloudflared: %w", err)
}
if err := cmd.Start(); err != nil {
return "", nil, fmt.Errorf("start cloudflared (is it installed?): %w", err)
}
// Parse output for the trycloudflare.com URL.
// Example: | https://name-name-name-name.trycloudflare.com
urlRegex := regexp.MustCompile(`https://[a-zA-Z0-9-]+\.trycloudflare\.com`)
foundURL := make(chan string, 1)
go func() {
scanner := bufio.NewScanner(stderr)
sent := false
for scanner.Scan() {
if !sent {
if match := urlRegex.FindString(scanner.Text()); match != "" {
foundURL <- match
sent = true
}
}
// Keep draining stderr for the life of the process even after the URL
// is found. cloudflared logs continuously (edge connections, keepalives);
// if we stopped reading, the ~64KB OS pipe buffer would eventually fill
// and cloudflared would block on write, stalling the tunnel. The loop
// ends when cloudflared exits and closes stderr.
}
}()
select {
case u := <-foundURL:
return u, cmd, nil
case <-time.After(20 * time.Second):
cmd.Process.Kill()
return "", nil, fmt.Errorf("timed out waiting for cloudflared tunnel URL for port %s", port)
}
}
func bootstrap(fs *flag.FlagSet, mode string) *sharedState {
portFlag := fs.String("port", "8081", "Port to listen on (IdP endpoints)")
dashPortFlag := fs.String("dash-port", "8082", "Port for the attacker dashboard (keep local)")
dashHostFlag := fs.String("dash-host", "127.0.0.1", "Host to bind the dashboard on (use 0.0.0.0 inside Docker)")
issuerFlag := fs.String("issuer", "", "Public issuer URL (e.g. https://abc.ngrok-free.app/). Defaults to http://localhost:<port>/")
dbPath := fs.String("db", "data.db", "SQLite database path")
cfEnabled := fs.Bool("cloudflared", false, "Tunnel IdP port through cloudflared (trycloudflare.com) and use its URL as issuer")
scimURL := fs.String("scim-url", "", "Target SP SCIM base URL (enables SCIM client mode)")
scimToken := fs.String("scim-token", "", "Bearer token for SCIM API (issued by SP)")
scimTokenType := fs.String("scim-token-type", "Bearer", "Auth scheme: Bearer, Basic, or custom header name")
scimTLSSkip := fs.Bool("scim-tls-skip-verify", false, "Skip TLS cert verification for SCIM requests")
duoFlag := fs.Bool("duo", false, "Run two IdP instances on --port and --port-b (duo mode)")
portBFlag := fs.String("port-b", "", "Port for the second IdP in duo mode (defaults to --port + 2, skipping the default --dash-port)")
nameAFlag := fs.String("name-a", "IdP A", "Name label for the first IdP in duo mode")
nameBFlag := fs.String("name-b", "IdP B", "Name label for the second IdP in duo mode")
colorAFlag := fs.String("color-a", "#fe9832", "Accent hex color for the first IdP in duo mode")
colorBFlag := fs.String("color-b", "#4a9eff", "Accent hex color for the second IdP in duo mode")
fs.Parse(os.Args[1:])
// Reject single-IdP "quick setup" flags in duo mode, before any tunnel or
// subprocess is started below - checking after bootstrap() returns would be
// too late, since cloudflared may already be running by then. In duo mode
// these flags no longer have one clear target: --acs/--audience only ever
// apply to IdP A (IdP B keeps its own independent, empty-until-configured
// SAMLConfig), and the OIDC client list is shared across both IdPs, so a
// CLI shortcut invites confusion about which of the two IdPs it was "for".
// Once both instances are up, the dashboard's Settings tab is the one place
// to configure each IdP - single mode keeps these flags for fast one-shot runs.
if *duoFlag {
explicitFlags := make(map[string]bool)
fs.Visit(func(f *flag.Flag) { explicitFlags[f.Name] = true })
quickSetupFlags := []string{"client-id", "client-secret", "redirect-uri", "any-redirect", "acs", "audience"}
for _, name := range quickSetupFlags {
if explicitFlags[name] {
log.Fatalf("--%s is not supported with --duo (start duo mode with --duo alone, then configure each IdP from the dashboard's Settings tab once both are up)", name)
}
}
}
issuer := *issuerFlag
// Resolve portB for duo mode up front so a second tunnel can target it below.
// Default is port+2 (not port+1) to avoid colliding with the default --dash-port (port+1).
portB := *portBFlag
if *duoFlag && portB == "" {
portAInt, _ := strconv.Atoi(*portFlag)
portB = strconv.Itoa(portAInt + 2)
}
if *duoFlag {
if portB == *portFlag {
log.Fatalf("--port-b (%s) must differ from --port (%s)", portB, *portFlag)
}
if portB == *dashPortFlag {
log.Fatalf("--port-b (%s) collides with --dash-port (%s); set --port-b or --dash-port explicitly", portB, *dashPortFlag)
}
}
// cfCmd/cfCmdB are the cloudflared tunnels for IdP A and (duo mode) IdP B.
// issuerB carries IdP B's public issuer when it is tunneled; empty otherwise,
// in which case duo setup falls back to http://localhost:<port-b>/.
var cfCmd, cfCmdB *exec.Cmd
var issuerB string
if *cfEnabled {
slog.Info("Establishing Cloudflare Tunnel (quick tunnel)...")
u, cmd, err := startQuickTunnel(*portFlag)
if err != nil {
log.Fatalf("Fatal: %v. Check your internet connection or cloudflared logs.", err)
}
issuer, cfCmd = u, cmd
slog.Info("Cloudflare Tunnel established", "instance", "A", "url", issuer)
// Duo mode: give IdP B its own tunnel so it is publicly reachable too.
// A failed second tunnel is non-fatal — fall back to a localhost issuer so
// a flaky B tunnel never aborts the whole run.
if *duoFlag {
slog.Info("Establishing Cloudflare Tunnel for IdP B...")
if ub, cmdB, tErr := startQuickTunnel(portB); tErr == nil {
issuerB, cfCmdB = ub, cmdB
slog.Info("Cloudflare Tunnel established", "instance", "B", "url", issuerB)
} else {
slog.Warn("IdP B Cloudflare Tunnel failed; using localhost issuer for IdP B", "error", tErr)
}
}
}
issuerSource := "default"
if cfCmd != nil {
issuerSource = "cloudflared"
} else if *issuerFlag != "" {
issuerSource = "flag"
}
if issuer == "" {
issuer = fmt.Sprintf("http://localhost:%s/", *portFlag)
}
// For a user-provided issuer with no explicit port over http (typical of a
// public host with direct access and no reverse proxy), advertise endpoints
// on the port the IdP actually listens on. https issuers (TLS/tunnel on 443)
// and issuers that already carry an explicit port are left untouched, so a
// reverse-proxy setup can override by specifying the port (e.g. :80).
if issuerSource == "flag" {
if adjusted, changed := appendIssuerPort(issuer, *portFlag); changed {
slog.Warn("Issuer had no explicit port; appended the IdP listen port so advertised endpoints are reachable for direct access",
"original", strings.TrimRight(*issuerFlag, "/")+"/", "issuer", adjusted,
"hint", "if a reverse proxy fronts the IdP on a standard port, set --issuer with an explicit port (e.g. http://host:80/) to override")
issuer = adjusted
}
}
if !strings.HasSuffix(issuer, "/") {
issuer += "/"
}
// Normalize IdP B's tunnel issuer the same way (localhost fallbacks already
// carry a trailing slash), so A and B advertise a consistent issuer format.
if issuerB != "" && !strings.HasSuffix(issuerB, "/") {
issuerB += "/"
}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
AddSource: true, Level: slog.LevelDebug,
}))
sqliteStore, err := storage.NewSQLiteStore(*dbPath)
if err != nil {
log.Fatalf("Failed to init database: %v", err)
}
if count, _ := sqliteStore.UserCount(); count == 0 {
sqliteStore.AddUser(&storage.User{
ID: "id1", Username: "testing@example.com", Password: "verysecure",
FirstName: "Test", LastName: "User", Email: "testing@example.com",
EmailVerified: true, PreferredLanguage: language.German, IsAdmin: true,
})
sqliteStore.AddUser(&storage.User{
ID: "id2", Username: "demo@example.com", Password: "verysecure",
FirstName: "Demo", LastName: "User", Email: "demo@example.com",
EmailVerified: true, PreferredLanguage: language.German,
})
logger.Info("Seeded default users into database", "path", *dbPath)
}
eng := interceptor.NewEngine(logger, mode)
// Load persisted endpoint configs for instance 0 (single mode / duo IdP A).
// Each instance's config is stored and retrieved separately by index; the
// second duo instance loads its own config (index 1) in the duo branch below.
if saved, loadErr := sqliteStore.LoadEndpointConfigs(0); loadErr == nil {
eng.Mu.Lock()
for path, cfg := range saved {
if ec, ok := eng.Endpoints[path]; ok {
ec.Mode = cfg.Mode
ec.MockResponse = cfg.MockResponse
ec.SAMLConfig = cfg.SAMLConfig
}
}
eng.Mu.Unlock()
logger.Info("Loaded persisted endpoint configs", "instance", 0, "count", len(saved))
}
var sc *massoSCIM.Client
if *scimURL != "" {
sc = massoSCIM.NewClient(massoSCIM.Config{
BaseURL: *scimURL,
Token: *scimToken,
TokenType: *scimTokenType,
TLSSkipVerify: *scimTLSSkip,
}, eng, logger)
logger.Info("SCIM client enabled", "base_url", *scimURL)
}
dash := dashboard.NewDashboard(eng, sqliteStore, sqliteStore, logger, sc, issuer, issuerSource)
router := chi.NewRouter()
router.Use(eng.Middleware)
// Do not register routes here: each mode (OIDC / SAML) may add middleware
// with Use() and chi requires all Use() before any routes.
dashRouter := chi.NewRouter()
dashRouter.Mount("/dashboard", dash.Router)
st := &sharedState{
port: *portFlag, dashPort: *dashPortFlag, dashHost: *dashHostFlag, dbPath: *dbPath, issuer: issuer,
issuerSource: issuerSource,
logger: logger, sqliteStore: sqliteStore,
engine: eng, dash: dash, router: router, dashRouter: dashRouter,
scimClient: sc,
cfTunnelCmd: cfCmd,
cfTunnelCmdB: cfCmdB,
duoMode: *duoFlag,
portB: portB,
issuerB: issuerB,
nameA: *nameAFlag,
nameB: *nameBFlag,
colorA: *colorAFlag,
colorB: *colorBFlag,
}
if sc != nil {
go func() {
time.Sleep(1 * time.Second)
n, err := sc.ImportUsers(sqliteStore)
if err != nil {
logger.Warn("SCIM auto-import failed", "error", err)
} else if n > 0 {
logger.Info("SCIM auto-import complete", "users", n)
}
}()
}
return st
}
func (s *sharedState) serve(banner string) {
fmt.Println()
fmt.Println(banner)
fmt.Println()
go func() {
dashAddr := s.dashHost + ":" + s.dashPort
s.logger.Info("Dashboard listening (local only)", "addr", dashAddr)
dashServer := &http.Server{Addr: dashAddr, Handler: s.dashRouter}
if err := dashServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
s.logger.Error("Dashboard server terminated", "error", err)
}
}()
server := &http.Server{Addr: ":" + s.port, Handler: s.router}
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
s.logger.Error("Server terminated", "error", err)
os.Exit(1)
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Crypto key / cert helpers
// ─────────────────────────────────────────────────────────────────────────────
// dataDir returns the data directory (next to the database) for storing generated keys.
func dataDir(dbPath string) string {
return filepath.Dir(dbPath)
}
// ensureSAMLNodeSessionSecret returns a stable secret for express-session in the Node SAML engine.
// Persisted next to the DB so container restarts do not invalidate in-flight SAML flows.
func ensureSAMLNodeSessionSecret(dbPath string) (string, error) {
secPath := filepath.Join(dataDir(dbPath), "saml-node-session-secret.txt")
if b, err := os.ReadFile(secPath); err == nil {
s := strings.TrimSpace(string(b))
if len(s) >= 32 {
return s, nil
}
}
sec := randomHex(32)
if err := os.MkdirAll(dataDir(dbPath), 0o755); err != nil {
return "", err
}
if err := os.WriteFile(secPath, []byte(sec+"\n"), 0o600); err != nil {
return "", err
}
return sec, nil
}
// ensureCryptoKey loads or generates a 32-byte AES key used by zitadel/oidc
// for encrypting session cookies. Stored as hex in <datadir>/crypto.key.
func ensureCryptoKey(dbPath string) ([32]byte, error) {
keyFile := filepath.Join(dataDir(dbPath), "crypto.key")
var key [32]byte
if data, err := os.ReadFile(keyFile); err == nil {
decoded, decErr := hex.DecodeString(strings.TrimSpace(string(data)))
if decErr == nil && len(decoded) == 32 {
copy(key[:], decoded)
return key, nil
}
}
if _, err := rand.Read(key[:]); err != nil {
return key, fmt.Errorf("generate crypto key: %w", err)
}
if err := os.MkdirAll(dataDir(dbPath), 0o755); err != nil {
return key, fmt.Errorf("create data dir: %w", err)
}
if err := os.WriteFile(keyFile, []byte(hex.EncodeToString(key[:])+"\n"), 0o600); err != nil {
return key, fmt.Errorf("write crypto key: %w", err)
}
return key, nil
}
// appendIssuerPort appends listenPort to an http issuer that has no explicit
// port, so a public host with direct access advertises endpoints on the port the
// IdP actually listens on. It returns the issuer unchanged (changed=false) when
// the issuer already has a port, is not http (e.g. an https tunnel on 443), or
// cannot be parsed.
func appendIssuerPort(issuer, listenPort string) (string, bool) {
u, err := url.Parse(issuer)
if err != nil || u.Host == "" {
return issuer, false
}
if u.Port() != "" {
return issuer, false // explicit port -> respect it (override hook)
}
if u.Scheme != "http" {
return issuer, false // https / other -> assume standard port or TLS proxy
}
u.Host = u.Hostname() + ":" + listenPort
return u.String(), true
}
// ensureSAMLCerts checks for SAML IdP cert/key in the engine directory.
// If missing, generates a fresh 2048-bit RSA key and self-signed X.509 cert.
// Returns the paths to the cert and key files.
func ensureSAMLCerts(engineDir string) (certPath, keyPath string, err error) {
certPath = filepath.Join(engineDir, "idp-public-cert.pem")
keyPath = filepath.Join(engineDir, "idp-private-key.pem")
return certPath, keyPath, ensureSAMLCertPair(engineDir, certPath, keyPath, "MASSO SAML IdP")
}
// ensureSAMLCertPair generates a self-signed RSA keypair at the given paths if
// either file is missing, and is a no-op if both already exist. Each duo-mode
// SAML instance passes distinct paths so IdP A and IdP B sign with their own key.
func ensureSAMLCertPair(engineDir, certPath, keyPath, commonName string) error {
if fileExists(certPath) && fileExists(keyPath) {
return nil
}
privKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return fmt.Errorf("generate RSA key: %w", err)
}
serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
template := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{CommonName: commonName, Organization: []string{"MASSO"}},
NotBefore: time.Now().Add(-1 * time.Hour),
NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
certDER, err := x509.CreateCertificate(rand.Reader, template, template, &privKey.PublicKey, privKey)
if err != nil {
return fmt.Errorf("create certificate: %w", err)
}
if err := os.MkdirAll(engineDir, 0o755); err != nil {
return fmt.Errorf("create engine dir: %w", err)
}
certFile, err := os.OpenFile(certPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return err
}
if err := pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certDER}); err != nil {
certFile.Close()
return fmt.Errorf("write cert PEM: %w", err)
}
certFile.Close()
keyFile, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
return err
}
if err := pem.Encode(keyFile, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privKey)}); err != nil {
keyFile.Close()
return fmt.Errorf("write key PEM: %w", err)
}
keyFile.Close()
return nil
}
func randomHex(n int) string {
b := make([]byte, n)
rand.Read(b)
return hex.EncodeToString(b)
}
func fileExists(path string) bool {
info, err := os.Stat(path)
return err == nil && !info.IsDir()
}
// ─────────────────────────────────────────────────────────────────────────────
// Terminal banner rendering (afl-fuzz-style boxes, one per active IdP)
// ─────────────────────────────────────────────────────────────────────────────
// isTTY reports whether f is an interactive terminal (character device). We only
// emit ANSI color when a human is watching, never into pipes or log files.
func isTTY(f *os.File) bool {
fi, err := f.Stat()
return err == nil && fi.Mode()&os.ModeCharDevice != 0
}
// hexANSI converts a #rrggbb accent to a 24-bit ANSI foreground escape plus the
// reset sequence. It returns empty strings when color is off or the hex is
// invalid, so callers can concatenate the results unconditionally.
func hexANSI(hex string, on bool) (open, reset string) {
if !on {
return "", ""
}
h := strings.TrimPrefix(strings.TrimSpace(hex), "#")
if len(h) != 6 {
return "", ""
}
v, err := strconv.ParseUint(h, 16, 32)
if err != nil {
return "", ""
}
return fmt.Sprintf("\x1b[38;2;%d;%d;%dm", (v>>16)&0xff, (v>>8)&0xff, v&0xff), "\x1b[0m"
}
// renderIdPBox draws one afl-style box with the IdP's title in the top border and
// each line left-aligned inside. The box width adapts to the longest line so long
// tunnel URLs are never truncated. Border and title are tinted with the accent
// hex when color is active; the body text is left uncolored for readability.
func renderIdPBox(title, accent string, colorOn bool, lines []string) string {
runes := func(s string) int { return len([]rune(s)) }
// inner = columns between the two vertical bars (includes the 1-space left pad).
inner := runes(title) + 4 // room for "─ title ─"
for _, l := range lines {
if n := runes(l) + 2; n > inner { // 1 space each side
inner = n
}
}
col, rst := hexANSI(accent, colorOn)
var b strings.Builder
titleSeg := "─ " + title + " "
dashes := inner - runes(titleSeg)
if dashes < 0 {
dashes = 0
}
b.WriteString(" " + col + "┌" + titleSeg + strings.Repeat("─", dashes) + "┐" + rst + "\n")
for _, l := range lines {
pad := inner - 1 - runes(l)
if pad < 0 {
pad = 0
}
b.WriteString(" " + col + "│" + rst + " " + l + strings.Repeat(" ", pad) + col + "│" + rst + "\n")
}
b.WriteString(" " + col + "└" + strings.Repeat("─", inner) + "┘" + rst + "\n")
return b.String()
}
// externalURLLabel renders the "External URL" value for one issuer given how the
// issuer was resolved (cloudflared tunnel, --issuer flag, or plain localhost).
func externalURLLabel(issuer, source string) string {
switch source {
case "cloudflared":
return issuer + " (Cloudflare)"
case "flag":
return issuer + " (--issuer)"
default:
return "None (localhost only)"
}
}
// oidcIdPLines returns the per-IdP body lines (listen addr, issuer, endpoints)
// for an OIDC box. Every endpoint is derived from that instance's own issuer so
// duo IdP A and IdP B advertise their distinct tunnel URLs.
func oidcIdPLines(port, issuer, source string) []string {
return []string{
"Listen : 0.0.0.0:" + port + " -> expose via tunnel",
"Issuer : " + issuer,
"External URL : " + externalURLLabel(issuer, source),
"",
"OIDC Endpoints:",
" Discovery : " + issuer + ".well-known/openid-configuration",
" Authorization : " + issuer + "authorize",
" Token : " + issuer + "oauth/token",
" UserInfo : " + issuer + "userinfo",
" JWKS : " + issuer + "keys",
" Dynamic Reg : " + issuer + "register",
" Device Auth : " + issuer + "device_authorization",
" Revocation : " + issuer + "revoke",
" Introspection : " + issuer + "oauth/introspect",
}
}
// samlIdPLines returns the per-IdP body lines for a SAML box.
func samlIdPLines(port, issuer, source, certPath string) []string {
return []string{
"Listen : 0.0.0.0:" + port + " -> expose via tunnel",
"Issuer / EID : " + issuer,
"External URL : " + externalURLLabel(issuer, source),
"Certificate : " + certPath,
" (import this cert into the SP trust store)",
"",
"SAML Endpoints:",
" Metadata (XML) : " + issuer + "metadata",
" SSO : " + issuer + "saml/sso",
" SLO : " + issuer + "saml/slo",
}
}
// ─────────────────────────────────────────────────────────────────────────────
// OIDC mode
// ─────────────────────────────────────────────────────────────────────────────
func runOIDC() {
fs := flag.NewFlagSet("oidc", flag.ExitOnError)
redirectURI := fs.String("redirect-uri", "http://localhost:9999/callback",
"Registered redirect URI for the web client. Use * or doublestar globs, or re: for regex. Quote * in the shell: '*'. See also -any-redirect.")
anyRedirect := fs.Bool("any-redirect", false,
"Register redirect as '*' (any URL) without shell globbing. Overrides -redirect-uri when set.")
clientID := fs.String("client-id", "web", "OIDC Client ID")
clientSecret := fs.String("client-secret", "secret", "OIDC Client Secret")
s := bootstrap(fs, "oidc")
defer s.sqliteStore.Close()
// Determine which flags were explicitly provided by the user.
explicitFlags := make(map[string]bool)
fs.Visit(func(f *flag.Flag) { explicitFlags[f.Name] = true })
// Load persisted client list (falls back to one default if not yet stored).
allClientCfgs, _ := s.sqliteStore.LoadOIDCClientConfigs()
if len(allClientCfgs) == 0 {
allClientCfgs = []storage.OIDCClientConfig{storage.DefaultOIDCClientConfig()}
}
cli := storage.OIDCClientCLI{
ClientID: *clientID,
ClientSecret: *clientSecret,
RedirectURI: *redirectURI,
AnyRedirect: *anyRedirect,
SetClientID: explicitFlags["client-id"],
SetClientSecret: explicitFlags["client-secret"],
SetRedirect: explicitFlags["redirect-uri"],
SetAnyRedirect: explicitFlags["any-redirect"],
}
clientCfg, mergeWarns := cli.Apply(allClientCfgs[0])
allClientCfgs[0] = clientCfg
for _, w := range mergeWarns {
s.logger.Warn("OIDC client redirect", "message", w)
}
// When any CLI field was set, flags override SQLite for the first client so the
// next dashboard-only run is consistent. We persist the full list each startup.
if err := s.sqliteStore.SaveOIDCClientConfigs(allClientCfgs); err != nil {
s.logger.Error("Failed to persist OIDC client config", "error", err)
}
if cli.ShouldPersistOIDCClient() {
s.logger.Info("OIDC client config: CLI flags applied over first persisted client",
"client_id", clientCfg.ClientID, "redirect_uris", clientCfg.RedirectURIs,
)
}
s.router.Use(httprate.LimitByIP(400, time.Minute))
reg := []*storage.Client{storage.NativeClient("native", allClientCfgs[0].RedirectURIs...)}
for _, c := range allClientCfgs {