-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
507 lines (441 loc) · 15.1 KB
/
main.go
File metadata and controls
507 lines (441 loc) · 15.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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/johnwmail/nclip/config"
"github.com/johnwmail/nclip/handlers"
"github.com/johnwmail/nclip/handlers/retrieval"
"github.com/johnwmail/nclip/handlers/upload"
"github.com/johnwmail/nclip/internal/services"
"github.com/johnwmail/nclip/storage"
"github.com/johnwmail/nclip/utils"
// Lambda imports (only used when in Lambda mode)
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
ginadapter "github.com/awslabs/aws-lambda-go-api-proxy/gin"
)
// Version/build info (set via -ldflags at build time)
var (
Version = "dev"
BuildTime = "unknown"
CommitHash = "none"
)
// Lambda-specific variables
var (
ginLambdaV1 *ginadapter.GinLambda
ginLambdaV2 *ginadapter.GinLambdaV2
ginLambdaOnce sync.Once
)
// isLambdaEnvironment detects if running in AWS Lambda
func isLambdaEnvironment() bool {
return os.Getenv("AWS_LAMBDA_FUNCTION_NAME") != ""
}
func main() {
// Print version/build info at startup
log.Printf("NCLIP Version: %s", Version)
log.Printf("Build Time: %s", BuildTime)
log.Printf("Commit Hash: %s", CommitHash)
// Load configuration
cfg := config.LoadConfig()
cfg.Version = Version
cfg.BuildTime = BuildTime
cfg.CommitHash = CommitHash
// Set Gin mode based on environment
if os.Getenv("GIN_MODE") == "release" {
gin.SetMode(gin.ReleaseMode)
}
// Print the NCLIP_UPLOAD_AUTH settings at startup
log.Printf("Upload Authentication Enabled: %v", cfg.UploadAuth)
if cfg.UploadAuth {
// Print the number of configured API keys without exposing them
// Count and log the number of non-empty API keys (do not print the keys themselves)
keys := strings.Split(cfg.APIKeys, ",")
numKeys := 0
for _, k := range keys {
if strings.TrimSpace(k) != "" {
numKeys++
}
}
log.Printf("Configured API Keys: %d", numKeys)
}
// Aggressive logging: print all environment variables
if utils.IsDebugEnabled() {
log.Printf("[DEBUG] ENVIRONMENT VARIABLES:")
for _, e := range os.Environ() {
log.Printf("[ENV] %s", e)
}
}
// Aggressive logging: print config
if utils.IsDebugEnabled() {
log.Printf("[DEBUG] Loaded config: %+v", cfg)
}
// Initialize storage backend based on deployment mode
var store storage.PasteStore
var err error
if isLambdaEnvironment() {
// Lambda mode: Use S3
store, err = storage.NewS3Store(cfg.S3Bucket, cfg.S3Prefix)
if err != nil {
log.Fatalf("Failed to initialize S3 storage for Lambda: %v", err)
}
if utils.IsDebugEnabled() {
log.Printf("S3 Bucket: %s", cfg.S3Bucket)
log.Printf("S3 Prefix: %s", cfg.S3Prefix)
}
log.Println("Lambda mode: Using S3 storage")
} else {
// Server mode: Use filesystem. Use configured DataDir.
store, err = storage.NewFilesystemStore(cfg.DataDir)
if err != nil {
log.Fatalf("Failed to initialize filesystem storage: %v", err)
}
log.Println("Server mode: Using filesystem storage")
if utils.IsDebugEnabled() {
log.Printf("Listening on port: %d", cfg.Port)
}
}
// Setup router
router := setupRouter(store, cfg)
// Check if running in Lambda environment
if isLambdaEnvironment() {
log.Println("Starting in AWS Lambda mode")
ginLambdaOnce.Do(func() {
ginLambdaV1 = ginadapter.New(router)
ginLambdaV2 = ginadapter.NewV2(router)
})
lambda.Start(lambdaHandler)
return
}
// Run in container/server mode
log.Println("Starting in HTTP server mode")
runHTTPServer(router, cfg, store)
}
// lambdaHandler handles Lambda requests for both v1 and v2 formats
func lambdaHandler(ctx context.Context, event interface{}) (interface{}, error) {
ginLambdaOnce.Do(func() {
// Defensive: adapters should already be initialized, but ensure they're not nil
if ginLambdaV1 == nil || ginLambdaV2 == nil {
log.Fatal("Lambda adapters are not initialized")
}
})
// Log the raw event for debugging
log.Printf("Received event type: %T", event)
// Convert event to JSON bytes for parsing
eventBytes, err := json.Marshal(event)
if err != nil {
log.Printf("Failed to marshal event: %v", err)
return events.APIGatewayV2HTTPResponse{
StatusCode: 500,
Body: "Failed to process event",
Headers: map[string]string{
"Content-Type": "text/plain",
},
}, err
}
// Try to parse as APIGatewayV2HTTPRequest first (for Lambda Function URLs and HTTP API)
var reqV2 events.APIGatewayV2HTTPRequest
if err := json.Unmarshal(eventBytes, &reqV2); err == nil && reqV2.RequestContext.HTTP.Method != "" {
log.Printf("Handling as APIGatewayV2HTTPRequest (Lambda Function URL/HTTP API)")
log.Printf("Method: %s, Path: %s", reqV2.RequestContext.HTTP.Method, reqV2.RawPath)
return ginLambdaV2.ProxyWithContext(ctx, reqV2)
}
// Try to parse as APIGatewayProxyRequest (for REST API and ALB)
var reqV1 events.APIGatewayProxyRequest
if err := json.Unmarshal(eventBytes, &reqV1); err == nil && reqV1.HTTPMethod != "" {
log.Printf("Handling as APIGatewayProxyRequest (REST API/ALB)")
log.Printf("Method: %s, Path: %s", reqV1.HTTPMethod, reqV1.Path)
return ginLambdaV1.ProxyWithContext(ctx, reqV1)
}
// If neither format works, log the event structure and return error
log.Printf("Unable to parse event as APIGateway v1 or v2 format")
log.Printf("Event JSON: %s", string(eventBytes))
// Check if this is a Lambda test event (contains test keys like key1, key2, key3)
var testEvent map[string]interface{}
if err := json.Unmarshal(eventBytes, &testEvent); err == nil {
if _, hasKey1 := testEvent["key1"]; hasKey1 {
log.Printf("Detected Lambda test event, returning success response")
return events.APIGatewayV2HTTPResponse{
StatusCode: 200,
Body: `{"message": "nclip Lambda function is working! Use a real HTTP request or API Gateway integration."}`,
Headers: map[string]string{
"Content-Type": "application/json",
},
}, nil
}
}
return events.APIGatewayV2HTTPResponse{
StatusCode: 500,
Body: "Unsupported event type - this function expects API Gateway or Lambda Function URL events",
Headers: map[string]string{
"Content-Type": "text/plain",
},
}, fmt.Errorf("unsupported event type: %T", event)
}
// setupRouter creates and configures the Gin router
func setupRouter(store storage.PasteStore, cfg *config.Config) *gin.Engine {
// Initialize service
pasteService := services.NewPasteService(store, cfg)
// Initialize handlers
uploadHandler := upload.NewHandler(pasteService, cfg)
retrievalHandler := retrieval.NewHandler(pasteService, store, cfg)
metaHandler := handlers.NewMetaHandler(store)
systemHandler := handlers.NewSystemHandler()
webuiHandler := handlers.NewWebUIHandler(cfg)
// Create Gin router
router := gin.New()
// Add logging middleware
// Use a JSON-safe recovery middleware and canonicalErrors middleware so
// API endpoints always return JSON error responses instead of HTML error
// pages that the web UI cannot parse.
router.Use(gin.Logger())
router.Use(jsonRecovery())
router.Use(canonicalErrors())
router.Use(gin.Recovery())
// Load favicon
router.StaticFile("/favicon.ico", "./static/favicon.ico")
// Load HTML templates
router.LoadHTMLGlob("static/*.html")
// Serve static files
router.Static("/static", "./static")
// Web UI routes
router.GET("/", webuiHandler.Index)
// Core API routes
if cfg.UploadAuth {
auth := apiKeyAuth(cfg)
router.POST("/", auth, uploadHandler.Upload)
router.POST("/burn/", auth, uploadHandler.UploadBurn)
// Base64 upload routes (shortcut that auto-sets X-Content-Encoding header)
router.POST("/base64", auth, base64UploadMiddleware(), uploadHandler.Upload)
} else {
router.POST("/", uploadHandler.Upload)
router.POST("/burn/", uploadHandler.UploadBurn)
// Base64 upload routes (shortcut that auto-sets X-Content-Encoding header)
router.POST("/base64", base64UploadMiddleware(), uploadHandler.Upload)
}
router.GET("/:slug", retrievalHandler.View)
router.GET("/raw/:slug", retrievalHandler.Raw)
if cfg.UploadAuth {
auth := apiKeyAuth(cfg)
router.DELETE("/:slug", auth, metaHandler.DeletePaste)
} else {
router.DELETE("/:slug", metaHandler.DeletePaste)
}
// Metadata API
router.GET("/api/v1/meta/:slug", metaHandler.GetMetadata)
// Alias for metadata API (shortcut)
router.GET("/json/:slug", metaHandler.GetMetadata)
// System routes
router.GET("/health", systemHandler.Health)
// Global 404 handler
router.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{"error": "Resource not found"})
})
return router
}
// base64UploadMiddleware sets the X-Base64 header
// This allows /base64 route to automatically enable base64 decoding
func base64UploadMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Request.Header.Set("X-Base64", "true")
c.Next()
}
}
// jsonRecovery returns a middleware that recovers from panics and ensures
// the response is JSON formatted so the web UI can parse error responses.
func jsonRecovery() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
// Log the panic for diagnostics
log.Printf("[PANIC] %v", r)
c.Header("Content-Type", "application/json; charset=utf-8")
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
}
}()
c.Next()
}
}
// canonicalErrors ensures that if a handler did not write a body but the
// response status is an error (>=400), a small JSON error body is written.
// This helps intermediaries and CDNs forward a predictable JSON payload.
func canonicalErrors() gin.HandlerFunc {
return func(c *gin.Context) {
// Wrap the ResponseWriter so we can buffer the body and inspect it
origWriter := c.Writer
bcw := &bodyCaptureWriter{ResponseWriter: origWriter}
c.Writer = bcw
c.Next()
status := bcw.Status()
// Read buffered body and content-type
buf := bcw.body.Bytes()
ct := bcw.Header().Get("Content-Type")
if status >= 400 {
// If the client explicitly accepts HTML, forward the original
// buffered response unchanged so browsers receive the HTML page.
// Only canonicalize to JSON for clients that do not accept HTML
// (e.g., APIs / CLI tools).
accept := c.Request.Header.Get("Accept")
if strings.Contains(accept, "text/html") {
if len(buf) > 0 {
origWriter.WriteHeader(status)
if _, err := origWriter.Write(buf); err != nil {
log.Printf("[ERROR] canonicalErrors: failed to write response body: %v", err)
}
} else {
origWriter.WriteHeader(status)
}
return
}
// Determine a suitable message to expose
msg := getErrorMessage(buf, ct, c, status)
// Write canonical JSON to the original writer
origWriter.Header().Set("Content-Type", "application/json; charset=utf-8")
origWriter.WriteHeader(status)
out, _ := json.Marshal(gin.H{"error": msg})
if _, err := origWriter.Write(out); err != nil {
log.Printf("[ERROR] canonicalErrors: failed to write error response: %v", err)
}
return
}
// Non-error: forward buffered content as-is
if len(buf) > 0 {
// Ensure headers/status are flushed
origWriter.WriteHeader(status)
if _, err := origWriter.Write(buf); err != nil {
log.Printf("[ERROR] canonicalErrors: failed to write response body: %v", err)
}
}
}
}
// getErrorMessage extracts a suitable error message from the response body,
// gin.Context errors, or HTTP status text.
//
// Parameters:
//
// buf - the response body as a byte slice
// ct - the content-type of the response
// c - the gin.Context for the current request
// status - the HTTP status code of the response
//
// Returns:
//
// A string containing a suitable error message for the client.
func getErrorMessage(buf []byte, ct string, c *gin.Context, status int) string {
// If there is a JSON body, try extracting its message/error
if len(buf) > 0 && strings.Contains(ct, "application/json") {
var parsed map[string]interface{}
if err := json.Unmarshal(buf, &parsed); err == nil {
if e, ok := parsed["error"].(string); ok {
return e
}
if m, ok := parsed["message"].(string); ok {
return m
}
}
}
// If not found, use raw body text if present
if len(buf) > 0 {
return string(bytes.TrimSpace(buf))
}
// Fallback to gin errors or status text
if len(c.Errors) > 0 {
return c.Errors.Last().Error()
}
return http.StatusText(status)
}
// apiKeyAuth returns a middleware that validates API keys supplied via
// Authorization: Bearer <key> or X-Api-Key: <key> headers. It reads keys
// from cfg.APIKeys (comma-separated) and denies unauthorized requests with
// HTTP 401.
func apiKeyAuth(cfg *config.Config) gin.HandlerFunc {
// Build a map of allowed keys for fast lookup
allowed := map[string]struct{}{}
for _, k := range strings.Split(cfg.APIKeys, ",") {
kk := strings.TrimSpace(k)
if kk != "" {
allowed[kk] = struct{}{}
}
}
return func(c *gin.Context) {
// Extract key from Authorization: Bearer <key>
var key string
if auth := c.GetHeader("Authorization"); auth != "" {
if strings.HasPrefix(strings.ToLower(auth), "bearer ") {
key = strings.TrimSpace(auth[7:])
}
}
// If not found, try X-Api-Key
if key == "" {
key = strings.TrimSpace(c.GetHeader("X-Api-Key"))
}
if key == "" {
c.Header("Content-Type", "application/json; charset=utf-8")
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing api key"})
return
}
if _, ok := allowed[key]; !ok {
// constant-time compare could be added, but we are checking map membership
c.Header("Content-Type", "application/json; charset=utf-8")
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
c.Next()
}
}
// bodyCaptureWriter buffers response body writes so middleware can inspect
// and optionally rewrite the output before sending to the client.
type bodyCaptureWriter struct {
gin.ResponseWriter
body bytes.Buffer
}
// Write implements io.Writer; buffer the bytes but do not write to the
// underlying writer until the middleware decides to forward them.
func (w *bodyCaptureWriter) Write(b []byte) (int, error) {
return w.body.Write(b)
}
// runHTTPServer starts the HTTP server for container mode
func runHTTPServer(router *gin.Engine, cfg *config.Config, store storage.PasteStore) {
// Ensure cleanup on exit
defer func() {
if err := store.Close(); err != nil {
log.Printf("Error closing storage: %v", err)
}
}()
// Create HTTP server
server := &http.Server{
Addr: fmt.Sprintf(":%d", cfg.Port),
Handler: router,
}
// Start server in a goroutine
go func() {
log.Printf("Starting nclip server on port %d", cfg.Port)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Failed to start server: %v", err)
}
}()
// Wait for interrupt signal to gracefully shutdown the server
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down server...")
// Create a deadline for shutdown
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Attempt graceful shutdown
if err := server.Shutdown(ctx); err != nil {
log.Printf("Server forced to shutdown: %v", err)
} else {
log.Println("Server shutdown complete")
}
}