Go · 14022 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 Pool: pool,
149 CookieSecure: cfg.Session.Secure,
150 }
151 if pool != nil {
152 deps.ReadyCheck = func(ctx context.Context) error { return pool.Ping(ctx) }
153 }
154 if cfg.Metrics.Enabled {
155 deps.MetricsHandler = metrics.Handler(cfg.Metrics.BasicAuthUser, cfg.Metrics.BasicAuthPass)
156 }
157
158 if pool != nil {
159 objectStore, err := buildObjectStore(cfg.Storage.S3, logger)
160 if err != nil {
161 return fmt.Errorf("object store: %w", err)
162 }
163
164 auth, err := buildAuthHandlers(cfg, pool, sessionStore, objectStore, logger, deps.TemplatesFS)
165 if err != nil {
166 return fmt.Errorf("auth handlers: %w", err)
167 }
168 deps.AuthMounter = auth.Mount
169
170 var (
171 runnerJWT *runnerjwt.Signer
172 actionsBox *secretbox.Box
173 )
174 if cfg.Auth.TOTPKeyB64 != "" {
175 runnerJWT, err = runnerjwt.NewFromTOTPKeyB64(cfg.Auth.TOTPKeyB64)
176 if err != nil {
177 return fmt.Errorf("runner jwt: %w", err)
178 }
179 actionsBox, err = secretbox.FromBase64(cfg.Auth.TOTPKeyB64)
180 if err != nil {
181 return fmt.Errorf("actions secretbox: %w", err)
182 }
183 } else {
184 logger.Warn("actions runner API disabled: auth.totp_key_b64 is not configured",
185 "hint", "set SHITHUB_TOTP_KEY=$(openssl rand -base64 32) to enable runner job JWTs")
186 }
187 api, err := buildAPIHandlers(pool, objectStore, runnerJWT, actionsBox, ratelimit.New(pool), logger)
188 if err != nil {
189 return fmt.Errorf("api handlers: %w", err)
190 }
191 deps.APIMounter = api.Mount
192
193 profile, err := buildProfileHandlers(cfg, pool, objectStore, deps.TemplatesFS, logger)
194 if err != nil {
195 return fmt.Errorf("profile handlers: %w", err)
196 }
197 deps.AvatarMounter = profile.MountAvatars
198 deps.ProfileMounter = profile.MountProfile
199 deps.OrgRepositoriesMounter = profile.MountOrgRepositories
200
201 repoH, err := buildRepoHandlers(cfg, pool, objectStore, deps.TemplatesFS, logger)
202 if err != nil {
203 return fmt.Errorf("repo handlers: %w", err)
204 }
205 // /new is wrapped in RequireUser — it requires a logged-in caller.
206 deps.RepoNewMounter = func(r chi.Router) {
207 r.Group(func(r chi.Router) {
208 r.Use(middleware.RequireUser)
209 repoH.MountNew(r)
210 })
211 }
212 deps.RepoHomeMounter = repoH.MountRepoHome
213 deps.RepoCodeMounter = repoH.MountCode
214 deps.RepoHistoryMounter = repoH.MountHistory
215 deps.RepoRefsMounter = repoH.MountRefs
216 deps.RepoSettingsBranchesMounter = func(r chi.Router) {
217 r.Group(func(r chi.Router) {
218 r.Use(middleware.RequireUser)
219 repoH.MountSettingsBranches(r)
220 })
221 }
222 deps.RepoActionsAPIMounter = func(r chi.Router) {
223 r.Group(func(r chi.Router) {
224 r.Use(middleware.RequireUser)
225 repoH.MountRepoActionsAPI(r)
226 })
227 }
228 deps.RepoSettingsGeneralMounter = func(r chi.Router) {
229 r.Group(func(r chi.Router) {
230 r.Use(middleware.RequireUser)
231 repoH.MountSettingsGeneral(r)
232 })
233 }
234 deps.RepoSettingsActionsMounter = func(r chi.Router) {
235 r.Group(func(r chi.Router) {
236 r.Use(middleware.RequireUser)
237 repoH.MountSettingsActions(r)
238 })
239 }
240 deps.RepoWebhooksMounter = func(r chi.Router) {
241 r.Group(func(r chi.Router) {
242 r.Use(middleware.RequireUser)
243 repoH.MountWebhooks(r)
244 })
245 }
246 // Issues GETs are public (subject to policy.Can), POSTs require
247 // auth. The handler enforces auth + policy per request, so we
248 // register the whole surface in the public group; an unauth
249 // POST hits the policy gate and 404s out of the existence-leak
250 // path. Browser flows still need RequireUser to redirect-to-login,
251 // so the POST routes get wrapped through the same group with
252 // RequireUser inserted only for state-mutating verbs.
253 deps.RepoIssuesMounter = repoH.MountIssues
254 deps.RepoPullsMounter = repoH.MountPulls
255 deps.RepoSocialMounter = repoH.MountSocial
256 deps.RepoForkMounter = repoH.MountFork
257
258 // Search gets its own Limiter wired around /search +
259 // /search/quick (audit 2026-05-10 H4). Independent instance
260 // from auth's RateLimiter; both share DB-backed counter
261 // state, segregated by Policy.Scope.
262 searchH, err := buildSearchHandlers(pool, deps.TemplatesFS, logger, ratelimit.New(pool))
263 if err != nil {
264 return fmt.Errorf("search handlers: %w", err)
265 }
266 deps.SearchMounter = searchH.Mount
267
268 notifH, err := buildNotifHandlers(cfg, pool, deps.TemplatesFS, logger)
269 if err != nil {
270 return fmt.Errorf("notif handlers: %w", err)
271 }
272 deps.NotifInboxMounter = func(r chi.Router) {
273 r.Group(func(r chi.Router) {
274 r.Use(middleware.RequireUser)
275 notifH.MountAuthed(r)
276 })
277 }
278 deps.NotifPublicMounter = notifH.MountPublic
279
280 // S30 — orgs.
281 orgH, err := buildOrgHandlers(cfg, pool, objectStore, deps.TemplatesFS, logger)
282 if err != nil {
283 return fmt.Errorf("org handlers: %w", err)
284 }
285 deps.OrgCreateMounter = func(r chi.Router) {
286 r.Group(func(r chi.Router) {
287 r.Use(middleware.RequireUser)
288 orgH.MountCreate(r)
289 })
290 }
291 // /{org}/people: GETs are public (org existence is non-secret;
292 // member lists for private orgs are deferred). Mutations are
293 // owner-checked inside the handler, but RequireUser wraps the
294 // POST routes so unauth submits redirect to /login.
295 deps.OrgRoutesMounter = func(r chi.Router) {
296 r.Group(func(r chi.Router) {
297 orgH.MountOrgRoutes(r)
298 })
299 }
300 deps.OrgInvitationsMounter = func(r chi.Router) {
301 r.Group(func(r chi.Router) {
302 r.Use(middleware.RequireUser)
303 orgH.MountInvitations(r)
304 })
305 }
306
307 // Lifecycle danger-zone routes — also auth-required.
308 deps.RepoLifecycleMounter = func(r chi.Router) {
309 r.Group(func(r chi.Router) {
310 r.Use(middleware.RequireUser)
311 repoH.MountLifecycle(r)
312 })
313 }
314
315 // S34 — site admin. Gated by RequireUser + RequireSiteAdmin
316 // (404 not 403 for non-admins). Uses its own renderer so the
317 // admin templates are loaded once at boot.
318 //
319 // Email sender is the same one auth uses; the admin "Reset
320 // password" action sends through it (SR2 C3). Version is the
321 // build-time-stamped value so /admin/system reports reality
322 // instead of the literal "dev" (SR2 L6).
323 adminSender, err := pickEmailSender(cfg)
324 if err != nil {
325 return fmt.Errorf("admin handlers: pick email sender: %w", err)
326 }
327 adminH, err := buildAdminHandlers(cfg, pool, deps.TemplatesFS, logger, version.Version, adminSender)
328 if err != nil {
329 return fmt.Errorf("admin handlers: %w", err)
330 }
331 deps.AdminMounter = func(r chi.Router) {
332 r.Group(func(r chi.Router) {
333 r.Use(middleware.RequireUser)
334 r.Use(middleware.RequireSiteAdmin(nil)) // nil ⇒ http.NotFound
335 adminH.Mount(r)
336 })
337 }
338
339 gitHTTPH, err := buildGitHTTPHandlers(cfg, pool, logger)
340 if err != nil {
341 return fmt.Errorf("git-http handlers: %w", err)
342 }
343 deps.GitHTTPMounter = gitHTTPH.MountSmartHTTP
344 } else {
345 logger.Warn("auth: no DB pool — signup/login routes not mounted")
346 }
347
348 _, panicHandler, notFoundHandler, err := handlers.RegisterChi(r, deps)
349 if err != nil {
350 return fmt.Errorf("register handlers: %w", err)
351 }
352 r.NotFound(notFoundHandler)
353
354 rootHandler := middleware.Recover(logger, panicHandler)(r)
355
356 srv := &http.Server{
357 Addr: cfg.Web.Addr,
358 Handler: rootHandler,
359 ReadHeaderTimeout: 10 * time.Second,
360 ReadTimeout: cfg.Web.ReadTimeout,
361 WriteTimeout: cfg.Web.WriteTimeout,
362 IdleTimeout: 120 * time.Second,
363 }
364
365 errCh := make(chan error, 1)
366 go func() {
367 logger.Info(
368 "shithub web server starting",
369 "addr", srv.Addr,
370 "env", cfg.Env,
371 "db", pool != nil,
372 "metrics", cfg.Metrics.Enabled,
373 "tracing", cfg.Tracing.Enabled,
374 "errrep", cfg.ErrorReporting.DSN != "",
375 )
376 if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
377 errCh <- err
378 }
379 close(errCh)
380 }()
381
382 sigCh := make(chan os.Signal, 1)
383 signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
384 defer signal.Stop(sigCh)
385
386 select {
387 case err, ok := <-errCh:
388 if !ok {
389 return nil
390 }
391 return err
392 case sig := <-sigCh:
393 logger.Info("shutdown signal received", "signal", sig.String())
394 case <-ctx.Done():
395 logger.Info("context canceled, shutting down")
396 }
397
398 shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Web.ShutdownTimeout)
399 defer cancel()
400 if err := srv.Shutdown(shutdownCtx); err != nil {
401 return fmt.Errorf("shutdown: %w", err)
402 }
403 return nil
404 }
405
406 // buildSessionStore constructs the cookie session store from the config's
407 // session block. SHITHUB_SESSION_KEY (env) overrides cfg.KeyB64 when set.
408 func buildSessionStore(cfg config.SessionConfig, logger *slog.Logger) (session.Store, error) {
409 keyB64 := os.Getenv("SHITHUB_SESSION_KEY")
410 if keyB64 == "" {
411 keyB64 = cfg.KeyB64
412 }
413 var key []byte
414 if keyB64 != "" {
415 decoded, err := base64.StdEncoding.DecodeString(keyB64)
416 if err != nil {
417 return nil, fmt.Errorf("session key: invalid base64: %w", err)
418 }
419 if len(decoded) != chacha20poly1305.KeySize {
420 return nil, fmt.Errorf("session key: must be %d bytes, got %d",
421 chacha20poly1305.KeySize, len(decoded))
422 }
423 key = decoded
424 } else {
425 generated, err := session.GenerateKey()
426 if err != nil {
427 return nil, fmt.Errorf("session key: generate: %w", err)
428 }
429 key = generated
430 logger.Warn(
431 "session: no key configured; generated an ephemeral key (sessions will not survive restart)",
432 "hint", "set SHITHUB_SESSION_KEY=<base64 32-byte> or session.key_b64 in production",
433 )
434 }
435 store, err := session.NewCookieStore(session.CookieStoreConfig{
436 Key: key,
437 MaxAge: cfg.MaxAge,
438 Secure: cfg.Secure,
439 })
440 if err != nil {
441 return nil, fmt.Errorf("session: build store: %w", err)
442 }
443 return store, nil
444 }
445