Skip to content

Improve Gateway descendant asset ID mapping to prevent collisions - #3547

Merged
richturner merged 20 commits into
mainfrom
gateway-data-leakage
Dec 1, 2026
Merged

richturner merged 20 commits into
mainfrom
gateway-data-leakage

Conversation

@wborn

@wborn wborn commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Description

Prevent cross-gateway asset data leakage when cloned edge gateways report identical local asset IDs. The legacy mapping uses only the first two characters of the gateway registration ID, so gateways with the same prefix can map the same local asset ID to the same central asset. This PR introduces V2 mapping for new registrations and enforces persisted ownership for both V1 and V2.

Asset ID mapping and ownership

  • Use all 22 characters of the gateway registration ID in the reversible V2 mapping. Gateways with the same two-character prefix can now synchronize identical local asset IDs to distinct central IDs.
  • Record the first activation of each normalized Manager version in the central database. Use the earliest recorded activation of 1.36.0 or later as the V2 cutoff so restarts and later upgrades do not change a registration’s mapping.
  • Validate persisted ancestry when a gateway creates, updates, moves, or deletes an asset, or writes an attribute. Keep the relevant database rows locked through validation and the write. Use an insert for new gateway assets so an ID collision cannot overwrite an existing asset.

Synchronization

  • Reject invalid inventories, including duplicate IDs, missing parents, and cyclic hierarchies. Abort synchronization on asset processing failures and skip obsolete-asset cleanup when reconciliation fails.
  • Reconcile asset events received during synchronization before deleting obsolete assets. Apply queued creates, account for queued deletes, and request fresh copies of assets changed during sync.
  • Preserve explicit empty inventories on the wire and accept legacy responses that omit the asset list. Run the same reconciliation and cleanup for a valid empty inventory.
  • Accept repeated gateway deletion requests for assets that are already absent or pending deletion, while checking ownership of records that still exist. Improve logging for legacy mapping collisions and clean up pending synchronization work on disconnect.

Ownership cache

  • Use the persisted asset path for outbound attribute routing on a cache miss. Let supported inbound events reach the existing transactional ownership checks when the cache has no entry.
  • Check persisted ownership before central edits, moves, and deletes. Reject creates and moves under a persisted gateway even while its connector registration is queued.
  • Build gateway subtree deletions from persisted descendants and revalidate the selected rows after locking them. Reject mixed requests that explicitly include a gateway descendant before queueing gateway deletion.
  • Reconcile cache entries from current persisted ancestry. This handles a child event arriving before its parent is cached and a delayed delete event arriving after restoration.
  • Use asset paths for local agent and attribute-link handling, and fall back to persisted ancestry for model lookups and protocol discovery when cache entries are missing.

Closes #2427
Closes #3457

Breaking changes and migration

  • New registrations use V2 starting with OpenRemote 1.36.0. Gateways registered at or after the central Manager’s first recorded activation of 1.36.0 or later use V2. Earlier registrations retain V1, their existing central asset IDs, and their history. A routine upgrade requires no re-registration.
  • Legacy collisions can now stop synchronization. The central Manager rejects a write when the existing asset belongs to another gateway. To move an affected registration to V2, back up the central history you need, remove the affected registration, provision a new Gateway asset, and reconnect the edge with the new credentials. The new registration creates descendants with new central IDs. Their previous central history does not carry over.
  • Downgrading the central Manager below 1.36.0 can disrupt V2 registrations. Older releases use V1 for every registration. Back up the central database before rolling back. Resynchronizing a V2 registration on an older Manager can replace its synchronized assets and lose their central history.
  • Java callers of GatewayConnector must select the mapping version. Use the connector instance’s mapAssetId(assetId, outbound) for the registered gateway, or pass an explicit version to the four-argument static overload. Subclasses must supply the V2 activation timestamp to the constructor.

Upgrade, collision recovery, and rollback guidance is covered in openremote/documentation#215.

