@tokamakdev/platform-android-arm64 0.1.1-beta.154 → 0.1.1-beta.155

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -260,55 +260,6 @@ release_signing() {
260
260
  EOF
261
261
  }
262
262
 
263
- # The gateway's server certificate for the app host, with its key, in
264
- # assets/tokamak-gateway.p12. The network security config trusts the
265
- # certificate's authority for the app host alone, so the WebView verifies the
266
- # gateway itself. Each build creates its own authority and discards the
267
- # authority's key. The gateway's key ships in the app, which is safe only while
268
- # the WebView sends the app host's traffic to no listener but the gateway. The
269
- # keystore's password is public, so the keystore uses the algorithms every
270
- # Android version reads, at one iteration, and the certificates outlive any app.
271
- gateway_identity() {
272
- local keytool=keytool
273
- if [[ -n "${JAVA_HOME:-}" ]]; then
274
- keytool=$JAVA_HOME/bin/keytool
275
- fi
276
- if ! command -v "$keytool" > /dev/null; then
277
- echo "Android builds create the gateway certificate with keytool, which the JDK provides" >&2
278
- exit 69
279
- fi
280
- local resources=$app/src/main/res
281
- local keystore=(
282
- "$keytool"
283
- -J-Dkeystore.pkcs12.certProtectionAlgorithm=NONE
284
- -J-Dkeystore.pkcs12.keyProtectionAlgorithm=PBEWithSHA1AndDESede
285
- -J-Dkeystore.pkcs12.macAlgorithm=HmacPBESHA1
286
- -J-Dkeystore.pkcs12.keyPbeIterationCount=1
287
- -J-Dkeystore.pkcs12.macIterationCount=1
288
- -keystore "$app/src/main/assets/tokamak-gateway.p12" -storetype PKCS12 -storepass tokamak
289
- )
290
- local key=(-keyalg EC -groupname secp256r1 -sigalg SHA256withECDSA -validity 36500)
291
- mkdir -p "$resources/raw" "$resources/xml"
292
- "${keystore[@]}" -genkeypair -alias authority "${key[@]}" -dname 'CN=tokamak gateway' \
293
- -ext bc:c=ca:true,pathlen:0
294
- "${keystore[@]}" -genkeypair -alias gateway "${key[@]}" -dname "CN=$host" -signer authority \
295
- -ext "san=dns:$host" -ext eku=serverAuth -ext ku:c=digitalSignature
296
- "${keystore[@]}" -exportcert -alias authority -rfc -file "$resources/raw/tokamak_gateway_authority.pem"
297
- "${keystore[@]}" -delete -alias authority
298
- cat > "$resources/xml/tokamak_network_security_config.xml" <<EOF
299
- <?xml version="1.0" encoding="utf-8"?>
300
- <network-security-config>
301
- <base-config cleartextTrafficPermitted="false" />
302
- <domain-config>
303
- <domain includeSubdomains="false">$(xml_escape "$host")</domain>
304
- <trust-anchors>
305
- <certificates src="@raw/tokamak_gateway_authority" />
306
- </trust-anchors>
307
- </domain-config>
308
- </network-security-config>
309
- EOF
310
- }
311
-
312
263
  xml_escape() {
313
264
  printf '%s' "$1" |
314
265
  sed -e 's/&/\&amp;/g' \
@@ -350,7 +301,6 @@ if [[ -n "$icon" ]]; then
350
301
  fi
351
302
  has_icon=true
352
303
  fi
353
- gateway_identity
354
304
 
355
305
  # Each plugin is a library module, so its manifest merges below the app's and
356
306
  # its dependencies stay its own. Its class is a Kotlin class name in a package,
@@ -524,7 +474,7 @@ manifest=$app/src/main/AndroidManifest.xml
524
474
  if [[ "$has_icon" == true ]]; then
525
475
  icon_attribute=' android:icon="@mipmap/ic_launcher"'
526
476
  fi
527
- printf ' <application android:name=".TokamakApplication" android:label="%s"%s android:networkSecurityConfig="@xml/tokamak_network_security_config">\n' "$(xml_escape "$app_name")" "$icon_attribute"
477
+ printf ' <application android:name=".TokamakApplication" android:label="%s"%s>\n' "$(xml_escape "$app_name")" "$icon_attribute"
528
478
  printf ' <meta-data android:name="tokamak.host" android:value="%s" />\n' "$host"
529
479
  if [[ -n "$dev_endpoint" ]]; then
530
480
  printf ' <meta-data android:name="tokamak.dev.endpoint" android:value="%s" />\n' "$dev_endpoint"
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/android-arm64/lib/TokamakRuntime/libtokamak.a
3
- size: 35491552 bytes
4
- sha256: c6c8fa2befb1c13110a8277ac80a59d60429bd236abca8351ff68e17dc66e372
3
+ size: 35501050 bytes
4
+ sha256: 0b6750c489dc8075331637a2b990298e118528c270e5e30ee774134f32343d44
@@ -23,6 +23,9 @@ class TokamakActivity : Activity() {
23
23
  get() = application as TokamakApplication
24
24
  internal lateinit var webView: WebView
25
25
  private set
26
+ private var runtime: TokamakRuntime? = null
27
+ private var proxyPort: Int? = null
28
+ private var restoreGeneration = 0L
26
29
  private var destroyed = false
27
30
 
28
31
  override fun onCreate(savedInstanceState: Bundle?) {
@@ -51,6 +54,13 @@ class TokamakActivity : Activity() {
51
54
  deliver(intent)
52
55
  }
53
56
 
57
+ override fun onResume() {
58
+ super.onResume()
59
+ restoreGeneration += 1
60
+ val generation = restoreGeneration
61
+ runtime?.let { restoreGateway(it, generation) }
62
+ }
63
+
54
64
  override fun onDestroy() {
55
65
  destroyed = true
56
66
  if (tokamak.activity === this) tokamak.activity = null
@@ -85,9 +95,35 @@ class TokamakActivity : Activity() {
85
95
  show(FAILED)
86
96
  return
87
97
  }
98
+ this.runtime = runtime
99
+ proxyPort = runtime.port
88
100
  TokamakProxy.route(this, tokamak.appHost, runtime.port) { load(runtime) }
89
101
  }
90
102
 
103
+ /** Waits for the gateway and re-routes the proxy once its port moved. */
104
+ private fun restoreGateway(runtime: TokamakRuntime, generation: Long) {
105
+ Thread {
106
+ val result = runCatching { runtime.restoreGateway() }
107
+ runOnUiThread {
108
+ if (
109
+ destroyed ||
110
+ this.runtime !== runtime ||
111
+ generation != restoreGeneration
112
+ ) return@runOnUiThread
113
+ result
114
+ .onSuccess { port ->
115
+ if (port != proxyPort) {
116
+ proxyPort = port
117
+ TokamakProxy.route(this, tokamak.appHost, port) { load(runtime) }
118
+ }
119
+ }
120
+ .onFailure { error ->
121
+ Log.w(TAG, "tokamak gateway could not recover", error)
122
+ }
123
+ }
124
+ }.start()
125
+ }
126
+
91
127
  private fun load(runtime: TokamakRuntime) {
92
128
  if (destroyed) return
93
129
  webView.webViewClient =
@@ -11,7 +11,6 @@ import androidx.lifecycle.Lifecycle
11
11
  import androidx.lifecycle.LifecycleOwner
12
12
  import androidx.lifecycle.ProcessLifecycleOwner
13
13
  import java.io.File
14
- import java.security.KeyStore
15
14
  import java.util.concurrent.Executors
16
15
  import kotlin.coroutines.resume
17
16
  import kotlin.reflect.KClass
@@ -24,12 +23,6 @@ private const val DEV_SESSION_TOKEN_METADATA = "tokamak.dev.session-token"
24
23
  /** How long the Worker has for `resume` and `suspend`. */
25
24
  private const val LIFECYCLE_DEADLINE_MILLIS = 10_000L
26
25
 
27
- /** The asset holding the gateway's server certificate and key, which the build creates. */
28
- private const val GATEWAY_KEYSTORE = "tokamak-gateway.p12"
29
-
30
- /** The gateway keystore's password, which is public: the key ships in the app. */
31
- private const val GATEWAY_KEYSTORE_PASSWORD = "tokamak"
32
-
33
26
  /**
34
27
  * The tokamak process. Owns the runtime and native plugins, which outlive any activity, so a
35
28
  * plugin can run Worker code when the system starts the app in the background.
@@ -207,15 +200,14 @@ class TokamakApplication : Application(), TokamakPlugins {
207
200
  val endpoint = metadata?.getString(DEV_ENDPOINT_METADATA)
208
201
  val sessionToken = metadata?.getString(DEV_SESSION_TOKEN_METADATA)
209
202
  val startsInForeground = activity != null
210
- val server = gatewayIdentity()
211
203
  val runtime =
212
204
  if (!endpoint.isNullOrEmpty() && !sessionToken.isNullOrEmpty()) {
213
205
  TokamakRuntime.startDevelopment(
214
- stateDir(), appHost, endpoint, sessionToken, server, startsInForeground, workerPlugins,
206
+ stateDir(), appHost, endpoint, sessionToken, startsInForeground, workerPlugins,
215
207
  )
216
208
  } else {
217
209
  TokamakRuntime.start(
218
- unpackApp(), stateDir(), storageDir(), appHost, server, startsInForeground, workerPlugins,
210
+ unpackApp(), stateDir(), storageDir(), appHost, startsInForeground, workerPlugins,
219
211
  )
220
212
  }
221
213
  mainExecutor.execute {
@@ -224,14 +216,6 @@ class TokamakApplication : Application(), TokamakPlugins {
224
216
  return runtime
225
217
  }
226
218
 
227
- /** The gateway's server certificate and key. */
228
- private fun gatewayIdentity(): KeyStore.PrivateKeyEntry {
229
- val password = GATEWAY_KEYSTORE_PASSWORD.toCharArray()
230
- val keystore = KeyStore.getInstance("PKCS12")
231
- assets.open(GATEWAY_KEYSTORE).use { keystore.load(it, password) }
232
- return keystore.getEntry("gateway", KeyStore.PasswordProtection(password)) as KeyStore.PrivateKeyEntry
233
- }
234
-
235
219
  private fun metadata() =
236
220
  packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA).metaData
237
221
 
@@ -6,30 +6,36 @@ import androidx.webkit.ProxyController
6
6
 
7
7
  /**
8
8
  * Routes the app host, in every WebView of the process, through the gateway's port. The gateway
9
- * keeps one port for the life of the process, so the route is set once and never cleared: without
10
- * it the WebView would connect to the app host itself, where another app or device could answer.
11
- * Main thread only.
9
+ * can lose its port and bind another, so the route follows whichever port it reports. Without a
10
+ * route the WebView would connect to the app host itself, where another app or device could
11
+ * answer. Main thread only.
12
12
  */
13
13
  internal object TokamakProxy {
14
- private var routed = false
14
+ private var routed: Int? = null
15
+ private var requested: Int? = null
15
16
  private val waiting = mutableListOf<() -> Unit>()
16
17
 
17
- /** Routes [host] through the gateway's [port], then runs [ready] once the route is in place. */
18
+ /**
19
+ * Routes [host] through the gateway's [port], then runs [ready] once the route is in place. A
20
+ * call for another port while a route is pending replaces it, and every waiting [ready] runs
21
+ * once the latest route is in place.
22
+ */
18
23
  fun route(context: Context, host: String, port: Int, ready: () -> Unit) {
19
- if (routed) {
24
+ if (routed == port && requested == port) {
20
25
  ready()
21
26
  return
22
27
  }
23
28
  waiting += ready
24
- // Only the first caller requests the route.
25
- if (waiting.size > 1) return
29
+ if (requested == port) return
30
+ requested = port
26
31
  val config = ProxyConfig.Builder()
27
32
  .addProxyRule("http://127.0.0.1:$port")
28
33
  .addBypassRule(host)
29
34
  .setReverseBypassEnabled(true)
30
35
  .build()
31
36
  ProxyController.getInstance().setProxyOverride(config, context.mainExecutor) {
32
- routed = true
37
+ routed = port
38
+ if (requested != port) return@setProxyOverride
33
39
  waiting.forEach { it() }
34
40
  waiting.clear()
35
41
  }
@@ -1,7 +1,6 @@
1
1
  package com.tokamak.runtime
2
2
 
3
3
  import java.io.File
4
- import java.security.KeyStore
5
4
 
6
5
  /** The tokamak runtime, running for the life of the process. */
7
6
  internal class TokamakRuntime private constructor(private val handle: Long) {
@@ -28,6 +27,15 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
28
27
  val port: Int
29
28
  get() = nativePort(handle)
30
29
 
30
+ /**
31
+ * The authority a server certificate for [host] must chain to, or null
32
+ * when tokamak does not vouch for the host.
33
+ */
34
+ fun serverAuthority(host: String): ByteArray? = nativeServerAuthority(handle, host)
35
+
36
+ /** Wait for the runtime's loopback gateway and return its current port. */
37
+ fun restoreGateway(): Int = nativeRestoreGateway(handle)
38
+
31
39
  /**
32
40
  * Delivers the event [name] with its encoded [payload] to the Worker's listeners, blocking
33
41
  * until they return or [timeoutMillis] passes, and returns their encoded reply, which is empty
@@ -68,15 +76,14 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
68
76
  }
69
77
 
70
78
  /**
71
- * Start the runtime, which delivers `start` with [foreground], whose Worker calls
72
- * [plugins], and whose gateway presents [server], throwing when it cannot serve the app.
79
+ * Start the runtime, which delivers `start` with [foreground] and whose Worker calls
80
+ * [plugins], throwing when it cannot serve the app.
73
81
  */
74
82
  fun start(
75
83
  packagedDir: File,
76
84
  stateDir: File,
77
85
  storageDir: File,
78
86
  host: String,
79
- server: KeyStore.PrivateKeyEntry,
80
87
  foreground: Boolean,
81
88
  plugins: Plugins,
82
89
  ): TokamakRuntime =
@@ -86,8 +93,6 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
86
93
  stateDir.path,
87
94
  storageDir.path,
88
95
  host,
89
- server.chain(),
90
- server.privateKey.encoded,
91
96
  foreground,
92
97
  plugins,
93
98
  ),
@@ -95,15 +100,13 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
95
100
 
96
101
  /**
97
102
  * Start the runtime against a host development server, delivering `start` with
98
- * [foreground], whose development Worker calls [plugins], and whose gateway presents
99
- * [server].
103
+ * [foreground] and whose development Worker calls [plugins].
100
104
  */
101
105
  fun startDevelopment(
102
106
  stateDir: File,
103
107
  host: String,
104
108
  endpoint: String,
105
109
  sessionToken: String,
106
- server: KeyStore.PrivateKeyEntry,
107
110
  foreground: Boolean,
108
111
  plugins: Plugins,
109
112
  ): TokamakRuntime =
@@ -113,25 +116,17 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
113
116
  host,
114
117
  endpoint,
115
118
  sessionToken,
116
- server.chain(),
117
- server.privateKey.encoded,
118
119
  foreground,
119
120
  plugins,
120
121
  ),
121
122
  )
122
123
 
123
- /** The entry's certificates, leaf first, in DER. */
124
- private fun KeyStore.PrivateKeyEntry.chain(): Array<ByteArray> =
125
- certificateChain.map { it.encoded }.toTypedArray()
126
-
127
124
  @JvmStatic
128
125
  private external fun nativeStart(
129
126
  packagedDir: String,
130
127
  stateDir: String,
131
128
  storageDir: String,
132
129
  host: String,
133
- serverChain: Array<ByteArray>,
134
- serverKey: ByteArray,
135
130
  foreground: Boolean,
136
131
  plugins: Plugins,
137
132
  ): Long
@@ -142,12 +137,16 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
142
137
  host: String,
143
138
  endpoint: String,
144
139
  sessionToken: String,
145
- serverChain: Array<ByteArray>,
146
- serverKey: ByteArray,
147
140
  foreground: Boolean,
148
141
  plugins: Plugins,
149
142
  ): Long
150
143
 
144
+ @JvmStatic
145
+ private external fun nativeServerAuthority(handle: Long, host: String): ByteArray?
146
+
147
+ @JvmStatic
148
+ private external fun nativeRestoreGateway(handle: Long): Int
149
+
151
150
  @JvmStatic
152
151
  private external fun nativeSetForeground(handle: Long, foreground: Boolean): Boolean
153
152
 
@@ -4,7 +4,9 @@ import android.app.Activity
4
4
  import android.content.Intent
5
5
  import android.graphics.Bitmap
6
6
  import android.net.Uri
7
+ import android.net.http.SslError
7
8
  import android.webkit.ClientCertRequest
9
+ import android.webkit.SslErrorHandler
8
10
  import android.webkit.WebResourceRequest
9
11
  import android.webkit.WebView
10
12
  import android.webkit.WebViewClient
@@ -15,10 +17,7 @@ import java.security.cert.CertificateFactory
15
17
  import java.security.cert.X509Certificate
16
18
  import java.security.spec.PKCS8EncodedKeySpec
17
19
 
18
- /**
19
- * Answers the app origin's client certificate requests with the runtime's decision. The network
20
- * security config trusts the gateway's certificate, so no certificate error reaches the app.
21
- */
20
+ /** Answers the app origin's TLS challenges with the runtime's decision. */
22
21
  internal class TokamakWebViewClient(
23
22
  private val activity: Activity,
24
23
  private val host: String,
@@ -41,6 +40,19 @@ internal class TokamakWebViewClient(
41
40
  return true
42
41
  }
43
42
 
43
+ override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
44
+ val host = Uri.parse(error.url).host
45
+ val authority = host?.let(runtime::serverAuthority)
46
+ val trusted = authority != null && chainsTo(error, authority)
47
+ if (trusted) {
48
+ android.util.Log.i("tokamak", "trusted the gateway's certificate for $host (${error.primaryError})")
49
+ handler.proceed()
50
+ return
51
+ }
52
+ if (authority != null) android.util.Log.w("tokamak", "refused the gateway's certificate: $error")
53
+ handler.cancel()
54
+ }
55
+
44
56
  override fun onReceivedClientCertRequest(view: WebView, request: ClientCertRequest) {
45
57
  val identity = runtime.clientIdentity(request.host)
46
58
  if (identity == null) {
@@ -76,4 +88,25 @@ internal class TokamakWebViewClient(
76
88
  runCatching {
77
89
  KeyFactory.getInstance("EC").generatePrivate(PKCS8EncodedKeySpec(der))
78
90
  }.getOrNull()
91
+
92
+ /**
93
+ * Whether the runtime's authority signed `error`'s certificate, allowing only the failures
94
+ * reported for an untrusted certificate or a wrong device clock: the runtime issues and renews
95
+ * the certificate itself, so its signature is the trust decision. The primary error is the most
96
+ * severe one, which hides a lesser hostname mismatch, so that is checked on its own.
97
+ */
98
+ private fun chainsTo(error: SslError, authority: ByteArray): Boolean {
99
+ if (!certificateError(error.primaryError)) return false
100
+ if (error.hasError(SslError.SSL_IDMISMATCH)) return false
101
+ val presented = error.certificate.x509Certificate ?: return false
102
+ val issuer = certificate(authority) ?: return false
103
+ return runCatching { presented.verify(issuer.publicKey) }.isSuccess
104
+ }
105
+
106
+ /** Whether `primary` names the certificate as untrusted or wrongly dated. */
107
+ private fun certificateError(primary: Int): Boolean =
108
+ primary == SslError.SSL_UNTRUSTED ||
109
+ primary == SslError.SSL_NOTYETVALID ||
110
+ primary == SslError.SSL_EXPIRED ||
111
+ primary == SslError.SSL_DATE_INVALID
79
112
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokamakdev/platform-android-arm64",
3
- "version": "0.1.1-beta.154",
3
+ "version": "0.1.1-beta.155",
4
4
  "description": "The tokamak platform pack for android-arm64",
5
5
  "repository": {
6
6
  "type": "git",