π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add signed URL download endpoints
Manav Rathifc59316d9937
diff --git a/rust/apps/cli/src/api/client.rs b/rust/apps/cli/src/api/client.rsindex 723d23c0f2..21c479efcb 100644--- a/rust/apps/cli/src/api/client.rs+++ b/rust/apps/cli/src/api/client.rs@@ -55,6 +55,10 @@ impl ApiClient {}pub(crate) fn api(&self, account_id: Option<&str>) -> Api {+ self.api_at(&self.base_url, account_id)+ }++ fn api_at(&self, origin: &str, account_id: Option<&str>) -> Api {let auth = account_id.and_then(|id| {let token = self.get_token(id);if token.is_none() {@@ -65,7 +69,7 @@ impl ApiClient {Api::new(self.http.clone(),ApiConfig {- origin: self.base_url.clone(),+ origin: origin.to_owned(),client_package: Some(self.client_package.clone()),client_version: None,user_agent: Some(USER_AGENT.to_string()),@@ -74,18 +78,68 @@ impl ApiClient {)}- pub async fn download_file(&self, url: &str, account_id: Option<&str>) -> Result<Vec<u8>> {- let token = account_id.and_then(|id| self.get_token(id));+ pub async fn download_file(&self, url: &str) -> Result<Vec<u8>> {Ok(http::retry_with_profile(RetryProfile::Background, || async {- let mut request = self.http.get(url);- if let Some(token) = &token {- // A header would ride the redirect to presigned storage; a query does not.- request = request.query(&[("token", token)]);- }- request.send().await?.error_for_status()?.bytes().await+ self.http+ .get(url)+ .send()+ .await?+ .error_for_status()?+ .bytes()+ .await}).await?,)}++ pub async fn download_from_proxy(+ &self,+ origin: &str,+ account_id: &str,+ file_id: i64,+ ) -> Result<Vec<u8>> {+ let api = self.api_at(origin, Some(account_id));+ Ok(+ http::retry_with_profile(RetryProfile::Background, || async {+ api.get("/")+ .query(&[("fileID", file_id)])+ .send()+ .await?+ .error_for_status()?+ .bytes()+ .await+ })+ .await?,+ )+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use mockito::{Matcher, Server};++ #[tokio::test]+ async fn proxy_download_uses_api_headers() {+ let mut server = Server::new_async().await;+ let download = server+ .mock("GET", "/")+ .match_query(Matcher::UrlEncoded("fileID".into(), "12345".into()))+ .match_header("x-auth-token", "token")+ .match_header("x-client-package", "io.ente.locker")+ .with_body("file")+ .create_async()+ .await;+ let client = ApiClient::new_with_client_package(None, "io.ente.locker").unwrap();+ client.add_token("account", "token");++ let bytes = client+ .download_from_proxy(&server.url(), "account", 12345)+ .await+ .unwrap();++ download.assert_async().await;+ assert_eq!(bytes, b"file");+ }}diff --git a/rust/apps/cli/src/api/methods.rs b/rust/apps/cli/src/api/methods.rsindex 5d65ee6789..7eaca9e3fb 100644--- a/rust/apps/cli/src/api/methods.rs+++ b/rust/apps/cli/src/api/methods.rs@@ -1,11 +1,14 @@use crate::api::client::ApiClient;use crate::api::models::{- Collection, File, GetCollectionsResponse, GetDiffResponse, GetFileResponse, GetFilesResponse,- GetThumbnailUrlResponse, UserDetails,+ Collection, File, GetCollectionsResponse, GetDiffResponse, GetFileResponse, GetFileUrlResponse,+ GetFilesResponse, GetThumbnailUrlResponse, UserDetails,};use crate::models::error::Result;use ente_core::http;-use ente_core::urls::file_download_url;+use ente_core::urls::{PRODUCTION_API_BASE_URL, file_download_url};++const FILES_ORIGIN: &str = "https://files.ente.com";+const THUMBNAILS_ORIGIN: &str = "https://thumbnails.ente.com";pub struct ApiMethods<'a> {client: &'a ApiClient,@@ -136,14 +139,31 @@ impl<'a> ApiMethods<'a> {Ok((response.diff, response.has_more))}- pub async fn get_file_url(&self, _account_id: &str, file_id: i64) -> Result<String> {- Ok(file_download_url(&self.client.base_url, file_id))+ pub async fn get_file_url(&self, account_id: &str, file_id: i64) -> Result<String> {+ if self.client.base_url == PRODUCTION_API_BASE_URL {+ return Ok(file_download_url(&self.client.base_url, file_id));+ }+ let api = self.client.api(Some(account_id));+ let response: GetFileUrlResponse = http::retry(|| async {+ api.get(&format!("/files/download/v2/{file_id}"))+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await+ })+ .await?;+ Ok(response.url)}pub async fn get_thumbnail_url(&self, account_id: &str, file_id: i64) -> Result<String> {+ if self.client.base_url == PRODUCTION_API_BASE_URL {+ return Ok(format!("{THUMBNAILS_ORIGIN}/?fileID={file_id}"));+ }let api = self.client.api(Some(account_id));let response: GetThumbnailUrlResponse = http::retry(|| async {- api.get(&format!("/files/preview/{file_id}"))+ api.get(&format!("/files/preview/v2/{file_id}")).send().await?.error_for_code()@@ -156,13 +176,25 @@ impl<'a> ApiMethods<'a> {}pub async fn download_file(&self, account_id: &str, file_id: i64) -> Result<Vec<u8>> {+ if self.client.base_url == PRODUCTION_API_BASE_URL {+ return self+ .client+ .download_from_proxy(FILES_ORIGIN, account_id, file_id)+ .await;+ }let url = self.get_file_url(account_id, file_id).await?;- self.client.download_file(&url, Some(account_id)).await+ self.client.download_file(&url).await}pub async fn download_thumbnail(&self, account_id: &str, file_id: i64) -> Result<Vec<u8>> {+ if self.client.base_url == PRODUCTION_API_BASE_URL {+ return self+ .client+ .download_from_proxy(THUMBNAILS_ORIGIN, account_id, file_id)+ .await;+ }let url = self.get_thumbnail_url(account_id, file_id).await?;- self.client.download_file(&url, Some(account_id)).await+ self.client.download_file(&url).await}pub async fn get_trash(&self, account_id: &str, since_time: i64) -> Result<(Vec<File>, bool)> {@@ -215,15 +247,52 @@ impl<'a> ApiMethods<'a> {#[cfg(test)]mod tests {use super::*;+ use mockito::{Matcher, Server};#[tokio::test]- async fn test_file_url_generation() {+ async fn test_production_urls() {let api = ApiClient::new(None).unwrap();let methods = ApiMethods::new(&api);- // For production endpoint, should use CDN- let url = methods.get_file_url("test", 12345).await;- assert!(url.is_ok());- assert!(url.unwrap().contains("files.ente.com"));+ assert_eq!(+ methods.get_file_url("test", 12345).await.unwrap(),+ "https://files.ente.com/?fileID=12345"+ );+ assert_eq!(+ methods.get_thumbnail_url("test", 12345).await.unwrap(),+ "https://thumbnails.ente.com/?fileID=12345"+ );+ }++ #[tokio::test]+ async fn test_self_hosted_download_uses_signed_url() {+ let mut server = Server::new_async().await;+ let signed_url = format!("{}/object", server.url());+ let url_mock = server+ .mock("GET", "/files/download/v2/12345")+ .match_header("x-auth-token", "token")+ .match_header("x-client-package", "io.ente.locker")+ .with_body(format!(r#"{{"url":"{signed_url}"}}"#))+ .create_async()+ .await;+ let download_mock = server+ .mock("GET", "/object")+ .match_header("x-auth-token", Matcher::Missing)+ .match_header("x-client-package", Matcher::Missing)+ .with_body("file")+ .create_async()+ .await;+ let client =+ ApiClient::new_with_client_package(Some(server.url()), "io.ente.locker").unwrap();+ client.add_token("account", "token");++ let bytes = ApiMethods::new(&client)+ .download_file("account", 12345)+ .await+ .unwrap();++ url_mock.assert_async().await;+ download_mock.assert_async().await;+ assert_eq!(bytes, b"file");}}diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.goindex c705cd7607..c4856e6059 100644--- a/server/cmd/museum/main.go+++ b/server/cmd/museum/main.go@@ -598,7 +598,9 @@ func main() {storageAPI.POST("/files/upload-url", fileHandler.GetUploadURLV2)storageAPI.POST("/files/multipart-upload-url", fileHandler.GetMultipartUploadURLV2)storageAPI.GET("/files/download/:fileID", fileHandler.Get)+ storageAPI.GET("/files/download/v2/:fileID", fileHandler.GetV2)storageAPI.GET("/files/preview/:fileID", fileHandler.GetThumbnail)+ storageAPI.GET("/files/preview/v2/:fileID", fileHandler.GetThumbnailV2)storageAPI.POST("/files/share-url", fileHandler.ShareUrl)storageAPI.GET("/files/share-url", fileHandler.GetUrls)@@ -1388,14 +1390,14 @@ func cacheHeaders() gin.HandlerFunc {// Add "Cache-Control: no-store" to HTTP GET API responses.if c.Request.Method == http.MethodGet {reqPath := urlSanitizer(c)- if strings.HasPrefix(reqPath, "/files/preview/") ||- strings.HasPrefix(reqPath, "/files/download/") ||- strings.HasPrefix(reqPath, "/public-collection/files/preview/") ||- strings.HasPrefix(reqPath, "/public-collection/files/download/") ||- strings.HasPrefix(reqPath, "/public-memory/files/preview/") ||- strings.HasPrefix(reqPath, "/public-memory/files/download/") ||- strings.HasPrefix(reqPath, "/cast/files/preview/") ||- strings.HasPrefix(reqPath, "/cast/files/download/") {+ if reqPath == "/files/preview/:fileID" ||+ reqPath == "/files/download/:fileID" ||+ reqPath == "/public-collection/files/preview/:fileID" ||+ reqPath == "/public-collection/files/download/:fileID" ||+ reqPath == "/public-memory/files/preview/:fileID" ||+ reqPath == "/public-memory/files/download/:fileID" ||+ reqPath == "/cast/files/preview/:fileID" ||+ reqPath == "/cast/files/download/:fileID" {// Exclude those that redirect to S3 for file downloads.} else {c.Writer.Header().Set("Cache-Control", "no-store")diff --git a/server/pkg/api/file.go b/server/pkg/api/file.goindex 4c7bd1f7f5..19ce94db00 100644--- a/server/pkg/api/file.go+++ b/server/pkg/api/file.go@@ -223,6 +223,17 @@ func (h *FileHandler) Get(c *gin.Context) {c.Redirect(http.StatusTemporaryRedirect, url)}+// GetV2 returns the URL of the file to the client+func (h *FileHandler) GetV2(c *gin.Context) {+ userID, fileID := getUserAndFileIDs(c)+ url, err := h.Controller.GetFileURL(c, userID, fileID)+ if err != nil {+ handler.Error(c, stacktrace.Propagate(err, ""))+ return+ }+ c.JSON(http.StatusOK, gin.H{"url": url})+}+// GetThumbnail redirects the request to the file's thumbnail locationfunc (h *FileHandler) GetThumbnail(c *gin.Context) {userID, fileID := getUserAndFileIDs(c)@@ -235,6 +246,17 @@ func (h *FileHandler) GetThumbnail(c *gin.Context) {c.Redirect(http.StatusTemporaryRedirect, url)}+// GetThumbnailV2 returns the URL of the thumbnail to the client+func (h *FileHandler) GetThumbnailV2(c *gin.Context) {+ userID, fileID := getUserAndFileIDs(c)+ url, err := h.Controller.GetThumbnailURL(c, userID, fileID)+ if err != nil {+ handler.Error(c, stacktrace.Propagate(err, ""))+ return+ }+ c.JSON(http.StatusOK, gin.H{"url": url})+}+// Trash moves the given files to the trash binfunc (h *FileHandler) Trash(c *gin.Context) {var request ente.TrashRequest