internal/httpd/accounts.go

ac8d910ff31c2fadc452928e1d56c64b4af25495
gitbay/internal/httpd/accounts.go

832 lines · 28170 bytes

  1package httpd
  2
  3import (
  4	"fmt"
  5	"html/template"
  6	"log"
  7	"net/http"
  8	"net/url"
  9	"path"
 10	"slices"
 11	"strconv"
 12	"strings"
 13	"time"
 14
 15	gossh "golang.org/x/crypto/ssh"
 16
 17	"gitbay.org/gitbay/internal/control"
 18	"gitbay.org/gitbay/internal/gitutil"
 19	"gitbay.org/gitbay/internal/policy"
 20	"gitbay.org/gitbay/internal/protocol"
 21	"gitbay.org/gitbay/internal/store"
 22)
 23
 24const sessionCookie = "gitbay_session"
 25
 26// sessionSameSite is Lax so a login link followed from a mail client keeps
 27// its session through the redirect. Cross-site POSTs are refused by
 28// checkOrigin and carry no Lax cookie anyway.
 29const sessionSameSite = http.SameSiteLaxMode
 30
 31// badLoginToken is what every refused /login?token= gets, whatever the
 32// reason. The reasons differ in whether the account exists.
 33const badLoginToken = "that login link is invalid, expired, or already used — mint a new one"
 34
 35// viewer returns the logged-in user, or a zero User for anonymous visitors.
 36// Only meaningful in accounts mode; in view_only no session route exists so
 37// every request is anonymous.
 38func (s *Server) viewer(r *http.Request) store.User {
 39	ck, err := r.Cookie(sessionCookie)
 40	if err != nil {
 41		return store.User{}
 42	}
 43	u, err := s.st.WebSessionUser(store.HashToken(ck.Value))
 44	if err != nil {
 45		return store.User{}
 46	}
 47	return u
 48}
 49
 50// requireUser wraps a handler that needs a session.
 51func (s *Server) requireUser(h func(http.ResponseWriter, *http.Request, store.User)) http.HandlerFunc {
 52	return func(w http.ResponseWriter, r *http.Request) {
 53		u := s.viewer(r)
 54		if u.ID == 0 {
 55			if r.Method == http.MethodGet {
 56				s.setNext(w, r.URL.RequestURI())
 57			}
 58			http.Redirect(w, r, "/login", http.StatusSeeOther)
 59			return
 60		}
 61		h(w, r, u)
 62	}
 63}
 64
 65// checkOrigin rejects cross-site POSTs. It is the primary CSRF defense:
 66// sessions use SameSite=Lax, which withholds the cookie from a cross-site
 67// POST but not from a cross-site top-level GET.
 68func (s *Server) checkOrigin(h http.HandlerFunc) http.HandlerFunc {
 69	return func(w http.ResponseWriter, r *http.Request) {
 70		if origin := r.Header.Get("Origin"); origin != "" && origin != "null" {
 71			host := strings.TrimPrefix(strings.TrimPrefix(origin, "https://"), "http://")
 72			if host != r.Host {
 73				http.Error(w, "cross-origin request refused", http.StatusForbidden)
 74				return
 75			}
 76		}
 77		h(w, r)
 78	}
 79}
 80
 81// renderLogin draws the login page. Mode carries the registration mode so
 82// the page can tell a brand-new visitor how to get an account. EmailLogin
 83// says whether this instance can mail a link; Sent switches the page to the
 84// confirmation that follows a request.
 85func (s *Server) renderLogin(w http.ResponseWriter, errMsg string, sent bool, next string) {
 86	s.render(w, "login.html", struct {
 87		basePage
 88		Mode       string // closed | invite | open
 89		Error      string
 90		EmailLogin bool
 91		Sent       bool
 92		Next       string
 93	}{s.anonBase(),
 94		s.cfg.Registration.Mode, errMsg, s.emailLoginEnabled(), sent, next})
 95}
 96
 97// emailLoginEnabled reports whether a link can be mailed at all. There is no
 98// separate switch: the capability is exactly the SMTP the instance already
 99// configured for verification and notification mail.
