-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
2057 lines (1815 loc) · 73.3 KB
/
main.go
File metadata and controls
2057 lines (1815 loc) · 73.3 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 (
"context"
"fmt"
"html/template" // Import for HTML templates
"log"
"net"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v4"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn" // Import for pgconn.CommandTag
"github.com/jackc/pgx/v5/pgxpool"
"github.com/joho/godotenv"
"github.com/spf13/viper"
"github.com/google/uuid"
)
// schemaSQL defines the PostgreSQL database schema for the FIRM protocol.
// This will be executed on application startup to ensure tables exist.
const schemaSQL = `
-- TABLE email_verifications
CREATE TABLE IF NOT EXISTS email_verifications (
email VARCHAR(255) PRIMARY KEY,
first_seen TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
token_count INTEGER NOT NULL DEFAULT 0,
verified BOOLEAN NOT NULL DEFAULT FALSE,
last_token VARCHAR(64),
last_ip VARCHAR(45),
last_attempt TIMESTAMP,
last_blocked TIMESTAMP,
blocked_count INTEGER NOT NULL DEFAULT 0,
expires_at TIMESTAMP,
notes TEXT
);
CREATE INDEX IF NOT EXISTS idx_email_verifications_email ON email_verifications(email);
CREATE INDEX IF NOT EXISTS idx_email_verifications_last_blocked ON email_verifications(last_blocked);
-- TABLE tokens
CREATE TABLE IF NOT EXISTS tokens (
token_id VARCHAR(64) PRIMARY KEY,
email VARCHAR(255) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NOT NULL,
used_at TIMESTAMP,
status VARCHAR(20) NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_tokens_token ON tokens(token_id);
CREATE INDEX IF NOT EXISTS idx_tokens_email ON tokens(email);
-- TABLE ip_activity
CREATE TABLE IF NOT EXISTS ip_activity (
ip_hex VARCHAR(45) PRIMARY KEY,
first_seen TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_seen TIMESTAMP,
token_requests INTEGER NOT NULL DEFAULT 0,
inbound_attempts INTEGER NOT NULL DEFAULT 0,
blocked BOOLEAN NOT NULL DEFAULT FALSE,
blocked_count INTEGER NOT NULL DEFAULT 0,
last_blocked TIMESTAMP,
expires_at TIMESTAMP,
notes TEXT
);
CREATE INDEX IF NOT EXISTS idx_ip_activity_ip_hex ON ip_activity(ip_hex);
CREATE INDEX IF NOT EXISTS idx_ip_activity_last_seen ON ip_activity(last_seen);
-- TABLE banned_subnets
CREATE TABLE IF NOT EXISTS banned_subnets (
subnet_hex VARCHAR(45) NOT NULL,
cidr INTEGER NOT NULL,
reason TEXT,
banned_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP,
hits INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (subnet_hex, cidr)
);
CREATE INDEX IF NOT EXISTS idx_banned_subnets_subnet_hex ON banned_subnets(subnet_hex);
-- TABLE admin_emails
CREATE TABLE IF NOT EXISTS admin_emails (
email VARCHAR(255) PRIMARY KEY,
added_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
added_by VARCHAR(255),
expires_at TIMESTAMP,
notes TEXT
);
CREATE INDEX IF NOT EXISTS idx_admin_emails_email ON admin_emails(email);
-- TABLE admin_events
CREATE TABLE IF NOT EXISTS admin_events (
id SERIAL PRIMARY KEY,
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
action VARCHAR(50) NOT NULL,
actor VARCHAR(255) NOT NULL,
target TEXT,
notes TEXT
);
CREATE INDEX IF NOT EXISTS idx_admin_events_timestamp ON admin_events(timestamp);
-- TABLE settings
CREATE TABLE IF NOT EXISTS settings (
key VARCHAR(100) PRIMARY KEY,
value TEXT NOT NULL,
description TEXT,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_by VARCHAR(255)
);
CREATE INDEX IF NOT EXISTS idx_settings_key ON settings(key);
-- Initial settings population if not exists.
-- Corrected syntax: Each INSERT statement must be complete and separated by a semicolon.
INSERT INTO settings (key, value, description, updated_at, updated_by) VALUES
('rate_limit_tokens_per_hour', '10', 'Maximum token requests per hour per email/IP.', NOW(), 'system') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value, description, updated_at, updated_by) VALUES
('email_retention_period', '1095d', 'How long to retain email verification records (e.g., 365d, 1y).', NOW(), 'system') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value, description, updated_at, updated_by) VALUES
('cleanup_interval', '10s', 'Frequency of the cleanup loop (e.g., 10s, 1m).', NOW(), 'system') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value, description, updated_at, updated_by) VALUES
('send_welcome_email', 'true', 'Whether to send an optional welcome email after verification.', NOW(), 'system') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value, description, updated_at, updated_by) VALUES
('firm_server_email', 'firmserver@example.com', 'The email address that FIRM expects verification emails to be sent to.', NOW(), 'system') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value, description, updated_at, updated_by) VALUES
('jwt_secret_key', 'your_super_secret_jwt_key_please_change_this_in_prod', 'Secret key for signing JWTs. MUST BE SECURE AND ROTATED.', NOW(), 'system') ON CONFLICT (key) DO NOTHING;
`
// Global database connection pool
var db *pgxpool.Pool
// Setting holds application configuration settings.
type Setting struct {
Key string `db:"key"`
Value string `db:"value"`
Description string `db:"description"`
UpdatedAt time.Time `db:"updated_at"`
UpdatedBy string `db:"updated_by"`
}
// Global variable for FIRM_SERVER_EMAIL, set from config
var firmServerEmail string
// Global variable for JWT secret key, updated from settings
var jwtSecretKey []byte
// Regex for FIRM token extraction
var firmTokenRegex = regexp.MustCompile(`FIRM-TOKEN:([A-Za-z0-9-]+)`)
// IPNormalization(inboundMessage)
// → Extracts IP (e.g., from c.ClientIP())
// → Returns hex string:
// • 8 chars for IPv4 (e.g., 192.168.1.1 → C0A80101)
// • 32 chars for IPv6 (e.g., ::1 → 00000000000000000000000000000001)
// • NOTE: hex IPs are *not* CIDR aware. Use separately for CIDR matching.
func IPNormalization(ipStr string) (string, error) {
ip := net.ParseIP(ipStr)
if ip == nil {
return "", fmt.Errorf("invalid IP address: %s", ipStr)
}
if ipv4 := ip.To4(); ipv4 != nil {
return fmt.Sprintf("%02X%02X%02X%02X", ipv4[0], ipv4[1], ipv4[2], ipv4[3]), nil
}
// For IPv6, we need to handle the 16 bytes
return fmt.Sprintf("%X", ip.To16()), nil
}
// IsBlockedIP(ipStr string)
// → Calls IPNormalization()
// → Returns true if:
// • IP is in banned_subnets table
// • OR ip_activity.blocked == true
func IsBlockedIP(c *gin.Context) bool {
ipStr := c.ClientIP()
ipHex, err := IPNormalization(ipStr)
if err != nil {
log.Printf("ERROR: Malformed IP %s for blocking check: %v", ipStr, err)
// Log to ip_activity with notes "malformed" and increment inbound_attempts (handled by middleware)
return true // Treat malformed IPs as blocked
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Check if IP is in banned_subnets table
var count int
err = db.QueryRow(ctx, "SELECT COUNT(*) FROM banned_subnets WHERE subnet_hex = $1", ipHex).Scan(&count)
if err == nil && count > 0 {
// Increment hits for the banned subnet (async or in a separate goroutine if performance critical)
go func() {
_, err := db.Exec(context.Background(), "UPDATE banned_subnets SET hits = hits + 1 WHERE subnet_hex = $1", ipHex)
if err != nil {
log.Printf("ERROR: Could not increment banned subnet hits for %s: %v", ipHex, err)
}
}()
log.Printf("IP %s blocked by direct subnet ban.", ipStr)
return true
}
// Check if ip_activity.blocked is true
var blocked bool
err = db.QueryRow(ctx, "SELECT blocked FROM ip_activity WHERE ip_hex = $1", ipHex).Scan(&blocked)
if err == nil && blocked {
log.Printf("IP %s blocked by ip_activity status.", ipStr)
return true
} else if err != nil && err != pgx.ErrNoRows {
log.Printf("ERROR: Database error checking ip_activity for %s: %v", ipStr, err)
return true // Fail safe: block if database is having issues
}
return false
}
// NormalizeCIDR(ipStr string, cidr int) → subnet
// → Converts any IP string and CIDR into the proper network base
// → e.g., "192.168.2.123" + /24 → "C0A80200" (hex of 192.168.2.0)
// → Used for inserts and IP-in-subnet checks
// NOTE: CIDR always wins: store corrected network base even if input IP is not aligned
func NormalizeCIDR(ipStr string, cidr int) (string, error) {
ip := net.ParseIP(ipStr)
if ip == nil {
return "", fmt.Errorf("invalid IP address: %s", ipStr)
}
// Calculate the network address for the given CIDR
var network *net.IPNet
if ip.To4() != nil {
if cidr < 0 || cidr > 32 {
return "", fmt.Errorf("invalid IPv4 CIDR %d", cidr)
}
// Create a mock CIDR string and parse it
_, network, _ = net.ParseCIDR(fmt.Sprintf("%s/%d", ip.To4().String(), cidr))
} else { // Assume IPv6
if cidr < 0 || cidr > 128 {
return "", fmt.Errorf("invalid IPv6 CIDR %d", cidr)
}
// Create a mock CIDR string and parse it
_, network, _ = net.ParseCIDR(fmt.Sprintf("%s/%d", ip.To16().String(), cidr))
}
return IPNormalization(network.IP.String())
}
// TimeOutHandler(db *pgxpool.Pool)
// All expired bans, rows, etc cleared
// Basically this is garbage collection and releasing users from ratelimit jail
// Runs every 'cleanup_interval' seconds and MUST be very efficent
func TimeOutHandler(db *pgxpool.Pool) {
log.Println("Cleanup routine started.")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) // Give cleanup 30s
defer cancel()
now := time.Now().UTC()
// 1. Delete expired or unused FIRM tokens
// FIRM tokens expire within 15-60 minutes. Delete if expired or if "issued" and older than 1 hour.
cmdTag, err := db.Exec(ctx, "DELETE FROM tokens WHERE expires_at < $1 OR (status = 'issued' AND created_at < $2)", now, now.Add(-1*time.Hour))
if err != nil {
log.Printf("ERROR: Cleanup - failed to delete expired/unused tokens: %v", err)
} else {
log.Printf("Cleanup: Deleted %d expired/unused tokens.", cmdTag.RowsAffected())
}
// 2. Delete expired email verifications
retentionPeriodStr := viper.GetString("settings.email_retention_period")
retentionDuration, err := time.ParseDuration(retentionPeriodStr)
if err != nil {
log.Printf("ERROR: Cleanup - invalid email_retention_period '%s', defaulting to 1095d: %v", retentionPeriodStr, err)
retentionDuration = 1095 * 24 * time.Hour // 3 years
}
cmdTag, err = db.Exec(ctx, "DELETE FROM email_verifications WHERE expires_at < $1 OR (verified = FALSE AND last_attempt < $2)", now, now.Add(-retentionDuration))
if err != nil {
log.Printf("ERROR: Cleanup - failed to delete expired email verifications: %v", err)
} else {
log.Printf("Cleanup: Deleted %d expired email verifications.", cmdTag.RowsAffected())
}
// 3. Delete expired IP activity records
cmdTag, err = db.Exec(ctx, "DELETE FROM ip_activity WHERE expires_at < $1", now)
if err != nil {
log.Printf("ERROR: Cleanup - failed to delete expired IP activity: %v", err)
} else {
log.Printf("Cleanup: Deleted %d expired IP activity records.", cmdTag.RowsAffected())
}
// 4. Delete expired banned subnets
cmdTag, err = db.Exec(ctx, "DELETE FROM banned_subnets WHERE expires_at IS NOT NULL AND expires_at < $1", now)
if err != nil {
log.Printf("ERROR: Cleanup - failed to delete expired banned subnets: %v", err)
} else {
log.Printf("Cleanup: Deleted %d expired banned subnets.", cmdTag.RowsAffected())
}
// 5. Delete expired admin emails
cmdTag, err = db.Exec(ctx, "DELETE FROM admin_emails WHERE expires_at IS NOT NULL AND expires_at < $1", now)
if err != nil {
log.Printf("ERROR: Cleanup - failed to delete expired admin emails: %v", err)
} else {
log.Printf("Cleanup: Deleted %d expired admin emails.", cmdTag.RowsAffected())
}
// 6. Release temporary blocks on IP activity (rate limiting jail)
// If an IP was last blocked more than 10 minutes ago, unblock it.
cmdTag, err = db.Exec(ctx, "UPDATE ip_activity SET blocked = FALSE, last_blocked = NULL WHERE blocked = TRUE AND last_blocked < $1", now.Add(-10*time.Minute))
if err != nil {
log.Printf("ERROR: Cleanup - failed to release IP blocks: %v", err)
} else {
log.Printf("Cleanup: Released %d IP blocks.", cmdTag.RowsAffected())
}
// Log cleanup completion to admin_events
_, err = db.Exec(ctx,
"INSERT INTO admin_events (timestamp, action, actor, target, notes) VALUES ($1, $2, $3, $4, $5)",
now, "cleanup_run", "system", "database", "Cleanup routine executed.",
)
if err != nil {
log.Printf("ERROR: Cleanup - failed to log admin event: %v", err)
}
log.Println("Cleanup routine finished.")
}
// initDB initializes the PostgreSQL database connection and creates tables if they don't exist.
func initDB() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pgURL := viper.GetString("database.url")
if pgURL == "" {
log.Fatalf("FATAL: database.url not found in configuration.")
}
var err error
db, err = pgxpool.New(ctx, pgURL)
if err != nil {
log.Fatalf("FATAL: Unable to connect to database: %v", err)
}
err = db.Ping(ctx)
if err != nil {
log.Fatalf("FATAL: Failed to ping database: %v", err)
}
log.Println("✅ Successfully connected to the PostgreSQL database.")
// Execute schema SQL to create tables and insert initial settings
// We use a single batch query for schemaSQL. If there are multiple statements
// within schemaSQL, db.ExecContext is sufficient for pgx as it handles
// multiple statements if they are separated by semicolons correctly.
_, err = db.Exec(ctx, schemaSQL)
if err != nil {
log.Fatalf("FATAL: Failed to initialize database schema: %v", err)
}
log.Println("✅ Database schema initialized successfully.")
// Load initial global settings from the database
firmServerEmail = getSetting("firm_server_email", "firmserver@example.m")
jwtSecretKey = []byte(getSetting("jwt_secret_key", "your_super_secret_jwt_key_please_change_this_in_prod"))
if string(jwtSecretKey) == "your_super_secret_jwt_key_please_change_this_in_prod" {
log.Println("WARNING: Using default JWT secret key. Please change 'jwt_secret_key' in settings table or .env file.")
}
}
// getSetting retrieves a setting value from the database.
// It uses a mutex to ensure thread-safe access if we were caching settings.
// For now, it directly queries the DB.
func getSetting(key, defaultValue string) string {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var value string
err := db.QueryRow(ctx, "SELECT value FROM settings WHERE key = $1", key).Scan(&value)
if err != nil {
if err != pgx.ErrNoRows {
log.Printf("ERROR: Could not fetch setting '%s': %v. Using default.", key, err)
}
return defaultValue
}
return value
}
// updateSettingInDB updates a setting in the database.
func updateSettingInDB(ctx context.Context, key, value, updatedBy string) error {
_, err := db.Exec(ctx,
`INSERT INTO settings (key, value, description, updated_at, updated_by)
VALUES ($1, $2, $3, NOW(), $4)
ON CONFLICT (key) DO UPDATE SET
value = EXCLUDED.value, updated_at = EXCLUDED.updated_at, updated_by = EXCLUDED.updated_by;`,
key, value, fmt.Sprintf("Updated by %s", updatedBy), updatedBy,
)
return err
}
// --- Core Helper Functions ---
// GenerateFIRMToken creates a unique FIRM-TOKEN string.
func GenerateFIRMToken() string {
// A simple UUID-based token for demonstration.
// Format: FIRM-TOKEN:XXXX-YYYY-ZZZZ (UUID v4 produces 32 hex chars, so we take a portion)
id := strings.ReplaceAll(uuid.New().String(), "-", "")
return fmt.Sprintf("FIRM-TOKEN:%s-%s-%s", id[0:4], id[4:8], id[8:12])
}
// ExtractFirstToken(subject, body string)
// Parses email subject/body for a FIRM-TOKEN.
func ExtractFirstToken(subject, body string) string {
// Try subject first
if matches := firmTokenRegex.FindStringSubmatch(subject); len(matches) > 0 { // Check len(matches) > 0 instead of > 1
return matches[0] // Return the full matched string, including prefix
}
// Then try body
if matches := firmTokenRegex.FindStringSubmatch(body); len(matches) > 0 {
return matches[0]
}
return ""
}
// CustomClaims for JWT
type Claims struct {
Email string `json:"sub"`
Scope string `json:"scope"`
jwt.RegisteredClaims
}
// GenerateJWT(email, scope string)
// Creates a signed JWT refresh token.
func GenerateJWT(email, scope string) (string, error) {
now := time.Now().UTC()
expirationTime := now.Add(90 * 24 * time.Hour) // 90 days expiration
jti := uuid.New().String()
claims := &Claims{
Email: email,
Scope: scope,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(expirationTime),
IssuedAt: jwt.NewNumericDate(now),
NotBefore: jwt.NewNumericDate(now),
Issuer: "firm.example.com",
Subject: email,
ID: jti,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtSecretKey)
if err != nil {
return "", fmt.Errorf("failed to sign JWT: %w", err)
}
// Insert jti into tokens table
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = db.Exec(ctx,
"INSERT INTO tokens (token_id, email, created_at, expires_at, status) VALUES ($1, $2, $3, $4, $5)",
jti, email, now, expirationTime, "issued",
)
if err != nil {
return "", fmt.Errorf("failed to store JWT jti in DB: %w", err)
}
return tokenString, nil
}
// ValidateJWT(token string)
// Decodes and validates a JWT, checking its signature, claims, and revocation status.
func ValidateJWT(tokenString string) (*Claims, error) {
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, 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 jwtSecretKey, nil
})
if err != nil {
return nil, fmt.Errorf("invalid JWT: %w", err)
}
if !token.Valid {
return nil, fmt.Errorf("JWT is invalid")
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Check jti in tokens table and status
var status string
var storedEmail string
err = db.QueryRow(ctx, "SELECT status, email FROM tokens WHERE token_id = $1", claims.ID).Scan(&status, &storedEmail)
if err != nil {
if err == pgx.ErrNoRows {
return nil, fmt.Errorf("JWT jti not found in tokens table")
}
return nil, fmt.Errorf("database error checking JWT jti: %w", err)
}
if status == "revoked" {
return nil, fmt.Errorf("JWT jti is revoked")
}
if storedEmail != claims.Email {
return nil, fmt.Errorf("JWT subject mismatch with stored email")
}
return claims, nil
}
// RevokeJWT(jti string)
// Marks a JWT's JTI as revoked in the database.
func RevokeJWT(jti string) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmdTag, err := db.Exec(ctx, "UPDATE tokens SET status = 'revoked', used_at = $1 WHERE token_id = $2", time.Now().UTC(), jti)
if err != nil {
return fmt.Errorf("failed to revoke JWT in DB: %w", err)
}
if cmdTag.RowsAffected() == 0 {
return fmt.Errorf("no JWT found with jti: %s", jti)
}
// Log to admin_events
_, err = db.Exec(ctx,
"INSERT INTO admin_events (timestamp, action, actor, target, notes) VALUES ($1, $2, $3, $4, $5)",
time.Now().UTC(), "revoke_jwt", "system", jti, "JWT revoked by server",
)
if err != nil {
log.Printf("ERROR: Failed to log revoke_jwt event: %v", err)
}
return nil
}
// Mock external services
func verifySPF(email, ip string) bool {
log.Printf("MOCK: Performing SPF check for %s from %s - Result: PASS", email, ip)
return true
}
func verifyDKIM(headers map[string]string) bool {
log.Printf("MOCK: Performing DKIM check for headers - Result: PASS")
return true
}
func sendWelcomeEmail(email string) {
log.Printf("MOCK: Sending welcome email to %s", email)
// Placeholder for actual email sending logic (e.g., SMTP, Mailgun API)
}
func sendWebSocketEvent(eventType, email, jwtToken string, timestamp time.Time) {
log.Printf("MOCK: Sending WebSocket event: %s for %s with JWT (first 10 chars): %s... at %s", eventType, email, jwtToken[:10], timestamp.Format(time.RFC3339))
// Placeholder for actual WebSocket/SSE communication
}
// --- Middleware ---
// ipActivityMiddleware logs and updates IP activity for each request.
// It also tracks potential blocks but does NOT enforce them; enforcement is left to routes.
func ipActivityMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
ipStr := c.ClientIP()
ipHex, err := IPNormalization(ipStr)
if err != nil {
log.Printf("ERROR: Malformed IP in middleware: %s. Notes: malformed", ipStr)
// For malformed IPs, we'll still log to ip_activity, but won't associate with specific token/inbound attempts initially
// The draft implies malformed IPs should increment ip_activity.inbound_attempts
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := db.Exec(ctx,
`INSERT INTO ip_activity (ip_hex, first_seen, last_seen, inbound_attempts, notes)
VALUES ($1, $2, $3, 1, 'malformed')
ON CONFLICT (ip_hex) DO UPDATE SET
last_seen = EXCLUDED.last_seen,
inbound_attempts = ip_activity.inbound_attempts + 1,
notes = 'malformed';`,
ipHex, time.Now().UTC(), time.Now().UTC(),
)
if err != nil {
log.Printf("ERROR: Failed to update ip_activity for malformed IP %s: %v", ipStr, err)
}
}()
c.Next()
return
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var tokenRequests, inboundAttempts int
var firstSeen time.Time
var blocked bool
var lastSeen time.Time
// Query existing record
err = db.QueryRow(ctx, "SELECT token_requests, inbound_attempts, first_seen, blocked, last_seen FROM ip_activity WHERE ip_hex = $1", ipHex).Scan(
&tokenRequests, &inboundAttempts, &firstSeen, &blocked, &lastSeen,
)
if err != nil && err != pgx.ErrNoRows {
log.Printf("ERROR: Database error in ipActivityMiddleware for %s: %v", ipStr, err)
c.Next() // Allow request to proceed, but don't track activity
return
}
now := time.Now().UTC()
if err == pgx.ErrNoRows {
// New IP, insert
_, err = db.Exec(ctx,
`INSERT INTO ip_activity (ip_hex, first_seen, last_seen, token_requests, inbound_attempts, blocked, expires_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
ipHex, now, now, 0, 0, false, now.Add(24*time.Hour), // Expire in 1 day for initial entry
)
if err != nil {
log.Printf("ERROR: Failed to insert new IP activity for %s: %v", ipStr, err)
}
} else {
// Existing IP, update
// Note: token_requests and inbound_attempts are incremented by specific routes.
// This middleware just updates last_seen and potentially 'blocked' status
_, err = db.Exec(ctx,
`UPDATE ip_activity SET last_seen = $1 WHERE ip_hex = $2`,
now, ipHex,
)
if err != nil {
log.Printf("ERROR: Failed to update existing IP activity for %s: %v", ipStr, err)
}
}
c.Next()
}
}
// autoIPBanMiddleware checks and updates IP ban status based on recent activity.
// It also unbans IPs after 10 minutes of "forgiveness".
func autoIPBanMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
ipStr := c.ClientIP()
ipHex, err := IPNormalization(ipStr)
if err != nil {
c.Next() // Malformed IPs handled by IPActivityMiddleware's logging and IPNormalization's block on check
return
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var tokenRequests, blockedCount int
var lastBlocked *time.Time // Use pointer for nullable timestamp
var blocked bool
// Retrieve current IP activity data
err = db.QueryRow(ctx, "SELECT token_requests, blocked, blocked_count, last_blocked FROM ip_activity WHERE ip_hex = $1", ipHex).Scan(
&tokenRequests, &blocked, &blockedCount, &lastBlocked,
)
if err != nil {
if err == pgx.ErrNoRows {
// IP not in ip_activity, it will be handled by IPActivityMiddleware for future requests.
// No rate limit check on first seen.
} else {
log.Printf("ERROR: Database error in autoIPBanMiddleware for %s: %v", ipStr, err)
}
c.Next()
return
}
now := time.Now().UTC()
// Unban if last_blocked was more than 10 minutes ago
if blocked && lastBlocked != nil && now.Sub(*lastBlocked) > 10*time.Minute {
log.Printf("Unbanning IP %s (hex: %s) due to forgiveness period.", ipStr, ipHex)
_, err := db.Exec(ctx, "UPDATE ip_activity SET blocked = FALSE, last_blocked = NULL WHERE ip_hex = $1", ipHex)
if err != nil {
log.Printf("ERROR: Failed to unban IP %s: %v", ipStr, err)
}
blocked = false // Update local state
}
// Check if token_requests in last 10 minutes >= threshold
// NOTE: This check needs improvement. 'token_requests' is a cumulative counter.
// A more robust rate limiting would involve tracking requests per time window (e.g., using Redis or a dedicated rate-limiting table).
// For now, we'll apply a simple check based on a high cumulative count.
// The draft suggests rate_limit_attempts_per_hour. We'll simulate a strict temporary ban.
rateLimitAttemptsPerHour, _ := strconv.Atoi(getSetting("rate_limit_attempts_per_hour", "10"))
// We'll use the cleanup routine to reset the 'blocked' status, making this a temporary ban.
// If the current token_requests count exceeds double the per-hour limit, block.
// This is a crude approximation until per-hour tracking is added to ip_activity or a separate mechanism.
// The `TimeOutHandler` (Cleanup) will handle unblocking if `last_blocked` is old enough.
// TEMPORARY LOGIC: If total token_requests exceeds double the per-hour limit, block.
// This is a crude approximation until per-hour tracking is added to ip_activity or a separate mechanism.
if tokenRequests > 2*rateLimitAttemptsPerHour && !blocked {
log.Printf("Automatically blocking IP %s (hex: %s) due to excessive token requests (%d).", ipStr, ipHex, tokenRequests)
_, err := db.Exec(ctx,
`UPDATE ip_activity SET blocked = TRUE, blocked_count = blocked_count + 1, last_blocked = $1 WHERE ip_hex = $2`,
now, ipHex,
)
if err != nil {
log.Printf("ERROR: Failed to automatically block IP %s: %v", ipStr, err)
}
// Insert a /32 or /128 ban into banned_subnets for this specific IP.
go func() {
var cidr int
if ip := net.ParseIP(ipStr); ip.To4() != nil {
cidr = 32
} else {
cidr = 128
}
subnetHex, err := NormalizeCIDR(ipStr, cidr)
if err != nil {
log.Printf("ERROR: Could not normalize CIDR for auto-ban: %v", err)
return
}
_, err = db.Exec(context.Background(),
`INSERT INTO banned_subnets (subnet_hex, cidr, reason, banned_at, expires_at)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (subnet_hex, cidr) DO UPDATE SET
reason = EXCLUDED.reason, banned_at = EXCLUDED.banned_at, expires_at = EXCLUDED.expires_at, hits = banned_subnets.hits + 1;`,
subnetHex, cidr, "Auto-rate-limit exceeded", now, now.Add(10*time.Minute), // Ban for 10 minutes initially
)
if err != nil {
log.Printf("ERROR: Failed to insert auto-ban into banned_subnets for %s/%d: %v", subnetHex, cidr, err)
}
}()
}
c.Next()
}
}
func main() {
// Dummy use of imported packages to prevent "imported and not used" errors
// These are here to satisfy the Go compiler's strictness about unused imports
// which can happen with indirect usage (e.g., Gin's template engine or type definitions).
_ = template.HTMLEscapeString // Use a function from html/template
_ = pgconn.CommandTag{} // Use a type from pgconn
// ✅ Load environment variables from .env or system and log success
if err := godotenv.Load(); err != nil {
log.Println("No .env file found, relying on system environment variables.")
} else {
log.Println("✅ .env file loaded successfully.")
}
// ✅ Read viper firm.conf file and log success
viper.SetConfigName("firm") // name of config file (without extension)
viper.SetConfigType("toml") // REQUIRED if the config file does not have the extension in the name
viper.AddConfigPath(".") // optionally look for config in the working directory
viper.AddConfigPath("/etc/firm/") // path to look for the config file in
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Fatalf("FATAL: Config file firm.toml not found. Please create one.")
} else {
log.Fatalf("FATAL: Error reading config file: %v", err)
}
}
log.Println("✅ Configuration file firm.toml loaded successfully.")
// Log all configuration values for debugging
log.Println("--- Configuration Settings ---")
for _, key := range viper.AllKeys() {
log.Printf(" %s: %v", key, viper.Get(key))
}
log.Println("----------------------------")
// ✅ Initialize the PostgreSQL database and all tables and log success
initDB()
defer db.Close() // Ensure database connection is closed when main exits
// Start the cleanup routine in a separate goroutine
cleanupIntervalStr := viper.GetString("settings.cleanup_interval")
cleanupInterval, err := time.ParseDuration(cleanupIntervalStr)
if err != nil {
log.Printf("ERROR: Invalid cleanup_interval '%s', defaulting to 10s: %v", cleanupIntervalStr, err)
cleanupInterval = 10 * time.Second
}
log.Printf("Starting cleanup routine every %v...", cleanupInterval)
go func() {
ticker := time.NewTicker(cleanupInterval)
defer ticker.Stop()
for range ticker.C {
TimeOutHandler(db)
}
}()
// ✅ Initialize the Gin router and attach middleware and log success
r := gin.Default()
log.Println("✅ Gin router initialized.")
// Configure template loading
// Load all templates including the layout
// IMPORTANT: When you have a base layout and content templates, Gin's LoadHTMLGlob
// will parse all files. Then, when calling c.HTML, you specify the name of the base layout template
// (e.g., "base.html") and the data will include ContentTemplate to tell base.html what content to render.
r.LoadHTMLGlob("templates/**/*.html")
// Configure static file serving
r.Static("/static", "./static")
// Favicon.ico specific handler
r.StaticFile("/favicon.ico", "./static/favicon.ico")
// ✅ Middleware: IP Logging and auto IP Ban (or unban)
// These run for every incoming request
r.Use(ipActivityMiddleware())
r.Use(autoIPBanMiddleware())
log.Println("✅ IP Logging and Auto IP Ban middleware attached.")
// Define API routes
// A sync.Mutex to protect temp_firm_tokens for /test routes
var tempTokensMutex sync.Mutex
tempFirmTokens := make(map[string]struct {
Email string
CreatedAt time.Time
ExpiresAt time.Time
})
// Non-admin API routes (no middleware needed here as they are public or handled internally)
r.POST("/test", func(c *gin.Context) {
var req struct {
Email string `json:"email" binding:"required,email"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if IsBlockedIP(c) {
c.JSON(403, gin.H{"error": "IP blocked"})
return
}
token := GenerateFIRMToken()
// Store in-memory for /test/inbound to consume
tempTokensMutex.Lock()
tempFirmTokens[token] = struct {
Email string
CreatedAt time.Time
ExpiresAt time.Time
}{
Email: req.Email,
CreatedAt: time.Now().UTC(),
ExpiresAt: time.Now().UTC().Add(1 * time.Hour), // 1 hour for test tokens
}
tempTokensMutex.Unlock()
c.JSON(200, gin.H{
"message": fmt.Sprintf("Send an email from %s to %s with token %s in the subject or body.", req.Email, firmServerEmail, token),
"token": token,
})
})
// /test/inbound route (POST) - For simulating inbound verification
r.POST("/test/inbound", func(c *gin.Context) {
var req struct {
Email string `json:"email" binding:"required,email"`
Subject string `json:"subject"`
Body string `json:"body"`
Headers map[string]string `json:"headers"` // Mock headers
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if IsBlockedIP(c) {
c.JSON(403, gin.H{"error": "IP blocked"})
return
}
// Mock SPF/DKIM checks for testing
if !verifySPF(req.Email, c.ClientIP()) {
c.JSON(403, gin.H{"error": "SPF check failed. See https://firm.example.com/blog/spf-dkim"})
return
}
if !verifyDKIM(req.Headers) {
c.JSON(403, gin.H{"error": "DKIM check failed. See https://firm.example.com/blog/spf-dkim"})
return
}
mailFromDomain := strings.ToLower(strings.Split(req.Email, "@")[1])
fromHeader, ok := req.Headers["From"] // Get "From" header from the map
if !ok || fromHeader == "" {
c.JSON(403, gin.H{"error": "Missing 'From' header for domain matching"})
return
}
fromHeaderParts := strings.Split(fromHeader, "@")
if len(fromHeaderParts) < 2 {
c.JSON(403, gin.H{"error": "Malformed 'From' header for domain matching"})
return
}
fromHeaderDomain := strings.ToLower(fromHeaderParts[1])
if mailFromDomain != fromHeaderDomain {
c.JSON(403, gin.H{"error": "MAIL FROM and From header domains mismatch"})
return
}
// CORRECTED: Extract token from req.Subject or req.Body
reqToken := ExtractFirstToken(req.Subject, req.Body)
if reqToken == "" || !strings.HasPrefix(reqToken, "FIRM-TOKEN:") {
c.JSON(400, gin.H{"error": "Invalid or missing token"})
return
}
tempTokensMutex.Lock()
defer tempTokensMutex.Unlock()
// CORRECTED: Use reqToken to access tempFirmTokens map
storedToken, exists := tempFirmTokens[reqToken]
if !exists || storedToken.Email != req.Email {
c.JSON(403, gin.H{"error": "Invalid or expired token"})
return
}
if storedToken.ExpiresAt.Before(time.Now().UTC()) {
delete(tempFirmTokens, reqToken) // CORRECTED: Delete using reqToken
c.JSON(400, gin.H{"error": "Token expired"})
return
}
delete(tempFirmTokens, reqToken) // CORRECTED: Delete using reqToken
c.JSON(200, gin.H{"message": "Test token verified"})
})
// ✅ /signup route (POST: {email})
r.POST("/signup", func(c *gin.Context) {
var req struct {
Email string `json:"email" binding:"required,email"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()
if IsBlockedIP(c) {
c.JSON(403, gin.H{"error": "IP blocked"})
return
}
var emailVerification struct {
TokenCount int `db:"token_count"`
LastAttempt *time.Time `db:"last_attempt"`
LastBlocked *time.Time `db:"last_blocked"`
}
// Retrieve current email verification data
err := db.QueryRow(ctx, "SELECT token_count, last_attempt, last_blocked FROM email_verifications WHERE email = $1", req.Email).Scan(
&emailVerification.TokenCount, &emailVerification.LastAttempt, &emailVerification.LastBlocked,
)
if err != nil && err != pgx.ErrNoRows {
log.Printf("ERROR: Database error retrieving email verification for %s: %v", req.Email, err)
c.JSON(500, gin.H{"error": "Internal server error"})
return
}
now := time.Now().UTC()
// If it has been 10 minutes since the last attempt, clear attempt counter (forgiveness)
if emailVerification.LastAttempt != nil && now.Sub(*emailVerification.LastAttempt) > 10*time.Minute {
log.Printf("Email %s: Clearing token_count due to 10-minute forgiveness.", req.Email)
emailVerification.TokenCount = 0 // Reset for the current check
_, err = db.Exec(ctx, "UPDATE email_verifications SET token_count = 0 WHERE email = $1", req.Email)
if err != nil {
log.Printf("ERROR: Failed to reset token_count for %s: %v", req.Email, err)
// Don't block, just log and continue
}
}
rateLimitPerHour, _ := strconv.Atoi(getSetting("rate_limit_tokens_per_hour", "10"))
if emailVerification.TokenCount >= rateLimitPerHour {
log.Printf("Email %s: Rate limit exceeded (%d attempts).", req.Email, emailVerification.TokenCount)
_, err = db.Exec(ctx,
`UPDATE email_verifications SET last_blocked = $1, blocked_count = blocked_count + 1 WHERE email = $2`,
now, req.Email,
)
if err != nil {
log.Printf("ERROR: Failed to update last_blocked for %s: %v", req.Email, err)
}
c.JSON(429, gin.H{"error": "Email rate limit exceeded"})
return
}