Skip to content

Delete a removed tag's keys, and offer to erase its history - #315

Open
lazzurs wants to merge 8 commits into
parawanderer:mainfrom
lazzurs:fix/s04-erase-removed-tag-data
Open

lazzurs wants to merge 8 commits into
parawanderer:mainfrom
lazzurs:fix/s04-erase-removed-tag-data

Conversation

@lazzurs

@lazzurs lazzurs commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes the deletion half of audit finding S-04: accessory keys and location history were never purged. "Remove device" only set is_removed, so the private key and shared secrets of every tag ever removed stayed in the Room database (content, accessory_json, alignment_plist) along with its whole location history. Nothing in the app ever deleted either, short of uninstalling. Somebody who removes a tag they sold or handed back reasonably believes its keys are gone.

Why Remove was a soft delete, and what's kept

Removal only applies to tags imported from a file (account tags already explain they have to be removed in Find My). The soft delete wasn't for sync. It was deliberate, so that a tag removed by mistake comes back with its history when the same export is imported again (MyDevicesListActivity.removeDevice says so). That's worth keeping, so this splits it:

  • Remove (default, unticked): the row stays hidden exactly as before, and its history stays with it, but the three key columns are cleared. Re-importing restores them: refreshFromImport's COALESCEs fill a null in, and a test pins that the history and all three keys come back.
  • Remove with "Also delete its location history" ticked: the row is deleted. ON DELETE CASCADE takes the location history, the fetched-day records, the last Bluetooth sighting and the user's name/emoji with it. The naming record goes too, and so does the import row (which records the exporter's Apple ID) once no tag refers to it, hidden ones included.

Multi-select uses removeBeacons, one transaction and one compaction for the whole selection. A fetch or Bluetooth sighting that was already running when a tag was removed can't write its accessory JSON back (updateAccessoryJson skips removed rows), and reports for a tag that no longer has a row are dropped rather than failing the whole insert.

Both paths then VACUUM and wal_checkpoint(TRUNCATE) (best effort; a busy database is logged, not surfaced), so the deleted bytes don't stay in the file's free pages.

