internal/httpd/accounts.go

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

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