-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathHaapiModule.kt
More file actions
372 lines (321 loc) · 13.5 KB
/
HaapiModule.kt
File metadata and controls
372 lines (321 loc) · 13.5 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
/*
* Copyright 2024 Curity AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.curity.haapi.react
import android.util.Log
import com.facebook.react.bridge.LifecycleEventListener
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.ReadableMap
import com.google.gson.Gson
import io.curity.haapi.react.JsonUtil.jsonToNativeMap
import io.curity.haapi.react.JsonUtil.mapToNativeMap
import io.curity.haapi.react.events.EventEmitter
import io.curity.haapi.react.events.EventType
import io.curity.haapi.react.events.EventType.*
import io.curity.haapi.react.webauthn.WebAuthnHandler
import se.curity.identityserver.haapi.android.driver.HaapiLogger
import se.curity.identityserver.haapi.android.sdk.models.AuthenticatorSelectorStep
import se.curity.identityserver.haapi.android.sdk.models.ContinueSameStep
import se.curity.identityserver.haapi.android.sdk.models.HaapiRepresentation
import se.curity.identityserver.haapi.android.sdk.models.HaapiResponse
import se.curity.identityserver.haapi.android.sdk.models.Link
import se.curity.identityserver.haapi.android.sdk.models.OAuthAuthorizationResponseStep
import se.curity.identityserver.haapi.android.sdk.models.PollingStatus
import se.curity.identityserver.haapi.android.sdk.models.PollingStep
import se.curity.identityserver.haapi.android.sdk.models.ProblemRepresentation
import se.curity.identityserver.haapi.android.sdk.models.ProblemType
import se.curity.identityserver.haapi.android.sdk.models.RepresentationType
import se.curity.identityserver.haapi.android.sdk.models.WebAuthnAuthenticationClientOperationStep
import se.curity.identityserver.haapi.android.sdk.models.WebAuthnRegistrationClientOperationStep
import se.curity.identityserver.haapi.android.sdk.models.actions.Action
import se.curity.identityserver.haapi.android.sdk.models.actions.FormActionModel
import se.curity.identityserver.haapi.android.sdk.models.oauth.ErrorTokenResponse
import se.curity.identityserver.haapi.android.sdk.models.oauth.SuccessfulTokenResponse
import se.curity.identityserver.haapi.android.sdk.models.oauth.TokenResponse
const val TAG = "HaapiNative"
class HaapiModule(private val _reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(_reactContext),
LifecycleEventListener {
override fun getName() = "HaapiModule"
private var _haapiResponse: HaapiRepresentation? = null
private var _tokenResponse: SuccessfulTokenResponse? = null
private val _gson = Gson()
private val _handler = HaapiInteractionHandler(_reactContext)
private val _eventEmitter = EventEmitter(_reactContext)
private val _webAuthnHandler = WebAuthnHandler(_reactContext)
init {
HaapiLogger.enabled = BuildConfig.DEBUG
HaapiLogger.isDebugEnabled = BuildConfig.DEBUG
_reactContext.addLifecycleEventListener(this)
}
override fun onHostResume() {
Log.d(TAG, "App was resumed")
}
override fun onHostPause() {
Log.d(TAG, "App was paused")
}
override fun onHostDestroy() {
Log.d(TAG, "App was destroyed")
}
@ReactMethod
fun load(conf: ReadableMap, promise: Promise) {
try {
_handler.loadConfiguration(conf.toHashMap())
} catch (e: HaapiException) {
rejectRequest(e, promise)
}
promise.resolve(true)
}
@ReactMethod
fun start(promise: Promise) {
Log.d(TAG, "Start was called")
_handler.startAuthentication(
onSuccess = { response -> handleHaapiResponse(response, promise) },
onError = { e ->
Log.e(TAG, e.message ?: "Failed to attest $e")
rejectRequest(e, promise)
}
)
}
@ReactMethod
fun logout(promise: Promise) {
Log.d(TAG, "Logout was called, revoking tokens")
if (_tokenResponse != null) {
_handler.logoutAndRevokeTokens(
_tokenResponse!!.accessToken,
_tokenResponse!!.refreshToken,
onSuccess = {
_tokenResponse = null
resolveRequest(LoggedOut, "{}", promise)
},
onError = { e ->
Log.w(TAG, "Failed to logout: ${e.message}")
rejectRequest(e, promise)
}
)
} else {
_handler.closeHaapiConnection()
_tokenResponse = null
resolveRequest(LoggedOut, "{}", promise)
}
}
@ReactMethod
fun refreshAccessToken(refreshToken: String, promise: Promise) {
Log.d(TAG, "Refreshing access token")
_handler.refreshAccessToken(
refreshToken,
onSuccess = { tokenResponse ->
handleTokenResponse(tokenResponse, promise)
},
onError = { e ->
rejectRequest(e, promise)
}
)
}
@ReactMethod
fun navigate(linkMap: ReadableMap, promise: Promise) {
val linkJson = _gson.toJson(linkMap.toHashMap())
val link = _gson.fromJson(linkJson, Link::class.java)
_handler.followLink(
link,
onSuccess = { response -> handleHaapiResponse(response, promise) },
onError = { e ->
Log.d(TAG, "Failed to navigate to link: ${e.message}")
rejectRequest(e, promise)
}
)
}
@ReactMethod
fun submitForm(actionMap: ReadableMap, parameters: ReadableMap, promise: Promise) {
val action = findAction(actionMap, _haapiResponse as HaapiRepresentation)
if (action == null) {
Log.d(TAG, "Failed to find action to submit. Possible re-submit")
return
}
submitModel(action.model, parameters.toHashMap(), promise)
}
/**
* Needs to be here to suppress warnings from react-native
*/
@ReactMethod
fun addListener(eventName: String) {
}
/**
* Needs to be here to suppress warnings from react-native
*/
@ReactMethod
fun removeListeners(count: Int) {
}
private fun submitModel(
model: FormActionModel,
parameters: Map<String, Any>,
promise: Promise
) {
Log.d(TAG, "Submitting form $model")
_handler.submitForm(
model,
parameters,
onSuccess = { response ->
handleHaapiResponse(response, promise)
},
onError = { e ->
Log.w(TAG, "Failed to submit form: ${e.message}")
rejectRequest(e, promise)
}
)
}
private fun handleCodeResponse(response: OAuthAuthorizationResponseStep, promise: Promise) {
_handler.exchangeCode(
response,
onSuccess = { tokenResponse ->
handleTokenResponse(tokenResponse, promise)
},
onError = { e ->
Log.w(TAG, "Failed to exchange code: ${e.message}")
rejectRequest(e, promise)
}
)
}
private fun handleTokenResponse(tokenResponse: TokenResponse, promise: Promise) {
if (tokenResponse is SuccessfulTokenResponse) {
val tokenMap = mapOf(
"accessToken" to tokenResponse.accessToken,
"refreshToken" to tokenResponse.refreshToken,
"scope" to tokenResponse.scope,
"idToken" to tokenResponse.idToken,
"expiresIn" to tokenResponse.expiresIn.seconds
)
_tokenResponse = tokenResponse
resolveRequest(TokenResponse, _gson.toJson(tokenMap), promise)
} else {
tokenResponse as ErrorTokenResponse
val errorResponseMap = mapOf(
"error" to tokenResponse.error,
"error_description" to tokenResponse.errorDescription
)
resolveRequest(TokenResponseError, JsonUtil.toJsonString(errorResponseMap), promise)
}
}
private fun findAction(
actionMap: ReadableMap,
representation: HaapiRepresentation,
): Action.Form? {
// TODO: Match more precise
val submitKind = actionMap.getString("kind")
Log.d(TAG, "Looking for form with kind $submitKind")
Log.d(TAG, "Current response: $_haapiResponse")
val action = representation.actions.find {
it.toJsonObject().get("kind") == submitKind
}
return action as? Action.Form
}
private fun handleHaapiResponse(response: HaapiResponse, promise: Promise) {
when (response) {
is HaapiRepresentation -> {
Log.d(TAG, "Updating reference to representation")
_haapiResponse = response
when (response) {
is WebAuthnRegistrationClientOperationStep -> handleWebAuthnRegistration(
response,
promise
)
is WebAuthnAuthenticationClientOperationStep -> handleWebAuthnAuthentication(
response,
promise
)
is AuthenticatorSelectorStep -> resolveRequest(
AuthenticationSelectorStep, response.toJsonString(), promise
)
is ContinueSameStep -> resolveRequest(
ContinueSameStep, response.toJsonString(), promise
)
is OAuthAuthorizationResponseStep -> handleCodeResponse(response, promise)
is PollingStep -> handlePollingStep(response, promise)
else -> when (response.type) {
RepresentationType.AUTHENTICATION_STEP -> {
resolveRequest(AuthenticationStep, response.toJsonString(), promise)
}
RepresentationType.REGISTRATION_STEP -> {
resolveRequest(RegistrationStep, response.toJsonString(), promise)
}
else -> {
Log.d(TAG, "Unknown step ${response.type}")
resolveRequest(UnknownResponse, response.toJsonString(), promise)
}
}
}
}
is ProblemRepresentation -> {
when (response.type) {
ProblemType.IncorrectCredentialsProblem -> {
resolveRequest(IncorrectCredentials, response.toJsonString(), promise)
}
ProblemType.SessionAndAccessTokenMismatchProblem -> {
resolveRequest(SessionTimedOut, response.toJsonString(), promise)
}
else -> {
resolveRequest(ProblemRepresentation, response.toJsonString(), promise)
}
}
}
}
Log.d(TAG, response.toJsonString())
}
private fun handleWebAuthnAuthentication(
response: WebAuthnAuthenticationClientOperationStep,
promise: Promise
) =
_webAuthnHandler.authenticationFlow(response, promise) { parameters ->
submitModel(response.continueFormActionModel, parameters, promise)
}
private fun handleWebAuthnRegistration(
response: WebAuthnRegistrationClientOperationStep,
promise: Promise
) =
_webAuthnHandler.registrationFlow(response, promise) { parameters ->
submitModel(response.continueFormActionModel, parameters, promise)
}
private fun handlePollingStep(pollingStep: PollingStep, promise: Promise) {
when (pollingStep.properties.status) {
PollingStatus.PENDING -> {
_eventEmitter.sendEvent(PollingStep, pollingStep.toJsonString())
resolveRequest(PollingStepResult, pollingStep.toJsonString(), promise)
}
PollingStatus.FAILED -> {
_eventEmitter.sendEvent(StopPolling, "{}")
submitModel(pollingStep.mainAction.model, emptyMap(), promise)
}
PollingStatus.DONE -> {
_eventEmitter.sendEvent(StopPolling, "{}")
submitModel(pollingStep.mainAction.model, emptyMap(), promise)
}
}
}
private fun rejectRequest(exception: Exception, promise: Promise) {
val errorDescription = exception.message ?: "general error"
val jsonMap = mutableMapOf("error" to "HaapiError", "error_description" to errorDescription)
Log.d(TAG, "Rejecting request using with description '$errorDescription'")
_eventEmitter.sendEvent(HaapiError, JsonUtil.toJsonString(jsonMap))
promise.reject(exception, mapToNativeMap(jsonMap))
}
private fun resolveRequest(eventType: EventType, body: String, promise: Promise) {
Log.d(TAG, "Resolving request using event type $eventType and body: $body")
_eventEmitter.sendEvent(eventType, body)
promise.resolve(jsonToNativeMap(body))
}
}