Validation

  • Added unit and integration coverage for V1 and V2 mapping, version activation, ownership conflicts, empty inventories, failed synchronization, and delayed cache updates.
  • Passed 54 targeted tests locally across gateway mapping, startup, ownership, provisioning, and the asset model. git diff --check also passed.

Checklist

  • 1. Acceptance criteria of the linked issue(s) are met
  • 2. Tests are written and all tests pass
  • 3. Changes are manually tested by you and the reviewer
  • 4. Documentation is written or updated

@wborn wborn added the Bug Error or issue in the system label Nov 5, 2026
- Introduce V2 asset ID mapping using all 22 characters of the gateway ID to reduce mapping collisions
- Preserve legacy V1 mapping for gateways registered before the upgrade to version 1.34.0
- Track first activation timestamps of normalized application versions to maintain a stable mapping cutoff across upgrades, restarts and rollbacks
- Enforce gateway asset ownership for creates, updates, deletions and attribute events using persisted asset ancestry
- Add database locking to prevent concurrent changes from bypassing ownership checks
- Reject conflicting asset IDs and invalid synchronization inventories to prevent unintended asset modifications or deletions
- Abort gateway synchronization when asset operations fail instead of continuing with inconsistent state
- Add unit and integration tests covering ID mapping, version tracking, ownership isolation and synchronization failures

Closes #2427
wborn added 6 commits November 6, 2026 12:13
- Serialize empty asset inventories so gateways can complete valid empty syncs
- Use inserts for gateway assets to prevent ID collisions from overwriting existing assets
- Add regression tests for inventory serialization and independent asset creation
- Process cached creates and attribute refreshes for empty inventories
- Reuse locked parent ancestry and identify ownership conflicts in logs
- Cover ownership rejection and cleanup after reconnect
@wborn
wborn marked this pull request as ready for review November 19, 2026 15:16
@wborn
wborn force-pushed the gateway-data-leakage branch from a1c24a6 to 64bfdad Compare November 19, 2026 16:44

@richturner richturner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The V2 mapping is fully reversible and can't collide between different gateways, and moving the ownership checks into the write transaction (reading persisted ancestry rather than cached state) is the right shape. Inserting a brand-new gateway asset with persist so a concurrent ID clash fails instead of overwriting, the inventory validation (duplicates, missing parents, cycles), and completeSync() fixing skipped cached events on an empty inventory are all good.

The unit specs pass locally (GatewayMappingTest, VersionInfoTest, AssetsEventTest, VersionUtilTest). I haven't run the integration specs.

Main concerns, with inline comments below:

  1. Older edge gateways with no assets can no longer sync. See the comment on GatewayConnector.java:650.
  2. The deployment in #2427 stays broken after upgrading. Both cloned gateways were created before the upgrade, so they stay on V1 and their IDs still collide. The leak is closed because the second gateway's merge now fails the ownership check, but since the whole sync aborts on any failure, that gateway never finishes syncing and keeps reconnecting. The only way onto V2 is deleting and recreating the gateway asset, which loses its central history. This needs release notes and a log message that names the fix, or a V1 to V2 migration path.
  3. Every attribute write now takes a row lock. See AssetProcessingService.java:429.
  4. A single thread can block itself forever. PersistenceService opens a new connection per transaction rather than reusing the outer one. When the gateway disabled attribute changes, createUpdateGatewayServiceUser can call assetStorageService.merge(gateway) while the outer attribute transaction already holds FOR UPDATE on that row. The inner write waits on the outer transaction from the same thread, and Postgres can't detect that as a deadlock, so the thread hangs. It only happens when the client ID or secret needs repairing, but it wasn't possible before because nothing locked the row early.
  5. Deletes that used to be harmless now cause a disconnect and full resync. See GatewayConnector.java:857.
  6. Locks can be taken in opposite orders. See AssetStorageService.java:1234.

