SwiftObjectServerTests.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2016 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. import XCTest
  19. import RealmSwift
  20. // Used by testOfflineClientReset
  21. // The naming here is nonstandard as the sync-1.x.realm test file comes from the .NET unit tests.
  22. // swiftlint:disable identifier_name
  23. @objc(Person)
  24. class Person: Object {
  25. @objc dynamic var FirstName: String?
  26. @objc dynamic var LastName: String?
  27. override class func shouldIncludeInDefaultSchema() -> Bool { return false }
  28. }
  29. class SwiftObjectServerTests: SwiftSyncTestCase {
  30. /// It should be possible to successfully open a Realm configured for sync.
  31. func testBasicSwiftSync() {
  32. let url = URL(string: "realm://127.0.0.1:9080/~/testBasicSync")!
  33. do {
  34. let user = try synchronouslyLogInUser(for: basicCredentials(register: true), server: authURL)
  35. let realm = try synchronouslyOpenRealm(url: url, user: user)
  36. XCTAssert(realm.isEmpty, "Freshly synced Realm was not empty...")
  37. } catch {
  38. XCTFail("Got an error: \(error)")
  39. }
  40. }
  41. /// If client B adds objects to a Realm, client A should see those new objects.
  42. func testSwiftAddObjects() {
  43. do {
  44. let user = try synchronouslyLogInUser(for: basicCredentials(register: isParent), server: authURL)
  45. let realm = try synchronouslyOpenRealm(url: realmURL, user: user)
  46. if isParent {
  47. waitForDownloads(for: realm)
  48. checkCount(expected: 0, realm, SwiftSyncObject.self)
  49. executeChild()
  50. waitForDownloads(for: realm)
  51. checkCount(expected: 3, realm, SwiftSyncObject.self)
  52. } else {
  53. // Add objects
  54. try realm.write {
  55. realm.add(SwiftSyncObject(value: ["child-1"]))
  56. realm.add(SwiftSyncObject(value: ["child-2"]))
  57. realm.add(SwiftSyncObject(value: ["child-3"]))
  58. }
  59. waitForUploads(for: realm)
  60. checkCount(expected: 3, realm, SwiftSyncObject.self)
  61. }
  62. } catch {
  63. XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
  64. }
  65. }
  66. /// If client B removes objects from a Realm, client A should see those changes.
  67. func testSwiftDeleteObjects() {
  68. do {
  69. let user = try synchronouslyLogInUser(for: basicCredentials(register: isParent), server: authURL)
  70. let realm = try synchronouslyOpenRealm(url: realmURL, user: user)
  71. if isParent {
  72. try realm.write {
  73. realm.add(SwiftSyncObject(value: ["child-1"]))
  74. realm.add(SwiftSyncObject(value: ["child-2"]))
  75. realm.add(SwiftSyncObject(value: ["child-3"]))
  76. }
  77. waitForUploads(for: realm)
  78. checkCount(expected: 3, realm, SwiftSyncObject.self)
  79. executeChild()
  80. waitForDownloads(for: realm)
  81. checkCount(expected: 0, realm, SwiftSyncObject.self)
  82. } else {
  83. try realm.write {
  84. realm.deleteAll()
  85. }
  86. waitForUploads(for: realm)
  87. checkCount(expected: 0, realm, SwiftSyncObject.self)
  88. }
  89. } catch {
  90. XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
  91. }
  92. }
  93. func testConnectionState() {
  94. let user = try! synchronouslyLogInUser(for: basicCredentials(register: true), server: authURL)
  95. let realm = try! synchronouslyOpenRealm(url: realmURL, user: user)
  96. let session = realm.syncSession!
  97. func wait(forState desiredState: SyncSession.ConnectionState) {
  98. let ex = expectation(description: "Wait for connection state: \(desiredState)")
  99. let token = session.observe(\SyncSession.connectionState, options: .initial) { s, _ in
  100. if s.connectionState == desiredState {
  101. ex.fulfill()
  102. }
  103. }
  104. waitForExpectations(timeout: 2.0)
  105. token.invalidate()
  106. }
  107. wait(forState: .connected)
  108. session.suspend()
  109. wait(forState: .disconnected)
  110. session.resume()
  111. wait(forState: .connecting)
  112. wait(forState: .connected)
  113. }
  114. // MARK: - Client reset
  115. func testClientReset() {
  116. do {
  117. let user = try synchronouslyLogInUser(for: basicCredentials(register: isParent), server: authURL)
  118. let realm = try synchronouslyOpenRealm(url: realmURL, user: user)
  119. var theError: SyncError?
  120. let ex = expectation(description: "Waiting for error handler to be called...")
  121. SyncManager.shared.errorHandler = { (error, session) in
  122. if let error = error as? SyncError {
  123. theError = error
  124. } else {
  125. XCTFail("Error \(error) was not a sync error. Something is wrong.")
  126. }
  127. ex.fulfill()
  128. }
  129. user.simulateClientResetError(forSession: realmURL)
  130. waitForExpectations(timeout: 10, handler: nil)
  131. XCTAssertNotNil(theError)
  132. XCTAssertTrue(theError!.code == SyncError.Code.clientResetError)
  133. let resetInfo = theError!.clientResetInfo()
  134. XCTAssertNotNil(resetInfo)
  135. XCTAssertTrue(resetInfo!.0.contains("io.realm.object-server-recovered-realms/recovered_realm"))
  136. XCTAssertNotNil(realm)
  137. } catch {
  138. XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
  139. }
  140. }
  141. func testClientResetManualInitiation() {
  142. do {
  143. let user = try synchronouslyLogInUser(for: basicCredentials(register: isParent), server: authURL)
  144. var theError: SyncError?
  145. try autoreleasepool {
  146. let realm = try synchronouslyOpenRealm(url: realmURL, user: user)
  147. let ex = expectation(description: "Waiting for error handler to be called...")
  148. SyncManager.shared.errorHandler = { (error, session) in
  149. if let error = error as? SyncError {
  150. theError = error
  151. } else {
  152. XCTFail("Error \(error) was not a sync error. Something is wrong.")
  153. }
  154. ex.fulfill()
  155. }
  156. user.simulateClientResetError(forSession: realmURL)
  157. waitForExpectations(timeout: 10, handler: nil)
  158. XCTAssertNotNil(theError)
  159. XCTAssertNotNil(realm)
  160. }
  161. let (path, errorToken) = theError!.clientResetInfo()!
  162. XCTAssertFalse(FileManager.default.fileExists(atPath: path))
  163. SyncSession.immediatelyHandleError(errorToken)
  164. XCTAssertTrue(FileManager.default.fileExists(atPath: path))
  165. } catch {
  166. XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
  167. }
  168. }
  169. // MARK: - Progress notifiers
  170. let bigObjectCount = 2
  171. func populateRealm(user: SyncUser, url: URL) {
  172. let realm = try! synchronouslyOpenRealm(url: realmURL, user: user)
  173. try! realm.write {
  174. for _ in 0..<bigObjectCount {
  175. realm.add(SwiftHugeSyncObject())
  176. }
  177. }
  178. waitForUploads(for: realm)
  179. checkCount(expected: bigObjectCount, realm, SwiftHugeSyncObject.self)
  180. }
  181. func testStreamingDownloadNotifier() {
  182. let user = try! synchronouslyLogInUser(for: basicCredentials(register: isParent), server: authURL)
  183. if !isParent {
  184. populateRealm(user: user, url: realmURL)
  185. return
  186. }
  187. var callCount = 0
  188. var transferred = 0
  189. var transferrable = 0
  190. let realm = try! synchronouslyOpenRealm(url: realmURL, user: user)
  191. let session = realm.syncSession
  192. XCTAssertNotNil(session)
  193. let ex = expectation(description: "streaming-downloads-expectation")
  194. var hasBeenFulfilled = false
  195. let token = session!.addProgressNotification(for: .download, mode: .reportIndefinitely) { p in
  196. callCount += 1
  197. XCTAssert(p.transferredBytes >= transferred)
  198. XCTAssert(p.transferrableBytes >= transferrable)
  199. transferred = p.transferredBytes
  200. transferrable = p.transferrableBytes
  201. if p.transferredBytes > 0 && p.isTransferComplete && !hasBeenFulfilled {
  202. ex.fulfill()
  203. hasBeenFulfilled = true
  204. }
  205. }
  206. // Wait for the child process to upload all the data.
  207. executeChild()
  208. waitForExpectations(timeout: 10.0, handler: nil)
  209. token!.invalidate()
  210. XCTAssert(callCount > 1)
  211. XCTAssert(transferred >= transferrable)
  212. }
  213. func testStreamingUploadNotifier() {
  214. do {
  215. var transferred = 0
  216. var transferrable = 0
  217. let user = try synchronouslyLogInUser(for: basicCredentials(register: isParent), server: authURL)
  218. let realm = try synchronouslyOpenRealm(url: realmURL, user: user)
  219. let session = realm.syncSession
  220. XCTAssertNotNil(session)
  221. var ex = expectation(description: "initial upload")
  222. let token = session!.addProgressNotification(for: .upload, mode: .reportIndefinitely) { p in
  223. XCTAssert(p.transferredBytes >= transferred)
  224. XCTAssert(p.transferrableBytes >= transferrable)
  225. transferred = p.transferredBytes
  226. transferrable = p.transferrableBytes
  227. if p.transferredBytes > 0 && p.isTransferComplete {
  228. ex.fulfill()
  229. }
  230. }
  231. waitForExpectations(timeout: 10.0, handler: nil)
  232. ex = expectation(description: "write transaction upload")
  233. try realm.write {
  234. for _ in 0..<bigObjectCount {
  235. realm.add(SwiftHugeSyncObject())
  236. }
  237. }
  238. waitForExpectations(timeout: 10.0, handler: nil)
  239. token!.invalidate()
  240. XCTAssert(transferred >= transferrable)
  241. } catch {
  242. XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
  243. }
  244. }
  245. // MARK: - Download Realm
  246. func testDownloadRealm() {
  247. let user = try! synchronouslyLogInUser(for: basicCredentials(register: isParent), server: authURL)
  248. if !isParent {
  249. populateRealm(user: user, url: realmURL)
  250. return
  251. }
  252. // Wait for the child process to upload everything.
  253. executeChild()
  254. let ex = expectation(description: "download-realm")
  255. let config = user.configuration(realmURL: realmURL, fullSynchronization: true)
  256. let pathOnDisk = ObjectiveCSupport.convert(object: config).pathOnDisk
  257. XCTAssertFalse(FileManager.default.fileExists(atPath: pathOnDisk))
  258. Realm.asyncOpen(configuration: config) { realm, error in
  259. XCTAssertNil(error)
  260. self.checkCount(expected: self.bigObjectCount, realm!, SwiftHugeSyncObject.self)
  261. ex.fulfill()
  262. }
  263. func fileSize(path: String) -> Int {
  264. if let attr = try? FileManager.default.attributesOfItem(atPath: path) {
  265. return attr[.size] as! Int
  266. }
  267. return 0
  268. }
  269. XCTAssertFalse(RLMHasCachedRealmForPath(pathOnDisk))
  270. waitForExpectations(timeout: 10.0, handler: nil)
  271. XCTAssertGreaterThan(fileSize(path: pathOnDisk), 0)
  272. XCTAssertFalse(RLMHasCachedRealmForPath(pathOnDisk))
  273. }
  274. func testCancelDownloadRealm() {
  275. let user = try! synchronouslyLogInUser(for: basicCredentials(register: isParent), server: authURL)
  276. if !isParent {
  277. populateRealm(user: user, url: realmURL)
  278. return
  279. }
  280. // Wait for the child process to upload everything.
  281. executeChild()
  282. // Use a serial queue for asyncOpen to ensure that the first one adds
  283. // the completion block before the second one cancels it
  284. RLMSetAsyncOpenQueue(DispatchQueue(label: "io.realm.asyncOpen"))
  285. let ex = expectation(description: "async open")
  286. let config = user.configuration(realmURL: realmURL, fullSynchronization: true)
  287. Realm.asyncOpen(configuration: config) { _, error in
  288. XCTAssertNotNil(error)
  289. ex.fulfill()
  290. }
  291. let task = Realm.asyncOpen(configuration: config) { _, _ in
  292. XCTFail("Cancelled completion handler was called")
  293. }
  294. task.cancel()
  295. waitForExpectations(timeout: 10.0, handler: nil)
  296. }
  297. func testAsyncOpenProgress() {
  298. let user = try! synchronouslyLogInUser(for: basicCredentials(register: isParent), server: authURL)
  299. if !isParent {
  300. populateRealm(user: user, url: realmURL)
  301. return
  302. }
  303. // Wait for the child process to upload everything.
  304. executeChild()
  305. let ex1 = expectation(description: "async open")
  306. let ex2 = expectation(description: "download progress")
  307. let config = user.configuration(realmURL: realmURL, fullSynchronization: true)
  308. let task = Realm.asyncOpen(configuration: config) { _, error in
  309. XCTAssertNil(error)
  310. ex1.fulfill()
  311. }
  312. task.addProgressNotification { progress in
  313. if progress.isTransferComplete {
  314. ex2.fulfill()
  315. }
  316. }
  317. waitForExpectations(timeout: 10.0, handler: nil)
  318. }
  319. // MARK: - Administration
  320. func testRetrieveUserInfo() {
  321. let adminUsername = "jyaku.swift"
  322. let nonAdminUsername = "meela.swift@realm.example.org"
  323. let password = "p"
  324. let server = SwiftObjectServerTests.authServerURL()
  325. // Create a non-admin user.
  326. _ = logInUser(for: .init(username: nonAdminUsername, password: password, register: true),
  327. server: server)
  328. // Create an admin user.
  329. let adminUser = createAdminUser(for: server, username: adminUsername)
  330. // Look up information about the non-admin user from the admin user.
  331. let ex = expectation(description: "Should be able to look up user information")
  332. adminUser.retrieveInfo(forUser: nonAdminUsername, identityProvider: .usernamePassword) { (userInfo, err) in
  333. XCTAssertNil(err)
  334. XCTAssertNotNil(userInfo)
  335. guard let userInfo = userInfo else {
  336. return
  337. }
  338. let account = userInfo.accounts.first!
  339. XCTAssertEqual(account.providerUserIdentity, nonAdminUsername)
  340. XCTAssertEqual(account.provider, Provider.usernamePassword)
  341. XCTAssertFalse(userInfo.isAdmin)
  342. ex.fulfill()
  343. }
  344. waitForExpectations(timeout: 10.0, handler: nil)
  345. }
  346. // MARK: - Authentication
  347. func testInvalidCredentials() {
  348. do {
  349. let username = "testInvalidCredentialsUsername"
  350. let credentials = SyncCredentials.usernamePassword(username: username,
  351. password: "THIS_IS_A_PASSWORD",
  352. register: true)
  353. _ = try synchronouslyLogInUser(for: credentials, server: authURL)
  354. // Now log in the same user, but with a bad password.
  355. let ex = expectation(description: "wait for user login")
  356. let credentials2 = SyncCredentials.usernamePassword(username: username, password: "NOT_A_VALID_PASSWORD")
  357. SyncUser.logIn(with: credentials2, server: authURL) { user, error in
  358. XCTAssertNil(user)
  359. XCTAssertTrue(error is SyncAuthError)
  360. let castError = error as! SyncAuthError
  361. XCTAssertEqual(castError.code, SyncAuthError.invalidCredential)
  362. ex.fulfill()
  363. }
  364. waitForExpectations(timeout: 2.0, handler: nil)
  365. } catch {
  366. XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
  367. }
  368. }
  369. // MARK: - User-specific functionality
  370. func testUserExpirationCallback() {
  371. do {
  372. let user = try synchronouslyLogInUser(for: basicCredentials(), server: authURL)
  373. // Set a callback on the user
  374. var blockCalled = false
  375. let ex = expectation(description: "Error callback should fire upon receiving an error")
  376. user.errorHandler = { (u, error) in
  377. XCTAssertEqual(u.identity, user.identity)
  378. XCTAssertEqual(error.code, .accessDeniedOrInvalidPath)
  379. blockCalled = true
  380. ex.fulfill()
  381. }
  382. // Screw up the token on the user.
  383. manuallySetRefreshToken(for: user, value: "not-a-real-token")
  384. // Try to open a Realm with the user; this will cause our errorHandler block defined above to be fired.
  385. XCTAssertFalse(blockCalled)
  386. _ = try immediatelyOpenRealm(url: realmURL, user: user)
  387. waitForExpectations(timeout: 10.0, handler: nil)
  388. XCTAssertEqual(user.state, .loggedOut)
  389. } catch {
  390. XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
  391. }
  392. }
  393. // MARK: - Offline client reset
  394. func testOfflineClientReset() {
  395. let user = try! synchronouslyLogInUser(for: basicCredentials(), server: authURL)
  396. let sourceFileURL = Bundle(for: type(of: self)).url(forResource: "sync-1.x", withExtension: "realm")!
  397. let fileName = "\(UUID()).realm"
  398. let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
  399. try! FileManager.default.copyItem(at: sourceFileURL, to: fileURL)
  400. let syncConfig = RLMSyncConfiguration(user: user, realmURL: realmURL)
  401. syncConfig.customFileURL = fileURL
  402. let config = Realm.Configuration(syncConfiguration: ObjectiveCSupport.convert(object: syncConfig))
  403. do {
  404. _ = try Realm(configuration: config)
  405. } catch let e as Realm.Error where e.code == .incompatibleSyncedFile {
  406. var backupConfiguration = e.backupConfiguration
  407. XCTAssertNotNil(backupConfiguration)
  408. // Open the backup Realm with a schema subset since it was created using the schema from .NET's unit tests.
  409. backupConfiguration!.objectTypes = [Person.self]
  410. let backupRealm = try! Realm(configuration: backupConfiguration!)
  411. let people = backupRealm.objects(Person.self)
  412. XCTAssertEqual(people.count, 1)
  413. XCTAssertEqual(people[0].FirstName, "John")
  414. XCTAssertEqual(people[0].LastName, "Smith")
  415. // Verify that we can now successfully open the original synced Realm.
  416. _ = try! Realm(configuration: config)
  417. } catch {
  418. fatalError("Unexpected error: \(error)")
  419. }
  420. }
  421. // MARK: - Certificate Pinning
  422. func testSecureConnectionToLocalhostWithDefaultSecurity() {
  423. let user = try! synchronouslyLogInUser(for: basicCredentials(), server: authURL)
  424. let config = user.configuration(realmURL: URL(string: "realms://localhost:9443/~/default"),
  425. serverValidationPolicy: .system)
  426. let ex = expectation(description: "Waiting for error handler to be called")
  427. SyncManager.shared.errorHandler = { (error, session) in
  428. ex.fulfill()
  429. }
  430. _ = try! Realm(configuration: config)
  431. self.waitForExpectations(timeout: 4.0)
  432. }
  433. func testSecureConnectionToLocalhostWithValidationDisabled() {
  434. let user = try! synchronouslyLogInUser(for: basicCredentials(), server: authURL)
  435. let config = user.configuration(realmURL: URL(string: "realms://localhost:9443/~/default"),
  436. serverValidationPolicy: .none)
  437. SyncManager.shared.errorHandler = { (error, session) in
  438. XCTFail("Unexpected connection failure: \(error)")
  439. }
  440. let realm = try! Realm(configuration: config)
  441. self.waitForUploads(for: realm)
  442. }
  443. func testSecureConnectionToLocalhostWithPinnedCertificate() {
  444. let user = try! synchronouslyLogInUser(for: basicCredentials(), server: authURL)
  445. let certURL = URL(string: #file)!
  446. .deletingLastPathComponent()
  447. .appendingPathComponent("certificates")
  448. .appendingPathComponent("localhost.cer")
  449. let config = user.configuration(realmURL: URL(string: "realms://localhost:9443/~/default"),
  450. serverValidationPolicy: .pinCertificate(path: certURL))
  451. SyncManager.shared.errorHandler = { (error, session) in
  452. XCTFail("Unexpected connection failure: \(error)")
  453. }
  454. let realm = try! Realm(configuration: config)
  455. self.waitForUploads(for: realm)
  456. }
  457. func testSecureConnectionToLocalhostWithIncorrectPinnedCertificate() {
  458. let user = try! synchronouslyLogInUser(for: basicCredentials(), server: authURL)
  459. let certURL = URL(string: #file)!
  460. .deletingLastPathComponent()
  461. .appendingPathComponent("certificates")
  462. .appendingPathComponent("localhost-other.cer")
  463. let config = user.configuration(realmURL: URL(string: "realms://localhost:9443/~/default"),
  464. serverValidationPolicy: .pinCertificate(path: certURL))
  465. let ex = expectation(description: "Waiting for error handler to be called")
  466. SyncManager.shared.errorHandler = { (error, session) in
  467. ex.fulfill()
  468. }
  469. _ = try! Realm(configuration: config)
  470. self.waitForExpectations(timeout: 4.0)
  471. }
  472. }