aboutsummaryrefslogtreecommitdiffstats
path: root/autofill-parser/src/main/java/com/github/androidpasswordstore/autofillparser/AutofillStrategyDsl.kt
blob: 673c7466caf198a9ae25d4e9f561d988bab4f706 (plain)
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/*
 * Copyright © 2014-2024 The Android Password Store Authors. All Rights Reserved.
 * SPDX-License-Identifier: LGPL-3.0-only WITH LGPL-3.0-linking-exception
 */
package com.github.androidpasswordstore.autofillparser

import android.os.Build
import androidx.annotation.RequiresApi
import logcat.LogPriority.WARN
import logcat.logcat

@DslMarker internal annotation class AutofillDsl

@RequiresApi(Build.VERSION_CODES.O)
internal interface FieldMatcher {

  fun match(fields: List<FormField>, alreadyMatched: List<FormField>): List<FormField>?

  @AutofillDsl
  class Builder {

    private var takeSingle: (FormField.(List<FormField>) -> Boolean)? = null
    private val tieBreakersSingle: MutableList<FormField.(List<FormField>) -> Boolean> =
      mutableListOf()

    private var takePair: (Pair<FormField, FormField>.(List<FormField>) -> Boolean)? = null
    private var tieBreakersPair:
      MutableList<Pair<FormField, FormField>.(List<FormField>) -> Boolean> =
      mutableListOf()

    fun takeSingle(block: FormField.(alreadyMatched: List<FormField>) -> Boolean = { true }) {
      check(takeSingle == null && takePair == null) {
        "Every block can only have at most one take{Single,Pair} block"
      }
      takeSingle = block
    }

    fun breakTieOnSingle(block: FormField.(alreadyMatched: List<FormField>) -> Boolean) {
      check(takeSingle != null) {
        "Every block needs a takeSingle block before a breakTieOnSingle block"
      }
      check(takePair == null) { "takePair cannot be mixed with breakTieOnSingle" }
      tieBreakersSingle.add(block)
    }

    fun takePair(
      block: Pair<FormField, FormField>.(alreadyMatched: List<FormField>) -> Boolean = { true }
    ) {
      check(takeSingle == null && takePair == null) {
        "Every block can only have at most one take{Single,Pair} block"
      }
      takePair = block
    }

    fun breakTieOnPair(
      block: Pair<FormField, FormField>.(alreadyMatched: List<FormField>) -> Boolean
    ) {
      check(takePair != null) { "Every block needs a takePair block before a breakTieOnPair block" }
      check(takeSingle == null) { "takeSingle cannot be mixed with breakTieOnPair" }
      tieBreakersPair.add(block)
    }

    fun build(): FieldMatcher {
      val takeSingle = takeSingle
      val takePair = takePair
      return when {
        takeSingle != null -> SingleFieldMatcher(takeSingle, tieBreakersSingle)
        takePair != null -> PairOfFieldsMatcher(takePair, tieBreakersPair)
        else -> throw IllegalArgumentException("Every block needs a take{Single,Pair} block")
      }
    }
  }
}

