| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/base64" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "flag" |
| 10 | "io" |
| 11 | "log/slog" |
| 12 | "net/http" |
| 13 | "os" |
| 14 | "os/signal" |
| 15 | "syscall" |
| 16 | "time" |
| 17 | |
| 18 | access "amadan.net/oficina/agent-access.git" |
| 19 | "amadan.net/oficina/agent-access.git/connection" |
| 20 | "amadan.net/rastrillo/rastrillo" |
| 21 | "amadan.net/rastrillo/rastrillo/db" |
| 22 | ) |
| 23 | |
| 24 | func main() { |
| 25 | logger := slog.New(slog.NewJSONHandler(os.Stderr, nil)) |
| 26 | if err := run(logger); err != nil { |
| 27 | logger.Error("connection service stopped", "reason", err.Error()) |
| 28 | os.Exit(1) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | func run(logger *slog.Logger) error { |
| 33 | if encoded := os.Getenv("OFICINA_CONNECT_CONFIG_BASE64"); encoded != "" { |
| 34 | return runPlatform(logger, encoded) |
| 35 | } |
| 36 | configPath := flag.String("config", "", "connection configuration JSON file") |
| 37 | dbPath := flag.String("db", "oficina-connect.db", "persistent SQLite database path") |
| 38 | listen := flag.String("listen", "127.0.0.1:8080", "HTTP listener behind the HTTPS proxy") |
| 39 | flag.Parse() |
| 40 | if *configPath == "" { |
| 41 | return errors.New("supply -config") |
| 42 | } |
| 43 | file, err := os.Open(*configPath) |
| 44 | if err != nil { |
| 45 | return errors.New("could not open connection configuration") |
| 46 | } |
| 47 | defer file.Close() |
| 48 | raw, err := io.ReadAll(io.LimitReader(file, (2<<20)+1)) |
| 49 | if err != nil || len(raw) > 2<<20 || access.UniqueJSON(raw) != nil { |
| 50 | return errors.New("invalid connection configuration JSON") |
| 51 | } |
| 52 | cfg, err := loadConfig(raw) |
| 53 | if err != nil { |
| 54 | return err |
| 55 | } |
| 56 | d, err := db.Open(*dbPath, logger) |
| 57 | if err != nil { |
| 58 | return errors.New("could not open connection database") |
| 59 | } |
| 60 | defer d.Close() |
| 61 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 62 | defer stop() |
| 63 | app, err := connection.New(ctx, cfg, d, logger) |
| 64 | if err != nil { |
| 65 | return errors.New("connection service configuration or storage is unavailable") |
| 66 | } |
| 67 | server := &http.Server{Addr: *listen, Handler: app.Handler, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 60 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10} |
| 68 | finished := make(chan error, 1) |
| 69 | go func() { finished <- server.ListenAndServe() }() |
| 70 | select { |
| 71 | case err := <-finished: |
| 72 | if !errors.Is(err, http.ErrServerClosed) { |
| 73 | return errors.New("connection HTTP listener failed") |
| 74 | } |
| 75 | return nil |
| 76 | case <-ctx.Done(): |
| 77 | shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 78 | defer cancel() |
| 79 | return server.Shutdown(shutdown) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | const platformConfigLimit = 64 << 10 |
| 84 | const appHeaderLimit = 16 << 10 |
| 85 | |
| 86 | func loadConfig(raw []byte) (connection.Config, error) { |
| 87 | var cfg connection.Config |
| 88 | if access.UniqueJSON(raw) != nil { |
| 89 | return cfg, errors.New("invalid connection configuration JSON") |
| 90 | } |
| 91 | decoder := json.NewDecoder(bytes.NewReader(raw)) |
| 92 | decoder.DisallowUnknownFields() |
| 93 | if decoder.Decode(&cfg) != nil { |
| 94 | return cfg, errors.New("invalid connection configuration") |
| 95 | } |
| 96 | var err error |
| 97 | cfg.DEK, err = base64.StdEncoding.DecodeString(os.Getenv("OFICINA_CONNECT_DEK")) |
| 98 | if err != nil || len(cfg.DEK) != 32 { |
| 99 | return cfg, errors.New("OFICINA_CONNECT_DEK must encode 32 bytes") |
| 100 | } |
| 101 | cfg.DirectoryToken = os.Getenv("OFICINA_DIRECTORY_TOKEN") |
| 102 | return cfg, nil |
| 103 | } |
| 104 | |
| 105 | func runPlatform(logger *slog.Logger, encoded string) error { |
| 106 | if len(encoded) > base64.StdEncoding.EncodedLen(platformConfigLimit) { |
| 107 | return errors.New("invalid deployment configuration size") |
| 108 | } |
| 109 | raw, err := base64.StdEncoding.Strict().DecodeString(encoded) |
| 110 | if err != nil || len(raw) > platformConfigLimit { |
| 111 | return errors.New("invalid deployment configuration encoding or size") |
| 112 | } |
| 113 | cfg, err := loadConfig(raw) |
| 114 | if err != nil { |
| 115 | return err |
| 116 | } |
| 117 | opts, err := rastrillo.Resolve(rastrillo.Options{DBPath: "oficina-connect.db", Logger: logger}) |
| 118 | if err != nil { |
| 119 | return errors.New("invalid platform activation arguments") |
| 120 | } |
| 121 | d, err := db.Open(opts.DBPath, logger) |
| 122 | if err != nil { |
| 123 | return errors.New("could not open connection database") |
| 124 | } |
| 125 | defer d.Close() |
| 126 | app, err := connection.New(context.Background(), cfg, d, logger) |
| 127 | if err != nil { |
| 128 | return errors.New("connection service configuration or storage is unavailable") |
| 129 | } |
| 130 | opts = servingOptions(opts, app.Handler) |
| 131 | if err := rastrillo.Serve(opts); err != nil { |
| 132 | return errors.New("connection platform runtime failed") |
| 133 | } |
| 134 | return nil |
| 135 | } |
| 136 | |
| 137 | // servingOptions relinquishes framework database ownership while preserving the |
| 138 | // resolved listener coordinates and logger. The caller closes its handle only |
| 139 | // after Serve has drained the HTTP server. |
| 140 | func servingOptions(opts rastrillo.Options, handler http.Handler) rastrillo.Options { |
| 141 | opts.DBPath = "" |
| 142 | opts.NoSpeculationRules = true |
| 143 | opts.ReadHeaderTimeout = 10 * time.Second |
| 144 | opts.ReadTimeout = 30 * time.Second |
| 145 | opts.WriteTimeout = 60 * time.Second |
| 146 | opts.IdleTimeout = 60 * time.Second |
| 147 | opts.Mux = http.NewServeMux() |
| 148 | opts.Mux.Handle("/", handler) |
| 149 | opts.Wrap = limitAppHeaders |
| 150 | return opts |
| 151 | } |
| 152 | |
| 153 | // This application budget is additional to the framework's 1 MiB parser limit. |
| 154 | // Probes bypass app middleware. Count Host separately: net/http removes it from |
| 155 | // Header. Repeated values each pay for their header name. |
| 156 | func limitAppHeaders(next http.Handler) http.Handler { |
| 157 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 158 | size := len(r.RequestURI) + len("Host") + len(r.Host) |
| 159 | for name, values := range r.Header { |
| 160 | for _, value := range values { |
| 161 | size += len(name) + len(value) |
| 162 | if size > appHeaderLimit { |
| 163 | http.Error(w, "Request headers too large", http.StatusRequestHeaderFieldsTooLarge) |
| 164 | return |
| 165 | } |
| 166 | } |
| 167 | } |
| 168 | if size > appHeaderLimit { |
| 169 | http.Error(w, "Request headers too large", http.StatusRequestHeaderFieldsTooLarge) |
| 170 | return |
| 171 | } |
| 172 | next.ServeHTTP(w, r) |
| 173 | }) |
| 174 | } |
| 175 | |