SwiftObjectServerTests.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. func testStreamingDownloadNotifier() {
  171. let bigObjectCount = 2
  172. do {
  173. var callCount = 0
  174. var transferred = 0
  175. var transferrable = 0
  176. let user = try synchronouslyLogInUser(for: basicCredentials(register: isParent), server: authURL)
  177. let realm = try synchronouslyOpenRealm(url: realmURL, user: user)
  178. if isParent {
  179. let session = realm.syncSession
  180. XCTAssertNotNil(session)
  181. let ex = expectation(description: "streaming-downloads-expectation")
  182. var hasBeenFulfilled = false
  183. let token = session!.addProgressNotification(for: .download, mode: .reportIndefinitely) { p in
  184. callCount += 1
  185. XCTAssert(p.transferredBytes >= transferred)
  186. XCTAssert(p.transferrableBytes >= transferrable)
  187. transferred = p.transferredBytes
  188. transferrable = p.transferrableBytes
  189. if p.transferredBytes > 0 && p.isTransferComplete && !hasBeenFulfilled {
  190. ex.fulfill()
  191. hasBeenFulfilled = true
  192. }
  193. }
  194. // Wait for the child process to upload all the data.
  195. executeChild()
  196. waitForExpectations(timeout: 10.0, handler: nil)
  197. token!.invalidate()
  198. XCTAssert(callCount > 1)
  199. XCTAssert(transferred >= transferrable)
  200. } else {
  201. try realm.write {
  202. for _ in 0..<bigObjectCount {
  203. realm.add(SwiftHugeSyncObject())
  204. }
  205. }
  206. waitForUploads(for: realm)
  207. checkCount(expected: bigObjectCount, realm, SwiftHugeSyncObject.self)
  208. }
  209. } catch {
  210. XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
  211. }
  212. }
  213. func testStreamingUploadNotifier() {
  214. let bigObjectCount = 2
  215. do {
  216. var transferred = 0
  217. var transferrable = 0
  218. let user = try synchronouslyLogInUser(for: basicCredentials(register: isParent), server: authURL)
  219. let realm = try synchronouslyOpenRealm(url: realmURL, user: user)
  220. let session = realm.syncSession
  221. XCTAssertNotNil(session)
  222. var ex = expectation(description: "initial upload")
  223. let token = session!.addProgressNotification(for: .upload, mode: .reportIndefinitely) { p in
  224. XCTAssert(p.transferredBytes >= transferred)
  225. XCTAssert(p.transferrableBytes >= transferrable)
  226. transferred = p.transferredBytes
  227. transferrable = p.transferrableBytes
  228. if p.transferredBytes > 0 && p.isTransferComplete {
  229. ex.fulfill()
  230. }
  231. }
  232. waitForExpectations(timeout: 10.0, handler: nil)
  233. ex = expectation(description: "write transaction upload")
  234. try realm.write {
  235. for _ in 0..<bigObjectCount {
  236. realm.add(SwiftHugeSyncObject())
  237. }
  238. }
  239. waitForExpectations(timeout: 10.0, handler: nil)
  240. token!.invalidate()
  241. XCTAssert(transferred >= transferrable)
  242. } catch {
  243. XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
  244. }
  245. }
  246. // MARK: - Download Realm
  247. func testDownloadRealm() {
  248. let bigObjectCount = 2
  249. do {
  250. let user = try synchronouslyLogInUser(for: basicCredentials(register: isParent), server: authURL)
  251. if isParent {
  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: 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. } else {
  274. let realm = try synchronouslyOpenRealm(url: realmURL, user: user)
  275. // Write lots of data to the Realm, then wait for it to be uploaded.
  276. try realm.write {
  277. for _ in 0..<bigObjectCount {
  278. realm.add(SwiftHugeSyncObject())
  279. }
  280. }
  281. waitForUploads(for: realm)
  282. checkCount(expected: bigObjectCount, realm, SwiftHugeSyncObject.self)
  283. }
  284. } catch {
  285. XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
  286. }
  287. }
  288. // MARK: - Administration
  289. func testRetrieveUserInfo() {
  290. let adminUsername = "jyaku.swift"
  291. let nonAdminUsername = "meela.swift@realm.example.org"
  292. let password = "p"
  293. let server = SwiftObjectServerTests.authServerURL()
  294. // Create a non-admin user.
  295. _ = logInUser(for: .init(username: nonAdminUsername, password: password, register: true),
  296. server: server)
  297. // Create an admin user.
  298. let adminUser = createAdminUser(for: server, username: adminUsername)
  299. // Look up information about the non-admin user from the admin user.
  300. let ex = expectation(description: "Should be able to look up user information")
  301. adminUser.retrieveInfo(forUser: nonAdminUsername, identityProvider: .usernamePassword) { (userInfo, err) in
  302. XCTAssertNil(err)
  303. XCTAssertNotNil(userInfo)
  304. guard let userInfo = userInfo else {
  305. return
  306. }
  307. let account = userInfo.accounts.first!
  308. XCTAssertEqual(account.providerUserIdentity, nonAdminUsername)
  309. XCTAssertEqual(account.provider, Provider.usernamePassword)
  310. XCTAssertFalse(userInfo.isAdmin)
  311. ex.fulfill()
  312. }
  313. waitForExpectations(timeout: 10.0, handler: nil)
  314. }
  315. // MARK: - Authentication
  316. func testInvalidCredentials() {
  317. do {
  318. let username = "testInvalidCredentialsUsername"
  319. let credentials = SyncCredentials.usernamePassword(username: username,
  320. password: "THIS_IS_A_PASSWORD",
  321. register: true)
  322. _ = try synchronouslyLogInUser(for: credentials, server: authURL)
  323. // Now log in the same user, but with a bad password.
  324. let ex = expectation(description: "wait for user login")
  325. let credentials2 = SyncCredentials.usernamePassword(username: username, password: "NOT_A_VALID_PASSWORD")
  326. SyncUser.logIn(with: credentials2, server: authURL) { user, error in
  327. XCTAssertNil(user)
  328. XCTAssertTrue(error is SyncAuthError)
  329. let castError = error as! SyncAuthError
  330. XCTAssertEqual(castError.code, SyncAuthError.invalidCredential)
  331. ex.fulfill()
  332. }
  333. waitForExpectations(timeout: 2.0, handler: nil)
  334. } catch {
  335. XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
  336. }
  337. }
  338. // MARK: - User-specific functionality
  339. func testUserExpirationCallback() {
  340. do {
  341. let user = try synchronouslyLogInUser(for: basicCredentials(), server: authURL)
  342. // Set a callback on the user
  343. var blockCalled = false
  344. let ex = expectation(description: "Error callback should fire upon receiving an error")
  345. user.errorHandler = { (u, error) in
  346. XCTAssertEqual(u.identity, user.identity)
  347. XCTAssertEqual(error.code, .accessDeniedOrInvalidPath)
  348. blockCalled = true
  349. ex.fulfill()
  350. }
  351. // Screw up the token on the user.
  352. manuallySetRefreshToken(for: user, value: "not-a-real-token")
  353. // Try to open a Realm with the user; this will cause our errorHandler block defined above to be fired.
  354. XCTAssertFalse(blockCalled)
  355. _ = try immediatelyOpenRealm(url: realmURL, user: user)
  356. waitForExpectations(timeout: 10.0, handler: nil)
  357. XCTAssertEqual(user.state, .loggedOut)
  358. } catch {
  359. XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
  360. }
  361. }
  362. // MARK: - Offline client reset
  363. func testOfflineClientReset() {
  364. let user = try! synchronouslyLogInUser(for: basicCredentials(), server: authURL)
  365. let sourceFileURL = Bundle(for: type(of: self)).url(forResource: "sync-1.x", withExtension: "realm")!
  366. let fileName = "\(UUID()).realm"
  367. let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
  368. try! FileManager.default.copyItem(at: sourceFileURL, to: fileURL)
  369. let syncConfig = RLMSyncConfiguration(user: user, realmURL: realmURL)
  370. syncConfig.customFileURL = fileURL
  371. let config = Realm.Configuration(syncConfiguration: ObjectiveCSupport.convert(object: syncConfig))
  372. do {
  373. _ = try Realm(configuration: config)
  374. } catch let e as Realm.Error where e.code == .incompatibleSyncedFile {
  375. var backupConfiguration = e.backupConfiguration
  376. XCTAssertNotNil(backupConfiguration)
  377. // Open the backup Realm with a schema subset since it was created using the schema from .NET's unit tests.
  378. backupConfiguration!.objectTypes = [Person.self]
  379. let backupRealm = try! Realm(configuration: backupConfiguration!)
  380. let people = backupRealm.objects(Person.self)
  381. XCTAssertEqual(people.count, 1)
  382. XCTAssertEqual(people[0].FirstName, "John")
  383. XCTAssertEqual(people[0].LastName, "Smith")
  384. // Verify that we can now successfully open the original synced Realm.
  385. _ = try! Realm(configuration: config)
  386. } catch {
  387. fatalError("Unexpected error: \(error)")
  388. }
  389. }
  390. // MARK: - Certificate Pinning
  391. func testSecureConnectionToLocalhostWithDefaultSecurity() {
  392. let user = try! synchronouslyLogInUser(for: basicCredentials(), server: authURL)
  393. let config = user.configuration(realmURL: URL(string: "realms://localhost:9443/~/default"),
  394. serverValidationPolicy: .system)
  395. let ex = expectation(description: "Waiting for error handler to be called")
  396. SyncManager.shared.errorHandler = { (error, session) in
  397. ex.fulfill()
  398. }
  399. _ = try! Realm(configuration: config)
  400. self.waitForExpectations(timeout: 4.0)
  401. }
  402. func testSecureConnectionToLocalhostWithValidationDisabled() {
  403. let user = try! synchronouslyLogInUser(for: basicCredentials(), server: authURL)
  404. let config = user.configuration(realmURL: URL(string: "realms://localhost:9443/~/default"),
  405. serverValidationPolicy: .none)
  406. SyncManager.shared.errorHandler = { (error, session) in
  407. XCTFail("Unexpected connection failure: \(error)")
  408. }
  409. let realm = try! Realm(configuration: config)
  410. self.waitForUploads(for: realm)
  411. }
  412. func testSecureConnectionToLocalhostWithPinnedCertificate() {
  413. let user = try! synchronouslyLogInUser(for: basicCredentials(), server: authURL)
  414. let certURL = URL(string: #file)!
  415. .deletingLastPathComponent()
  416. .appendingPathComponent("certificates")
  417. .appendingPathComponent("localhost.cer")
  418. let config = user.configuration(realmURL: URL(string: "realms://localhost:9443/~/default"),
  419. serverValidationPolicy: .pinCertificate(path: certURL))
  420. SyncManager.shared.errorHandler = { (error, session) in
  421. XCTFail("Unexpected connection failure: \(error)")
  422. }
  423. let realm = try! Realm(configuration: config)
  424. self.waitForUploads(for: realm)
  425. }
  426. func testSecureConnectionToLocalhostWithIncorrectPinnedCertificate() {
  427. let user = try! synchronouslyLogInUser(for: basicCredentials(), server: authURL)
  428. let certURL = URL(string: #file)!
  429. .deletingLastPathComponent()
  430. .appendingPathComponent("certificates")
  431. .appendingPathComponent("localhost-other.cer")
  432. let config = user.configuration(realmURL: URL(string: "realms://localhost:9443/~/default"),
  433. serverValidationPolicy: .pinCertificate(path: certURL))
  434. let ex = expectation(description: "Waiting for error handler to be called")
  435. SyncManager.shared.errorHandler = { (error, session) in
  436. ex.fulfill()
  437. }
  438. _ = try! Realm(configuration: config)
  439. self.waitForExpectations(timeout: 4.0)
  440. }
  441. }