Skip to content

armgit / ente

Public Imported from GitHub
0

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

Implement sealed share secret flow

Neeraj Gupta4fc017bc00d6
diff --git a/mobile/apps/locker/lib/services/files/links/links_client.dart b/mobile/apps/locker/lib/services/files/links/links_client.dart
index ca7b6ec8c4..45a8cadeac 100644
--- a/mobile/apps/locker/lib/services/files/links/links_client.dart
+++ b/mobile/apps/locker/lib/services/files/links/links_client.dart
@@ -12,13 +12,17 @@ class LinksClient {
Future<void> init() async {}
- Future<ShareableLink> getOrCreateLink(int fileID) async {
+ Future<ShareableLink> getOrCreateLink(
+ int fileID, {
+ Map<String, dynamic>? metadata,
+ }) async {
try {
final response = await _enteDio.post(
'/files/share-url',
data: {
'fileID': fileID,
'app': 'locker',
+ if (metadata != null) ...metadata,
},
);
return ShareableLink.fromJson(response.data as Map<String, dynamic>);
diff --git a/mobile/apps/locker/lib/services/files/links/links_service.dart b/mobile/apps/locker/lib/services/files/links/links_service.dart
index 9114e0c918..0571a3fa63 100644
--- a/mobile/apps/locker/lib/services/files/links/links_service.dart
+++ b/mobile/apps/locker/lib/services/files/links/links_service.dart
@@ -1,8 +1,14 @@
-import "package:fast_base58/fast_base58.dart";
+import "dart:convert";
+import "dart:math";
+import "dart:typed_data";
+
+import "package:ente_crypto_dart/ente_crypto_dart.dart";
import "package:locker/services/collections/collections_service.dart";
+import "package:locker/services/configuration.dart";
import "package:locker/services/files/links/links_client.dart";
import "package:locker/services/files/links/models/shareable_link.dart";
import "package:locker/services/files/sync/models/file.dart";
+import "package:logging/logging.dart";
class LinksService {
LinksService._();
@@ -10,20 +16,138 @@ class LinksService {
static final LinksService instance = LinksService._();
late final LinksClient _client;
+ final Logger _logger = Logger("LinksService");
Future<void> init() async {
_client = LinksClient.instance;
}
Future<ShareableLink> getOrCreateLink(EnteFile file) async {
- final link = await _client.getOrCreateLink(file.uploadedFileID!);
- link.fullURL = link.url +
- "#" +
- Base58Encode(await CollectionService.instance.getFileKey(file));
+ final fileKey = await CollectionService.instance.getFileKey(file);
+ final secretPayload = await _prepareLinkSecret(fileKey);
+
+ final link = await _client.getOrCreateLink(
+ file.uploadedFileID!,
+ metadata: secretPayload.metadata(),
+ );
+ final fragmentSecret = await _resolveFragmentSecret(
+ link,
+ secretPayload,
+ );
+ link.fullURL = "${link.url}#$fragmentSecret";
return link;
}
Future<void> deleteLink(int fileID) async {
await _client.deleteLink(fileID);
}
+
+ Future<_LinkSecretPayload> _prepareLinkSecret(Uint8List fileKey) async {
+ try {
+ final secret = _generateBase62Secret(12);
+ final secretBytes = Uint8List.fromList(utf8.encode(secret));
+ final secretBase64 = CryptoUtil.bin2base64(secretBytes);
+
+ final kdfSalt = CryptoUtil.getSaltToDeriveKey();
+ final derivedKey = await CryptoUtil.deriveInteractiveKey(
+ Uint8List.fromList(utf8.encode(secret)),
+ kdfSalt,
+ );
+ final encryptedKey = CryptoUtil.encryptSync(fileKey, derivedKey.key);
+
+ final keyAttributes = Configuration.instance.getKeyAttributes();
+ final userPublicKey = keyAttributes?.publicKey;
+ if (userPublicKey == null) {
+ throw StateError(
+ "Public key unavailable while generating share secret");
+ }
+ final encryptedShareKeyBytes = CryptoUtil.sealSync(
+ Uint8List.fromList(utf8.encode(secretBase64)),
+ CryptoUtil.base642bin(userPublicKey),
+ );
+
+ return _LinkSecretPayload(
+ secret: secret,
+ encryptedFileKey: CryptoUtil.bin2base64(encryptedKey.encryptedData!),
+ encryptedFileKeyNonce: CryptoUtil.bin2base64(encryptedKey.nonce!),
+ kdfNonce: CryptoUtil.bin2base64(kdfSalt),
+ kdfMemLimit: derivedKey.memLimit,
+ kdfOpsLimit: derivedKey.opsLimit,
+ encryptedShareKey: CryptoUtil.bin2base64(encryptedShareKeyBytes),
+ );
+ } catch (e, s) {
+ _logger.severe("Failed to prepare link secret", e, s);
+ rethrow;
+ }
+ }
+
+ Future<String> _resolveFragmentSecret(
+ ShareableLink link,
+ _LinkSecretPayload payload,
+ ) async {
+ final encryptedShareKey = link.encryptedShareKey;
+ if (encryptedShareKey != null) {
+ try {
+ final keyAttributes = Configuration.instance.getKeyAttributes();
+ final secretKey = Configuration.instance.getSecretKey();
+ if (keyAttributes != null && secretKey != null) {
+ final decryptedBytes = CryptoUtil.openSealSync(
+ CryptoUtil.base642bin(encryptedShareKey),
+ CryptoUtil.base642bin(keyAttributes.publicKey),
+ secretKey,
+ );
+ final secretBase64 = utf8.decode(decryptedBytes);
+ final secret = utf8.decode(CryptoUtil.base642bin(secretBase64));
+ return secret;
+ }
+ _logger.warning("Missing key material to decrypt share secret");
+ } catch (e, s) {
+ _logger.severe("Failed to decrypt share secret", e, s);
+ }
+ }
+
+ return payload.secret;
+ }
+
+ String _generateBase62Secret(int length) {
+ const charset =
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+ final random = Random.secure();
+ final buffer = StringBuffer();
+ for (var i = 0; i < length; i++) {
+ buffer.write(charset[random.nextInt(charset.length)]);
+ }
+ return buffer.toString();
+ }
+}
+
+class _LinkSecretPayload {
+ _LinkSecretPayload({
+ required this.secret,
+ required this.encryptedFileKey,
+ required this.encryptedFileKeyNonce,
+ required this.kdfNonce,
+ required this.kdfMemLimit,
+ required this.kdfOpsLimit,
+ required this.encryptedShareKey,
+ });
+
+ final String secret;
+ final String encryptedFileKey;
+ final String encryptedFileKeyNonce;
+ final String kdfNonce;
+ final int kdfMemLimit;
+ final int kdfOpsLimit;
+ final String encryptedShareKey;
+
+ Map<String, dynamic> metadata() {
+ return {
+ 'encryptedFileKey': encryptedFileKey,
+ 'encryptedFileKeyNonce': encryptedFileKeyNonce,
+ 'kdfNonce': kdfNonce,
+ 'kdfMemLimit': kdfMemLimit,
+ 'kdfOpsLimit': kdfOpsLimit,
+ 'encryptedShareKey': encryptedShareKey,
+ };
+ }
}
diff --git a/mobile/apps/locker/lib/services/files/links/models/shareable_link.dart b/mobile/apps/locker/lib/services/files/links/models/shareable_link.dart
index 9e71fdd401..6c308aeffe 100644
--- a/mobile/apps/locker/lib/services/files/links/models/shareable_link.dart
+++ b/mobile/apps/locker/lib/services/files/links/models/shareable_link.dart
@@ -12,6 +12,12 @@ class ShareableLink {
final bool enableDownload;
final int createdAt;
String? fullURL;
+ final String? encryptedFileKey;
+ final String? encryptedFileKeyNonce;
+ final String? kdfNonce;
+ final int? kdfMemLimit;
+ final int? kdfOpsLimit;
+ final String? encryptedShareKey;
ShareableLink({
required this.linkID,
@@ -26,6 +32,12 @@ class ShareableLink {
this.opsLimit,
required this.enableDownload,
required this.createdAt,
+ this.encryptedFileKey,
+ this.encryptedFileKeyNonce,
+ this.kdfNonce,
+ this.kdfMemLimit,
+ this.kdfOpsLimit,
+ this.encryptedShareKey,
});
factory ShareableLink.fromJson(Map<String, dynamic> json) {
@@ -42,6 +54,12 @@ class ShareableLink {
opsLimit: json['opsLimit'] as int?,
enableDownload: json['enableDownload'] as bool,
createdAt: json['createdAt'] as int,
+ encryptedFileKey: json['encryptedFileKey'] as String?,
+ encryptedFileKeyNonce: json['encryptedFileKeyNonce'] as String?,
+ kdfNonce: json['kdfNonce'] as String?,
+ kdfMemLimit: json['kdfMemLimit'] as int?,
+ kdfOpsLimit: json['kdfOpsLimit'] as int?,
+ encryptedShareKey: json['encryptedShareKey'] as String?,
);
}
@@ -59,6 +77,13 @@ class ShareableLink {
if (opsLimit != null) 'opsLimit': opsLimit,
'enableDownload': enableDownload,
'createdAt': createdAt,
+ if (encryptedFileKey != null) 'encryptedFileKey': encryptedFileKey,
+ if (encryptedFileKeyNonce != null)
+ 'encryptedFileKeyNonce': encryptedFileKeyNonce,
+ if (kdfNonce != null) 'kdfNonce': kdfNonce,
+ if (kdfMemLimit != null) 'kdfMemLimit': kdfMemLimit,
+ if (kdfOpsLimit != null) 'kdfOpsLimit': kdfOpsLimit,
+ if (encryptedShareKey != null) 'encryptedShareKey': encryptedShareKey,
};
}
@@ -77,7 +102,13 @@ class ShareableLink {
other.memLimit == memLimit &&
other.opsLimit == opsLimit &&
other.enableDownload == enableDownload &&
- other.createdAt == createdAt;
+ other.createdAt == createdAt &&
+ other.encryptedFileKey == encryptedFileKey &&
+ other.encryptedFileKeyNonce == encryptedFileKeyNonce &&
+ other.kdfNonce == kdfNonce &&
+ other.kdfMemLimit == kdfMemLimit &&
+ other.kdfOpsLimit == kdfOpsLimit &&
+ other.encryptedShareKey == encryptedShareKey;
}
@override
@@ -95,6 +126,12 @@ class ShareableLink {
opsLimit,
enableDownload,
createdAt,
+ encryptedFileKey,
+ encryptedFileKeyNonce,
+ kdfNonce,
+ kdfMemLimit,
+ kdfOpsLimit,
+ encryptedShareKey,
);
}
@@ -112,7 +149,13 @@ class ShareableLink {
'memLimit: $memLimit, '
'opsLimit: $opsLimit, '
'enableDownload: $enableDownload, '
- 'createdAt: $createdAt'
+ 'createdAt: $createdAt, '
+ 'encryptedFileKey: $encryptedFileKey, '
+ 'encryptedFileKeyNonce: $encryptedFileKeyNonce, '
+ 'kdfNonce: $kdfNonce, '
+ 'kdfMemLimit: $kdfMemLimit, '
+ 'kdfOpsLimit: $kdfOpsLimit, '
+ 'encryptedShareKey: $encryptedShareKey'
')';
}
@@ -129,6 +172,12 @@ class ShareableLink {
int? opsLimit,
bool? enableDownload,
int? createdAt,
+ String? encryptedFileKey,
+ String? encryptedFileKeyNonce,
+ String? kdfNonce,
+ int? kdfMemLimit,
+ int? kdfOpsLimit,
+ String? encryptedShareKey,
}) {
return ShareableLink(
linkID: linkID ?? this.linkID,
@@ -143,6 +192,13 @@ class ShareableLink {
opsLimit: opsLimit ?? this.opsLimit,
enableDownload: enableDownload ?? this.enableDownload,
createdAt: createdAt ?? this.createdAt,
+ encryptedFileKey: encryptedFileKey ?? this.encryptedFileKey,
+ encryptedFileKeyNonce:
+ encryptedFileKeyNonce ?? this.encryptedFileKeyNonce,
+ kdfNonce: kdfNonce ?? this.kdfNonce,
+ kdfMemLimit: kdfMemLimit ?? this.kdfMemLimit,
+ kdfOpsLimit: kdfOpsLimit ?? this.kdfOpsLimit,
+ encryptedShareKey: encryptedShareKey ?? this.encryptedShareKey,
);
}
}
diff --git a/server/ente/file_link.go b/server/ente/file_link.go
index e817e35da0..27ec1b5beb 100644
--- a/server/ente/file_link.go
+++ b/server/ente/file_link.go
@@ -7,8 +7,14 @@ import (
// CreateFileUrl represents an encrypted file in the system
type CreateFileUrl struct {
- FileID int64 `json:"fileID" binding:"required"`
- App App `json:"app" binding:"required"`
+ FileID int64 `json:"fileID" binding:"required"`
+ App App `json:"app" binding:"required"`
+ EncryptedFileKey *string `json:"encryptedFileKey,omitempty"`
+ EncryptedFileKeyNonce *string `json:"encryptedFileKeyNonce,omitempty"`
+ KdfNonce *string `json:"kdfNonce,omitempty"`
+ KdfMemLimit *int64 `json:"kdfMemLimit,omitempty"`
+ KdfOpsLimit *int64 `json:"kdfOpsLimit,omitempty"`
+ EncryptedShareKey *string `json:"encryptedShareKey,omitempty"`
}
// UpdateFileUrl ..
@@ -53,20 +59,26 @@ func (ut *UpdateFileUrl) Validate() error {
}
type FileLinkRow struct {
- LinkID string
- OwnerID int64
- FileID int64
- Token string
- DeviceLimit int
- ValidTill int64
- IsDisabled bool
- PassHash *string
- Nonce *string
- MemLimit *int64
- OpsLimit *int64
- EnableDownload bool
- CreatedAt int64
- UpdatedAt int64
+ LinkID string
+ OwnerID int64
+ FileID int64
+ Token string
+ DeviceLimit int
+ ValidTill int64
+ IsDisabled bool
+ PassHash *string
+ Nonce *string
+ MemLimit *int64
+ OpsLimit *int64
+ EnableDownload bool
+ CreatedAt int64
+ UpdatedAt int64
+ EncryptedFileKey *string
+ EncryptedFileKeyNonce *string
+ KdfNonce *string
+ KdfMemLimit *int64
+ KdfOpsLimit *int64
+ EncryptedShareKey *string
}
type FileUrl struct {
@@ -78,11 +90,17 @@ type FileUrl struct {
DeviceLimit int `json:"deviceLimit"`
PasswordEnabled bool `json:"passwordEnabled"`
// Nonce contains the nonce value for the password if the link is password protected.
- Nonce *string `json:"nonce,omitempty"`
- MemLimit *int64 `json:"memLimit,omitempty"`
- OpsLimit *int64 `json:"opsLimit,omitempty"`
- EnableDownload bool `json:"enableDownload"`
- CreatedAt int64 `json:"createdAt"`
+ Nonce *string `json:"nonce,omitempty"`
+ MemLimit *int64 `json:"memLimit,omitempty"`
+ OpsLimit *int64 `json:"opsLimit,omitempty"`
+ EnableDownload bool `json:"enableDownload"`
+ CreatedAt int64 `json:"createdAt"`
+ EncryptedFileKey *string `json:"encryptedFileKey,omitempty"`
+ EncryptedFileKeyNonce *string `json:"encryptedFileKeyNonce,omitempty"`
+ KdfNonce *string `json:"kdfNonce,omitempty"`
+ KdfMemLimit *int64 `json:"kdfMemLimit,omitempty"`
+ KdfOpsLimit *int64 `json:"kdfOpsLimit,omitempty"`
+ EncryptedShareKey *string `json:"encryptedShareKey,omitempty"`
}
type FileLinkAccessContext struct {
diff --git a/server/migrations/108_file_link_secret_fields.down.sql b/server/migrations/108_file_link_secret_fields.down.sql
new file mode 100644
index 0000000000..ffeba7d6b4
--- /dev/null
+++ b/server/migrations/108_file_link_secret_fields.down.sql
@@ -0,0 +1,7 @@
+ALTER TABLE public_file_tokens
+ DROP COLUMN IF EXISTS encrypted_file_key,
+ DROP COLUMN IF EXISTS encrypted_file_key_nonce,
+ DROP COLUMN IF EXISTS kdf_nonce,
+ DROP COLUMN IF EXISTS kdf_mem_limit,
+ DROP COLUMN IF EXISTS kdf_ops_limit,
+ DROP COLUMN IF EXISTS encrypted_share_key;
diff --git a/server/migrations/108_file_link_secret_fields.up.sql b/server/migrations/108_file_link_secret_fields.up.sql
new file mode 100644
index 0000000000..4716c73bd8
--- /dev/null
+++ b/server/migrations/108_file_link_secret_fields.up.sql
@@ -0,0 +1,7 @@
+ALTER TABLE public_file_tokens
+ ADD COLUMN IF NOT EXISTS encrypted_file_key TEXT,
+ ADD COLUMN IF NOT EXISTS encrypted_file_key_nonce TEXT,
+ ADD COLUMN IF NOT EXISTS kdf_nonce TEXT,
+ ADD COLUMN IF NOT EXISTS kdf_mem_limit BIGINT,
+ ADD COLUMN IF NOT EXISTS kdf_ops_limit BIGINT,
+ ADD COLUMN IF NOT EXISTS encrypted_share_key TEXT;
diff --git a/server/pkg/api/file_link.go b/server/pkg/api/file_link.go
index d243a87532..fb5c699e87 100644
--- a/server/pkg/api/file_link.go
+++ b/server/pkg/api/file_link.go
@@ -27,14 +27,18 @@ func (h *FileHandler) ShareUrl(c *gin.Context) {
}
func (h *FileHandler) LinkInfo(c *gin.Context) {
- resp, err := h.FileUrlCtrl.Info(c)
+ fileResp, linkResp, err := h.FileUrlCtrl.Info(c)
if err != nil {
handler.Error(c, stacktrace.Propagate(err, ""))
return
}
- c.JSON(http.StatusOK, gin.H{
- "file": resp,
- })
+ response := gin.H{
+ "file": fileResp,
+ }
+ if linkResp != nil {
+ response["link"] = linkResp
+ }
+ c.JSON(http.StatusOK, response)
}
func (h *FileHandler) PasswordInfo(c *gin.Context) {
diff --git a/server/pkg/controller/public/file_link.go b/server/pkg/controller/public/file_link.go
index f541c0bf0f..37d9957a0a 100644
--- a/server/pkg/controller/public/file_link.go
+++ b/server/pkg/controller/public/file_link.go
@@ -33,12 +33,23 @@ func (c *FileLinkController) CreateLink(ctx *gin.Context, req ente.CreateFileUrl
return nil, stacktrace.Propagate(ente.NewPermissionDeniedError("not file owner"), "")
}
accessToken := shortuuid.New()[0:AccessTokenLength]
- _, err = c.FileLinkRepo.Insert(ctx, req.FileID, actorUserID, accessToken, app)
+ _, err = c.FileLinkRepo.Insert(ctx, req, actorUserID, accessToken)
if err == nil || err == ente.ErrActiveLinkAlreadyExists {
row, rowErr := c.FileLinkRepo.GetFileUrlRowByFileID(ctx, req.FileID)
if rowErr != nil {
return nil, stacktrace.Propagate(rowErr, "failed to get active file url token")
}
+ if err == ente.ErrActiveLinkAlreadyExists {
+ updateErr := c.FileLinkRepo.UpdateLinkSecretIfEmpty(ctx, row.LinkID, req)
+ if updateErr != nil {
+ return nil, stacktrace.Propagate(updateErr, "failed to update link secret")
+ }
+ // Re-fetch to include any values that might have been updated.
+ row, rowErr = c.FileLinkRepo.GetFileUrlRowByFileID(ctx, req.FileID)
+ if rowErr != nil {
+ return nil, stacktrace.Propagate(rowErr, "failed to get active file url token after updating secret")
+ }
+ }
return c.mapRowToFileUrl(ctx, row), nil
}
return nil, stacktrace.Propagate(err, "failed to create public file link")
@@ -110,9 +121,17 @@ func (c *FileLinkController) UpdateSharedUrl(ctx *gin.Context, req ente.UpdateFi
return c.mapRowToFileUrl(ctx, fileLinkRow), nil
}
-func (c *FileLinkController) Info(ctx *gin.Context) (*ente.File, error) {
+func (c *FileLinkController) Info(ctx *gin.Context) (*ente.File, *ente.FileUrl, error) {
accessContext := auth.MustGetFileLinkAccessContext(ctx)
- return c.FileRepo.GetFileAttributes(accessContext.FileID)
+ file, err := c.FileRepo.GetFileAttributes(accessContext.FileID)
+ if err != nil {
+ return nil, nil, stacktrace.Propagate(err, "failed to get file attributes")
+ }
+ row, err := c.FileLinkRepo.GetFileUrlRowByFileID(ctx, accessContext.FileID)
+ if err != nil {
+ return nil, nil, stacktrace.Propagate(err, "failed to get file link row")
+ }
+ return file, c.mapRowToFileUrl(ctx, row), nil
}
func (c *FileLinkController) PassInfo(ctx *gin.Context) (*ente.FileLinkRow, error) {
@@ -142,17 +161,23 @@ func (c *FileLinkController) mapRowToFileUrl(ctx *gin.Context, row *ente.FileLin
url := c.FileLinkRepo.FileLink(app, row.Token)
return &ente.FileUrl{
- LinkID: row.LinkID,
- FileID: row.FileID,
- URL: url,
- OwnerID: row.OwnerID,
- ValidTill: row.ValidTill,
- DeviceLimit: row.DeviceLimit,
- PasswordEnabled: row.PassHash != nil,
- Nonce: row.Nonce,
- OpsLimit: row.OpsLimit,
- MemLimit: row.MemLimit,
- EnableDownload: row.EnableDownload,
- CreatedAt: row.CreatedAt,
+ LinkID: row.LinkID,
+ FileID: row.FileID,
+ URL: url,
+ OwnerID: row.OwnerID,
+ ValidTill: row.ValidTill,
+ DeviceLimit: row.DeviceLimit,
+ PasswordEnabled: row.PassHash != nil,
+ Nonce: row.Nonce,
+ OpsLimit: row.OpsLimit,
+ MemLimit: row.MemLimit,
+ EnableDownload: row.EnableDownload,
+ CreatedAt: row.CreatedAt,
+ EncryptedFileKey: row.EncryptedFileKey,
+ EncryptedFileKeyNonce: row.EncryptedFileKeyNonce,
+ KdfNonce: row.KdfNonce,
+ KdfMemLimit: row.KdfMemLimit,
+ KdfOpsLimit: row.KdfOpsLimit,
+ EncryptedShareKey: row.EncryptedShareKey,
}
}
diff --git a/server/pkg/repo/public/file_link.go b/server/pkg/repo/public/file_link.go
index 9e69d31c01..836bba0375 100644
--- a/server/pkg/repo/public/file_link.go
+++ b/server/pkg/repo/public/file_link.go
@@ -47,18 +47,29 @@ func (pcr *FileLinkRepository) FileLink(app ente.App, token string) string {
func (pcr *FileLinkRepository) Insert(
ctx context.Context,
- fileID int64,
+ req ente.CreateFileUrl,
ownerID int64,
token string,
- app ente.App,
) (*string, error) {
id, err := base.NewID("pft")
if err != nil {
return nil, stacktrace.Propagate(err, "failed to generate new ID for public file token")
}
_, err = pcr.DB.ExecContext(ctx, `INSERT INTO public_file_tokens
- (id, file_id, owner_id, access_token, app) VALUES ($1, $2, $3, $4, $5)`,
- id, fileID, ownerID, token, string(app))
+ (id, file_id, owner_id, access_token, app, encrypted_file_key, encrypted_file_key_nonce, kdf_nonce, kdf_mem_limit, kdf_ops_limit, encrypted_share_key)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
+ id,
+ req.FileID,
+ ownerID,
+ token,
+ string(req.App),
+ req.EncryptedFileKey,
+ req.EncryptedFileKeyNonce,
+ req.KdfNonce,
+ req.KdfMemLimit,
+ req.KdfOpsLimit,
+ req.EncryptedShareKey,
+ )
if err != nil {
if err.Error() == "pq: duplicate key value violates unique constraint \"public_active_file_link_unique_idx\"" {
return nil, ente.ErrActiveLinkAlreadyExists
@@ -68,17 +79,53 @@ func (pcr *FileLinkRepository) Insert(
return id, nil
}
+// UpdateLinkSecretIfEmpty updates link key metadata if it hasn't been set already.
+func (pcr *FileLinkRepository) UpdateLinkSecretIfEmpty(
+ ctx context.Context,
+ linkID string,
+ data ente.CreateFileUrl,
+) error {
+ if data.EncryptedFileKey == nil &&
+ data.EncryptedFileKeyNonce == nil &&
+ data.KdfNonce == nil &&
+ data.KdfMemLimit == nil &&
+ data.KdfOpsLimit == nil &&
+ data.EncryptedShareKey == nil {
+ return nil
+ }
+ _, err := pcr.DB.ExecContext(ctx, `
+ UPDATE public_file_tokens
+ SET encrypted_file_key = COALESCE(encrypted_file_key, $1),
+ encrypted_file_key_nonce = COALESCE(encrypted_file_key_nonce, $2),
+ kdf_nonce = COALESCE(kdf_nonce, $3),
+ kdf_mem_limit = COALESCE(kdf_mem_limit, $4),
+ kdf_ops_limit = COALESCE(kdf_ops_limit, $5),
+ encrypted_share_key = COALESCE(encrypted_share_key, $6)
+ WHERE id = $7`,
+ data.EncryptedFileKey,
+ data.EncryptedFileKeyNonce,
+ data.KdfNonce,
+ data.KdfMemLimit,
+ data.KdfOpsLimit,
+ data.EncryptedShareKey,
+ linkID,
+ )
+ return stacktrace.Propagate(err, "failed to update link secret metadata")
+}
+
// GetActiveFileUrlToken will return ente.CollectionLinkRow for given collection ID
// Note: The token could be expired or deviceLimit is already reached
func (pcr *FileLinkRepository) GetActiveFileUrlToken(ctx context.Context, fileID int64) (*ente.FileLinkRow, error) {
row := pcr.DB.QueryRowContext(ctx, `SELECT id, file_id, owner_id, access_token, valid_till, device_limit,
- is_disabled, pw_hash, pw_nonce, mem_limit, ops_limit, enable_download FROM
+ is_disabled, pw_hash, pw_nonce, mem_limit, ops_limit, enable_download,
+ encrypted_file_key, encrypted_file_key_nonce, kdf_nonce, kdf_mem_limit, kdf_ops_limit, encrypted_share_key FROM
public_file_tokens WHERE file_id = $1 and is_disabled = FALSE`,
fileID)
ret := ente.FileLinkRow{}
err := row.Scan(&ret.LinkID, &ret.FileID, &ret.OwnerID, &ret.Token, &ret.ValidTill, &ret.DeviceLimit,
- &ret.IsDisabled, &ret.PassHash, &ret.Nonce, &ret.MemLimit, &ret.OpsLimit, &ret.EnableDownload)
+ &ret.IsDisabled, &ret.PassHash, &ret.Nonce, &ret.MemLimit, &ret.OpsLimit, &ret.EnableDownload,
+ &ret.EncryptedFileKey, &ret.EncryptedFileKeyNonce, &ret.KdfNonce, &ret.KdfMemLimit, &ret.KdfOpsLimit, &ret.EncryptedShareKey)
if err != nil {
return nil, stacktrace.Propagate(err, "")
}
@@ -89,7 +136,8 @@ func (pcr *FileLinkRepository) GetFileUrls(ctx context.Context, userID int64, si
limit = 500
}
query := `SELECT id, file_id, owner_id, is_disabled, valid_till, device_limit, enable_download, pw_hash, pw_nonce, mem_limit, ops_limit,
- created_at, updated_at FROM public_file_tokens
+ created_at, updated_at, encrypted_file_key, encrypted_file_key_nonce, kdf_nonce, kdf_mem_limit, kdf_ops_limit, encrypted_share_key
+ FROM public_file_tokens
WHERE owner_id = $1 AND created_at > $2 AND app = $3 ORDER BY updated_at DESC LIMIT $4`
rows, err := pcr.DB.QueryContext(ctx, query, userID, sinceTime, string(app), limit)
if err != nil {
@@ -103,7 +151,8 @@ func (pcr *FileLinkRepository) GetFileUrls(ctx context.Context, userID int64, si
err = rows.Scan(&row.LinkID, &row.FileID, &row.OwnerID, &row.IsDisabled,
&row.ValidTill, &row.DeviceLimit, &row.EnableDownload,
&row.PassHash, &row.Nonce, &row.MemLimit,
- &row.OpsLimit, &row.CreatedAt, &row.UpdatedAt)
+ &row.OpsLimit, &row.CreatedAt, &row.UpdatedAt,
+ &row.EncryptedFileKey, &row.EncryptedFileKeyNonce, &row.KdfNonce, &row.KdfMemLimit, &row.KdfOpsLimit, &row.EncryptedShareKey)
if err != nil {
return nil, stacktrace.Propagate(err, "failed to scan public file url row")
}
@@ -136,12 +185,12 @@ func (pcr *FileLinkRepository) DisableLinksForUser(ctx context.Context, userID i
func (pcr *FileLinkRepository) GetFileUrlRowByToken(ctx context.Context, accessToken string) (*ente.FileLinkRow, error) {
row := pcr.DB.QueryRowContext(ctx,
`SELECT id, file_id, owner_id, is_disabled, valid_till, device_limit, enable_download, pw_hash, pw_nonce, mem_limit, ops_limit,
- created_at, updated_at
+ created_at, updated_at, encrypted_file_key, encrypted_file_key_nonce, kdf_nonce, kdf_mem_limit, kdf_ops_limit, encrypted_share_key
from public_file_tokens
where access_token = $1
`, accessToken)
var result = ente.FileLinkRow{}
- err := row.Scan(&result.LinkID, &result.FileID, &result.OwnerID, &result.IsDisabled, &result.ValidTill, &result.DeviceLimit, &result.EnableDownload, &result.PassHash, &result.Nonce, &result.MemLimit, &result.OpsLimit, &result.CreatedAt, &result.UpdatedAt)
+ err := row.Scan(&result.LinkID, &result.FileID, &result.OwnerID, &result.IsDisabled, &result.ValidTill, &result.DeviceLimit, &result.EnableDownload, &result.PassHash, &result.Nonce, &result.MemLimit, &result.OpsLimit, &result.CreatedAt, &result.UpdatedAt, &result.EncryptedFileKey, &result.EncryptedFileKeyNonce, &result.KdfNonce, &result.KdfMemLimit, &result.KdfOpsLimit, &result.EncryptedShareKey)
if err != nil {
if err == sql.ErrNoRows {
return nil, ente.ErrNotFound
@@ -154,11 +203,11 @@ func (pcr *FileLinkRepository) GetFileUrlRowByToken(ctx context.Context, accessT
func (pcr *FileLinkRepository) GetFileUrlRowByFileID(ctx context.Context, fileID int64) (*ente.FileLinkRow, error) {
row := pcr.DB.QueryRowContext(ctx,
`SELECT id, file_id, access_token, owner_id, is_disabled, enable_download, valid_till, device_limit, pw_hash, pw_nonce, mem_limit, ops_limit,
- created_at, updated_at
+ created_at, updated_at, encrypted_file_key, encrypted_file_key_nonce, kdf_nonce, kdf_mem_limit, kdf_ops_limit, encrypted_share_key
from public_file_tokens
where file_id = $1 and is_disabled = FALSE`, fileID)
var result = ente.FileLinkRow{}
- err := row.Scan(&result.LinkID, &result.FileID, &result.Token, &result.OwnerID, &result.IsDisabled, &result.EnableDownload, &result.ValidTill, &result.DeviceLimit, &result.PassHash, &result.Nonce, &result.MemLimit, &result.OpsLimit, &result.CreatedAt, &result.UpdatedAt)
+ err := row.Scan(&result.LinkID, &result.FileID, &result.Token, &result.OwnerID, &result.IsDisabled, &result.EnableDownload, &result.ValidTill, &result.DeviceLimit, &result.PassHash, &result.Nonce, &result.MemLimit, &result.OpsLimit, &result.CreatedAt, &result.UpdatedAt, &result.EncryptedFileKey, &result.EncryptedFileKeyNonce, &result.KdfNonce, &result.KdfMemLimit, &result.KdfOpsLimit, &result.EncryptedShareKey)
if err != nil {
if err == sql.ErrNoRows {
return nil, ente.ErrNotFound
diff --git a/web/apps/share/src/hooks/useFileShare.ts b/web/apps/share/src/hooks/useFileShare.ts
index 074456d266..cad1ef0f95 100644
--- a/web/apps/share/src/hooks/useFileShare.ts
+++ b/web/apps/share/src/hooks/useFileShare.ts
@@ -46,10 +46,10 @@ export const useFileShare = (): UseFileShareResult => {
}
const currentURL = new URL(window.location.href);
- const key = await extractFileKeyFromURL(currentURL);
+ const keyMaterial = await extractFileKeyFromURL(currentURL);
- if (!key) {
- setError("Invalid file link. Missing file key.");
+ if (!keyMaterial) {
+ setError("Invalid file link. Missing secret.");
setLoading(false);
return;
}
@@ -57,7 +57,10 @@ export const useFileShare = (): UseFileShareResult => {
setAccessToken(token);
const encryptedInfo = await fetchFileInfo(token);
- const decryptedInfo = await decryptFileInfo(encryptedInfo, key);
+ const decryptedInfo = await decryptFileInfo(
+ encryptedInfo,
+ keyMaterial,
+ );
// Check if decryption failed (invalid key)
if (
diff --git a/web/apps/share/src/services/file-share.ts b/web/apps/share/src/services/file-share.ts
index c47e0ecfbf..39575a9f69 100644
--- a/web/apps/share/src/services/file-share.ts
+++ b/web/apps/share/src/services/file-share.ts
@@ -3,6 +3,7 @@ import {
decryptBoxBytes,
decryptMetadataJSON,
decryptStreamBytes,
+ deriveKey,
fromHex,
toB64,
} from "ente-base/crypto";
@@ -11,6 +12,7 @@ import type {
DecryptedFileInfo,
FileLinkInfo,
FileMetadata,
+ LinkKeyMaterial,
LockerInfo,
} from "../types/file-share";
@@ -19,22 +21,25 @@ import type {
*/
export const extractFileKeyFromURL = async (
url: URL,
-): Promise<string | null> => {
+): Promise<LinkKeyMaterial | null> => {
const hashValue = url.hash.slice(1); // Remove '#' prefix
if (!hashValue) return null;
try {
- let decodedKey: string;
- // Support both base58 and hex encoding
+ const base62SecretPattern = /^[0-9A-Za-z]{12}$/;
+
+ if (hashValue.length === 12 && base62SecretPattern.test(hashValue)) {
+ return { type: "secret", passphrase: hashValue };
+ }
+
+ // Support both base58 and hex encoding for legacy links
if (hashValue.length < 50) {
// Base58 encoded - convert to base64
const decoded = bs58.decode(hashValue);
- decodedKey = await toB64(decoded);
- } else {
- // Hex encoded - convert to base64
- decodedKey = await fromHex(hashValue);
+ return { type: "direct", fileKey: await toB64(decoded) };
}
- return decodedKey;
+ // Hex encoded - convert to base64
+ return { type: "direct", fileKey: await fromHex(hashValue) };
} catch {
return null;
}
@@ -169,12 +174,58 @@ const extractFileInfo = (
return { fileName, fileSize, uploadedTime };
};
+const resolveFileKey = async (
+ fileLinkInfo: FileLinkInfo,
+ keyMaterial: LinkKeyMaterial,
+): Promise<string> => {
+ const file = fileLinkInfo.file;
+
+ if (keyMaterial.type === "secret") {
+ const linkMeta = fileLinkInfo.link;
+ if (
+ !linkMeta?.encryptedFileKey ||
+ !linkMeta.encryptedFileKeyNonce ||
+ !linkMeta.kdfNonce ||
+ linkMeta.kdfMemLimit == null ||
+ linkMeta.kdfOpsLimit == null
+ ) {
+ throw new Error("Missing link metadata for deriving file key");
+ }
+
+ const derivedKey = await deriveKey(
+ keyMaterial.passphrase,
+ linkMeta.kdfNonce,
+ linkMeta.kdfOpsLimit,
+ linkMeta.kdfMemLimit,
+ );
+
+ const decryptedKeyBytes = await decryptBoxBytes(
+ {
+ encryptedData: linkMeta.encryptedFileKey,
+ nonce: linkMeta.encryptedFileKeyNonce,
+ },
+ derivedKey,
+ );
+ return await toB64(decryptedKeyBytes);
+ }
+
+ if (file?.encryptedKey && file.keyDecryptionNonce) {
+ return await decryptFileKey(
+ file.encryptedKey,
+ file.keyDecryptionNonce,
+ keyMaterial.fileKey,
+ );
+ }
+
+ return keyMaterial.fileKey;
+};
+
/**
* Decrypt file info
*/
export const decryptFileInfo = async (
fileLinkInfo: FileLinkInfo,
- linkKey: string,
+ keyMaterial: LinkKeyMaterial,
): Promise<DecryptedFileInfo> => {
try {
const file = fileLinkInfo.file;
@@ -184,15 +235,7 @@ export const decryptFileInfo = async (
throw new Error("No file object in response");
}
- // Decrypt the file key if it exists
- let fileKey = linkKey; // Default to link key
- if (file.encryptedKey && file.keyDecryptionNonce) {
- fileKey = await decryptFileKey(
- file.encryptedKey,
- file.keyDecryptionNonce,
- linkKey,
- );
- }
+ const fileKey = await resolveFileKey(fileLinkInfo, keyMaterial);
const fileId = file.id || 0;
const fileDecryptionHeader = file.file?.decryptionHeader;
diff --git a/web/apps/share/src/types/file-share.ts b/web/apps/share/src/types/file-share.ts
index 4c54a9ea89..922407bbb2 100644
--- a/web/apps/share/src/types/file-share.ts
+++ b/web/apps/share/src/types/file-share.ts
@@ -1,3 +1,11 @@
+export interface FileLinkMeta {
+ encryptedFileKey?: string;
+ encryptedFileKeyNonce?: string;
+ kdfNonce?: string;
+ kdfMemLimit?: number;
+ kdfOpsLimit?: number;
+}
+
export interface FileLinkInfo {
file?: {
id?: number;
@@ -28,6 +36,7 @@ export interface FileLinkInfo {
uploadedTime?: number;
};
ownerName?: string;
+ link?: FileLinkMeta;
}
export interface LockerInfoData {
@@ -68,3 +77,7 @@ export interface DecryptedFileInfo {
lockerType?: string;
lockerInfoData?: LockerInfoData;
}
+
+export type LinkKeyMaterial =
+ | { type: "direct"; fileKey: string }
+ | { type: "secret"; passphrase: string };