π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Fix wall invite link rotation
Anand Baburajancd0afb2a42d1
diff --git a/rust/wall/src/client.rs b/rust/wall/src/client.rsindex 0bb3a31db9..ebb560178b 100644--- a/rust/wall/src/client.rs+++ b/rust/wall/src/client.rs@@ -2,8 +2,8 @@ use std::collections::BTreeMap;use crate::crypto::{PACKED_SECRETBOX_OVERHEAD_BYTES, decode_b64, decrypt_entity_key, decrypt_secretbox_packed,- derive_wall_link_access_key, derive_wall_link_auth_key, derive_wall_link_wrap_key, encode_b64,- encrypt_asset_payload, encrypt_entity_key, encrypt_secretbox_packed, generate_key,+ derive_wall_link_auth_key, derive_wall_link_wrap_key, encode_b64, encrypt_asset_payload,+ encrypt_entity_key, encrypt_secretbox_packed, generate_key, generate_wall_link_access_key,pack_payload, unpack_payload, wall_link_access_key_material,};use crate::error::{Result, WallError};@@ -46,6 +46,13 @@ struct ResolvedWallAccess {key_version: i32,}+#[derive(Debug, Clone)]+struct ResolvedOwnedWallAccess {+ root_wall_key: Vec<u8>,+ wall_key: Vec<u8>,+ key_version: i32,+}+pub struct AccountWallCtx {client: HttpClient,master_key: Vec<u8>,@@ -1133,12 +1140,39 @@ impl AccountWallCtx {pub async fn create_wall_link(&self, wall_id: &str) -> Result<CreatedWallLink> {let access = self- .resolve_owned_wall_access(wall_id)+ .resolve_owned_wall_access_with_root(wall_id)+ .await?+ .ok_or_else(|| {+ WallError::InvalidInput(format!("wall {wall_id} is not owned by the account"))+ })?;+ let status = self.get_wall_link_status(wall_id).await?;+ if status.active {+ return self.created_wall_link_from_status(&access.root_wall_key, status);+ }+ let access_key = generate_wall_link_access_key()?;+ self.write_wall_link(wall_id, access, access_key, "/wall/links")+ .await+ }++ pub async fn rotate_wall_link(&self, wall_id: &str) -> Result<CreatedWallLink> {+ let access = self+ .resolve_owned_wall_access_with_root(wall_id).await?.ok_or_else(|| {WallError::InvalidInput(format!("wall {wall_id} is not owned by the account"))})?;- let access_key = derive_wall_link_access_key(wall_id, &access.wall_key)?;+ let access_key = generate_wall_link_access_key()?;+ self.write_wall_link(wall_id, access, access_key, "/wall/links/rotate")+ .await+ }++ async fn write_wall_link(+ &self,+ wall_id: &str,+ access: ResolvedOwnedWallAccess,+ access_key: String,+ path: &str,+ ) -> Result<CreatedWallLink> {let access_key_material = wall_link_access_key_material(&access_key)?;let auth_key = derive_wall_link_auth_key(&access_key_material)?;let wrap_key = derive_wall_link_wrap_key(&access_key_material)?;@@ -1147,8 +1181,12 @@ impl AccountWallCtx {auth_key: encode_b64(&auth_key),key_version: access.key_version,encrypted_wall_key: encode_b64(&encrypt_secretbox_packed(&wrap_key, &access.wall_key)?),+ encrypted_access_key: encode_b64(&encrypt_secretbox_packed(+ &access.root_wall_key,+ access_key.as_bytes(),+ )?),};- let status: WallLinkStatusResponse = self.client.post_json("/wall/links", &request).await?;+ let status: WallLinkStatusResponse = self.client.post_json(path, &request).await?;Ok(CreatedWallLink {access_key,wall_username: status.wall_slug.clone(),@@ -1158,6 +1196,31 @@ impl AccountWallCtx {})}+ fn created_wall_link_from_status(+ &self,+ root_wall_key: &[u8],+ status: WallLinkStatusResponse,+ ) -> Result<CreatedWallLink> {+ if status.encrypted_access_key.trim().is_empty() {+ return Err(WallError::InvalidInput(+ "active wall link is missing encrypted access key".into(),+ ));+ }+ let access_key_bytes =+ decrypt_secretbox_packed(root_wall_key, &decode_b64(&status.encrypted_access_key)?)?;+ let access_key = String::from_utf8(access_key_bytes).map_err(|err| {+ WallError::InvalidInput(format!("invalid wall link access key utf8: {err}"))+ })?;+ wall_link_access_key_material(&access_key)?;+ Ok(CreatedWallLink {+ access_key,+ wall_username: status.wall_slug.clone(),+ wall_id: status.wall_id,+ wall_slug: status.wall_slug,+ key_version: status.key_version,+ })+ }+pub async fn delete_wall_link(&self, wall_id: &str) -> Result<()> {let path = format!("/wall/links/{wall_id}");self.client.delete_empty(&path, &[]).await?;@@ -1165,6 +1228,19 @@ impl AccountWallCtx {}async fn resolve_owned_wall_access(&self, wall_id: &str) -> Result<Option<ResolvedWallAccess>> {+ Ok(self+ .resolve_owned_wall_access_with_root(wall_id)+ .await?+ .map(|value| ResolvedWallAccess {+ wall_key: value.wall_key,+ key_version: value.key_version,+ }))+ }++ async fn resolve_owned_wall_access_with_root(+ &self,+ wall_id: &str,+ ) -> Result<Option<ResolvedOwnedWallAccess>> {let root_wall_key = match self.get_root_wall_key().await? {Some(value) => value,None => return Ok(None),@@ -1175,7 +1251,8 @@ impl AccountWallCtx {};let packed = decode_b64(&record.encrypted_wall_key)?;let wall_key = decrypt_secretbox_packed(&root_wall_key, &packed)?;- Ok(Some(ResolvedWallAccess {+ Ok(Some(ResolvedOwnedWallAccess {+ root_wall_key,wall_key,key_version: record.key_version,}))@@ -2936,6 +3013,7 @@ mod tests {)).with_status(200).with_body(root_entity_response(&ctx.master_key, &root_wall_key))+ .expect(2).create_async().await;let walls = server@@ -2949,6 +3027,7 @@ mod tests {"owner-main",3,))+ .expect(2).create_async().await;let status = server@@ -2960,12 +3039,14 @@ mod tests {"wallId": "wall_owner_main","wallSlug": "owner-main","keyVersion": 3,- "active": true,+ "active": false,+ "encryptedAccessKey": "","createdAt": "2026-04-16T00:00:00Z","updatedAt": "2026-04-16T00:00:00Z"}).to_string(),)+ .expect(2).create_async().await;let create = server@@ -2976,6 +3057,7 @@ mod tests {Matcher::Regex("\"authKey\":\"[^\"]+\"".into()),Matcher::Regex("\"keyVersion\":3".into()),Matcher::Regex("\"encryptedWallKey\":\"[^\"]+\"".into()),+ Matcher::Regex("\"encryptedAccessKey\":\"[^\"]+\"".into()),])).with_status(200).with_body(@@ -2984,6 +3066,7 @@ mod tests {"wallSlug": "owner-main","keyVersion": 3,"active": true,+ "encryptedAccessKey": "owner-link-secret","createdAt": "2026-04-16T00:00:00Z","updatedAt": "2026-04-16T00:00:00Z"})@@ -2991,6 +3074,31 @@ mod tests {).create_async().await;+ let rotate = server+ .mock("POST", "/wall/links/rotate")+ .match_header("x-auth-token", "token")+ .match_body(Matcher::AllOf(vec![+ Matcher::Regex("\"wallId\":\"wall_owner_main\"".into()),+ Matcher::Regex("\"authKey\":\"[^\"]+\"".into()),+ Matcher::Regex("\"keyVersion\":3".into()),+ Matcher::Regex("\"encryptedWallKey\":\"[^\"]+\"".into()),+ Matcher::Regex("\"encryptedAccessKey\":\"[^\"]+\"".into()),+ ]))+ .with_status(200)+ .with_body(+ json!({+ "wallId": "wall_owner_main",+ "wallSlug": "owner-main",+ "keyVersion": 3,+ "active": true,+ "encryptedAccessKey": "rotated-owner-link-secret",+ "createdAt": "2026-04-16T00:00:00Z",+ "updatedAt": "2026-04-16T00:01:00Z"+ })+ .to_string(),+ )+ .create_async()+ .await;let delete = server.mock("DELETE", "/wall/links/wall_owner_main").match_header("x-auth-token", "token")@@ -3006,11 +3114,15 @@ mod tests {.create_wall_link("wall_owner_main").await.expect("link should be created");+ let rotated = ctx+ .rotate_wall_link("wall_owner_main")+ .await+ .expect("link should be rotated");ctx.delete_wall_link("wall_owner_main").await.expect("link should be deleted");- assert!(status_response.active);+ assert!(!status_response.active);assert_eq!(created.wall_id, "wall_owner_main");assert_eq!(created.wall_username, "owner-main");assert_eq!(created.access_key.len(), 12);@@ -3021,13 +3133,87 @@ mod tests {.all(|value| value.is_ascii_alphanumeric()));assert_eq!(created.key_version, 3);+ assert_eq!(rotated.wall_id, "wall_owner_main");+ assert_eq!(rotated.wall_username, "owner-main");+ assert_eq!(rotated.access_key.len(), 12);+ assert_ne!(rotated.access_key, created.access_key);status.assert_async().await;entity.assert_async().await;walls.assert_async().await;create.assert_async().await;+ rotate.assert_async().await;delete.assert_async().await;}+ #[tokio::test]+ async fn create_wall_link_reuses_active_encrypted_access_key() {+ 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 access_key = "AbC123xYz789";+ let encrypted_access_key = encode_b64(+ &encrypt_secretbox_packed(&root_wall_key, access_key.as_bytes())+ .expect("encrypted access key"),+ );++ 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(root_entity_response(&ctx.master_key, &root_wall_key))+ .create_async()+ .await;+ let walls = server+ .mock("GET", "/wall")+ .match_header("x-auth-token", "token")+ .with_status(200)+ .with_body(owned_wall_response(+ &root_wall_key,+ &wall_key,+ "wall_owner_main",+ "owner-main",+ 3,+ ))+ .create_async()+ .await;+ let status = server+ .mock("GET", "/wall/links/wall_owner_main")+ .match_header("x-auth-token", "token")+ .with_status(200)+ .with_body(+ json!({+ "wallId": "wall_owner_main",+ "wallSlug": "owner-main",+ "keyVersion": 3,+ "active": true,+ "encryptedAccessKey": encrypted_access_key,+ "createdAt": "2026-04-16T00:00:00Z",+ "updatedAt": "2026-04-16T00:00:00Z"+ })+ .to_string(),+ )+ .create_async()+ .await;++ let created = ctx+ .create_wall_link("wall_owner_main")+ .await+ .expect("active link should be reusable");++ assert_eq!(created.access_key, access_key);+ assert_eq!(created.wall_id, "wall_owner_main");+ assert_eq!(created.wall_username, "owner-main");+ assert_eq!(created.key_version, 3);+ entity.assert_async().await;+ walls.assert_async().await;+ status.assert_async().await;+ }+#[tokio::test]async fn list_feed_uses_wall_feed_endpoint() {let mut server = Server::new_async().await;diff --git a/rust/wall/src/crypto.rs b/rust/wall/src/crypto.rsindex 5a538f3eac..70d8c2f528 100644--- a/rust/wall/src/crypto.rs+++ b/rust/wall/src/crypto.rs@@ -15,6 +15,15 @@ pub fn generate_key() -> Vec<u8> {keys::generate_key_secure().into_vec()}+pub fn generate_wall_link_access_key() -> Result<String> {+ let seed = generate_key();+ let mut input = Vec::with_capacity(seed.len() + 32);+ input.extend_from_slice(b"ente.wall.link.access-key.random.v1");+ input.push(0);+ input.extend_from_slice(&seed);+ wall_link_access_key_from_hash_input(&input)+}+fn wall_link_access_key_from_hash_input(input: &[u8]) -> Result<String> {let max_unbiased_value = 256 - (256 % WALL_LINK_ACCESS_KEY_ALPHABET.len());let mut out = String::with_capacity(WALL_LINK_ACCESS_KEY_LEN);@@ -43,22 +52,6 @@ fn wall_link_access_key_from_hash_input(input: &[u8]) -> Result<String> {Ok(out)}-pub fn derive_wall_link_access_key(wall_id: &str, wall_key: &[u8]) -> Result<String> {- let wall_id = wall_id.trim();- if wall_id.is_empty() || wall_key.is_empty() {- return Err(WallError::InvalidInput(- "wall id and wall key are required".into(),- ));- }- let mut input = Vec::with_capacity(wall_id.len() + wall_key.len() + 32);- input.extend_from_slice(b"ente.wall.link.access-key.v1");- input.push(0);- input.extend_from_slice(wall_id.as_bytes());- input.push(0);- input.extend_from_slice(wall_key);- wall_link_access_key_from_hash_input(&input)-}-pub fn wall_link_access_key_material(access_key: &str) -> Result<Vec<u8>> {let trimmed = access_key.trim();let is_base62 = trimmed@@ -196,29 +189,21 @@ mod tests {}#[test]- fn wall_link_access_key_is_stable_short_base62() {- let wall_key = generate_key();- let access_key = derive_wall_link_access_key("wall_owner_main", &wall_key).unwrap();- let repeated = derive_wall_link_access_key("wall_owner_main", &wall_key).unwrap();+ fn generated_wall_link_access_key_is_short_base62() {+ let access_key = generate_wall_link_access_key().unwrap();+ let repeated = generate_wall_link_access_key().unwrap();assert_eq!(access_key.len(), 12);- assert_eq!(access_key, repeated);assert!(access_key.bytes().all(|value| value.is_ascii_alphanumeric()));+ assert_ne!(access_key, repeated);let material = wall_link_access_key_material(&access_key).unwrap();assert_eq!(material.len(), 32);}- #[test]- fn wall_link_access_key_changes_with_wall_key() {- let access_key_a = derive_wall_link_access_key("wall_owner_main", b"wall-key-a").unwrap();- let access_key_b = derive_wall_link_access_key("wall_owner_main", b"wall-key-b").unwrap();- assert_ne!(access_key_a, access_key_b);- }-#[test]fn wall_link_access_key_rejects_legacy_b64_url_key() {let old_key = "LqUerMGZjrvdfkd6TayOiDa9pM0pYeGcakjhhsB47Hc";diff --git a/rust/wall/src/transport.rs b/rust/wall/src/transport.rsindex 3c16f1a602..baf3e44476 100644--- a/rust/wall/src/transport.rs+++ b/rust/wall/src/transport.rs@@ -481,6 +481,7 @@ pub struct WallLinkStatusResponse {pub wall_slug: String,pub key_version: i32,pub active: bool,+ pub encrypted_access_key: String,pub created_at: String,pub updated_at: String,}@@ -492,6 +493,7 @@ pub struct WallLinkCreateRequest {pub auth_key: String,pub key_version: i32,pub encrypted_wall_key: String,+ pub encrypted_access_key: String,}#[derive(Debug, Clone, Serialize)]diff --git a/server/migrations/121_wall.up.sql b/server/migrations/121_wall.up.sqlindex dea1ec288b..d60f027170 100644--- a/server/migrations/121_wall.up.sql+++ b/server/migrations/121_wall.up.sql@@ -267,18 +267,23 @@ CREATE TRIGGER update_wall_messages_updated_atEXECUTE PROCEDURE trigger_updated_at_microseconds_column();CREATE TABLE IF NOT EXISTS wall_links (- wall_id TEXT PRIMARY KEY REFERENCES walls (wall_id) ON DELETE CASCADE,- auth_key_hash BYTEA NOT NULL UNIQUE,- key_version INTEGER NOT NULL,- encrypted_wall_key TEXT NOT NULL,- active BOOLEAN NOT NULL DEFAULT TRUE,- created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),- updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds()+ wall_id TEXT NOT NULL REFERENCES walls (wall_id) ON DELETE CASCADE,+ auth_key_hash BYTEA NOT NULL UNIQUE,+ key_version INTEGER NOT NULL,+ encrypted_wall_key TEXT NOT NULL,+ encrypted_access_key TEXT NOT NULL,+ active BOOLEAN NOT NULL DEFAULT TRUE,+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),+ updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds());CREATE INDEX IF NOT EXISTS idx_wall_links_activeON wall_links (active, updated_at DESC);+CREATE UNIQUE INDEX IF NOT EXISTS uq_wall_links_active_wall+ ON wall_links (wall_id)+ WHERE active = TRUE;+CREATE TRIGGER update_wall_links_updated_atBEFORE UPDATE ON wall_linksFOR EACH ROWdiff --git a/server/wall/api/links.go b/server/wall/api/links.goindex 2bde81056e..aeeebcb672 100644--- a/server/wall/api/links.go+++ b/server/wall/api/links.go@@ -21,6 +21,16 @@ func (h *Handlers) CreateWallLink(c *gin.Context) {respondJSON(c, resp, err)}+func (h *Handlers) RotateWallLink(c *gin.Context) {+ var req models.WallLinkCreateRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ respondJSON(c, nil, ente.ErrBadRequest)+ return+ }+ resp, err := h.Module.Links.Rotate(c, req)+ respondJSON(c, resp, err)+}+func (h *Handlers) DeleteWallLink(c *gin.Context) {respondStatus(c, h.Module.Links.Delete(c, c.Param("wallID")))}diff --git a/server/wall/api/register.go b/server/wall/api/register.goindex e75ec0b1e6..aa06c13aac 100644--- a/server/wall/api/register.go+++ b/server/wall/api/register.go@@ -33,6 +33,7 @@ func Register(privateAPI, publicAPI gin.IRoutes, handlers *Handlers) {privateAPI.POST("/wall/rotate", handlers.RotateWallKey)privateAPI.GET("/wall/links/:wallID", handlers.GetWallLink)privateAPI.POST("/wall/links", handlers.CreateWallLink)+ privateAPI.POST("/wall/links/rotate", handlers.RotateWallLink)privateAPI.DELETE("/wall/links/:wallID", handlers.DeleteWallLink)publicAPI.GET("/wall/profile", handlers.GetWallProfile)diff --git a/server/wall/controller/auth_test.go b/server/wall/controller/auth_test.goindex 80cc48f78a..2861ad4f4a 100644--- a/server/wall/controller/auth_test.go+++ b/server/wall/controller/auth_test.go@@ -75,7 +75,7 @@ func TestResolveViewerAcceptsWallLinkSessionToken(t *testing.T) {wall, err := repos.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")require.NoError(t, err)authHash := sha256.Sum256([]byte("link-auth-key"))- link, err := repos.Links.UpsertLink(ctx, wall.WallID, authHash[:], wall.CurrentVersion, "encrypted-link-wall-key")+ link, err := repos.Links.UpsertLink(ctx, wall.WallID, authHash[:], wall.CurrentVersion, "encrypted-link-wall-key", "encrypted-owner-link-secret")require.NoError(t, err)sessionHash := sha256.Sum256([]byte("link-session-token"))require.NoError(t, repos.Links.CreateSession(ctx, sessionHash[:], link.WallID, link.AuthKeyHash, link.KeyVersion, timeutil.MicrosecondsAfterMinutes(5)))diff --git a/server/wall/controller/links.go b/server/wall/controller/links.goindex 556af50974..f6e528f600 100644--- a/server/wall/controller/links.go+++ b/server/wall/controller/links.go@@ -42,22 +42,31 @@ func (c *LinksController) Get(ctx *gin.Context, wallID string) (*models.WallLink}, nil}return &models.WallLinkStatusResponse{- WallID: link.WallID,- WallSlug: link.WallSlug,- KeyVersion: link.KeyVersion,- Active: link.Active,- CreatedAt: formatMicros(link.CreatedAt),- UpdatedAt: formatMicros(link.UpdatedAt),+ WallID: link.WallID,+ WallSlug: link.WallSlug,+ KeyVersion: link.KeyVersion,+ Active: link.Active,+ EncryptedAccessKey: link.EncryptedAccessKey,+ CreatedAt: formatMicros(link.CreatedAt),+ UpdatedAt: formatMicros(link.UpdatedAt),}, nil}func (c *LinksController) Create(ctx *gin.Context, req models.WallLinkCreateRequest) (*models.WallLinkStatusResponse, error) {+ return c.writeLink(ctx, req, false)+}++func (c *LinksController) Rotate(ctx *gin.Context, req models.WallLinkCreateRequest) (*models.WallLinkStatusResponse, error) {+ return c.writeLink(ctx, req, true)+}++func (c *LinksController) writeLink(ctx *gin.Context, req models.WallLinkCreateRequest, rotate bool) (*models.WallLinkStatusResponse, error) {userID, err := c.auth.requireUser(ctx)if err != nil {return nil, err}- if strings.TrimSpace(req.WallID) == "" || strings.TrimSpace(req.AuthKey) == "" || strings.TrimSpace(req.EncryptedWallKey) == "" || req.KeyVersion <= 0 {- return nil, ente.NewBadRequestWithMessage("wallId, authKey, encryptedWallKey and keyVersion are required")+ if strings.TrimSpace(req.WallID) == "" || strings.TrimSpace(req.AuthKey) == "" || strings.TrimSpace(req.EncryptedWallKey) == "" || strings.TrimSpace(req.EncryptedAccessKey) == "" || req.KeyVersion <= 0 {+ return nil, ente.NewBadRequestWithMessage("wallId, authKey, encryptedWallKey, encryptedAccessKey and keyVersion are required")}wall, err := c.auth.requireWallOwner(ctx.Request.Context(), userID, req.WallID)if err != nil {@@ -71,20 +80,32 @@ func (c *LinksController) Create(ctx *gin.Context, req models.WallLinkCreateRequreturn nil, ente.NewBadRequestWithMessage("keyVersion does not match current wall version")}sum := sha256.Sum256(authKeyBytes)- link, err := c.LinksRepo.UpsertLink(ctx.Request.Context(), wall.WallID, sum[:], req.KeyVersion, req.EncryptedWallKey)+ var link *repo.WallLinkRecord+ if rotate {+ link, err = c.LinksRepo.RotateLink(ctx.Request.Context(), wall.WallID, sum[:], req.KeyVersion, req.EncryptedWallKey, req.EncryptedAccessKey)+ } else {+ link, err = c.LinksRepo.UpsertLink(ctx.Request.Context(), wall.WallID, sum[:], req.KeyVersion, req.EncryptedWallKey, req.EncryptedAccessKey)+ }if err != nil {if errors.Is(err, sql.ErrNoRows) {return nil, ente.NewBadRequestWithMessage("keyVersion does not match current wall version")}+ if errors.Is(err, repo.ErrActiveLinkAlreadyExists) {+ return nil, ente.NewBadRequestWithMessage("active wall link already exists; rotate it instead")+ }+ if errors.Is(err, repo.ErrLinkAuthKeyReused) {+ return nil, ente.NewBadRequestWithMessage("wall link secret has already been used")+ }return nil, err}return &models.WallLinkStatusResponse{- WallID: link.WallID,- WallSlug: link.WallSlug,- KeyVersion: link.KeyVersion,- Active: link.Active,- CreatedAt: formatMicros(link.CreatedAt),- UpdatedAt: formatMicros(link.UpdatedAt),+ WallID: link.WallID,+ WallSlug: link.WallSlug,+ KeyVersion: link.KeyVersion,+ Active: link.Active,+ EncryptedAccessKey: link.EncryptedAccessKey,+ CreatedAt: formatMicros(link.CreatedAt),+ UpdatedAt: formatMicros(link.UpdatedAt),}, nil}diff --git a/server/wall/models/models.go b/server/wall/models/models.goindex 77f3424079..c70ac52366 100644--- a/server/wall/models/models.go+++ b/server/wall/models/models.go@@ -95,19 +95,21 @@ type WallActorResponse struct {}type WallLinkCreateRequest struct {- WallID string `json:"wallId"`- AuthKey string `json:"authKey"`- KeyVersion int `json:"keyVersion"`- EncryptedWallKey string `json:"encryptedWallKey"`+ WallID string `json:"wallId"`+ AuthKey string `json:"authKey"`+ KeyVersion int `json:"keyVersion"`+ EncryptedWallKey string `json:"encryptedWallKey"`+ EncryptedAccessKey string `json:"encryptedAccessKey"`}type WallLinkStatusResponse struct {- WallID string `json:"wallId"`- WallSlug string `json:"wallSlug"`- KeyVersion int `json:"keyVersion"`- Active bool `json:"active"`- CreatedAt string `json:"createdAt"`- UpdatedAt string `json:"updatedAt"`+ WallID string `json:"wallId"`+ WallSlug string `json:"wallSlug"`+ KeyVersion int `json:"keyVersion"`+ Active bool `json:"active"`+ EncryptedAccessKey string `json:"encryptedAccessKey"`+ CreatedAt string `json:"createdAt"`+ UpdatedAt string `json:"updatedAt"`}type WallLinkLoginRequest struct {diff --git a/server/wall/repo/links.go b/server/wall/repo/links.goindex 67302fc032..4828f430b8 100644--- a/server/wall/repo/links.go+++ b/server/wall/repo/links.go@@ -7,9 +7,23 @@ import ("errors""github.com/ente-io/stacktrace"+ "github.com/lib/pq")-func (r *LinksRepository) UpsertLink(ctx context.Context, wallID string, authKeyHash []byte, keyVersion int, encryptedWallKey string) (*WallLinkRecord, error) {+var (+ ErrActiveLinkAlreadyExists = errors.New("active wall link already exists")+ ErrLinkAuthKeyReused = errors.New("wall link auth key has already been used")+)++func (r *LinksRepository) UpsertLink(ctx context.Context, wallID string, authKeyHash []byte, keyVersion int, encryptedWallKey string, encryptedAccessKey string) (*WallLinkRecord, error) {+ return r.writeLink(ctx, wallID, authKeyHash, keyVersion, encryptedWallKey, encryptedAccessKey, false)+}++func (r *LinksRepository) RotateLink(ctx context.Context, wallID string, authKeyHash []byte, keyVersion int, encryptedWallKey string, encryptedAccessKey string) (*WallLinkRecord, error) {+ return r.writeLink(ctx, wallID, authKeyHash, keyVersion, encryptedWallKey, encryptedAccessKey, true)+}++func (r *LinksRepository) writeLink(ctx context.Context, wallID string, authKeyHash []byte, keyVersion int, encryptedWallKey string, encryptedAccessKey string, rotate bool) (*WallLinkRecord, error) {tx, err := r.DB.BeginTx(ctx, nil)if err != nil {return nil, stacktrace.Propagate(err, "")@@ -32,52 +46,68 @@ func (r *LinksRepository) UpsertLink(ctx context.Context, wallID string, authKeyvar existingAuthKeyHash []bytevar existingKeyVersion int- var existingActive boolerr = tx.QueryRowContext(ctx, `- SELECT auth_key_hash, key_version, active+ SELECT auth_key_hash, key_versionFROM wall_links- WHERE wall_id = $1+ WHERE wall_id = $1 AND active = TRUEFOR UPDATE- `, wallID).Scan(&existingAuthKeyHash, &existingKeyVersion, &existingActive)- if err == nil && bytes.Equal(existingAuthKeyHash, authKeyHash) && existingKeyVersion == keyVersion && existingActive {+ `, wallID).Scan(&existingAuthKeyHash, &existingKeyVersion)+ if err == nil && bytes.Equal(existingAuthKeyHash, authKeyHash) && existingKeyVersion == keyVersion {+ if rotate {+ return nil, ErrLinkAuthKeyReused+ }return scanLinkRecord(tx.QueryRowContext(ctx, `- SELECT l.wall_id, $2::text, $3::bigint, $2::text, l.auth_key_hash, l.key_version, l.encrypted_wall_key, l.active, l.created_at, l.updated_at+ SELECT l.wall_id, $2::text, $3::bigint, $2::text, l.auth_key_hash, l.key_version, l.encrypted_wall_key, l.encrypted_access_key, l.active, l.created_at, l.updated_atFROM wall_links l- WHERE l.wall_id = $1+ WHERE l.wall_id = $1 AND l.active = TRUE`, wallID, wallSlug, ownerID))}if err != nil && !errors.Is(err, sql.ErrNoRows) {return nil, stacktrace.Propagate(err, "")}if err == nil {+ if !rotate {+ return nil, ErrActiveLinkAlreadyExists+ }if _, err := tx.ExecContext(ctx, `DELETE FROM wall_link_sessions WHERE wall_id = $1`, wallID); err != nil {return nil, stacktrace.Propagate(err, "")}- link, err := scanLinkRecord(tx.QueryRowContext(ctx, `+ if _, err := tx.ExecContext(ctx, `UPDATE wall_links- SET auth_key_hash = $2,- key_version = $3,- encrypted_wall_key = $4,- active = TRUE- WHERE wall_id = $1- RETURNING wall_id, $5::text, $6::bigint, $5::text, auth_key_hash, key_version, encrypted_wall_key, active, created_at, updated_at- `, wallID, authKeyHash, keyVersion, encryptedWallKey, wallSlug, ownerID))- if err != nil {- return nil, err- }- if err := tx.Commit(); err != nil {+ SET active = FALSE+ WHERE wall_id = $1 AND active = TRUE+ `, wallID); err != nil {return nil, stacktrace.Propagate(err, "")}- return link, nil+ }++ var reusedAuthKeyHash []byte+ err = tx.QueryRowContext(ctx, `+ SELECT auth_key_hash+ FROM wall_links+ WHERE auth_key_hash = $1+ FOR UPDATE+ `, authKeyHash).Scan(&reusedAuthKeyHash)+ if err == nil {+ return nil, ErrLinkAuthKeyReused+ }+ if !errors.Is(err, sql.ErrNoRows) {+ return nil, stacktrace.Propagate(err, "")}link, err := scanLinkRecord(tx.QueryRowContext(ctx, `- INSERT INTO wall_links (wall_id, auth_key_hash, key_version, encrypted_wall_key, active)- VALUES ($1, $2, $3, $4, TRUE)- RETURNING wall_id, $5::text, $6::bigint, $5::text, auth_key_hash, key_version, encrypted_wall_key, active, created_at, updated_at- `, wallID, authKeyHash, keyVersion, encryptedWallKey, wallSlug, ownerID))+ INSERT INTO wall_links (wall_id, auth_key_hash, key_version, encrypted_wall_key, encrypted_access_key, active)+ VALUES ($1, $2, $3, $4, $5, TRUE)+ RETURNING wall_id, $6::text, $7::bigint, $6::text, auth_key_hash, key_version, encrypted_wall_key, encrypted_access_key, active, created_at, updated_at+ `, wallID, authKeyHash, keyVersion, encryptedWallKey, encryptedAccessKey, wallSlug, ownerID))if err != nil {- return nil, err+ if isUniqueViolationFor(err, "uq_wall_links_active_wall") {+ return nil, ErrActiveLinkAlreadyExists+ }+ if isUniqueViolation(err) {+ return nil, ErrLinkAuthKeyReused+ }+ return nil, stacktrace.Propagate(err, "")}if err := tx.Commit(); err != nil {return nil, stacktrace.Propagate(err, "")@@ -87,7 +117,7 @@ func (r *LinksRepository) UpsertLink(ctx context.Context, wallID string, authKeyfunc (r *LinksRepository) GetLink(ctx context.Context, wallID string) (*WallLinkRecord, error) {return scanLinkRecord(r.DB.QueryRowContext(ctx, `- SELECT l.wall_id, w.wall_slug, w.owner_id, w.wall_slug, l.auth_key_hash, l.key_version, l.encrypted_wall_key, l.active, l.created_at, l.updated_at+ SELECT l.wall_id, w.wall_slug, w.owner_id, w.wall_slug, l.auth_key_hash, l.key_version, l.encrypted_wall_key, l.encrypted_access_key, l.active, l.created_at, l.updated_atFROM wall_links lJOIN walls w ON w.wall_id = l.wall_idWHERE l.wall_id = $1 AND l.active = TRUE@@ -110,7 +140,7 @@ func deleteLinkTx(ctx context.Context, tx *sql.Tx, wallID string) error {if _, err := tx.ExecContext(ctx, `DELETE FROM wall_link_sessions WHERE wall_id = $1`, wallID); err != nil {return stacktrace.Propagate(err, "")}- if _, err := tx.ExecContext(ctx, `DELETE FROM wall_links WHERE wall_id = $1`, wallID); err != nil {+ if _, err := tx.ExecContext(ctx, `UPDATE wall_links SET active = FALSE WHERE wall_id = $1 AND active = TRUE`, wallID); err != nil {return stacktrace.Propagate(err, "")}return nil@@ -118,7 +148,7 @@ func deleteLinkTx(ctx context.Context, tx *sql.Tx, wallID string) error {func (r *LinksRepository) GetLinkByAuthHash(ctx context.Context, wallID string, authHash []byte) (*WallLinkRecord, error) {return scanLinkRecord(r.DB.QueryRowContext(ctx, `- SELECT l.wall_id, w.wall_slug, w.owner_id, w.wall_slug, l.auth_key_hash, l.key_version, l.encrypted_wall_key, l.active, l.created_at, l.updated_at+ SELECT l.wall_id, w.wall_slug, w.owner_id, w.wall_slug, l.auth_key_hash, l.key_version, l.encrypted_wall_key, l.encrypted_access_key, l.active, l.created_at, l.updated_atFROM wall_links lJOIN walls w ON w.wall_id = l.wall_idWHERE l.wall_id = $1 AND l.auth_key_hash = $2 AND l.active = TRUE@@ -167,6 +197,16 @@ func (r *LinksRepository) GetSession(ctx context.Context, tokenHash []byte) (*Wareturn &rec, nil}+func isUniqueViolation(err error) bool {+ var pqErr *pq.Error+ return errors.As(err, &pqErr) && pqErr.Code == "23505"+}++func isUniqueViolationFor(err error, constraint string) bool {+ var pqErr *pq.Error+ return errors.As(err, &pqErr) && pqErr.Code == "23505" && pqErr.Constraint == constraint+}+func (r *LinksRepository) DeleteSession(ctx context.Context, tokenHash []byte) error {_, err := r.DB.ExecContext(ctx, `DELETE FROM wall_link_sessions WHERE token_hash = $1`, tokenHash)return stacktrace.Propagate(err, "")@@ -174,7 +214,7 @@ func (r *LinksRepository) DeleteSession(ctx context.Context, tokenHash []byte) efunc scanLinkRecord(scanner interface{ Scan(dest ...any) error }) (*WallLinkRecord, error) {var rec WallLinkRecord- if err := scanner.Scan(&rec.WallID, &rec.WallSlug, &rec.OwnerID, &rec.OwnerSlug, &rec.AuthKeyHash, &rec.KeyVersion, &rec.EncryptedWallKey, &rec.Active, &rec.CreatedAt, &rec.UpdatedAt); err != nil {+ if err := scanner.Scan(&rec.WallID, &rec.WallSlug, &rec.OwnerID, &rec.OwnerSlug, &rec.AuthKeyHash, &rec.KeyVersion, &rec.EncryptedWallKey, &rec.EncryptedAccessKey, &rec.Active, &rec.CreatedAt, &rec.UpdatedAt); err != nil {return nil, stacktrace.Propagate(err, "")}return &rec, nildiff --git a/server/wall/repo/module.go b/server/wall/repo/module.goindex 56cc682fc1..337cf743cb 100644--- a/server/wall/repo/module.go+++ b/server/wall/repo/module.go@@ -215,16 +215,17 @@ type WallFriendRecord struct {}type WallLinkRecord struct {- WallID string- WallSlug string- OwnerID int64- OwnerSlug string- AuthKeyHash []byte- KeyVersion int- EncryptedWallKey string- Active bool- CreatedAt int64- UpdatedAt int64+ WallID string+ WallSlug string+ OwnerID int64+ OwnerSlug string+ AuthKeyHash []byte+ KeyVersion int+ EncryptedWallKey string+ EncryptedAccessKey string+ Active bool+ CreatedAt int64+ UpdatedAt int64}type WallLinkSessionRecord struct {diff --git a/server/wall/repo/module_test.go b/server/wall/repo/module_test.goindex b913b59f49..d4c1343cb9 100644--- a/server/wall/repo/module_test.go+++ b/server/wall/repo/module_test.go@@ -503,7 +503,7 @@ func TestWallModuleLifecycle(t *testing.T) {require.False(t, referenced)require.NoError(t, tx.Rollback())- link, err := module.Links.UpsertLink(ctx, aliceWall.WallID, []byte("hash"), rotatedWall.CurrentVersion, "wall-link-key")+ link, err := module.Links.UpsertLink(ctx, aliceWall.WallID, []byte("hash"), rotatedWall.CurrentVersion, "wall-link-key", "owner-link-secret")require.NoError(t, err)require.Equal(t, "wall-link-key", link.EncryptedWallKey)@@ -514,7 +514,7 @@ func TestWallModuleLifecycle(t *testing.T) {require.NoError(t, err)require.Equal(t, aliceWall.WallID, session.WallID)- newLink, err := module.Links.UpsertLink(ctx, aliceWall.WallID, []byte("new-hash"), rotatedWall.CurrentVersion, "new-wall-link-key")+ newLink, err := module.Links.RotateLink(ctx, aliceWall.WallID, []byte("new-hash"), rotatedWall.CurrentVersion, "new-wall-link-key", "new-owner-link-secret")require.NoError(t, err)_, err = module.Links.GetSession(ctx, []byte("token-hash"))require.Error(t, err)@@ -814,7 +814,7 @@ func TestRotateKeyRevokesWallLinks(t *testing.T) {wall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")require.NoError(t, err)- link, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("hash"), wall.CurrentVersion, "wall-link-key")+ link, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("hash"), wall.CurrentVersion, "wall-link-key", "owner-link-secret")require.NoError(t, err)require.Equal(t, "wall-link-key", link.EncryptedWallKey)@@ -867,21 +867,62 @@ func TestUpsertLinkReusesExistingLinkWithoutRevokingSessions(t *testing.T) {wall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")require.NoError(t, err)- link, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("same-hash"), wall.CurrentVersion, "wall-link-key")+ link, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("same-hash"), wall.CurrentVersion, "wall-link-key", "owner-link-secret")require.NoError(t, err)err = module.Links.CreateSession(ctx, []byte("token-hash"), link.WallID, link.AuthKeyHash, link.KeyVersion, timeutil.NMinFromNow(30))require.NoError(t, err)- reused, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("same-hash"), wall.CurrentVersion, "new-random-envelope")+ reused, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("same-hash"), wall.CurrentVersion, "new-random-envelope", "new-owner-link-secret")require.NoError(t, err)require.Equal(t, link.AuthKeyHash, reused.AuthKeyHash)require.Equal(t, link.EncryptedWallKey, reused.EncryptedWallKey)+ require.Equal(t, link.EncryptedAccessKey, reused.EncryptedAccessKey)session, err := module.Links.GetSession(ctx, []byte("token-hash"))require.NoError(t, err)require.Equal(t, link.AuthKeyHash, session.AuthKeyHash)}+func TestUpsertLinkRejectsDifferentActiveLinkSecret(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.Links.UpsertLink(ctx, wall.WallID, []byte("old-hash"), wall.CurrentVersion, "old-wall-link-key", "old-owner-link-secret")+ require.NoError(t, err)++ _, err = module.Links.UpsertLink(ctx, wall.WallID, []byte("new-hash"), wall.CurrentVersion, "new-wall-link-key", "new-owner-link-secret")+ require.ErrorIs(t, err, ErrActiveLinkAlreadyExists)+}++func TestDeleteLinkTombstonesAuthHash(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)++ link, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("old-hash"), wall.CurrentVersion, "old-wall-link-key", "old-owner-link-secret")+ require.NoError(t, err)+ err = module.Links.CreateSession(ctx, []byte("token-hash"), link.WallID, link.AuthKeyHash, link.KeyVersion, timeutil.NMinFromNow(30))+ require.NoError(t, err)++ require.NoError(t, module.Links.DeleteLink(ctx, wall.WallID))+ _, err = module.Links.GetSession(ctx, []byte("token-hash"))+ require.Error(t, err)++ _, err = module.Links.UpsertLink(ctx, wall.WallID, link.AuthKeyHash, wall.CurrentVersion, "resurrected-wall-link-key", "resurrected-owner-link-secret")+ require.ErrorIs(t, err, ErrLinkAuthKeyReused)++ freshLink, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("fresh-hash"), wall.CurrentVersion, "fresh-wall-link-key", "fresh-owner-link-secret")+ require.NoError(t, err)+ require.Equal(t, "fresh-wall-link-key", freshLink.EncryptedWallKey)+}+func TestCreateSessionRejectsStaleLinkAuthHash(t *testing.T) {ctx := context.Background()module := newWallTestModule(t)@@ -890,9 +931,9 @@ func TestCreateSessionRejectsStaleLinkAuthHash(t *testing.T) {wall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")require.NoError(t, err)- oldLink, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("old-hash"), wall.CurrentVersion, "old-wall-link-key")+ oldLink, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("old-hash"), wall.CurrentVersion, "old-wall-link-key", "old-owner-link-secret")require.NoError(t, err)- newLink, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("new-hash"), wall.CurrentVersion, "new-wall-link-key")+ newLink, err := module.Links.RotateLink(ctx, wall.WallID, []byte("new-hash"), wall.CurrentVersion, "new-wall-link-key", "new-owner-link-secret")require.NoError(t, err)err = module.Links.CreateSession(ctx, []byte("stale-token"), oldLink.WallID, oldLink.AuthKeyHash, oldLink.KeyVersion, timeutil.NMinFromNow(30))@@ -914,9 +955,9 @@ func TestGetSessionRejectsStaleLinkMetadata(t *testing.T) {wall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")require.NoError(t, err)- oldLink, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("old-hash"), wall.CurrentVersion, "old-wall-link-key")+ oldLink, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("old-hash"), wall.CurrentVersion, "old-wall-link-key", "old-owner-link-secret")require.NoError(t, err)- _, err = module.Links.UpsertLink(ctx, wall.WallID, []byte("new-hash"), wall.CurrentVersion, "new-wall-link-key")+ _, err = module.Links.RotateLink(ctx, wall.WallID, []byte("new-hash"), wall.CurrentVersion, "new-wall-link-key", "new-owner-link-secret")require.NoError(t, err)_, err = module.Links.DB.Exec(`@@ -929,7 +970,7 @@ func TestGetSessionRejectsStaleLinkMetadata(t *testing.T) {rotatedWall, err := module.Walls.RotateKey(ctx, aliceID, wall.WallID, "alice-wall-key-v2", "wrapped-prev-key", nil)require.NoError(t, err)- reusedHashLink, err := module.Links.UpsertLink(ctx, wall.WallID, oldLink.AuthKeyHash, rotatedWall.CurrentVersion, "reused-hash-new-version-key")+ reusedHashLink, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("fresh-after-wall-rotate"), rotatedWall.CurrentVersion, "fresh-new-version-key", "fresh-owner-link-secret")require.NoError(t, err)_, err = module.Links.DB.Exec(`INSERT INTO wall_link_sessions (token_hash, wall_id, owner_id, auth_key_hash, key_version, expires_at)@@ -952,7 +993,7 @@ func TestUpsertLinkRejectsStaleKeyVersion(t *testing.T) {require.NoError(t, err)require.Equal(t, wall.CurrentVersion+1, rotatedWall.CurrentVersion)- _, err = module.Links.UpsertLink(ctx, wall.WallID, []byte("stale-hash"), wall.CurrentVersion, "stale-wall-link-key")+ _, err = module.Links.UpsertLink(ctx, wall.WallID, []byte("stale-hash"), wall.CurrentVersion, "stale-wall-link-key", "stale-owner-link-secret")require.ErrorIs(t, err, sql.ErrNoRows)_, err = module.Links.GetLink(ctx, wall.WallID)diff --git a/web/packages/wasm/src/wall.rs b/web/packages/wasm/src/wall.rsindex 7ace3bdfe3..ece7a41cf6 100644--- a/web/packages/wasm/src/wall.rs+++ b/web/packages/wasm/src/wall.rs@@ -647,6 +647,14 @@ impl WallAccountCtxHandle {.map_err(Into::into)}+ /// Rotate a shareable wall link to a fresh secret.+ pub async fn rotate_wall_link(&self, wall_id: String) -> Result<JsValue, WasmWallError> {+ swb::to_value(&created_link_to_js(+ self.inner.rotate_wall_link(&wall_id).await?,+ ))+ .map_err(Into::into)+ }+/// Fetch wall link status.pub async fn get_wall_link_status(&self, wall_id: String) -> Result<JsValue, WasmWallError> {swb::to_value(&self.inner.get_wall_link_status(&wall_id).await?).map_err(Into::into)