@RequiresApi(Build.VERSION_CODES.O)
internal class SingleFieldMatcher(
  private val take: (FormField, List<FormField>) -> Boolean,
  private val tieBreakers: List<(FormField, List<FormField>) -> Boolean>,
) : FieldMatcher {

  @AutofillDsl
  class Builder {

    private var takeSingle: (FormField.(List<FormField>) -> Boolean)? = null
    private val tieBreakersSingle: MutableList<FormField.(List<FormField>) -> Boolean> =
      mutableListOf()

    fun takeSingle(block: FormField.(alreadyMatched: List<FormField>) -> Boolean = { true }) {
      check(takeSingle == null) { "Every block can only have at most one takeSingle block" }
      takeSingle = block
    }

    fun breakTieOnSingle(block: FormField.(alreadyMatched: List<FormField>) -> Boolean) {
      check(takeSingle != null) {
        "Every block needs a takeSingle block before a breakTieOnSingle block"
      }
      tieBreakersSingle.add(block)
    }

    fun build() =
      SingleFieldMatcher(
        takeSingle ?: throw IllegalArgumentException("Every block needs a take{Single,Pair} block"),
        tieBreakersSingle,
      )
  }

  override fun match(fields: List<FormField>, alreadyMatched: List<FormField>): List<FormField>? {
    return fields
      .minus(alreadyMatched)
      .filter { take(it, alreadyMatched) }
      .let { contestants ->
        when (contestants.size) {
          1 -> return@let listOf(contestants.single())
          0 -> return@let null
        }
        var current = contestants
        for ((i, tieBreaker) in tieBreakers.withIndex()) {
          // Successively filter matched fields via tie breakers...
          val new = current.filter { tieBreaker(it, alreadyMatched) }
          // skipping those tie breakers that are not satisfied for any remaining field...
          if (new.isEmpty()) {
            logcat { "Tie breaker #${i + 1}: Didn't match any field; skipping" }
            continue
          }
          // and return if the available options have been narrowed to a single field.
          if (new.size == 1) {
            logcat { "Tie breaker #${i + 1}: Success" }
            current = new
            break
          }
          logcat { "Tie breaker #${i + 1}: Matched ${new.size} fields; continuing" }
          current = new
        }
        listOf(current.singleOrNull() ?: return null)
      }
  }
}

@RequiresApi(Build.VERSION_CODES.O)
private class PairOfFieldsMatcher(
  private val take: (Pair<FormField, FormField>, List<FormField>) -> Boolean,
  private val tieBreakers: List<(Pair<FormField, FormField>, List<FormField>) -> Boolean>,
) : FieldMatcher {

  override fun match(fields: List<FormField>, alreadyMatched: List<FormField>): List<FormField>? {
    return fields
      .minus(alreadyMatched)
      .zipWithNext()
      .filter { it.first directlyPrecedes it.second }
      .filter { take(it, alreadyMatched) }
      .let { contestants ->
        when (contestants.size) {
          1 -> return@let contestants.single().toList()
          0 -> return@let null
        }
        var current = contestants
        for ((i, tieBreaker) in tieBreakers.withIndex()) {
          val new = current.filter { tieBreaker(it, alreadyMatched) }
          if (new.isEmpty()) {
            logcat { "Tie breaker #${i + 1}: Didn't match any pair of fields; skipping" }
            continue
          }
          // and return if the available options have been narrowed to a single field.
          if (new.size == 1) {
            logcat { "Tie breaker #${i + 1}: Success" }
            current = new
            break
          }
          logcat { "Tie breaker #${i + 1}: Matched ${new.size} pairs of fields; continuing" }
          current = new
        }
        current.singleOrNull()?.toList()
      }
  }
}

