Skip to content

armgit / ente

Public Imported from GitHub
0

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

Optimize public space profile link loading

Anand Baburajan4e002d75d35f
diff --git a/rust/space/src/client.rs b/rust/space/src/client.rs
index cffa930a39..42eef61f85 100644
--- a/rust/space/src/client.rs
+++ b/rust/space/src/client.rs
@@ -1508,17 +1508,27 @@ impl SpaceLinkCtx {
self.client.get_json(&path, &[]).await.map_err(Into::into)
}
- pub async fn decrypt_post_key(&self, post: &PostResponse) -> Result<Vec<u8>> {
+ pub async fn decrypt_post_key_fields(
+ &self,
+ post_id: i64,
+ encrypted_post_key: &str,
+ key_version: i32,
+ ) -> Result<Vec<u8>> {
let space_key = self
- .resolve_space_key_for_version(Some(post.key_version))
+ .resolve_space_key_for_version(Some(key_version))
.await?
.ok_or_else(|| {
- SpaceError::InvalidInput(format!("missing space key for post {}", post.post_id))
+ SpaceError::InvalidInput(format!("missing space key for post {post_id}"))
})?;
- let packed = decode_b64(&post.encrypted_post_key)?;
+ let packed = decode_b64(encrypted_post_key)?;
decrypt_secretbox_packed(&space_key, &packed)
}
+ pub async fn decrypt_post_key(&self, post: &PostResponse) -> Result<Vec<u8>> {
+ self.decrypt_post_key_fields(post.post_id, &post.encrypted_post_key, post.key_version)
+ .await
+ }
+
pub async fn decrypt_post(&self, post: &PostResponse) -> Result<DecryptedPost> {
let post_key = self.decrypt_post_key(post).await?;
let caption_plaintext = if post.caption_cipher.is_empty() {
@@ -1564,6 +1574,19 @@ impl SpaceLinkCtx {
.await
}
+ pub async fn download_post_asset_with_key(
+ &self,
+ post_id: i64,
+ encrypted_post_key: &str,
+ key_version: i32,
+ object_key: &str,
+ ) -> Result<Vec<u8>> {
+ let post_key = self
+ .decrypt_post_key_fields(post_id, encrypted_post_key, key_version)
+ .await?;
+ self.download_decrypted_asset(object_key, &post_key).await
+ }
+
pub async fn list_post_likers(
&self,
post_id: i64,
@@ -2033,6 +2056,68 @@ mod tests {
versions.assert_async().await;
}
+ #[tokio::test]
+ async fn space_link_download_post_asset_with_key_skips_post_fetch() {
+ let mut server = Server::new_async().await;
+ let space_key = generate_key();
+ let post_key = generate_key();
+ let object_key = "space/1/posts/post-object";
+ let encrypted_post_key =
+ encode_b64(&encrypt_secretbox_packed(&space_key, &post_key).expect("post key wrap"));
+ let encrypted_asset =
+ encrypt_asset_payload(&post_key, b"post-image").expect("asset encryption");
+
+ let redirect = server
+ .mock("GET", "/space/assets/redirect")
+ .match_header("x-auth-token", "link-token")
+ .match_query(Matcher::AllOf(vec![
+ Matcher::UrlEncoded("spaceId".into(), "space_owner_gallery".into()),
+ Matcher::UrlEncoded("objectKey".into(), object_key.into()),
+ ]))
+ .with_status(200)
+ .with_body(
+ json!({
+ "url": format!("{}/objects/post-object", server.url()),
+ "expiresIn": 900
+ })
+ .to_string(),
+ )
+ .create_async()
+ .await;
+ let object = server
+ .mock("GET", "/objects/post-object")
+ .with_status(200)
+ .with_body(encrypted_asset)
+ .create_async()
+ .await;
+ let ctx = SpaceLinkCtx {
+ client: build_http_client(
+ &server.url(),
+ Some("link-token".to_owned()),
+ None,
+ None,
+ None,
+ )
+ .expect("http client"),
+ session_token: "link-token".to_owned(),
+ owner_handle: "owner".to_owned(),
+ space_id: "space_owner_gallery".to_owned(),
+ space_slug: "owner-gallery".to_owned(),
+ owner_public_key: Vec::new(),
+ space_key,
+ key_version: 1,
+ };
+
+ let bytes = ctx
+ .download_post_asset_with_key(42, &encrypted_post_key, 1, object_key)
+ .await
+ .expect("asset should decrypt");
+
+ assert_eq!(bytes, b"post-image");
+ redirect.assert_async().await;
+ object.assert_async().await;
+ }
+
#[tokio::test]
async fn upload_post_asset_uses_presign_and_object_store() {
let mut server = Server::new_async().await;
diff --git a/server/space/api/links.go b/server/space/api/links.go
index 900180b80b..6a3fc66a36 100644
--- a/server/space/api/links.go
+++ b/server/space/api/links.go
@@ -36,6 +36,7 @@ func (h *Handlers) DeleteSpaceLink(c *gin.Context) {
}
func (h *Handlers) SpaceLinkLogin(c *gin.Context) {
+ c.Header("Cache-Control", "no-store")
var req models.SpaceLinkLoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
respondJSON(c, nil, ente.ErrBadRequest)
diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.ts
index 42f507cc49..beeea5aab3 100644
--- a/web/apps/space/src/services/space.ts
+++ b/web/apps/space/src/services/space.ts
@@ -52,6 +52,8 @@ interface SpacePostResponse {
author: SpaceActor;
caption?: string;
createdAt: string;
+ encryptedPostKey: string;
+ keyVersion: number;
likes: number;
objects?: SpacePostObject[];
postId: number;
@@ -337,9 +339,17 @@ const accountAvatarURL = async (
const linkAvatarURL = async (
ctx: SpaceLinkCtxHandle,
avatar: SpaceAvatar | undefined,
+ cache?: Map<string, Promise<string | null>>,
) => {
if (!avatar?.objectKey) return null;
- return blobURLForBytes(await ctx.download_space_avatar(avatar.objectKey));
+ const cached = cache?.get(avatar.objectKey);
+ if (cached) return cached;
+
+ const promise = ctx
+ .download_space_avatar(avatar.objectKey)
+ .then((bytes) => blobURLForBytes(bytes));
+ cache?.set(avatar.objectKey, promise);
+ return promise;
};
const firstObject = (post: { objects?: SpacePostObject[] }) =>
@@ -383,15 +393,21 @@ const postFromAccountPost = async (
const postFromLinkPost = async (
ctx: SpaceLinkCtxHandle,
post: SpacePostResponse,
+ avatarCache: Map<string, Promise<string | null>>,
): Promise<SpacePost | null> => {
const object = firstObject(post);
if (!object) return null;
const author = actorProfile(post.author);
- author.avatarUrl = await linkAvatarURL(ctx, post.author.avatar);
+ author.avatarUrl = await linkAvatarURL(ctx, post.author.avatar, avatarCache);
const imageUrl = blobURLForBytes(
- await ctx.download_post_asset(BigInt(post.postId), object.objectKey),
+ await ctx.download_post_asset_with_key(
+ BigInt(post.postId),
+ post.encryptedPostKey,
+ post.keyVersion,
+ object.objectKey,
+ ),
object.mediaType,
);
return {
@@ -426,10 +442,13 @@ const postPageFromAccountPage = async (
const postPageFromLinkPage = async (
ctx: SpaceLinkCtxHandle,
page: SpacePostPageResponse,
+ avatarCache = new Map<string, Promise<string | null>>(),
): Promise<SpacePostPage> => {
const items = (
await Promise.all(
- (page.items ?? []).map((post) => postFromLinkPost(ctx, post)),
+ (page.items ?? []).map((post) =>
+ postFromLinkPost(ctx, post, avatarCache),
+ ),
)
).filter((post): post is SpacePost => Boolean(post));
return { items, nextCursor: page.nextCursor || undefined };
@@ -910,13 +929,19 @@ export const loadPublicSpaceInvite = async ({
spaceUsername,
});
try {
+ const avatarCache = new Map<string, Promise<string | null>>();
const spaceProfile =
(await ctx.get_space_profile()) as SpaceProfileResponse;
const profile = profileFromSpaceProfile(spaceProfile);
- profile.avatarUrl = await linkAvatarURL(ctx, spaceProfile.avatar);
+ profile.avatarUrl = await linkAvatarURL(
+ ctx,
+ spaceProfile.avatar,
+ avatarCache,
+ );
const posts = await postPageFromLinkPage(
ctx,
(await ctx.list_posts(null, 60)) as SpacePostPageResponse,
+ avatarCache,
);
return { posts: posts.items, profile };
} finally {
diff --git a/web/packages/wasm/src/space.rs b/web/packages/wasm/src/space.rs
index f3228a8f1a..83357f312b 100644
--- a/web/packages/wasm/src/space.rs
+++ b/web/packages/wasm/src/space.rs
@@ -158,6 +158,7 @@ struct PostJs {
owner_user_id: i64,
author: ActorJs,
caption: Option<String>,
+ encrypted_post_key: String,
key_version: i32,
objects: Vec<ente_space::PostObjectPayload>,
created_at: String,
@@ -364,6 +365,7 @@ async fn account_post_to_js(
owner_user_id: post.owner_user_id,
author,
caption: optional_utf8_field(decrypted.caption_plaintext, "caption")?,
+ encrypted_post_key: post.encrypted_post_key,
key_version: post.key_version,
objects: post.objects,
created_at: post.created_at,
@@ -386,6 +388,7 @@ async fn link_post_to_js(
owner_user_id: post.owner_user_id,
author,
caption: optional_utf8_field(decrypted.caption_plaintext, "caption")?,
+ encrypted_post_key: post.encrypted_post_key,
key_version: post.key_version,
objects: post.objects,
created_at: post.created_at,
@@ -1071,6 +1074,20 @@ impl SpaceLinkCtxHandle {
.map_err(Into::into)
}
+ /// Download and decrypt one object from an already fetched public space post.
+ pub async fn download_post_asset_with_key(
+ &self,
+ post_id: i64,
+ encrypted_post_key: String,
+ key_version: i32,
+ object_key: String,
+ ) -> Result<Vec<u8>, WasmSpaceError> {
+ self.inner
+ .download_post_asset_with_key(post_id, &encrypted_post_key, key_version, &object_key)
+ .await
+ .map_err(Into::into)
+ }
+
/// Download and decrypt the public space avatar.
pub async fn download_space_avatar(
&self,