Files
scratchbox/cmd/scratchbox/server.go
T
s1d3sw1ped ad4355df17
CI / Go Tests (push) Successful in 15s
CI / Build (push) Successful in 9s
Format / gofmt (push) Successful in 7s
Release Artifacts / Validate release tag (push) Successful in 2s
Release Artifacts / Build and release executables (push) Successful in 15s
Release Artifacts / Build and release Docker image (push) Successful in 28s
Heavy security and file splitting
2026-06-01 20:15:28 -05:00

194 lines
5.3 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"sort"
"strings"
"syscall"
"github.com/spf13/cobra"
"scratchbox/internal/cleanup"
"scratchbox/internal/config"
httpapi "scratchbox/internal/http"
"scratchbox/internal/storage"
)
func newServerCmd() *cobra.Command {
var configPath string
var useEnv bool
cmd := &cobra.Command{
Use: "server",
Short: "Run the scratchbox service",
Args: cobra.NoArgs,
RunE: func(_ *cobra.Command, _ []string) error {
return run(configPath, useEnv)
},
}
cmd.Flags().StringVarP(&configPath, "config", "c", "", "path to config file")
cmd.Flags().BoolVar(&useEnv, "env", false, "load config from SCRATCHBOX_* environment variables")
cmd.MarkFlagsMutuallyExclusive("config", "env")
return cmd
}
func run(configPath string, useEnv bool) error {
var (
cfg config.Config
err error
)
if useEnv {
envCount := printEnvStartup()
if envCount == 0 {
return errors.New("no SCRATCHBOX_* environment variables set for --env mode")
}
cfg, err = config.LoadFromEnv()
} else {
generated, err := ensureConfigFile(configPath)
if err != nil {
return fmt.Errorf("config init failed: %w", err)
}
if generated {
fmt.Fprintf(os.Stdout, "Generated default config at %s\nReview and adjust it, then re-run the same command.\n", strings.TrimSpace(configPath))
return nil
}
cfg, err = config.Load(configPath)
}
if err != nil {
return fmt.Errorf("config load failed: %w", err)
}
// Prepare data dir + key (side effects) after pure Validate inside Load*/Default.
// This addresses the layering issue where Validate used to mutate FS.
if err := cfg.PrepareDataDir(); err != nil {
return fmt.Errorf("prepare storage data dir failed: %w", err)
}
logger := log.New(os.Stdout, "[scratchbox] ", log.LstdFlags|log.LUTC)
accessWriter, closeAccessWriter, err := newAccessLogWriter(cfg)
if err != nil {
return fmt.Errorf("access log init failed: %w", err)
}
defer func() {
if closeErr := closeAccessWriter(); closeErr != nil {
logger.Printf("access log writer close failed: %v", closeErr)
}
}()
var accessLogger *log.Logger
if cfg.Server.AccessLog.Enabled {
accessLogger = log.New(accessWriter, "[access] ", log.LstdFlags|log.LUTC)
}
store, err := storage.NewFilesystemStoreWithDefaultTTL(
cfg.Storage.DataDir,
cfg.Limits.DefaultTTLDuration,
cfg.Storage.EncryptionKeyBytes,
)
if err != nil {
return fmt.Errorf("storage init failed: %w", err)
}
server, err := httpapi.NewServer(cfg, store, logger, accessLogger)
if err != nil {
return fmt.Errorf("http init failed: %w", err)
}
cleanupWorker := cleanup.NewWorker(store, cfg.Storage.CleanupIntervalParsed, logger)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
go cleanupWorker.Start(ctx)
httpServer := &http.Server{
Addr: cfg.Server.ListenAddr,
Handler: server.Routes(),
ReadHeaderTimeout: cfg.Server.ReadHeaderTimeoutDur,
ReadTimeout: cfg.Server.ReadTimeoutDur,
WriteTimeout: cfg.Server.WriteTimeoutDur,
IdleTimeout: cfg.Server.IdleTimeoutDur,
MaxHeaderBytes: cfg.Server.MaxHeaderBytes,
}
go func() {
<-ctx.Done()
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), cfg.Server.ShutdownTimeoutDur)
defer shutdownCancel()
if err := httpServer.Shutdown(shutdownCtx); err != nil {
logger.Printf("http shutdown failed: %v", err)
}
}()
logger.Printf("listening on %s", cfg.Server.ListenAddr)
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
return fmt.Errorf("http server exited with error: %w", err)
}
return nil
}
func printEnvStartup() int {
entries := make([]string, 0)
for _, item := range os.Environ() {
if strings.HasPrefix(item, "SCRATCHBOX_") {
entries = append(entries, item)
}
}
sort.Strings(entries)
fmt.Fprintln(os.Stdout, "[scratchbox] --env startup variables:")
if len(entries) == 0 {
fmt.Fprintln(os.Stdout, "[scratchbox] (no SCRATCHBOX_* variables set)")
return 0
}
for _, item := range entries {
printItem := item
// Redact values for IP list config (security sensitive for allowlist/rate/proxy spoof surface).
// Rates and other are left as-is (numeric, not secret).
if strings.Contains(item, "ALLOWED_IPS=") || strings.Contains(item, "TRUSTED_PROXY_IPS=") {
if eq := strings.IndexByte(item, '='); eq >= 0 {
printItem = item[:eq+1] + "*** (redacted)"
}
}
fmt.Fprintf(os.Stdout, "[scratchbox] %s\n", printItem)
}
return len(entries)
}
func ensureConfigFile(configPath string) (bool, error) {
path := strings.TrimSpace(configPath)
if path == "" {
return false, nil
}
info, err := os.Stat(path)
if err == nil {
if info.IsDir() {
return false, fmt.Errorf("config path %q is a directory", path)
}
return false, nil
}
if !errors.Is(err, os.ErrNotExist) {
return false, fmt.Errorf("stat config path %q: %w", path, err)
}
cfg := config.Default()
content, err := marshalYAMLWithComments(cfg)
if err != nil {
return false, fmt.Errorf("marshal default config: %w", err)
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return false, fmt.Errorf("create config dir: %w", err)
}
if err := os.WriteFile(path, content, 0o644); err != nil {
return false, fmt.Errorf("write default config: %w", err)
}
return true, nil
}