Go · 13987 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/runnerjwt"
27 "github.com/tenseleyFlow/shithub/internal/auth/secretbox"
28 "github.com/tenseleyFlow/shithub/internal/auth/session"
29 "github.com/tenseleyFlow/shithub/internal/infra/config"
30 "github.com/tenseleyFlow/shithub/internal/infra/db"
31 "github.com/tenseleyFlow/shithub/internal/infra/errrep"
32 infralog "github.com/tenseleyFlow/shithub/internal/infra/log"
33 "github.com/tenseleyFlow/shithub/internal/infra/metrics"
34 "github.com/tenseleyFlow/shithub/internal/infra/tracing"
35 "github.com/tenseleyFlow/shithub/internal/ratelimit"
36 "github.com/tenseleyFlow/shithub/internal/version"
37 "github.com/tenseleyFlow/shithub/internal/web/handlers"
38 "github.com/tenseleyFlow/shithub/internal/web/middleware"
39 )
40
41 // Options configures the web server. Addr overrides config when non-empty
42 // (preserves the existing --addr CLI flag behavior).
43 type Options struct {
44 Addr string
45 }
46
47 // Run boots the web server and blocks until shutdown.
48 func Run(ctx context.Context, opts Options) error {
49 cfg, err := config.Load(nil)
50 if err != nil {
51 return err
52 }
53 if opts.Addr != "" {
54 cfg.Web.Addr = opts.Addr
55 }
56
57 logger := infralog.New(infralog.Options{
58 Level: cfg.Log.Level,
59 Format: cfg.Log.Format,
60 Writer: os.Stderr,
61 })
62
63 // Error reporting (no-op when DSN empty).
64 flushErrRep, err := errrep.Init(errrep.Config{
65 DSN: cfg.ErrorReporting.DSN,
66 Environment: cfg.ErrorReporting.Environment,
67 Release: cfg.ErrorReporting.Release,
68 })
69 if err != nil {
70 return fmt.Errorf("errrep: %w", err)
71 }
72 defer func() { _ = flushErrRep(context.Background()) }()
73 if cfg.ErrorReporting.DSN != "" {
74 // Wrap the slog handler so error-level records are reported.
75 // We rebuild the logger so every component that pulls it from
76 // here gets the wrapped chain.
77 logger = slog.New(&errrep.SlogHandler{Inner: logger.Handler()})
78 }
79
80 // Tracing (no-op when disabled).
81 flushTracing, err := tracing.Init(ctx, tracing.Config{
82 Enabled: cfg.Tracing.Enabled,
83 Endpoint: cfg.Tracing.Endpoint,
84 SampleRate: cfg.Tracing.SampleRate,
85 ServiceName: cfg.Tracing.ServiceName,
86 })
87 if err != nil {
88 return fmt.Errorf("tracing: %w", err)
89 }
90 defer func() { _ = flushTracing(context.Background()) }()
91
92 logoBytes, err := LogoSVG()
93 if err != nil {
94 return fmt.Errorf("load logo: %w", err)
95 }
96
97 sessionStore, err := buildSessionStore(cfg.Session, logger)
98 if err != nil {
99 return err
100 }
101
102 // Optional DB pool (carried over from S01); now driven by config.
103 var pool *pgxpool.Pool
104 if cfg.DB.URL != "" {
105 //nolint:gosec // G115: max_conns is operator-configured with small numeric values (typ. 10–100).
106 p, err := db.Open(ctx, db.Config{
107 URL: cfg.DB.URL,
108 MaxConns: int32(cfg.DB.MaxConns),
109 MinConns: int32(cfg.DB.MinConns),
110 ConnectTimeout: cfg.DB.ConnectTimeout,
111 })
112 if err != nil {
113 logger.Warn("db: open failed; /readyz will report unhealthy", "error", err)
114 } else {
115 pool = p
116 defer p.Close()
117 metrics.ObserveDBPool(ctx, pool, 10*time.Second)
118 }
119 }
120
121 r := chi.NewRouter()
122
123 // Middleware stack — outermost first.
124 r.Use(middleware.RequestID)
125 r.Use(middleware.RealIP(middleware.RealIPConfig{}))
126 r.Use(middleware.AccessLog(logger))
127 r.Use(middleware.Metrics)
128 if cfg.Tracing.Enabled {
129 r.Use(tracing.Middleware)
130 }
131 r.Use(middleware.SecureHeaders(middleware.DefaultSecureHeaders()))
132 // Compress + Timeout are NOT global: the smart-HTTP git routes need
133 // to stream uncompressed pack data for many minutes. RegisterChi
134 // applies them inside the CSRF-exempt and CSRF-protected groups but
135 // skips the git group.
136 r.Use(middleware.SessionLoader(sessionStore, logger))
137 if pool != nil {
138 r.Use(middleware.OptionalUser(usernameLookup(pool)))
139 }
140 r.Use(middleware.PolicyCache())
141
142 deps := handlers.Deps{
143 Logger: logger,
144 TemplatesFS: TemplatesFS(),
145 StaticFS: StaticFS(),
146 LogoSVG: string(logoBytes),
147 SessionStore: sessionStore,
148 CookieSecure: cfg.Session.Secure,
149 }
150 if pool != nil {
151 deps.ReadyCheck = func(ctx context.Context) error { return pool.Ping(ctx) }
152 }
153 if cfg.Metrics.Enabled {
154 deps.MetricsHandler = metrics.Handler(cfg.Metrics.BasicAuthUser, cfg.Metrics.BasicAuthPass)
155 }
156
157 if pool != nil {
158 objectStore, err := buildObjectStore(cfg.Storage.S3, logger)
159 if err != nil {
160 return fmt.Errorf("object store: %w", err)
161 }
162
163 auth, err := buildAuthHandlers(cfg, pool, sessionStore, objectStore, logger, deps.TemplatesFS)
164 if err != nil {
165 return fmt.Errorf("auth handlers: %w", err)
166 }
167 deps.AuthMounter = auth.Mount
168
169 var (
170 runnerJWT *runnerjwt.Signer
171 actionsBox *secretbox.Box
172 )
173 if cfg.Auth.TOTPKeyB64 != "" {
174 runnerJWT, err = runnerjwt.NewFromTOTPKeyB64(cfg.Auth.TOTPKeyB64)
175 if err != nil {
176 return fmt.Errorf("runner jwt: %w", err)
177 }
178 actionsBox, err = secretbox.FromBase64(cfg.Auth.TOTPKeyB64)
179 if err != nil {
180 return fmt.Errorf("actions secretbox: %w", err)
181 }
182 } else {
183 logger.Warn("actions runner API disabled: auth.totp_key_b64 is not configured",
184 "hint", "set SHITHUB_TOTP_KEY=$(openssl rand -base64 32) to enable runner job JWTs")
185 }
186 api, err := buildAPIHandlers(pool, objectStore, runnerJWT, actionsBox, ratelimit.New(pool), logger)
187 if err != nil {
188 return fmt.Errorf("api handlers: %w", err)
189 }
190 deps.APIMounter = api.Mount
191
192 profile, err := buildProfileHandlers(cfg, pool, objectStore, deps.TemplatesFS, logger)
193 if err != nil {
194 return fmt.Errorf("profile handlers: %w", err)
195 }
196 deps.AvatarMounter = profile.MountAvatars
197 deps.ProfileMounter = profile.MountProfile
198 deps.OrgRepositoriesMounter = profile.MountOrgRepositories
199
200 repoH, err := buildRepoHandlers(cfg, pool, deps.TemplatesFS, logger)
201 if err != nil {
202 return fmt.Errorf("repo handlers: %w", err)
203 }
204 // /new is wrapped in RequireUser — it requires a logged-in caller.
205 deps.RepoNewMounter = func(r chi.Router) {
206 r.Group(func(r chi.Router) {
207 r.Use(middleware.RequireUser)
208 repoH.MountNew(r)
209 })
210 }
211 deps.RepoHomeMounter = repoH.MountRepoHome
212 deps.RepoCodeMounter = repoH.MountCode
213 deps.RepoHistoryMounter = repoH.MountHistory
214 deps.RepoRefsMounter = repoH.MountRefs
215 deps.RepoSettingsBranchesMounter = func(r chi.Router) {
216 r.Group(func(r chi.Router) {
217 r.Use(middleware.RequireUser)
218 repoH.MountSettingsBranches(r)
219 })
220 }
221 deps.RepoActionsAPIMounter = func(r chi.Router) {
222 r.Group(func(r chi.Router) {
223 r.Use(middleware.RequireUser)
224 repoH.MountRepoActionsAPI(r)
225 })
226 }
227 deps.RepoSettingsGeneralMounter = func(r chi.Router) {
228 r.Group(func(r chi.Router) {
229 r.Use(middleware.RequireUser)
230 repoH.MountSettingsGeneral(r)
231 })
232 }
233 deps.RepoSettingsActionsMounter = func(r chi.Router) {
234 r.Group(func(r chi.Router) {
235 r.Use(middleware.RequireUser)
236 repoH.MountSettingsActions(r)
237 })
238 }
239 deps.RepoWebhooksMounter = func(r chi.Router) {
240 r.Group(func(r chi.Router) {
241 r.Use(middleware.RequireUser)
242 repoH.MountWebhooks(r)
243 })
244 }
245 // Issues GETs are public (subject to policy.Can), POSTs require
246 // auth. The handler enforces auth + policy per request, so we
247 // register the whole surface in the public group; an unauth
248 // POST hits the policy gate and 404s out of the existence-leak
249 // path. Browser flows still need RequireUser to redirect-to-login,
250 // so the POST routes get wrapped through the same group with
251 // RequireUser inserted only for state-mutating verbs.
252 deps.RepoIssuesMounter = repoH.MountIssues
253 deps.RepoPullsMounter = repoH.MountPulls
254 deps.RepoSocialMounter = repoH.MountSocial
255 deps.RepoForkMounter = repoH.MountFork
256
257 // Search gets its own Limiter wired around /search +
258 // /search/quick (audit 2026-05-10 H4). Independent instance
259 // from auth's RateLimiter; both share DB-backed counter
260 // state, segregated by Policy.Scope.
261 searchH, err := buildSearchHandlers(pool, deps.TemplatesFS, logger, ratelimit.New(pool))
262 if err != nil {
263 return fmt.Errorf("search handlers: %w", err)
264 }
265 deps.SearchMounter = searchH.Mount
266
267 notifH, err := buildNotifHandlers(cfg, pool, deps.TemplatesFS, logger)
268 if err != nil {
269 return fmt.Errorf("notif handlers: %w", err)
270 }
271 deps.NotifInboxMounter = func(r chi.Router) {
272 r.Group(func(r chi.Router) {
273 r.Use(middleware.RequireUser)
274 notifH.MountAuthed(r)
275 })
276 }
277 deps.NotifPublicMounter = notifH.MountPublic
278
279 // S30 — orgs.
280 orgH, err := buildOrgHandlers(cfg, pool, objectStore, deps.TemplatesFS, logger)
281 if err != nil {
282 return fmt.Errorf("org handlers: %w", err)
283 }
284 deps.OrgCreateMounter = func(r chi.Router) {
285 r.Group(func(r chi.Router) {
286 r.Use(middleware.RequireUser)
287 orgH.MountCreate(r)
288 })
289 }
290 // /{org}/people: GETs are public (org existence is non-secret;
291 // member lists for private orgs are deferred). Mutations are
292 // owner-checked inside the handler, but RequireUser wraps the
293 // POST routes so unauth submits redirect to /login.
294 deps.OrgRoutesMounter = func(r chi.Router) {
295 r.Group(func(r chi.Router) {
296 orgH.MountOrgRoutes(r)
297 })
298 }
299 deps.OrgInvitationsMounter = func(r chi.Router) {
300 r.Group(func(r chi.Router) {
301 r.Use(middleware.RequireUser)
302 orgH.MountInvitations(r)
303 })
304 }
305
306 // Lifecycle danger-zone routes — also auth-required.
307 deps.RepoLifecycleMounter = func(r chi.Router) {
308 r.Group(func(r chi.Router) {
309 r.Use(middleware.RequireUser)
310 repoH.MountLifecycle(r)
311 })
312 }
313
314 // S34 — site admin. Gated by RequireUser + RequireSiteAdmin
315 // (404 not 403 for non-admins). Uses its own renderer so the
316 // admin templates are loaded once at boot.
317 //
318 // Email sender is the same one auth uses; the admin "Reset
319 // password" action sends through it (SR2 C3). Version is the
320 // build-time-stamped value so /admin/system reports reality
321 // instead of the literal "dev" (SR2 L6).
322 adminSender, err := pickEmailSender(cfg)
323 if err != nil {
324 return fmt.Errorf("admin handlers: pick email sender: %w", err)
325 }
326 adminH, err := buildAdminHandlers(cfg, pool, deps.TemplatesFS, logger, version.Version, adminSender)
327 if err != nil {
328 return fmt.Errorf("admin handlers: %w", err)
329 }
330 deps.AdminMounter = func(r chi.Router) {
331 r.Group(func(r chi.Router) {
332 r.Use(middleware.RequireUser)
333 r.Use(middleware.RequireSiteAdmin(nil)) // nil ⇒ http.NotFound
334 adminH.Mount(r)
335 })
336 }
337
338 gitHTTPH, err := buildGitHTTPHandlers(cfg, pool, logger)
339 if err != nil {
340 return fmt.Errorf("git-http handlers: %w", err)
341 }
342 deps.GitHTTPMounter = gitHTTPH.MountSmartHTTP
343 } else {
344 logger.Warn("auth: no DB pool — signup/login routes not mounted")
345 }
346
347 _, panicHandler, notFoundHandler, err := handlers.RegisterChi(r, deps)
348 if err != nil {
349 return fmt.Errorf("register handlers: %w", err)
350 }
351 r.NotFound(notFoundHandler)
352
353 rootHandler := middleware.Recover(logger, panicHandler)(r)
354
355 srv := &http.Server{
356 Addr: cfg.Web.Addr,
357 Handler: rootHandler,
358 ReadHeaderTimeout: 10 * time.Second,
359 ReadTimeout: cfg.Web.ReadTimeout,
360 WriteTimeout: cfg.Web.WriteTimeout,
361 IdleTimeout: 120 * time.Second,
362 }
363
364 errCh := make(chan error, 1)
365 go func() {
366 logger.Info(
367 "shithub web server starting",
368 "addr", srv.Addr,
369 "env", cfg.Env,
370 "db", pool != nil,
371 "metrics", cfg.Metrics.Enabled,
372 "tracing", cfg.Tracing.Enabled,
373 "errrep", cfg.ErrorReporting.DSN != "",
374 )
375 if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
376 errCh <- err
377 }
378 close(errCh)
379 }()
380
381 sigCh := make(chan os.Signal, 1)
382 signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
383 defer signal.Stop(sigCh)
384
385 select {
386 case err, ok := <-errCh:
387 if !ok {
388 return nil
389 }
390 return err
391 case sig := <-sigCh:
392 logger.Info("shutdown signal received", "signal", sig.String())
393 case <-ctx.Done():
394 logger.Info("context canceled, shutting down")
395 }
396
397 shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Web.ShutdownTimeout)
398 defer cancel()
399 if err := srv.Shutdown(shutdownCtx); err != nil {
400 return fmt.Errorf("shutdown: %w", err)
401 }
402 return nil
403 }
404
405 // buildSessionStore constructs the cookie session store from the config's
406 // session block. SHITHUB_SESSION_KEY (env) overrides cfg.KeyB64 when set.
407 func buildSessionStore(cfg config.SessionConfig, logger *slog.Logger) (session.Store, error) {
408 keyB64 := os.Getenv("SHITHUB_SESSION_KEY")
409 if keyB64 == "" {
410 keyB64 = cfg.KeyB64
411 }
412 var key []byte
413 if keyB64 != "" {
414 decoded, err := base64.StdEncoding.DecodeString(keyB64)
415 if err != nil {
416 return nil, fmt.Errorf("session key: invalid base64: %w", err)
417 }
418 if len(decoded) != chacha20poly1305.KeySize {
419 return nil, fmt.Errorf("session key: must be %d bytes, got %d",
420 chacha20poly1305.KeySize, len(decoded))
421 }
422 key = decoded
423 } else {
424 generated, err := session.GenerateKey()
425 if err != nil {
426 return nil, fmt.Errorf("session key: generate: %w", err)
427 }
428 key = generated
429 logger.Warn(
430 "session: no key configured; generated an ephemeral key (sessions will not survive restart)",
431 "hint", "set SHITHUB_SESSION_KEY=<base64 32-byte> or session.key_b64 in production",
432 )
433 }
434 store, err := session.NewCookieStore(session.CookieStoreConfig{
435 Key: key,
436 MaxAge: cfg.MaxAge,
437 Secure: cfg.Secure,
438 })
439 if err != nil {
440 return nil, fmt.Errorf("session: build store: %w", err)
441 }
442 return store, nil
443 }
444