-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
2651 lines (2224 loc) · 73.1 KB
/
main.go
File metadata and controls
2651 lines (2224 loc) · 73.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 main
import (
"bytes"
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"log"
"log/slog"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/dusted-go/logging/prettylog"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/tionis/patchwork/internal/huproxy"
"golang.org/x/time/rate"
"github.com/tionis/patchwork/internal/metrics"
"github.com/tionis/patchwork/internal/notification"
"github.com/tionis/patchwork/internal/types"
sshUtil "github.com/tionis/ssh-tools/util"
"github.com/urfave/cli/v2"
"gopkg.in/yaml.v3"
)
//go:embed assets/*
var assets embed.FS
// =============================================================================
// TYPE DEFINITIONS
// =============================================================================
// patchChannel represents a communication channel between producers and consumers.
type patchChannel struct {
data chan stream
unpersist chan bool
}
// stream represents a data stream with metadata.
type stream struct {
reader io.ReadCloser
done chan struct{}
headers map[string]string
}
// server contains the main server state and configuration.
type server struct {
logger *slog.Logger
channels map[string]*patchChannel
channelsMutex sync.RWMutex
ctx context.Context
forgejoURL string
forgejoToken string
aclTTL time.Duration
secretKey []byte
authCache *AuthCache
metrics *metrics.Metrics
// Rate limiting for public namespaces
publicRateLimiters map[string]*rate.Limiter
rateLimiterMutex sync.RWMutex
}
// =============================================================================
// SERVER INTERFACE IMPLEMENTATIONS
// =============================================================================
// AuthenticateToken implements the ServerInterface for huproxy.
func (s *server) AuthenticateToken(
username string,
token, path, reqType string,
isHuProxy bool,
clientIP net.IP,
) (bool, string, error) {
return s.authenticateToken(username, token, path, reqType, isHuProxy, clientIP)
}
// GetLogger implements the ServerInterface for huproxy.
func (s *server) GetLogger() interface {
Info(msg string, args ...interface{})
Error(msg string, args ...interface{})
} {
return s.logger
}
// Configuration template data for rendering index.html.
type ConfigData struct {
ForgejoURL string
ACLTTL time.Duration
BaseURL string
WebSocketURL string
}
// TokenInfo represents information about a token from config.yaml.
type TokenInfo struct {
IsAdmin bool `yaml:"is_admin"`
HuProxy []*sshUtil.Pattern `yaml:"huproxy,omitempty"`
GET []*sshUtil.Pattern `yaml:"GET,omitempty"`
POST []*sshUtil.Pattern `yaml:"POST,omitempty"`
PUT []*sshUtil.Pattern `yaml:"PUT,omitempty"`
DELETE []*sshUtil.Pattern `yaml:"DELETE,omitempty"`
PATCH []*sshUtil.Pattern `yaml:"PATCH,omitempty"`
ExpiresAt *time.Time `yaml:"expires_at,omitempty"`
}
// MarshalYAML implements custom YAML marshaling for TokenInfo.
func (t TokenInfo) MarshalYAML() (interface{}, error) {
// Create a temporary struct with string slices for patterns
type TokenInfoYAML struct {
IsAdmin bool `yaml:"is_admin"`
HuProxy []string `yaml:"huproxy,omitempty"`
GET []string `yaml:"GET,omitempty"`
POST []string `yaml:"POST,omitempty"`
PUT []string `yaml:"PUT,omitempty"`
DELETE []string `yaml:"DELETE,omitempty"`
PATCH []string `yaml:"PATCH,omitempty"`
ExpiresAt *time.Time `yaml:"expires_at,omitempty"`
}
// Convert sshUtil.Pattern slices to string slices
result := TokenInfoYAML{
IsAdmin: t.IsAdmin,
ExpiresAt: t.ExpiresAt,
}
for _, pattern := range t.HuProxy {
result.HuProxy = append(result.HuProxy, pattern.String())
}
for _, pattern := range t.GET {
result.GET = append(result.GET, pattern.String())
}
for _, pattern := range t.POST {
result.POST = append(result.POST, pattern.String())
}
for _, pattern := range t.PUT {
result.PUT = append(result.PUT, pattern.String())
}
for _, pattern := range t.DELETE {
result.DELETE = append(result.DELETE, pattern.String())
}
for _, pattern := range t.PATCH {
result.PATCH = append(result.PATCH, pattern.String())
}
return result, nil
}
// UnmarshalYAML implements custom YAML unmarshaling for TokenInfo.
func (t *TokenInfo) UnmarshalYAML(node *yaml.Node) error {
// Create a temporary struct with string slices for patterns
type TokenInfoYAML struct {
IsAdmin bool `yaml:"is_admin"`
HuProxy []string `yaml:"huproxy,omitempty"`
GET []string `yaml:"GET,omitempty"`
POST []string `yaml:"POST,omitempty"`
PUT []string `yaml:"PUT,omitempty"`
DELETE []string `yaml:"DELETE,omitempty"`
PATCH []string `yaml:"PATCH,omitempty"`
ExpiresAt *time.Time `yaml:"expires_at,omitempty"`
}
var temp TokenInfoYAML
err := node.Decode(&temp)
if err != nil {
return err
}
// Convert string slices to sshUtil.Pattern slices
t.IsAdmin = temp.IsAdmin
t.ExpiresAt = temp.ExpiresAt
// Convert strings to patterns using sshUtil.NewPattern
for _, str := range temp.HuProxy {
pattern, err := sshUtil.NewPattern(str)
if err != nil {
return fmt.Errorf("invalid huproxy pattern %q: %w", str, err)
}
t.HuProxy = append(t.HuProxy, pattern)
}
for _, str := range temp.GET {
pattern, err := sshUtil.NewPattern(str)
if err != nil {
return fmt.Errorf("invalid GET pattern %q: %w", str, err)
}
t.GET = append(t.GET, pattern)
}
for _, str := range temp.POST {
pattern, err := sshUtil.NewPattern(str)
if err != nil {
return fmt.Errorf("invalid POST pattern %q: %w", str, err)
}
t.POST = append(t.POST, pattern)
}
for _, str := range temp.PUT {
pattern, err := sshUtil.NewPattern(str)
if err != nil {
return fmt.Errorf("invalid PUT pattern %q: %w", str, err)
}
t.PUT = append(t.PUT, pattern)
}
for _, str := range temp.DELETE {
pattern, err := sshUtil.NewPattern(str)
if err != nil {
return fmt.Errorf("invalid DELETE pattern %q: %w", str, err)
}
t.DELETE = append(t.DELETE, pattern)
}
for _, str := range temp.PATCH {
pattern, err := sshUtil.NewPattern(str)
if err != nil {
return fmt.Errorf("invalid PATCH pattern %q: %w", str, err)
}
t.PATCH = append(t.PATCH, pattern)
}
return nil
}
// UserAuth represents the config.yaml configuration for a user.
type UserAuth struct {
Tokens map[string]TokenInfo `yaml:"tokens"`
UpdatedAt time.Time `yaml:"-"`
}
// AuthCache represents cached auth data with expiration.
type AuthCache struct {
data map[string]*UserAuth
mutex sync.RWMutex
ttl time.Duration
forgejoURL string
forgejoToken string
logger *slog.Logger
}
// =============================================================================
// UTILITY FUNCTIONS
// =============================================================================
// getClientIP extracts the real client IP from reverse proxy headers.
func getClientIP(r *http.Request) string {
// Check X-Forwarded-For header first (most common)
xff := r.Header.Get("X-Forwarded-For")
if xff != "" {
// X-Forwarded-For can contain multiple IPs, take the first one
if idx := strings.Index(xff, ","); idx != -1 {
return strings.TrimSpace(xff[:idx])
}
return strings.TrimSpace(xff)
}
// Check X-Real-IP header (nginx)
xri := r.Header.Get("X-Real-IP")
if xri != "" {
return strings.TrimSpace(xri)
}
// Check CF-Connecting-IP header (Cloudflare)
cfip := r.Header.Get("CF-Connecting-IP")
if cfip != "" {
return strings.TrimSpace(cfip)
}
// Fall back to RemoteAddr
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return ip
}
// logRequest logs HTTP request details at info level.
func (s *server) logRequest(r *http.Request, message string) {
clientIP := getClientIP(r)
s.logger.Info(message,
"method", r.Method,
"path", r.URL.Path,
"query", r.URL.RawQuery,
"client_ip", clientIP,
"user_agent", r.Header.Get("User-Agent"),
"referer", r.Header.Get("Referer"),
)
}
// statusHandler handles health check requests.
func (s *server) statusHandler(w http.ResponseWriter, r *http.Request) {
s.logRequest(r, "Status check request")
w.WriteHeader(http.StatusOK)
if _, err := io.WriteString(w, "OK!\n"); err != nil {
s.logger.Error("Failed to write status response", "error", err)
}
}
// authenticateToken provides authentication for tokens using ACL cache.
func (s *server) authenticateToken(
username string,
token, path, reqType string,
isHuProxy bool,
clientIP net.IP,
) (bool, string, error) {
if username == "" {
// Public namespace, no authentication required
return true, "public", nil
}
if token == "" {
// Missing token in user namespace should be treated as "public" token
token = "public"
}
// For HuProxy, pass the path as the operation to check against patterns
// For regular HTTP requests, pass the path for pattern matching
operation := path
if !isHuProxy {
// For regular HTTP requests, we need both the method and path
// The method determines which patterns to check, the path is what gets matched
// So we pass the HTTP method as the operation type and path for pattern matching
operation = path
}
// Use auth cache to validate token
valid, reason, tokenInfo, err := s.authCache.validateToken(
username,
token,
reqType,
operation,
isHuProxy,
)
if err != nil {
s.logger.Error(
"Token validation error",
"username",
username,
"error",
err,
"is_huproxy",
isHuProxy,
)
s.metrics.RecordAuthRequest("error")
return false, fmt.Sprintf("token validation error: %v", err), nil
}
if !valid {
s.metrics.RecordAuthRequest("denied")
return false, reason, nil
}
s.metrics.RecordAuthRequest("success")
s.logger.Info("Token authenticated",
"username", username,
"path", path,
"operation", operation,
"is_admin", tokenInfo.IsAdmin,
"is_huproxy", isHuProxy,
"client_ip", clientIP.String())
return true, "authenticated", nil
}
// metricsHandler creates a public metrics endpoint (no authentication required).
// Serving metrics is often useful to allow external monitoring systems to scrape
// this endpoint without requiring credentials. If you want to restrict access
// again later, add appropriate auth checks here.
func (s *server) metricsHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
promhttp.HandlerFor(s.metrics.GetRegistry(), promhttp.HandlerOpts{}).ServeHTTP(w, r)
})
}
// generateUUID generates a simple UUID-like string using crypto/rand.
func generateUUID() (string, error) {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
return "", err
}
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
}
// computeSecret generates an HMAC-SHA256 secret for a given channel.
// This provides cryptographic authentication for channels, ensuring that
// only clients with the correct secret can access the channel.
func (s *server) computeSecret(namespace, channel string) string {
h := hmac.New(sha256.New, s.secretKey)
_, _ = fmt.Fprintf(h, "%s:%s", namespace, channel) // hash.Hash.Write never returns an error
return hex.EncodeToString(h.Sum(nil))
}
// verifySecret verifies if the provided secret matches the expected secret for a channel.
// This function provides constant-time comparison to prevent timing attacks.
func (s *server) verifySecret(namespace, channel, providedSecret string) bool {
expectedSecret := s.computeSecret(namespace, channel)
return hmac.Equal([]byte(expectedSecret), []byte(providedSecret))
}
// NewAuthCache creates a new auth cache instance.
// The cache automatically fetches and caches user authentication configurations
// from Forgejo repositories, reducing API calls and improving performance.
func NewAuthCache(
forgejoURL, forgejoToken string,
ttl time.Duration,
logger *slog.Logger,
) *AuthCache {
return &AuthCache{
data: make(map[string]*UserAuth),
mutex: sync.RWMutex{},
ttl: ttl,
forgejoURL: forgejoURL,
forgejoToken: forgejoToken,
logger: logger,
}
}
// fetchUserAuth fetches config.yaml data from Forgejo for a specific user.
// This function directly contacts the Forgejo API to retrieve the latest
// authentication configuration without using cache.
func (cache *AuthCache) fetchUserAuth(username string) (*UserAuth, error) {
// Construct the API URL for the config.yaml file
apiURL := fmt.Sprintf(
"%s/api/v1/repos/%s/.patchwork/media/config.yaml",
cache.forgejoURL,
url.QueryEscape(username),
)
cache.logger.Debug("Fetching auth from Forgejo", "username", username, "url", apiURL)
req, err := http.NewRequest(http.MethodGet, apiURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Accept", "application/octet-stream")
req.Header.Set("Authorization", "token "+cache.forgejoToken)
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch auth: %w", err)
}
defer func() {
closeErr := resp.Body.Close()
if closeErr != nil {
cache.logger.Error("Failed to close response body", "error", closeErr)
}
}()
if resp.StatusCode == http.StatusNotFound {
// Return empty auth if file doesn't exist
cache.logger.Info("Auth file not found, returning empty auth", "username", username)
return &UserAuth{
Tokens: make(map[string]TokenInfo),
UpdatedAt: time.Now(),
}, nil
}
if resp.StatusCode != http.StatusOK {
cache.logger.Error("Unexpected status code from Forgejo",
"username", username,
"status_code", resp.StatusCode,
"url", apiURL)
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
cache.logger.Error("Failed to read response body", "username", username, "error", err)
return nil, fmt.Errorf("failed to read response body: %w", err)
}
var auth UserAuth
if err := yaml.Unmarshal(body, &auth); err != nil {
cache.logger.Error("Failed to parse YAML", "username", username, "error", err)
return nil, fmt.Errorf("failed to parse YAML: %w", err)
}
auth.UpdatedAt = time.Now()
cache.logger.Info("Fetched auth from Forgejo", "username", username, "tokens", len(auth.Tokens))
return &auth, nil
}
// GetUserAuth retrieves auth data for a user, using cache if available and not expired.
func (cache *AuthCache) GetUserAuth(username string) (*UserAuth, error) {
cache.logger.Debug("Getting user auth from cache", "username", username)
cache.mutex.RLock()
auth, exists := cache.data[username]
cache.mutex.RUnlock()
// Check if cached data is still valid
if exists && time.Since(auth.UpdatedAt) < cache.ttl {
cache.logger.Debug("Using cached auth data", "username", username)
cache.logger.Debug("Returning auth data", "username", username, "auth", auth)
return auth, nil
}
// Fetch fresh data
cache.logger.Debug("Fetching fresh auth data", "username", username)
freshAuth, err := cache.fetchUserAuth(username)
if err != nil {
cache.logger.Error("Failed to fetch auth", "username", username, "error", err)
// Return cached data if available, even if expired
if exists {
cache.logger.Warn("Using expired auth data", "username", username)
cache.logger.Debug("Returning auth data", "username", username, "auth", auth)
return auth, nil
}
return nil, err
}
// Update cache
cache.mutex.Lock()
cache.data[username] = freshAuth
cache.mutex.Unlock()
cache.logger.Debug("Updated auth cache", "username", username)
cache.logger.Debug("Returning auth data", "username", username, "auth", freshAuth)
return freshAuth, nil
}
// InvalidateUser removes a user's auth data from the cache.
func (cache *AuthCache) InvalidateUser(username string) {
cache.mutex.Lock()
delete(cache.data, username)
cache.mutex.Unlock()
cache.logger.Info("Invalidated auth cache", "username", username)
}
// validateToken checks if a token is valid for a user and operation.
func (cache *AuthCache) validateToken(
username, token, method, path string,
isHuProxy bool,
) (bool, string, *TokenInfo, error) {
auth, err := cache.GetUserAuth(username)
if err != nil {
cache.logger.Debug("Failed to get user auth", "username", username, "error", err)
return false, "user not found", nil, nil
}
tokenInfo, exists := auth.Tokens[token]
if !exists {
return false, "token not found", nil, nil
}
// Check if token is expired
if tokenInfo.ExpiresAt != nil && time.Now().After(*tokenInfo.ExpiresAt) {
return false, "token expired", nil, nil
}
// For HuProxy requests, check if token has huproxy permissions
if isHuProxy {
if len(tokenInfo.HuProxy) == 0 {
return false, "huproxy token has no permissions", nil, nil
}
if sshUtil.MatchPatternList(tokenInfo.HuProxy, path) {
return true, "", &tokenInfo, nil
} else {
return false, "huproxy token does not match patterns", nil, nil
}
}
// For regular HTTP requests, check method-specific permissions
var patterns []*sshUtil.Pattern
switch strings.ToUpper(method) {
case "GET":
patterns = tokenInfo.GET
case "POST":
patterns = tokenInfo.POST
case "PUT":
patterns = tokenInfo.PUT
case "DELETE":
patterns = tokenInfo.DELETE
case "PATCH":
patterns = tokenInfo.PATCH
case "ADMIN":
// Admin operations require is_admin flag
return tokenInfo.IsAdmin, "", &tokenInfo, nil
default:
return false, "unsupported method", nil, nil
}
if len(patterns) == 0 {
return false, "no patterns found", nil, nil
}
if sshUtil.MatchPatternList(patterns, path) {
return true, "", &tokenInfo, nil
} else {
return false, "token does not match patterns", nil, nil
}
}
// HookResponse represents the response structure for hook endpoint requests.
type HookResponse struct {
Channel string `json:"channel"`
Secret string `json:"secret"`
}
// =============================================================================
// HTTP HANDLERS
// =============================================================================
// Placeholder handlers for various namespace endpoints.
func (s *server) publicHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
path := vars["path"]
s.logRequest(r, "Public namespace access")
// Determine namespace based on request path
namespace := "p" // default for backward compatibility
if strings.HasPrefix(r.URL.Path, "/public/") {
namespace = "public"
}
s.handlePatch(w, r, namespace, "", path)
}
func (s *server) userHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
username := vars["username"]
path := vars["path"]
s.logRequest(r, "User namespace access")
s.logger.Info("User namespace details", "username", username, "path", path)
s.handlePatch(w, r, "u/"+username, username, path)
}
func (s *server) userAdminHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
username := vars["username"]
adminPath := vars["adminPath"]
s.logRequest(r, "User administrative namespace access")
s.logger.Info("User admin namespace details", "username", username, "admin_path", adminPath)
// Get Authorization header
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
s.logger.Info(
"Admin access denied - no authorization header",
"username",
username,
"admin_path",
adminPath,
)
http.Error(w, "Authorization required", http.StatusUnauthorized)
return
}
// Extract token from Authorization header (expecting "Bearer <token>" or "token <token>")
var token string
if strings.HasPrefix(authHeader, "Bearer ") {
token = strings.TrimPrefix(authHeader, "Bearer ")
} else if strings.HasPrefix(authHeader, "token ") {
token = strings.TrimPrefix(authHeader, "token ")
} else {
token = authHeader // Direct token
}
// Validate token and check admin status
valid, reason, tokenInfo, err := s.authCache.validateToken(
username,
token,
"ADMIN",
adminPath,
false,
)
if err != nil {
s.logger.Error("Admin token validation error", "username", username, "error", err)
http.Error(w, "Token validation error", http.StatusInternalServerError)
return
}
if !valid || !tokenInfo.IsAdmin {
s.logger.Info(
"Admin access denied - invalid or non-admin token",
"username",
username,
"admin_path",
adminPath,
"reason",
reason,
)
http.Error(w, "Admin access denied: "+reason, http.StatusForbidden)
return
}
// Handle administrative endpoints
switch adminPath {
case "invalidate_cache":
s.authCache.InvalidateUser(username)
s.logger.Info(
"Cache invalidated via admin endpoint",
"username",
username,
"client_ip",
getClientIP(r),
)
w.WriteHeader(http.StatusOK)
if _, err := w.Write([]byte(`{"status": "cache invalidated"}`)); err != nil {
s.logger.Error("Failed to write response", "error", err)
}
default:
s.logger.Info("Unknown admin endpoint", "username", username, "admin_path", adminPath)
http.Error(w, "Unknown administrative endpoint", http.StatusNotFound)
}
}
func (s *server) userNtfyHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
username := vars["username"]
s.logRequest(r, "User notification request")
s.logger.Info("User notification details", "username", username, "method", r.Method)
// Only allow POST and GET methods
if r.Method != http.MethodPost && r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Authenticate the request
token := r.Header.Get("Authorization")
if token == "" {
token = r.URL.Query().Get("token")
}
// Handle different Authorization header formats
if strings.HasPrefix(token, "Bearer ") {
token = strings.TrimPrefix(token, "Bearer ")
} else if strings.HasPrefix(token, "token ") {
token = strings.TrimPrefix(token, "token ")
}
clientIPParsed := net.ParseIP(getClientIP(r))
if clientIPParsed == nil {
clientIPParsed = net.IPv4(127, 0, 0, 1)
}
allowed, reason, err := s.authenticateToken(
username,
token,
"/_/ntfy",
r.Method,
false,
clientIPParsed,
)
if err != nil {
s.logger.Error("Authentication error", "error", err, "username", username)
http.Error(w, "Authentication error", http.StatusInternalServerError)
return
}
if !allowed {
s.logger.Info("Access denied", "username", username, "reason", reason)
http.Error(w, "Access denied: "+reason, http.StatusUnauthorized)
return
}
// Fetch user configuration to get notification settings
userConfig, err := s.fetchUserConfig(username)
if err != nil {
s.logger.Error("Failed to fetch user config", "error", err, "username", username)
http.Error(w, "Failed to fetch user configuration", http.StatusInternalServerError)
return
}
// Check if notification backend is configured
if userConfig.Ntfy.Type == "" {
s.logger.Error("No notification backend configured for user", "username", username)
http.Error(w, "Notification backend not configured", http.StatusServiceUnavailable)
return
}
// Create notification backend
backend, err := notification.BackendFactory(s.logger, userConfig.Ntfy)
if err != nil {
s.logger.Error("Failed to create notification backend", "error", err, "username", username)
http.Error(w, "Failed to create notification backend", http.StatusInternalServerError)
return
}
defer backend.Close()
// Parse the notification message
var msg types.NotificationMessage
var parseErr error
if r.Method == http.MethodPost {
contentType := r.Header.Get("Content-Type")
if strings.Contains(contentType, "application/json") {
// Parse JSON body
body, err := io.ReadAll(r.Body)
if err != nil {
s.logger.Error("Failed to read request body", "error", err)
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
if err := json.Unmarshal(body, &msg); err != nil {
s.logger.Error("Failed to parse JSON", "error", err)
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
} else if strings.Contains(contentType, "application/x-www-form-urlencoded") {
// Parse form data
if err := r.ParseForm(); err != nil {
s.logger.Error("Failed to parse form", "error", err)
http.Error(w, "Failed to parse form", http.StatusBadRequest)
return
}
msg, parseErr = s.parseNotificationFromForm(r.Form)
if parseErr != nil {
s.logger.Error("Failed to parse notification from form", "error", parseErr)
http.Error(w, parseErr.Error(), http.StatusBadRequest)
return
}
} else {
// Treat as plain text
body, err := io.ReadAll(r.Body)
if err != nil {
s.logger.Error("Failed to read request body", "error", err)
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
msg = types.NotificationMessage{
Type: "plain",
Content: string(body),
}
}
} else if r.Method == http.MethodGet {
// Parse query parameters
msg, parseErr = s.parseNotificationFromQuery(r.URL.Query())
if parseErr != nil {
s.logger.Error("Failed to parse notification from query", "error", parseErr)
http.Error(w, parseErr.Error(), http.StatusBadRequest)
return
}
}
// Set default values
if msg.Type == "" {
msg.Type = "plain"
}
// Validate the message
if msg.Content == "" {
http.Error(w, "Content is required", http.StatusBadRequest)
return
}
// Send the notification
if err := backend.SendNotification(msg); err != nil {
s.logger.Error("Failed to send notification", "error", err, "username", username)
http.Error(w, "Failed to send notification", http.StatusInternalServerError)
return
}
s.logger.Info("Notification sent successfully", "username", username, "type", msg.Type)
// Return success response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
response := map[string]string{
"status": "sent",
"type": msg.Type,
}
if err := json.NewEncoder(w).Encode(response); err != nil {
s.logger.Error("Failed to encode response", "error", err)
}
}
// fetchUserConfig fetches the user's configuration from Forgejo.
func (s *server) fetchUserConfig(username string) (*types.Config, error) {
return s.fetchUserConfigFile(username, "config.yaml")
}
// fetchUserConfigFile fetches a config.yaml file from Forgejo.
func (s *server) fetchUserConfigFile(username, filename string) (*types.Config, error) {
data, err := s.fetchFileFromForgejo(username, filename)
if err != nil {
return nil, err
}
var config types.Config
if err := yaml.Unmarshal(data, &config); err != nil {
return nil, fmt.Errorf("failed to parse %s: %w", filename, err)
}
return &config, nil
}
// fetchUserAuthFile fetches a config.yaml file from Forgejo.
// fetchFileFromForgejo fetches a file from a user's .patchwork repository.
func (s *server) fetchFileFromForgejo(username, filename string) ([]byte, error) {
apiURL := fmt.Sprintf("%s/api/v1/repos/%s/.patchwork/media/%s", s.forgejoURL, username, filename)
req, err := http.NewRequest(http.MethodGet, apiURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Accept", "application/octet-stream")
req.Header.Set("Authorization", "token "+s.forgejoToken)
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch %s: %w", filename, err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, fmt.Errorf("%s not found", filename)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
return io.ReadAll(resp.Body)
}
// parseNotificationFromQuery parses notification data from URL query parameters.
func (s *server) parseNotificationFromQuery(values url.Values) (types.NotificationMessage, error) {
msg := types.NotificationMessage{
Type: values.Get("type"),
Title: values.Get("title"),
Content: values.Get("message"),
Room: values.Get("room"),
}
if msg.Content == "" {
// Try alternative parameter names
if body := values.Get("body"); body != "" {
msg.Content = body
} else if message := values.Get("message"); message != "" {
msg.Content = message
}
}
if msg.Content == "" {