bambuddy/backend/tests/unit/test_orca_cloud_refresh.py
maziggy 455a9e4ba7 fix(backup): collect cloud profiles from every connected account (#2717)
Enabling Cloud Profiles for a Git backup produced nothing, and said it had
worked. Two independent faults, either one sufficient.

The collector looked for a "setting" list. The Bambu Cloud listing endpoint
is keyed by preset type instead, each key holding private and public arrays,
so the loop body never executed once — and the entries carry no type of
their own either, which routes/cloud.py already knew: it takes the type from
the outer key and maps Bambu's "print" to process. Two bugs on one line.

It also asked build_authenticated_cloud for the credential store used when
authentication is disabled. With auth on, tokens live on User rows, so the
collector returned at "Cloud not authenticated" before ever reaching the bad
key. Every multi-user install was collecting from zero accounts.

Neither failure surfaced. backup_metadata.json recorded the configured flag
rather than the outcome, so it claimed cloud_profiles: true on runs that
wrote nothing, and the log read "Collected cloud profiles: 0 filament, 0
printer, 0 process" at INFO — which is exactly what a successful backup of
an empty account looks like.

Cloud profiles now come from every connected account across both clouds. The
toggle predates Orca Cloud entirely, and Orca has the same three preset
types, so both are collected and grouped the same way:

    cloud_profiles/bambu/user-3/{filament,printer,process}.json
    cloud_profiles/orca/user-3/{filament,printer,process}.json

Accounts are keyed by Bambuddy user id, "global" when auth is off. Never by
email: a backup repository can be public, and the Bambu listing's user_id is
dropped for the same reason. Both credential stores are read on every run,
because a Settings row survives someone enabling auth later and dropping it
would silently stop backing that account up.

Bambu costs one get_setting_detail per private preset. The listing is
metadata only, and without base_id and setting the backup is a list of names
that create_setting cannot rebuild from. Public presets are skipped — Bambu's
bundled catalogue is the same hundreds of entries for everyone, always
re-downloadable, not recreatable under your account, and would rewrite the
repository on every run. Orca needs no second call; its sync-pull carries
each profile's content inline. Where the Orca route drops a profile whose
content.type it cannot map, the backup writes it to other.json instead:
silently omitting a profile because Orca added a type is the same class of
bug as this one.

Failures are contained per account and per preset, and counted rather than
swallowed. A partial backup that looks complete is how this stayed invisible.

The metadata now reports what was collected, per cloud and per account, and a
run that collects nothing while the category is enabled warns with the reason
instead of an INFO line that reads like success.

The checkbox gated on the viewer's own Bambu sign-in, which is not the same
question as whether there is anything to back up — with auth enabled the
accounts belong to individual users, and an administrator who never signed
in personally saw the category disabled with plenty in scope. It now gates
on the total across both clouds and shows the counts. That comes from its
own endpoint rather than a field on /config, since /config answers null
until the first save and would disable the toggle during the very setup it
belongs to. Counts only, never identities.

One deliberate restraint. _build_authenticated_service clears stored
credentials when a refresh is rejected, which is right for a route — the
user is on the page and can pair again — and wrong for a scheduled job.
Orca reports every rejection with one composite reason ("unknown, expired,
revoked, or already used"), so a genuine revocation cannot be told apart
from a lost token-rotation race, and acting destructively on a signal that
cannot be disambiguated is the #2562 mistake in a different cloud. It also
gains nothing: the Profiles route hits the same failure and clears it then,
with the user present. Background callers now pass clear_on_auth_failure=
False and skip the account. A successful refresh is still persisted either
way — by that point the old token is consumed, so dropping the new pair
would break a working pairing for real.

Restore is not part of this. Nothing reads cloud_profiles/* yet; the format
carries base_id/setting for Bambu and content for Orca so that it can.
2026-07-31 16:59:33 +02:00

125 lines
5.4 KiB
Python

"""What a rejected Orca Cloud refresh is allowed to do to stored credentials.
The refresh token is single-use and rotating, and Orca reports every rejection
with one composite reason (``unknown, expired, revoked, or already used``), so
Bambuddy cannot tell a genuine revocation from a lost rotation race. Routes may
still clear on that signal — a person is looking at the page and can pair again
— but a background job must not, or an unattended run can destroy a working
pairing (#2717).
"""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import HTTPException
from sqlalchemy import select
from backend.app.api.routes.orca_cloud import _SETTINGS_KEYS, _build_authenticated_service
from backend.app.models.settings import Settings
from backend.app.services.orca_cloud import OrcaCloudAuthError, OrcaCloudError
async def _store_global_credentials(db):
"""An auth-disabled install's Orca credentials, expired so the helper
refreshes rather than returning straight away."""
db.add_all(
[
Settings(key=_SETTINGS_KEYS["token"], value="oc_ext_old"),
Settings(key=_SETTINGS_KEYS["refresh_token"], value="oc_ext_rt_old"),
Settings(key=_SETTINGS_KEYS["expires_at"], value="2000-01-01T00:00:00+00:00"),
Settings(key=_SETTINGS_KEYS["email"], value="a@b.c"),
]
)
await db.commit()
async def _stored_keys(db) -> set[str]:
result = await db.execute(select(Settings).where(Settings.key.in_(list(_SETTINGS_KEYS.values()))))
return {s.key for s in result.scalars().all()}
def _expired_service(refresh_side_effect=None):
"""A service that reports its access token as expired, so the helper takes
the refresh branch."""
svc = MagicMock()
svc.is_authenticated = False
svc.refresh_token = "oc_ext_rt_old"
svc.set_tokens = MagicMock()
svc.refresh = AsyncMock(side_effect=refresh_side_effect)
svc.access_token = "oc_ext_new"
svc.token_expiry = None
return svc
class TestRejectedRefresh:
@pytest.mark.asyncio
async def test_routes_clear_the_dead_pairing_by_default(self, db_session):
"""Unchanged behaviour for interactive callers: the page flips to
disconnected while the user is there to pair again."""
await _store_global_credentials(db_session)
svc = _expired_service(OrcaCloudAuthError("grant already used"))
with (
patch("backend.app.api.routes.orca_cloud.OrcaCloudService", return_value=svc),
pytest.raises(HTTPException) as exc,
):
await _build_authenticated_service(db_session, None)
assert exc.value.status_code == 401
assert await _stored_keys(db_session) == set()
@pytest.mark.asyncio
async def test_background_callers_leave_the_credentials_alone(self, db_session):
"""The whole point of the flag. A scheduled backup that guesses wrong
here destroys a pairing nobody asked it to touch, and the user finds
out when their profiles stop being backed up."""
await _store_global_credentials(db_session)
svc = _expired_service(OrcaCloudAuthError("grant already used"))
with (
patch("backend.app.api.routes.orca_cloud.OrcaCloudService", return_value=svc),
pytest.raises(HTTPException) as exc,
):
await _build_authenticated_service(db_session, None, clear_on_auth_failure=False)
# Still reported as a hard auth failure — the caller has to skip the
# account — but nothing was destroyed on the way out.
assert exc.value.status_code == 401
assert _SETTINGS_KEYS["token"] in await _stored_keys(db_session)
assert _SETTINGS_KEYS["refresh_token"] in await _stored_keys(db_session)
@pytest.mark.asyncio
async def test_an_unreachable_orca_never_clears_either_way(self, db_session):
"""A transport failure says nothing about the credentials' validity."""
await _store_global_credentials(db_session)
svc = _expired_service(OrcaCloudError("connection reset"))
with (
patch("backend.app.api.routes.orca_cloud.OrcaCloudService", return_value=svc),
pytest.raises(HTTPException) as exc,
):
await _build_authenticated_service(db_session, None)
assert exc.value.status_code == 502
assert _SETTINGS_KEYS["token"] in await _stored_keys(db_session)
class TestSuccessfulRefresh:
@pytest.mark.asyncio
async def test_the_rotated_pair_is_persisted_even_for_background_callers(self, db_session):
"""Not optional: by the time the refresh succeeds the old token is
consumed, so failing to store the new pair would break a live pairing
for real. The flag suppresses destruction, never persistence.
"""
await _store_global_credentials(db_session)
svc = _expired_service()
svc.refresh_token = "oc_ext_rt_new"
with patch("backend.app.api.routes.orca_cloud.OrcaCloudService", return_value=svc):
returned = await _build_authenticated_service(db_session, None, clear_on_auth_failure=False)
assert returned is svc
result = await db_session.execute(select(Settings).where(Settings.key == _SETTINGS_KEYS["token"]))
assert result.scalar_one().value == "oc_ext_new"
result = await db_session.execute(select(Settings).where(Settings.key == _SETTINGS_KEYS["refresh_token"]))
assert result.scalar_one().value == "oc_ext_rt_new"