Nits:

  • Rolling back to a pre-1.35 release and upgrading again re-creates every V2 gateway's central assets, losing history each time. Worth a line in the release notes.
  • The cutoff is stamped with the database clock (clock_timestamp()) but compared against createdOn, which Hibernate stamps with the JVM clock. A gateway created within any clock skew of the first 1.35 startup could get the wrong version.
  • ApplicationVersionService.getFirstActivation is only used by tests.
  • GatewayService uses a fully qualified jakarta.persistence.LockModeType in two places instead of importing it.

- Accept empty legacy inventories and repeated gateway deletes
- Scope attribute locks and repair credentials in the existing transaction
- Improve diagnostics for missing build tags and legacy ID collisions

wborn commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

Follow-up to the review summary in 40aeef3.

  • Disabling a gateway now repairs missing credentials in the existing attribute transaction. This avoids reacquiring the same per-asset lock through a nested merge. A regression test covers that path.
  • Existing V1 registrations keep their mapped IDs. The central manager blocks writes across ownership boundaries and logs recovery guidance for V1 conflicts. An affected gateway may still fail to sync until it is re-registered with V2 IDs. Back up any required central history before re-registering or rolling back to a release earlier than 1.36.0. Re-registration creates new IDs and does not carry forward the old central history. The upgrade and rollback guidance is prepared separately in the documentation repository.
  • Activation timestamps now use the application clock, matching asset creation on the manager. The test-only exact-version lookup was removed from the service and the lock-mode import was cleaned up.

Verified with 27 gateway unit tests and 26 integration tests, including legacy protocol compatibility.

- Add parameter, return value, and exception details to the affected Javadocs
- Clarify asset ID mapping direction and version activation rules
- Document ownership checks, transaction locks, and asynchronous deletion semantics

@MartinaeyNL MartinaeyNL left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Just out of curiosity, I let my AI-assistant take a look at any breaking changes in this PR.
Maybe not all of them are noteworthy (possibly not true), but I think they're worth sharing;

Summary of breaking changes assessed by AI

Compile-time (for code built against the manager API)

  • GatewayConnector.mapAssetId(gatewayId, assetId, outbound) (3-arg static) removed — replaced by a 4-arg version requiring a mapping version, plus a new instance method
  • GatewayConnector constructor gained a new Instant mappingV2ActivatedOn parameter
  • Inbound gateway attribute events now carry source "GatewayService:<gatewayId>" instead of "GatewayService" — breaks interceptors/authorizers matching on the old source string
  • AssetsEvent now serializes an explicit "assets":[] for empty inventories (previously omitted the field)

