oficina / base Public

Refuse a stale Scratchpad save instead of overwriting

The note now has a revision. The form carries the revision it edited,
and a save from an older one writes nothing: the page comes back with
409, a plain explanation, the note as saved, and the person's own text
still in the form, ready to save again on purpose (R29). A form with no
revision counts as stale. look gains PageStatus for non-200 pages.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 9d780f9e2a25a3b688dc68a02391e6637dae57cf parent a4d856e
7 files changed, +156 −13
  • docs/copy-pending.md +3 −0
  • internal/look/look.go +7 −0
  • internal/look/static/app.css +5 −0
  • internal/scratchpad/migrations/0002_revision.sql +3 −0
  • internal/scratchpad/scratchpad.go +66 −9
  • internal/scratchpad/scratchpad_test.go +65 −2
  • internal/scratchpad/templates/notes.html +7 −2
diff --git a/docs/copy-pending.md b/docs/copy-pending.md
index 26ad21c..595a881 100644
--- a/docs/copy-pending.md
+++ b/docs/copy-pending.md
@@ -120,6 +120,9 @@ Installed apps: the shared sign-in (`internal/consumer`), Scratchpad and Welcome
| internal/scratchpad/templates/notes.html | Scratchpad page, heading and crumb | Scratchpad |
| internal/scratchpad/templates/notes.html | Note field, label (screen readers) | Shared note |
| internal/scratchpad/templates/notes.html | Note button | Save |
+| internal/scratchpad/templates/notes.html | Save refused because someone saved first (409), above the saved note | Someone else saved this note while you were editing it. Your text is below and hasn't been saved. Save again to replace their version. |
+| internal/scratchpad/templates/notes.html | Save refused: label of the read-only saved note | The note as it was saved |
+| internal/scratchpad/templates/notes.html | Save refused: note field label (screen readers), holding the refused text | Your text |
| internal/scratchpad/scratchpad.go | Note over 64 KiB (413) | The note is too long. |
| internal/scratchpad/scratchpad.go | Note read or save failed (503) | unavailable |
| internal/scratchpad/scratchpad.go | Page failed to render (500) | something went wrong |
diff --git a/internal/look/look.go b/internal/look/look.go
index 344fa8a..33f5803 100644
--- a/internal/look/look.go
+++ b/internal/look/look.go
@@ -91,6 +91,12 @@ func NewRenderer(pageFS fs.FS, funcs template.FuncMap) (*Renderer, error) {
// Page renders the named page in layout.html with status 200. It executes
// into a buffer first, so a template error writes nothing to w.
func (r *Renderer) Page(w http.ResponseWriter, name string, data any) error {
+ return r.PageStatus(w, http.StatusOK, name, data)
+}
+
+// PageStatus is Page with another status, such as 409 for a refused save
+// shown again with what the person typed.
+func (r *Renderer) PageStatus(w http.ResponseWriter, status int, name string, data any) error {
t, ok := r.pages[name]
if !ok {
return fmt.Errorf("look: no page %q", name)
@@ -100,6 +106,7 @@ func (r *Renderer) Page(w http.ResponseWriter, name string, data any) error {
return fmt.Errorf("look: render %s: %w", name, err)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.WriteHeader(status)
_, err := buf.WriteTo(w)
return err
}
diff --git a/internal/look/static/app.css b/internal/look/static/app.css
index 54f8a8e..8966375 100644
--- a/internal/look/static/app.css
+++ b/internal/look/static/app.css
@@ -168,3 +168,8 @@ a.btn { display: inline-flex; align-items: center; text-decoration: none; }
.notepad { display: flex; flex-direction: column; gap: 12px; align-items: flex-start; }
.notepad textarea.input { font: inherit; width: 100%; height: auto; min-height: 280px; padding: 12px 14px;
line-height: 1.5; resize: vertical; }
+
+/* A refused save: the note as saved, read-only, above the person's own text. */
+.saved { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; color: var(--haze); font-size: 14px; }
+.saved textarea.input { font: inherit; color: var(--frost); width: 100%; height: auto; min-height: 140px; padding: 12px 14px;
+ line-height: 1.5; resize: vertical; }
diff --git a/internal/scratchpad/migrations/0002_revision.sql b/internal/scratchpad/migrations/0002_revision.sql
new file mode 100644
index 0000000..3fda4b8
--- /dev/null
+++ b/internal/scratchpad/migrations/0002_revision.sql
@@ -0,0 +1,3 @@
+-- Every save bumps the revision; a save made from an older one is refused,
+-- so two people editing at once cannot silently overwrite each other.
+ALTER TABLE notes ADD COLUMN revision INTEGER NOT NULL DEFAULT 0;
diff --git a/internal/scratchpad/scratchpad.go b/internal/scratchpad/scratchpad.go
index 00f938e..1e9878d 100644
--- a/internal/scratchpad/scratchpad.go
+++ b/internal/scratchpad/scratchpad.go
@@ -9,12 +9,14 @@
package scratchpad
import (
+ "context"
"database/sql"
"embed"
"errors"
"io/fs"
"log/slog"
"net/http"
+ "strconv"
"time"
"github.com/go-chi/chi/v5"
@@ -97,26 +99,49 @@ func App(d *db.DB, cfg consumer.Config, logger *slog.Logger) (http.Handler, erro
type notesPage struct {
Name, Base, Note string
+ Revision int64 // the revision the form edits
+ // Conflict is set when a save was refused because someone saved first:
+ // Note is then the refused text and Saved the note as it stands.
+ Conflict bool
+ Saved string
+}
+
+// current reads the note and its revision; no note yet is "" at revision 0.
+func current(ctx context.Context, q interface {
+ QueryRowContext(context.Context, string, ...any) *sql.Row
+}) (string, int64, error) {
+ var note string
+ var rev int64
+ err := q.QueryRowContext(ctx, `SELECT body, revision FROM notes WHERE id = 1`).Scan(&note, &rev)
+ if errors.Is(err, sql.ErrNoRows) {
+ return "", 0, nil
+ }
+ return note, rev, err
}
func (a *app) notes(w http.ResponseWriter, r *http.Request) {
_, name, base, _ := consumer.Person(r)
- var note string
- err := a.db.QueryRowContext(r.Context(), `SELECT body FROM notes WHERE id = 1`).Scan(&note)
- if err != nil && !errors.Is(err, sql.ErrNoRows) {
+ note, rev, err := current(r.Context(), a.db)
+ if err != nil {
a.logger.Error("scratchpad: reading the note", "err", err)
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
- if err := a.pages.Page(w, "notes", notesPage{Name: name, Base: base, Note: note}); err != nil {
+ a.page(w, http.StatusOK, notesPage{Name: name, Base: base, Note: note, Revision: rev})
+}
+
+func (a *app) page(w http.ResponseWriter, status int, p notesPage) {
+ if err := a.pages.PageStatus(w, status, "notes", p); err != nil {
a.logger.Error("scratchpad: render", "err", err)
http.Error(w, "something went wrong", http.StatusInternalServerError)
}
}
-// save replaces the shared note, then sends the browser back to it.
+// save replaces the shared note, then sends the browser back to it. The form
+// says which revision it edited; if someone has saved since, nothing is
+// written and the page comes back with the person's text still in it.
func (a *app) save(w http.ResponseWriter, r *http.Request) {
- sub, _, _, _ := consumer.Person(r)
+ sub, name, base, _ := consumer.Person(r)
r.Body = http.MaxBytesReader(w, r.Body, 4*maxNote) // form encoding can triple a byte
if err := r.ParseForm(); err != nil {
http.Error(w, "The note is too long.", http.StatusRequestEntityTooLarge)
@@ -127,13 +152,45 @@ func (a *app) save(w http.ResponseWriter, r *http.Request) {
http.Error(w, "The note is too long.", http.StatusRequestEntityTooLarge)
return
}
- _, err := a.db.ExecContext(r.Context(), `INSERT INTO notes (id, body, updated_by, updated_at) VALUES (1, ?, ?, ?)
- ON CONFLICT (id) DO UPDATE SET body = excluded.body, updated_by = excluded.updated_by, updated_at = excluded.updated_at`,
- note, sub, time.Now().Unix())
+ // A missing or malformed revision edited nothing in particular: it is
+ // treated as stale, never as permission to overwrite.
+ edited, err := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64)
+ if err != nil {
+ edited = -1
+ }
+ saved, rev, stale, err := a.write(r.Context(), note, sub, edited)
if err != nil {
a.logger.Error("scratchpad: saving the note", "err", err)
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
+ if stale {
+ a.page(w, http.StatusConflict, notesPage{Name: name, Base: base, Note: note, Revision: rev, Conflict: true, Saved: saved})
+ return
+ }
http.Redirect(w, r, "/", http.StatusSeeOther)
}
+
+// write saves note if the stored revision is still edited. Otherwise it
+// writes nothing and reports stale with the note and revision as they are.
+func (a *app) write(ctx context.Context, note, by string, edited int64) (saved string, rev int64, stale bool, err error) {
+ tx, err := a.db.BeginTx(ctx, nil)
+ if err != nil {
+ return "", 0, false, err
+ }
+ defer tx.Rollback()
+ saved, rev, err = current(ctx, tx)
+ if err != nil {
+ return "", 0, false, err
+ }
+ if rev != edited {
+ return saved, rev, true, nil
+ }
+ if _, err := tx.ExecContext(ctx, `INSERT INTO notes (id, body, updated_by, updated_at, revision) VALUES (1, ?, ?, ?, ?)
+ ON CONFLICT (id) DO UPDATE SET body = excluded.body, updated_by = excluded.updated_by,
+ updated_at = excluded.updated_at, revision = excluded.revision`,
+ note, by, time.Now().Unix(), rev+1); err != nil {
+ return "", 0, false, err
+ }
+ return note, rev + 1, false, tx.Commit()
+}
diff --git a/internal/scratchpad/scratchpad_test.go b/internal/scratchpad/scratchpad_test.go
index 04ae2b7..d9ba617 100644
--- a/internal/scratchpad/scratchpad_test.go
+++ b/internal/scratchpad/scratchpad_test.go
@@ -13,6 +13,7 @@ import (
"net/http/httptest"
"net/url"
"os"
+ "regexp"
"strings"
"testing"
"time"
@@ -123,10 +124,27 @@ func (b *browser) do(method, path string, form url.Values, origin string) resp {
func (b *browser) get(path string) resp { b.p.t.Helper(); return b.do(http.MethodGet, path, nil, "") }
-// save posts the notepad form as Scratchpad's own page would.
+var revisionRE = regexp.MustCompile(`<input type="hidden" name="revision" value="([0-9]+)">`)
+
+// revision is the revision the notepad form on body carries, or "".
+func revision(body string) string {
+ if m := revisionRE.FindStringSubmatch(body); m != nil {
+ return m[1]
+ }
+ return ""
+}
+
+// save loads the page and posts its notepad form with note, as a person
+// editing it would.
func (b *browser) save(note string) resp {
b.p.t.Helper()
- return b.do(http.MethodPost, "/", url.Values{"note": {note}}, appOrigin)
+ return b.saveAt(revision(b.get("/").Body), note)
+}
+
+// saveAt posts the notepad form as a page loaded at rev would.
+func (b *browser) saveAt(rev, note string) resp {
+ b.p.t.Helper()
+ return b.do(http.MethodPost, "/", url.Values{"note": {note}, "revision": {rev}}, appOrigin)
}
// signIn runs the handoff with an assertion signed as Base would sign it.
@@ -246,3 +264,48 @@ func TestScratchpadServesTheLook(t *testing.T) {
t.Errorf("stylesheet %s: %d %q", href, r.Code, r.Header.Get("Content-Type"))
}
}
+
+// Finding 6 (R29): two people edit the same note; the second save is refused
+// and keeps what they typed, and saving again from there replaces the note.
+func TestStaleSaveIsRefused(t *testing.T) {
+ p := newPad(t)
+ paul, ana := p.browser(), p.browser()
+ paul.signIn("member-paul", "Paul", "Acme Ltd")
+ ana.signIn("member-ana", "Ana", "Acme Ltd")
+ paul.save("first draft")
+
+ paulRev, anaRev := revision(paul.get("/").Body), revision(ana.get("/").Body)
+ if paulRev == "" || paulRev != anaRev {
+ t.Fatalf("revisions %q and %q", paulRev, anaRev)
+ }
+ if r := paul.saveAt(paulRev, "Paul's <edit>"); r.Code != http.StatusSeeOther {
+ t.Fatalf("Paul's save: %d", r.Code)
+ }
+ r := ana.saveAt(anaRev, "Ana's edit")
+ if r.Code != http.StatusConflict {
+ t.Fatalf("stale save: %d, want 409\n%s", r.Code, r.Body)
+ }
+ if !strings.Contains(r.Body, "Someone else saved this note while you were editing it.") {
+ t.Errorf("no explanation:\n%s", r.Body)
+ }
+ if !strings.Contains(r.Body, "\nAna&#39;s edit</textarea>") {
+ t.Errorf("Ana's text is not in the form:\n%s", r.Body)
+ }
+ if !strings.Contains(r.Body, html.EscapeString("Paul's <edit>")) {
+ t.Errorf("the saved note is not shown:\n%s", r.Body)
+ }
+ if page := paul.get("/"); !strings.Contains(page.Body, html.EscapeString("Paul's <edit>")) || strings.Contains(page.Body, "Ana") {
+ t.Fatalf("the stale save changed the note:\n%s", page.Body)
+ }
+ // Saving the refused page again is a deliberate replace.
+ if r := ana.saveAt(revision(r.Body), "Ana's edit"); r.Code != http.StatusSeeOther {
+ t.Fatalf("second save: %d\n%s", r.Code, r.Body)
+ }
+ if page := paul.get("/"); !strings.Contains(page.Body, "Ana&#39;s edit") {
+ t.Errorf("Ana's second save did not land:\n%s", page.Body)
+ }
+ // A form with no revision is not a save of anything in particular.
+ if r := ana.saveAt("", "no revision"); r.Code != http.StatusConflict {
+ t.Errorf("save without a revision: %d", r.Code)
+ }
+}
diff --git a/internal/scratchpad/templates/notes.html b/internal/scratchpad/templates/notes.html
index eb16b6d..9bfea15 100644
--- a/internal/scratchpad/templates/notes.html
+++ b/internal/scratchpad/templates/notes.html
@@ -4,8 +4,13 @@
<div class="crumb"><div class="wordmark">base</div><span>Scratchpad</span></div>
<h2>Scratchpad</h2>
<p class="lead">Signed in as {{.Name}}, {{.Base}}</p>
-<form class="notepad" method="post" action="/">
-{{/* The newline after the opening tag is dropped by the parser, so a note that starts with one keeps it. */}}<textarea class="input" name="note" rows="14" aria-label="Shared note">
+{{if .Conflict}}<p role="status">Someone else saved this note while you were editing it. Your text is below and hasn't been saved. Save again to replace their version.</p>
+<label class="saved">The note as it was saved
+<textarea class="input" rows="8" readonly>
+{{.Saved}}</textarea></label>
+{{end}}<form class="notepad" method="post" action="/">
+<input type="hidden" name="revision" value="{{.Revision}}">
+{{/* The newline after the opening tag is dropped by the parser, so a note that starts with one keeps it. */}}<textarea class="input" name="note" rows="14" aria-label="{{if .Conflict}}Your text{{else}}Shared note{{end}}">
{{.Note}}</textarea>
<button class="btn" type="submit">Save</button>
</form>