This repository was archived by the owner on Dec 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathAccountStore.kt
More file actions
425 lines (365 loc) · 15.3 KB
/
Copy pathAccountStore.kt
File metadata and controls
425 lines (365 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package mozilla.lockbox.store
import android.content.Context
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.webkit.CookieManager
import android.webkit.WebStorage
import android.webkit.WebView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers.mainThread
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.ReplaySubject
import io.reactivex.subjects.Subject
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.rx2.asMaybe
import kotlinx.coroutines.rx2.asSingle
import mozilla.appservices.fxaclient.FxaException
import mozilla.components.concept.sync.AccessTokenInfo
import mozilla.components.concept.sync.Avatar
import mozilla.components.concept.sync.OAuthScopedKey
import mozilla.components.concept.sync.Profile
import mozilla.components.service.fxa.ServerConfig
import mozilla.components.service.fxa.FirefoxAccount
import mozilla.components.service.fxa.sharing.AccountSharing
import mozilla.components.service.fxa.sharing.ShareableAccount
import mozilla.lockbox.action.AccountAction
import mozilla.lockbox.action.DataStoreAction
import mozilla.lockbox.action.LifecycleAction
import mozilla.lockbox.action.SentryAction
import mozilla.lockbox.extensions.filterByType
import mozilla.lockbox.flux.Dispatcher
import mozilla.lockbox.log
import mozilla.lockbox.model.FixedSyncCredentials
import mozilla.lockbox.model.FxASyncCredentials
import mozilla.lockbox.model.SyncCredentials
import mozilla.lockbox.support.Constant
import mozilla.lockbox.support.DeviceSystemTimingSupport
import mozilla.lockbox.support.Optional
import mozilla.lockbox.support.SecurePreferences
import mozilla.lockbox.support.SystemTimingSupport
import mozilla.lockbox.support.asOptional
import org.json.JSONObject
import java.io.File
import java.lang.Long.min
import java.util.concurrent.TimeUnit
import kotlin.coroutines.CoroutineContext
@ExperimentalCoroutinesApi
open class AccountStore(
private val lifecycleStore: LifecycleStore = LifecycleStore.shared,
private val settingStore: SettingStore = SettingStore.shared,
private val dispatcher: Dispatcher = Dispatcher.shared,
private val securePreferences: SecurePreferences = SecurePreferences.shared,
private val timingSupport: SystemTimingSupport = DeviceSystemTimingSupport.shared
) : ContextStore {
companion object {
val shared by lazy { AccountStore() }
}
internal val compositeDisposable = CompositeDisposable()
private val exceptionHandler: CoroutineExceptionHandler
get() = CoroutineExceptionHandler { _, e ->
log.error(
message = "Unexpected error occurred during Firefox Account authentication",
throwable = e
)
}
private val coroutineContext: CoroutineContext
get() = Dispatchers.Default + exceptionHandler
private val testProfile = Profile(
uid = "test",
email = "whovian@tardis.net",
displayName = "Jodie Whittaker",
avatar = Avatar(
url = "https://nerdist.com/wp-content/uploads/2017/11/The-Doctor-Jodie-Whittaker.jpg",
isDefault = true
)
)
private val storedAccountJSON: String?
get() = securePreferences.getString(Constant.Key.firefoxAccount)
private var fxa: FirefoxAccount? = null
open val loginURL: Observable<String> = ReplaySubject.createWithSize(1)
private val syncCredentials: Observable<Optional<SyncCredentials>> = ReplaySubject.createWithSize(1)
open val profile: Observable<Optional<Profile>> = ReplaySubject.createWithSize(1)
private lateinit var context: Context
private val tokenRotationHandler = Handler()
init {
val resetObservable = lifecycleStore.lifecycleEvents
.filter { it == LifecycleAction.UserReset }
.map { AccountAction.Reset }
val useTestData = lifecycleStore.lifecycleEvents
.filter { it == LifecycleAction.UseTestData }
.map { AccountAction.UseTestData }
this.dispatcher.register
.filterByType(AccountAction::class.java)
.mergeWith(resetObservable)
.mergeWith(useTestData)
.subscribe {
when (it) {
is AccountAction.OauthRedirect -> this.oauthLogin(it.url)
is AccountAction.UseTestData -> this.populateTestAccountInformation(true)
is AccountAction.AutomaticLogin -> this.automaticLogin(it.account)
is AccountAction.Reset -> this.clear()
}
}
.addTo(compositeDisposable)
// Moves credentials from the AccountStore, into the DataStore.
syncCredentials
.map {
it.value?.let { credentials -> DataStoreAction.UpdateSyncCredentials(credentials) }
?: DataStoreAction.Reset
}
.subscribe(dispatcher::dispatch)
.addTo(compositeDisposable)
}
override fun injectContext(context: Context) {
detectAccount()
this.context = context
}
fun checkAccountExisting(): Boolean {
return (storedAccountJSON != null)
}
fun shareableAccount(): ShareableAccount? {
return AccountSharing.queryShareableAccounts(context).firstOrNull()
}
private fun automaticLogin(account: ShareableAccount) {
fxa?.migrateFromSessionTokenAsync(
account.authInfo.sessionToken,
account.authInfo.kSync,
account.authInfo.kXCS
)
?.let {
it.asSingle(coroutineContext)
.map { true }
.subscribe(this::populateAccountInformation, this::pushError)
.addTo(compositeDisposable)
}
}
private fun detectAccount() {
storedAccountJSON?.let { accountJSON ->
if (accountJSON == Constant.App.testMarker) {
populateTestAccountInformation(false)
} else {
try {
this.fxa = FirefoxAccount.fromJSONString(accountJSON)
} catch (e: FxaException) {
pushError(e)
}
generateLoginURL()
populateAccountInformation(false)
}
} ?: run {
this.generateNewFirefoxAccount()
}
}
private fun populateTestAccountInformation(isNew: Boolean) {
val profileSubject = profile as Subject
val syncCredentialSubject = syncCredentials as Subject
securePreferences.putString(Constant.Key.firefoxAccount, Constant.App.testMarker)
profileSubject.onNext(testProfile.asOptional())
syncCredentialSubject.onNext(FixedSyncCredentials(isNew).asOptional())
}
private fun populateAccountInformation(isNew: Boolean) {
val profileSubject = profile as Subject
val fxa = fxa ?: return
securePreferences.putString(Constant.Key.firefoxAccount, fxa.toJSONString())
fxa.getProfileAsync()
.asMaybe(coroutineContext)
.delay(1L, TimeUnit.SECONDS)
.map { it.asOptional() }
.subscribe(profileSubject::onNext, this::pushError)
.addTo(compositeDisposable)
val token = securePreferences.getString(Constant.Key.accessToken)?.let {
accessTokenInfoFromJSON(JSONObject(it))
}
token?.let { handleAccessToken(it, isNew) } ?: tokenRotationHandler.post { fetchFreshToken(isNew) }
}
private fun fetchFreshToken(isNewLogin: Boolean = false) {
val fxa = fxa ?: return
fxa.getAccessTokenAsync(Constant.FxA.oldSyncScope)
.asMaybe(coroutineContext)
.delay(1L, TimeUnit.SECONDS)
.subscribe({ token ->
handleAccessToken(token, isNewLogin)
}, this::pushError)
.addTo(compositeDisposable)
}
private fun handleAccessToken(
token: AccessTokenInfo,
isNewLogin: Boolean
) {
// We've just got a new token. It might be from secure preferences (we've just been
// restarted) or a token refresh.
// 1. Update the rest of the app.
generateSyncCredentials(token, isNewLogin)
.take(1)
.observeOn(mainThread())
.subscribe((syncCredentials as Subject)::onNext, this::pushError)
.addTo(compositeDisposable)
// 2. Store this token in the secure preferences.
securePreferences.putString(Constant.Key.accessToken, token.toJSONObject().toString())
// 3. Schedule a token refresh. It may be quite a long time away.
// Calculate how long before the token expires in milliseconds.
val msDelay = token.expiresAt * 1000L - timingSupport.currentTimeMillis
// We'll wait until it's almost expired, leaving at most 10 minutes to fetch the token.
val refreshMargin = min(msDelay * 95L / 100L, 10 * 60 * 1000L)
// Wait until the token has nearly expired, and then fetch a new one.
scheduleFetchFreshToken(msDelay - refreshMargin)
}
private fun scheduleFetchFreshToken(msDelay: Long) {
// If the app is killed, then this will be refreshed when the app is restarted.
tokenRotationHandler.postDelayed({
fetchFreshToken(false)
}, msDelay)
}
private fun generateSyncCredentials(oauthInfo: AccessTokenInfo, isNew: Boolean): Observable<Optional<SyncCredentials>> {
return Observable.just(Unit)
.observeOn(Schedulers.io())
.map {
fxa?.let {
val url = it.getTokenServerEndpointURL()
FxASyncCredentials(oauthInfo, url, isNew) as SyncCredentials
}.asOptional()
}
}
private fun generateNewFirefoxAccount() {
try {
settingStore.useLocalService.subscribe {
val config: ServerConfig
if (it)
config = ServerConfig("https://accounts.firefox.com.cn", Constant.FxA.clientID, Constant.FxA.redirectUri)
else
config = ServerConfig.release(Constant.FxA.clientID, Constant.FxA.redirectUri)
fxa = FirefoxAccount(config)
generateLoginURL()
}
.addTo(compositeDisposable)
} catch (e: FxaException) {
this.pushError(e)
}
(syncCredentials as Subject).onNext(Optional(null))
(profile as Subject).onNext(Optional(null))
}
private fun generateLoginURL() {
val fxa = fxa ?: return
fxa.beginOAuthFlowAsync(Constant.FxA.scopes)
.asMaybe(coroutineContext)
.map { it.url }
.subscribe((this.loginURL as Subject)::onNext, this::pushError)
.addTo(compositeDisposable)
}
private fun oauthLogin(url: String) {
val fxa = fxa ?: return
val uri = Uri.parse(url)
val codeQP = uri.getQueryParameter("code")
val stateQP = uri.getQueryParameter("state")
codeQP?.let { code ->
stateQP?.let { state ->
fxa.completeOAuthFlowAsync(code, state)
.asSingle(coroutineContext)
.map { true }
.subscribe(this::populateAccountInformation, this::pushError)
.addTo(compositeDisposable)
}
}
}
private fun clear() {
removeDeviceFromFxA()
if (Looper.myLooper() != null) {
CookieManager.getInstance().removeAllCookies(null)
WebStorage.getInstance().deleteAllData()
}
tokenRotationHandler.removeCallbacksAndMessages(null)
this.securePreferences.clear()
this.generateNewFirefoxAccount()
// Clear down the webview subsystem as best we can.
// Unfortunately, some of this assumes we have a webview to hand. No matter, we can just
// create one.
// This was previously being held from `injectContext` to now, (PR #694).
// Now, our very rare event (disconnect) is slightly slower and more memory instance,
// but our frequent event (injectContext) is fast and svelte.
WebView(context).clearCache(true)
// Clear the log directories.
val logDirectory = context.getDir("webview", Context.MODE_PRIVATE)
clearLogFolder(logDirectory)
}
private fun removeDeviceFromFxA() {
if (fxa != null) {
fxa!!.disconnectAsync()
.asSingle(coroutineContext)
.subscribe()
.addTo(compositeDisposable)
} else {
log.info("FxA is null. No devices to disconnect.")
}
}
private fun clearLogFolder(dir: File) {
if (dir.isDirectory) {
try {
val leveldbDir = dir.listFiles()
.filter { file ->
file.name.startsWith("Local")
}[0]
.listFiles()
.filter { file ->
file.name.startsWith("leveldb")
}[0]
.listFiles()
for (file in leveldbDir) {
val logname = file.name
if (logname.endsWith(".log")) {
file.delete()
}
}
} catch (exception: Exception) {
log.error("Failed to clear the directory.", exception)
}
}
}
private fun pushError(it: Throwable) {
when (it) {
is FxaException.Unauthorized -> log.error(
"FxA error populating account information. Message: " + it.message,
it
)
is FxaException.Unspecified -> log.error("Unspecified FxA error. Message: " + it.message, it)
is FxaException.Network -> log.error("FxA network error. Message: " + it.message, it)
is FxaException.Panic -> log.error("FxA error. Message: " + it.message, it)
}
dispatcher.dispatch(SentryAction(it))
}
}
private fun AccessTokenInfo.toJSONObject() = JSONObject()
.put("scope", scope)
.put("token", token)
.put("expiresAt", expiresAt)
.put("key", key?.toJSONObject())
private fun OAuthScopedKey.toJSONObject() = JSONObject()
.put("kty", kty)
.put("scope", scope)
.put("kid", kid)
.put("k", k)
private fun accessTokenInfoFromJSON(obj: JSONObject): AccessTokenInfo? {
return AccessTokenInfo(
scope = obj.optString("scope", null) ?: return null,
token = obj.optString("token", null) ?: return null,
expiresAt = obj.optLong("expiresAt", 0L),
key = obj.optJSONObject("key")?.let { oauthScopedKeyFromJSON(it) }
)
}
private fun oauthScopedKeyFromJSON(obj: JSONObject): OAuthScopedKey? {
return OAuthScopedKey(
kty = obj.optString("kty", null) ?: return null,
scope = obj.optString("scope", null) ?: return null,
kid = obj.optString("kid", null) ?: return null,
k = obj.optString("k", null) ?: return null
)
}