100func (s *Server) emailLoginEnabled() bool {
101	return s.cfg.Web.Mode == "accounts" && s.cfg.Mail.SMTPHost != ""
102}
103
104// loginSubmit mails a one-time login link. The response is the same page
105// whatever happened, including when nothing happened.
106func (s *Server) loginSubmit(w http.ResponseWriter, r *http.Request) {
107	if !s.emailLoginEnabled() {
108		s.notFound(w, r)
109		return
110	}
111	// The per-account bound lives in the store and survives a restart; this
112	// one stops a single source from spending every account's budget.
113	if allowed, wait := s.apiLimit.allow("login"+s.clientIP(r), true); !allowed {
114		w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1))
115		http.Error(w, "too many login requests; wait a moment", http.StatusTooManyRequests)
116		return
117	}
118	if err := control.RequestLoginLink(s.cfg, s.st, r.FormValue("identifier")); err != nil {
119		log.Printf("login link: %v", err)
120	}
121	s.renderLogin(w, "", true, "")
122}
123
124func (s *Server) login(w http.ResponseWriter, r *http.Request) {
125	// token, when present, is a single-use secret in the query string —
126	// the documented exception to "never in a URL" (Threat-Model). No
127	// cache may keep a copy of this response.
128	w.Header().Set("Cache-Control", "no-store")
129	token := r.URL.Query().Get("token")
130	if token == "" {
131		s.renderLogin(w, "", false, s.peekNext(r))
132		return
133	}
134	userID, err := s.st.ConsumeLoginToken(store.HashToken(token))
135	if err != nil {
136		s.renderLogin(w, badLoginToken, false, "")
137		return
138	}
139	// A token minted before the account was suspended is still consumable,
140	// and the session it would create renders every page the account can
141	// read. Checking here covers every mint path. The message is the one a
142	// bad token gets: a distinct one would confirm the account exists.
143	// A login is how the owner of an account scheduled for deletion
144	// cancels it.
145	u, err := s.st.UserByID(userID)
146	if err == nil {
147		control.CancelScheduledDeletion(s.st, &u, "web")
148	}
149	if err != nil || u.Disabled {
150		s.renderLogin(w, badLoginToken, false, "")
151		return
152	}
153	sessTok, sessHash, err := store.NewToken()
154	if err != nil {
155		http.Error(w, "internal error", http.StatusInternalServerError)
156		return
157	}
158	// Seven days is the cap; the store ends it sooner after
159	// store.WebSessionIdle without a request.
160	if err := s.st.CreateWebSession(sessHash, userID, 7*24*time.Hour); err != nil {
161		http.Error(w, "internal error", http.StatusInternalServerError)
162		return
163	}
164	http.SetCookie(w, s.sessionCookieFor(sessTok))
165	dest := s.takeNext(w, r)
166	if dest == "" {
167		dest = "/"
168	}
169	http.Redirect(w, r, dest, http.StatusSeeOther)
170}
171
172// sessionCookieFor is the cookie a new session ships in. Secure follows TLS
173// the way clearCookie does, so a plain-HTTP deployment still works.
174func (s *Server) sessionCookieFor(tok string) *http.Cookie {
175	return &http.Cookie{
176		Name: sessionCookie, Value: tok, Path: "/",
177		HttpOnly: true, SameSite: sessionSameSite,
178		Secure: s.cfg.HTTP.TLS != "off",
179		MaxAge: 7 * 24 * 3600,
180	}
181}
182
183// logoutForm is GET /logout: the confirmation the rail's signout square
184// and the More menu link to, so the session does not end on one stray
185// click. The button posts to the same path.
186func (s *Server) logoutForm(w http.ResponseWriter, r *http.Request, u store.User) {
187	s.render(w, "logout.html", struct {
188		basePage
189	}{s.baseFor(u)})
190}
191
192func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
193	if ck, err := r.Cookie(sessionCookie); err == nil {
194		s.st.DeleteWebSession(store.HashToken(ck.Value))
195	}
196	http.SetCookie(w, s.clearCookie(sessionCookie, sessionSameSite))
197	http.Redirect(w, r, "/", http.StatusSeeOther)
198}
199
200// adminOrgs lists organizations the user administers, for owner pickers.
201func (s *Server) adminOrgs(u store.User) []string {
202	var out []string
203	if orgs, err := s.st.ListOrgsForUser(u.ID); err == nil {
204		for _, o := range orgs {
205			if o.Role == "admin" {
206				out = append(out, o.Username)
207			}
208		}
209	}
210	return out
211}
212
213func (s *Server) renderNewRepo(w http.ResponseWriter, u store.User, errMsg string, submitted url.Values) {
214	// A refused import keeps what was typed, except the token.
215	panel := "create"
216	switch submitted.Get("field") {
217	case "import":
218		panel = "import"
219	case "org-create":
220		panel = "org"
221	}
222	subm := map[string]string{
223		"owner": submitted.Get("owner"), "name": submitted.Get("name"),
224		"from": submitted.Get("from"), "visibility": submitted.Get("visibility"),
225		"panel": panel,
226	}
227	s.render(w, "new.html", struct {
228		basePage
229		Orgs      []string
230		Error     string
231		Submitted map[string]string
232	}{s.baseFor(u), s.adminOrgs(u), errMsg, subm})
233}
234
235func (s *Server) newRepoForm(w http.ResponseWriter, r *http.Request, u store.User) {
236	s.renderNewRepo(w, u, "", nil)
237}
238
239// newSubmit creates a repository or an organization: /new carries both
240// forms, told apart by the org form's field. An organization's page is
241// the redirect, the same as org-create from anywhere else.
242func (s *Server) newSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
243	r.ParseForm()
244	if r.FormValue("field") == "org-create" {
245		name := strings.TrimSpace(r.FormValue("name"))
246		if _, msg, ok := s.runControl(u, []string{"org", "create", name}); !ok {
247			s.renderNewRepo(w, u, msg, r.Form)
248			return
249		}
250		http.Redirect(w, r, "/"+name, http.StatusSeeOther)
251		return
252	}
253	owner := r.FormValue("owner")
254	if owner == "" {
255		owner = u.Username
256	}
257	name := r.FormValue("name")
258	if r.FormValue("field") == "import" {
259		// The token, if any, reaches the command on stdin only.
260		argv := []string{"repo", "import", owner + "/" + name, "--from", strings.TrimSpace(r.FormValue("from"))}
261		if r.FormValue("visibility") == "private" {
262			argv = append(argv, "--private")
263		}
264		var stdin string
265		if tok := strings.TrimSpace(r.FormValue("token")); tok != "" {
266			argv = append(argv, "--token-stdin")
267			stdin = tok + "\n"
268		}
269		if msg, ok := s.runControlStdin(u, argv, stdin); !ok {
270			s.renderNewRepo(w, u, msg, r.Form)
271			return
272		}
273		http.Redirect(w, r, "/"+owner+"/"+name, http.StatusSeeOther)
274		return
275	}
276	argv := []string{"repo", "create", owner + "/" + name}
277	if r.FormValue("visibility") == "private" {
278		argv = append(argv, "--private")
279	}
280	if _, msg, ok := s.runControl(u, argv); !ok {
281		s.renderNewRepo(w, u, msg, r.Form)
282		return
283	}
284	http.Redirect(w, r, "/"+owner+"/"+name, http.StatusSeeOther)
285}
286
287// safeReturnTo returns a same-origin path from Referer when it lives under
288// prefix, falling back to prefix itself so toggling a repo-header button on
289// a subpage (/issues/42, /mrs/10) stays on that subpage.
290func safeReturnTo(r *http.Request, fallback string) string {
291	ref := r.Header.Get("Referer")
292	if ref == "" {
293		return fallback
294	}
295	u, err := url.Parse(ref)
296	if err != nil {
297		return fallback
298	}
299	if u.Host != "" && u.Host != r.Host {
300		return fallback
301	}
302	dest := u.RequestURI()
303	if !localPath(dest) || len(dest) > 300 {
304		return fallback
305	}
306	if dest == fallback || strings.HasPrefix(dest, fallback+"/") || strings.HasPrefix(dest, fallback+"?") {
307		return dest
308	}
309	return fallback
310}
311
312// pinToggle pins or unpins the repo for the logged-in viewer, through
313// repo pin/repo unpin — the same commands the CLI runs — rather than
314// writing the store directly (#261).
315func (s *Server) pinToggle(w http.ResponseWriter, r *http.Request, u store.User) {
316	repo, ok := s.repoForUser(w, r, u, policy.CanRead)
317	if !ok {
318		return
319	}
320	verb := "pin"
321	if s.st.IsPinned(u.ID, repo.ID) {
322		verb = "unpin"
323	}
324	if _, msg, ok := s.runControl(u, []string{"repo", verb, repo.Path()}); !ok {
325		s.setFlash(w, msg)
326	}
327	http.Redirect(w, r, safeReturnTo(r, "/"+repo.Path()), http.StatusSeeOther)
328}
329
330// bookmarkToggle saves or unsaves a repository for the viewer. Read
331// access is all a bookmark needs — it is something you do to someone
332// else's repository — and repoForUser 404s a private one either way.
333func (s *Server) bookmarkToggle(w http.ResponseWriter, r *http.Request, u store.User) {
334	repo, ok := s.repoForUser(w, r, u, policy.CanRead)
335	if !ok {
336		return
337	}
338	verb := "bookmark"
339	if s.st.IsBookmarked(u.ID, repo.ID) {
340		verb = "unbookmark"
341	}
342	if _, msg, ok := s.runControl(u, []string{"repo", verb, repo.Path()}); !ok {
343		s.setFlash(w, msg)
344	}
345	http.Redirect(w, r, safeReturnTo(r, "/"+repo.Path()), http.StatusSeeOther)
346}
347
348// bookmarksPage lists what the viewer has saved.
349// bookmarksPage keeps /bookmarks working: the list is a tab on the
350// viewer's own profile now, so there is one page of it rather than two
351// showing the same rows.
352func (s *Server) bookmarksPage(w http.ResponseWriter, r *http.Request, u store.User) {
353	http.Redirect(w, r, "/"+u.Username+"/-/bookmarks", http.StatusSeeOther)
354}
355
356// renderFork draws the fork form: where the copy lands and what it is
357// called. owner and name are what the field should hold, which after a
358// refusal is what was submitted.
359func (s *Server) renderFork(w http.ResponseWriter, u store.User, repo store.Repo, owner, name, errMsg string) {
360	s.render(w, "fork.html", struct {
361		basePage
362		Repo  store.Repo
363		Orgs  []string
364		Owner string
365		Name  string
366		Error string
367	}{s.baseFor(u), repo, s.adminOrgs(u), owner, name, errMsg})
368}
369
370func (s *Server) forkForm(w http.ResponseWriter, r *http.Request, u store.User) {
371	repo, ok := s.repoForUser(w, r, u, policy.CanRead)
372	if !ok {
373		return
374	}
375	s.renderFork(w, u, repo, u.Username, repo.Name, "")
376}
377
378// forkSubmit forks the repository to the owner the form picked and sends
379// them to it. The command decides everything that matters — read access,
380// the right to create under that owner, quota, name collisions — so a
381// refusal comes back as its own message on the form (#174).
382func (s *Server) forkSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
383	repo, ok := s.repoForUser(w, r, u, policy.CanRead)
384	if !ok {
385		return
386	}
387	owner, name := r.FormValue("owner"), r.FormValue("name")
388	if owner == "" {
389		owner = u.Username
390	}
391	if name == "" {
392		name = repo.Name
393	}
394	var fork control.ForkOut
395	argv := []string{"repo", "fork", repo.Path(), "--owner", owner, "--name", name}
396	if msg, ok := s.runControlInto(u, argv, &fork); !ok {
397		s.renderFork(w, u, repo, owner, name, msg)
398		return
399	}
400	http.Redirect(w, r, "/"+fork.Path, http.StatusSeeOther)
401}
402
403// repoForUser is repoFor with a write/read permission requirement for a
404// logged-in user.
405func (s *Server) repoForUser(w http.ResponseWriter, r *http.Request, u store.User,
406	perm func(store.User, store.Repo, string) bool) (store.Repo, bool) {
407	repo, err := s.st.RepoByPath(r.PathValue("owner") + "/" + r.PathValue("repo"))
408	if err != nil {
409		http.NotFound(w, r)
410		return store.Repo{}, false
411	}
412	grant, err := s.st.AccessRole(repo.ID, u.ID)
413	if err != nil {
414		http.Error(w, "internal error", http.StatusInternalServerError)
415		return store.Repo{}, false
416	}
417	if !policy.CanRead(u, repo, grant) {
418		http.NotFound(w, r) // invisible: same as nonexistent
419		return store.Repo{}, false
420	}
421	if !perm(u, repo, grant) {
422		http.Error(w, "permission denied", http.StatusForbidden)
423		return store.Repo{}, false
424	}
425	return repo, true
426}
427
428// signupForm and signupSubmit front the SSH registration path for open
429// and invite instances: same store transactions, same rules, a pasted
430// public key instead of the connecting one.
431func (s *Server) signupForm(w http.ResponseWriter, r *http.Request) {
432	s.renderSignup(w, "", "")
433}
434
435func (s *Server) renderSignup(w http.ResponseWriter, errMsg, username string) {
436	s.render(w, "register.html", struct {
437		basePage
438		Host     string
439		Mode     string // open | invite
440		Error    string
441		Username string
442	}{s.anonBase(), s.cfg.SiteHost(), s.cfg.Registration.Mode, errMsg, username})
443}
444
445func (s *Server) signupSubmit(w http.ResponseWriter, r *http.Request) {
446	username := strings.TrimSpace(r.FormValue("username"))
447	keyText := strings.TrimSpace(r.FormValue("key"))
448	pub, _, _, _, err := gossh.ParseAuthorizedKey([]byte(keyText))
449	if err != nil {
450		s.renderSignup(w, "that does not parse as an SSH public key (expected e.g. \"ssh-ed25519 AAAA... comment\")", username)
451		return
452	}
453	msg, errMsg, code := control.RegisterAccount(s.cfg, s.st, pub, username,
454		strings.TrimSpace(r.FormValue("email")), strings.TrimSpace(r.FormValue("invite")))
455	if code != 0 {
456		s.renderSignup(w, errMsg, username)
457		return
458	}
459	s.render(w, "registered.html", struct {
460		basePage
461		Username string
462		Message  string
463		Host     string
464		Mode     string
465		Error    string
466	}{s.anonBase(), username, msg, s.cfg.SiteHost(), s.cfg.Registration.Mode, ""})
467}
468
469func (s *Server) signupVerifySubmit(w http.ResponseWriter, r *http.Request) {
470	if allowed, wait := s.apiLimit.allow("regverify"+s.clientIP(r), true); !allowed {
471		w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1))
472		http.Error(w, "too many verification attempts; wait a moment", http.StatusTooManyRequests)
473		return
474	}
475	username := strings.TrimSpace(r.FormValue("username"))
476	code := strings.TrimSpace(r.FormValue("code"))
477	u, errMsg := control.VerifyPendingSignup(s.cfg, s.st, username, code)
478	if errMsg != "" {
479		s.render(w, "registered.html", struct {
480			basePage
481			Username string
482			Message  string
483			Host     string
484			Mode     string
485			Error    string
486		}{s.anonBase(), username, "Check your inbox for the verification code.", s.cfg.SiteHost(), s.cfg.Registration.Mode, errMsg})
487		return
488	}
489	sessTok, sessHash, err := store.NewToken()
490	if err != nil {
491		http.Error(w, "internal error", http.StatusInternalServerError)
492		return
493	}
494	if err := s.st.CreateWebSession(sessHash, u.ID, 7*24*time.Hour); err != nil {
495		http.Error(w, "internal error", http.StatusInternalServerError)
496		return
497	}
498	http.SetCookie(w, s.sessionCookieFor(sessTok))
499	http.Redirect(w, r, "/", http.StatusSeeOther)
500}
501
502// issueNewPage is what the new-issue form renders with, whether that is a
503// fresh form, a Preview round trip, or a refused create — each keeps
504// whatever the visitor typed (#271).
505type issueNewPage struct {
506	repoPage
507	Body      string
508	Format    string
509	Title     string
510	Labels    string
511	Milestone string
512	Assignee  string
513	Template  string
514	Templates []control.IssueTemplate
515	Draft     *draft
516	CanWrite  bool
517	Notice    string
518}
519
520// issueCreateForm renders the new-issue form, prefilled from the repo's
521// default issue template when one exists. A Preview submit comes back
522// here with the draft in the form, so the page returns with everything
523// still typed and the rendering above the textarea (#235).
524func (s *Server) issueCreateForm(w http.ResponseWriter, r *http.Request, u store.User) {
525	p, ok := s.repoFor(w, r, "")
526	if !ok {
527		return
528	}
529	p.Tab = "issues"
530	if wantsPreview(r) {
531		d := s.draftFor(r, p.Repo, "body", "body", bodyFormat(r))
532		s.render(w, "issuenew.html", issueNewPage{
533			repoPage: p, Body: d.Body, Format: d.Format, Title: r.FormValue("title"),
534			Labels: r.FormValue("labels"), Milestone: r.FormValue("milestone"), Assignee: r.FormValue("assignee"),
535			Templates: control.IssueTemplates(p.Dir, p.Repo.DefaultBranch), Draft: d, CanWrite: s.canWriteRepoAs(u, p.Repo),
536		})
537		return
538	}
539	templates := control.IssueTemplates(p.Dir, p.Repo.DefaultBranch)
540	body, tplName := "", ""
541	if want := r.URL.Query().Get("template"); want != "" {
542		for _, t := range templates {
543			if t.Name == want {
544				body, tplName = t.Body, t.Name
545			}
546		}
547	} else {
548		for _, t := range templates {
549			if t.Name == "issue-template.md" || body == "" {
550				body, tplName = t.Body, t.Name
551			}
552			if t.Name == "issue-template.md" {
553				break
554			}
555		}
556	}
557	format := r.URL.Query().Get("format")
558	if format != "org" {
559		format = "md"
560	}
561	s.render(w, "issuenew.html", issueNewPage{
562		repoPage: p, Body: body, Format: format, Template: tplName, Templates: templates,
563		CanWrite: s.canWriteRepoAs(u, p.Repo),
564	})
565}
566
567// Issue and merge request writes run the command the CLI runs, so the
568// archived check, notifications, body format and the audit entry have one
569// implementation. Bodies travel on stdin, the way --file - does.
570
571func (s *Server) issueCreateSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
572	p, ok := s.repoFor(w, r, "")
573	if !ok {
574		return
575	}
576	repoPath := p.Repo.Path()
577	title := strings.TrimSpace(r.FormValue("title"))
578	format := bodyFormat(r)
579	if wantsPreview(r) {
580		s.issueCreateForm(w, r, u)
581		return
582	}
583	canWrite := s.canWriteRepoAs(u, p.Repo)
584	var created control.Created
585	argv := []string{"issue", "create", repoPath, "--title", title, "--format", format, "--file", "-"}
586	// Labels, milestone and assignee go on the same dispatch issue create
587	// itself resolves and applies: a typo in any of them creates nothing,
588	// and the label/milestone/assign code paths run so notifications and
589	// events happen (#271). issue create refuses the whole create when any
590	// of them is set without write access, so a reader's hand-crafted POST
591	// carrying one is dropped here rather than failing the create.
592	if canWrite {
593		argv = append(argv, fieldArgs("--label", r.FormValue("labels"))...)
594		if milestone := strings.TrimSpace(r.FormValue("milestone")); milestone != "" {
595			argv = append(argv, "--milestone", milestone)
596		}
597		argv = append(argv, fieldArgs("--assignee", r.FormValue("assignee"))...)
598	}
599	code, msg := s.dispatchIntoStdin(u, argv, r.FormValue("body"), &created)
600	if code != protocol.ExitOK {
601		p.Tab = "issues"
602		s.render(w, "issuenew.html", issueNewPage{
603			repoPage: p, Body: r.FormValue("body"), Format: format, Title: title,
604			Labels: r.FormValue("labels"), Milestone: r.FormValue("milestone"), Assignee: r.FormValue("assignee"),
605			Templates: control.IssueTemplates(p.Dir, p.Repo.DefaultBranch), CanWrite: canWrite, Notice: msg,
606		})
607		return
608	}
609	n := created.Number
610	http.Redirect(w, r, fmt.Sprintf("/%s/issues/%d", repoPath, n), http.StatusSeeOther)
611}
612
613// issueEditSubmit edits title/body (author or write) and, with write
614// access, replaces the label set.
615func (s *Server) issueEditSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
616	repoPath := r.PathValue("owner") + "/" + r.PathValue("repo")
617	n := r.PathValue("n")
618	if wantsPreview(r) {
619		s.issuePage(w, r, "edit")
620		return
621	}
622	title := strings.TrimSpace(r.FormValue("title"))
623	code, msg := s.dispatchJSON(u, []string{"issue", "edit", repoPath, n, "--title", title, "--file", "-"}, r.FormValue("body"))
624	if code != protocol.ExitOK {
625		http.Error(w, msg, statusForExit(code))
626		return
627	}
628	var cur struct {
629		Labels []string `json:"labels"`
630	}
631	if _, ok := s.runControlInto(u, []string{"issue", "show", repoPath, n}, &cur); ok {
632		want := strings.Fields(r.FormValue("labels"))
633		var args []string
634		for _, l := range cur.Labels {
635			if !slices.Contains(want, l) {
636				args = append(args, "--remove", l)
637			}
638		}
639		for _, l := range want {
640			if !slices.Contains(cur.Labels, l) {
641				args = append(args, "--add", l)
642			}
643		}
644		if len(args) > 0 {
645			s.runControl(u, append([]string{"issue", "label", repoPath, n}, args...))
646		}
647	}
648	http.Redirect(w, r, fmt.Sprintf("/%s/issues/%s", repoPath, n), http.StatusSeeOther)
649}
650
651// mrEditSubmit edits an MR's title/body (author or write).
652func (s *Server) mrEditSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
653	repoPath := r.PathValue("owner") + "/" + r.PathValue("repo")
654	n := r.PathValue("n")
655	if wantsPreview(r) {
656		s.mrPage(w, r, "edit")
657		return
658	}
659	title := strings.TrimSpace(r.FormValue("title"))
660	code, msg := s.dispatchJSON(u, []string{"mr", "edit", repoPath, n, "--title", title, "--file", "-"}, r.FormValue("body"))
661	if code != protocol.ExitOK {
662		http.Error(w, msg, statusForExit(code))
663		return
664	}
665	http.Redirect(w, r, fmt.Sprintf("/%s/mrs/%s", repoPath, n), http.StatusSeeOther)
666}
667
668func (s *Server) issueCommentSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
669	if wantsPreview(r) {
670		s.issuePage(w, r, "comment")
671		return
672	}
673	s.commentSubmit(w, r, u, "issue", "issues")
674}
675
676func (s *Server) mrCommentSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
677	if wantsPreview(r) {
678		s.mrPage(w, r, "comment")
679		return
680	}
681	s.commentSubmit(w, r, u, "mr", "mrs")
682}
683
684func (s *Server) commentSubmit(w http.ResponseWriter, r *http.Request, u store.User, noun, segment string) {
685	repoPath := r.PathValue("owner") + "/" + r.PathValue("repo")
686	n := r.PathValue("n")
687	code, msg := s.dispatchJSON(u, []string{noun, "comment", repoPath, n, "--format", bodyFormat(r), "--file", "-"}, strings.TrimSpace(r.FormValue("body")))
688	if code != protocol.ExitOK {
689		http.Error(w, msg, statusForExit(code))
690		return
691	}
692	http.Redirect(w, r, fmt.Sprintf("/%s/%s/%s", repoPath, segment, n), http.StatusSeeOther)
693}
694
695type editPage struct {
696	basePage
697	Repo    store.Repo
698	Ref     string
699	Path    string
700	Content string
701	Error   string
702	Blocked string
703	// ProposeBranch is suggested when direct commits to Ref are blocked by
704	// require_mr (and signed commits are not required), enabling a 1-step
705	// branch-and-MR edit flow.
706	ProposeBranch string
707	RequireMR     bool
708	// Creating marks a path the branch does not have yet.
709	Creating bool
710	// Markup is set for a path the forge renders, which is where a
711	// Preview button makes sense; Draft holds one when asked for (#235).
712	Markup bool
713	Draft  *draft
714	Nav    fileNav
715}
716
717func nextPatchBranch(dir, username string) string {
718	base := username + "-patch-"
719	for i := 1; i <= 50; i++ {
720		cand := base + strconv.Itoa(i)
721		if _, err := gitutil.ResolveRef(dir, "refs/heads/"+cand); err != nil {
722			return cand
723		}
724	}
725	return base + "edit"
726}
727
728func (s *Server) editForm(w http.ResponseWriter, r *http.Request, u store.User) {
729	repo, ok := s.repoForUser(w, r, u, policy.CanWrite)
730	if !ok {
731		return
732	}
733	ref := r.PathValue("ref")
734	filePath := strings.Trim(r.PathValue("path"), "/")
735
736	dir := control.RepoDir(s.cfg.Server.Root, repo.OwnerName, repo.Name)
737	// A branch that does not exist has nothing to edit. A path that does
738	// not exist on a real branch is a new file: commit-file creates it.
739	if _, err := gitutil.ResolveRef(dir, "refs/heads/"+ref); err != nil {
740		s.notFound(w, r)
741		return
742	}
743
744	blocked := ""
745	requireMR := false
746	propose := ""
747	switch {
748	case repo.Settings.RequireSignedCommits:
749		blocked = repo.Path() + " requires signed commits and the web editor cannot sign; edit locally and push a signed commit."
750	case repo.Settings.RequireMR && slices.Contains(repo.Settings.ProtectedBranches, ref):
751		requireMR = true
752		propose = nextPatchBranch(dir, u.Username)
753	}
754
755	content, err := gitutil.ReadBlob(dir, "refs/heads/"+ref, filePath, maxRenderBytes)
756	creating := err != nil
757	if creating {
758		content = nil
759	}
760	if gitutil.IsBinary(content) {
761		http.Error(w, "binary files cannot be edited in the browser", http.StatusBadRequest)
762		return
763	}
764	navEntries, _ := gitutil.ListTree(dir, "refs/heads/"+ref, navDir(filePath))
765	nav := fileNavFor(repo.Path(), ref, filePath, navEntries)
766	s.render(w, "edit.html", editPage{
767		basePage: s.baseFor(u), Repo: repo,
768		Ref: ref, Path: filePath, Content: string(content), Blocked: blocked,
769		ProposeBranch: propose, RequireMR: requireMR, Creating: creating,
770		Markup: markupFile(filePath),
771		Nav:    nav,
772	})
773}
774
775func (s *Server) editSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
776	repo, ok := s.repoForUser(w, r, u, policy.CanWrite)
777	if !ok {
778		return
779	}
780	ref := r.PathValue("ref")
781	filePath := strings.Trim(r.PathValue("path"), "/")
782	targetBranch := strings.TrimSpace(r.FormValue("target_branch"))
783	requireMR := repo.Settings.RequireMR && slices.Contains(repo.Settings.ProtectedBranches, ref)
784
785	// Preview: the file as the blob page will render it, above the
786	// editor, with nothing committed. Only for paths the forge renders.
787	if wantsPreview(r) && markupFile(filePath) {
788		content := r.FormValue("content")
789		d := s.draftWith(r, "content", "", content, func(raw, _ string) template.HTML {
790			return renderReadme(path.Base(filePath), []byte(raw))
791		})
792		s.render(w, "edit.html", editPage{
793			basePage: s.baseFor(u), Repo: repo,
794			Ref: ref, Path: filePath, Content: content,
795			ProposeBranch: targetBranch, RequireMR: requireMR,
796			Markup: true, Draft: d,
797		})
798		return
799	}
800
801	commitRef := ref
802	var argv []string
803	if targetBranch != "" && targetBranch != ref {
804		commitRef = targetBranch
805		argv = []string{"repo", "commit-file", repo.Path(), filePath, "--ref", commitRef, "--from", ref, "--file", "-"}
806	} else {
807		argv = []string{"repo", "commit-file", repo.Path(), filePath, "--ref", ref, "--file", "-"}
808	}
809	message := strings.TrimSpace(r.FormValue("message"))
810	if message != "" {
811		argv = append(argv, "--message", message)
812	}
813	if msg, ok := s.runControlStdin(u, argv, r.FormValue("content")); !ok {
814		s.render(w, "edit.html", editPage{
815			basePage: s.baseFor(u), Repo: repo,
816			Ref: ref, Path: filePath, Content: r.FormValue("content"), Error: msg,
817			ProposeBranch: targetBranch, RequireMR: requireMR,
818			Markup: markupFile(filePath),
819		})
820		return
821	}
822	if commitRef != ref {
823		title := message
824		if title == "" {
825			title = "Update " + filePath
826		}
827		q := url.Values{"source": {commitRef}, "target": {ref}, "title": {title}}
828		http.Redirect(w, r, fmt.Sprintf("/%s/mrs/new?%s", repo.Path(), q.Encode()), http.StatusSeeOther)
829		return
830	}
831	http.Redirect(w, r, fmt.Sprintf("/%s/blob/%s/%s", repo.Path(), ref, filePath), http.StatusSeeOther)
832}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form