From 90c56393406e1b6ea252e455bcd36d1eb18ef5d9 Mon Sep 17 00:00:00 2001 From: Torben Dannhauer Date: Thu, 12 Nov 2026 10:49:41 +0100 Subject: [PATCH 1/2] fix(activesync): keep sync state of two devices apart after a device change A client that is moved to a new phone keeps its sync keys but reports a new DeviceId. Both device ids then advanced the same key series. Only one state row can exist per sync key, so the device falling behind could never store its next state and repeated its SYNC forever with HTTP 500 (duplicate key on horde_activesync_state). - Mutating loads only accept state stored for the requesting device and user. A key of another device is reported as StateGone, so the client resyncs the folder and gets a key series of its own. - Mutating loads also reset the device if the next key of the series already belongs to another device. - Saving never overwrites (Sql) or removes (Mongo) state of another device. State_Sql rolls back the aborted transaction before it recovers from a failed INSERT, so the recovery works on PostgreSQL. - Read-only (PING) loads stay unrestricted, so the folder is not dropped from the PING set before the next SYNC resets it. --- lib/Horde/ActiveSync/State/Mongo.php | 326 +++++++++++- lib/Horde/ActiveSync/State/Sql.php | 345 +++++++++++-- .../StateTest/Mongo/DeviceChangeTest.php | 466 ++++++++++++++++++ .../StateTest/Sql/DeviceChangeTest.php | 442 +++++++++++++++++ 4 files changed, 1517 insertions(+), 62 deletions(-) create mode 100644 test/integration/Horde/ActiveSync/StateTest/Mongo/DeviceChangeTest.php create mode 100644 test/unit/Horde/ActiveSync/StateTest/Sql/DeviceChangeTest.php diff --git a/lib/Horde/ActiveSync/State/Mongo.php b/lib/Horde/ActiveSync/State/Mongo.php index 248039c1..463f72f8 100644 --- a/lib/Horde/ActiveSync/State/Mongo.php +++ b/lib/Horde/ActiveSync/State/Mongo.php @@ -295,6 +295,218 @@ protected function _stateRowLockQuery() ]; } + /** + * Query for the state document of the current sync key, restricted to + * the requesting device and user. + * + * The device and user restriction is what keeps a changed device from + * locking and adopting another device's sync key series + * (@see self::_isOwnStateRow()). + * + * @author Torben Dannhauer + * + * @return array + */ + protected function _ownStateRowQuery() + { + return array_merge( + $this->_stateRowLockQuery(), + [ + self::SYNC_DEVID => $this->_deviceInfo->id, + self::SYNC_USER => $this->_deviceInfo->user, + ] + ); + } + + /** + * Tell whether a state document belongs to the requesting device, user + * and folder. + * + * DEVICE CHANGE - why state documents have an owner check + * ------------------------------------------------------- + * HAS_state uses the sync key as document _id, but every document also + * records the device (sync_devid), user (sync_user) and folder + * (sync_folderid) it was written for. Sync keys are generated per + * device, so normally nobody else ever presents them. + * + * A device change breaks that assumption. When an account is moved to a + * new phone (device-to-device transfer, restore from a backup), the + * client keeps its per-folder sync keys but reports a NEW DeviceId. The + * new device then presents sync keys that were issued to the old device. + * If the old phone stays online, two device ids advance the same key + * series ("{guid}N" -> "{guid}N+1") at the same time, while only one + * document can exist per sync key. Without an owner check each device + * would load, lock and replace the documents of the other one, so both + * would continue from each other's folder state and pending changes. + * (The SQL driver hit the same conflict as an endless duplicate key + * failure, @see Horde_ActiveSync_State_Sql::_isOwnStateRow().) + * + * The state of two devices must therefore never share a key series. + * Three places enforce this, all based on this ownership test: + * + * 1. Mutating loads (self::_ownStateRowQuery()): a sync key that is + * stored for another device or user is treated as unknown. The + * request gets Horde_ActiveSync_Exception_StateGone, which SYNC + * answers with a key mismatch status; the client restarts the + * folder with sync key 0 and receives a key series of its own. This + * is what a changed device hits on its first SYNC. + * + * 2. Mutating loads (self::_assertNextSyncKeyAvailable()): if the NEXT + * key of the series already belongs to another device, the series + * has been continued by that device (documents written before + * check 1 existed, or a race). The requesting device is reset the + * same way, before any client changes are imported or response data + * is sent. + * + * 3. Saving (self::_recoverFromFailedStateInsert()): a document owned + * by another device is never removed or replaced. The save fails, + * and check 2 resets the device on its next request. + * + * Read-only loads (PING) are exempt on purpose; the reason is documented + * in self::_acquireStateRowLock(). + * + * Resetting is always safe for the other device: a folder reset only + * removes documents of the requesting device + * (self::_resetDeviceState()). + * + * @author Torben Dannhauer + * + * @param array $owner A document as returned by self::_syncStateOwner(). + * + * @return boolean + */ + protected function _isOwnStateRow(array $owner) + { + // Same folder id save() stores for the current request. + $folderId = !empty($this->_collection['id']) + ? $this->_collection['id'] + : Horde_ActiveSync::REQUEST_TYPE_FOLDERSYNC; + + return (string) ($owner[self::SYNC_DEVID] ?? '') === (string) $this->_deviceInfo->id + && (string) ($owner[self::SYNC_USER] ?? '') === (string) $this->_deviceInfo->user + && (string) ($owner[self::SYNC_FOLDERID] ?? '') === (string) $folderId; + } + + /** + * Return the owner fields of the state document stored under a sync key, + * regardless of which device it belongs to. + * + * @author Torben Dannhauer + * + * @param string $syncKey The sync key. + * + * @return array|null Hash with sync_devid, sync_user and sync_folderid, + * or null if no document exists for the key. + * @throws MongoException + */ + protected function _syncStateOwner($syncKey) + { + $doc = $this->_stateCollection()->findOne( + [self::MONGO_ID => $syncKey], + [ + self::SYNC_DEVID => true, + self::SYNC_USER => true, + self::SYNC_FOLDERID => true, + ] + ); + + return empty($doc) ? null : $doc; + } + + /** + * Log why no state document could be loaded for the current sync key. + * + * A key that exists for another device is logged as such, so a device + * change (@see self::_isOwnStateRow()) can be told apart from state that + * is really gone. The lookup is diagnostic only: the caller raises + * Horde_ActiveSync_Exception_StateGone in both cases. + * + * @author Torben Dannhauer + */ + protected function _logStateNotFound() + { + $owner = null; + try { + $owner = $this->_syncStateOwner($this->_syncKey); + } catch (MongoException $e) { + // Only the reason is lost; fall back to the generic message. + $this->_logger->err($e->getMessage()); + } + + if ($owner !== null + && (string) ($owner[self::SYNC_DEVID] ?? '') !== (string) $this->_deviceInfo->id) { + $this->_logger->warn( + sprintf( + 'STATE: Synckey %s is stored for device %s, not for the requesting device %s (device change). Treating the state as gone so the client resyncs with its own keys.', + $this->_syncKey, + $owner[self::SYNC_DEVID] ?? '', + $this->_deviceInfo->id + ) + ); + return; + } + + $this->_logger->warn(sprintf( + 'Could not find state for synckey %s.', + $this->_syncKey + )); + } + + /** + * Ensure the next sync key of the current series can be stored by the + * requesting device. + * + * If the next key already exists for another device, that device has + * continued this key series (device change, + * @see self::_isOwnStateRow()) and the requesting device could never + * save its next state. It is reset instead, while nothing has been + * imported or sent yet. + * + * A next key owned by the requesting device itself is fine: the client + * did not receive the previous response and repeats the request, and + * the save replaces that document. + * + * Only mutating loads check this. Read-only loads (PING) never store a + * new key; the client is reset by the SYNC it sends once PING reports + * changes. + * + * @author Torben Dannhauer + * + * @throws Horde_ActiveSync_Exception + * @throws Horde_ActiveSync_Exception_StateGone + */ + protected function _assertNextSyncKeyAvailable() + { + // Same key format loadState() accepts. + if (!preg_match('/^(\{[0-9A-Za-z-]+\})([0-9]+)$/', (string) $this->_syncKey, $matches)) { + return; + } + $nextKey = $matches[1] . ((int) $matches[2] + 1); + + try { + $owner = $this->_syncStateOwner($nextKey); + } catch (MongoException $e) { + $this->_logger->err($e->getMessage()); + throw new Horde_ActiveSync_Exception($e); + } + + if ($owner === null || $this->_isOwnStateRow($owner)) { + return; + } + + $this->_logger->warn( + sprintf( + 'STATE: Next synckey %s is already stored for device %s (device change). The requesting device %s cannot continue this key series; treating the state as gone so the client resyncs with its own keys.', + $nextKey, + $owner[self::SYNC_DEVID] ?? '', + $this->_deviceInfo->id + ) + ); + throw new Horde_ActiveSync_Exception_StateGone( + 'Sync key series continued by another device.' + ); + } + /** * Release a document lock opened by _loadState(). * @@ -333,7 +545,20 @@ protected function _releaseStateRowLock($commit = false) protected function _acquireStateRowLock() { $collection = $this->_stateCollection(); - $baseQuery = $this->_stateRowLockQuery(); + // Mutating loads only see documents of the requesting device, so a + // changed device cannot adopt another device's sync key series + // (@see self::_isOwnStateRow()). + // + // Read-only loads (PING) are deliberately NOT restricted: after a + // device change the peek may read the document the key was copied + // from. That is harmless, as PING stores no new key, and it keeps + // PING working until the client's next SYNC for the folder is reset. + // Reporting the state as gone instead would make + // Horde_ActiveSync_Collections::pollForChanges() drop the folder + // from the device's PING set, so nothing would trigger that SYNC. + $baseQuery = $this->_loadReadonly + ? $this->_stateRowLockQuery() + : $this->_ownStateRowQuery(); try { $exists = $collection->count($baseQuery); @@ -343,10 +568,7 @@ protected function _acquireStateRowLock() } if (!$exists) { - $this->_logger->warn(sprintf( - 'Could not find state for synckey %s.', - $this->_syncKey - )); + $this->_logStateNotFound(); throw new Horde_ActiveSync_Exception_StateGone(); } @@ -660,6 +882,14 @@ protected function _loadState() { $this->_releaseStateRowLock(false); + if (!$this->_loadReadonly) { + // Device change: stop here if another device already continued + // this key series (@see self::_isOwnStateRow()). Checked before + // the document lock is taken, so a rejected load leaves no lock + // behind. + $this->_assertNextSyncKeyAvailable(); + } + $results = $this->_acquireStateRowLock(); $this->_loadStateFromResults($results); } @@ -824,20 +1054,10 @@ protected function _saveSyncStateRow(array $document) try { $collection->insert($document); - } catch (Exception $e) { - // Might exist already if the last sync attempt failed. - $this->_logger->notice( - sprintf( - 'Previous request processing for synckey %s failed to be accepted by the client, removing previous state and trying again.', - $this->_syncKey - ) - ); - try { - $collection->remove([self::MONGO_ID => $this->_syncKey]); - $collection->insert($document); - } catch (Exception $e2) { - throw new Horde_ActiveSync_Exception('Error saving state.'); - } + } catch (MongoException $e) { + // Usually the key exists already because the last sync + // attempt failed - but it may also belong to another device. + $this->_recoverFromFailedStateInsert($document, $e); } } catch (Horde_ActiveSync_Exception $e) { if ($lockHeld) { @@ -852,6 +1072,74 @@ protected function _saveSyncStateRow(array $document) } } + /** + * Decide what to do after inserting the state document of the current + * sync key failed. + * + * - A document of the requesting device exists: the client did not + * accept the previous response and the key is stored again. The old + * document is replaced. + * - A document of ANOTHER device exists: device change + * (@see self::_isOwnStateRow()). It is left untouched and the save + * fails; removing it would hand this device's state to the other + * device. The requesting device is reset on its next request by + * self::_assertNextSyncKeyAvailable(). + * - No document exists: the insert failed for another reason, which is + * reported as it is. + * + * @author Torben Dannhauer + * + * @param array $document State document fields. + * @param MongoException $e The failure of the insert. + * + * @throws MongoException Converted to Horde_ActiveSync_Exception by + * self::_saveSyncStateRow(). + */ + protected function _recoverFromFailedStateInsert(array $document, MongoException $e) + { + $collection = $this->_stateCollection(); + $owner = $this->_syncStateOwner($this->_syncKey); + + if ($owner === null) { + $this->_logger->err( + sprintf( + 'STATE: Persist INSERT failed for synckey %s folder %s: %s', + $this->_syncKey, + $document[self::SYNC_FOLDERID], + $e->getMessage() + ) + ); + throw $e; + } + + if (!$this->_isOwnStateRow($owner)) { + $this->_logger->err( + sprintf( + 'STATE: Synckey %s is already stored for device %s (device change). Not replacing it; the requesting device %s is reset on its next request.', + $this->_syncKey, + $owner[self::SYNC_DEVID] ?? '', + $this->_deviceInfo->id + ) + ); + throw $e; + } + + $this->_logger->notice( + sprintf( + 'Previous request processing for synckey %s failed to be accepted by the client, removing previous state and trying again.', + $this->_syncKey + ) + ); + // Restricted to the requesting device, so a document that another + // device stored in the meantime is never removed. + $collection->remove([ + self::MONGO_ID => $this->_syncKey, + self::SYNC_DEVID => $this->_deviceInfo->id, + self::SYNC_USER => $this->_deviceInfo->user, + ]); + $collection->insert($document); + } + /** * Update the syncStamp in the collection state, outside of any other changes. * Used to prevent extremely large differences in syncStamps for clients diff --git a/lib/Horde/ActiveSync/State/Sql.php b/lib/Horde/ActiveSync/State/Sql.php index dcd4427f..516e4b01 100644 --- a/lib/Horde/ActiveSync/State/Sql.php +++ b/lib/Horde/ActiveSync/State/Sql.php @@ -212,6 +212,10 @@ public function __destruct() * transaction is kept open across the request. Serializing mutating * loads against each other is the job of the collection lock. * + * Only a row stored for the requesting device and user is returned. A + * sync key that exists for another device is reported as missing state + * (device change, @see self::_isOwnStateRow()). + * * @return array The state row (sync_data, sync_devid, sync_mod, * sync_pending). * @throws Horde_ActiveSync_Exception @@ -225,13 +229,7 @@ protected function _readStateRow() $started = true; } - $sql = 'SELECT sync_data, sync_devid, sync_mod, sync_pending FROM ' - . $this->_syncStateTable . ' WHERE sync_key = ?'; - $values = [$this->_syncKey]; - if (!empty($this->_collection['id'])) { - $sql .= ' AND sync_folderid = ?'; - $values[] = $this->_collection['id']; - } + [$sql, $values] = $this->_ownStateRowQuery(); /* addLock() appends FOR UPDATE on MySQL/PostgreSQL but is a no-op on * SQLite (Horde_Db_Adapter_Pdo_Sqlite). SQLite's file-level locking * serializes writes anyway, so the row lock is advisory only there. */ @@ -260,16 +258,220 @@ protected function _readStateRow() } if (empty($results)) { + $this->_logStateNotFound(); + throw new Horde_ActiveSync_Exception_StateGone(); + } + + return $results; + } + + /** + * Build the query that reads the state row of the current sync key for + * the requesting device and user. + * + * The device and user restriction is what keeps a changed device from + * adopting another device's sync key series + * (@see self::_isOwnStateRow()). + * + * @author Torben Dannhauer + * + * @return array [SQL string, bound values]. + */ + protected function _ownStateRowQuery() + { + $sql = 'SELECT sync_data, sync_devid, sync_mod, sync_pending FROM ' + . $this->_syncStateTable + . ' WHERE sync_key = ? AND sync_devid = ? AND sync_user = ?'; + $values = [ + $this->_syncKey, + $this->_deviceInfo->id, + $this->_deviceInfo->user, + ]; + if (!empty($this->_collection['id'])) { + $sql .= ' AND sync_folderid = ?'; + $values[] = $this->_collection['id']; + } + + return [$sql, $values]; + } + + /** + * Tell whether a state row belongs to the requesting device, user and + * folder. + * + * DEVICE CHANGE - why state rows have an owner check + * -------------------------------------------------- + * horde_activesync_state has the sync key as its only primary key, but + * every row also records the device (sync_devid), user (sync_user) and + * folder (sync_folderid) it was written for. Sync keys are generated per + * device, so normally nobody else ever presents them. + * + * A device change breaks that assumption. When an account is moved to a + * new phone (device-to-device transfer, restore from a backup), the + * client keeps its per-folder sync keys but reports a NEW DeviceId. The + * new device then presents sync keys that were issued to the old device. + * If the old phone stays online, two device ids advance the same key + * series ("{guid}N" -> "{guid}N+1") at the same time. Because only one + * row can exist per sync key, the device that falls behind can never + * store its next state: its UPDATE does not match (other sync_devid) and + * its INSERT violates the primary key. It then repeats the same SYNC + * request forever, each attempt ending in HTTP 500. + * + * The state of two devices must therefore never share a key series. + * Three places enforce this, all based on this ownership test: + * + * 1. Mutating loads (self::_ownStateRowQuery()): a sync key that is + * stored for another device or user is treated as unknown. The + * request gets Horde_ActiveSync_Exception_StateGone, which SYNC + * answers with a key mismatch status; the client restarts the + * folder with sync key 0 and receives a key series of its own. This + * is what a changed device hits on its first SYNC. + * + * 2. Mutating loads (self::_assertNextSyncKeyAvailable()): if the NEXT + * key of the series already belongs to another device, the series + * has been continued by that device (rows written before check 1 + * existed, or a race). The requesting device is reset the same way, + * before any client changes are imported or response data is sent. + * + * 3. Saving (self::_saveSyncStateRow()): a row owned by another device + * is never overwritten. The save fails, and check 2 resets the + * device on its next request. + * + * Read-only loads (PING, self::_loadStateReadonly()) are exempt on + * purpose; the reason is documented there. + * + * Resetting is always safe for the other device: a folder reset only + * deletes rows of the requesting device (self::_resetDeviceState()). + * + * @author Torben Dannhauer + * + * @param array $owner A row as returned by self::_syncStateOwner(). + * + * @return boolean + */ + protected function _isOwnStateRow(array $owner) + { + return (string) $owner['sync_devid'] === (string) $this->_deviceInfo->id + && (string) $owner['sync_user'] === (string) $this->_deviceInfo->user + && (string) $owner['sync_folderid'] === (string) $this->_stateFolderId(); + } + + /** + * Return the owner columns of the state row stored under a sync key, + * regardless of which device it belongs to. + * + * @author Torben Dannhauer + * + * @param string $syncKey The sync key. + * + * @return array|null Hash with sync_devid, sync_user and sync_folderid, + * or null if no row exists for the key. + * @throws Horde_Db_Exception + */ + protected function _syncStateOwner($syncKey) + { + $row = $this->_db->selectOne( + 'SELECT sync_devid, sync_user, sync_folderid FROM ' + . $this->_syncStateTable . ' WHERE sync_key = ?', + [$syncKey] + ); + + return empty($row) ? null : $row; + } + + /** + * Log why no state row could be loaded for the current sync key. + * + * A key that exists for another device is logged as such, so a device + * change (@see self::_isOwnStateRow()) can be told apart from state that + * is really gone. The lookup is diagnostic only: the caller raises + * Horde_ActiveSync_Exception_StateGone in both cases. + * + * @author Torben Dannhauer + */ + protected function _logStateNotFound() + { + $owner = null; + try { + $owner = $this->_syncStateOwner($this->_syncKey); + } catch (Horde_Db_Exception $e) { + // Only the reason is lost; fall back to the generic message. + $this->_logger->err($e->getMessage()); + } + + if ($owner !== null && !$this->_isOwnStateRow($owner)) { $this->_logger->warn( sprintf( - 'STATE: Could not find state for synckey %s.', - $this->_syncKey + 'STATE: Synckey %s is stored for device %s, not for the requesting device %s (device change). Treating the state as gone so the client resyncs with its own keys.', + $this->_syncKey, + $owner['sync_devid'], + $this->_deviceInfo->id ) ); - throw new Horde_ActiveSync_Exception_StateGone(); + return; } - return $results; + $this->_logger->warn( + sprintf( + 'STATE: Could not find state for synckey %s.', + $this->_syncKey + ) + ); + } + + /** + * Ensure the next sync key of the current series can be stored by the + * requesting device. + * + * If the next key already exists for another device, that device has + * continued this key series (device change, + * @see self::_isOwnStateRow()) and the requesting device could never + * save its next state. It is reset instead, while nothing has been + * imported or sent yet. + * + * A next key owned by the requesting device itself is fine: the client + * did not receive the previous response and repeats the request, and + * the save updates that row. + * + * Only mutating loads check this. Read-only loads (PING) never store a + * new key; the client is reset by the SYNC it sends once PING reports + * changes (@see self::_loadStateReadonly()). + * + * @author Torben Dannhauer + * + * @throws Horde_ActiveSync_Exception + * @throws Horde_ActiveSync_Exception_StateGone + */ + protected function _assertNextSyncKeyAvailable() + { + // Same key format loadState() accepts. + if (!preg_match('/^(\{[0-9A-Za-z-]+\})([0-9]+)$/', (string) $this->_syncKey, $matches)) { + return; + } + $nextKey = $matches[1] . ((int) $matches[2] + 1); + + try { + $owner = $this->_syncStateOwner($nextKey); + } catch (Horde_Db_Exception $e) { + $this->_logger->err($e->getMessage()); + throw new Horde_ActiveSync_Exception($e); + } + + if ($owner === null || $this->_isOwnStateRow($owner)) { + return; + } + + $this->_logger->warn( + sprintf( + 'STATE: Next synckey %s is already stored for device %s (device change). The requesting device %s cannot continue this key series; treating the state as gone so the client resyncs with its own keys.', + $nextKey, + $owner['sync_devid'], + $this->_deviceInfo->id + ) + ); + throw new Horde_ActiveSync_Exception_StateGone( + 'Sync key series continued by another device.' + ); } /** @@ -633,6 +835,9 @@ protected function _loadState() unset($this->_readonlyStateMemo[$this->_stateFolderId()]); $results = $this->_readStateRow(); + // Device change: stop here if another device already continued + // this key series (@see self::_isOwnStateRow()). + $this->_assertNextSyncKeyAvailable(); $this->_loadStateFromResults($results); } @@ -663,6 +868,14 @@ protected function _loadStateReadonly() } unset($this->_readonlyStateMemo[$folderid]); + // Deliberately NOT restricted to the requesting device, unlike + // _readStateRow(): after a device change + // (@see self::_isOwnStateRow()) the peek may read the row the key + // was copied from. That is harmless, as nothing is written here, and + // it keeps PING working until the client's next SYNC for the folder + // is reset. Reporting the state as gone instead would make + // Horde_ActiveSync_Collections::pollForChanges() drop the folder + // from the device's PING set, so nothing would trigger that SYNC. $sql = 'SELECT sync_data, sync_devid, sync_mod, sync_pending FROM ' . $this->_syncStateTable . ' WHERE sync_key = ?'; $values = [$this->_syncKey]; @@ -954,6 +1167,13 @@ protected function _saveState(array $options = []) * by the collection lock, so no row lock has to be carried from * _loadState() to this point. * + * The UPDATE only matches a row of the requesting device, user and + * folder. If it matches nothing and the INSERT then fails, the sync key + * is already taken: either by a parallel request of the same device + * (the row is updated instead) or by another device after a device + * change (the row is left alone and the save fails, + * @see self::_recoverFromFailedStateInsert()). + * * @param array $params Column data for horde_activesync_state. * * @throws Horde_ActiveSync_Exception @@ -996,28 +1216,21 @@ protected function _saveSyncStateRow(array $params) $params['sync_key'] ); } catch (Horde_Db_Exception $e) { - if (!$this->_syncStateExists($params['sync_key'])) { - $this->_logger->err( - sprintf( - 'STATE: Persist INSERT failed for synckey %s folder %s: %s', - $params['sync_key'], - $params['sync_folderid'], - $e->getMessage() - ) - ); - throw $e; - } - - $message = 'STATE: Concurrent insert for synckey ' - . $params['sync_key'] - . '; updating existing row.'; - Horde::log($message, 'DEBUG'); - $this->_logger->meta($message); - - $updated = $this->_db->updateBlob($this->_syncStateTable, $params, $where); - if (!$updated) { - throw $e; + // PostgreSQL aborts the whole transaction when a statement + // fails: every further statement, including the lookup + // that decides how to recover, is rejected with SQLSTATE + // 25P02 until the transaction is rolled back. Nothing else + // was written in it (the UPDATE above matched no row), so + // start over with a fresh one. + // + // A caller's transaction is not ours to roll back. The + // recovery then only works on databases that keep a + // transaction usable after a constraint violation. + if ($started) { + $this->_db->rollbackDbTransaction(); + $this->_db->beginDbTransaction(); } + $this->_recoverFromFailedStateInsert($params, $where, $e); } if ($started) { @@ -1037,22 +1250,68 @@ protected function _saveSyncStateRow(array $params) } /** - * Check if a sync state row exists for the given sync key. + * Decide what to do after the INSERT of a state row failed. * - * @param string $syncKey The sync key. + * Must run in a usable transaction (@see self::_saveSyncStateRow()). + * + * - No row exists under the sync key: the INSERT failed for another + * reason; the failure is passed on. + * - The row belongs to the requesting device, user and folder: a + * parallel request inserted it first; it is updated instead. + * - The row belongs to another device: device change + * (@see self::_isOwnStateRow()). The other device's state must not + * be overwritten, so the failure is passed on. The requesting + * device is reset on its next request by + * self::_assertNextSyncKeyAvailable(). + * + * @author Torben Dannhauer + * + * @param array $params Column data for horde_activesync_state. + * @param array $where The UPDATE condition matching the + * requesting device's own row. + * @param Horde_Db_Exception $e The INSERT failure. * - * @return boolean * @throws Horde_Db_Exception */ - protected function _syncStateExists($syncKey) - { - return (bool) $this->_db->selectValue( - sprintf( - 'SELECT 1 FROM %s WHERE sync_key = ?', - $this->_db->quoteTableName($this->_syncStateTable) - ), - [$syncKey] + protected function _recoverFromFailedStateInsert( + array $params, + array $where, + Horde_Db_Exception $e + ) { + $owner = $this->_syncStateOwner($params['sync_key']); + + if ($owner === null) { + $this->_logger->err( + sprintf( + 'STATE: Persist INSERT failed for synckey %s folder %s: %s', + $params['sync_key'], + $params['sync_folderid'], + $e->getMessage() + ) + ); + throw $e; + } + + if (!$this->_isOwnStateRow($owner)) { + $this->_logger->err( + sprintf( + 'STATE: Synckey %s is already stored for device %s (device change). Not overwriting it with the state of the requesting device %s.', + $params['sync_key'], + $owner['sync_devid'], + $params['sync_devid'] + ) + ); + throw $e; + } + + $this->_logger->meta( + 'STATE: Concurrent insert for synckey ' + . $params['sync_key'] + . '; updating existing row.' ); + if (!$this->_db->updateBlob($this->_syncStateTable, $params, $where)) { + throw $e; + } } /** diff --git a/test/integration/Horde/ActiveSync/StateTest/Mongo/DeviceChangeTest.php b/test/integration/Horde/ActiveSync/StateTest/Mongo/DeviceChangeTest.php new file mode 100644 index 00000000..ba1656a2 --- /dev/null +++ b/test/integration/Horde/ActiveSync/StateTest/Mongo/DeviceChangeTest.php @@ -0,0 +1,466 @@ + + * @copyright 2026 The Horde Project + * @license http://www.horde.org/licenses/gpl GPLv2 + * @category Horde + * @package Horde_ActiveSync + * @subpackage UnitTests + */ + +namespace { + if (!interface_exists('Horde_Mongo_Collection_Index', false)) { + interface Horde_Mongo_Collection_Index + { + public function checkMongoIndices(); + public function createMongoIndices(); + } + } + if (!class_exists('MongoException', false)) { + class MongoException extends Exception {} + } +} + +namespace Horde\ActiveSync\StateTest\Mongo { + + use MongoException; + use PHPUnit\Framework\TestCase; + use Horde_ActiveSync; + use Horde_ActiveSync_Exception; + use Horde_ActiveSync_Exception_StateGone; + use Horde_ActiveSync_Folder_Imap; + use Horde_ActiveSync_Log_Logger; + use Horde_ActiveSync_State_Mongo; + use Horde_Log_Handler_Null; + use ReflectionClass; + + class DeviceChangeTest extends TestCase + { + private const SERIES = '{a1b2c3d4-0000-0000-0000-000000000000}'; + private const FOLDER_ID = 'Ftest'; + private const USER = 'user@example.com'; + private const OLD_DEVICE = 'old-device'; + private const NEW_DEVICE = 'new-device'; + + /** + * Guard 1: the new device presents a sync key that was issued to the + * old device. It must be told the state is gone instead of locking + * and adopting the old device's document. + */ + public function testChangedDeviceCannotLoadSyncKeyOfOtherDevice() + { + $collection = new InMemoryMongoCollection(); + $this->_insertDoc($collection, 23, self::OLD_DEVICE); + + $state = $this->_newState($collection, self::NEW_DEVICE, 23); + try { + $this->_loadState($state); + $this->fail('The sync key of another device must not be loadable.'); + } catch (Horde_ActiveSync_Exception_StateGone $e) { + } + + $this->assertFalse($this->_getProperty($state, '_stateRowLockHeld')); + $this->assertArrayNotHasKey( + Horde_ActiveSync_State_Mongo::SYNC_LOCK, + $collection->docs[self::SERIES . '23'], + 'The document of the other device must not be locked.' + ); + } + + /** + * The device that owns the key still loads it. + */ + public function testOwnSyncKeyIsLoaded() + { + $collection = new InMemoryMongoCollection(); + $this->_insertDoc($collection, 23, self::OLD_DEVICE); + + $state = $this->_newState($collection, self::OLD_DEVICE, 23); + $this->_loadState($state); + + $this->assertTrue($this->_getProperty($state, '_stateRowLockHeld')); + $this->assertSame(1000, $this->_getProperty($state, '_lastSyncStamp')); + } + + /** + * Read-only loads (PING) are exempt from guard 1: peeking at the + * document the key was copied from keeps PING working until the + * client's next SYNC is reset. + */ + public function testReadonlyLoadMayPeekAtSyncKeyOfOtherDevice() + { + $collection = new InMemoryMongoCollection(); + $this->_insertDoc($collection, 23, self::OLD_DEVICE); + + $state = $this->_newState($collection, self::NEW_DEVICE, 23); + $this->_setProperty($state, '_loadReadonly', true); + $this->_loadState($state); + + $this->assertSame(1000, $this->_getProperty($state, '_lastSyncStamp')); + } + + /** + * Guard 2: the old device comes back with its last key, but the new + * device has already stored the next key of that series. The old + * device could never save its next state, so it is reset before the + * document lock is taken. + */ + public function testDeviceIsResetWhenAnotherDeviceContinuedItsKeySeries() + { + $collection = new InMemoryMongoCollection(); + $this->_insertDoc($collection, 23, self::OLD_DEVICE); + $this->_insertDoc($collection, 24, self::NEW_DEVICE); + + $state = $this->_newState($collection, self::OLD_DEVICE, 23); + try { + $this->_loadState($state); + $this->fail('A key series continued by another device must reset the device.'); + } catch (Horde_ActiveSync_Exception_StateGone $e) { + } + + $this->assertFalse($this->_getProperty($state, '_stateRowLockHeld')); + $this->assertArrayNotHasKey( + Horde_ActiveSync_State_Mongo::SYNC_LOCK, + $collection->docs[self::SERIES . '23'], + 'No document lock may be left behind by the rejected load.' + ); + } + + /** + * A next key stored by the same device (the client repeats a request + * whose response it never received) must not reset the device. + */ + public function testOwnNextKeyDoesNotResetDevice() + { + $collection = new InMemoryMongoCollection(); + $this->_insertDoc($collection, 23, self::OLD_DEVICE); + $this->_insertDoc($collection, 24, self::OLD_DEVICE); + + $state = $this->_newState($collection, self::OLD_DEVICE, 23); + $this->_loadState($state); + + $this->assertTrue($this->_getProperty($state, '_stateRowLockHeld')); + } + + /** + * Guard 3: saving never removes or replaces a document that belongs + * to another device. + */ + public function testSaveDoesNotOverwriteStateOfOtherDevice() + { + $collection = new InMemoryMongoCollection(); + $this->_insertDoc($collection, 24, self::NEW_DEVICE); + $before = $collection->docs[self::SERIES . '24']; + + $state = $this->_newState($collection, self::OLD_DEVICE, 24); + $this->_primeForSave($state); + try { + $state->save(); + $this->fail('Saving over the state of another device must fail.'); + } catch (Horde_ActiveSync_Exception $e) { + } + + $this->assertSame($before, $collection->docs[self::SERIES . '24']); + } + + /** + * The previous response was not accepted by the client and the same + * device stores the key again: its own document is replaced. + */ + public function testSaveReplacesOwnExistingState() + { + $collection = new InMemoryMongoCollection(); + $this->_insertDoc($collection, 24, self::OLD_DEVICE); + + $state = $this->_newState($collection, self::OLD_DEVICE, 24); + $this->_primeForSave($state); + $state->save(); + + $doc = $collection->docs[self::SERIES . '24']; + $this->assertSame(self::OLD_DEVICE, $doc[Horde_ActiveSync_State_Mongo::SYNC_DEVID]); + $this->assertSame(2000, $doc[Horde_ActiveSync_State_Mongo::SYNC_MOD]); + } + + /** + * An insert that fails although no document exists for the key is a + * storage error and is reported as such. + */ + public function testSaveReportsInsertFailureWithoutExistingState() + { + $collection = new InMemoryMongoCollection(); + $collection->failInsert = true; + + $state = $this->_newState($collection, self::OLD_DEVICE, 24); + $this->_primeForSave($state); + + $this->expectException(Horde_ActiveSync_Exception::class); + try { + $state->save(); + } finally { + $this->assertSame([], $collection->docs); + } + } + + protected function _newState(InMemoryMongoCollection $collection, $deviceId, $counter) + { + $ref = new ReflectionClass(Horde_ActiveSync_State_Mongo::class); + $state = $ref->newInstanceWithoutConstructor(); + $this->_setProperty($state, '_db', new InMemoryMongoDb($collection)); + + $this->_setProperty( + $state, + '_logger', + new Horde_ActiveSync_Log_Logger(new Horde_Log_Handler_Null()) + ); + // A plain object: a mocked Horde_ActiveSync_Device swallows the + // magic property writes and would report id and user as null. + $this->_setProperty($state, '_deviceInfo', (object) [ + 'id' => $deviceId, + 'user' => self::USER, + ]); + $this->_setProperty($state, '_type', Horde_ActiveSync::REQUEST_TYPE_SYNC); + $this->_setProperty($state, '_syncKey', self::SERIES . $counter); + $this->_setProperty($state, '_collection', [ + 'id' => self::FOLDER_ID, + 'class' => Horde_ActiveSync::CLASS_EMAIL, + ]); + + return $state; + } + + protected function _primeForSave(Horde_ActiveSync_State_Mongo $state) + { + $this->_setProperty( + $state, + '_folder', + new Horde_ActiveSync_Folder_Imap('INBOX', Horde_ActiveSync::CLASS_EMAIL) + ); + $this->_setProperty($state, '_thisSyncStamp', 2000); + $this->_setProperty($state, '_changes', null); + } + + protected function _loadState(Horde_ActiveSync_State_Mongo $state) + { + $ref = new ReflectionClass($state); + $method = $ref->getMethod('_loadState'); + $method->setAccessible(true); + $method->invoke($state); + } + + protected function _insertDoc(InMemoryMongoCollection $collection, $counter, $deviceId) + { + $key = self::SERIES . $counter; + $collection->insert([ + Horde_ActiveSync_State_Mongo::MONGO_ID => $key, + Horde_ActiveSync_State_Mongo::SYNC_KEY => $key, + Horde_ActiveSync_State_Mongo::SYNC_DATA => serialize( + new Horde_ActiveSync_Folder_Imap('INBOX', Horde_ActiveSync::CLASS_EMAIL) + ), + Horde_ActiveSync_State_Mongo::SYNC_DEVID => $deviceId, + Horde_ActiveSync_State_Mongo::SYNC_MOD => 1000, + Horde_ActiveSync_State_Mongo::SYNC_FOLDERID => self::FOLDER_ID, + Horde_ActiveSync_State_Mongo::SYNC_USER => self::USER, + Horde_ActiveSync_State_Mongo::SYNC_PENDING => '', + Horde_ActiveSync_State_Mongo::SYNC_TIMESTAMP => 1, + ]); + } + + protected function _setProperty($object, $name, $value) + { + $ref = new ReflectionClass($object); + $prop = $ref->getProperty($name); + $prop->setAccessible(true); + $prop->setValue($object, $value); + } + + protected function _getProperty($object, $name) + { + $ref = new ReflectionClass($object); + $prop = $ref->getProperty($name); + $prop->setAccessible(true); + return $prop->getValue($object); + } + } + + /** + * In-memory stand-in for the parts of the legacy MongoCollection API the + * state driver uses on HAS_state. Documents are keyed by _id, and a + * second insert for the same _id fails like MongoDB's unique _id index. + * + * Supported query syntax: field equality, $or, $exists and $lt. + */ + class InMemoryMongoCollection + { + /** + * Stored documents, keyed by _id. + * + * @var array + */ + public $docs = []; + + /** + * Make every insert fail, whether or not the _id exists. + * + * @var boolean + */ + public $failInsert = false; + + public function count($query = []) + { + return count($this->_find($query)); + } + + public function findOne($query = [], $fields = []) + { + $ids = $this->_find($query); + + return $ids ? $this->_project($this->docs[$ids[0]], $fields) : null; + } + + public function findAndModify($query, $update = [], $fields = [], $options = []) + { + $ids = $this->_find($query); + if (!$ids) { + return null; + } + $before = $this->docs[$ids[0]]; + $this->_apply($ids[0], $update); + + return $this->_project($before, $fields); + } + + public function update($query, $update, $options = []) + { + $ids = $this->_find($query); + if ($ids) { + $this->_apply($ids[0], $update); + } + + return ['ok' => 1, 'n' => $ids ? 1 : 0]; + } + + public function insert($document) + { + $id = $document['_id']; + if ($this->failInsert) { + throw new MongoException('insert failed'); + } + if (isset($this->docs[$id])) { + throw new MongoException('E11000 duplicate key error', 11000); + } + $this->docs[$id] = $document; + + return ['ok' => 1]; + } + + public function remove($query = []) + { + $ids = $this->_find($query); + foreach ($ids as $id) { + unset($this->docs[$id]); + } + + return ['ok' => 1, 'n' => count($ids)]; + } + + private function _find(array $query) + { + $ids = []; + foreach ($this->docs as $id => $doc) { + if ($this->_matches($doc, $query)) { + $ids[] = $id; + } + } + + return $ids; + } + + private function _matches(array $doc, array $query) + { + foreach ($query as $field => $condition) { + if ($field === '$or') { + $any = false; + foreach ($condition as $alternative) { + $any = $any || $this->_matches($doc, $alternative); + } + if (!$any) { + return false; + } + continue; + } + + $exists = array_key_exists($field, $doc); + if (!is_array($condition)) { + // Like MongoDB, null also matches a missing field. + if (($exists ? $doc[$field] : null) !== $condition) { + return false; + } + continue; + } + foreach ($condition as $operator => $operand) { + if ($operator === '$exists') { + $ok = ($exists === (bool) $operand); + } elseif ($operator === '$lt') { + $ok = $exists && $doc[$field] < $operand; + } else { + throw new \LogicException('Unsupported operator ' . $operator); + } + if (!$ok) { + return false; + } + } + } + + return true; + } + + private function _apply($id, array $update) + { + foreach ($update['$set'] ?? [] as $field => $value) { + $this->docs[$id][$field] = $value; + } + foreach (array_keys($update['$unset'] ?? []) as $field) { + unset($this->docs[$id][$field]); + } + } + + private function _project(array $doc, array $fields) + { + if (!$fields) { + return $doc; + } + + return array_intersect_key($doc, $fields + ['_id' => true]); + } + } + + class InMemoryMongoDb + { + private $_collection; + + public function __construct(InMemoryMongoCollection $collection) + { + $this->_collection = $collection; + } + + public function selectCollection($name) + { + return $this->_collection; + } + } + +} diff --git a/test/unit/Horde/ActiveSync/StateTest/Sql/DeviceChangeTest.php b/test/unit/Horde/ActiveSync/StateTest/Sql/DeviceChangeTest.php new file mode 100644 index 00000000..e48aa9df --- /dev/null +++ b/test/unit/Horde/ActiveSync/StateTest/Sql/DeviceChangeTest.php @@ -0,0 +1,442 @@ + + * @copyright 2026 The Horde Project + * @license http://www.horde.org/licenses/gpl GPLv2 + * @category Horde + * @package Horde_ActiveSync + * @subpackage UnitTests + */ + +namespace Horde\ActiveSync\StateTest\Sql; + +use Horde\ActiveSync\Test\Helpers\DbHelper; +use PHPUnit\Framework\TestCase; +use Horde_ActiveSync; +use Horde_ActiveSync_Exception; +use Horde_ActiveSync_Exception_StateGone; +use Horde_ActiveSync_Folder_Collection; +use Horde_ActiveSync_Folder_Imap; +use Horde_ActiveSync_Log_Logger; +use Horde_ActiveSync_State_Sql; +use Horde_Db_Exception; +use Horde_Db_Value_Binary; +use Horde_Log_Handler_Null; +use ReflectionClass; + +class DeviceChangeTest extends TestCase +{ + private const SERIES = '{a1b2c3d4-0000-0000-0000-000000000000}'; + private const FOLDER_ID = 'Ftest'; + private const USER = 'user@example.com'; + private const OLD_DEVICE = 'old-device'; + private const NEW_DEVICE = 'new-device'; + + /** + * Guard 1: the new device presents a sync key that was issued to the + * old device. It must be told the state is gone (SYNC answers with a + * key mismatch) instead of adopting the old device's key series. + */ + public function testChangedDeviceCannotLoadSyncKeyOfOtherDevice() + { + $db = $this->_db(); + $this->_insertRow($db, 23, self::OLD_DEVICE); + + $state = $this->_newState($db, self::NEW_DEVICE); + try { + $state->loadState( + $this->_collection(), + self::SERIES . '23', + Horde_ActiveSync::REQUEST_TYPE_SYNC, + self::FOLDER_ID + ); + $this->fail('Expected the foreign sync key to be rejected.'); + } catch (Horde_ActiveSync_Exception_StateGone $e) { + // expected + } + + $this->assertFalse($this->_getProperty($state, '_collectionLockHeld')); + $this->assertFalse($db->transactionStarted()); + // The old device's state is untouched. + $this->assertSame(self::OLD_DEVICE, $this->_owner($db, 23)); + } + + /** + * Read-only loads (PING) are exempt: peeking at the copied row keeps + * PING working until the next SYNC for the folder is reset. + */ + public function testReadonlyLoadMayPeekAtSyncKeyOfOtherDevice() + { + $db = $this->_db(); + $this->_insertRow($db, 23, self::OLD_DEVICE); + + $state = $this->_newState($db, self::NEW_DEVICE); + $state->loadState( + $this->_collection(), + self::SERIES . '23', + Horde_ActiveSync::REQUEST_TYPE_SYNC, + self::FOLDER_ID, + ['readonly' => true] + ); + + $this->assertInstanceOf( + Horde_ActiveSync_Folder_Collection::class, + $this->_getProperty($state, '_folder') + ); + $this->assertFalse($this->_getProperty($state, '_collectionLockHeld')); + } + + /** + * Guard 2: the new device already continued the old device's series + * (key 24 is its row). The old device, still at key 23, can never store + * key 24 and must be reset - without losing the new device's state. + */ + public function testDeviceIsResetWhenAnotherDeviceContinuedItsKeySeries() + { + $db = $this->_db(); + $this->_insertRow($db, 23, self::OLD_DEVICE); + $this->_insertRow($db, 24, self::NEW_DEVICE); + + $state = $this->_newState($db, self::OLD_DEVICE); + try { + $state->loadState( + $this->_collection(), + self::SERIES . '23', + Horde_ActiveSync::REQUEST_TYPE_SYNC, + self::FOLDER_ID + ); + $this->fail('Expected the taken-over key series to be rejected.'); + } catch (Horde_ActiveSync_Exception_StateGone $e) { + // expected + } + $this->assertFalse($this->_getProperty($state, '_collectionLockHeld')); + + // The client now restarts the folder with sync key 0. + $state->loadState( + $this->_collection(), + 0, + Horde_ActiveSync::REQUEST_TYPE_SYNC, + self::FOLDER_ID + ); + + $this->assertNull($this->_owner($db, 23)); + $this->assertSame(self::NEW_DEVICE, $this->_owner($db, 24)); + } + + /** + * A next key owned by the same device is a repeated request (the + * client never received the response), not a device change. + */ + public function testOwnNextKeyDoesNotResetDevice() + { + $db = $this->_db(); + $this->_insertRow($db, 23, self::OLD_DEVICE); + $this->_insertRow($db, 24, self::OLD_DEVICE); + + $state = $this->_newState($db, self::OLD_DEVICE); + $state->loadState( + $this->_collection(), + self::SERIES . '23', + Horde_ActiveSync::REQUEST_TYPE_SYNC, + self::FOLDER_ID + ); + + $state->setNewSyncKey(self::SERIES . '24'); + $this->_setProperty($state, '_thisSyncStamp', 9); + $state->save(); + + $this->assertSame( + '9', + (string) $db->selectValue( + 'SELECT sync_mod FROM horde_activesync_state WHERE sync_key = ?', + [self::SERIES . '24'] + ) + ); + $this->assertFalse($db->transactionStarted()); + } + + /** + * Guard 3: a save must never overwrite the row of another device. + */ + public function testSaveDoesNotOverwriteStateOfOtherDevice() + { + $db = $this->_db(); + $this->_insertRow($db, 24, self::NEW_DEVICE, 7); + + $state = $this->_newState($db, self::OLD_DEVICE); + $this->_primeForSave($state, self::SERIES . '24'); + + try { + $state->save(); + $this->fail('Expected the save over a foreign row to fail.'); + } catch (Horde_ActiveSync_Exception $e) { + // expected + } + + $this->assertFalse($db->transactionStarted()); + $this->assertSame(self::NEW_DEVICE, $this->_owner($db, 24)); + $this->assertSame( + '7', + (string) $db->selectValue( + 'SELECT sync_mod FROM horde_activesync_state WHERE sync_key = ?', + [self::SERIES . '24'] + ) + ); + } + + /** + * PostgreSQL aborts the transaction when the INSERT fails; any further + * statement is rejected (SQLSTATE 25P02) until it is rolled back. A + * parallel request of the same device having inserted the row first + * must still be recovered: roll back, start over, update. + */ + public function testSaveRecoversFromConcurrentInsertInAbortedTransaction() + { + $db = $this->_abortingDb([ + 'sync_devid' => self::OLD_DEVICE, + 'sync_user' => self::USER, + 'sync_folderid' => self::FOLDER_ID, + ]); + $db->expects($this->exactly(2))->method('beginDbTransaction'); + $db->expects($this->exactly(2))->method('updateBlob'); + $db->expects($this->once())->method('commitDbTransaction'); + + $state = $this->_newState($db, self::OLD_DEVICE); + $this->_primeForSave($state, self::SERIES . '24'); + + $state->save(); + + $this->assertSame(1, $this->_rollbacks); + } + + /** + * Same aborted transaction, but the existing row belongs to another + * device: no second UPDATE, the save fails and nothing is committed. + */ + public function testSaveLeavesForeignRowAloneInAbortedTransaction() + { + $db = $this->_abortingDb([ + 'sync_devid' => self::NEW_DEVICE, + 'sync_user' => self::USER, + 'sync_folderid' => self::FOLDER_ID, + ]); + $db->expects($this->once())->method('updateBlob'); + $db->expects($this->never())->method('commitDbTransaction'); + + $state = $this->_newState($db, self::OLD_DEVICE); + $this->_primeForSave($state, self::SERIES . '24'); + + try { + $state->save(); + $this->fail('Expected the save over a foreign row to fail.'); + } catch (Horde_ActiveSync_Exception $e) { + // expected + } + + // Once to leave the aborted transaction, once for the failed save. + $this->assertSame(2, $this->_rollbacks); + } + + /** + * An INSERT that failed although no row exists under the key is a + * genuine failure and must surface. + */ + public function testSaveReportsInsertFailureWithoutExistingRow() + { + $db = $this->_abortingDb(null); + $db->expects($this->once())->method('updateBlob'); + $db->expects($this->never())->method('commitDbTransaction'); + + $state = $this->_newState($db, self::OLD_DEVICE); + $this->_primeForSave($state, self::SERIES . '24'); + + $this->expectException(Horde_ActiveSync_Exception::class); + $state->save(); + } + + /** + * Number of rollbacks seen by the adapter from _abortingDb(). + * + * @var integer + */ + protected $_rollbacks = 0; + + /** + * Mock adapter behaving like PostgreSQL around a failed INSERT: the + * first UPDATE matches no row, the INSERT fails, and from then on every + * statement fails with SQLSTATE 25P02 until the transaction is rolled + * back. + * + * @param array|null $owner The row returned by the owner lookup. + * + * @return \PHPUnit\Framework\MockObject\MockObject + */ + protected function _abortingDb(?array $owner) + { + $aborted = false; + $updates = 0; + $this->_rollbacks = 0; + $failIfAborted = function () use (&$aborted) { + if ($aborted) { + throw new Horde_Db_Exception( + 'SQLSTATE[25P02]: In failed sql transaction' + ); + } + }; + + $db = $this->getMockBuilder('Horde_Db_Adapter') + ->disableOriginalConstructor() + ->getMock(); + $db->method('transactionStarted')->willReturn(false); + $db->method('updateBlob')->willReturnCallback( + function () use ($failIfAborted, &$updates) { + $failIfAborted(); + return $updates++ ? 1 : 0; + } + ); + $db->method('insertBlob')->willReturnCallback( + function () use (&$aborted) { + $aborted = true; + throw new Horde_Db_Exception('SQLSTATE[23505]: Unique violation'); + } + ); + $db->method('selectOne')->willReturnCallback( + function () use ($failIfAborted, $owner) { + $failIfAborted(); + return $owner; + } + ); + $db->method('rollbackDbTransaction')->willReturnCallback( + function () use (&$aborted) { + $aborted = false; + $this->_rollbacks++; + } + ); + + return $db; + } + + protected function _db() + { + if (!extension_loaded('pdo_sqlite')) { + $this->markTestSkipped('PDO SQLite extension is not loaded'); + } + + $db = DbHelper::createSqliteDb([ + 'migrations' => [[ + 'migrationsPath' => dirname(__DIR__, 6) . '/migration/Horde/ActiveSync', + 'schemaTableName' => 'horde_activesync_schema_info', + ]], + ]); + + // The SQLite schema produced by the migrations ends up without the + // primary key on sync_key that PostgreSQL has. That constraint is + // what makes a shared key series fail, so add it back here. + $db->execute( + 'CREATE UNIQUE INDEX test_state_sync_key' + . ' ON horde_activesync_state (sync_key)' + ); + + return $db; + } + + protected function _collection() + { + return [ + 'id' => self::FOLDER_ID, + 'class' => Horde_ActiveSync::CLASS_CONTACTS, + 'serverid' => self::FOLDER_ID, + ]; + } + + protected function _insertRow($db, $counter, $device, $mod = 1) + { + $folder = new Horde_ActiveSync_Folder_Collection( + self::FOLDER_ID, + Horde_ActiveSync::CLASS_CONTACTS + ); + $db->insertBlob('horde_activesync_state', [ + 'sync_key' => self::SERIES . $counter, + 'sync_data' => new Horde_Db_Value_Binary(serialize($folder)), + 'sync_devid' => $device, + 'sync_mod' => $mod, + 'sync_folderid' => self::FOLDER_ID, + 'sync_user' => self::USER, + 'sync_pending' => '', + 'sync_timestamp' => time(), + ]); + } + + /** + * Return the device owning the state row of a key, or null if the row + * does not exist. + */ + protected function _owner($db, $counter) + { + $devid = $db->selectValue( + 'SELECT sync_devid FROM horde_activesync_state WHERE sync_key = ?', + [self::SERIES . $counter] + ); + + return $devid ? (string) $devid : null; + } + + protected function _newState($db, $device) + { + $state = new Horde_ActiveSync_State_Sql(['db' => $db]); + $this->_setProperty( + $state, + '_logger', + new Horde_ActiveSync_Log_Logger(new Horde_Log_Handler_Null()) + ); + $this->_setProperty($state, '_deviceInfo', (object) [ + 'id' => $device, + 'user' => self::USER, + ]); + + return $state; + } + + protected function _primeForSave(Horde_ActiveSync_State_Sql $state, $syncKey) + { + $folder = new Horde_ActiveSync_Folder_Imap('INBOX', Horde_ActiveSync::CLASS_EMAIL); + $this->_setProperty($state, '_type', Horde_ActiveSync::REQUEST_TYPE_SYNC); + $this->_setProperty($state, '_folder', $folder); + $this->_setProperty($state, '_syncKey', $syncKey); + $this->_setProperty($state, '_collection', [ + 'id' => self::FOLDER_ID, + 'class' => Horde_ActiveSync::CLASS_EMAIL, + ]); + $this->_setProperty($state, '_thisSyncStamp', 100); + $this->_setProperty($state, '_changes', null); + } + + protected function _getProperty($object, $name) + { + $ref = new ReflectionClass($object); + $prop = $ref->getProperty($name); + $prop->setAccessible(true); + return $prop->getValue($object); + } + + protected function _setProperty($object, $name, $value) + { + $ref = new ReflectionClass($object); + $prop = $ref->getProperty($name); + $prop->setAccessible(true); + $prop->setValue($object, $value); + } +} From 8001ede023bcd810c33028b5965ade9130a58d75 Mon Sep 17 00:00:00 2001 From: Torben Dannhauer Date: Thu, 12 Nov 2026 11:05:48 +0100 Subject: [PATCH 2/2] fix(activesync): log failed state saves through the ActiveSync logger The failure path of State_Sql::_saveSyncStateRow() called the static Horde::log(). That class belongs to horde/core, which is not a dependency of this package: where it is not installed, a failed save ended in "Class Horde not found" instead of the intended Horde_ActiveSync_Exception. Use the injected logger like the rest of the class. --- lib/Horde/ActiveSync/State/Sql.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/Horde/ActiveSync/State/Sql.php b/lib/Horde/ActiveSync/State/Sql.php index 516e4b01..83b6bd53 100644 --- a/lib/Horde/ActiveSync/State/Sql.php +++ b/lib/Horde/ActiveSync/State/Sql.php @@ -1244,7 +1244,7 @@ protected function _saveSyncStateRow(array $params) } } - Horde::log($e, 'ERR'); + $this->_logger->err($e->getMessage()); throw new Horde_ActiveSync_Exception($e); } }