@RequiresApi(Build.VERSION_CODES.O)
internal class AutofillRule
private constructor(
  private val matchers: List<AutofillRuleMatcher>,
  private val applyInSingleOriginMode: Boolean,
  private val applyOnManualRequestOnly: Boolean,
  private val name: String,
) {

  data class AutofillRuleMatcher(
    val type: FillableFieldType,
    val matcher: FieldMatcher,
    val optional: Boolean,
    val matchHidden: Boolean,
  )

  enum class FillableFieldType {
    Username,
    Otp,
    CurrentPassword,
    NewPassword,
    GenericPassword,
  }

  @AutofillDsl
  class Builder(
    private val applyInSingleOriginMode: Boolean,
    private val applyOnManualRequestOnly: Boolean,
  ) {

    companion object {

      private var ruleId = 1
    }

    private val matchers = mutableListOf<AutofillRuleMatcher>()
    var name: String? = null

    fun username(
      optional: Boolean = false,
      matchHidden: Boolean = false,
      block: SingleFieldMatcher.Builder.() -> Unit,
    ) {
      require(matchers.none { it.type == FillableFieldType.Username }) {
        "Every rule block can only have at most one username block"
      }
      matchers.add(
        AutofillRuleMatcher(
          type = FillableFieldType.Username,
          matcher = SingleFieldMatcher.Builder().apply(block).build(),
          optional = optional,
          matchHidden = matchHidden,
        )
      )
    }

    fun otp(optional: Boolean = false, block: SingleFieldMatcher.Builder.() -> Unit) {
      require(matchers.none { it.type == FillableFieldType.Otp }) {
        "Every rule block can only have at most one otp block"
      }
      matchers.add(
        AutofillRuleMatcher(
          type = FillableFieldType.Otp,
          matcher = SingleFieldMatcher.Builder().apply(block).build(),
          optional = optional,
          matchHidden = false,
        )
      )
    }

    fun currentPassword(
      optional: Boolean = false,
      matchHidden: Boolean = false,
      block: FieldMatcher.Builder.() -> Unit,
    ) {
      require(matchers.none { it.type == FillableFieldType.GenericPassword }) {
        "Every rule block can only have either genericPassword or {current,new}Password blocks"
      }
      matchers.add(
        AutofillRuleMatcher(
          type = FillableFieldType.CurrentPassword,
          matcher = FieldMatcher.Builder().apply(block).build(),
          optional = optional,
          matchHidden = matchHidden,
        )
      )
    }

    fun newPassword(optional: Boolean = false, block: FieldMatcher.Builder.() -> Unit) {
      require(matchers.none { it.type == FillableFieldType.GenericPassword }) {
        "Every rule block can only have either genericPassword or {current,new}Password blocks"
      }
      matchers.add(
        AutofillRuleMatcher(
          type = FillableFieldType.NewPassword,
          matcher = FieldMatcher.Builder().apply(block).build(),
          optional = optional,
          matchHidden = false,
        )
      )
    }

    fun genericPassword(optional: Boolean = false, block: FieldMatcher.Builder.() -> Unit) {
      require(
        matchers.none {
          it.type in listOf(FillableFieldType.CurrentPassword, FillableFieldType.NewPassword)
        }
      ) {
        "Every rule block can only have either genericPassword or {current,new}Password blocks"
      }
      matchers.add(
        AutofillRuleMatcher(
          type = FillableFieldType.GenericPassword,
          matcher = FieldMatcher.Builder().apply(block).build(),
          optional = optional,
          matchHidden = false,
        )
      )
    }

    fun build(): AutofillRule {
      if (applyInSingleOriginMode) {
        require(matchers.none { it.matcher is PairOfFieldsMatcher }) {
          "Rules with applyInSingleOriginMode set to true must only match single fields"
        }
        require(matchers.filter { it.type != FillableFieldType.Username }.size <= 1) {
          "Rules with applyInSingleOriginMode set to true must only match at most one password field"
        }
        require(matchers.none { it.matchHidden }) {
          "Rules with applyInSingleOriginMode set to true must not fill into hidden fields"
        }
      }
      return AutofillRule(
          matchers,
          applyInSingleOriginMode,
          applyOnManualRequestOnly,
          name ?: "Rule #$ruleId",
        )
        .also { ruleId++ }
    }
  }

  fun match(
    allPassword: List<FormField>,
    allUsername: List<FormField>,
    allOtp: List<FormField>,
    singleOriginMode: Boolean,
    isManualRequest: Boolean,
  ): AutofillScenario<FormField>? {
    if (singleOriginMode && !applyInSingleOriginMode) {
      logcat { "$name: Skipped in single origin mode" }
      return null
    }
    if (!isManualRequest && applyOnManualRequestOnly) {
      logcat { "$name: Skipped since not a manual request" }
      return null
    }
    logcat { "$name: Applying..." }
    val scenarioBuilder = AutofillScenario.Builder<FormField>()
    val alreadyMatched = mutableListOf<FormField>()
    for ((type, matcher, optional, matchHidden) in matchers) {
      val fieldsToMatchOn =
        when (type) {
          FillableFieldType.Username -> allUsername
          FillableFieldType.Otp -> allOtp
          else -> allPassword
        }.filter { matchHidden || it.isVisible }
      val matchResult =
        matcher.match(fieldsToMatchOn, alreadyMatched)
          ?: if (optional) {
            logcat { "$name: Skipping optional $type matcher" }
            continue
          } else {
            logcat { "$name: Required $type matcher didn't match; passing to next rule" }
            return null
          }
      logcat { "$name: Matched $type" }
      when (type) {
        FillableFieldType.Username -> {
          check(matchResult.size == 1 && scenarioBuilder.username == null) {
            "Scenario has existing username or too many matches"
          }
          scenarioBuilder.username = matchResult.single()
          // Hidden username fields should be saved but not filled.
          scenarioBuilder.fillUsername = scenarioBuilder.username!!.isVisible == true
        }
        FillableFieldType.Otp -> {
          check(matchResult.size == 1 && scenarioBuilder.otp == null) {
            "Scenario has existing OTP or too many matches"
          }
          scenarioBuilder.otp = matchResult.single()
        }
        FillableFieldType.CurrentPassword -> scenarioBuilder.currentPassword.addAll(matchResult)
        FillableFieldType.NewPassword -> scenarioBuilder.newPassword.addAll(matchResult)
        FillableFieldType.GenericPassword -> scenarioBuilder.genericPassword.addAll(matchResult)
      }
      alreadyMatched.addAll(matchResult)
    }
    return scenarioBuilder.build().takeIf { scenario ->
      scenario.passesOriginCheck(singleOriginMode = singleOriginMode).also { passed ->
        if (passed) {
          logcat { "$name: Detected scenario:\n$scenario" }
        } else {
          logcat(WARN) { "$name: Scenario failed origin check:\n$scenario" }
        }
      }
    }
  }
}

