internal/httpd/accounts.go

v1.36.0
gitbay/internal/httpd/accounts.go history · blame · raw

658 lines · 22217 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	if err := s.st.CreateWebSession(sessHash, userID, 7*24*time.Hour); err != nil {
148		http.Error(w, "internal error", http.StatusInternalServerError)
149		return
150	}
151	http.SetCookie(w, s.sessionCookieFor(sessTok))
152	dest := s.takeNext(w, r)
153	if dest == "" {
154		dest = "/"
155	}
156	http.Redirect(w, r, dest, http.StatusSeeOther)
157}
158
159// sessionCookieFor is the cookie a new session ships in. Secure follows TLS
160// the way clearCookie does, so a plain-HTTP deployment still works.
161func (s *Server) sessionCookieFor(tok string) *http.Cookie {
162	return &http.Cookie{
163		Name: sessionCookie, Value: tok, Path: "/",
164		HttpOnly: true, SameSite: sessionSameSite,
165		Secure: s.cfg.HTTP.TLS != "off",
166		MaxAge: 7 * 24 * 3600,
167	}
168}
169
170// logoutForm is GET /logout: the confirmation the rail's signout square
171// and the More menu link to, so the session does not end on one stray
172// click. The button posts to the same path.
173func (s *Server) logoutForm(w http.ResponseWriter, r *http.Request, u store.User) {
174	s.render(w, "logout.html", struct {
175		basePage
176	}{s.baseFor(u)})
177}
178
179func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
180	if ck, err := r.Cookie(sessionCookie); err == nil {
181		s.st.DeleteWebSession(store.HashToken(ck.Value))
182	}
183	http.SetCookie(w, s.clearCookie(sessionCookie, sessionSameSite))
184	http.Redirect(w, r, "/", http.StatusSeeOther)
185}
186
187// adminOrgs lists organizations the user administers, for owner pickers.
188func (s *Server) adminOrgs(u store.User) []string {
189	var out []string
190	if orgs, err := s.st.ListOrgsForUser(u.ID); err == nil {
191		for _, o := range orgs {
192			if o.Role == "admin" {
193				out = append(out, o.Username)
194			}
195		}
196	}
197	return out
198}
199
200func (s *Server) renderNewRepo(w http.ResponseWriter, u store.User, errMsg string) {
201	s.render(w, "new.html", struct {
202		basePage
203		Orgs  []string
204		Error string
205	}{s.baseFor(u), s.adminOrgs(u), errMsg})
206}
207
208func (s *Server) newRepoForm(w http.ResponseWriter, r *http.Request, u store.User) {
209	s.renderNewRepo(w, u, "")
210}
211
212// newSubmit creates a repository or an organization: /new carries both
213// forms, told apart by the org form's field. An organization's page is
214// the redirect, the same as org-create from anywhere else.
215func (s *Server) newSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
216	if r.FormValue("field") == "org-create" {
217		name := strings.TrimSpace(r.FormValue("name"))
218		if _, msg, ok := s.runControl(u, []string{"org", "create", name}); !ok {
219			s.renderNewRepo(w, u, msg)
220			return
221		}
222		http.Redirect(w, r, "/"+name, http.StatusSeeOther)
223		return
224	}
225	owner := r.FormValue("owner")
226	if owner == "" {
227		owner = u.Username
228	}
229	name := r.FormValue("name")
230	argv := []string{"repo", "create", owner + "/" + name}
231	if r.FormValue("visibility") == "private" {
232		argv = append(argv, "--private")
233	}
234	if _, msg, ok := s.runControl(u, argv); !ok {
235		s.renderNewRepo(w, u, msg)
236		return
237	}
238	http.Redirect(w, r, "/"+owner+"/"+name, http.StatusSeeOther)
239}
240
241// pinToggle pins or unpins the repo for the logged-in viewer.
242func (s *Server) pinToggle(w http.ResponseWriter, r *http.Request, u store.User) {
243	repo, ok := s.repoForUser(w, r, u, policy.CanRead)
244	if !ok {
245		return
246	}
247	if s.st.IsPinned(u.ID, repo.ID) {
248		s.st.UnpinRepo(u.ID, repo.ID)
249	} else {
250		s.st.PinRepo(u.ID, repo.ID)
251	}
252	http.Redirect(w, r, "/"+repo.Path(), http.StatusSeeOther)
253}
254
255// bookmarkToggle saves or unsaves a repository for the viewer. Read
256// access is all a bookmark needs — it is something you do to someone
257// else's repository — and repoForUser 404s a private one either way.
258func (s *Server) bookmarkToggle(w http.ResponseWriter, r *http.Request, u store.User) {
259	repo, ok := s.repoForUser(w, r, u, policy.CanRead)
260	if !ok {
261		return
262	}
263	verb := "bookmark"
264	if s.st.IsBookmarked(u.ID, repo.ID) {
265		verb = "unbookmark"
266	}
267	if _, msg, ok := s.runControl(u, []string{"repo", verb, repo.Path()}); !ok {
268		s.setFlash(w, msg)
269	}
270	http.Redirect(w, r, "/"+repo.Path(), http.StatusSeeOther)
271}
272
273// bookmarksPage lists what the viewer has saved.
274// bookmarksPage keeps /bookmarks working: the list is a tab on the
275// viewer's own profile now, so there is one page of it rather than two
276// showing the same rows.
277func (s *Server) bookmarksPage(w http.ResponseWriter, r *http.Request, u store.User) {
278	http.Redirect(w, r, "/"+u.Username+"/-/bookmarks", http.StatusSeeOther)
279}
280
281// renderFork draws the fork form: where the copy lands and what it is
282// called. owner and name are what the field should hold, which after a
283// refusal is what was submitted.
284func (s *Server) renderFork(w http.ResponseWriter, u store.User, repo store.Repo, owner, name, errMsg string) {
285	s.render(w, "fork.html", struct {
286		basePage
287		Repo  store.Repo
288		Orgs  []string
289		Owner string
290		Name  string
291		Error string
292	}{s.baseFor(u), repo, s.adminOrgs(u), owner, name, errMsg})
293}
294
295func (s *Server) forkForm(w http.ResponseWriter, r *http.Request, u store.User) {
296	repo, ok := s.repoForUser(w, r, u, policy.CanRead)
297	if !ok {
298		return
299	}
300	s.renderFork(w, u, repo, u.Username, repo.Name, "")
301}
302
303// forkSubmit forks the repository to the owner the form picked and sends
304// them to it. The command decides everything that matters — read access,
305// the right to create under that owner, quota, name collisions — so a
306// refusal comes back as its own message on the form (#174).
307func (s *Server) forkSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
308	repo, ok := s.repoForUser(w, r, u, policy.CanRead)
309	if !ok {
310		return
311	}
312	owner, name := r.FormValue("owner"), r.FormValue("name")
313	if owner == "" {
314		owner = u.Username
315	}
316	if name == "" {
317		name = repo.Name
318	}
319	var fork control.ForkOut
320	argv := []string{"repo", "fork", repo.Path(), "--owner", owner, "--name", name}
321	if msg, ok := s.runControlInto(u, argv, &fork); !ok {
322		s.renderFork(w, u, repo, owner, name, msg)
323		return
324	}
325	http.Redirect(w, r, "/"+fork.Path, http.StatusSeeOther)
326}
327
328// repoForUser is repoFor with a write/read permission requirement for a
329// logged-in user.
330func (s *Server) repoForUser(w http.ResponseWriter, r *http.Request, u store.User,
331	perm func(store.User, store.Repo, string) bool) (store.Repo, bool) {
332	repo, err := s.st.RepoByPath(r.PathValue("owner") + "/" + r.PathValue("repo"))
333	if err != nil {
334		http.NotFound(w, r)
335		return store.Repo{}, false
336	}
337	grant, err := s.st.AccessRole(repo.ID, u.ID)
338	if err != nil {
339		http.Error(w, "internal error", http.StatusInternalServerError)
340		return store.Repo{}, false
341	}
342	if !policy.CanRead(u, repo, grant) {
343		http.NotFound(w, r) // invisible: same as nonexistent
344		return store.Repo{}, false
345	}
346	if !perm(u, repo, grant) {
347		http.Error(w, "permission denied", http.StatusForbidden)
348		return store.Repo{}, false
349	}
350	return repo, true
351}
352
353// signupForm and signupSubmit front the SSH registration path for open
354// and invite instances: same store transactions, same rules, a pasted
355// public key instead of the connecting one.
356func (s *Server) signupForm(w http.ResponseWriter, r *http.Request) {
357	s.renderSignup(w, "", "")
358}
359
360func (s *Server) renderSignup(w http.ResponseWriter, errMsg, username string) {
361	s.render(w, "register.html", struct {
362		basePage
363		Host     string
364		Mode     string // open | invite
365		Error    string
366		Username string
367	}{basePage{Site: s.siteName(), Host: s.cfg.SiteHost()}, s.cfg.SiteHost(), s.cfg.Registration.Mode, errMsg, username})
368}
369
370func (s *Server) signupSubmit(w http.ResponseWriter, r *http.Request) {
371	username := strings.TrimSpace(r.FormValue("username"))
372	keyText := strings.TrimSpace(r.FormValue("key"))
373	pub, _, _, _, err := gossh.ParseAuthorizedKey([]byte(keyText))
374	if err != nil {
375		s.renderSignup(w, "that does not parse as an SSH public key (expected e.g. \"ssh-ed25519 AAAA... comment\")", username)
376		return
377	}
378	msg, errMsg, code := control.RegisterAccount(s.cfg, s.st, pub, username,
379		strings.TrimSpace(r.FormValue("email")), strings.TrimSpace(r.FormValue("invite")))
380	if code != 0 {
381		s.renderSignup(w, errMsg, username)
382		return
383	}
384	s.render(w, "registered.html", struct {
385		basePage
386		Username string
387		Message  string
388		Host     string
389	}{basePage{Site: s.siteName(), Host: s.cfg.SiteHost()}, username, msg, s.cfg.SiteHost()})
390}
391
392// issueCreateForm renders the new-issue form, prefilled from the repo's
393// default issue template when one exists. A Preview submit comes back
394// here with the draft in the form, so the page returns with everything
395// still typed and the rendering above the textarea (#235).
396func (s *Server) issueCreateForm(w http.ResponseWriter, r *http.Request, u store.User) {
397	p, ok := s.repoFor(w, r, "")
398	if !ok {
399		return
400	}
401	p.Tab = "issues"
402	if wantsPreview(r) {
403		d := s.draftFor(r, p.Repo, "body", "body", bodyFormat(r))
404		s.render(w, "issuenew.html", struct {
405			repoPage
406			Body      string
407			Format    string
408			Title     string
409			Labels    string
410			Template  string
411			Templates []control.IssueTemplate
412			Draft     *draft
413		}{p, d.Body, d.Format, r.FormValue("title"), r.FormValue("labels"),
414			"", control.IssueTemplates(p.Dir, p.Repo.DefaultBranch), d})
415		return
416	}
417	templates := control.IssueTemplates(p.Dir, p.Repo.DefaultBranch)
418	body, tplName := "", ""
419	if want := r.URL.Query().Get("template"); want != "" {
420		for _, t := range templates {
421			if t.Name == want {
422				body, tplName = t.Body, t.Name
423			}
424		}
425	} else {
426		for _, t := range templates {
427			if t.Name == "issue-template.md" || body == "" {
428				body, tplName = t.Body, t.Name
429			}
430			if t.Name == "issue-template.md" {
431				break
432			}
433		}
434	}
435	format := r.URL.Query().Get("format")
436	if format != "org" {
437		format = "md"
438	}
439	s.render(w, "issuenew.html", struct {
440		repoPage
441		Body      string
442		Format    string
443		Title     string
444		Labels    string
445		Template  string
446		Templates []control.IssueTemplate
447		Draft     *draft
448	}{p, body, format, "", "", tplName, templates, nil})
449}
450
451// Issue and merge request writes run the command the CLI runs, so the
452// archived check, notifications, body format and the audit entry have one
453// implementation. Bodies travel on stdin, the way --file - does.
454
455func (s *Server) issueCreateSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
456	repoPath := r.PathValue("owner") + "/" + r.PathValue("repo")
457	title := strings.TrimSpace(r.FormValue("title"))
458	format := bodyFormat(r)
459	if wantsPreview(r) {
460		s.issueCreateForm(w, r, u)
461		return
462	}
463	var created control.Created
464	argv := []string{"issue", "create", repoPath, "--title", title, "--format", format, "--file", "-"}
465	code, msg := s.dispatchIntoStdin(u, argv, r.FormValue("body"), &created)
466	if code != protocol.ExitOK {
467		http.Error(w, msg, statusForExit(code))
468		return
469	}
470	n := created.Number
471	// Labels need write access, matching the SSH rule; the command refuses
472	// otherwise and the issue stands without them.
473	if args := fieldArgs("--add", r.FormValue("labels")); len(args) > 0 {
474		s.runControl(u, append([]string{"issue", "label", repoPath, fmt.Sprint(n)}, args...))
475	}
476	http.Redirect(w, r, fmt.Sprintf("/%s/issues/%d", repoPath, n), http.StatusSeeOther)
477}
478
479// issueEditSubmit edits title/body (author or write) and, with write
480// access, replaces the label set.
481func (s *Server) issueEditSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
482	repoPath := r.PathValue("owner") + "/" + r.PathValue("repo")
483	n := r.PathValue("n")
484	if wantsPreview(r) {
485		s.issuePage(w, r, "edit")
486		return
487	}
488	title := strings.TrimSpace(r.FormValue("title"))
489	code, msg := s.dispatchJSON(u, []string{"issue", "edit", repoPath, n, "--title", title, "--file", "-"}, r.FormValue("body"))
490	if code != protocol.ExitOK {
491		http.Error(w, msg, statusForExit(code))
492		return
493	}
494	var cur struct {
495		Labels []string `json:"labels"`
496	}
497	if _, ok := s.runControlInto(u, []string{"issue", "show", repoPath, n}, &cur); ok {
498		want := strings.Fields(r.FormValue("labels"))
499		var args []string
500		for _, l := range cur.Labels {
501			if !slices.Contains(want, l) {
502				args = append(args, "--remove", l)
503			}
504		}
505		for _, l := range want {
506			if !slices.Contains(cur.Labels, l) {
507				args = append(args, "--add", l)
508			}
509		}
510		if len(args) > 0 {
511			s.runControl(u, append([]string{"issue", "label", repoPath, n}, args...))
512		}
513	}
514	http.Redirect(w, r, fmt.Sprintf("/%s/issues/%s", repoPath, n), http.StatusSeeOther)
515}
516
517// mrEditSubmit edits an MR's title/body (author or write).
518func (s *Server) mrEditSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
519	repoPath := r.PathValue("owner") + "/" + r.PathValue("repo")
520	n := r.PathValue("n")
521	if wantsPreview(r) {
522		s.mrPage(w, r, "edit")
523		return
524	}
525	title := strings.TrimSpace(r.FormValue("title"))
526	code, msg := s.dispatchJSON(u, []string{"mr", "edit", repoPath, n, "--title", title, "--file", "-"}, r.FormValue("body"))
527	if code != protocol.ExitOK {
528		http.Error(w, msg, statusForExit(code))
529		return
530	}
531	http.Redirect(w, r, fmt.Sprintf("/%s/mrs/%s", repoPath, n), http.StatusSeeOther)
532}
533
534func (s *Server) issueCommentSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
535	if wantsPreview(r) {
536		s.issuePage(w, r, "comment")
537		return
538	}
539	s.commentSubmit(w, r, u, "issue", "issues")
540}
541
542func (s *Server) mrCommentSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
543	if wantsPreview(r) {
544		s.mrPage(w, r, "comment")
545		return
546	}
547	s.commentSubmit(w, r, u, "mr", "mrs")
548}
549
550func (s *Server) commentSubmit(w http.ResponseWriter, r *http.Request, u store.User, noun, segment string) {
551	repoPath := r.PathValue("owner") + "/" + r.PathValue("repo")
552	n := r.PathValue("n")
553	code, msg := s.dispatchJSON(u, []string{noun, "comment", repoPath, n, "--file", "-"}, strings.TrimSpace(r.FormValue("body")))
554	if code != protocol.ExitOK {
555		http.Error(w, msg, statusForExit(code))
556		return
557	}
558	http.Redirect(w, r, fmt.Sprintf("/%s/%s/%s", repoPath, segment, n), http.StatusSeeOther)
559}
560
561type editPage struct {
562	basePage
563	Repo    store.Repo
564	Ref     string
565	Path    string
566	Content string
567	Error   string
568	Blocked string
569	// Creating marks a path the branch does not have yet.
570	Creating bool
571	// Markup is set for a path the forge renders, which is where a
572	// Preview button makes sense; Draft holds one when asked for (#235).
573	Markup bool
574	Draft  *draft
575	Nav    fileNav
576}
577
578func (s *Server) editForm(w http.ResponseWriter, r *http.Request, u store.User) {
579	repo, ok := s.repoForUser(w, r, u, policy.CanWrite)
580	if !ok {
581		return
582	}
583	ref := r.PathValue("ref")
584	filePath := strings.Trim(r.PathValue("path"), "/")
585
586	blocked := ""
587	switch {
588	case repo.Settings.RequireSignedCommits:
589		blocked = repo.Path() + " requires signed commits and the web editor cannot sign; edit locally and push a signed commit."
590	case repo.Settings.RequireMR && slices.Contains(repo.Settings.ProtectedBranches, ref):
591		blocked = "branch " + ref + " accepts changes through merge requests only; edit on another branch and open one."
592	}
593
594	dir := control.RepoDir(s.cfg.Server.Root, repo.OwnerName, repo.Name)
595	// A branch that does not exist has nothing to edit. A path that does
596	// not exist on a real branch is a new file: commit-file creates it.
597	if _, err := gitutil.ResolveRef(dir, "refs/heads/"+ref); err != nil {
598		s.notFound(w, r)
599		return
600	}
601	content, err := gitutil.ReadBlob(dir, "refs/heads/"+ref, filePath, maxRenderBytes)
602	creating := err != nil
603	if creating {
604		content = nil
605	}
606	if gitutil.IsBinary(content) {
607		http.Error(w, "binary files cannot be edited in the browser", http.StatusBadRequest)
608		return
609	}
610	navEntries, _ := gitutil.ListTree(dir, "refs/heads/"+ref, navDir(filePath))
611	nav := fileNavFor(repo.Path(), ref, filePath, navEntries)
612	s.render(w, "edit.html", editPage{
613		basePage: s.baseFor(u), Repo: repo,
614		Ref: ref, Path: filePath, Content: string(content), Blocked: blocked, Creating: creating,
615		Markup: markupFile(filePath),
616		Nav:    nav,
617	})
618}
619
620func (s *Server) editSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
621	repo, ok := s.repoForUser(w, r, u, policy.CanWrite)
622	if !ok {
623		return
624	}
625	ref := r.PathValue("ref")
626	filePath := strings.Trim(r.PathValue("path"), "/")
627
628	// Preview: the file as the blob page will render it, above the
629	// editor, with nothing committed. Only for paths the forge renders.
630	if wantsPreview(r) && markupFile(filePath) {
631		content := r.FormValue("content")
632		d := s.draftWith(r, "content", "", content, func(raw, _ string) template.HTML {
633			return renderReadme(path.Base(filePath), []byte(raw))
634		})
635		s.render(w, "edit.html", editPage{
636			basePage: s.baseFor(u), Repo: repo,
637			Ref: ref, Path: filePath, Content: content, Markup: true, Draft: d,
638		})
639		return
640	}
641
642	// Editing is a control command; the web supplies the form and lets
643	// the registry enforce the rules — signed-commit policy, verified
644	// identity, archived repositories — so every surface agrees on them.
645	argv := []string{"repo", "commit-file", repo.Path(), filePath, "--ref", ref, "--file", "-"}
646	if message := strings.TrimSpace(r.FormValue("message")); message != "" {
647		argv = append(argv, "--message", message)
648	}
649	if msg, ok := s.runControlStdin(u, argv, r.FormValue("content")); !ok {
650		s.render(w, "edit.html", editPage{
651			basePage: s.baseFor(u), Repo: repo,
652			Ref: ref, Path: filePath, Content: r.FormValue("content"), Error: msg,
653			Markup: markupFile(filePath),
654		})
655		return
656	}
657	http.Redirect(w, r, fmt.Sprintf("/%s/blob/%s/%s", repo.Path(), ref, filePath), http.StatusSeeOther)
658}