π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
wall: guard encrypted writes by key version
Neeraj Guptad3ab1bf1856e
diff --git a/rust/wall/src/client.rs b/rust/wall/src/client.rsindex f7492668e6..c4ff6fc53b 100644--- a/rust/wall/src/client.rs+++ b/rust/wall/src/client.rs@@ -549,6 +549,7 @@ impl AccountWallCtx {&access.wall_key,&post_key_bytes,)?),+ key_version: access.key_version,caption_cipher,objects: objects.to_vec(),};@@ -832,6 +833,7 @@ impl AccountWallCtx {request_id: request.request_id,wall_id: request.wall_id.clone(),encrypted_wall_key: encode_b64(&pack_payload(&sealed_share, &[])),+ key_version: access.key_version,};self.client.post_json("/wall/follow/approve", &payload)@@ -922,6 +924,7 @@ impl AccountWallCtx {}let payload = RefreshFollowSharesRequest {wall_id: wall_id.to_owned(),+ key_version: access.key_version,shares: updates,};let updated = payload.shares.len();@@ -1616,6 +1619,142 @@ mod tests {upload.assert_async().await;}+ #[tokio::test]+ async fn create_post_includes_wall_key_version() {+ let mut server = Server::new_async().await;+ let ctx = test_account_ctx(&server.url());+ let root_wall_key = generate_key();+ let wall_key = generate_key();+ let entity_payload =+ encrypt_entity_key(&ctx.master_key, &root_wall_key).expect("root wall entity");++ let entity = server+ .mock("GET", "/user-entity/key")+ .match_header("x-auth-token", "token")+ .match_query(Matcher::UrlEncoded(+ "type".into(),+ ROOT_WALL_KEY_TYPE.into(),+ ))+ .with_status(200)+ .with_body(+ json!({+ "type": ROOT_WALL_KEY_TYPE,+ "encryptedKey": entity_payload.encrypted_key,+ "header": entity_payload.header,+ })+ .to_string(),+ )+ .create_async()+ .await;+ let walls = server+ .mock("GET", "/wall")+ .match_header("x-auth-token", "token")+ .with_status(200)+ .with_body(+ json!([{+ "wallId": "wall_owner_main",+ "wallSlug": "owner-main",+ "encryptedWallKey": encode_b64(&encrypt_secretbox_packed(&root_wall_key, &wall_key).expect("wall key wrap")),+ "encryptedProfile": "",+ "keyVersion": 3+ }])+ .to_string(),+ )+ .create_async()+ .await;+ let create = server+ .mock("POST", "/wall/posts")+ .match_header("x-auth-token", "token")+ .match_body(Matcher::Regex("\"keyVersion\":3".into()))+ .with_status(200)+ .with_body(json!({"postId": 42}).to_string())+ .create_async()+ .await;++ let (post_id, _) = ctx+ .create_post("wall_owner_main", &[], None, None)+ .await+ .expect("post creation should send key version");++ assert_eq!(post_id, 42);+ entity.assert_async().await;+ walls.assert_async().await;+ create.assert_async().await;+ }++ #[tokio::test]+ async fn approve_follow_request_includes_wall_key_version() {+ let mut server = Server::new_async().await;+ let ctx = test_account_ctx(&server.url());+ let root_wall_key = generate_key();+ let wall_key = generate_key();+ let (follower_public_key, _) = keys::generate_keypair().expect("valid follower keypair");+ let entity_payload =+ encrypt_entity_key(&ctx.master_key, &root_wall_key).expect("root wall entity");++ let entity = server+ .mock("GET", "/user-entity/key")+ .match_header("x-auth-token", "token")+ .match_query(Matcher::UrlEncoded(+ "type".into(),+ ROOT_WALL_KEY_TYPE.into(),+ ))+ .with_status(200)+ .with_body(+ json!({+ "type": ROOT_WALL_KEY_TYPE,+ "encryptedKey": entity_payload.encrypted_key,+ "header": entity_payload.header,+ })+ .to_string(),+ )+ .create_async()+ .await;+ let walls = server+ .mock("GET", "/wall")+ .match_header("x-auth-token", "token")+ .with_status(200)+ .with_body(+ json!([{+ "wallId": "wall_owner_main",+ "wallSlug": "owner-main",+ "encryptedWallKey": encode_b64(&encrypt_secretbox_packed(&root_wall_key, &wall_key).expect("wall key wrap")),+ "encryptedProfile": "",+ "keyVersion": 3+ }])+ .to_string(),+ )+ .create_async()+ .await;+ let approve = server+ .mock("POST", "/wall/follow/approve")+ .match_header("x-auth-token", "token")+ .match_body(Matcher::Regex("\"keyVersion\":3".into()))+ .with_status(200)+ .with_body(json!({"requestId": 11, "status": "approved"}).to_string())+ .create_async()+ .await;+ let request = FollowRequestResponse {+ request_id: 11,+ follower: "viewer".to_owned(),+ wall_id: "wall_owner_main".to_owned(),+ wall_slug: "owner-main".to_owned(),+ follower_public_key: encode_b64(&follower_public_key),+ status: "pending".to_owned(),+ created_at: "2026-04-16T00:00:00Z".to_owned(),+ };++ let response = ctx+ .approve_follow_request(&request)+ .await+ .expect("approval should send key version");++ assert_eq!(response.request_id, 11);+ entity.assert_async().await;+ walls.assert_async().await;+ approve.assert_async().await;+ }+#[tokio::test]async fn follow_request_helpers_use_explicit_incoming_and_outgoing_routes() {let mut server = Server::new_async().await;@@ -1826,7 +1965,10 @@ mod tests {let refresh = server.mock("POST", "/wall/follow/shares/refresh").match_header("x-auth-token", "token")- .match_body(Matcher::Regex("\"followerId\":7".into()))+ .match_body(Matcher::AllOf(vec![+ Matcher::Regex("\"followerId\":7".into()),+ Matcher::Regex("\"keyVersion\":3".into()),+ ])).with_status(200).create_async().await;diff --git a/rust/wall/src/transport.rs b/rust/wall/src/transport.rsindex 8981d28b5d..7300dd3b66 100644--- a/rust/wall/src/transport.rs+++ b/rust/wall/src/transport.rs@@ -99,6 +99,7 @@ pub struct PostObjectPayload {pub struct CreatePostRequest {pub wall_id: String,pub encrypted_post_key: String,+ pub key_version: i32,#[serde(skip_serializing_if = "Option::is_none")]pub caption_cipher: Option<String>,pub objects: Vec<PostObjectPayload>,@@ -314,6 +315,7 @@ pub struct ApproveFollowPayload {pub request_id: i64,pub wall_id: String,pub encrypted_wall_key: String,+ pub key_version: i32,}#[derive(Debug, Clone, Serialize)]@@ -349,6 +351,7 @@ pub struct ShareUpdatePayload {#[serde(rename_all = "camelCase")]pub struct RefreshFollowSharesRequest {pub wall_id: String,+ pub key_version: i32,pub shares: Vec<ShareUpdatePayload>,}diff --git a/server/wall/controller/follow.go b/server/wall/controller/follow.goindex 1b51d96897..2e2bf7a39f 100644--- a/server/wall/controller/follow.go+++ b/server/wall/controller/follow.go@@ -137,17 +137,17 @@ func (c *FollowController) Approve(ctx *gin.Context, req models.ApproveFollowPayif err != nil {return nil, err}- if req.RequestID <= 0 || strings.TrimSpace(req.WallID) == "" || strings.TrimSpace(req.EncryptedWallKey) == "" {- return nil, ente.NewBadRequestWithMessage("requestId, wallId and encryptedWallKey are required")+ if req.RequestID <= 0 || strings.TrimSpace(req.WallID) == "" || strings.TrimSpace(req.EncryptedWallKey) == "" || req.KeyVersion <= 0 {+ return nil, ente.NewBadRequestWithMessage("requestId, wallId, encryptedWallKey and keyVersion are required")}wall, err := c.auth.requireWallOwner(ctx.Request.Context(), userID, req.WallID)if err != nil {return nil, err}- record, err := c.FollowRepo.ApproveRequest(ctx.Request.Context(), req.RequestID, wall.WallID, req.EncryptedWallKey, wall.CurrentVersion)+ record, err := c.FollowRepo.ApproveRequest(ctx.Request.Context(), req.RequestID, wall.WallID, req.EncryptedWallKey, req.KeyVersion)if err != nil {if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {- return nil, ente.NewBadRequestWithMessage("follow request is not pending")+ return nil, ente.NewBadRequestWithMessage("follow request is not pending or keyVersion does not match current wall version")}return nil, err}@@ -239,16 +239,24 @@ func (c *FollowController) RefreshShares(ctx *gin.Context, req models.RefreshFolif err != nil {return err}+ if req.KeyVersion <= 0 {+ return ente.NewBadRequestWithMessage("keyVersion is required")+ }+ updates := make([]repo.WallShareUpdateRecord, 0, len(req.Shares))for _, share := range req.Shares {if share.FollowerID == 0 || strings.TrimSpace(share.EncryptedWallKey) == "" {return ente.NewBadRequestWithMessage("followerId and encryptedWallKey are required for each share")}- if err := c.FollowRepo.UpdateShare(ctx.Request.Context(), wall.WallID, share.FollowerID, share.EncryptedWallKey, wall.CurrentVersion); err != nil {- if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {- return ente.NewBadRequestWithMessage("follow share does not exist")- }- return err+ updates = append(updates, repo.WallShareUpdateRecord{+ FollowerID: share.FollowerID,+ EncryptedWallKey: share.EncryptedWallKey,+ })+ }+ if err := c.FollowRepo.UpdateShares(ctx.Request.Context(), wall.WallID, updates, req.KeyVersion); err != nil {+ if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {+ return ente.NewBadRequestWithMessage("keyVersion does not match current wall version or follow share does not exist")}+ return err}return nil}diff --git a/server/wall/controller/posts.go b/server/wall/controller/posts.goindex 069bb51d6a..4fa3cfed67 100644--- a/server/wall/controller/posts.go+++ b/server/wall/controller/posts.go@@ -29,6 +29,9 @@ func (c *PostsController) Create(ctx *gin.Context, req models.CreatePostRequest)if strings.TrimSpace(req.WallID) == "" || strings.TrimSpace(req.EncryptedPostKey) == "" || len(req.Objects) == 0 {return nil, ente.NewBadRequestWithMessage("wallId, encryptedPostKey and objects are required")}+ if req.KeyVersion <= 0 {+ return nil, ente.NewBadRequestWithMessage("keyVersion is required")+ }wall, err := c.auth.requireWallOwner(ctx.Request.Context(), userID, req.WallID)if err != nil {return nil, err@@ -51,8 +54,11 @@ func (c *PostsController) Create(ctx *gin.Context, req models.CreatePostRequest)BlurHashCipher: sql.NullString{String: object.BlurHashCipher, Valid: strings.TrimSpace(object.BlurHashCipher) != ""},})}- postID, err := c.PostsRepo.CreatePost(ctx.Request.Context(), userID, wall.WallID, req.EncryptedPostKey, req.CaptionCipher, wall.CurrentVersion, assets)+ postID, err := c.PostsRepo.CreatePost(ctx.Request.Context(), userID, wall.WallID, req.EncryptedPostKey, req.CaptionCipher, req.KeyVersion, assets)if err != nil {+ if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {+ return nil, ente.NewBadRequestWithMessage("keyVersion does not match current wall version")+ }return nil, err}return &models.CreatePostResponse{PostID: postID}, nildiff --git a/server/wall/models/models.go b/server/wall/models/models.goindex d95862292f..fef531c20a 100644--- a/server/wall/models/models.go+++ b/server/wall/models/models.go@@ -112,6 +112,7 @@ type ApproveFollowPayload struct {RequestID int64 `json:"requestId"`WallID string `json:"wallId"`EncryptedWallKey string `json:"encryptedWallKey"`+ KeyVersion int `json:"keyVersion"`}type RejectFollowPayload struct {@@ -213,8 +214,9 @@ type WallFollowerResponse struct {}type RefreshFollowSharesRequest struct {- WallID string `json:"wallId"`- Shares []ShareUpdatePayload `json:"shares"`+ WallID string `json:"wallId"`+ KeyVersion int `json:"keyVersion"`+ Shares []ShareUpdatePayload `json:"shares"`}type ShareUpdatePayload struct {@@ -225,6 +227,7 @@ type ShareUpdatePayload struct {type CreatePostRequest struct {WallID string `json:"wallId"`EncryptedPostKey string `json:"encryptedPostKey"`+ KeyVersion int `json:"keyVersion"`CaptionCipher *string `json:"captionCipher,omitempty"`Objects []PostObjectPayload `json:"objects"`}diff --git a/server/wall/repo/follow.go b/server/wall/repo/follow.goindex 9145d13e52..b3c48007e5 100644--- a/server/wall/repo/follow.go+++ b/server/wall/repo/follow.go@@ -140,23 +140,53 @@ func (r *FollowRepository) UpsertShare(ctx context.Context, wallID string, follo}func (r *FollowRepository) UpdateShare(ctx context.Context, wallID string, followerID int64, encryptedWallKey string, keyVersion int) error {- res, err := r.DB.ExecContext(ctx, `- UPDATE wall_follow_shares- SET encrypted_wall_key = $3,- key_version = $4- WHERE wall_id = $1 AND follower_id = $2- `, wallID, followerID, encryptedWallKey, keyVersion)+ return r.UpdateShares(ctx, wallID, []WallShareUpdateRecord{+ {FollowerID: followerID, EncryptedWallKey: encryptedWallKey},+ }, keyVersion)+}++func (r *FollowRepository) UpdateShares(ctx context.Context, wallID string, shares []WallShareUpdateRecord, keyVersion int) error {+ if len(shares) == 0 {+ return nil+ }+ tx, err := r.DB.BeginTx(ctx, nil)if err != nil {return stacktrace.Propagate(err, "")}- affected, err := res.RowsAffected()- if err != nil {+ defer tx.Rollback()++ var currentVersion int+ if err := tx.QueryRowContext(ctx, `+ SELECT current_version+ FROM walls+ WHERE wall_id = $1+ FOR UPDATE+ `, wallID).Scan(¤tVersion); err != nil {return stacktrace.Propagate(err, "")}- if affected == 0 {+ if currentVersion != keyVersion {return sql.ErrNoRows}- return nil++ for _, share := range shares {+ res, err := tx.ExecContext(ctx, `+ UPDATE wall_follow_shares+ SET encrypted_wall_key = $3,+ key_version = $4+ WHERE wall_id = $1 AND follower_id = $2+ `, wallID, share.FollowerID, share.EncryptedWallKey, keyVersion)+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ affected, err := res.RowsAffected()+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ if affected == 0 {+ return sql.ErrNoRows+ }+ }+ return stacktrace.Propagate(tx.Commit(), "")}func (r *FollowRepository) ApproveRequest(ctx context.Context, requestID int64, wallID string, encryptedWallKey string, keyVersion int) (*WallFollowRequestRecord, error) {@@ -166,8 +196,21 @@ func (r *FollowRepository) ApproveRequest(ctx context.Context, requestID int64,}defer tx.Rollback()+ var currentVersion int+ if err := tx.QueryRowContext(ctx, `+ SELECT current_version+ FROM walls+ WHERE wall_id = $1+ FOR UPDATE+ `, wallID).Scan(¤tVersion); err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ if currentVersion != keyVersion {+ return nil, sql.ErrNoRows+ }+rec, err := scanFollowRequest(tx.QueryRowContext(ctx, `- SELECT r.request_id, r.requester_id, r.target_wall_id, r.status, r.created_at, r.updated_at,+ SELECT r.request_id, r.requester_id, r.target_wall_id, r.status, r.created_at, r.updated_at,requester_wall.wall_slug,ka.public_key,target_wall.wall_slugdiff --git a/server/wall/repo/module.go b/server/wall/repo/module.goindex 9a35081343..077711f208 100644--- a/server/wall/repo/module.go+++ b/server/wall/repo/module.go@@ -130,6 +130,11 @@ type WallShareRecord struct {PublicKey string}+type WallShareUpdateRecord struct {+ FollowerID int64+ EncryptedWallKey string+}+type WallFollowerRecord struct {FollowerID int64Username stringdiff --git a/server/wall/repo/module_test.go b/server/wall/repo/module_test.goindex 2af4116b92..b3d0d4d83c 100644--- a/server/wall/repo/module_test.go+++ b/server/wall/repo/module_test.go@@ -383,22 +383,95 @@ func TestUpdateShareOnlyRefreshesExistingShares(t *testing.T) {err = module.Follow.UpsertShare(ctx, aliceWall.WallID, bobID, "share-key-v1", aliceWall.CurrentVersion)require.NoError(t, err)- err = module.Follow.UpdateShare(ctx, aliceWall.WallID, bobID, "share-key-v2", aliceWall.CurrentVersion+1)+ rotatedWall, err := module.Walls.RotateKey(ctx, aliceID, aliceWall.WallID, "alice-wall-key-v2", "wrapped-prev-key", nil)+ require.NoError(t, err)++ err = module.Follow.UpdateShare(ctx, aliceWall.WallID, bobID, "share-key-v2", rotatedWall.CurrentVersion)require.NoError(t, err)share, err := module.Follow.GetShareForFollowerAndWall(ctx, bobID, aliceWall.WallID)require.NoError(t, err)require.Equal(t, "share-key-v2", share.EncryptedWallKey)- require.Equal(t, aliceWall.CurrentVersion+1, share.KeyVersion)+ require.Equal(t, rotatedWall.CurrentVersion, share.KeyVersion)err = module.Follow.DeleteShareByWallAndFollower(ctx, aliceWall.WallID, bobID)require.NoError(t, err)- err = module.Follow.UpdateShare(ctx, aliceWall.WallID, bobID, "stale-share-key", aliceWall.CurrentVersion+2)+ err = module.Follow.UpdateShare(ctx, aliceWall.WallID, bobID, "stale-share-key", rotatedWall.CurrentVersion)require.ErrorIs(t, err, sql.ErrNoRows)_, err = module.Follow.GetShareForFollowerAndWall(ctx, bobID, aliceWall.WallID)require.ErrorIs(t, err, sql.ErrNoRows)}+func TestCreatePostRejectsStaleKeyVersion(t *testing.T) {+ ctx := context.Background()+ module := newWallTestModule(t)++ aliceID := insertWallUser(t, module, "[email protected]", "alice-public")+ wall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")+ require.NoError(t, err)+ _, err = module.Walls.RotateKey(ctx, aliceID, wall.WallID, "alice-wall-key-v2", "wrapped-prev-key", nil)+ require.NoError(t, err)++ postID, err := module.Posts.CreatePost(ctx, aliceID, wall.WallID, "post-key-stale", nil, wall.CurrentVersion, nil)+ require.Zero(t, postID)+ require.ErrorIs(t, err, sql.ErrNoRows)++ posts, next, err := module.Posts.ListPostsByWall(ctx, wall.WallID, aliceID, "", 20)+ require.NoError(t, err)+ require.Empty(t, next)+ require.Empty(t, posts)+}++func TestApproveRequestRejectsStaleKeyVersion(t *testing.T) {+ ctx := context.Background()+ module := newWallTestModule(t)++ aliceID := insertWallUser(t, module, "[email protected]", "alice-public")+ bobID := insertWallUser(t, module, "[email protected]", "bob-public")+ aliceWall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")+ require.NoError(t, err)+ _, err = module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")+ require.NoError(t, err)+ request, err := module.Follow.CreateRequest(ctx, bobID, aliceWall.WallID)+ require.NoError(t, err)+ _, err = module.Walls.RotateKey(ctx, aliceID, aliceWall.WallID, "alice-wall-key-v2", "wrapped-prev-key", nil)+ require.NoError(t, err)++ approved, err := module.Follow.ApproveRequest(ctx, request.RequestID, aliceWall.WallID, "stale-share-key", aliceWall.CurrentVersion)+ require.Nil(t, approved)+ require.ErrorIs(t, err, sql.ErrNoRows)++ stored, err := module.Follow.GetRequest(ctx, request.RequestID)+ require.NoError(t, err)+ require.Equal(t, "pending", stored.Status)+ _, err = module.Follow.GetShareForFollowerAndWall(ctx, bobID, aliceWall.WallID)+ require.ErrorIs(t, err, sql.ErrNoRows)+}++func TestUpdateShareRejectsStaleKeyVersion(t *testing.T) {+ ctx := context.Background()+ module := newWallTestModule(t)++ aliceID := insertWallUser(t, module, "[email protected]", "alice-public")+ bobID := insertWallUser(t, module, "[email protected]", "bob-public")+ aliceWall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")+ require.NoError(t, err)+ _, err = module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")+ require.NoError(t, err)+ err = module.Follow.UpsertShare(ctx, aliceWall.WallID, bobID, "share-key-v1", aliceWall.CurrentVersion)+ require.NoError(t, err)+ _, err = module.Walls.RotateKey(ctx, aliceID, aliceWall.WallID, "alice-wall-key-v2", "wrapped-prev-key", nil)+ require.NoError(t, err)++ err = module.Follow.UpdateShare(ctx, aliceWall.WallID, bobID, "stale-share-key", aliceWall.CurrentVersion)+ require.ErrorIs(t, err, sql.ErrNoRows)++ share, err := module.Follow.GetShareForFollowerAndWall(ctx, bobID, aliceWall.WallID)+ require.NoError(t, err)+ require.Equal(t, "share-key-v1", share.EncryptedWallKey)+ require.Equal(t, aliceWall.CurrentVersion, share.KeyVersion)+}+func TestRotateKeyRevokesWallLinks(t *testing.T) {ctx := context.Background()module := newWallTestModule(t)diff --git a/server/wall/repo/posts.go b/server/wall/repo/posts.goindex a5e7191ed5..c672b8feaa 100644--- a/server/wall/repo/posts.go+++ b/server/wall/repo/posts.go@@ -15,6 +15,18 @@ func (r *PostsRepository) CreatePost(ctx context.Context, ownerID int64, wallID,return 0, stacktrace.Propagate(err, "")}defer tx.Rollback()+ var currentVersion int+ if err := tx.QueryRowContext(ctx, `+ SELECT current_version+ FROM walls+ WHERE owner_id = $1 AND wall_id = $2+ FOR UPDATE+ `, ownerID, wallID).Scan(¤tVersion); err != nil {+ return 0, stacktrace.Propagate(err, "")+ }+ if currentVersion != keyVersion {+ return 0, sql.ErrNoRows+ }caption := ""if captionCipher != nil {caption = *captionCipher