Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

fix: keep asset groups within their workspace (#1093)

Albert Dolkuna86d1dbe42bd
diff --git a/backend/app/services/asset_group_service.py b/backend/app/services/asset_group_service.py
index 0b5a52dc..fd2cad0b 100644
--- a/backend/app/services/asset_group_service.py
+++ b/backend/app/services/asset_group_service.py
@@ -2,6 +2,7 @@ import uuid
from decimal import Decimal
from typing import Optional
+from fastapi import HTTPException, status
from sqlalchemy import func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
@@ -16,6 +17,17 @@ from app.schemas.asset_group import AssetGroupCreate, AssetGroupRead, AssetGroup
from app.services.fx_rate_service import convert
+async def ensure_group_in_workspace(
+ session: AsyncSession, group_id: Optional[uuid.UUID], workspace_id: uuid.UUID
+) -> None:
+ """Reject a wallet outside the workspace, while allowing ungrouped assets."""
+ if group_id is None:
+ return
+ group = await session.get(AssetGroup, group_id)
+ if group is None or group.workspace_id != workspace_id:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")
+
+
async def _latest_value_amount(session: AsyncSession, asset_id: uuid.UUID) -> Optional[Decimal]:
"""Return the most recent AssetValue.amount for an asset, or None."""
row = await session.execute(
@@ -71,6 +83,7 @@ async def _rollup(
assets = await session.execute(
select(Asset).where(
Asset.group_id == group.id,
+ Asset.workspace_id == group.workspace_id,
Asset.is_archived == False,
Asset.sell_date.is_(None),
)
diff --git a/backend/app/services/asset_import_service.py b/backend/app/services/asset_import_service.py
index 1ba30640..4f56baab 100644
--- a/backend/app/services/asset_import_service.py
+++ b/backend/app/services/asset_import_service.py
@@ -46,6 +46,7 @@ from app.schemas.asset_import import (
AssetOrderImport,
)
from app.services import asset_transaction_service
+from app.services.asset_group_service import ensure_group_in_workspace
from app.services.import_service import (
DATE_FORMAT_MAP,
_sniff_csv_dialect,
@@ -470,6 +471,7 @@ async def import_orders(
without writing anything, so the preview can promise what the import will
do instead of guessing.
"""
+ await ensure_group_in_workspace(session, group_id, workspace_id)
ordered = sorted(orders, key=lambda o: (o.date, o.row))
tickers = [o.ticker for o in ordered]
diff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.py
index 575c16dc..3aa8adf6 100644
--- a/backend/app/services/asset_service.py
+++ b/backend/app/services/asset_service.py
@@ -21,6 +21,7 @@ from app.providers.market_price import (
get_market_price_provider,
)
from app.schemas.asset import AssetCreate, AssetUpdate, AssetValueCreate, AssetRead, AssetValueRead
+from app.services.asset_group_service import ensure_group_in_workspace
from app.services.fx_rate_service import convert, stamp_primary_amount
logger = logging.getLogger(__name__)
@@ -426,6 +427,7 @@ async def create_asset(
market_provider: Optional[MarketPriceProvider] = None,
) -> AssetRead:
"""Create an asset, optionally with an initial value."""
+ await ensure_group_in_workspace(session, data.group_id, workspace_id)
# Market-priced path: fetch a live quote first so we can derive currency
# and the initial value from the ticker. Validate up-front rather than
# half-creating an asset and failing on a 5xx from Yahoo.
@@ -648,6 +650,8 @@ async def update_asset(
return None
update_data = data.model_dump(exclude_unset=True)
+ if "group_id" in update_data:
+ await ensure_group_in_workspace(session, update_data["group_id"], workspace_id)
# Prevent changing valuation_method on existing assets
update_data.pop("valuation_method", None)
diff --git a/backend/app/services/asset_transaction_service.py b/backend/app/services/asset_transaction_service.py
index ae2239f0..5cf3ed2a 100644
--- a/backend/app/services/asset_transaction_service.py
+++ b/backend/app/services/asset_transaction_service.py
@@ -29,6 +29,7 @@ from app.schemas.asset import (
AssetTransactionUpdate,
)
from app.services import asset_service
+from app.services.asset_group_service import ensure_group_in_workspace
logger = logging.getLogger(__name__)
@@ -355,6 +356,7 @@ async def buy_into_holding(
"""Record a buy, consolidating onto the existing ticker holding in the
chosen wallet (`group_id`) or creating a new market-priced holding."""
_validate("buy", data.quantity, data.price)
+ await ensure_group_in_workspace(session, data.group_id, workspace_id)
ticker = data.ticker.upper()
result = await session.execute(
diff --git a/backend/tests/test_asset_group_workspace_scope.py b/backend/tests/test_asset_group_workspace_scope.py
new file mode 100644
index 00000000..37b7cfec
--- /dev/null
+++ b/backend/tests/test_asset_group_workspace_scope.py
@@ -0,0 +1,226 @@
+"""A wallet belongs to a workspace, and so does everything it totals.
+
+`Asset.group_id` is a plain foreign key. Nothing checked that the id a
+request supplied named a wallet in the request's own workspace, and the
+wallet rollup selected assets on `group_id` alone. An asset created,
+bought or imported against another workspace's wallet id was therefore
+counted in that wallet's item count and value, so one workspace's
+holdings surfaced inside another workspace's totals.
+
+The rule these tests pin: a `group_id` accepted from a request must name
+a wallet in the request's own workspace, and the rollup counts only
+assets belonging to the wallet's workspace whatever the column says.
+"""
+import uuid
+from datetime import date
+from decimal import Decimal
+
+import pytest
+from fastapi import HTTPException
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.asset import Asset
+from app.models.asset_group import AssetGroup
+from app.models.user import User
+from app.models.workspace import Workspace, WorkspaceMember
+from app.providers.market_price import (
+ MarketPriceProvider,
+ MarketSymbolMatch,
+ MarketSymbolQuote,
+)
+from app.schemas.asset import AssetBuyCreate, AssetCreate, AssetUpdate
+from app.services import asset_import_service, asset_service, asset_transaction_service
+from app.services.asset_group_service import get_group
+
+
+class FakeProvider(MarketPriceProvider):
+ """Quotes every ticker, so a rejection is the guard's doing rather than a
+ lookup that failed on the way to the write."""
+
+ async def search(self, query: str, limit: int = 20) -> list[MarketSymbolMatch]:
+ return []
+
+ async def get_quote(self, symbol: str) -> MarketSymbolQuote:
+ return MarketSymbolQuote(
+ symbol=symbol.upper(), name=f"{symbol.upper()} Inc", price=100.0,
+ currency="BRL", exchange="XNAS", quote_type="EQUITY", logo_url=None,
+ )
+
+
+async def _second_workspace(session: AsyncSession, user_id: uuid.UUID) -> Workspace:
+ """A second workspace the same user belongs to — a shared household one,
+ or one they were added to. Its wallets are off-limits from the first."""
+ ws = Workspace(
+ id=uuid.uuid4(), name="Shared", kind="personal",
+ created_by_user_id=user_id, default_currency="BRL",
+ )
+ session.add(ws)
+ await session.flush()
+ session.add(
+ WorkspaceMember(id=uuid.uuid4(), workspace_id=ws.id, user_id=user_id, role="owner")
+ )
+ await session.commit()
+ await session.refresh(ws)
+ return ws
+
+
+async def _wallet(
+ session: AsyncSession, user_id: uuid.UUID, workspace_id: uuid.UUID, name: str
+) -> AssetGroup:
+ group = AssetGroup(
+ id=uuid.uuid4(), user_id=user_id, workspace_id=workspace_id, name=name,
+ )
+ session.add(group)
+ await session.commit()
+ return group
+
+
+# ---------------------------------------------------------------------------
+# the write paths
+# ---------------------------------------------------------------------------
+
+
+async def test_create_rejects_a_wallet_from_another_workspace(
+ session: AsyncSession, test_user: User, test_workspace: Workspace
+):
+ other = await _second_workspace(session, test_user.id)
+ theirs = await _wallet(session, test_user.id, other.id, "Their Wallet")
+
+ with pytest.raises(HTTPException) as exc:
+ await asset_service.create_asset(
+ session, test_workspace.id, test_user.id,
+ AssetCreate(name="Apartment", type="real_estate", currency="BRL",
+ group_id=theirs.id),
+ )
+
+ assert exc.value.status_code == 404
+
+
+async def test_update_rejects_a_move_into_another_workspace(
+ session: AsyncSession, test_user: User, test_workspace: Workspace
+):
+ other = await _second_workspace(session, test_user.id)
+ theirs = await _wallet(session, test_user.id, other.id, "Their Wallet")
+ asset = await asset_service.create_asset(
+ session, test_workspace.id, test_user.id,
+ AssetCreate(name="Apartment", type="real_estate", currency="BRL"),
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await asset_service.update_asset(
+ session, asset.id, test_workspace.id, test_user.id,
+ AssetUpdate(group_id=theirs.id),
+ )
+
+ assert exc.value.status_code == 404
+
+
+async def test_update_still_clears_the_wallet(
+ session: AsyncSession, test_user: User, test_workspace: Workspace
+):
+ """Ungrouping is an explicit null, which the guard must let through."""
+ mine = await _wallet(session, test_user.id, test_workspace.id, "My Wallet")
+ asset = await asset_service.create_asset(
+ session, test_workspace.id, test_user.id,
+ AssetCreate(name="Apartment", type="real_estate", currency="BRL", group_id=mine.id),
+ )
+
+ updated = await asset_service.update_asset(
+ session, asset.id, test_workspace.id, test_user.id, AssetUpdate(group_id=None),
+ )
+
+ assert updated is not None
+ assert updated.group_id is None
+
+
+async def test_buy_rejects_a_wallet_from_another_workspace(
+ session: AsyncSession, test_user: User, test_workspace: Workspace
+):
+ other = await _second_workspace(session, test_user.id)
+ theirs = await _wallet(session, test_user.id, other.id, "Their Wallet")
+
+ with pytest.raises(HTTPException) as exc:
+ await asset_transaction_service.buy_into_holding(
+ session, test_workspace.id, test_user.id,
+ AssetBuyCreate(ticker="AAPL", quantity=Decimal("10"), price=Decimal("100"),
+ date=date(2026, 1, 15), group_id=theirs.id),
+ market_provider=FakeProvider(),
+ )
+
+ assert exc.value.status_code == 404
+
+
+async def test_import_rejects_a_wallet_from_another_workspace(
+ session: AsyncSession, test_user: User, test_workspace: Workspace
+):
+ other = await _second_workspace(session, test_user.id)
+ theirs = await _wallet(session, test_user.id, other.id, "Their Wallet")
+ orders, _, _ = asset_import_service.parse_orders_csv(
+ b"ticker,date,quantity,price\nAAPL,2026-01-15,10,100.00"
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await asset_import_service.import_orders(
+ session, test_workspace.id, test_user.id, orders,
+ group_id=theirs.id, market_provider=FakeProvider(),
+ )
+
+ assert exc.value.status_code == 404
+
+
+async def test_import_preview_rejects_it_too(
+ session: AsyncSession, test_user: User, test_workspace: Workspace
+):
+ """The preview runs the same function with `dry_run`, and is what the UI
+ calls first — it has to refuse there rather than promise an import that
+ the commit will reject."""
+ other = await _second_workspace(session, test_user.id)
+ theirs = await _wallet(session, test_user.id, other.id, "Their Wallet")
+ orders, _, _ = asset_import_service.parse_orders_csv(
+ b"ticker,date,quantity,price\nAAPL,2026-01-15,10,100.00"
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await asset_import_service.import_orders(
+ session, test_workspace.id, test_user.id, orders,
+ group_id=theirs.id, dry_run=True, market_provider=FakeProvider(),
+ )
+
+ assert exc.value.status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# the read path
+# ---------------------------------------------------------------------------
+
+
+async def test_rollup_ignores_an_asset_from_another_workspace(
+ session: AsyncSession, test_user: User, test_workspace: Workspace
+):
+ """The backstop, for rows already written before the guard existed."""
+ other = await _second_workspace(session, test_user.id)
+ mine = await _wallet(session, test_user.id, test_workspace.id, "My Wallet")
+
+ session.add_all([
+ Asset(id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,
+ name="Mine", type="investment", currency="BRL",
+ purchase_price=Decimal("100"), group_id=mine.id),
+ Asset(id=uuid.uuid4(), user_id=test_user.id, workspace_id=other.id,
+ name="Theirs", type="investment", currency="BRL",
+ purchase_price=Decimal("900"), group_id=mine.id),
+ ])
+ await session.commit()
+
+ read = await get_group(session, mine.id, test_workspace.id, test_user.id)
+
+ assert read is not None
+ assert read.asset_count == 1
+ assert read.current_value == 100.0
+ assert read.current_value_primary == 100.0