~bigbes/sr-ht-dolt

ref: 82d997d27047a6f8a0be69a4b50414203b123618 sr-ht-dolt/web/handlers_settings.go -rw-r--r-- 8.0 KiB
82d997d2 — Eugene Blikh web: the detail pane says when its read was clipped 5 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
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 (description/visibility, ACLs, danger
// zone). Owner only.
func (a *app) handleSettings(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := a.loadRepoForAdmin(w, r)
	if !ok {
		return
	}
	a.renderSettings(w, r, http.StatusOK, repo, "", "")
}

// handleSettingsPost dispatches the settings form on its "action" field:
// update (description + visibility), 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 "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.")
}

// 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
	}
}