internal/httpd/routes.go

617b05d09be747ad310179ce5432dec98ebe2c17
gitbay/internal/httpd/routes.go history · blame · raw

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