~bigbes/sr-ht-dolt

ref: cd0b0c0fb427bff6060c3f785d67784b999610f3 sr-ht-dolt/web/handlers_settings.go -rw-r--r-- 12.7 KiB
cd0b0c0f — Eugene Blikh web: rename a database from its settings page 3 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
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
	}
}