Skip to content

armgit / ente

Public Imported from GitHub
0

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

Address Space web push review feedback

Anand Baburajan29bff5ae3d4f
diff --git a/rust/bindings/wasm/space/src/space.rs b/rust/bindings/wasm/space/src/space.rs
index 17499043f4..987b59b042 100644
--- a/rust/bindings/wasm/space/src/space.rs
+++ b/rust/bindings/wasm/space/src/space.rs
@@ -609,7 +609,7 @@ impl SpaceLinkCtxHandle {
auth: String,
) -> Result<String, WasmSpaceError> {
self.inner
- .subscribe_web_push(&endpoint, &p256dh, &auth)
+ .subscribe_web_push(endpoint, p256dh, auth)
.await
.map_err(Into::into)
}
@@ -618,7 +618,7 @@ impl SpaceLinkCtxHandle {
#[wasm_bindgen(js_name = unsubscribeWebPush)]
pub async fn unsubscribe_web_push(&self, endpoint: String) -> Result<(), WasmSpaceError> {
self.inner
- .unsubscribe_web_push(&endpoint)
+ .unsubscribe_web_push(endpoint)
.await
.map_err(Into::into)
}
diff --git a/rust/space/src/client/links.rs b/rust/space/src/client/links.rs
index 0024184590..67f99466e8 100644
--- a/rust/space/src/client/links.rs
+++ b/rust/space/src/client/links.rs
@@ -262,20 +262,17 @@ impl SpaceLinkCtx {
pub async fn subscribe_web_push(
&self,
- endpoint: &str,
- p256dh: &str,
- auth: &str,
+ endpoint: String,
+ p256dh: String,
+ auth: String,
) -> Result<String> {
let response: WebPushTargetResponse = self
.api
.put(&format!("{}/push/subscription", self.prefix()))
.header(AUTH_HEADER, &self.auth_key)
.json(&WebPushSubscriptionRequest {
- endpoint: endpoint.to_owned(),
- keys: WebPushSubscriptionKeys {
- p256dh: p256dh.to_owned(),
- auth: auth.to_owned(),
- },
+ endpoint,
+ keys: WebPushSubscriptionKeys { p256dh, auth },
})
.send()
.await?
@@ -285,13 +282,11 @@ impl SpaceLinkCtx {
Ok(response.target_id)
}
- pub async fn unsubscribe_web_push(&self, endpoint: &str) -> Result<()> {
+ pub async fn unsubscribe_web_push(&self, endpoint: String) -> Result<()> {
self.api
.delete(&format!("{}/push/subscription", self.prefix()))
.header(AUTH_HEADER, &self.auth_key)
- .json(&WebPushUnsubscriptionRequest {
- endpoint: endpoint.to_owned(),
- })
+ .json(&WebPushUnsubscriptionRequest { endpoint })
.send()
.await?
.error_for_status()?;
@@ -515,6 +510,11 @@ mod tests {
use mockito::{Matcher, Server};
use serde_json::json;
+ const WEB_PUSH_ENDPOINT: &str = "https://push.example/subscription";
+ const WEB_PUSH_P256DH: &str =
+ "BGsX0fLhLEJH-Lzm5WOkQPJ3A32BLeszoPShOUXYmMKWT-NC4v4af5uO5-tKfA-eFivOM1drMV7Oy7ZAaDe_UfU";
+ const WEB_PUSH_AUTH: &str = "AAAAAAAAAAAAAAAAAAAAAA";
+
#[test]
fn generated_access_keys_are_valid() {
for _ in 0..100 {
@@ -598,14 +598,38 @@ mod tests {
)
.create_async()
.await;
+ let ctx = SpaceLinkCtx::open(OpenSpaceLinkCtxInput {
+ base_url: server.url(),
+ space_slug: "Alice".to_owned(),
+ access_key: access_key.to_owned(),
+ user_agent: None,
+ client_package: None,
+ client_version: None,
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(ctx.profile().profile, profile);
+ assert_eq!(ctx.profile().friends, 2);
+ assert_eq!(ctx.posts(), 3);
+ bootstrap.assert_async().await;
+ profile_request.assert_async().await;
+ versions.assert_async().await;
+ }
+
+ #[tokio::test]
+ async fn public_link_serializes_web_push_subscriptions() {
+ let mut server = Server::new_async().await;
+ let prefix = "/space/public/by-slug/alice/link";
+ let link_auth = "link-auth";
let subscribe = server
.mock("PUT", format!("{prefix}/push/subscription").as_str())
- .match_header("x-ente-space-link-auth", auth.as_str())
+ .match_header("x-ente-space-link-auth", link_auth)
.match_body(Matcher::Json(json!({
- "endpoint": "https://push.example/subscription",
+ "endpoint": WEB_PUSH_ENDPOINT,
"keys": {
- "p256dh": "p256dh",
- "auth": "auth"
+ "p256dh": WEB_PUSH_P256DH,
+ "auth": WEB_PUSH_AUTH
}
})))
.with_status(200)
@@ -614,40 +638,46 @@ mod tests {
.await;
let unsubscribe = server
.mock("DELETE", format!("{prefix}/push/subscription").as_str())
- .match_header("x-ente-space-link-auth", auth.as_str())
+ .match_header("x-ente-space-link-auth", link_auth)
.match_body(Matcher::Json(json!({
- "endpoint": "https://push.example/subscription"
+ "endpoint": WEB_PUSH_ENDPOINT
})))
.with_status(204)
.create_async()
.await;
+ let ctx = SpaceLinkCtx {
+ api: build_api(&server.url(), None, None, None, None).unwrap(),
+ space_slug: "alice".to_owned(),
+ auth_key: link_auth.to_owned(),
+ wrap_key: Vec::new(),
+ profile: DecryptedSpaceProfile {
+ space_id: "space-alice".to_owned(),
+ space_slug: "alice".to_owned(),
+ version: 1,
+ friends: 0,
+ profile: Vec::new(),
+ avatar: None,
+ cover: None,
+ updated_at: None,
+ },
+ posts: 0,
+ key_history: Mutex::new(BTreeMap::new()),
+ };
- let ctx = SpaceLinkCtx::open(OpenSpaceLinkCtxInput {
- base_url: server.url(),
- space_slug: "Alice".to_owned(),
- access_key: access_key.to_owned(),
- user_agent: None,
- client_package: None,
- client_version: None,
- })
- .await
- .unwrap();
-
- assert_eq!(ctx.profile().profile, profile);
- assert_eq!(ctx.profile().friends, 2);
- assert_eq!(ctx.posts(), 3);
assert_eq!(
- ctx.subscribe_web_push("https://push.example/subscription", "p256dh", "auth")
- .await
- .unwrap(),
+ ctx.subscribe_web_push(
+ WEB_PUSH_ENDPOINT.to_owned(),
+ WEB_PUSH_P256DH.to_owned(),
+ WEB_PUSH_AUTH.to_owned(),
+ )
+ .await
+ .unwrap(),
"wpt_target"
);
- ctx.unsubscribe_web_push("https://push.example/subscription")
+ ctx.unsubscribe_web_push(WEB_PUSH_ENDPOINT.to_owned())
.await
.unwrap();
- bootstrap.assert_async().await;
- profile_request.assert_async().await;
- versions.assert_async().await;
+
subscribe.assert_async().await;
unsubscribe.assert_async().await;
}
diff --git a/rust/space/src/transport.rs b/rust/space/src/transport.rs
index 9d3c333c31..4986d20d4d 100644
--- a/rust/space/src/transport.rs
+++ b/rust/space/src/transport.rs
@@ -406,30 +406,30 @@ pub struct SpaceLinkProfileResponse {
pub profile: SpaceProfileResponse,
}
-#[derive(Debug, Clone, Serialize)]
+#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct WebPushSubscriptionKeys {
- pub p256dh: String,
- pub auth: String,
+pub(crate) struct WebPushSubscriptionKeys {
+ pub(crate) p256dh: String,
+ pub(crate) auth: String,
}
-#[derive(Debug, Clone, Serialize)]
+#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct WebPushSubscriptionRequest {
- pub endpoint: String,
- pub keys: WebPushSubscriptionKeys,
+pub(crate) struct WebPushSubscriptionRequest {
+ pub(crate) endpoint: String,
+ pub(crate) keys: WebPushSubscriptionKeys,
}
-#[derive(Debug, Clone, Serialize)]
+#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct WebPushUnsubscriptionRequest {
- pub endpoint: String,
+pub(crate) struct WebPushUnsubscriptionRequest {
+ pub(crate) endpoint: String,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
-pub struct WebPushTargetResponse {
- pub target_id: String,
+pub(crate) struct WebPushTargetResponse {
+ pub(crate) target_id: String,
}
#[cfg(test)]
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index e9cc77e9ad..3c2e58df2f 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -989,7 +989,17 @@ func main() {
userEntityHandler := &api.UserEntityHandler{Controller: userEntityController}
spaceRepos := spacerepo.NewModule(db, s3Config)
userController.SpaceAccessResetter = spaceRepos
- spaceModule := spacecontroller.NewModule(spaceRepos, userAuthRepo, spacecontroller.NewSpaceWebPushSender(spaceRepos.WebPush))
+ spaceWebPushConfig := spacecontroller.NewSpaceWebPushConfig(
+ viper.GetString("space.webPush.publicKey"),
+ viper.GetString("space.webPush.privateKey"),
+ viper.GetString("space.webPush.subscriber"),
+ )
+ spaceModule := spacecontroller.NewModule(
+ spaceRepos,
+ userAuthRepo,
+ spacecontroller.NewSpaceWebPushSender(spaceRepos.WebPush, spaceWebPushConfig),
+ spaceWebPushConfig,
+ )
spaceModule.Posts.AbuseNotifier = discordController
spaceDripController := spacecontroller.NewSpaceDripController(spaceRepos, userRepo, notificationHistoryRepo, lockController)
spaceModule.UserTokens = userController
diff --git a/server/pkg/utils/email/space_drip_template_test.go b/server/pkg/utils/email/space_drip_template_test.go
new file mode 100644
index 0000000000..12f5a2c0a3
--- /dev/null
+++ b/server/pkg/utils/email/space_drip_template_test.go
@@ -0,0 +1,50 @@
+package email
+
+import (
+ "testing"
+
+ "github.com/ente/museum/internal/testutil"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSpaceDripTemplateRendersCTAAndBody(t *testing.T) {
+ testutil.WithServerRoot(t)
+
+ body, err := getMailBody("space_drip.html", map[string]interface{}{
+ "BodyLines": []string{
+ "Hey,",
+ "Your Ente Space profile is still unfinished.",
+ },
+ "CTAURL": "https://ente.space/app",
+ "CTALabel": "Finish setup",
+ })
+ require.NoError(t, err)
+ require.Contains(t, body, `role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#f0f1f3"`)
+ require.Contains(t, body, `max-width: 420px; width: 100%;`)
+ require.Contains(t, body, `align="left" style="color: #5f5f5f;`)
+ require.Contains(t, body, "Your Ente Space profile is still unfinished.")
+ require.Contains(t, body, `style="border-collapse: separate; border-spacing: 0; width: 100%;"`)
+ require.Contains(t, body, `href="https://ente.space/app"`)
+ require.Contains(t, body, "Finish setup")
+ require.Contains(t, body, `https://email-assets.ente.com/ente-2026-green.png`)
+ require.Contains(t, body, `class="footer-icons" style="width: 24px; padding: 4px"`)
+ require.Contains(t, body, "Ente Technologies, Inc.")
+}
+
+func TestSpaceDripTemplateOmitsCTAWithoutLabel(t *testing.T) {
+ testutil.WithServerRoot(t)
+
+ body, err := getMailBody("space_drip.html", map[string]interface{}{
+ "BodyLines": []string{
+ "Hey,",
+ "Reply to this email or drop a message on our Discord!",
+ },
+ "CTAURL": "https://ente.space/app",
+ })
+ require.NoError(t, err)
+ require.Contains(t, body, "Reply to this email or drop a message on our Discord!")
+ require.Contains(t, body, `padding: 0 0 0; text-align: left;`)
+ require.NotContains(t, body, `href="https://ente.space/app"`)
+ require.NotContains(t, body, `Open Ente Space`)
+ require.Contains(t, body, `https://email-assets.ente.com/ente-2026-green.png`)
+}
diff --git a/server/space/api/register.go b/server/space/api/register.go
index 3d4d131e3c..7e332a4aa3 100644
--- a/server/space/api/register.go
+++ b/server/space/api/register.go
@@ -5,7 +5,6 @@ import "github.com/gin-gonic/gin"
func Register(privateAPI, publicAPI gin.IRouter, handlers *Handlers) {
privateAPI.GET("/account/space", handlers.ListSpaces)
privateAPI.POST("/account/space", handlers.CreateSpace)
- privateAPI.GET("/account/space/push/vapid-key", handlers.GetWebPushVAPIDKey)
privateAPI.PUT("/account/space/push/subscription", handlers.UpsertWebPushSubscription)
privateAPI.DELETE("/account/space/push/subscription", handlers.DeleteWebPushSubscription)
diff --git a/server/space/api/sessions_test.go b/server/space/api/sessions_test.go
index f637a70a1b..8dc6dc086a 100644
--- a/server/space/api/sessions_test.go
+++ b/server/space/api/sessions_test.go
@@ -36,7 +36,10 @@ func (failingUserTokenTerminator) TerminateSession(int64, string) error {
return errors.New("cache eviction failed")
}
-func setupSpaceSessionAPITest(t *testing.T) (*Handlers, *spacerepo.Module, int64) {
+func setupSpaceSessionAPITest(
+ t *testing.T,
+ webPushConfig *controller.SpaceWebPushConfig,
+) (*Handlers, *spacerepo.Module, int64) {
t.Helper()
testutil.WithServerRoot(t)
db := testutil.RequireTestDB(t)
@@ -60,12 +63,13 @@ func setupSpaceSessionAPITest(t *testing.T) (*Handlers, *spacerepo.Module, int64
return NewHandlers(controller.NewModule(
repos,
&baserepo.UserAuthRepository{DB: db},
- controller.NewSpaceWebPushSender(repos.WebPush),
+ controller.NewSpaceWebPushSender(repos.WebPush, webPushConfig),
+ webPushConfig,
)), repos, userID
}
func TestCreateSpaceBrowserSessionReturnsTokenWhenCacheEvictionFails(t *testing.T) {
- handlers, repos, userID := setupSpaceSessionAPITest(t)
+ handlers, repos, userID := setupSpaceSessionAPITest(t, nil)
handlers.Module.UserTokens = failingUserTokenTerminator{}
authToken := "space-bootstrap-token"
require.NoError(t, (&baserepo.UserAuthRepository{DB: repos.Sessions.DB}).AddToken(userID, ente.Photos, authToken, "127.0.0.1", "space-test"))
@@ -92,7 +96,7 @@ func TestCreateSpaceBrowserSessionReturnsTokenWhenCacheEvictionFails(t *testing.
}
func TestCreateSpaceBrowserSessionRejectsInvalidWrapKey(t *testing.T) {
- handlers, repos, userID := setupSpaceSessionAPITest(t)
+ handlers, repos, userID := setupSpaceSessionAPITest(t, nil)
router := gin.New()
router.POST("/account/space/sessions", setTestAuthenticatedApp, handlers.CreateBrowserSession)
@@ -121,7 +125,7 @@ func TestCreateSpaceBrowserSessionRejectsInvalidWrapKey(t *testing.T) {
}
func TestRegisteredTokenSessionRoutesEnforceAppPolicy(t *testing.T) {
- handlers, repos, userID := setupSpaceSessionAPITest(t)
+ handlers, repos, userID := setupSpaceSessionAPITest(t, nil)
authToken := "space-route-bootstrap-token"
require.NoError(t, (&baserepo.UserAuthRepository{DB: repos.Sessions.DB}).AddToken(userID, ente.Photos, authToken, "127.0.0.1", "space-test"))
router := gin.New()
@@ -169,7 +173,7 @@ func TestRegisteredTokenSessionRoutesEnforceAppPolicy(t *testing.T) {
}
func TestRequireSpaceBrowserSessionAcceptsValidHeader(t *testing.T) {
- handlers, repos, userID := setupSpaceSessionAPITest(t)
+ handlers, repos, userID := setupSpaceSessionAPITest(t, nil)
token := "valid-space-session-token"
tokenHash := sha256.Sum256([]byte(token))
require.NoError(t, repos.Sessions.CreateBrowserSession(context.Background(), tokenHash[:], userID, "session-wrap-key", timeutil.NDaysFromNow(1)))
@@ -190,7 +194,7 @@ func TestRequireSpaceBrowserSessionAcceptsValidHeader(t *testing.T) {
}
func TestValidateSpaceBrowserSessionCoalescesLastUsedAtUpdates(t *testing.T) {
- handlers, repos, userID := setupSpaceSessionAPITest(t)
+ handlers, repos, userID := setupSpaceSessionAPITest(t, nil)
token := "space-session-touch-token"
tokenHash := sha256.Sum256([]byte(token))
require.NoError(t, repos.Sessions.CreateBrowserSession(context.Background(), tokenHash[:], userID, "session-wrap-key", timeutil.NDaysFromNow(1)))
@@ -218,7 +222,7 @@ func TestValidateSpaceBrowserSessionCoalescesLastUsedAtUpdates(t *testing.T) {
}
func TestRequireSpaceBrowserSessionRejectsInvalidHeader(t *testing.T) {
- handlers, _, _ := setupSpaceSessionAPITest(t)
+ handlers, _, _ := setupSpaceSessionAPITest(t, nil)
router := gin.New()
router.GET("/space", handlers.RequireSpaceBrowserSession(), func(c *gin.Context) {
c.Status(http.StatusOK)
@@ -234,7 +238,7 @@ func TestRequireSpaceBrowserSessionRejectsInvalidHeader(t *testing.T) {
}
func TestBootstrapBrowserSessionAcceptsHeader(t *testing.T) {
- handlers, repos, userID := setupSpaceSessionAPITest(t)
+ handlers, repos, userID := setupSpaceSessionAPITest(t, nil)
token := "valid-space-session-token"
tokenHash := sha256.Sum256([]byte(token))
require.NoError(t, repos.Sessions.CreateBrowserSession(context.Background(), tokenHash[:], userID, "session-wrap-key", timeutil.NDaysFromNow(1)))
@@ -251,7 +255,7 @@ func TestBootstrapBrowserSessionAcceptsHeader(t *testing.T) {
}
func TestDeleteBrowserSessionRevokesAllUserSessions(t *testing.T) {
- handlers, repos, userID := setupSpaceSessionAPITest(t)
+ handlers, repos, userID := setupSpaceSessionAPITest(t, nil)
otherUserID := testutil.InsertUser(t, repos.Sessions.DB, testutil.UserFixture{
CreationTime: timeutil.Microseconds(),
@@ -280,7 +284,7 @@ func TestDeleteBrowserSessionRevokesAllUserSessions(t *testing.T) {
}
func TestDeleteBrowserSessionDoesNotAcceptExpiredSession(t *testing.T) {
- handlers, repos, userID := setupSpaceSessionAPITest(t)
+ handlers, repos, userID := setupSpaceSessionAPITest(t, nil)
expiredToken := "expired-space-session-token"
expiredHash := sha256.Sum256([]byte(expiredToken))
require.NoError(t, repos.Sessions.CreateBrowserSession(context.Background(), expiredHash[:], userID, "expired-wrap-key", timeutil.Microseconds()-1))
diff --git a/server/space/api/spaces_test.go b/server/space/api/spaces_test.go
index 01fb2f5195..c355f755f8 100644
--- a/server/space/api/spaces_test.go
+++ b/server/space/api/spaces_test.go
@@ -34,7 +34,8 @@ func TestSpaceSlugAvailabilityRouteReturnsOK(t *testing.T) {
Register(router.Group(""), router.Group(""), NewHandlers(controller.NewModule(
repos,
&baserepo.UserAuthRepository{DB: db},
- controller.NewSpaceWebPushSender(repos.WebPush),
+ controller.NewSpaceWebPushSender(repos.WebPush, nil),
+ nil,
)))
existing := httptest.NewRecorder()
diff --git a/server/space/api/web_push_test.go b/server/space/api/web_push_test.go
index 599faaaeed..9cfb5ae7a9 100644
--- a/server/space/api/web_push_test.go
+++ b/server/space/api/web_push_test.go
@@ -16,16 +16,15 @@ import (
timeutil "github.com/ente/museum/pkg/utils/time"
"github.com/ente/museum/space/controller"
"github.com/gin-gonic/gin"
- "github.com/spf13/viper"
"github.com/stretchr/testify/require"
)
func TestSpaceWebPushAccountSubscriptionAPI(t *testing.T) {
- handlers, repos, userID := setupSpaceSessionAPITest(t)
+ webPushConfig, vapidPublicKey := newSpaceWebPushAPITestConfig(t)
+ handlers, repos, userID := setupSpaceSessionAPITest(t, webPushConfig)
sessionToken := "space-web-push-session"
sessionHash := sha256.Sum256([]byte(sessionToken))
require.NoError(t, repos.Sessions.CreateBrowserSession(context.Background(), sessionHash[:], userID, "wrap-key", timeutil.NDaysFromNow(1)))
- vapidPublicKey := setSpaceWebPushTestConfig(t)
publicRouter := gin.New()
publicRouter.GET("/space/push/vapid-key", handlers.GetWebPushVAPIDKey)
@@ -85,9 +84,7 @@ func TestSpaceWebPushAccountSubscriptionAPI(t *testing.T) {
}
func TestSpaceWebPushVAPIDKeyRequiresCompleteConfig(t *testing.T) {
- handlers, _, _ := setupSpaceSessionAPITest(t)
- setSpaceWebPushTestConfig(t)
- viper.Set("space.webPush.privateKey", "")
+ handlers, _, _ := setupSpaceSessionAPITest(t, nil)
router := gin.New()
router.GET("/space/push/vapid-key", handlers.GetWebPushVAPIDKey)
@@ -97,17 +94,13 @@ func TestSpaceWebPushVAPIDKeyRequiresCompleteConfig(t *testing.T) {
require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
}
-func setSpaceWebPushTestConfig(t *testing.T) string {
+func newSpaceWebPushAPITestConfig(
+ t *testing.T,
+) (*controller.SpaceWebPushConfig, string) {
t.Helper()
privateKey, publicKey, err := webpush.GenerateVAPIDKeys()
require.NoError(t, err)
- viper.Set("space.webPush.publicKey", publicKey)
- viper.Set("space.webPush.privateKey", privateKey)
- viper.Set("space.webPush.subscriber", "[email protected]")
- t.Cleanup(func() {
- viper.Set("space.webPush.publicKey", "")
- viper.Set("space.webPush.privateKey", "")
- viper.Set("space.webPush.subscriber", "")
- })
- return publicKey
+ config := controller.NewSpaceWebPushConfig(publicKey, privateKey, "[email protected]")
+ require.NotNil(t, config)
+ return config, publicKey
}
diff --git a/server/space/controller/auth_test.go b/server/space/controller/auth_test.go
index 896147d5e3..450a6879ab 100644
--- a/server/space/controller/auth_test.go
+++ b/server/space/controller/auth_test.go
@@ -28,7 +28,7 @@ func setupSpaceAuthControllerTest(t *testing.T) (*Module, *spacerepo.Module, *ba
gin.SetMode(gin.TestMode)
repos := spacerepo.NewModule(db, nil)
userAuthRepo := &baserepo.UserAuthRepository{DB: db}
- return NewModule(repos, userAuthRepo, noopSpaceActivityNotifier{}), repos, userAuthRepo, context.Background()
+ return NewModule(repos, userAuthRepo, noopSpaceActivityNotifier{}, nil), repos, userAuthRepo, context.Background()
}
func newPublicSpaceContext() *gin.Context {
diff --git a/server/space/controller/friends_test.go b/server/space/controller/friends_test.go
index 71e379e546..cc6a2024de 100644
--- a/server/space/controller/friends_test.go
+++ b/server/space/controller/friends_test.go
@@ -13,7 +13,7 @@ import (
func setupFriendsControllerTest(t *testing.T) (*FriendsController, *spacerepo.Module, context.Context) {
t.Helper()
_, repos, ctx := setupPostsControllerTest(t)
- return NewModule(repos, nil, noopSpaceActivityNotifier{}).Friends, repos, ctx
+ return NewModule(repos, nil, noopSpaceActivityNotifier{}, nil).Friends, repos, ctx
}
func TestFriendRelationshipReportsSelfFriendAndEmpty(t *testing.T) {
diff --git a/server/space/controller/messages_test.go b/server/space/controller/messages_test.go
index 4454deec5c..f2297dd2b1 100644
--- a/server/space/controller/messages_test.go
+++ b/server/space/controller/messages_test.go
@@ -25,7 +25,7 @@ func setupMessagesControllerTest(t *testing.T) (*MessagesController, *spacerepo.
})
gin.SetMode(gin.TestMode)
repos := spacerepo.NewModule(db, nil)
- return NewModule(repos, nil, noopSpaceActivityNotifier{}).Messages, repos, context.Background()
+ return NewModule(repos, nil, noopSpaceActivityNotifier{}, nil).Messages, repos, context.Background()
}
func TestMessageReplyValidation(t *testing.T) {
diff --git a/server/space/controller/module.go b/server/space/controller/module.go
index f22e50c091..c66ae0bb7f 100644
--- a/server/space/controller/module.go
+++ b/server/space/controller/module.go
@@ -25,7 +25,12 @@ type UserTokenTerminator interface {
TerminateSession(userID int64, token string) error
}
-func NewModule(repos *repo.Module, userAuthRepo *baserepo.UserAuthRepository, activityNotifier SpaceActivityNotifier) *Module {
+func NewModule(
+ repos *repo.Module,
+ userAuthRepo *baserepo.UserAuthRepository,
+ activityNotifier SpaceActivityNotifier,
+ webPushConfig *SpaceWebPushConfig,
+) *Module {
authDeps := authDeps{
UserAuthRepo: userAuthRepo,
SpacesRepo: repos.Spaces,
@@ -44,7 +49,7 @@ func NewModule(repos *repo.Module, userAuthRepo *baserepo.UserAuthRepository, ac
Assets: assets,
Read: &ReadMarkersController{ReadMarkersRepo: repos.Read},
Sessions: &SessionsController{SessionsRepo: repos.Sessions},
- WebPush: &WebPushController{WebPushRepo: repos.WebPush, Links: links},
+ WebPush: &WebPushController{WebPushRepo: repos.WebPush, Links: links, config: webPushConfig},
Cleanup: &CleanupController{AssetsRepo: repos.Assets},
Links: links,
auth: authDeps,
diff --git a/server/space/controller/notifications.go b/server/space/controller/notifications.go
index 1720c542fd..1ce97ca5bb 100644
--- a/server/space/controller/notifications.go
+++ b/server/space/controller/notifications.go
@@ -50,6 +50,7 @@ type SpaceActivityNotifier interface {
type SpaceWebPushSender struct {
WebPushRepo *repo.WebPushRepository
HTTPClient webpush.HTTPClient
+ config *SpaceWebPushConfig
sendLimiter *limiter.Limiter
sendSlots chan struct{}
}
@@ -62,10 +63,14 @@ type spaceWebPushPayload struct {
TargetID string `json:"targetId,omitempty"`
}
-func NewSpaceWebPushSender(webPushRepo *repo.WebPushRepository) *SpaceWebPushSender {
+func NewSpaceWebPushSender(
+ webPushRepo *repo.WebPushRepository,
+ config *SpaceWebPushConfig,
+) *SpaceWebPushSender {
return &SpaceWebPushSender{
WebPushRepo: webPushRepo,
HTTPClient: newSpaceWebPushHTTPClient(),
+ config: config,
sendLimiter: util.NewRateLimiter(spaceWebPushSendRate),
sendSlots: make(chan struct{}, spaceWebPushConcurrency),
}
@@ -180,6 +185,7 @@ func (n *SpaceWebPushSender) available() bool {
return n != nil &&
n.WebPushRepo != nil &&
n.HTTPClient != nil &&
+ n.config != nil &&
n.sendLimiter != nil &&
n.sendSlots != nil &&
!viper.GetBool("internal.silent")
@@ -190,8 +196,8 @@ func (n *SpaceWebPushSender) send(
actorSlug, activity, action, event, destination string,
subscriptions []repo.SpaceWebPushSubscriptionRecord,
) {
- options, ok := spaceWebPushOptions(n.HTTPClient)
- if !ok {
+ options := spaceWebPushOptions(n.config, n.HTTPClient)
+ if options == nil {
return
}
subscriptions = deduplicateSpaceWebPushSubscriptions(subscriptions)
@@ -286,19 +292,21 @@ func (n *SpaceWebPushSender) sendSubscription(
}
}
-func spaceWebPushOptions(client webpush.HTTPClient) (*webpush.Options, bool) {
- config, ok := configuredSpaceWebPush()
- if !ok {
- return nil, false
+func spaceWebPushOptions(
+ config *SpaceWebPushConfig,
+ client webpush.HTTPClient,
+) *webpush.Options {
+ if config == nil {
+ return nil
}
return &webpush.Options{
HTTPClient: client,
- Subscriber: config.Subscriber,
+ Subscriber: config.subscriber,
TTL: spaceWebPushTTLSeconds,
Urgency: webpush.UrgencyNormal,
- VAPIDPublicKey: config.PublicKey,
- VAPIDPrivateKey: config.PrivateKey,
- }, true
+ VAPIDPublicKey: config.publicKey,
+ VAPIDPrivateKey: config.privateKey,
+ }
}
func deduplicateSpaceWebPushSubscriptions(
diff --git a/server/space/controller/notifications_test.go b/server/space/controller/notifications_test.go
index eb16959862..244de12e96 100644
--- a/server/space/controller/notifications_test.go
+++ b/server/space/controller/notifications_test.go
@@ -18,7 +18,6 @@ import (
timeutil "github.com/ente/museum/pkg/utils/time"
"github.com/ente/museum/space/models"
"github.com/ente/museum/space/repo"
- "github.com/spf13/viper"
"github.com/stretchr/testify/require"
)
@@ -127,29 +126,30 @@ func TestSpaceWebPushAddressMustBePublic(t *testing.T) {
func TestSpaceWebPushConfigRequiresMatchingKeysAndBareSubscriber(t *testing.T) {
privateKey, publicKey, err := webpush.GenerateVAPIDKeys()
require.NoError(t, err)
- viper.Set("space.webPush.publicKey", publicKey)
- viper.Set("space.webPush.privateKey", privateKey)
- viper.Set("space.webPush.subscriber", "[email protected]")
- t.Cleanup(func() {
- viper.Set("space.webPush.publicKey", "")
- viper.Set("space.webPush.privateKey", "")
- viper.Set("space.webPush.subscriber", "")
- })
-
- config, ok := configuredSpaceWebPush()
- require.True(t, ok)
- require.Equal(t, publicKey, config.PublicKey)
+ config := NewSpaceWebPushConfig(publicKey, privateKey, "[email protected]")
+ require.NotNil(t, config)
+ require.Equal(t, publicKey, config.publicKey)
otherPrivateKey, _, err := webpush.GenerateVAPIDKeys()
require.NoError(t, err)
- viper.Set("space.webPush.privateKey", otherPrivateKey)
- _, ok = configuredSpaceWebPush()
- require.False(t, ok)
-
- viper.Set("space.webPush.privateKey", privateKey)
- viper.Set("space.webPush.subscriber", "mailto:[email protected]")
- _, ok = configuredSpaceWebPush()
- require.False(t, ok)
+ require.Nil(t, NewSpaceWebPushConfig(publicKey, otherPrivateKey, "[email protected]"))
+ require.Nil(t, NewSpaceWebPushConfig(publicKey, privateKey, "mailto:[email protected]"))
+ require.Nil(t, NewSpaceWebPushConfig("", "", ""))
+}
+
+func newSpaceWebPushTestConfig(t *testing.T) *SpaceWebPushConfig {
+ t.Helper()
+ privateKey, publicKey, err := webpush.GenerateVAPIDKeys()
+ require.NoError(t, err)
+ config := NewSpaceWebPushConfig(publicKey, privateKey, "[email protected]")
+ require.NotNil(t, config)
+ return config
+}
+
+func TestUnconfiguredSpaceWebPushSenderIsUnavailable(t *testing.T) {
+ sender := NewSpaceWebPushSender(&repo.WebPushRepository{}, nil)
+ require.False(t, sender.available())
+ sender.OnSpacePostReplied(1, "alice_space", "alice", 2)
}
func TestSpaceWebPushDeduplicatesSharedEndpointForAccount(t *testing.T) {
@@ -167,7 +167,7 @@ func TestSpaceWebPushDeduplicatesSharedEndpointForAccount(t *testing.T) {
func TestNewPostNotifiesWithNoAccountFriends(t *testing.T) {
_, repos, _ := setupPostsControllerTest(t)
notifier := newRecordingSpaceActivityNotifier()
- posts := NewModule(repos, nil, notifier).Posts
+ posts := NewModule(repos, nil, notifier, nil).Posts
posts.notifyFriendsOfNewPost(1, "space_id", "alice")
@@ -182,7 +182,7 @@ func TestNewPostNotifiesWithNoAccountFriends(t *testing.T) {
func TestPostLikeSendsActivityOnlyOnLikeTransition(t *testing.T) {
_, repos, ctx := setupPostsControllerTest(t)
notifier := newRecordingSpaceActivityNotifier()
- posts := NewModule(repos, nil, notifier).Posts
+ posts := NewModule(repos, nil, notifier, nil).Posts
aliceID := insertSpaceControllerUser(t, repos, "[email protected]", "alice-public")
bobID := insertSpaceControllerUser(t, repos, "[email protected]", "bob-public")
aliceSpace, err := testCreateSpace(ctx, repos, aliceID, "alice_post_like_push", "alice-space-key", "alice-post-public", "alice-post-secret", "nonce", "alice-profile")
@@ -218,7 +218,7 @@ func TestPostLikeSendsActivityOnlyOnLikeTransition(t *testing.T) {
func TestMessageActivitiesAndLikeTransition(t *testing.T) {
_, repos, ctx := setupMessagesControllerTest(t)
notifier := newRecordingSpaceActivityNotifier()
- messages := NewModule(repos, nil, notifier).Messages
+ messages := NewModule(repos, nil, notifier, nil).Messages
aliceID, aliceSpace := createMessageControllerUserAndSpace(t, repos, "alice-message-push", "alice-public")
bobID, bobSpace := createMessageControllerUserAndSpace(t, repos, "bob-message-push", "bob-public")
require.NoError(t, testAddFriend(ctx, repos, bobID, bobSpace.SpaceID, aliceSpace.SpaceID, "alice-share-key", aliceSpace.CurrentVersion, "bob-share-key", bobSpace.CurrentVersion))
@@ -271,7 +271,7 @@ func TestMessageActivitiesAndLikeTransition(t *testing.T) {
func TestFriendActivitiesOnlyOnRelationshipTransitions(t *testing.T) {
_, repos, ctx := setupFriendsControllerTest(t)
notifier := newRecordingSpaceActivityNotifier()
- friends := NewModule(repos, nil, notifier).Friends
+ friends := NewModule(repos, nil, notifier, nil).Friends
aliceID := insertSpaceControllerUser(t, repos, "[email protected]", "alice-public")
bobID := insertSpaceControllerUser(t, repos, "[email protected]", "bob-public")
aliceSpace, err := testCreateSpace(ctx, repos, aliceID, "alice_friend_push", "alice-space-key", "alice-public", "alice-secret", "nonce", "alice-profile")
@@ -321,16 +321,7 @@ func TestSpaceWebPushSenderUsesGenericPayloadAndPrunesDeadEndpoint(t *testing.T)
_, err := repos.WebPush.UpsertAccountSubscription(ctx, sessionHash, "https://push.example/subscription", "p256dh", "auth")
require.NoError(t, err)
- vapidPrivateKey, vapidPublicKey, err := webpush.GenerateVAPIDKeys()
- require.NoError(t, err)
- viper.Set("space.webPush.publicKey", vapidPublicKey)
- viper.Set("space.webPush.privateKey", vapidPrivateKey)
- viper.Set("space.webPush.subscriber", "[email protected]")
- t.Cleanup(func() {
- viper.Set("space.webPush.publicKey", "")
- viper.Set("space.webPush.privateKey", "")
- viper.Set("space.webPush.subscriber", "")
- })
+ config := newSpaceWebPushTestConfig(t)
originalSend := sendSpaceWebPush
t.Cleanup(func() { sendSpaceWebPush = originalSend })
@@ -344,7 +335,7 @@ func TestSpaceWebPushSenderUsesGenericPayloadAndPrunesDeadEndpoint(t *testing.T)
return &http.Response{StatusCode: http.StatusGone, Body: io.NopCloser(strings.NewReader(""))}, nil
}
- sender := NewSpaceWebPushSender(repos.WebPush)
+ sender := NewSpaceWebPushSender(repos.WebPush, config)
sender.OnSpacePostReplied(1, "alice_space", "alice", recipientID)
require.Equal(t, spaceWebPushPayload{
Title: "Ente Space",
@@ -358,16 +349,7 @@ func TestSpaceWebPushSenderUsesGenericPayloadAndPrunesDeadEndpoint(t *testing.T)
}
func TestPublicPostPushCarriesOnlyOpaqueLocalRouteTarget(t *testing.T) {
- vapidPrivateKey, vapidPublicKey, err := webpush.GenerateVAPIDKeys()
- require.NoError(t, err)
- viper.Set("space.webPush.publicKey", vapidPublicKey)
- viper.Set("space.webPush.privateKey", vapidPrivateKey)
- viper.Set("space.webPush.subscriber", "[email protected]")
- t.Cleanup(func() {
- viper.Set("space.webPush.publicKey", "")
- viper.Set("space.webPush.privateKey", "")
- viper.Set("space.webPush.subscriber", "")
- })
+ config := newSpaceWebPushTestConfig(t)
originalSend := sendSpaceWebPush
t.Cleanup(func() { sendSpaceWebPush = originalSend })
@@ -377,7 +359,7 @@ func TestPublicPostPushCarriesOnlyOpaqueLocalRouteTarget(t *testing.T) {
return &http.Response{StatusCode: http.StatusCreated, Body: io.NopCloser(strings.NewReader(""))}, nil
}
- sender := NewSpaceWebPushSender(nil)
+ sender := NewSpaceWebPushSender(nil, config)
sender.send(
2,
"alice",
@@ -402,16 +384,7 @@ func TestPublicPostPushCarriesOnlyOpaqueLocalRouteTarget(t *testing.T) {
}
func TestSpaceWebPushSendRateAppliesOncePerActivity(t *testing.T) {
- vapidPrivateKey, vapidPublicKey, err := webpush.GenerateVAPIDKeys()
- require.NoError(t, err)
- viper.Set("space.webPush.publicKey", vapidPublicKey)
- viper.Set("space.webPush.privateKey", vapidPrivateKey)
- viper.Set("space.webPush.subscriber", "[email protected]")
- t.Cleanup(func() {
- viper.Set("space.webPush.publicKey", "")
- viper.Set("space.webPush.privateKey", "")
- viper.Set("space.webPush.subscriber", "")
- })
+ config := newSpaceWebPushTestConfig(t)
originalSend := sendSpaceWebPush
t.Cleanup(func() { sendSpaceWebPush = originalSend })
@@ -429,7 +402,7 @@ func TestSpaceWebPushSendRateAppliesOncePerActivity(t *testing.T) {
Auth: "auth",
}
}
- NewSpaceWebPushSender(nil).send(
+ NewSpaceWebPushSender(nil, config).send(
3,
"alice",
"posted a new photo",
diff --git a/server/space/controller/test_helpers_test.go b/server/space/controller/test_helpers_test.go
index b16e8d721e..39fb035a18 100644
--- a/server/space/controller/test_helpers_test.go
+++ b/server/space/controller/test_helpers_test.go
@@ -23,7 +23,7 @@ func setupPostsControllerTest(t *testing.T) (*PostsController, *spacerepo.Module
})
gin.SetMode(gin.TestMode)
repos := spacerepo.NewModule(db, nil)
- return NewModule(repos, nil, noopSpaceActivityNotifier{}).Posts, repos, context.Background()
+ return NewModule(repos, nil, noopSpaceActivityNotifier{}, nil).Posts, repos, context.Background()
}
type noopSpaceActivityNotifier struct{}
diff --git a/server/space/controller/web_push.go b/server/space/controller/web_push.go
index c8bbb57d36..d8f1f44632 100644
--- a/server/space/controller/web_push.go
+++ b/server/space/controller/web_push.go
@@ -17,7 +17,6 @@ import (
"github.com/ente/museum/space/repo"
"github.com/ente/stacktrace"
"github.com/gin-gonic/gin"
- "github.com/spf13/viper"
)
const (
@@ -29,24 +28,24 @@ const (
type WebPushController struct {
WebPushRepo *repo.WebPushRepository
Links *LinksController
+ config *SpaceWebPushConfig
}
-type spaceWebPushConfig struct {
- PublicKey string
- PrivateKey string
- Subscriber string
+type SpaceWebPushConfig struct {
+ publicKey string
+ privateKey string
+ subscriber string
}
func (c *WebPushController) VAPIDPublicKey() (*models.SpaceWebPushVAPIDKeyResponse, error) {
- config, ok := configuredSpaceWebPush()
- if !ok {
+ if c == nil || c.config == nil {
return nil, &ente.ApiError{
Code: ente.ErrorCode("SPACE_WEB_PUSH_UNAVAILABLE"),
Message: "space web push is unavailable",
HttpStatusCode: http.StatusServiceUnavailable,
}
}
- return &models.SpaceWebPushVAPIDKeyResponse{PublicKey: config.PublicKey}, nil
+ return &models.SpaceWebPushVAPIDKeyResponse{PublicKey: c.config.publicKey}, nil
}
func (c *WebPushController) UpsertAccountSubscription(
@@ -183,29 +182,29 @@ func validateWebPushSubscription(endpoint, p256dh, auth string) error {
return nil
}
-func configuredSpaceWebPush() (spaceWebPushConfig, bool) {
- config := spaceWebPushConfig{
- PublicKey: strings.TrimSpace(viper.GetString("space.webPush.publicKey")),
- PrivateKey: strings.TrimSpace(viper.GetString("space.webPush.privateKey")),
- Subscriber: strings.TrimSpace(viper.GetString("space.webPush.subscriber")),
+func NewSpaceWebPushConfig(publicKey, privateKey, subscriber string) *SpaceWebPushConfig {
+ config := &SpaceWebPushConfig{
+ publicKey: strings.TrimSpace(publicKey),
+ privateKey: strings.TrimSpace(privateKey),
+ subscriber: strings.TrimSpace(subscriber),
}
- decodedPublicKey, publicKeyErr := decodeBase64URL(config.PublicKey)
+ decodedPublicKey, publicKeyErr := decodeBase64URL(config.publicKey)
_, publicCurveErr := ecdh.P256().NewPublicKey(decodedPublicKey)
- decodedPrivateKey, privateKeyErr := decodeBase64URL(config.PrivateKey)
- privateKey, privateCurveErr := ecdh.P256().NewPrivateKey(decodedPrivateKey)
- subscriber, subscriberErr := mail.ParseAddress(config.Subscriber)
+ decodedPrivateKey, privateKeyErr := decodeBase64URL(config.privateKey)
+ parsedPrivateKey, privateCurveErr := ecdh.P256().NewPrivateKey(decodedPrivateKey)
+ parsedSubscriber, subscriberErr := mail.ParseAddress(config.subscriber)
if publicKeyErr != nil ||
len(decodedPublicKey) != 65 ||
publicCurveErr != nil ||
privateKeyErr != nil ||
len(decodedPrivateKey) != 32 ||
privateCurveErr != nil ||
- !bytes.Equal(privateKey.PublicKey().Bytes(), decodedPublicKey) ||
+ !bytes.Equal(parsedPrivateKey.PublicKey().Bytes(), decodedPublicKey) ||
subscriberErr != nil ||
- subscriber.Address != config.Subscriber {
- return spaceWebPushConfig{}, false
+ parsedSubscriber.Address != config.subscriber {
+ return nil
}
- return config, true
+ return config
}
func decodeBase64URL(value string) ([]byte, error) {