Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[space][web][rust][server] Protect push subscription updates and deletion (#14182)

Ananda86b34093e61
diff --git a/rust/bindings/wasm/space/src/space.rs b/rust/bindings/wasm/space/src/space.rs
index 778ca08415..f950698d76 100644
--- a/rust/bindings/wasm/space/src/space.rs
+++ b/rust/bindings/wasm/space/src/space.rs
@@ -973,9 +973,9 @@ impl SpaceLinkCtxHandle {
}
#[wasm_bindgen(js_name = unsubscribeWebPush)]
- pub async fn unsubscribe_web_push(&self, endpoint: String) -> Result<(), Error> {
+ pub async fn unsubscribe_web_push(&self, endpoint: String, auth: String) -> Result<(), Error> {
self.inner
- .unsubscribe_web_push(endpoint)
+ .unsubscribe_web_push(endpoint, auth)
.await
.map_err(Into::into)
}
diff --git a/rust/crates/space/src/client/links.rs b/rust/crates/space/src/client/links.rs
index 7809cb24e7..9362da4f80 100644
--- a/rust/crates/space/src/client/links.rs
+++ b/rust/crates/space/src/client/links.rs
@@ -307,11 +307,11 @@ impl SpaceLinkCtx {
Ok(response.target_id)
}
- pub async fn unsubscribe_web_push(&self, endpoint: String) -> Result<()> {
+ pub async fn unsubscribe_web_push(&self, endpoint: String, auth: String) -> Result<()> {
self.api
.delete(&format!("{}/push/subscription", self.prefix()))
.header(AUTH_HEADER, &self.auth_key)
- .json(&WebPushUnsubscriptionRequest { endpoint })
+ .json(&WebPushUnsubscriptionRequest { endpoint, auth })
.send()
.await?
.error_for_status()?;
@@ -722,7 +722,8 @@ mod tests {
.mock("DELETE", format!("{prefix}/push/subscription").as_str())
.match_header("x-space-link-auth", link_auth)
.match_body(Matcher::Json(json!({
- "endpoint": WEB_PUSH_ENDPOINT
+ "endpoint": WEB_PUSH_ENDPOINT,
+ "auth": WEB_PUSH_AUTH
})))
.with_status(204)
.create_async()
@@ -756,7 +757,7 @@ mod tests {
.unwrap(),
"wpt_target"
);
- ctx.unsubscribe_web_push(WEB_PUSH_ENDPOINT.to_owned())
+ ctx.unsubscribe_web_push(WEB_PUSH_ENDPOINT.to_owned(), WEB_PUSH_AUTH.to_owned())
.await
.unwrap();
diff --git a/rust/crates/space/src/transport.rs b/rust/crates/space/src/transport.rs
index 5cfba8d464..697da7287d 100644
--- a/rust/crates/space/src/transport.rs
+++ b/rust/crates/space/src/transport.rs
@@ -458,6 +458,7 @@ pub(crate) struct WebPushSubscriptionRequest {
#[serde(rename_all = "camelCase")]
pub(crate) struct WebPushUnsubscriptionRequest {
pub(crate) endpoint: String,
+ pub(crate) auth: String,
}
#[derive(Deserialize)]
diff --git a/server/space/api/web_push.go b/server/space/api/web_push.go
index 75466a3315..3611dd297e 100644
--- a/server/space/api/web_push.go
+++ b/server/space/api/web_push.go
@@ -43,7 +43,7 @@ func (h *Handlers) UpsertSpaceLinkWebPushSubscription(c *gin.Context) {
}
func (h *Handlers) DeleteSpaceLinkWebPushSubscription(c *gin.Context) {
- var req models.SpaceWebPushUnsubscriptionRequest
+ var req models.SpaceLinkWebPushUnsubscriptionRequest
if !bindJSON(c, &req) {
return
}
diff --git a/server/space/api/web_push_test.go b/server/space/api/web_push_test.go
index 583113514d..4267fefe1f 100644
--- a/server/space/api/web_push_test.go
+++ b/server/space/api/web_push_test.go
@@ -36,11 +36,12 @@ func TestSpaceWebPushAccountSubscriptionAPI(t *testing.T) {
privateKey, err := ecdh.P256().GenerateKey(rand.Reader)
require.NoError(t, err)
+ auth := base64.URLEncoding.EncodeToString(make([]byte, 16))
payload, err := json.Marshal(map[string]any{
"endpoint": "https://fcm.googleapis.com/wp/subscription",
"keys": map[string]string{
"p256dh": base64.RawURLEncoding.EncodeToString(privateKey.PublicKey().Bytes()),
- "auth": base64.RawURLEncoding.EncodeToString(make([]byte, 16)),
+ "auth": auth,
},
})
require.NoError(t, err)
@@ -65,6 +66,35 @@ func TestSpaceWebPushAccountSubscriptionAPI(t *testing.T) {
`, sessionHash[:]).Scan(&count))
require.Equal(t, 1, count)
+ sessionToken = "new-space-web-push-session"
+ sessionHash = sha256.Sum256([]byte(sessionToken))
+ require.NoError(t, repos.Sessions.CreateBrowserSession(context.Background(), sessionHash[:], userID, "wrap-key", timeutil.NDaysFromNow(1)))
+ for _, testCase := range []struct {
+ auth string
+ status int
+ }{
+ {base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{1}, 16)), http.StatusConflict},
+ {base64.RawURLEncoding.EncodeToString(make([]byte, 16)), http.StatusOK},
+ {auth, http.StatusOK},
+ } {
+ retryPayload := bytes.ReplaceAll(payload, []byte(auth), []byte(testCase.auth))
+ retryRequest := httptest.NewRequest(http.MethodPut, "/account/space/push/subscription", bytes.NewReader(retryPayload))
+ retryRequest.Header.Set(controller.SpaceBrowserSessionTokenHeader, sessionToken)
+ retryRequest.Header.Set("Content-Type", "application/json")
+ retryRecorder := httptest.NewRecorder()
+ privateRouter.ServeHTTP(retryRecorder, retryRequest)
+ require.Equal(t, testCase.status, retryRecorder.Code)
+ if testCase.status == http.StatusOK {
+ require.JSONEq(t, subscriptionRecorder.Body.String(), retryRecorder.Body.String())
+ }
+ }
+ require.NoError(t, repos.WebPush.DB.QueryRow(`
+ SELECT COUNT(*)
+ FROM space_web_push_subscriptions
+ WHERE session_token_hash = $1
+ `, sessionHash[:]).Scan(&count))
+ require.Equal(t, 1, count)
+
unsubscriptionPayload, err := json.Marshal(map[string]string{
"endpoint": "https://fcm.googleapis.com/wp/subscription",
})
@@ -83,6 +113,92 @@ func TestSpaceWebPushAccountSubscriptionAPI(t *testing.T) {
require.Zero(t, count)
}
+func TestSpaceLinkWebPushDeletionRequiresSubscriptionAuth(t *testing.T) {
+ handlers, repos, userID := setupSpaceSessionAPITest(t, nil)
+ ctx := context.Background()
+ space, err := testCreateSpace(ctx, repos, userID, "space_push_link", "root", "public", "secret", "nonce", "profile")
+ require.NoError(t, err)
+ linkAuth := bytes.Repeat([]byte{1}, 32)
+ linkAuthHash := sha256.Sum256(linkAuth)
+ link, err := repos.Links.Create(ctx, space.SpaceID, linkAuthHash[:], bytes.Repeat([]byte{2}, 16), 67108864, 2, space.CurrentVersion, []byte("encrypted-space-key"), []byte("encrypted-access-key"))
+ require.NoError(t, err)
+ privateKey, err := ecdh.P256().GenerateKey(rand.Reader)
+ require.NoError(t, err)
+ p256dh := base64.RawURLEncoding.EncodeToString(privateKey.PublicKey().Bytes())
+ auth := base64.RawURLEncoding.EncodeToString(make([]byte, 16))
+ paddedAuth := base64.URLEncoding.EncodeToString(make([]byte, 16))
+ wrongAuth := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{1}, 16))
+ endpoint := "https://fcm.googleapis.com/wp/link-subscription"
+ targetID, err := repos.WebPush.UpsertLinkSubscription(ctx, link.LinkID, endpoint, p256dh, paddedAuth)
+ require.NoError(t, err)
+
+ router := gin.New()
+ path := "/space/public/by-slug/:spaceSlug/link/push/subscription"
+ router.PUT(path, handlers.UpsertSpaceLinkWebPushSubscription)
+ router.DELETE(path, handlers.DeleteSpaceLinkWebPushSubscription)
+ url := "/space/public/by-slug/" + space.SpaceSlug + "/link/push/subscription"
+ for _, testCase := range []struct {
+ auth string
+ status int
+ }{
+ {"", http.StatusBadRequest},
+ {wrongAuth, http.StatusOK},
+ } {
+ payload, err := json.Marshal(map[string]string{"endpoint": endpoint, "auth": testCase.auth})
+ require.NoError(t, err)
+ request := httptest.NewRequest(http.MethodDelete, url, bytes.NewReader(payload))
+ request.Header.Set(controller.SpaceLinkAuthHeader, base64.StdEncoding.EncodeToString(linkAuth))
+ request.Header.Set("Content-Type", "application/json")
+ recorder := httptest.NewRecorder()
+ router.ServeHTTP(recorder, request)
+ require.Equal(t, testCase.status, recorder.Code, recorder.Body.String())
+ var storedP256dh, storedAuth string
+ require.NoError(t, repos.WebPush.DB.QueryRow(`
+ SELECT p256dh, auth FROM space_web_push_subscriptions WHERE target_id = $1
+ `, targetID).Scan(&storedP256dh, &storedAuth))
+ require.Equal(t, p256dh, storedP256dh)
+ require.Equal(t, paddedAuth, storedAuth)
+ }
+ for _, testCase := range []struct {
+ auth string
+ status int
+ }{
+ {wrongAuth, http.StatusConflict},
+ {auth, http.StatusOK},
+ {paddedAuth, http.StatusOK},
+ } {
+ payload, err := json.Marshal(map[string]any{
+ "endpoint": endpoint,
+ "keys": map[string]string{"p256dh": p256dh, "auth": testCase.auth},
+ })
+ require.NoError(t, err)
+ request := httptest.NewRequest(http.MethodPut, url, bytes.NewReader(payload))
+ request.Header.Set(controller.SpaceLinkAuthHeader, base64.StdEncoding.EncodeToString(linkAuth))
+ request.Header.Set("Content-Type", "application/json")
+ recorder := httptest.NewRecorder()
+ router.ServeHTTP(recorder, request)
+ require.Equal(t, testCase.status, recorder.Code, recorder.Body.String())
+ if testCase.status == http.StatusOK {
+ require.JSONEq(t, `{"targetId":"`+targetID+`"}`, recorder.Body.String())
+ }
+ }
+ for range 2 {
+ payload, err := json.Marshal(map[string]string{"endpoint": endpoint, "auth": auth})
+ require.NoError(t, err)
+ request := httptest.NewRequest(http.MethodDelete, url, bytes.NewReader(payload))
+ request.Header.Set(controller.SpaceLinkAuthHeader, base64.StdEncoding.EncodeToString(linkAuth))
+ request.Header.Set("Content-Type", "application/json")
+ recorder := httptest.NewRecorder()
+ router.ServeHTTP(recorder, request)
+ require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
+ var count int
+ require.NoError(t, repos.WebPush.DB.QueryRow(`
+ SELECT COUNT(*) FROM space_web_push_subscriptions WHERE target_id = $1
+ `, targetID).Scan(&count))
+ require.Zero(t, count)
+ }
+}
+
func TestSpaceWebPushVAPIDKeyRequiresCompleteConfig(t *testing.T) {
handlers, _, _ := setupSpaceSessionAPITest(t, nil)
diff --git a/server/space/controller/web_push.go b/server/space/controller/web_push.go
index bc96947b2c..25a5c54d3b 100644
--- a/server/space/controller/web_push.go
+++ b/server/space/controller/web_push.go
@@ -123,7 +123,7 @@ func (c *WebPushController) UpsertLinkSubscription(
func (c *WebPushController) DeleteLinkSubscription(
ctx *gin.Context,
slug string,
- req models.SpaceWebPushUnsubscriptionRequest,
+ req models.SpaceLinkWebPushUnsubscriptionRequest,
) error {
endpoint := strings.TrimSpace(req.Endpoint)
if _, err := parseWebPushEndpoint(endpoint); err != nil {
@@ -133,7 +133,7 @@ func (c *WebPushController) DeleteLinkSubscription(
if err != nil {
return err
}
- return c.webPushRepo.DeleteLinkSubscription(ctx, link.LinkID, endpoint)
+ return c.webPushRepo.DeleteLinkSubscription(ctx, link.LinkID, endpoint, strings.TrimSpace(req.Auth))
}
func validatedWebPushSubscription(
diff --git a/server/space/models/models.go b/server/space/models/models.go
index ee6b09da5f..dc7a1a2c64 100644
--- a/server/space/models/models.go
+++ b/server/space/models/models.go
@@ -40,6 +40,11 @@ type SpaceWebPushUnsubscriptionRequest struct {
Endpoint string `json:"endpoint" binding:"required"`
}
+type SpaceLinkWebPushUnsubscriptionRequest struct {
+ Endpoint string `json:"endpoint" binding:"required"`
+ Auth string `json:"auth" binding:"required"`
+}
+
type SpaceWebPushTargetResponse struct {
TargetID string `json:"targetId"`
}
diff --git a/server/space/repo/web_push.go b/server/space/repo/web_push.go
index 1ed7ea910d..02c2875ca5 100644
--- a/server/space/repo/web_push.go
+++ b/server/space/repo/web_push.go
@@ -5,6 +5,7 @@ import (
"database/sql"
"errors"
+ "github.com/ente/museum/ente"
"github.com/ente/museum/ente/base"
timeutil "github.com/ente/museum/pkg/utils/time"
"github.com/ente/stacktrace"
@@ -40,14 +41,6 @@ func (r *WebPushRepository) UpsertAccountSubscription(
`, sessionTokenHash, endpoint); err != nil {
return "", stacktrace.Propagate(err, "")
}
- if _, err := tx.ExecContext(ctx, `
- UPDATE space_web_push_subscriptions
- SET p256dh = $2, auth = $3
- WHERE endpoint = $1
- `, endpoint, p256dh, auth); err != nil {
- return "", stacktrace.Propagate(err, "")
- }
-
targetID := base.MustNewID("wpt")
if err := tx.QueryRowContext(ctx, `
INSERT INTO space_web_push_subscriptions (
@@ -59,8 +52,12 @@ func (r *WebPushRepository) UpsertAccountSubscription(
session_token_hash = EXCLUDED.session_token_hash,
p256dh = EXCLUDED.p256dh,
auth = EXCLUDED.auth
+ WHERE rtrim(space_web_push_subscriptions.auth, '=') = rtrim(EXCLUDED.auth, '=')
RETURNING target_id
`, targetID, endpoint, sessionTokenHash, p256dh, auth).Scan(&targetID); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return "", ente.NewConflictError("web push subscription auth does not match")
+ }
return "", stacktrace.Propagate(err, "")
}
if err := tx.Commit(); err != nil {
@@ -101,14 +98,6 @@ func (r *WebPushRepository) UpsertLinkSubscription(
if !endpointExists && subscriptionCount >= spaceWebPushLinkSubscriptionLimit {
return "", ErrSpaceWebPushLinkSubscriptionLimit
}
- if _, err := tx.ExecContext(ctx, `
- UPDATE space_web_push_subscriptions
- SET p256dh = $2, auth = $3
- WHERE endpoint = $1
- `, endpoint, p256dh, auth); err != nil {
- return "", stacktrace.Propagate(err, "")
- }
-
targetID := base.MustNewID("wpt")
if err := tx.QueryRowContext(ctx, `
INSERT INTO space_web_push_subscriptions (
@@ -119,8 +108,12 @@ func (r *WebPushRepository) UpsertLinkSubscription(
DO UPDATE SET
p256dh = EXCLUDED.p256dh,
auth = EXCLUDED.auth
+ WHERE rtrim(space_web_push_subscriptions.auth, '=') = rtrim(EXCLUDED.auth, '=')
RETURNING target_id
`, targetID, endpoint, activeLinkID, p256dh, auth).Scan(&targetID); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return "", ente.NewConflictError("web push subscription auth does not match")
+ }
return "", stacktrace.Propagate(err, "")
}
if err := tx.Commit(); err != nil {
@@ -144,12 +137,12 @@ func (r *WebPushRepository) DeleteAccountSubscription(
func (r *WebPushRepository) DeleteLinkSubscription(
ctx context.Context,
linkID int64,
- endpoint string,
+ endpoint, auth string,
) error {
_, err := r.DB.ExecContext(ctx, `
DELETE FROM space_web_push_subscriptions
- WHERE link_id = $1 AND endpoint = $2
- `, linkID, endpoint)
+ WHERE link_id = $1 AND endpoint = $2 AND rtrim(auth, '=') = rtrim($3, '=')
+ `, linkID, endpoint, auth)
return stacktrace.Propagate(err, "")
}
diff --git a/server/space/repo/web_push_test.go b/server/space/repo/web_push_test.go
index 54bcfd73aa..e04bb9608c 100644
--- a/server/space/repo/web_push_test.go
+++ b/server/space/repo/web_push_test.go
@@ -5,6 +5,7 @@ import (
"context"
"testing"
+ "github.com/ente/museum/ente"
timeutil "github.com/ente/museum/pkg/utils/time"
"github.com/stretchr/testify/require"
)
@@ -151,6 +152,54 @@ func TestWebPushSubscriptionsFollowTargetsAndActiveSessions(t *testing.T) {
require.Zero(t, count)
}
+func TestWebPushAccountSubscriptionRequiresAuthToReassignSession(t *testing.T) {
+ module := newSpaceTestModule(t)
+ ctx := context.Background()
+ ownerID := insertSpaceUser(t, module, "[email protected]", "owner-public")
+ attackerID := insertSpaceUser(t, module, "[email protected]", "attacker-public")
+ session := []byte("original-space-web-push-session")
+ newSession := []byte("new-space-web-push-session")
+ attackerSession := []byte("attacker-space-web-push-session")
+ require.NoError(t, module.Sessions.CreateBrowserSession(ctx, session, ownerID, "wrap", timeutil.NDaysFromNow(1)))
+ require.NoError(t, module.Sessions.CreateBrowserSession(ctx, newSession, ownerID, "wrap", timeutil.NDaysFromNow(1)))
+ require.NoError(t, module.Sessions.CreateBrowserSession(ctx, attackerSession, attackerID, "wrap", timeutil.NDaysFromNow(1)))
+ endpoint := "https://push.example/victim"
+ targetID, err := module.WebPush.UpsertAccountSubscription(ctx, session, endpoint, "victim-p256dh", "victim-auth")
+ require.NoError(t, err)
+ _, err = module.WebPush.UpsertAccountSubscription(ctx, attackerSession, "https://push.example/attacker", "attacker-p256dh", "attacker-auth")
+ require.NoError(t, err)
+ before, err := module.WebPush.ListActiveAccountSubscriptions(ctx, ownerID)
+ require.NoError(t, err)
+ attackerBefore, err := module.WebPush.ListActiveAccountSubscriptions(ctx, attackerID)
+ require.NoError(t, err)
+
+ for _, caller := range [][]byte{session, attackerSession} {
+ _, err = module.WebPush.UpsertAccountSubscription(ctx, caller, endpoint, "attacker-p256dh", "attacker-auth")
+ require.Error(t, err)
+ }
+ unchanged, err := module.WebPush.ListActiveAccountSubscriptions(ctx, ownerID)
+ require.NoError(t, err)
+ require.Equal(t, before, unchanged)
+ attackerUnchanged, err := module.WebPush.ListActiveAccountSubscriptions(ctx, attackerID)
+ require.NoError(t, err)
+ require.Equal(t, attackerBefore, attackerUnchanged)
+
+ repeatedTargetID, err := module.WebPush.UpsertAccountSubscription(ctx, session, endpoint, "victim-p256dh", "victim-auth")
+ require.NoError(t, err)
+ require.Equal(t, targetID, repeatedTargetID)
+ newTargetID, err := module.WebPush.UpsertAccountSubscription(ctx, newSession, endpoint, "victim-p256dh", "victim-auth")
+ require.NoError(t, err)
+ require.Equal(t, targetID, newTargetID)
+ var storedSession []byte
+ require.NoError(t, module.WebPush.DB.QueryRow(`
+ SELECT session_token_hash FROM space_web_push_subscriptions WHERE target_id = $1
+ `, targetID).Scan(&storedSession))
+ require.Equal(t, newSession, storedSession)
+ after, err := module.WebPush.ListActiveAccountSubscriptions(ctx, ownerID)
+ require.NoError(t, err)
+ require.Equal(t, before, after)
+}
+
func TestResetUserAccessDeletesLinkSubscriptions(t *testing.T) {
module := newSpaceTestModule(t)
ctx := context.Background()
@@ -200,10 +249,47 @@ func TestWebPushSharedEndpointKeepsIndependentTargets(t *testing.T) {
require.NoError(t, module.Sessions.CreateBrowserSession(ctx, session, ownerID, "wrap", timeutil.NDaysFromNow(1)))
endpoint := "https://push.example/shared"
- _, err = module.WebPush.UpsertAccountSubscription(ctx, session, endpoint, "first-p256dh", "first-auth")
+ accountTargetID, err := module.WebPush.UpsertAccountSubscription(ctx, session, endpoint, "first-p256dh", "first-auth")
+ require.NoError(t, err)
+ linkTargetID, err := module.WebPush.UpsertLinkSubscription(ctx, link.LinkID, endpoint, "second-p256dh", "second-auth")
require.NoError(t, err)
- _, err = module.WebPush.UpsertLinkSubscription(ctx, link.LinkID, endpoint, "second-p256dh", "second-auth")
+ _, err = module.WebPush.UpsertLinkSubscription(ctx, link.LinkID, endpoint, "attacker-p256dh", "attacker-auth")
+ var conflict *ente.ApiError
+ require.ErrorAs(t, err, &conflict)
+ require.Equal(t, ente.CONFLICT, conflict.Code)
+ var linkP256dh, linkAuth string
+ require.NoError(t, module.WebPush.DB.QueryRow(`
+ SELECT p256dh, auth FROM space_web_push_subscriptions WHERE target_id = $1
+ `, linkTargetID).Scan(&linkP256dh, &linkAuth))
+ require.Equal(t, "second-p256dh", linkP256dh)
+ require.Equal(t, "second-auth", linkAuth)
+ updatedLinkTargetID, err := module.WebPush.UpsertLinkSubscription(ctx, link.LinkID, endpoint, "updated-link-p256dh", "second-auth")
+ require.NoError(t, err)
+ require.Equal(t, linkTargetID, updatedLinkTargetID)
+ accountSubscriptions, err := module.WebPush.ListActiveAccountSubscriptions(ctx, ownerID)
+ require.NoError(t, err)
+ require.Equal(t, []SpaceWebPushSubscriptionRecord{{
+ TargetID: accountTargetID,
+ Endpoint: endpoint,
+ P256dh: "first-p256dh",
+ Auth: "first-auth",
+ }}, accountSubscriptions)
+ updatedAccountTargetID, err := module.WebPush.UpsertAccountSubscription(ctx, session, endpoint, "updated-account-p256dh", "first-auth")
require.NoError(t, err)
+ require.Equal(t, accountTargetID, updatedAccountTargetID)
+ accountSubscriptions, err = module.WebPush.ListActiveAccountSubscriptions(ctx, ownerID)
+ require.NoError(t, err)
+ require.Equal(t, []SpaceWebPushSubscriptionRecord{{
+ TargetID: accountTargetID,
+ Endpoint: endpoint,
+ P256dh: "updated-account-p256dh",
+ Auth: "first-auth",
+ }}, accountSubscriptions)
+ require.NoError(t, module.WebPush.DB.QueryRow(`
+ SELECT p256dh, auth FROM space_web_push_subscriptions WHERE target_id = $1
+ `, linkTargetID).Scan(&linkP256dh, &linkAuth))
+ require.Equal(t, "updated-link-p256dh", linkP256dh)
+ require.Equal(t, "second-auth", linkAuth)
var count int
require.NoError(t, module.WebPush.DB.QueryRow(`
@@ -221,7 +307,7 @@ func TestWebPushSharedEndpointKeepsIndependentTargets(t *testing.T) {
`, endpoint, link.LinkID).Scan(&count))
require.Equal(t, 1, count)
- require.NoError(t, module.WebPush.DeleteLinkSubscription(ctx, link.LinkID, endpoint))
+ require.NoError(t, module.WebPush.DeleteLinkSubscription(ctx, link.LinkID, endpoint, "second-auth"))
require.NoError(t, module.WebPush.DB.QueryRow(`
SELECT COUNT(*)
FROM space_web_push_subscriptions
@@ -281,7 +367,7 @@ func TestWebPushLinkSubscriptionLimit(t *testing.T) {
link.LinkID,
"https://push.example/limit/1",
"updated-p256dh",
- "updated-auth",
+ "auth",
)
require.NoError(t, err)
}
diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.ts
index 752245cf11..13d580bcfa 100644
--- a/web/apps/space/src/services/space.ts
+++ b/web/apps/space/src/services/space.ts
@@ -132,7 +132,7 @@ export interface PublicSpaceLinkSession {
p256dh: string,
auth: string,
) => Promise<string>;
- unsubscribeWebPush: (endpoint: string) => Promise<void>;
+ unsubscribeWebPush: (endpoint: string, auth: string) => Promise<void>;
}
export type SpacePostAssetURLLoader = (
@@ -619,7 +619,8 @@ export const openPublicSpaceLink = async (
postsCount: response.posts ?? 0,
subscribeWebPush: (endpoint, p256dh, auth) =>
ctx.subscribeWebPush(endpoint, p256dh, auth),
- unsubscribeWebPush: (endpoint) => ctx.unsubscribeWebPush(endpoint),
+ unsubscribeWebPush: (endpoint, auth) =>
+ ctx.unsubscribeWebPush(endpoint, auth),
};
} catch (error) {
ctx.free();
diff --git a/web/apps/space/src/services/web-push.ts b/web/apps/space/src/services/web-push.ts
index 1da1284046..db2fb2ae6f 100644
--- a/web/apps/space/src/services/web-push.ts
+++ b/web/apps/space/src/services/web-push.ts
@@ -18,6 +18,7 @@ const vapidPublicKeyStorageKey = "ente-space-web-push-vapid-key";
const publicTargetSyncInterval = 24 * 60 * 60 * 1000;
interface StoredPushTarget {
+ auth?: string;
endpoint: string;
key: string;
kind: "account" | "public";
@@ -415,7 +416,8 @@ export const reconcilePublicSpaceWebPush = async (
);
}
}
- await session.unsubscribeWebPush(subscription.endpoint);
+ const details = subscriptionDetails(subscription);
+ await session.unsubscribeWebPush(details.endpoint, details.auth);
}
return "unsubscribed";
}
@@ -423,6 +425,7 @@ export const reconcilePublicSpaceWebPush = async (
const details = subscriptionDetails(subscription);
if (
target.endpoint == details.endpoint &&
+ target.auth == details.auth &&
target.targetId &&
(target.lastSyncedAt ?? 0) > Date.now() - publicTargetSyncInterval
) {
@@ -434,6 +437,7 @@ export const reconcilePublicSpaceWebPush = async (
details.auth,
);
await putTarget({
+ auth: details.auth,
endpoint: details.endpoint,
key,
kind: "public",
@@ -464,11 +468,16 @@ export const subscribeToPublicSpaceWebPush = async (
const details = subscriptionDetails(subscription);
if (
previousTarget?.endpoint &&
+ previousTarget.auth &&
previousTarget.endpoint != details.endpoint
) {
- await session.unsubscribeWebPush(previousTarget.endpoint);
+ await session.unsubscribeWebPush(
+ previousTarget.endpoint,
+ previousTarget.auth,
+ );
}
await putTarget({
+ auth: details.auth,
endpoint: details.endpoint,
key,
kind: "public",
@@ -481,6 +490,7 @@ export const subscribeToPublicSpaceWebPush = async (
details.auth,
);
await putTarget({
+ auth: details.auth,
endpoint: details.endpoint,
key,
kind: "public",