Repository navigation
Improve Gateway descendant asset ID mapping to prevent collisions - #3547
Conversation
- 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
1325e32 to
418dd84
Compare
- 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
a1c24a6 to
64bfdad
Compare
richturner
left a comment
There was a problem hiding this comment.
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:
- Older edge gateways with no assets can no longer sync. See the comment on
GatewayConnector.java:650. - 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.
- Every attribute write now takes a row lock. See
AssetProcessingService.java:429. - A single thread can block itself forever.
PersistenceServiceopens a new connection per transaction rather than reusing the outer one. When the gatewaydisabledattribute changes,createUpdateGatewayServiceUsercan callassetStorageService.merge(gateway)while the outer attribute transaction already holdsFOR UPDATEon 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. - Deletes that used to be harmless now cause a disconnect and full resync. See
GatewayConnector.java:857. - 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 againstcreatedOn, 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.getFirstActivationis only used by tests.GatewayServiceuses a fully qualifiedjakarta.persistence.LockModeTypein 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
|
Follow-up to the review summary in 40aeef3.
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
There was a problem hiding this comment.
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 methodGatewayConnectorconstructor gained a newInstant mappingV2ActivatedOnparameter- Inbound gateway attribute events now carry source
"GatewayService:<gatewayId>"instead of"GatewayService"— breaks interceptors/authorizers matching on the old source string AssetsEventnow 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_ERRORforever; 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 UPDATErow locks plusFOR SHAREon all ancestors — new lock contention for busy gateways
- 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
left a comment
There was a problem hiding this comment.
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 | |
| 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
DELETEwhen the row becomes pending, andfindexcludes pending rows, so gateway deletion still reachesprocessGatewayChange. doTransactionrethrows the original exception, so theGatewayAssetOwnershipExceptionrethrow works.- Re-queuing an already-pending descendant is harmless, because
doAssetDeletiontreats a missing row as done. isGatewayAssetOrDescendantadds a query on a cache miss, but it's only called from the asset-model endpoints and protocol discovery.
Findings, inline below:
- A gateway delete can be rejected by a race with in-flight descendant deletes (minor).
- A failed credential repair surfaces as "current transaction is aborted" (nit).
- 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()) { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
- 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
|
Following up on the review, inbound gateway writes carry All 37 targeted gateway tests and |
|
|
Post-merge review notes. Please check whether any of these need a follow-up. Each one includes steps for reproducing it in 1. Gateway attribute updates remove
|
I've created #3657 for this. |



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
Synchronization
Ownership cache
Closes #2427
Closes #3457
Breaking changes and migration
GatewayConnectormust select the mapping version. Use the connector instance’smapAssetId(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
git diff --checkalso passed.Checklist