Deployment/upgrade (operator action required)

  • Pre-1.36 gateways with colliding V1 IDs (the #2427 victims) loop on SYNC_ERROR forever; only fix is re-registering the gateway, which loses its central history — no V1→V2 migration path
  • Rolling back below 1.36.0 and re-upgrading re-creates every V2 gateway's central assets (history loss)
  • Manager startup hard-fails (gateway connectors won't start) if no 1.36.0+ version activation is recorded — notably affects source builds without release git tags
  • Sync is fail-closed: any invalid inventory (duplicates, missing parents, cycles), rejected create/update/delete, or failed cleanup now aborts sync and disconnects the gateway instead of continuing

Runtime behavior (previously-accepted operations now fail)

  • Gateway writes to assets owned by another gateway (merge, move, delete, attribute update) now throw instead of silently overwriting/misrouting — the security fix itself
  • Concurrent gateway asset ID clashes now fail on insert instead of overwriting
  • Attribute events targeting assets pending deletion now throw AssetProcessingException
  • Stale gateway routing-cache entries that misdelivered writes to the wrong gateway now throw instead of forwarding
  • Inbound gateway attribute events take FOR UPDATE row locks plus FOR SHARE on all ancestors — new lock contention for busy gateways

@MartinaeyNL MartinaeyNL added the Breaking Change Indicates that a PR includes a breaking change label Nov 27, 2026
- Check persisted ownership before central asset writes and subtree deletion
- Route outbound attributes on cache misses and validate inbound events in the write transaction
- Reconcile cached ownership from persisted paths after out-of-order events
- Use persisted ancestry for model lookups, discovery, and local event handling
- Cover cache misses, delayed deletes, and pending connector registration in integration tests

Relates to #3457

@richturner richturner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Re-reviewed the changes since my last review (77201fae85). Everything I raised before is addressed (point 2 through docs and a log warning, not a migration path). CI is green; I haven't run anything locally this round.

Previous comments

# Concern Status
1 Older edge gateways with no assets can't sync ✅ Fixed. A missing assets field is treated as an empty inventory, with a frozen legacy JSON case in GatewayMappingTest.
2 Cloned V1 gateways stay broken after upgrade ⚠️ Mitigated. Recovery warning, breaking-change section and openremote/documentation#215, but no V1 to V2 migration, so an affected gateway keeps reconnecting until it's re-registered and loses its central history. Reasonable, but it's a product decision.
3 Row lock on every attribute write ✅ Fixed. FOR UPDATE only for GatewayService: sources. Every ingress (REST, websocket, MQTT) sets that source on the server, so clients can't spoof it.
4 Single-thread self-deadlock on credential repair ✅ Fixed, with a regression test. Keycloak calls finish before the lock is taken.
5 Duplicate or racing deletes force a disconnect ✅ Fixed.
6 Locks taken in opposite orders ✅ Fixed. I traced the new order against inbound attribute processing and found no cycle.
Nits Cutoff version, clock source, test-only method, qualified import ✅ All fixed.

New commits

Resolving ownership from the persisted path in 468ba7ae7 is the right approach. It also fixes a case the old code got wrong: when the parent's cache entry lagged, a GatewayAsset mirrored from an edge fell through as top-level, and processGatewayChange registered it and created a Keycloak client. processAssetPersistenceEvent now resolves the owner from the persisted row.

What I checked:

  • Soft delete publishes DELETE when the row becomes pending, and find excludes pending rows, so gateway deletion still reaches processGatewayChange.
  • doTransaction rethrows the original exception, so the GatewayAssetOwnershipException rethrow works.
  • Re-queuing an already-pending descendant is harmless, because doAssetDeletion treats a missing row as done.
  • isGatewayAssetOrDescendant adds a query on a cache miss, but it's only called from the asset-model endpoints and protocol discovery.

Findings, inline below:

  1. A gateway delete can be rejected by a race with in-flight descendant deletes (minor).
  2. A failed credential repair surfaces as "current transaction is aborted" (nit).
  3. The ownership-conflict message doesn't name the other gateway (nit, helps with point 2).

Also, one point from the 27 Nov review is still unanswered: inbound gateway attribute events now carry the source GatewayService:<gatewayId> instead of GatewayService. Nothing in core matches the old string, but it should either go in the breaking-change section, with a note on whether Extensions was checked, or get a reply saying it's internal.

On scope: 468ba7ae7 adds about 550 lines of production code and now also closes #3457. It's fine here since GatewayOwnershipTest covers it, but splitting would make sense if you want the #2427 fix merged first.

I'd approve once 1 is fixed or deliberately accepted. 2 and 3 can be follow-ups.

}
}

