Go · 11199 bytes Raw Blame History
1 // SPDX-License-Identifier: AGPL-3.0-or-later
2
3 // Package web boots the shithub HTTP server. The full middleware stack
4 // (recover, request_id, logging, real-IP, timeout, compress, secure
5 // headers, CSRF, session, CORS, metrics, tracing), the chi router, the
6 // session store, the styled error pages, and the observability sinks
7 // (logging, metrics, tracing, error reporting) are composed here.
8 package web
9
10 import (
11 "context"
12 "encoding/base64"
13 "errors"
14 "fmt"
15 "log/slog"
16 "net/http"
17 "os"
18 "os/signal"
19 "syscall"
20 "time"
21
22 "github.com/go-chi/chi/v5"
23 "github.com/jackc/pgx/v5/pgxpool"
24 "golang.org/x/crypto/chacha20poly1305"
25
26 "github.com/tenseleyFlow/shithub/internal/auth/session"
27 "github.com/tenseleyFlow/shithub/internal/infra/config"
28 "github.com/tenseleyFlow/shithub/internal/infra/db"
29 "github.com/tenseleyFlow/shithub/internal/infra/errrep"
30 infralog "github.com/tenseleyFlow/shithub/internal/infra/log"
31 "github.com/tenseleyFlow/shithub/internal/infra/metrics"
32 "github.com/tenseleyFlow/shithub/internal/infra/tracing"
33 "github.com/tenseleyFlow/shithub/internal/web/handlers"
34 "github.com/tenseleyFlow/shithub/internal/web/middleware"
35 )
36
37 // Options configures the web server. Addr overrides config when non-empty
38 // (preserves the existing --addr CLI flag behavior).
39 type Options struct {
40 Addr string
41 }
42
43 // Run boots the web server and blocks until shutdown.
44 func Run(ctx context.Context, opts Options) error {
45 cfg, err := config.Load(nil)
46 if err != nil {
47 return err
48 }
49 if opts.Addr != "" {
50 cfg.Web.Addr = opts.Addr
51 }
52
53 logger := infralog.New(infralog.Options{
54 Level: cfg.Log.Level,
55 Format: cfg.Log.Format,
56 Writer: os.Stderr,
57 })
58
59 // Error reporting (no-op when DSN empty).
60 flushErrRep, err := errrep.Init(errrep.Config{
61 DSN: cfg.ErrorReporting.DSN,
62 Environment: cfg.ErrorReporting.Environment,
63 Release: cfg.ErrorReporting.Release,
64 })
65 if err != nil {
66 return fmt.Errorf("errrep: %w", err)
67 }
68 defer func() { _ = flushErrRep(context.Background()) }()
69 if cfg.ErrorReporting.DSN != "" {
70 // Wrap the slog handler so error-level records are reported.
71 // We rebuild the logger so every component that pulls it from
72 // here gets the wrapped chain.
73 logger = slog.New(&errrep.SlogHandler{Inner: logger.Handler()})
74 }
75
76 // Tracing (no-op when disabled).
77 flushTracing, err := tracing.Init(ctx, tracing.Config{
78 Enabled: cfg.Tracing.Enabled,
79 Endpoint: cfg.Tracing.Endpoint,
80 SampleRate: cfg.Tracing.SampleRate,
81 ServiceName: cfg.Tracing.ServiceName,
82 })
83 if err != nil {
84 return fmt.Errorf("tracing: %w", err)
85 }
86 defer func() { _ = flushTracing(context.Background()) }()
87
88 logoBytes, err := LogoSVG()
89 if err != nil {
90 return fmt.Errorf("load logo: %w", err)
91 }
92
93 sessionStore, err := buildSessionStore(cfg.Session, logger)
94 if err != nil {
95 return err
96 }
97
98 // Optional DB pool (carried over from S01); now driven by config.
99 var pool *pgxpool.Pool
100 if cfg.DB.URL != "" {
101 //nolint:gosec // G115: max_conns is operator-configured with small numeric values (typ. 10–100).
102 p, err := db.Open(ctx, db.Config{
103 URL: cfg.DB.URL,
104 MaxConns: int32(cfg.DB.MaxConns),
105 MinConns: int32(cfg.DB.MinConns),
106 ConnectTimeout: cfg.DB.ConnectTimeout,
107 })
108 if err != nil {
109 logger.Warn("db: open failed; /readyz will report unhealthy", "error", err)
110 } else {
111 pool = p
112 defer p.Close()
113 metrics.ObserveDBPool(ctx, pool, 10*time.Second)
114 }
115 }
116
117 r := chi.NewRouter()
118
119 // Middleware stack — outermost first.
120 r.Use(middleware.RequestID)
121 r.Use(middleware.RealIP(middleware.RealIPConfig{}))
122 r.Use(middleware.AccessLog(logger))
123 r.Use(middleware.Metrics)
124 if cfg.Tracing.Enabled {
125 r.Use(tracing.Middleware)
126 }
127 r.Use(middleware.SecureHeaders(middleware.DefaultSecureHeaders()))
128 // Compress + Timeout are NOT global: the smart-HTTP git routes need
129 // to stream uncompressed pack data for many minutes. RegisterChi
130 // applies them inside the CSRF-exempt and CSRF-protected groups but
131 // skips the git group.
132 r.Use(middleware.SessionLoader(sessionStore, logger))
133 if pool != nil {
134 r.Use(middleware.OptionalUser(usernameLookup(pool)))
135 }
136 r.Use(middleware.PolicyCache())
137
138 deps := handlers.Deps{
139 Logger: logger,
140 TemplatesFS: TemplatesFS(),
141 StaticFS: StaticFS(),
142 LogoSVG: string(logoBytes),
143 SessionStore: sessionStore,
144 }
145 if pool != nil {
146 deps.ReadyCheck = func(ctx context.Context) error { return pool.Ping(ctx) }
147 }
148 if cfg.Metrics.Enabled {
149 deps.MetricsHandler = metrics.Handler(cfg.Metrics.BasicAuthUser, cfg.Metrics.BasicAuthPass)
150 }
151
152 if pool != nil {
153 objectStore, err := buildObjectStore(cfg.Storage.S3, logger)
154 if err != nil {
155 return fmt.Errorf("object store: %w", err)
156 }
157
158 auth, err := buildAuthHandlers(cfg, pool, sessionStore, objectStore, logger, deps.TemplatesFS)
159 if err != nil {
160 return fmt.Errorf("auth handlers: %w", err)
161 }
162 deps.AuthMounter = auth.Mount
163
164 api, err := buildAPIHandlers(pool)
165 if err != nil {
166 return fmt.Errorf("api handlers: %w", err)
167 }
168 deps.APIMounter = api.Mount
169
170 profile, err := buildProfileHandlers(pool, objectStore, deps.TemplatesFS, logger)
171 if err != nil {
172 return fmt.Errorf("profile handlers: %w", err)
173 }
174 deps.AvatarMounter = profile.MountAvatars
175 deps.ProfileMounter = profile.MountProfile
176
177 repoH, err := buildRepoHandlers(cfg, pool, deps.TemplatesFS, logger)
178 if err != nil {
179 return fmt.Errorf("repo handlers: %w", err)
180 }
181 // /new is wrapped in RequireUser — it requires a logged-in caller.
182 deps.RepoNewMounter = func(r chi.Router) {
183 r.Group(func(r chi.Router) {
184 r.Use(middleware.RequireUser)
185 repoH.MountNew(r)
186 })
187 }
188 deps.RepoHomeMounter = repoH.MountRepoHome
189 deps.RepoCodeMounter = repoH.MountCode
190 deps.RepoHistoryMounter = repoH.MountHistory
191 deps.RepoRefsMounter = repoH.MountRefs
192 deps.RepoSettingsBranchesMounter = func(r chi.Router) {
193 r.Group(func(r chi.Router) {
194 r.Use(middleware.RequireUser)
195 repoH.MountSettingsBranches(r)
196 })
197 }
198 // Issues GETs are public (subject to policy.Can), POSTs require
199 // auth. The handler enforces auth + policy per request, so we
200 // register the whole surface in the public group; an unauth
201 // POST hits the policy gate and 404s out of the existence-leak
202 // path. Browser flows still need RequireUser to redirect-to-login,
203 // so the POST routes get wrapped through the same group with
204 // RequireUser inserted only for state-mutating verbs.
205 deps.RepoIssuesMounter = repoH.MountIssues
206 deps.RepoPullsMounter = repoH.MountPulls
207 deps.RepoSocialMounter = repoH.MountSocial
208 deps.RepoForkMounter = repoH.MountFork
209
210 searchH, err := buildSearchHandlers(pool, deps.TemplatesFS, logger)
211 if err != nil {
212 return fmt.Errorf("search handlers: %w", err)
213 }
214 deps.SearchMounter = searchH.Mount
215
216 notifH, err := buildNotifHandlers(cfg, pool, deps.TemplatesFS, logger)
217 if err != nil {
218 return fmt.Errorf("notif handlers: %w", err)
219 }
220 deps.NotifInboxMounter = func(r chi.Router) {
221 r.Group(func(r chi.Router) {
222 r.Use(middleware.RequireUser)
223 notifH.MountAuthed(r)
224 })
225 }
226 deps.NotifPublicMounter = notifH.MountPublic
227
228 // S30 — orgs.
229 orgH, err := buildOrgHandlers(cfg, pool, deps.TemplatesFS, logger)
230 if err != nil {
231 return fmt.Errorf("org handlers: %w", err)
232 }
233 deps.OrgCreateMounter = func(r chi.Router) {
234 r.Group(func(r chi.Router) {
235 r.Use(middleware.RequireUser)
236 orgH.MountCreate(r)
237 })
238 }
239 // /{org}/people: GETs are public (org existence is non-secret;
240 // member lists for private orgs are deferred). Mutations are
241 // owner-checked inside the handler, but RequireUser wraps the
242 // POST routes so unauth submits redirect to /login.
243 deps.OrgRoutesMounter = func(r chi.Router) {
244 r.Group(func(r chi.Router) {
245 orgH.MountOrgRoutes(r)
246 })
247 }
248 deps.OrgInvitationsMounter = func(r chi.Router) {
249 r.Group(func(r chi.Router) {
250 r.Use(middleware.RequireUser)
251 orgH.MountInvitations(r)
252 })
253 }
254
255 // Lifecycle danger-zone routes — also auth-required.
256 deps.RepoLifecycleMounter = func(r chi.Router) {
257 r.Group(func(r chi.Router) {
258 r.Use(middleware.RequireUser)
259 repoH.MountLifecycle(r)
260 })
261 }
262
263 gitHTTPH, err := buildGitHTTPHandlers(cfg, pool, logger)
264 if err != nil {
265 return fmt.Errorf("git-http handlers: %w", err)
266 }
267 deps.GitHTTPMounter = gitHTTPH.MountSmartHTTP
268 } else {
269 logger.Warn("auth: no DB pool — signup/login routes not mounted")
270 }
271
272 _, panicHandler, notFoundHandler, err := handlers.RegisterChi(r, deps)
273 if err != nil {
274 return fmt.Errorf("register handlers: %w", err)
275 }
276 r.NotFound(notFoundHandler)
277
278 rootHandler := middleware.Recover(logger, panicHandler)(r)
279
280 srv := &http.Server{
281 Addr: cfg.Web.Addr,
282 Handler: rootHandler,
283 ReadHeaderTimeout: 10 * time.Second,
284 ReadTimeout: cfg.Web.ReadTimeout,
285 WriteTimeout: cfg.Web.WriteTimeout,
286 IdleTimeout: 120 * time.Second,
287 }
288
289 errCh := make(chan error, 1)
290 go func() {
291 logger.Info(
292 "shithub web server starting",
293 "addr", srv.Addr,
294 "env", cfg.Env,
295 "db", pool != nil,
296 "metrics", cfg.Metrics.Enabled,
297 "tracing", cfg.Tracing.Enabled,
298 "errrep", cfg.ErrorReporting.DSN != "",
299 )
300 if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
301 errCh <- err
302 }
303 close(errCh)
304 }()
305
306 sigCh := make(chan os.Signal, 1)
307 signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
308 defer signal.Stop(sigCh)
309
310 select {
311 case err, ok := <-errCh:
312 if !ok {
313 return nil
314 }
315 return err
316 case sig := <-sigCh:
317 logger.Info("shutdown signal received", "signal", sig.String())
318 case <-ctx.Done():
319 logger.Info("context canceled, shutting down")
320 }
321
322 shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Web.ShutdownTimeout)
323 defer cancel()
324 if err := srv.Shutdown(shutdownCtx); err != nil {
325 return fmt.Errorf("shutdown: %w", err)
326 }
327 return nil
328 }
329
330 // buildSessionStore constructs the cookie session store from the config's
331 // session block. SHITHUB_SESSION_KEY (env) overrides cfg.KeyB64 when set.
332 func buildSessionStore(cfg config.SessionConfig, logger *slog.Logger) (session.Store, error) {
333 keyB64 := os.Getenv("SHITHUB_SESSION_KEY")
334 if keyB64 == "" {
335 keyB64 = cfg.KeyB64
336 }
337 var key []byte
338 if keyB64 != "" {
339 decoded, err := base64.StdEncoding.DecodeString(keyB64)
340 if err != nil {
341 return nil, fmt.Errorf("session key: invalid base64: %w", err)
342 }
343 if len(decoded) != chacha20poly1305.KeySize {
344 return nil, fmt.Errorf("session key: must be %d bytes, got %d",
345 chacha20poly1305.KeySize, len(decoded))
346 }
347 key = decoded
348 } else {
349 generated, err := session.GenerateKey()
350 if err != nil {
351 return nil, fmt.Errorf("session key: generate: %w", err)
352 }
353 key = generated
354 logger.Warn(
355 "session: no key configured; generated an ephemeral key (sessions will not survive restart)",
356 "hint", "set SHITHUB_SESSION_KEY=<base64 32-byte> or session.key_b64 in production",
357 )
358 }
359 store, err := session.NewCookieStore(session.CookieStoreConfig{
360 Key: key,
361 MaxAge: cfg.MaxAge,
362 Secure: cfg.Secure,
363 })
364 if err != nil {
365 return nil, fmt.Errorf("session: build store: %w", err)
366 }
367 return store, nil
368 }
369