internal/httpd/routes.go

b4684c088d2b99f0f42c4e95231c4c0edc122323
gitbay/internal/httpd/routes.go history · blame · raw

180 lines · 8798 bytes

  1package httpd
  2
  3import (
  4	"fmt"
  5	"net"
  6	"net/http"
  7	"strings"
  8)
  9
 10// Route is one entry in the explicit route table. The view-only guarantee is
 11// structural: Handler() consults web.mode when building the table, and the
 12// route test asserts no mutating route exists in view_only mode.
 13type Route struct {
 14	Method  string
 15	Pattern string // without method prefix
 16	// Mutating marks routes that can change server state. The git transport
 17	// POSTs are not mutating: upload-pack is a pure read, and the
 18	// receive-pack endpoint is a static refusal that writes nothing.
 19	Mutating bool
 20	Handler  http.HandlerFunc
 21}
 22
 23// Routes returns the route table for the configured web.mode.
 24func (s *Server) Routes() []Route {
 25	// Git smart transport (anonymous, public repos only).
 26	routes := []Route{
 27		{Method: "GET", Pattern: "/{owner}/{repo}/info/refs", Handler: s.infoRefs},
 28		{Method: "POST", Pattern: "/{owner}/{repo}/git-upload-pack", Handler: s.uploadPack},
 29		{Method: "POST", Pattern: "/{owner}/{repo}/git-receive-pack", Handler: s.receivePackRefusal},
 30		// Git LFS: token-authenticated transport (minted over SSH), not
 31		// web-session routes — anonymous download for public repos only.
 32		{Method: "POST", Pattern: "/{owner}/{repo}/info/lfs/objects/batch", Handler: s.lfsBatch},
 33		{Method: "GET", Pattern: "/{owner}/{repo}/info/lfs/objects/{oid}", Handler: s.lfsDownload},
 34		{Method: "PUT", Pattern: "/{owner}/{repo}/info/lfs/objects/{oid}", Handler: s.lfsUpload},
 35	}
 36
 37	// Web UI, read-only. These exist in every mode.
 38	routes = append(routes,
 39		Route{Method: "GET", Pattern: "/{$}", Handler: s.index},
 40		Route{Method: "GET", Pattern: "/explore", Handler: s.explore},
 41		Route{Method: "GET", Pattern: "/privacy", Handler: s.privacy},
 42		Route{Method: "GET", Pattern: "/static/style.css", Handler: s.stylesheet},
 43		Route{Method: "GET", Pattern: "/favicon.svg", Handler: s.favicon},
 44		Route{Method: "GET", Pattern: "/{owner}", Handler: s.ownerPage},
 45		Route{Method: "GET", Pattern: "/{owner}/{repo}", Handler: s.repoHome},
 46		Route{Method: "GET", Pattern: "/{owner}/{repo}/tree/{ref}/{path...}", Handler: s.tree},
 47		Route{Method: "GET", Pattern: "/{owner}/{repo}/blob/{ref}/{path...}", Handler: s.blob},
 48		Route{Method: "GET", Pattern: "/{owner}/{repo}/blame/{ref}/{path...}", Handler: s.blame},
 49		Route{Method: "GET", Pattern: "/{owner}/{repo}/search", Handler: s.search},
 50		Route{Method: "GET", Pattern: "/{owner}/{repo}/milestones", Handler: s.milestones},
 51		Route{Method: "GET", Pattern: "/{owner}/{repo}/wiki", Handler: s.wiki},
 52		Route{Method: "GET", Pattern: "/{owner}/{repo}/wiki/_raw/{path...}", Handler: s.wikiRaw},
 53		Route{Method: "GET", Pattern: "/{owner}/{repo}/wiki/{page}", Handler: s.wiki},
 54		Route{Method: "GET", Pattern: "/{owner}/{repo}/releases", Handler: s.releases},
 55		Route{Method: "GET", Pattern: "/{owner}/{repo}/builds", Handler: s.builds},
 56		Route{Method: "GET", Pattern: "/{owner}/{repo}/builds/{n}", Handler: s.build},
 57		Route{Method: "GET", Pattern: "/{owner}/{repo}/releases/download/{tag}/{name}", Handler: s.releaseAsset},
 58		Route{Method: "GET", Pattern: "/{owner}/{repo}/raw/{ref}/{path...}", Handler: s.raw},
 59		Route{Method: "GET", Pattern: "/{owner}/{repo}/log", Handler: s.log},
 60		Route{Method: "GET", Pattern: "/{owner}/{repo}/log/{ref}", Handler: s.log},
 61		Route{Method: "GET", Pattern: "/{owner}/{repo}/commit/{sha}", Handler: s.commit},
 62		Route{Method: "GET", Pattern: "/{owner}/{repo}/refs", Handler: s.refs},
 63		Route{Method: "GET", Pattern: "/{owner}/{repo}/archive/{file}", Handler: s.archive},
 64		Route{Method: "GET", Pattern: "/{owner}/{repo}/issues", Handler: s.issues},
 65		Route{Method: "GET", Pattern: "/{owner}/{repo}/issues/{n}", Handler: s.issue},
 66		Route{Method: "GET", Pattern: "/{owner}/{repo}/mrs", Handler: s.mrs},
 67		Route{Method: "GET", Pattern: "/{owner}/{repo}/mrs/{n}", Handler: s.mr},
 68	)
 69
 70	// The JSON API is its own opt-in surface, independent of web.mode.
 71	if s.cfg.API.Enabled {
 72		routes = append(routes,
 73			Route{Method: "POST", Pattern: "/api/v1/cmd", Mutating: true, Handler: s.apiCmd},
 74		)
 75	}
 76
 77	// Account-mode routes exist only when web.mode = "accounts". In
 78	// view_only they are never registered — the structural guarantee.
 79	if s.cfg.Web.Mode == "accounts" {
 80		routes = append(routes,
 81			Route{Method: "GET", Pattern: "/login", Handler: s.login, Mutating: true}, // consumes a one-time token
 82			Route{Method: "POST", Pattern: "/logout", Mutating: true,
 83				Handler: s.checkOrigin(s.logout)},
 84			Route{Method: "GET", Pattern: "/new", Handler: s.requireUser(s.newRepoForm)},
 85		)
 86		// Web signup fronts the same registration path as SSH register,
 87		// so it exists only when registration is open or invite.
 88		if s.cfg.Registration.Mode != "closed" {
 89			routes = append(routes,
 90				Route{Method: "GET", Pattern: "/register", Handler: s.signupForm},
 91				Route{Method: "POST", Pattern: "/register", Mutating: true,
 92					Handler: s.checkOrigin(s.signupSubmit)},
 93			)
 94		}
 95		routes = append(routes,
 96			Route{Method: "POST", Pattern: "/new", Mutating: true,
 97				Handler: s.checkOrigin(s.requireUser(s.newRepoSubmit))},
 98			Route{Method: "POST", Pattern: "/{owner}/{repo}/pin", Mutating: true,
 99				Handler: s.checkOrigin(s.requireUser(s.pinToggle))},
100			Route{Method: "GET", Pattern: "/{owner}/{repo}/issues/new",
101				Handler: s.requireUser(s.issueCreateForm)},
102			Route{Method: "POST", Pattern: "/{owner}/{repo}/issues/new", Mutating: true,
103				Handler: s.checkOrigin(s.requireUser(s.issueCreateSubmit))},
104			Route{Method: "POST", Pattern: "/{owner}/{repo}/issues/{n}/comment", Mutating: true,
105				Handler: s.checkOrigin(s.requireUser(s.issueCommentSubmit))},
106			Route{Method: "POST", Pattern: "/{owner}/{repo}/issues/{n}/edit", Mutating: true,
107				Handler: s.checkOrigin(s.requireUser(s.issueEditSubmit))},
108			Route{Method: "POST", Pattern: "/{owner}/{repo}/mrs/{n}/edit", Mutating: true,
109				Handler: s.checkOrigin(s.requireUser(s.mrEditSubmit))},
110			Route{Method: "POST", Pattern: "/{owner}/{repo}/mrs/{n}/comment", Mutating: true,
111				Handler: s.checkOrigin(s.requireUser(s.mrCommentSubmit))},
112			Route{Method: "GET", Pattern: "/{owner}/{repo}/edit/{ref}/{path...}",
113				Handler: s.requireUser(s.editForm)},
114			Route{Method: "POST", Pattern: "/{owner}/{repo}/edit/{ref}/{path...}", Mutating: true,
115				Handler: s.checkOrigin(s.requireUser(s.editSubmit))},
116		)
117	}
118	return routes
119}
120
121func (s *Server) Handler() http.Handler {
122	mux := http.NewServeMux()
123	for _, r := range s.Routes() {
124		mux.HandleFunc(r.Method+" "+r.Pattern, r.Handler)
125	}
126	var h http.Handler = mux
127	if len(s.cfg.GoImport) > 0 {
128		h = s.goImportHandler(mux)
129	}
130	// Always wrapped: custom pages domains work with or without the
131	// built-in [pages] domain.
132	return s.pagesRouter(s.securityHeaders(h))
133}
134
135// securityHeaders sets defensive response headers on every reply. The CSP
136// is strict where it can be: no scripts at all (the UI needs none), no
137// plugins, no embedding. Inline styles are allowed because label chips
138// carry their color inline (chroma is class-based so the syntax palette
139// can follow the color scheme). Images may load from anywhere so external README images
140// still render; they are the one thing a reader-facing forge can't police
141// without a proxy.
142func (s *Server) securityHeaders(next http.Handler) http.Handler {
143	const csp = "default-src 'self'; script-src 'none'; style-src 'self' 'unsafe-inline'; " +
144		"img-src * data:; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'"
145	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
146		hd := w.Header()
147		hd.Set("Content-Security-Policy", csp)
148		hd.Set("X-Frame-Options", "DENY")
149		hd.Set("X-Content-Type-Options", "nosniff")
150		hd.Set("Referrer-Policy", "no-referrer")
151		hd.Set("Cross-Origin-Opener-Policy", "same-origin")
152		if s.cfg.HTTP.TLS != "off" {
153			hd.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
154		}
155		next.ServeHTTP(w, r)
156	})
157}
158
159func (s *Server) goImportHandler(mux http.Handler) http.Handler {
160	// Vanity Go modules: ?go-get=1 requests under a configured module
161	// path answer with the go-import meta tag before normal routing.
162	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
163		if r.URL.Query().Get("go-get") == "1" {
164			host := r.Host
165			if h, _, err := net.SplitHostPort(host); err == nil {
166				host = h
167			}
168			requested := host + strings.TrimSuffix(r.URL.Path, "/")
169			for module, repo := range s.cfg.GoImport {
170				if requested == module || strings.HasPrefix(requested, module+"/") {
171					w.Header().Set("Content-Type", "text/html; charset=utf-8")
172					fmt.Fprintf(w, `<!DOCTYPE html><html><head><meta name="go-import" content="%s git %s/%s.git"></head><body>%s</body></html>`,
173						module, s.cfg.Server.SiteURL, repo, module)
174					return
175				}
176			}
177		}
178		mux.ServeHTTP(w, r)
179	})
180}