@RequiresApi(Build.VERSION_CODES.O)
internal class AutofillStrategy private constructor(private val rules: List<AutofillRule>) {

  @AutofillDsl
  class Builder {

    private val rules: MutableList<AutofillRule> = mutableListOf()

    fun rule(
      applyInSingleOriginMode: Boolean = false,
      applyOnManualRequestOnly: Boolean = false,
      block: AutofillRule.Builder.() -> Unit,
    ) {
      rules.add(
        AutofillRule.Builder(
            applyInSingleOriginMode = applyInSingleOriginMode,
            applyOnManualRequestOnly = applyOnManualRequestOnly,
          )
          .apply(block)
          .build()
      )
    }

    fun build() = AutofillStrategy(rules)
  }

  fun match(
    fields: List<FormField>,
    singleOriginMode: Boolean,
    isManualRequest: Boolean,
  ): AutofillScenario<FormField>? {
    val possiblePasswordFields = fields.filter { it.passwordCertainty >= CertaintyLevel.Possible }
    logcat { "Possible password fields: ${possiblePasswordFields.size}" }
    val possibleUsernameFields = fields.filter { it.usernameCertainty >= CertaintyLevel.Possible }
    logcat { "Possible username fields: ${possibleUsernameFields.size}" }
    val possibleOtpFields = fields.filter { it.otpCertainty >= CertaintyLevel.Possible }
    logcat { "Possible otp fields: ${possibleOtpFields.size}" }
    // Return the result of the first rule that matches
    logcat { "Rules: ${rules.size}" }
    for (rule in rules) {
      return rule.match(
        possiblePasswordFields,
        possibleUsernameFields,
        possibleOtpFields,
        singleOriginMode = singleOriginMode,
        isManualRequest = isManualRequest,
      ) ?: continue
    }
    return null
  }
}

@RequiresApi(Build.VERSION_CODES.O)
internal fun strategy(block: AutofillStrategy.Builder.() -> Unit) =
  AutofillStrategy.Builder().apply(block).build()