internal/httpd/routes.go

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

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