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