internal/httpd/accounts.go

0338e6ace3de199d5fc383852649919b68ef3e42
gitbay/internal/httpd/accounts.go history · blame · raw

660 lines · 22319 bytes

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