package web
import (
"errors"
"log/slog"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
"go.bigb.es/auxilia/scribe"
"sourcecraft.dev/bigbes/sr-ht-ecore/chrome"
"sourcecraft.dev/bigbes/sr-ht-ecore/pages"
"sourcecraft.dev/bigbes/sr-ht-dolt/core"
"sourcecraft.dev/bigbes/sr-ht-dolt/db"
)
// loadRepoForAdmin loads the {user}/{db} repo and enforces the owner-only admin
// gate for settings. Login is required (anonymous → login redirect). A missing
// repo, or a hidden PRIVATE repo the caller cannot even browse, is reported as
// not found; a visible repo the caller does not own is a plain 403. On any of
// these it writes the response and returns ok=false.
//
// The lookup is classified by repoLookupFailed, exactly as the browse path is: a
// settings URL that answered "no such database" while the metadata store was
// unreachable would be the same lie told on a different page.
func (a *app) loadRepoForAdmin(w http.ResponseWriter, r *http.Request) (repo *core.Repo, ac *authContext, ok bool) {
ac = a.requireLogin(w, r)
if ac == nil {
return nil, nil, false
}
_, caller := callerOf(r.Context())
owner := chi.URLParam(r, "user")
name := chi.URLParam(r, "db")
repo, err := a.cfg.Repos.GetRepoByOwnerAndName(r.Context(), owner, name)
if err != nil {
a.repoLookupFailed(w, r, err)
return nil, nil, false
}
if caller.UserID != repo.OwnerID {
aclMode := a.effectiveACL(r, caller, repo)
if core.NotFoundForPrivate(caller, repo, aclMode) {
a.notFound(w, r)
} else {
a.forbidden(w, r, "Only the owner may change database settings.")
}
return nil, nil, false
}
return repo, ac, true
}
// settingsView is the settings page model.
type settingsView struct {
chrome.Page
Repo *core.Repo
ACL []*db.ACLEntry
Error string
Notice string
}
func (a *app) renderSettings(w http.ResponseWriter, r *http.Request, status int, repo *core.Repo, errMsg, notice string) {
acl, err := a.cfg.Repos.ListACL(r.Context(), repo.ID)
if err != nil {
http.Error(w, "failed to list access", http.StatusInternalServerError)
return
}
view := settingsView{
Page: a.page(r, "Settings — "+repo.OwnerName+"/"+repo.Name),
Repo: repo,
ACL: acl,
Error: errMsg,
Notice: notice,
}
a.render(w, status, "settings", view)
}
// handleSettings renders the settings page (name, description/visibility, ACLs,
// danger zone). Owner only.
//
// A completed rename lands here by redirect rather than by rendering in place,
// so the browser's address bar carries the new name; the "renamed" query
// parameter is how the notice survives that redirect. It is echoed back to the
// page, so it is name-validated first — the value is a redirect target we wrote
// ourselves, but nothing stops a reader from hand-editing the URL.
func (a *app) handleSettings(w http.ResponseWriter, r *http.Request) {
repo, _, ok := a.loadRepoForAdmin(w, r)
if !ok {
return
}
notice := ""
if from := r.URL.Query().Get("renamed"); from != "" && core.ValidateName(from) == nil {
notice = "Renamed from " + from + "."
}
a.renderSettings(w, r, http.StatusOK, repo, "", notice)
}
// handleSettingsPost dispatches the settings form on its "action" field:
// update (description + visibility), rename, acl_add, acl_remove, or delete.
// Owner only; the same-origin check is the router's (csrf.Require) and has
// already run.
func (a *app) handleSettingsPost(w http.ResponseWriter, r *http.Request) {
repo, _, ok := a.loadRepoForAdmin(w, r)
if !ok {
return
}
form, err := pages.FormValues(w, r, 0)
if err != nil {
a.renderSettings(w, r, http.StatusBadRequest, repo, "Malformed form submission.", "")
return
}
switch form.Get("action") {
case "update":
a.settingsUpdate(w, r, repo, form)
case "rename":
a.settingsRename(w, r, repo, form)
case "acl_add":
a.settingsACLAdd(w, r, repo, form)
case "acl_remove":
a.settingsACLRemove(w, r, repo, form)
case "delete":
a.settingsDelete(w, r, repo, form)
default:
a.renderSettings(w, r, http.StatusBadRequest, repo, "Unknown action.", "")
}
}
// settingsUpdate applies the description + visibility change.
func (a *app) settingsUpdate(w http.ResponseWriter, r *http.Request, repo *core.Repo, form url.Values) {
description := strings.TrimSpace(form.Get("description"))
visibility, ok := parseVisibility(form.Get("visibility"))
if !ok {
a.renderSettings(w, r, http.StatusBadRequest, repo, "Invalid visibility.", "")
return
}
if err := a.cfg.Repos.UpdateRepo(r.Context(), repo.ID, description, visibility); err != nil {
http.Error(w, "failed to update database", http.StatusInternalServerError)
return
}
repo.Description = description
repo.Visibility = visibility
a.renderSettings(w, r, http.StatusOK, repo, "", "Settings saved.")
}
// settingsRename moves the database to a new name. A database is one metadata
// row plus one on-disk store directory, and the name is written into both — the
// row's name column and its path, which storage.RepoDiskPath derives from
// (owner, name). Both must move, and the served handle memoized under the old
// path must go with them.
//
// The order mirrors creation, which inserts the row before it touches disk: the
// row moves first, so a name already taken is caught by the unique index while
// nothing on disk has changed, and once it has moved no request can re-open the
// store under the old path behind us. A failed store move then rolls the row
// back, so metadata and disk never disagree about where a database lives.
//
// Renaming does not leave a redirect behind: the old address stops resolving,
// exactly as it does on git.sr.ht, and clones pointing at it must have their
// remote updated. A companion database provisioned from a git repository will
// also be re-created under its old name by the next push to that repository —
// the hook provisions by the git repo's name, which this rename does not touch.
func (a *app) settingsRename(w http.ResponseWriter, r *http.Request, repo *core.Repo, form url.Values) {
newName := strings.TrimSpace(form.Get("name"))
if newName == repo.Name {
a.renderSettings(w, r, http.StatusOK, repo, "", "That is already the name of this database.")
return
}
if err := core.ValidateName(newName); err != nil {
a.renderSettings(w, r, http.StatusBadRequest, repo, err.Error(), "")
return
}
oldName, oldPath := repo.Name, repo.Path
newPath := a.cfg.RepoDiskPath(repo.OwnerName, newName)
if err := a.cfg.Repos.RenameRepo(r.Context(), repo.ID, newName, newPath); err != nil {
switch {
case errors.Is(err, db.ErrNameTaken):
a.renderSettings(w, r, http.StatusConflict, repo,
"You already have a database named "+newName+".", "")
case errors.Is(err, db.ErrNotFound):
a.notFound(w, r)
default:
http.Error(w, "failed to rename database", http.StatusInternalServerError)
}
return
}
if err := a.cfg.Stores.MoveStore(r.Context(), a.cfg.ReposRoot, oldPath, newPath); err != nil {
// The store-layer error names on-disk paths, which this surface never
// discloses; the reader gets the fact that matters to them — the rename
// did not happen — and the detail goes to the log against the id.
slog.Error("moving a database's on-disk store failed; rolling the renamed record back",
"component", "web", "database", repo.ID, scribe.Err(err))
if rerr := a.cfg.Repos.RenameRepo(r.Context(), repo.ID, oldName, oldPath); rerr != nil {
// Both halves failed: the row now names a database whose store is
// still at the old path, which no later request can repair on its
// own. This is the one outcome worth escalating to a human.
slog.Error("rolling a database's renamed record back failed; the record and its store disagree",
"component", "web", "database", repo.ID, scribe.Err(rerr))
http.Error(w, "The database record was renamed, but its on-disk store could not be moved and the record could not be restored. Contact support.",
http.StatusInternalServerError)
return
}
a.renderSettings(w, r, http.StatusInternalServerError, repo,
"The database could not be renamed: its on-disk store could not be moved.", "")
return
}
repo.Name, repo.Path = newName, newPath
if err := a.cfg.Stores.Evict(oldPath); err != nil {
// The rename itself is done — record and store are both at the new name
// — and only the memoized handle for the old path outlived it. Kept
// distinct from the failures above for that reason.
slog.Error("evicting a database's cached store handle failed after it was renamed",
"component", "web", "database", repo.ID, scribe.Err(err))
http.Error(w, "The database was renamed, but the cached handle for its old location could not be evicted. Contact support.",
http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/~"+repo.OwnerName+"/"+newName+"/settings?renamed="+url.QueryEscape(oldName),
http.StatusSeeOther)
}
// settingsACLAdd grants (or updates) an ACL entry for a username. The grantee is
// resolved via the user resolver, which mirrors the meta profile on first sight.
func (a *app) settingsACLAdd(w http.ResponseWriter, r *http.Request, repo *core.Repo, form url.Values) {
username := strings.TrimPrefix(strings.TrimSpace(form.Get("username")), "~")
mode, ok := parseAccessMode(form.Get("mode"))
if !ok {
a.renderSettings(w, r, http.StatusBadRequest, repo, "Invalid access mode.", "")
return
}
if username == "" {
a.renderSettings(w, r, http.StatusBadRequest, repo, "A username is required.", "")
return
}
grantee, err := a.cfg.Users.LookupUser(r.Context(), username)
if err != nil || grantee == nil {
a.renderSettings(w, r, http.StatusBadRequest, repo,
"No such user: "+username, "")
return
}
if grantee.UserID == repo.OwnerID {
a.renderSettings(w, r, http.StatusBadRequest, repo,
"The owner already has full access.", "")
return
}
if err := a.cfg.Repos.UpsertACL(r.Context(), repo.ID, grantee.UserID, mode); err != nil {
http.Error(w, "failed to grant access", http.StatusInternalServerError)
return
}
a.renderSettings(w, r, http.StatusOK, repo, "", "Access granted to "+username+".")
}
// settingsACLRemove revokes an ACL entry by user id.
func (a *app) settingsACLRemove(w http.ResponseWriter, r *http.Request, repo *core.Repo, form url.Values) {
userID, err := strconv.Atoi(form.Get("user_id"))
if err != nil {
a.renderSettings(w, r, http.StatusBadRequest, repo, "Invalid user.", "")
return
}
if err := a.cfg.Repos.DeleteACL(r.Context(), repo.ID, userID); err != nil {
if errors.Is(err, db.ErrNotFound) {
a.renderSettings(w, r, http.StatusNotFound, repo, "No such access entry.", "")
return
}
http.Error(w, "failed to revoke access", http.StatusInternalServerError)
return
}
a.renderSettings(w, r, http.StatusOK, repo, "", "Access revoked.")
}
// settingsDelete deletes the database after a name-confirmation check: the row,
// then the on-disk store, then the served-cache handle. The confirmation guards
// against accidental deletion.
func (a *app) settingsDelete(w http.ResponseWriter, r *http.Request, repo *core.Repo, form url.Values) {
if form.Get("confirm_name") != repo.Name {
a.renderSettings(w, r, http.StatusBadRequest, repo,
"Type the database name exactly to confirm deletion.", "")
return
}
if err := a.cfg.Repos.DeleteRepo(r.Context(), repo.ID); err != nil {
http.Error(w, "failed to delete database", http.StatusInternalServerError)
return
}
if err := a.cfg.Stores.DeleteStore(r.Context(), a.cfg.ReposRoot, repo.Path); err != nil {
// The store-layer error names the on-disk path, which nothing else on
// this surface discloses. The reader keeps the fact that matters to
// them — the record is gone but the store may still be on disk — and
// the detail goes to the log against the database id.
slog.Error("deleting a database's on-disk store failed after the record was removed",
"component", "web", "database", repo.ID, scribe.Err(err))
http.Error(w, "The database record was removed, but the on-disk store could not be deleted. Contact support.",
http.StatusInternalServerError)
return
}
if err := a.cfg.Stores.Evict(repo.Path); err != nil {
// Same split: the store is gone, but the cached handle may survive it
// — a different fact from the one above, kept distinct on purpose.
slog.Error("evicting a database's cached store handle failed after the store was deleted",
"component", "web", "database", repo.ID, scribe.Err(err))
http.Error(w, "The on-disk store was deleted, but the cached handle could not be evicted. Contact support.",
http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
}
// parseAccessMode validates and maps a form access-mode string.
func parseAccessMode(s string) (core.AccessMode, bool) {
switch core.AccessMode(s) {
case core.AccessRO:
return core.AccessRO, true
case core.AccessRW:
return core.AccessRW, true
default:
return "", false
}
}