Skip to content

armgit / ente

Public Imported from GitHub
0

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

Reuse social profile links

Anand Baburajan570ea3bd58ee
diff --git a/rust/wall/src/client.rs b/rust/wall/src/client.rs
index 3a38184e92..eaa097e254 100644
--- a/rust/wall/src/client.rs
+++ b/rust/wall/src/client.rs
@@ -1,10 +1,10 @@
use std::collections::BTreeMap;
use crate::crypto::{
- decode_b64, decrypt_entity_key, decrypt_secretbox_packed, 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,
+ 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, pack_payload, unpack_payload,
+ wall_link_access_key_material,
};
use crate::error::{Result, WallError};
use crate::models::{
@@ -920,7 +920,7 @@ impl AccountWallCtx {
.ok_or_else(|| {
WallError::InvalidInput(format!("wall {wall_id} is not owned by the account"))
})?;
- let access_key = generate_wall_link_access_key();
+ let access_key = derive_wall_link_access_key(wall_id, &access.wall_key)?;
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)?;
diff --git a/rust/wall/src/crypto.rs b/rust/wall/src/crypto.rs
index 99e8492ee2..687c66ce87 100644
--- a/rust/wall/src/crypto.rs
+++ b/rust/wall/src/crypto.rs
@@ -13,12 +13,17 @@ pub fn generate_key() -> Vec<u8> {
keys::generate_key_secure().into_vec()
}
-pub fn generate_wall_link_access_key() -> String {
+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);
+ let mut counter = 0u8;
while out.len() < WALL_LINK_ACCESS_KEY_LEN {
- for value in generate_key() {
+ let mut hash_input = Vec::with_capacity(input.len() + 1);
+ hash_input.extend_from_slice(input);
+ hash_input.push(counter);
+ let digest = hash::hash(&hash_input, Some(64), None)?;
+ for value in digest {
if usize::from(value) >= max_unbiased_value {
continue;
}
@@ -30,9 +35,26 @@ pub fn generate_wall_link_access_key() -> String {
break;
}
}
+ counter = counter.wrapping_add(1);
}
- out
+ 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>> {
@@ -172,9 +194,12 @@ mod tests {
}
#[test]
- fn wall_link_access_key_is_short_base62() {
- let access_key = generate_wall_link_access_key();
+ 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();
assert_eq!(access_key.len(), 12);
+ assert_eq!(access_key, repeated);
assert!(
access_key
.bytes()
@@ -185,6 +210,13 @@ mod tests {
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/server/migrations/123_wall_single_active_link.down.sql b/server/migrations/123_wall_single_active_link.down.sql
new file mode 100644
index 0000000000..b382ffadb7
--- /dev/null
+++ b/server/migrations/123_wall_single_active_link.down.sql
@@ -0,0 +1,8 @@
+ALTER TABLE wall_links
+ DROP CONSTRAINT IF EXISTS wall_links_pkey;
+
+ALTER TABLE wall_links
+ ADD PRIMARY KEY (wall_id, auth_key_hash);
+
+CREATE INDEX IF NOT EXISTS idx_wall_links_wall_updated
+ ON wall_links (wall_id, updated_at DESC);
diff --git a/server/migrations/123_wall_single_active_link.up.sql b/server/migrations/123_wall_single_active_link.up.sql
new file mode 100644
index 0000000000..d91f7f0f6a
--- /dev/null
+++ b/server/migrations/123_wall_single_active_link.up.sql
@@ -0,0 +1,17 @@
+DELETE FROM wall_link_sessions;
+
+DELETE FROM wall_links existing
+USING wall_links newer
+WHERE existing.wall_id = newer.wall_id
+ AND (
+ existing.updated_at < newer.updated_at
+ OR (existing.updated_at = newer.updated_at AND existing.auth_key_hash < newer.auth_key_hash)
+ );
+
+DROP INDEX IF EXISTS idx_wall_links_wall_updated;
+
+ALTER TABLE wall_links
+ DROP CONSTRAINT IF EXISTS wall_links_pkey;
+
+ALTER TABLE wall_links
+ ADD PRIMARY KEY (wall_id);
diff --git a/server/wall/repo/links.go b/server/wall/repo/links.go
index c27d6ca28f..73945c2797 100644
--- a/server/wall/repo/links.go
+++ b/server/wall/repo/links.go
@@ -1,8 +1,10 @@
package repo
import (
+ "bytes"
"context"
"database/sql"
+ "errors"
"github.com/ente-io/stacktrace"
)
@@ -27,13 +29,51 @@ func (r *LinksRepository) UpsertLink(ctx context.Context, wallID string, authKey
if currentVersion != keyVersion {
return nil, sql.ErrNoRows
}
+
+ var existingAuthKeyHash []byte
+ var existingKeyVersion int
+ var existingActive bool
+ err = tx.QueryRowContext(ctx, `
+ SELECT auth_key_hash, key_version, active
+ FROM wall_links
+ WHERE wall_id = $1
+ FOR UPDATE
+ `, wallID).Scan(&existingAuthKeyHash, &existingKeyVersion, &existingActive)
+ if err == nil && bytes.Equal(existingAuthKeyHash, authKeyHash) && existingKeyVersion == keyVersion && existingActive {
+ 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
+ FROM wall_links l
+ WHERE l.wall_id = $1
+ `, wallID, wallSlug, ownerID))
+ }
+ if err != nil && !errors.Is(err, sql.ErrNoRows) {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if err == nil {
+ 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, `
+ 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 {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return link, nil
+ }
+
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)
- ON CONFLICT (wall_id, auth_key_hash) DO UPDATE
- SET key_version = EXCLUDED.key_version,
- encrypted_wall_key = EXCLUDED.encrypted_wall_key,
- active = 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))
if err != nil {
@@ -51,8 +91,6 @@ func (r *LinksRepository) GetLink(ctx context.Context, wallID string) (*WallLink
FROM wall_links l
JOIN walls w ON w.wall_id = l.wall_id
WHERE l.wall_id = $1 AND l.active = TRUE
- ORDER BY l.updated_at DESC
- LIMIT 1
`, wallID))
}
diff --git a/server/wall/repo/module_test.go b/server/wall/repo/module_test.go
index e0c79ccb0b..386e257c16 100644
--- a/server/wall/repo/module_test.go
+++ b/server/wall/repo/module_test.go
@@ -251,18 +251,13 @@ func TestWallModuleLifecycle(t *testing.T) {
newLink, err := module.Links.UpsertLink(ctx, aliceWall.WallID, []byte("new-hash"), rotatedWall.CurrentVersion, "new-wall-link-key")
require.NoError(t, err)
- session, err = module.Links.GetSession(ctx, []byte("token-hash"))
- require.NoError(t, err)
- require.Equal(t, link.AuthKeyHash, session.AuthKeyHash)
+ _, err = module.Links.GetSession(ctx, []byte("token-hash"))
+ require.Error(t, err)
- err = module.Links.CreateSession(ctx, []byte("new-token-hash"), newLink.WallID, newLink.AuthKeyHash, newLink.KeyVersion, timeutil.NMinFromNow(30))
+ err = module.Links.CreateSession(ctx, []byte("token-hash"), newLink.WallID, newLink.AuthKeyHash, newLink.KeyVersion, timeutil.NMinFromNow(30))
require.NoError(t, err)
err = module.Links.DeleteLink(ctx, aliceWall.WallID)
require.NoError(t, err)
- _, err = module.Links.GetSession(ctx, []byte("token-hash"))
- require.Error(t, err)
- _, err = module.Links.GetSession(ctx, []byte("new-token-hash"))
- require.Error(t, err)
lookup, err := module.Walls.GetWallBySlug(ctx, "alice")
require.NoError(t, err)
@@ -574,7 +569,7 @@ func TestGetVersionReturnsHistoricalProfile(t *testing.T) {
require.Equal(t, "alice-profile-v2", v2.EncryptedProfile)
}
-func TestCreateSessionAcceptsMultipleActiveLinkAuthHashes(t *testing.T) {
+func TestUpsertLinkReusesExistingLinkWithoutRevokingSessions(t *testing.T) {
ctx := context.Background()
module := newWallTestModule(t)
@@ -582,21 +577,40 @@ func TestCreateSessionAcceptsMultipleActiveLinkAuthHashes(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")
+ link, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("same-hash"), wall.CurrentVersion, "wall-link-key")
require.NoError(t, err)
- newLink, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("new-hash"), wall.CurrentVersion, "new-wall-link-key")
+ 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")
+ require.NoError(t, err)
+ require.Equal(t, link.AuthKeyHash, reused.AuthKeyHash)
+ require.Equal(t, link.EncryptedWallKey, reused.EncryptedWallKey)
+
+ session, err := module.Links.GetSession(ctx, []byte("token-hash"))
require.NoError(t, err)
+ require.Equal(t, link.AuthKeyHash, session.AuthKeyHash)
+}
+
+func TestCreateSessionRejectsStaleLinkAuthHash(t *testing.T) {
+ ctx := context.Background()
+ module := newWallTestModule(t)
- err = module.Links.CreateSession(ctx, []byte("old-token"), oldLink.WallID, oldLink.AuthKeyHash, oldLink.KeyVersion, timeutil.NMinFromNow(30))
+ 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)
- session, err := module.Links.GetSession(ctx, []byte("old-token"))
+
+ oldLink, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("old-hash"), wall.CurrentVersion, "old-wall-link-key")
+ require.NoError(t, err)
+ newLink, err := module.Links.UpsertLink(ctx, wall.WallID, []byte("new-hash"), wall.CurrentVersion, "new-wall-link-key")
require.NoError(t, err)
- require.Equal(t, oldLink.KeyVersion, session.KeyVersion)
- require.Equal(t, oldLink.AuthKeyHash, session.AuthKeyHash)
+
+ err = module.Links.CreateSession(ctx, []byte("stale-token"), oldLink.WallID, oldLink.AuthKeyHash, oldLink.KeyVersion, timeutil.NMinFromNow(30))
+ require.Error(t, err)
err = module.Links.CreateSession(ctx, []byte("fresh-token"), newLink.WallID, newLink.AuthKeyHash, newLink.KeyVersion, timeutil.NMinFromNow(30))
require.NoError(t, err)
- session, err = module.Links.GetSession(ctx, []byte("fresh-token"))
+ session, err := module.Links.GetSession(ctx, []byte("fresh-token"))
require.NoError(t, err)
require.Equal(t, newLink.KeyVersion, session.KeyVersion)
require.Equal(t, newLink.AuthKeyHash, session.AuthKeyHash)
@@ -618,11 +632,10 @@ func TestGetSessionRejectsStaleLinkMetadata(t *testing.T) {
_, err = module.Links.DB.Exec(`
INSERT INTO wall_link_sessions (token_hash, wall_id, owner_id, auth_key_hash, key_version, expires_at)
VALUES ($1, $2, $3, $4, $5, $6)
- `, []byte("old-auth-token"), oldLink.WallID, oldLink.OwnerID, oldLink.AuthKeyHash, oldLink.KeyVersion, timeutil.NMinFromNow(30))
- require.NoError(t, err)
- session, err := module.Links.GetSession(ctx, []byte("old-auth-token"))
+ `, []byte("stale-auth-token"), oldLink.WallID, oldLink.OwnerID, oldLink.AuthKeyHash, oldLink.KeyVersion, timeutil.NMinFromNow(30))
require.NoError(t, err)
- require.Equal(t, oldLink.AuthKeyHash, session.AuthKeyHash)
+ _, err = module.Links.GetSession(ctx, []byte("stale-auth-token"))
+ require.Error(t, err)
rotatedWall, err := module.Walls.RotateKey(ctx, aliceID, wall.WallID, "alice-wall-key-v2", "wrapped-prev-key", nil)
require.NoError(t, err)
diff --git a/web/apps/social/src/services/socialWall.ts b/web/apps/social/src/services/socialWall.ts
index 38d437a4e4..f42eb9aa6f 100644
--- a/web/apps/social/src/services/socialWall.ts
+++ b/web/apps/social/src/services/socialWall.ts
@@ -1,5 +1,4 @@
import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
-import { getKV, removeKV, setKV } from "ente-base/kv";
import { apiOrigin } from "ente-base/origins";
import type { WallAccountCtxHandle, WallLinkCtxHandle } from "ente-wasm";
import { loadEnteWasm } from "ente-wasm/load";
@@ -94,21 +93,6 @@ interface WallPostLikerPage {
nextCursor?: string;
}
-interface WallLinkStatus {
- active?: boolean;
- keyVersion?: number;
- wallId?: string;
- wallSlug?: string;
-}
-
-interface StoredSocialWallLink {
- accessKey: string;
- keyVersion: number;
- wallId: string;
- wallSlug: string;
- wallUsername: string;
-}
-
export interface SocialWallPost {
avatarUrl?: string | null;
caption?: string;
@@ -157,38 +141,6 @@ export interface SocialLiker {
name: string;
}
-const socialWallLinkKey = (wallId: string) =>
- `social:wall-link:${encodeURIComponent(wallId)}`;
-
-const isStoredSocialWallLink = (
- value: unknown,
- wallId: string,
-): value is StoredSocialWallLink => {
- if (!value || typeof value != "object") return false;
- const link = value as Partial<StoredSocialWallLink>;
- return (
- link.wallId == wallId &&
- typeof link.accessKey == "string" &&
- /^[0-9A-Za-z]{12}$/.test(link.accessKey) &&
- typeof link.keyVersion == "number" &&
- typeof link.wallSlug == "string" &&
- typeof link.wallUsername == "string"
- );
-};
-
-const socialWallLinkFromStored = (
- stored: StoredSocialWallLink,
-): SocialWallLink => ({
- accessKey: stored.accessKey,
- url: socialInviteURL({
- accessKey: stored.accessKey,
- wallUsername: stored.wallUsername || stored.wallSlug,
- }),
- wallId: stored.wallId,
- wallSlug: stored.wallSlug,
- wallUsername: stored.wallUsername || stored.wallSlug,
-});
-
const parseWallProfilePayload = (profile: string): WallProfilePayload => {
if (!profile.trim()) return {};
try {
@@ -366,19 +318,6 @@ export const createCurrentProfileLink = async (
): Promise<SocialWallLink> => {
const ctx = await ensureCurrentWallContext();
try {
- const status = (await ctx.get_wall_link_status(
- wallId,
- )) as WallLinkStatus;
- const stored = await getKV(socialWallLinkKey(wallId));
- if (
- status.active &&
- isStoredSocialWallLink(stored, wallId) &&
- stored.keyVersion == status.keyVersion
- ) {
- return socialWallLinkFromStored(stored);
- }
- if (!status.active) await removeKV(socialWallLinkKey(wallId));
-
const created = (await ctx.create_wall_link(wallId)) as {
accessKey: string;
keyVersion: number;
@@ -386,20 +325,16 @@ export const createCurrentProfileLink = async (
wallSlug: string;
wallUsername: string;
};
- const storedLink: StoredSocialWallLink = {
+ const invite: PendingSocialInvite = {
accessKey: created.accessKey,
- keyVersion: created.keyVersion,
- wallId: created.wallId,
- wallSlug: created.wallSlug,
wallUsername: created.wallUsername || created.wallSlug,
};
- await setKV(socialWallLinkKey(wallId), storedLink);
return {
accessKey: created.accessKey,
- url: socialInviteURL(storedLink),
+ url: socialInviteURL(invite),
wallId: created.wallId,
wallSlug: created.wallSlug,
- wallUsername: storedLink.wallUsername,
+ wallUsername: invite.wallUsername,
};
} finally {
ctx.free();