diff --git a/RemoteShared/ShareClientExtension.swift b/RemoteShared/ShareClientExtension.swift index c8b492b78..1ea22be65 100644 --- a/RemoteShared/ShareClientExtension.swift +++ b/RemoteShared/ShareClientExtension.swift @@ -58,9 +58,57 @@ private var TrendTable: [String] = [ "RATE OUT OF RANGE", // 9 ] +/// Share locks an account after repeated bad logins, so a login it rejects for the account or +/// password blocks further logins with the same credentials on the same Share server for +/// `interval`. Other failures are tried again at the next fetch. +enum ShareLoginBackoff { + static let interval: TimeInterval = 15 * 60 + + private static let lock = NSLock() + private static var blocks: [String: (until: Date, code: String)] = [:] + + private static func key(_ server: String, _ username: String, _ password: String) -> String { + "\(server)\n\(username)\n\(password)" + } + + /// The rejection code while logins with these credentials are blocked, else nil. + static func blockedCode(server: String, username: String, password: String, now: Date = Date()) -> String? { + lock.lock() + defer { lock.unlock() } + guard let block = blocks[key(server, username, password)], now < block.until else { return nil } + return block.code + } + + static func block(server: String, username: String, password: String, code: String, now: Date = Date()) { + lock.lock() + defer { lock.unlock() } + blocks[key(server, username, password)] = (now.addingTimeInterval(interval), code) + } + + /// Share's codes for an unknown account, a wrong password or too many attempts. + static func rejectsCredentials(_ code: String) -> Bool { + [ + "AccountPasswordInvalid", "AccountNotFound", "SSO_AuthenticatePasswordInvalid", + "SSO_AuthenticateAccountNotFound", "SSO_AuthenticateMaxAttemptsExceeed", "SSO_AuthenticateMaxAttemptsExceeded", + ].contains(code) + } +} + public extension ShareClient { + /// The Share server URL this client logs in to. ShareClient keeps it private. + private var serverURL: String { + Mirror(reflecting: self).children.first { $0.label == "shareServer" }?.value as? String ?? "" + } + func fetchData(_ entries: Int, callback: @escaping (ShareError?, [ShareGlucoseData]?) -> Void) { - fetchLast(entries) { error, result in + let server = serverURL + if let code = ShareLoginBackoff.blockedCode(server: server, username: username, password: password) { + return callback(.loginError(errorCode: code), nil) + } + fetchLast(entries) { [username, password] error, result in + if case let .loginError(code)? = error, ShareLoginBackoff.rejectsCredentials(code) { + ShareLoginBackoff.block(server: server, username: username, password: password, code: code) + } guard error == nil, let result = result else { return callback(error ?? .fetchError, nil) } diff --git a/Tests/ShareLoginBackoffTests.swift b/Tests/ShareLoginBackoffTests.swift new file mode 100644 index 000000000..8d564f7cf --- /dev/null +++ b/Tests/ShareLoginBackoffTests.swift @@ -0,0 +1,56 @@ +// LoopFollow +// ShareLoginBackoffTests.swift + +import Foundation +@testable import LoopFollow +import ShareClient +import Testing + +struct ShareLoginBackoffTests { + private let start = Date(timeIntervalSince1970: 1_000_000) + private let us = KnownShareServers.US.rawValue + private let nonUS = KnownShareServers.NON_US.rawValue + + @Test("a rejected login blocks the same credentials for fifteen minutes") + func blocksSameCredentials() { + ShareLoginBackoff.block(server: us, username: "user-a", password: "wrong", code: "AccountPasswordInvalid", now: start) + #expect(ShareLoginBackoff.blockedCode(server: us, username: "user-a", password: "wrong", now: start.addingTimeInterval(899)) == "AccountPasswordInvalid") + #expect(ShareLoginBackoff.blockedCode(server: us, username: "user-a", password: "wrong", now: start.addingTimeInterval(900)) == nil) + } + + @Test("other credentials are not blocked") + func otherCredentials() { + ShareLoginBackoff.block(server: us, username: "user-b", password: "wrong", code: "AccountPasswordInvalid", now: start) + #expect(ShareLoginBackoff.blockedCode(server: us, username: "user-b", password: "corrected", now: start.addingTimeInterval(1)) == nil) + #expect(ShareLoginBackoff.blockedCode(server: us, username: "user-c", password: "wrong", now: start.addingTimeInterval(1)) == nil) + } + + @Test("the same credentials on another Share server are not blocked") + func otherServer() { + ShareLoginBackoff.block(server: us, username: "user-d", password: "secret", code: "AccountPasswordInvalid", now: start) + #expect(ShareLoginBackoff.blockedCode(server: nonUS, username: "user-d", password: "secret", now: start.addingTimeInterval(1)) == nil) + } + + @Test("a blocked client answers with the rejection without contacting Share") + func blockedClientUsesServer() async { + let client = ShareClient(username: "user-e", password: "wrong", shareServer: nonUS) + ShareLoginBackoff.block(server: nonUS, username: "user-e", password: "wrong", code: "AccountPasswordInvalid") + let error: ShareError? = await withCheckedContinuation { continuation in + client.fetchData(1) { error, _ in continuation.resume(returning: error) } + } + guard case let .loginError(code)? = error else { + Issue.record("expected a login error, got \(String(describing: error))") + return + } + #expect(code == "AccountPasswordInvalid") + } + + @Test("only account and password rejections block") + func onlyRejections() { + #expect(ShareLoginBackoff.rejectsCredentials("SSO_AuthenticatePasswordInvalid")) + #expect(ShareLoginBackoff.rejectsCredentials("SSO_AuthenticateMaxAttemptsExceeed")) + #expect(ShareLoginBackoff.rejectsCredentials("AccountNotFound")) + #expect(!ShareLoginBackoff.rejectsCredentials("SSO_InternalError")) + #expect(!ShareLoginBackoff.rejectsCredentials("unknown")) + } +}