if (gatewayId == null && ids.size() != assets.size()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

deleteGatewayTree collects descendants with includeDeletePending(true), but calls this with gatewayId == null, so this strict check still applies. If the delete worker removes a pending descendant between findAll and taking the row locks, the whole gateway delete is rejected. That's likely when a gateway is deleted just after the edge deleted some assets.

deleteGatewayUntilFinished has already called connector.setDisabled(true) at that point, so a rejection also leaves the connector disabled in memory while the asset still says it's enabled. The disable-first behavior is older, but this makes rejection more likely. Could missing rows be tolerated when gatewayRootId != null, the way the gatewayId path does?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 8d22c2b. A gateway tree delete now tolerates descendants that the delete worker removes after the subtree query. The gateway root must still exist, and the locked rows are checked to confirm they remain in the subtree. A regression test removes a pending descendant between collection and locking.

wborn added 2 commits December 1, 2026 14:03
- Tolerate completed descendant deletions during gateway removal
- Preserve credential repair errors and identify conflicting gateway owners
- Keep gateway attribute metrics grouped under the existing source label

wborn commented Dec 1, 2026

Copy link
Copy Markdown
Member Author

Following up on the review, inbound gateway writes carry GatewayService:<gatewayId> in the Java-only AttributeEvent.getSource() field. Custom Java interceptors that inspect this field can match GatewayConnector.REMOTE_EVENT_SOURCE_PREFIX. The source is excluded from JSON. A source scan found no affected consumers in Extensions or the Custom Project template. 8d22c2b also keeps metrics grouped under the existing GatewayService label.

All 37 targeted gateway tests and spotlessBackendCheck passed.

@wborn
wborn requested a review from richturner December 1, 2026 13:38
@richturner richturner changed the title Prevent cross-gateway asset data leakage Improve Gateway descendant asset ID mapping to prevent collisions Dec 1, 2026
@richturner
richturner enabled auto-merge December 1, 2026 22:19
@sonarqubecloud

sonarqubecloud Bot commented Dec 1, 2026

Copy link
Copy Markdown

@richturner
richturner added this pull request to the merge queue Dec 1, 2026
Merged via the queue into main with commit 0af5ffe Dec 1, 2026
23 of 24 checks passed
@richturner
richturner deleted the gateway-data-leakage branch December 1, 2026 23:18
@richturner

Copy link
Copy Markdown
Member

Post-merge review notes. Please check whether any of these need a follow-up. Each one includes steps for reproducing it in GatewayTest.

1. Gateway attribute updates remove AGENT_LINK from the stored central asset

AssetProcessingService.processAttributeEvent now loads the asset with em.find(Asset.class, id, lockMode). This returns the managed entity. new AttributeEvent(asset, attribute, ...) takes attribute.getMeta() by reference. The inbound branch in GatewayService.onAttributeEventIntercepted then calls event.getMeta().remove(MetaItemType.AGENT_LINK). That changes the managed attribute, so Hibernate flushes an asset UPDATE when the transaction commits. On main the asset came from assetStorageService.find(...), which is not managed, so the removal only affected the event.

The removal is there so the agent interceptor skips the event (see the comment on the internal-source branch). It is not meant to change stored data. Sync keeps agent links: GatewayTest asserts hasMeta(AGENT_LINK) on the mirrored assets. The result is that central has the link after a sync, loses it on the first update from the edge, and gets an extra version bump and asset UPDATE persistence event.

Suggested fix: remove the item from a copy, event.setMeta(new MetaMap(event.getMeta())). If central should never hold agent links, strip them once in saveAssetLocally instead.

To reproduce: in GatewayTest, after the existing "all the gateway assets should be replicated" step:

  1. Read the central copy of building 1 room 1 (mapAssetId(gateway.id, assetIds[1], false)) and note its version.
  2. Send a gateway-sourced update from the edge client: gatewayClient.sendMessage(SharedEvent.MESSAGE_PREFIX + ValueUtil.asJSON(new AttributeEvent(assetIds[1], "temp", 21d)).get()).
  3. Wait until the central temp value is 21d, then re-read the asset.
  4. Assert getAttribute("temp").get().hasMeta(AGENT_LINK) and that version has not changed. Both should fail today.

2. A gateway can't re-sync an asset that central has pending deletion

For gateway merges in AssetStorageService.merge, requireGatewayOwnership(em, existingAsset, gatewayId, false) runs with allowDeletePending = false. It throws Invalid gateway asset ancestry when the subject is deletePending. This happens before the existing "Canceling pending asset deletion" branch, so that branch can no longer run for gateway saves. Before this PR, gateway saves skipped the check and revived the asset.

An asset gets into this state when a background delete fails (it stays deletePending and goes into failedAssetDeleteIds), or when the edge re-sends an asset before its queued deletion has finished. The save throws, onGatewayEvent disconnects with SYNC_ERROR, and the edge reconnects and re-sends the same asset. When the background delete has failed, nothing clears the flag, so the gateway keeps reconnecting.

Suggested fix: allow a pending-deletion subject in this check so the cancellation branch runs. If reviving a child under an ancestor that is being deleted should be rejected, check the ancestors separately.

To reproduce: after the initial sync completes:

  1. Simulate a failed delete on a mirrored descendant: persistenceService.doTransaction { em -> em.find(Asset, centralId).setDeletePending(true) } and assetStorageService.failedAssetDeleteIds.add(centralId).
  2. From the edge client, send an AssetEvent(UPDATE, ...) for that asset (edge ID) with a bumped version.
  3. Assert the connector stays connected, !assetStorageService.isDeletePending(centralId), and the update is applied. Today the connector disconnects with SYNC_ERROR, and after reconnecting it fails the same way.

3. One rejected asset stops the whole initial sync

completeSync no longer catches exceptions when it saves cached CREATE events. On main it logged Failed to add new gateway asset and continued. deleteObsoleteLocalAssets now throws where it used to log a warning. Either exception reaches onGatewayEvent and disconnects with SYNC_ERROR before onInitialSyncComplete. The edge re-sends the same state on reconnect, so the same rejection happens every time and the gateway never finishes syncing. The batch save path already failed closed on main, so making stage 2 match it may be intended. If so, it would help to log which asset caused the disconnect. The alternative is to disconnect only on GatewayAssetOwnershipException and log other rejections as before.

To reproduce, cached CREATE:

  1. Connect an edge client and reply to the capabilities request, but don't reply to the sync batch request yet.
  2. While the sync is in progress, send an AssetEvent(CREATE, ...) for a new asset that central will reject, e.g. one whose realm differs from its parent's (Gateway asset realm mismatch), or one whose parent ID is not in the inventory.
  3. Reply to the batch request so completeSync runs.
  4. Assert that GatewayInitDoneEvent is received and !connector.isInitialSyncInProgress(), with the bad asset skipped. Today the gateway disconnects with SYNC_ERROR.

To reproduce, obsolete cleanup:

  1. After one full sync, insert a child directly with persistenceService/em.persist under a mirrored descendant that the edge will leave out of its next inventory. The normal merge path refuses writes under gateway descendants.
  2. Reconnect the edge with an inventory that leaves out that descendant.
  3. deleteObsoleteLocalAssets is rejected ("One or more requested assets still have children") and the gateway disconnects. Assert whichever behavior is intended.

Minor

  • GatewayService.isGatewayAssetOrDescendant runs a database lookup on every cache miss, even when gatewayConnectorMap is empty. It's called from the AssetModelService descriptor and asset-info calls that take a parentId, and from agent discovery. Returning false early when no gateways are registered avoids the query.
  • AssetIntegrityTest "creating assets from a reused template returns independent persisted instances" starts the container inside the feature method and doesn't remove the assets it creates. AGENTS.md asks for setupSpec and cleanup.

@wborn

wborn commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

Post-merge review notes. Please check whether any of these need a follow-up. Each one includes steps for reproducing it in GatewayTest.

I've created #3657 for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Breaking Change Indicates that a PR includes a breaking change Bug Error or issue in the system

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GatewayService.assetIdGatewayIdMap is accessed from multiple threads without synchronization Prevent gateway descendant asset data leakage

3 participants