Erasing everything

  • Logout gets an unticked box: "Also erase every tag on this phone, with its keys and location history, and the iCloud link". Unticked, Logout does exactly what it did before. The anisette-change re-login path still never erases.
  • Settings → App → Erase all data (last row on the page, outside the account block so it stays reachable when the session can't be read): a confirmation, then the same as Logout with the box ticked.
  • What "everything" means is ThisPhonesTagData, in this order: the iCloud link's stored keychain membership, the last map camera position, every Room table (clearAllTables, which checkpoints and vacuums), and then what the background scan holds. That last step deletes the on-disk derived-address cache and restarts NearbyScanService if it's running, since it reads the tags once and would otherwise keep listening for, and alerting on, the erased ones. Then the session is cleared as usual. Kept: settings, and the Apple device identity/serial, since erasing it would make the next sign-in register a second device on the account (AGENTS.md rule 11).
  • The iCloud link: KeychainMembershipRepository says signing out "must not silently strand the peer", and plain Logout still doesn't touch it. Erasing it is explicit here (named in the box and in the confirmation), and the confirmation says the app stays on the Apple account until it's removed on an Apple device. Those are a circle member's private keys, so keeping them after "erase all data" would be the opposite of what was asked. Leaving the circle is S-01's business, and this doesn't change that flow.
  • If the erase fails, the user is not signed out, and a toast says so. The link goes first on purpose (so an account read can't refill the emptied database), so the toast says the tags are still there but the iCloud link may already be gone.
  • MapsActivity no longer re-saves the camera position on its way to the sign-in screen, which would otherwise have written it straight back after an erase.

The eraser goes through AppDependencies.dataEraser, so the Settings tests can press the button without wiping the real on-device database the suite shares (which on somebody's own phone holds their tags).

Schema and strings

  • No schema change. The three key columns were already nullable in schema 10, so there's no migration (AGENTS rule 1 doesn't apply) and no new schema JSON. The build regenerated nothing under app/schemas/.
  • Nine new strings, added to all ten locales with scripts/add_strings.py from a JSON file. --check passes. German and Dutch use the informal register most of those files use.

A trap this ran into: DataStore writes start when called

RxDataStore.updateDataAsync starts writing when called, so erase.andThen(authRepository.clearUser()) signed the user out while the chain was being built, even when the erase failed. aFailedEraseDoesNotSignOut caught it. The sign-out and the eraser's steps now use RxFlows.onlyAfter from #317, which fixed the same shape in MapsActivity, and AGENTS.md rule 23 points at it.

Tests

  • db/repo/RemovingATagForgetsItsKeysTest (in-memory DB): Remove clears the keys and keeps the history hidden; re-import brings both back; ticked Remove deletes the row, history, fetch records, sighting, options, naming record and the now-empty import; a sibling from the same zip is untouched; an import a hidden tag still points at is kept (deleting it would cascade into history Remove promised to keep); eraseEverything empties every table; a fetch or sighting landing after Remove doesn't write the keys back; a fetch landing after a tag was erased still stores the others' reports; an import a naming record still points at is kept; removing several at once does to each what removing one does, and erasing a whole zip at once deletes its import.
  • ui/mydevices/RemovingAFileTagTest: the list's dialog offers the box, unticked, with the right wording; unticked deletes the keys and keeps the history; ticked deletes both; the tag page does the same.
  • ui/settings/ErasingEverythingFromSettingsTest (fake eraser, real sign-out with the session captured and restored): Erase all data asks first and Cancel does nothing; confirming erases then signs out and sends the map to sign-in; a failed erase stays signed in on Settings; Logout's box is unticked and Logout alone erases nothing; ticked, it erases first.
  • db/repo/ThisPhonesTagDataTest (JVM): nothing is erased until subscribed; link, map position, database, then scan; a failure stops there and leaves the scan alone.
  • ErasingEverythingFromSettingsTest also checks the failure message says the iCloud link may be gone.
  • ui/AlsoEraseDialogLayoutTest: the box inflates in an M3 alert-dialog theme in light and dark, unticked, with ≥ 4.5:1 contrast against colorSurfaceContainerHigh.

Verified

  • Local: compile, :app:testDebugUnitTest (578 tests, 0 failures, 1 skipped), add_strings.py --check, check_java_imports.py.
  • PR CI on d9cdf58: Generate APK (Debug) with 909 instrumented tests, 0 failed, plus Static checks.

Not verified

  • I have no KVM here, so the instrumented tests ran only in fork CI (above), not on a physical phone. I haven't looked at the dialogs on a real device, only in the inflate test.
  • Forensic recovery after VACUUM isn't tested. The test checks the rows are gone, not that the bytes are.
  • The scan restart after an erase has only been tested for ordering on the JVM, not on a device.
  • Erasing forgets the iCloud link before emptying the database, which narrows but doesn't close the window for a background account read that is already past the membership lookup.

Follow-ups, not in this PR

  • Encryption at rest (SQLCipher, or wrapping the three key columns with AppCryptographyUtil under a new alias as the audit suggests). That needs a new dependency or a data migration, so it's deliberately left out.
  • A retention setting for LocationReport (the audit's other suggestion).
  • data_extraction_rules.xml <device-transfer> (S-05) is untouched.

Relationship to the other two PRs

One of three PRs from the same audit (S-02 #313, S-03 #314 merged, S-04), tracked in #318. Rebased on main after #314 and #317.

🤖 Generated with Claude Code

@parawanderer parawanderer left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. OwnedBeaconDao.updateAccessoryJson has no is_removed filter, so a fetch in flight when a tag is removed (BeaconRepository.storeFetchResult, and recordAccessorySighting) writes accessory_json back onto the hidden row. Add AND is_removed = 0, with a test that removes a tag and then calls storeFetchResult for it.
  2. ImportDao.deleteIfNothingRefersTo checks only OwnedBeacons, but BeaconNamingRecord.import_id cascades on delete. A tag that moved to the account keeps a naming record on the old import and loses its name when that import is deleted. Also require NOT EXISTS (SELECT 1 FROM BeaconNamingRecord WHERE import_id = :importId).
  3. NearbyScanService loads getAllBeacons() once and holds the key material, so after Erase all data it keeps scanning for, and alerting on, the erased tags until the process dies. Restart it after a successful erase.
  4. memberships.forget() and forgetLastCameraPosition() run before clearAllTables, so when the erase fails the iCloud link is already gone, but the toast says nothing was erased. Reword the toast, or clear Room first.
  5. Optional: multi-select Remove runs removeBeacon once per tag, and each call does a full VACUUM. A batch removeBeacons(List, boolean) that compacts once avoids rewriting the file N times.

Out of scope here: MapsActivity.offerLocalAnisetteUpgradeIfDue has the andThen(clearUser()) shape the PR describes. I'll fix that separately.

Drafted by Claude Code, reviewed by @parawanderer

@parawanderer

Copy link
Copy Markdown
Owner

Sidenote, regarding your proposed follow-ups:

  • Encryption at rest (SQLCipher, or wrapping the three key columns with AppCryptographyUtil under a new alias as the audit suggests). That needs a new dependency or a data migration, so it's deliberately left out.
  • A retention setting for LocationReport (the audit's other suggestion).
  • data_extraction_rules.xml <device-transfer> (S-05) is untouched.

I agree with them if you end up wanting to work on them. All 3 seem reasonable.

Rob Lazzurs and others added 5 commits November 23, 2026 13:44
Removing a tag only set is_removed, so the private key and shared
secrets of every tag ever removed stayed in the database, with its
location history. Nothing on the phone ever deleted either, short of
uninstalling.

Remove now clears content, accessory_json and alignment_plist. The row
stays hidden, as before, so a tag removed by mistake still comes back
with its history when imported again; the keys come back from the
import. A new box in both Remove dialogs, unticked, deletes the row
instead, and with it the location history, fetched-day records, last
Bluetooth sighting, the user's name for it, its naming record, and its
import once nothing refers to it. The database is vacuumed afterwards
so the deleted bytes do not stay in free pages.

Logout gains the same kind of box: erase every tag, key and history
and the iCloud link before signing out. Settings gains "Erase all
data", which does that behind a confirmation. If the erase fails the
user stays signed in and is told. Settings, the Apple device identity
and the iCloud peer on the Apple account are left alone, and the
dialog says the last of those.

No schema change. Nine new strings in all ten locales.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RxDataStore.updateDataAsync starts its write as soon as it is called,
so `.andThen(authRepository.clearUser())` cleared the session while
the chain was being built, before the erase had run, and whether or
not it then failed. The toast said the user was still signed in; they
were not. ErasingEverythingFromSettingsTest.aFailedEraseDoesNotSignOut
caught it on the emulator.

clearUser is now deferred until the erase completes, and the three
steps of ThisPhonesTagData are deferred one after another for the same
reason. AGENTS.md rule 23 records the trap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
parawanderer#317 added RxFlows.onlyAfter for the same eager-DataStore trap this
branch worked around with Completable.defer. Settings' sign-out and
ThisPhonesTagData's three steps now use it, so there is one way to
write "only after" rather than two. AGENTS.md rule 23 points at the
helper instead of describing a second convention.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
updateAccessoryJson had no is_removed filter, so a fetch or Bluetooth
sighting that was already running when the user removed a tag landed
afterwards and wrote the accessory JSON, the keys Remove had just
deleted, back onto the hidden row. It now updates only listed rows.

The same race after "also delete its location history" failed the
other way: the tag has no row, so its reports failed LocationReport's
foreign key, and the single insert took every other tag's reports
from that fetch with it. Reports are now stored only for tags that
still have a row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
deleteIfNothingRefersTo checked only OwnedBeacons. A tag from a zip
that later arrived from the Apple account has its row moved off the
import, but keeps the zip's naming record when the account holds
none, and BeaconNamingRecord cascades on delete. Erasing the other
tag from that zip deleted the import and the account tag's name with
it. The import now stays while a naming record refers to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@lazzurs
lazzurs force-pushed the fix/s04-erase-removed-tag-data branch from 3c16370 to 1af5098 Compare November 23, 2026 13:54
Rob Lazzurs and others added 3 commits November 23, 2026 13:55
NearbyScanService reads the tags once, when it starts, and keeps their
keys for the life of the service, so after "Erase all data" it went on
listening for the erased tags, and alerting on them, until the process
died. The eraser now restarts it, if it is running, as its last step,
so only once the erase has succeeded.

The same step deletes the addresses derived from each tag's keys,
which are cached on disk. The restarted scan would retire them too,
but only with Bluetooth permission, and only if it was running.

ThisPhonesTagData takes its steps rather than the repositories, so
ThisPhonesTagDataTest can pin the order on the JVM: link, map
position, database, then the scan, and nothing after a failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The eraser forgets the iCloud link before it empties the database, so
an account read in between cannot write account tags back. A failure
after that step leaves the link gone and the tags still there, but the
toast said nothing had been erased. It now says the tags are still
there and the link may not be. The order stays as it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Multi-select Remove called removeBeacon once per tag, concurrently,
and each call vacuumed: the whole file was rewritten once per tag, and
a vacuum that found another call holding the database failed. The
device list now calls removeBeacons, which removes every selected tag
in one transaction and compacts once. removeBeacon delegates to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@lazzurs
lazzurs force-pushed the fix/s04-erase-removed-tag-data branch from 1af5098 to d9cdf58 Compare November 23, 2026 13:55
@lazzurs

lazzurs commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, all five done. I rebased on main first (#314, #317).

  1. updateAccessoryJson now has AND is_removed = 0 (1b6e579). aFetchThatLandsAfterRemovalDoesNotWriteTheKeysBack removes a tag and then calls storeFetchResult for it and a listed sibling, which still gets its new alignment. aSightingThatLandsAfterRemovalDoesNotWriteTheKeysBack covers the write recordAccessorySighting ends in. The same race had a second shape after a ticked Remove: the tag has no row, so its reports failed LocationReport's foreign key, and the single insert took every other tag's reports from that fetch with it. storeToLocationCache now skips tags with no row (aFetchThatLandsAfterTheTagWasErasedStillStoresTheOthers).
  2. Added the BeaconNamingRecord check (01faa37). anImportANamingRecordStillPointsAtIsKept moves a zip tag to the account with no naming record, then erases its sibling.
  3. The eraser restarts NearbyScanService as its last step, and only if it's running, so only after a successful erase (0c1208e). The same step deletes the derived-address cache on disk, since the restarted scan only clears that with Bluetooth permission. ThisPhonesTagData now takes its steps as suppliers, so ThisPhonesTagDataTest checks the order on the JVM, including that a failure leaves the scan alone.
  4. I reworded the toast (1c0fb8a). The link goes first on purpose, so a background account read can't write account tags back into the emptied database, and clearing Room first would reopen that. It narrows the window rather than closing it: a read already past the membership lookup can still land afterwards. The toast now says the tags are still there but the iCloud link may already be gone.
  5. Done (d9cdf58): removeBeacons(List, boolean), one transaction and one compaction. removeBeacon delegates to it, and multi-select uses it.

I also switched to your RxFlows.onlyAfter from #317 for the sign-out and the eraser's steps, so there's one way to write it (4c81ca4). Rule 23 in AGENTS.md now just points at the helper. Happy to drop the rule if you'd rather the javadoc be the only place it lives.

@lazzurs

lazzurs commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

Sidenote, regarding your proposed follow-ups

Thanks. I'll take them as separate PRs once this one lands. Encryption at rest needs a choice between SQLCipher and wrapping the three key columns, so I'll open an issue for that one first rather than turn up with a migration.

@lazzurs
lazzurs requested a review from parawanderer November 23, 2026 20:37
rubo77 pushed a commit to rubo77/OpenTagViewer that referenced this pull request Nov 23, 2026
clearUser() is built on RxDataStore.updateDataAsync, which starts its write when called rather
than when subscribed. Passed straight to andThen, it cleared the session while the chain was
being built, so accepting the upgrade signed the user out even if saving the choice failed.
Defer it so it runs after the save completes.

Found by lazzurs while working on parawanderer#315.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@parawanderer parawanderer left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All five verified. Optional follow-up: storeToLocationCache runs whichExist and insertAll outside a transaction, so an erase between the two still fails the whole insert. Wrapping both in db.runInTransaction closes it.

Keep rule 23.

Drafted by Claude Code, reviewed by @parawanderer

This branch was previously deployed

1 inactive deployment
Android Build — d9cdf58e Deployed Nov 23, 2026 by lazzurs via build #425
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants