Просмотр исходного кода

fix(api): generate entry share codes atomically

Concurrent share requests could each write a new code, leaving one
caller with a code that matched no entry. Use a single conditional
update instead.

Sharing and unsharing now update changed_at, and the share endpoint
returns 200 when the entry was already shared.
Frédéric Guillot 17 часов назад
Родитель
Сommit
2283c5cb53

+ 4 - 4
client/client.go

@@ -1097,14 +1097,14 @@ func (c *Client) ToggleStarredContext(ctx context.Context, entryID int64) error
 	return err
 }
 
-// ShareEntry creates a share link
+// ShareEntry returns the share code of an entry, creating one if needed.
 func (c *Client) ShareEntry(entryID int64) (string, error) {
 	ctx, cancel := withDefaultTimeout()
 	defer cancel()
 	return c.ShareEntryContext(ctx, entryID)
 }
 
-// ShareEntryContext creates a share link
+// ShareEntryContext returns the share code of an entry, creating one if needed.
 func (c *Client) ShareEntryContext(ctx context.Context, entryID int64) (string, error) {
 	body, err := c.request.Post(ctx, fmt.Sprintf("/v1/entries/%d/share", entryID), nil)
 	if err != nil {
@@ -1120,14 +1120,14 @@ func (c *Client) ShareEntryContext(ctx context.Context, entryID int64) (string,
 	return response.ShareCode, nil
 }
 
-// UnshareEntry deletes a share link
+// UnshareEntry removes the share code of an entry.
 func (c *Client) UnshareEntry(entryID int64) error {
 	ctx, cancel := withDefaultTimeout()
 	defer cancel()
 	return c.UnshareEntryContext(ctx, entryID)
 }
 
-// UnshareEntryContext deletes a share link
+// UnshareEntryContext removes the share code of an entry.
 func (c *Client) UnshareEntryContext(ctx context.Context, entryID int64) error {
 	return c.request.Delete(ctx, fmt.Sprintf("/v1/entries/%d/share", entryID))
 }

+ 18 - 14
client/client_test.go

@@ -1185,19 +1185,23 @@ func TestShareEntry(t *testing.T) {
 	expected := &ShareCodeResponse{
 		ShareCode: "ExampleShareCode",
 	}
-	client := NewClientWithOptions(
-		"http://mf",
-		WithHTTPClient(
-			newFakeHTTPClient(t, func(t *testing.T, req *http.Request) *http.Response {
-				expectRequest(t, http.MethodPost, "http://mf/v1/entries/1/share", nil, req)
-				return jsonResponseFrom(t, http.StatusOK, http.Header{}, expected)
-			})))
-	shareCode, err := client.ShareEntryContext(t.Context(), 1)
-	if err != nil {
-		t.Fatalf("Expected no error, got %v", err)
-	}
-	if shareCode != expected.ShareCode {
-		t.Fatalf("Expected '%s', got '%s'", expected.ShareCode, shareCode)
+
+	// The server answers 201 when it creates a share code and 200 when the entry was already shared.
+	for _, status := range []int{http.StatusCreated, http.StatusOK} {
+		client := NewClientWithOptions(
+			"http://mf",
+			WithHTTPClient(
+				newFakeHTTPClient(t, func(t *testing.T, req *http.Request) *http.Response {
+					expectRequest(t, http.MethodPost, "http://mf/v1/entries/1/share", nil, req)
+					return jsonResponseFrom(t, status, http.Header{}, expected)
+				})))
+		shareCode, err := client.ShareEntryContext(t.Context(), 1)
+		if err != nil {
+			t.Fatalf("Expected no error for status %d, got %v", status, err)
+		}
+		if shareCode != expected.ShareCode {
+			t.Fatalf("Expected '%s' for status %d, got '%s'", expected.ShareCode, status, shareCode)
+		}
 	}
 }
 
@@ -1207,7 +1211,7 @@ func TestUnshareEntry(t *testing.T) {
 		WithHTTPClient(
 			newFakeHTTPClient(t, func(t *testing.T, req *http.Request) *http.Response {
 				expectRequest(t, http.MethodDelete, "http://mf/v1/entries/1/share", nil, req)
-				return jsonResponseFrom(t, http.StatusOK, http.Header{}, nil)
+				return jsonResponseFrom(t, http.StatusNoContent, http.Header{}, nil)
 			})))
 	if err := client.UnshareEntryContext(t.Context(), 1); err != nil {
 		t.Fatalf("Expected no error, got %v", err)

+ 1 - 1
client/model.go

@@ -291,7 +291,7 @@ type EntryModificationRequest struct {
 // Entries represents a list of entries.
 type Entries []*Entry
 
-// ShareCodeResponse represents a
+// ShareCodeResponse represents the response of the share entry endpoint.
 type ShareCodeResponse struct {
 	ShareCode string `json:"share_code"`
 }

+ 36 - 13
internal/api/api_integration_test.go

@@ -3587,7 +3587,14 @@ func TestShareEntryEndpoint(t *testing.T) {
 		t.Fatalf(`Failed to get entries: %v`, err)
 	}
 
-	shareCode, err := regularUserClient.ShareEntry(result.Entries[0].ID)
+	entryID := result.Entries[0].ID
+
+	entryBeforeShare, err := regularUserClient.Entry(entryID)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	shareCode, err := regularUserClient.ShareEntry(entryID)
 	if err != nil {
 		t.Fatal(err)
 	}
@@ -3595,33 +3602,49 @@ func TestShareEntryEndpoint(t *testing.T) {
 		t.Fatal(`The entry should have a share code`)
 	}
 
-	entry, err := regularUserClient.Entry(result.Entries[0].ID)
+	existingShareCode, err := regularUserClient.ShareEntry(entryID)
 	if err != nil {
 		t.Fatal(err)
 	}
+	if existingShareCode != shareCode {
+		t.Fatalf(`Sharing an entry twice should return the same code, got %q and %q`, shareCode, existingShareCode)
+	}
 
-	if entry.ShareCode != shareCode {
+	entryAfterShare, err := regularUserClient.Entry(entryID)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if entryAfterShare.ShareCode != shareCode {
 		t.Fatal(`The entry share code should match`)
 	}
 
-	if err := regularUserClient.UnshareEntry(result.Entries[0].ID); err != nil {
+	if !entryAfterShare.ChangedAt.After(entryBeforeShare.ChangedAt) {
+		t.Fatalf(`Sharing should update the entry change date, got %v before and %v after`, entryBeforeShare.ChangedAt, entryAfterShare.ChangedAt)
+	}
+
+	if err := regularUserClient.UnshareEntry(entryID); err != nil {
 		t.Fatal(err)
 	}
 
-	entry, err = regularUserClient.Entry(result.Entries[0].ID)
+	entryAfterUnshare, err := regularUserClient.Entry(entryID)
 	if err != nil {
 		t.Fatal(err)
 	}
 
-	if entry.ShareCode != "" {
-		t.Fatalf(`The share code should be deleted`)
+	if entryAfterUnshare.ShareCode != "" {
+		t.Fatal(`The share code should be deleted`)
+	}
+
+	if !entryAfterUnshare.ChangedAt.After(entryAfterShare.ChangedAt) {
+		t.Fatalf(`Unsharing should update the entry change date, got %v before and %v after`, entryAfterShare.ChangedAt, entryAfterUnshare.ChangedAt)
 	}
 
-	nonExistingEntryId := int64(math.MaxInt64)
-	if _, err = regularUserClient.ShareEntry(nonExistingEntryId); !errors.Is(err, miniflux.ErrNotFound) {
+	nonExistingEntryID := int64(math.MaxInt64)
+	if _, err = regularUserClient.ShareEntry(nonExistingEntryID); !errors.Is(err, miniflux.ErrNotFound) {
 		t.Fatalf(`Expected Not Found when sharing non existent entry: %v`, err)
 	}
-	if err = regularUserClient.UnshareEntry(nonExistingEntryId); !errors.Is(err, miniflux.ErrNotFound) {
+	if err = regularUserClient.UnshareEntry(nonExistingEntryID); !errors.Is(err, miniflux.ErrNotFound) {
 		t.Fatalf(`Expected Not Found when unsharing non existent entry: %v`, err)
 	}
 
@@ -3645,11 +3668,11 @@ func TestShareEntryEndpoint(t *testing.T) {
 		t.Fatalf(`Failed to get entries: %v`, err)
 	}
 
-	otherUserEntryId := result.Entries[0].ID
-	if _, err = regularUserClient.ShareEntry(otherUserEntryId); !errors.Is(err, miniflux.ErrNotFound) {
+	otherUserEntryID := result.Entries[0].ID
+	if _, err = regularUserClient.ShareEntry(otherUserEntryID); !errors.Is(err, miniflux.ErrNotFound) {
 		t.Fatalf(`Expected Not Found when sharing other user's entry: %v`, err)
 	}
-	if err = regularUserClient.UnshareEntry(otherUserEntryId); !errors.Is(err, miniflux.ErrNotFound) {
+	if err = regularUserClient.UnshareEntry(otherUserEntryID); !errors.Is(err, miniflux.ErrNotFound) {
 		t.Fatalf(`Expected Not Found when unsharing other user's entry: %v`, err)
 	}
 }

+ 6 - 2
internal/api/entry_handlers.go

@@ -296,7 +296,7 @@ func (h *handler) createSharedEntryHandler(w http.ResponseWriter, r *http.Reques
 		return
 	}
 
-	shareCode, err := h.store.EntryShareCode(request.UserID(r), entryID)
+	shareCode, created, err := h.store.EntryShareCode(request.UserID(r), entryID)
 	if errors.Is(err, storage.ErrEntryNotFound) {
 		response.JSONNotFound(w, r)
 		return
@@ -305,7 +305,11 @@ func (h *handler) createSharedEntryHandler(w http.ResponseWriter, r *http.Reques
 		return
 	}
 
-	response.JSONCreated(w, r, &entryShareResponse{ShareCode: shareCode})
+	if created {
+		response.JSONCreated(w, r, &entryShareResponse{ShareCode: shareCode})
+	} else {
+		response.JSON(w, r, &entryShareResponse{ShareCode: shareCode})
+	}
 }
 
 func (h *handler) unshareEntryHandler(w http.ResponseWriter, r *http.Request) {

+ 30 - 20
internal/storage/entry.go

@@ -20,8 +20,7 @@ import (
 // (feed_id, hash) pair has a tombstone recording a prior deletion.
 var ErrEntryTombstoned = errors.New("store: entry is tombstoned")
 
-// ErrEntryNotFound is returned when the user does not have access to the entry
-// or the entry does not exist
+// ErrEntryNotFound is returned when the entry does not exist or belongs to another user.
 var ErrEntryNotFound = errors.New(`store: entry not found`)
 
 // CountAllEntries returns the number of entries for each status in the database.
@@ -645,36 +644,47 @@ func (s *Storage) MarkCategoryAsRead(userID, categoryID int64, before time.Time)
 	return nil
 }
 
-// EntryShareCode returns the share code of the provided entry.
-// It generates a new one if not already defined.
-func (s *Storage) EntryShareCode(userID int64, entryID int64) (shareCode string, err error) {
-	query := `SELECT share_code FROM entries WHERE user_id=$1 AND id=$2`
-	err = s.db.QueryRow(query, userID, entryID).Scan(&shareCode)
+// EntryShareCode returns the entry share code, generating one if needed, and whether it was created.
+func (s *Storage) EntryShareCode(userID int64, entryID int64) (shareCode string, created bool, err error) {
+	// A single statement keeps concurrent calls from overwriting each other's code.
+	query := `
+		UPDATE
+			entries
+		SET
+			share_code = CASE WHEN share_code = '' THEN $1 ELSE share_code END,
+			changed_at = CASE WHEN share_code = '' THEN now() ELSE changed_at END
+		WHERE
+			user_id=$2 AND
+			id=$3
+		RETURNING
+			share_code
+	`
+	newShareCode := crypto.GenerateRandomStringHex(20)
+	err = s.db.QueryRow(query, newShareCode, userID, entryID).Scan(&shareCode)
 	if errors.Is(err, sql.ErrNoRows) {
 		err = ErrEntryNotFound
 		return
 	} else if err != nil {
-		err = fmt.Errorf(`store: unable to get share code for entry #%d: %v`, entryID, err)
+		err = fmt.Errorf(`store: unable to set share code for entry #%d: %v`, entryID, err)
 		return
 	}
 
-	if shareCode == "" {
-		shareCode = crypto.GenerateRandomStringHex(20)
-
-		query = `UPDATE entries SET share_code = $1 WHERE user_id=$2 AND id=$3`
-		_, err = s.db.Exec(query, shareCode, userID, entryID)
-		if err != nil {
-			err = fmt.Errorf(`store: unable to set share code for entry #%d: %v`, entryID, err)
-			return
-		}
-	}
-
+	created = shareCode == newShareCode
 	return
 }
 
 // UnshareEntry removes the share code for the given entry.
 func (s *Storage) UnshareEntry(userID int64, entryID int64) (err error) {
-	query := `UPDATE entries SET share_code='' WHERE user_id=$1 AND id=$2`
+	query := `
+		UPDATE
+			entries
+		SET
+			share_code = '',
+			changed_at = CASE WHEN share_code <> '' THEN now() ELSE changed_at END
+		WHERE
+			user_id=$1 AND
+			id=$2
+	`
 	result, err := s.db.Exec(query, userID, entryID)
 	if err != nil {
 		err = fmt.Errorf(`store: unable to remove share code for entry #%d: %v`, entryID, err)

+ 1 - 1
internal/ui/share.go

@@ -16,7 +16,7 @@ import (
 
 func (h *handler) createSharedEntry(w http.ResponseWriter, r *http.Request) {
 	entryID := request.RouteInt64Param(r, "entryID")
-	shareCode, err := h.store.EntryShareCode(request.UserID(r), entryID)
+	shareCode, _, err := h.store.EntryShareCode(request.UserID(r), entryID)
 	if errors.Is(err, storage.ErrEntryNotFound) {
 		response.HTMLNotFound(w, r)
 		return