-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcryptauth.go
More file actions
1361 lines (1185 loc) · 37.1 KB
/
Copy pathcryptauth.go
File metadata and controls
1361 lines (1185 loc) · 37.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
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 cryptauth
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"filippo.io/age"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
"gopkg.in/yaml.v3"
"github.com/nativebpm/totp"
)
// SecurityEvent captures a security/authentication log.
type SecurityEvent struct {
Timestamp time.Time `json:"timestamp"`
Event string `json:"event"` // e.g. LOGIN_SUCCESS, LOGIN_FAILED, LOGOUT, UNAUTHORIZED, FORBIDDEN
Username string `json:"username"`
IP string `json:"ip"`
Details string `json:"details"`
}
// GopassMetadata represents the metadata stored below the password in a gopass-style secret.
type GopassMetadata struct {
Role string `yaml:"role"`
Totp string `yaml:"totp"`
RecoveryHash string `yaml:"recovery_hash,omitempty"`
}
// User represents a loaded credentials account.
type User struct {
Username string
PasswordHash string
Role string
TOTPSecret string
RecoveryHash string
AccessToken string // JWT token if authenticated via Supabase
Timezone string // timezone identifier
}
// Session represents the cryptographically signed user session.
type Session struct {
Username string `json:"username"`
Role string `json:"role"`
ExpiresAt int64 `json:"expires_at"`
Timezone string `json:"timezone,omitempty"`
}
type cachedSession struct {
Session *Session
ExpiresAt time.Time
}
// Authenticator handles loading credentials, verifying passwords, generating/validating sessions, and logging audit events.
type Authenticator struct {
SessionSecret []byte
Users map[string]*User
muUsers sync.RWMutex
muEvents sync.RWMutex
Events []*SecurityEvent
err error // internal error tracking
// Supabase integration fields
SupabaseJWTSecret []byte
SupabaseURL string
// In-memory session cache fields
cacheMu sync.RWMutex
sessionCache map[[32]byte]*cachedSession
userSessionHashes map[string][][32]byte
// Custom callbacks to retrieve age/recovery encrypted data from database/storage (local mode)
GetEncryptedAgeData func(username string) ([]byte, error)
GetEncryptedRecoveryData func(username string) ([]byte, error)
}
// New creates a new, unconfigured Authenticator builder.
func New() *Authenticator {
return &Authenticator{
Users: make(map[string]*User),
Events: make([]*SecurityEvent, 0),
sessionCache: make(map[[32]byte]*cachedSession),
userSessionHashes: make(map[string][][32]byte),
}
}
// WithSessionSecret configures the session HMAC secret key.
func (a *Authenticator) WithSessionSecret(secret string) *Authenticator {
if a.err != nil {
return a
}
if secret == "" {
a.err = errors.New("session secret cannot be empty")
return a
}
a.SessionSecret = []byte(secret)
return a
}
// WithSupabase configures the Supabase API endpoint and JWT verification secret.
func (a *Authenticator) WithSupabase(url, jwtSecret string) *Authenticator {
if a.err != nil {
return a
}
a.SupabaseURL = url
if jwtSecret != "" {
a.SupabaseJWTSecret = []byte(jwtSecret)
}
return a
}
// ValidatePassword checks if the password meets the age-compatible length and safe character set criteria.
func ValidatePassword(password string) error {
if len(password) < 8 {
return errors.New("password must be at least 8 characters long")
}
if len(password) > 72 {
return errors.New("password must be at most 72 characters long")
}
if strings.TrimSpace(password) != password {
return errors.New("password cannot start or end with a space")
}
// Safe character set check:
// Allowed: alphanumeric, space, and a safe list of symbols.
// Disallowed: $, \, `, ", ', |, &, <, >, control characters.
for _, char := range password {
if char < 32 || char > 126 {
return errors.New("password contains unsupported or non-printable characters")
}
switch char {
case '$', '\\', '`', '"', '\'', '|', '&', '<', '>':
return fmt.Errorf("password contains unsafe special character: %c", char)
}
}
return nil
}
func encryptAgeSymmetric(data []byte, passphrase string) ([]byte, error) {
recipient, err := age.NewScryptRecipient(passphrase)
if err != nil {
return nil, err
}
var buf bytes.Buffer
w, err := age.Encrypt(&buf, recipient)
if err != nil {
return nil, err
}
if _, err := w.Write(data); err != nil {
return nil, err
}
if err := w.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func decryptAgeSymmetric(encrypted []byte, passphrase string) ([]byte, error) {
identity, err := age.NewScryptIdentity(passphrase)
if err != nil {
return nil, err
}
r, err := age.Decrypt(bytes.NewReader(encrypted), identity)
if err != nil {
return nil, err
}
return io.ReadAll(r)
}
// WithGopassUser decrypts age-encrypted data using credentials, then parses and registers the user.
func (a *Authenticator) WithGopassUser(username string, encryptedData []byte, passphrase string, privateKey string) *Authenticator {
if a.err != nil {
return a
}
if err := a.LoadUserFromGopassContent(username, encryptedData, passphrase, privateKey); err != nil {
a.err = err
}
return a
}
// WithUser directly adds a User struct to the authenticator.
func (a *Authenticator) WithUser(username string, user *User) *Authenticator {
if a.err != nil {
return a
}
a.muUsers.Lock()
a.Users[username] = user
a.muUsers.Unlock()
return a
}
// Error returns the first configuration error encountered, if any.
func (a *Authenticator) Error() error {
return a.err
}
// NewAuthenticator creates a new Authenticator with the given session HMAC secret key.
func NewAuthenticator(sessionSecret string) (*Authenticator, error) {
if sessionSecret == "" {
return nil, errors.New("session secret cannot be empty")
}
return &Authenticator{
SessionSecret: []byte(sessionSecret),
Users: make(map[string]*User),
Events: make([]*SecurityEvent, 0),
sessionCache: make(map[[32]byte]*cachedSession),
userSessionHashes: make(map[string][][32]byte),
}, nil
}
// LoadUserFromGopassContent decrypts age-encrypted data using asymmetric identities
// or symmetric passphrase, then parses the gopass format.
func (a *Authenticator) LoadUserFromGopassContent(username string, encryptedData []byte, passphrase string, privateKey string) error {
var decrypted []byte
var err error
if privateKey != "" {
// Asymmetric decryption
ids, errIdentities := age.ParseIdentities(strings.NewReader(privateKey))
if errIdentities != nil {
return fmt.Errorf("failed to parse age identities: %w", errIdentities)
}
r, errDecrypt := age.Decrypt(bytes.NewReader(encryptedData), ids...)
if errDecrypt != nil {
return fmt.Errorf("failed to decrypt asymmetric age file: %w", errDecrypt)
}
decrypted, err = io.ReadAll(r)
if err != nil {
return err
}
} else if passphrase != "" {
// Symmetric decryption
identity, errSymmetric := age.NewScryptIdentity(passphrase)
if errSymmetric != nil {
return fmt.Errorf("failed to create symmetric age identity: %w", errSymmetric)
}
r, errDecrypt := age.Decrypt(bytes.NewReader(encryptedData), identity)
if errDecrypt != nil {
return fmt.Errorf("failed to decrypt symmetric age file: %w", errDecrypt)
}
decrypted, err = io.ReadAll(r)
if err != nil {
return err
}
} else {
return errors.New("no decryption key or passphrase provided")
}
// Parse gopass format: first line is password/hash, then optional "---" followed by YAML metadata
content := string(decrypted)
parts := strings.SplitN(content, "---", 2)
passwordLine := strings.TrimSpace(parts[0])
// Split by newline in case there's no "---" but multiple lines
lines := strings.Split(passwordLine, "\n")
passwordHash := strings.TrimSpace(lines[0])
var meta GopassMetadata
if len(parts) > 1 {
if errYaml := yaml.Unmarshal([]byte(parts[1]), &meta); errYaml != nil {
return fmt.Errorf("failed to parse gopass metadata YAML: %w", errYaml)
}
}
// Resolve TOTP secret (could be simple secret or otpauth URI)
totpSecret := strings.TrimSpace(meta.Totp)
if strings.HasPrefix(totpSecret, "otpauth://") {
parsedURL, errURL := url.Parse(totpSecret)
if errURL == nil {
secretVal := parsedURL.Query().Get("secret")
if secretVal != "" {
totpSecret = secretVal
}
}
}
role := strings.TrimSpace(meta.Role)
if role == "" {
role = "viewer" // default role
}
a.muUsers.Lock()
a.Users[username] = &User{
Username: username,
PasswordHash: passwordHash,
Role: role,
TOTPSecret: totpSecret,
RecoveryHash: meta.RecoveryHash,
}
a.muUsers.Unlock()
return nil
}
// IsSupabase returns true if Supabase URL is configured.
func (a *Authenticator) IsSupabase() bool {
return a.SupabaseURL != ""
}
// Authenticate verifies the user's credentials. If Supabase is enabled,
// it authenticates against Supabase GoTrue endpoint, otherwise it uses
// local bcrypt password comparison and TOTP validation.
func (a *Authenticator) Authenticate(username, password, code string) (*User, error) {
if a.IsSupabase() {
tokenURL := fmt.Sprintf("%s/auth/v1/token?grant_type=password", strings.TrimSuffix(a.SupabaseURL, "/"))
payloadMap := map[string]string{
"email": username,
"password": password,
}
jsonBytes, err := json.Marshal(payloadMap)
if err != nil {
return nil, fmt.Errorf("internal json error: %w", err)
}
req, err := http.NewRequest("POST", tokenURL, bytes.NewBuffer(jsonBytes))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
anonKey := os.Getenv("SUPABASE_ANON_KEY")
if anonKey != "" {
req.Header.Set("apiKey", anonKey)
} else if len(a.SupabaseJWTSecret) > 0 {
req.Header.Set("apiKey", string(a.SupabaseJWTSecret))
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("Supabase connection error: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var errResp struct {
ErrorDescription string `json:"error_description"`
Error string `json:"error"`
Message string `json:"msg"`
}
_ = json.NewDecoder(resp.Body).Decode(&errResp)
errMsg := errResp.ErrorDescription
if errMsg == "" {
errMsg = errResp.Message
}
if errMsg == "" {
errMsg = errResp.Error
}
if errMsg == "" {
errMsg = fmt.Sprintf("HTTP %d", resp.StatusCode)
}
return nil, errors.New(errMsg)
}
var tokenResp struct {
AccessToken string `json:"access_token"`
}
if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
return nil, fmt.Errorf("invalid token response from Supabase: %w", err)
}
// Verify and parse JWT locally to extract role
sess, err := a.verifySupabaseJWT(tokenResp.AccessToken)
if err != nil {
return nil, fmt.Errorf("failed to verify Supabase JWT: %w", err)
}
return &User{
Username: sess.Username,
Role: sess.Role,
AccessToken: tokenResp.AccessToken,
}, nil
}
a.muUsers.RLock()
user, exists := a.Users[username]
a.muUsers.RUnlock()
if !exists {
return nil, errors.New("invalid username or password")
}
// Try in-memory check if credentials are already loaded
if user.PasswordHash != "" {
err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password))
if err == nil {
if user.TOTPSecret != "" {
if !totp.Validate(code, user.TOTPSecret) {
return nil, errors.New("invalid TOTP verification code")
}
} else {
return nil, errors.New("TOTP is not configured for this user")
}
return user, nil
}
}
if a.GetEncryptedAgeData == nil {
return nil, errors.New("database credentials provider is not configured")
}
encryptedData, err := a.GetEncryptedAgeData(username)
if err != nil {
return nil, errors.New("invalid username or password")
}
decrypted, err := decryptAgeSymmetric(encryptedData, password)
if err != nil {
return nil, errors.New("invalid username or password")
}
content := string(decrypted)
parts := strings.SplitN(content, "---", 2)
passwordLine := strings.TrimSpace(parts[0])
lines := strings.Split(passwordLine, "\n")
passwordHash := strings.TrimSpace(lines[0])
var meta GopassMetadata
if len(parts) > 1 {
if errYaml := yaml.Unmarshal([]byte(parts[1]), &meta); errYaml != nil {
return nil, fmt.Errorf("failed to parse gopass metadata YAML: %w", errYaml)
}
}
totpSecret := strings.TrimSpace(meta.Totp)
if strings.HasPrefix(totpSecret, "otpauth://") {
parsedURL, errURL := url.Parse(totpSecret)
if errURL == nil {
secretVal := parsedURL.Query().Get("secret")
if secretVal != "" {
totpSecret = secretVal
}
}
}
role := strings.TrimSpace(meta.Role)
if role == "" {
role = "viewer"
}
// Verify the password hash
err = bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(password))
if err != nil {
return nil, errors.New("invalid username or password")
}
// Validate TOTP token
if totpSecret != "" {
if !totp.Validate(code, totpSecret) {
return nil, errors.New("invalid TOTP verification code")
}
} else {
return nil, errors.New("TOTP is not configured for this user")
}
// Populate in-memory user
a.muUsers.Lock()
user = &User{
Username: username,
PasswordHash: passwordHash,
Role: role,
TOTPSecret: totpSecret,
RecoveryHash: meta.RecoveryHash,
}
a.Users[username] = user
return user, nil
}
// AuthenticateLocal verifies the user's credentials without requiring a TOTP code.
// This is strictly intended for local development and testing purposes.
func (a *Authenticator) AuthenticateLocal(username, password string) (*User, error) {
if a.IsSupabase() {
return a.Authenticate(username, password, "")
}
a.muUsers.RLock()
user, exists := a.Users[username]
a.muUsers.RUnlock()
if !exists {
return nil, errors.New("invalid username or password")
}
// Try in-memory check if credentials are already loaded
if user.PasswordHash != "" {
err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password))
if err == nil {
return user, nil
}
}
if a.GetEncryptedAgeData == nil {
return nil, errors.New("database credentials provider is not configured")
}
encryptedData, err := a.GetEncryptedAgeData(username)
if err != nil {
return nil, errors.New("invalid username or password")
}
decrypted, err := decryptAgeSymmetric(encryptedData, password)
if err != nil {
return nil, errors.New("invalid username or password")
}
content := string(decrypted)
parts := strings.SplitN(content, "---", 2)
passwordLine := strings.TrimSpace(parts[0])
lines := strings.Split(passwordLine, "\n")
passwordHash := strings.TrimSpace(lines[0])
var meta GopassMetadata
if len(parts) > 1 {
if errYaml := yaml.Unmarshal([]byte(parts[1]), &meta); errYaml != nil {
return nil, fmt.Errorf("failed to parse gopass metadata YAML: %w", errYaml)
}
}
totpSecret := strings.TrimSpace(meta.Totp)
if strings.HasPrefix(totpSecret, "otpauth://") {
parsedURL, errURL := url.Parse(totpSecret)
if errURL == nil {
secretVal := parsedURL.Query().Get("secret")
if secretVal != "" {
totpSecret = secretVal
}
}
}
role := strings.TrimSpace(meta.Role)
if role == "" {
role = "viewer"
}
// Verify the password hash
err = bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(password))
if err != nil {
return nil, errors.New("invalid username or password")
}
// Populate in-memory user
a.muUsers.Lock()
user = &User{
Username: username,
PasswordHash: passwordHash,
Role: role,
TOTPSecret: totpSecret,
RecoveryHash: meta.RecoveryHash,
}
a.Users[username] = user
a.muUsers.Unlock()
return user, nil
}
// SignUp registers a new user with Supabase GoTrue. If Supabase is disabled,
// it returns an error because self-service signup is not allowed without the MFA flow.
func (a *Authenticator) SignUp(username, password string) error {
if err := ValidatePassword(password); err != nil {
return err
}
if !a.IsSupabase() {
return errors.New("self-service registration is disabled when running in local fallback mode")
}
signupURL := fmt.Sprintf("%s/auth/v1/signup", strings.TrimSuffix(a.SupabaseURL, "/"))
payloadMap := map[string]string{
"email": username,
"password": password,
}
jsonBytes, err := json.Marshal(payloadMap)
if err != nil {
return fmt.Errorf("failed to encode json: %w", err)
}
req, err := http.NewRequest("POST", signupURL, bytes.NewBuffer(jsonBytes))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
anonKey := os.Getenv("SUPABASE_ANON_KEY")
if anonKey != "" {
req.Header.Set("apiKey", anonKey)
} else if len(a.SupabaseJWTSecret) > 0 {
req.Header.Set("apiKey", string(a.SupabaseJWTSecret))
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("Supabase connection error: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
var errResp struct {
Message string `json:"msg"`
Error string `json:"error"`
}
_ = json.NewDecoder(resp.Body).Decode(&errResp)
errMsg := errResp.Message
if errMsg == "" {
errMsg = errResp.Error
}
if errMsg == "" {
errMsg = fmt.Sprintf("HTTP %d", resp.StatusCode)
}
return errors.New(errMsg)
}
return nil
}
// InitiateSSO initiates the SAML/SSO authentication flow for a given domain
// and returns the target redirection URL.
func (a *Authenticator) InitiateSSO(domain, redirectURL string) (string, error) {
if !a.IsSupabase() {
return "", errors.New("Supabase SSO is not configured on this server")
}
ssoReqURL := fmt.Sprintf("%s/auth/v1/sso", strings.TrimSuffix(a.SupabaseURL, "/"))
payload := map[string]interface{}{
"domain": domain,
"redirect_to": redirectURL,
"skip_http_redirect": true, // We parse URL response ourselves
}
jsonBytes, err := json.Marshal(payload)
if err != nil {
return "", fmt.Errorf("failed to encode JSON payload: %w", err)
}
req, err := http.NewRequest("POST", ssoReqURL, bytes.NewBuffer(jsonBytes))
if err != nil {
return "", fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
anonKey := os.Getenv("SUPABASE_ANON_KEY")
if anonKey != "" {
req.Header.Set("apiKey", anonKey)
} else if len(a.SupabaseJWTSecret) > 0 {
req.Header.Set("apiKey", string(a.SupabaseJWTSecret))
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("Supabase connection error: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var errResp struct {
Message string `json:"msg"`
Error string `json:"error"`
}
_ = json.NewDecoder(resp.Body).Decode(&errResp)
errMsg := errResp.Message
if errMsg == "" {
errMsg = errResp.Error
}
if errMsg == "" {
errMsg = fmt.Sprintf("HTTP %d", resp.StatusCode)
}
return "", errors.New(errMsg)
}
var ssoResp struct {
URL string `json:"url"`
}
if err := json.NewDecoder(resp.Body).Decode(&ssoResp); err != nil {
return "", fmt.Errorf("invalid SSO response from Supabase: %w", err)
}
return ssoResp.URL, nil
}
// GetSessionCookie retrieves the correct cookie value. If Supabase is enabled,
// it returns the stored AccessToken. Otherwise, it generates a standard local session cookie.
func (a *Authenticator) GetSessionCookie(user *User, duration time.Duration) (string, error) {
if a.IsSupabase() && user.AccessToken != "" {
return user.AccessToken, nil
}
return a.CreateSessionCookieWithTimezone(user.Username, user.Role, user.Timezone, duration)
}
// CreateSessionCookie generates a signed session token.
func (a *Authenticator) CreateSessionCookie(username, role string, duration time.Duration) (string, error) {
return a.CreateSessionCookieWithTimezone(username, role, "", duration)
}
// CreateSessionCookieWithTimezone generates a signed session token with a timezone.
func (a *Authenticator) CreateSessionCookieWithTimezone(username, role, timezone string, duration time.Duration) (string, error) {
expiresAt := time.Now().Add(duration).Unix()
sess := Session{
Username: username,
Role: role,
ExpiresAt: expiresAt,
Timezone: timezone,
}
payload, err := json.Marshal(sess)
if err != nil {
return "", err
}
// Sign payload using HMAC-SHA256
mac := hmac.New(sha256.New, a.SessionSecret)
mac.Write(payload)
signature := mac.Sum(nil)
// Combine payload and signature as Base64 UrlEncoded format: payload.signature
encodedPayload := base64.URLEncoding.EncodeToString(payload)
encodedSignature := base64.URLEncoding.EncodeToString(signature)
return encodedPayload + "." + encodedSignature, nil
}
// VerifySessionCookie decodes and validates a session token, utilizing an in-memory cache.
func (a *Authenticator) VerifySessionCookie(cookieValue string) (*Session, error) {
// 1. Check in-memory cache first
if sess, ok := a.GetCachedSession(cookieValue); ok {
if len(a.SupabaseJWTSecret) == 0 {
a.muUsers.RLock()
user, exists := a.Users[sess.Username]
a.muUsers.RUnlock()
if !exists {
a.InvalidateToken(cookieValue)
return nil, errors.New("user no longer exists")
}
sess.Role = user.Role
sess.Timezone = user.Timezone
}
return sess, nil
}
// 2. Perform full cryptographic verification
var sess *Session
var err error
if len(a.SupabaseJWTSecret) > 0 {
sess, err = a.verifySupabaseJWT(cookieValue)
} else {
sess, err = a.verifyLocalSession(cookieValue)
}
if err != nil {
return nil, err
}
// 3. Cache the verified session
a.AddCachedSession(cookieValue, sess)
return sess, nil
}
func (a *Authenticator) verifySupabaseJWT(cookieValue string) (*Session, error) {
token, err := jwt.Parse(cookieValue, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return a.SupabaseJWTSecret, nil
})
if err != nil {
return nil, fmt.Errorf("invalid Supabase session token: %w", err)
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || !token.Valid {
return nil, errors.New("invalid Supabase token claims")
}
// Extract Username (use email, if empty use sub)
var username string
if emailVal, ok := claims["email"]; ok {
username, _ = emailVal.(string)
}
if username == "" {
if subVal, ok := claims["sub"]; ok {
username, _ = subVal.(string)
}
}
// Extract Role from user_metadata or app_metadata
role := "viewer"
if userMetaVal, ok := claims["user_metadata"]; ok {
if userMeta, ok := userMetaVal.(map[string]interface{}); ok {
if rVal, ok := userMeta["role"]; ok {
if rStr, ok := rVal.(string); ok && rStr != "" {
role = rStr
}
}
}
}
if role == "viewer" {
if appMetaVal, ok := claims["app_metadata"]; ok {
if appMeta, ok := appMetaVal.(map[string]interface{}); ok {
if rVal, ok := appMeta["role"]; ok {
if rStr, ok := rVal.(string); ok && rStr != "" {
role = rStr
}
}
}
}
}
// Extract Expiry
var expiresAt int64
if expVal, ok := claims["exp"]; ok {
if expFloat, ok := expVal.(float64); ok {
expiresAt = int64(expFloat)
}
}
return &Session{
Username: username,
Role: role,
ExpiresAt: expiresAt,
}, nil
}
func (a *Authenticator) verifyLocalSession(cookieValue string) (*Session, error) {
idx := strings.IndexByte(cookieValue, '.')
if idx == -1 {
return nil, errors.New("invalid session format")
}
part0 := cookieValue[:idx]
part1 := cookieValue[idx+1:]
payload, err := base64.URLEncoding.DecodeString(part0)
if err != nil {
return nil, errors.New("failed to decode session payload")
}
signature, err := base64.URLEncoding.DecodeString(part1)
if err != nil {
return nil, errors.New("failed to decode session signature")
}
// Verify HMAC signature
mac := hmac.New(sha256.New, a.SessionSecret)
mac.Write(payload)
expectedSignature := mac.Sum(nil)
if !hmac.Equal(signature, expectedSignature) {
return nil, errors.New("session signature mismatch (tampering detected)")
}
var sess Session
if errJSON := json.Unmarshal(payload, &sess); errJSON != nil {
return nil, errJSON
}
// Check expiration
if time.Now().Unix() > sess.ExpiresAt {
return nil, errors.New("session has expired")
}
// Dynamically look up current user role and active status
a.muUsers.RLock()
user, exists := a.Users[sess.Username]
a.muUsers.RUnlock()
if !exists {
return nil, errors.New("user no longer exists")
}
// Dynamically override role to enforce immediate revocation
sess.Role = user.Role
return &sess, nil
}
// ExtractSession retrieves and validates session information from HTTP Request cookies.
func (a *Authenticator) ExtractSession(r *http.Request) (*Session, error) {
cookie, err := r.Cookie("nativebpm_session")
if err != nil {
return nil, err
}
return a.VerifySessionCookie(cookie.Value)
}
// LogEvent registers a new security audit event in the circular memory log and system slog.
func (a *Authenticator) LogEvent(event, username, ip, details string) {
a.muEvents.Lock()
a.Events = append(a.Events, &SecurityEvent{
Timestamp: time.Now(),
Event: event,
Username: username,
IP: ip,
Details: details,
})
// Circular buffer: keep only the latest 200 security logs
if len(a.Events) > 200 {
a.Events = a.Events[len(a.Events)-200:]
}
a.muEvents.Unlock()
// Log via system-wide structured logger
attrs := []any{
slog.String("event", event),
slog.String("username", username),
slog.String("ip", ip),
slog.String("details", details),
}
switch event {
case "LOGIN_FAILED", "UNAUTHORIZED", "FORBIDDEN", "REGISTER_FAILED":
slog.Warn("Security event", attrs...)
default:
slog.Info("Security event", attrs...)
}
}
// GetEvents returns a copy of all current security audit logs (ordered latest first).
func (a *Authenticator) GetEvents() []*SecurityEvent {
a.muEvents.RLock()
defer a.muEvents.RUnlock()
n := len(a.Events)
res := make([]*SecurityEvent, n)
for i := 0; i < n; i++ {
res[i] = a.Events[n-1-i]
}
return res
}
// EventBuilder is a fluent helper to construct and log security events.
type EventBuilder struct {
auth *Authenticator
event string
username string
ip string
details string
}
// NewEvent starts a fluent builder chain to log a security audit event.
func (a *Authenticator) NewEvent(event string) *EventBuilder {
return &EventBuilder{
auth: a,
event: event,
}
}
// ForUser sets the username of the user associated with the event.
func (eb *EventBuilder) ForUser(username string) *EventBuilder {
eb.username = username
return eb
}
// FromIP sets the IP address of the request.
func (eb *EventBuilder) FromIP(ip string) *EventBuilder {
eb.ip = ip
return eb
}
// WithDetails sets the details description for the event.
func (eb *EventBuilder) WithDetails(details string) *EventBuilder {
eb.details = details
return eb
}
// Log writes the security event to the audit log.
func (eb *EventBuilder) Log() {
if eb.auth != nil {
eb.auth.LogEvent(eb.event, eb.username, eb.ip, eb.details)
}
}
// GenerateGopassContent hashes the password, serializes metadata, encrypts the gopass file using age scrypt symmetric encryption,
// and returns raw encrypted data: ageData (encrypted with password), recoveryData (encrypted with recoveryKey, optional), and plain text role YAML content.
func (a *Authenticator) GenerateGopassContent(username, password, passphrase, role, totpSecret, recoveryKey string) (ageData []byte, recoveryData []byte, roleData []byte, err error) {
if username == "" {
err = errors.New("username cannot be empty")
return
}
if password == "" {
err = errors.New("password cannot be empty")
return
}
if errVal := ValidatePassword(password); errVal != nil {
err = errVal
return
}
if role == "" {
role = "viewer"
}
// 1. Hash password using bcrypt
hash, errHash := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if errHash != nil {