/
ReceiptExchangeTest.kt
412 lines (364 loc) · 19.3 KB
/
ReceiptExchangeTest.kt
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
package ch.veehait.devicecheck.appattest.receipt
import ch.veehait.devicecheck.appattest.AppleAppAttest
import ch.veehait.devicecheck.appattest.CertUtils
import ch.veehait.devicecheck.appattest.CertUtils.toPEM
import ch.veehait.devicecheck.appattest.TestExtensions.fixedUtcClock
import ch.veehait.devicecheck.appattest.common.App
import ch.veehait.devicecheck.appattest.common.AppleAppAttestEnvironment
import ch.veehait.devicecheck.appattest.common.EqualsVerifierPrefabValues
import ch.veehait.devicecheck.appattest.util.Extensions.createAppleKeyId
import ch.veehait.devicecheck.appattest.util.Extensions.fromBase64
import ch.veehait.devicecheck.appattest.util.Extensions.toBase64
import io.kotest.assertions.throwables.shouldNotThrowAny
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.comparables.shouldBeGreaterThan
import io.kotest.matchers.comparables.shouldBeLessThan
import io.kotest.matchers.ints.shouldBeGreaterThanOrEqual
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.kotest.matchers.throwable.shouldHaveMessage
import io.kotest.property.Exhaustive
import io.kotest.property.checkAll
import io.kotest.property.exhaustive.longs
import nl.jqno.equalsverifier.EqualsVerifier
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import java.net.HttpURLConnection
import java.net.URI
import java.net.http.HttpHeaders
import java.time.Clock
import java.time.Duration
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
class ReceiptExchangeTest : FreeSpec() {
private val nullAppleJwsGenerator = object : AppleJwsGenerator {
override val teamIdentifier = ""
override val keyIdentifier = ""
override val privateKey = CertUtils.generateP256KeyPair().private
override fun issueToken() = ""
}
init {
"AppleReceiptHttpClientAdapter.Response: equals/hashCode" {
EqualsVerifier.forClass(AppleReceiptExchangeHttpClientAdapter.Response::class.java)
.withPrefabValues(
HttpHeaders::class.java,
EqualsVerifierPrefabValues.HttpHeaders.red,
EqualsVerifierPrefabValues.HttpHeaders.blue,
)
.verify()
}
"Has correct constant for Apple's development server endpoint" {
// Use the base URL of https://data-development.appattest.apple.com shown in the example above for testing.
with(ReceiptExchange) {
APPLE_DEVICE_CHECK_APP_ATTEST_DEVELOPMENT_URL.toString() shouldBe
"https://data-development.appattest.apple.com/v1/attestationData"
APPLE_DEVICE_CHECK_APP_ATTEST_DEVELOPMENT_URL shouldNotBe APPLE_DEVICE_CHECK_APP_ATTEST_PRODUCTION_URL
}
}
"Has correct constant for Apple's production server endpoint" {
// To work with apps that you’ve distributed through the App Store, TestFlight, or with an Enterprise
// Developer certificate, use a base URL of https://data.appattest.apple.com instead.
with(ReceiptExchange) {
APPLE_DEVICE_CHECK_APP_ATTEST_PRODUCTION_URL.toString() shouldBe
"https://data.appattest.apple.com/v1/attestationData"
APPLE_DEVICE_CHECK_APP_ATTEST_PRODUCTION_URL shouldNotBe APPLE_DEVICE_CHECK_APP_ATTEST_DEVELOPMENT_URL
}
}
"ReceiptExchange works with MockWebServer" {
val receiptSamples: List<ReceiptSample> = ReceiptSample.all
val attestationReceipt = receiptSamples.first { it.properties.type == Receipt.Type.ATTEST }
val responseReceipt = receiptSamples.first { it.properties.type == Receipt.Type.RECEIPT }
val appleAppAttest = AppleAppAttest(
app = App(attestationReceipt.teamIdentifier, attestationReceipt.bundleIdentifier),
appleAppAttestEnvironment = attestationReceipt.environment,
)
val serverResponseClock = Clock.fixed(responseReceipt.timestamp, ZoneOffset.UTC)
val date = DateTimeFormatter
.RFC_1123_DATE_TIME
.withZone(serverResponseClock.zone)
.format(serverResponseClock.instant())
val responseBody = responseReceipt.receipt.toBase64()
val mockResponse = MockResponse().apply {
setHeader("Server", "Apple")
setHeader("Date", date)
setHeader("Content-Type", "base64")
setHeader("Content-Length", responseBody.length.toString())
setHeader("Connection", "keep-alive")
setHeader("X-B3-TraceId", "6aa9ae171ae70fd9")
setHeader("Strict-Transport-Security", "max-age=31536000; includeSubdomains")
setHeader("X-Frame-Options", "SAMEORIGIN")
setHeader("X-Content-Type-Options", "nosniff")
setHeader("X-XSS-Protection", "1; mode=block")
setResponseCode(HttpURLConnection.HTTP_OK)
setBody(responseBody)
}
val mockWebServer = MockWebServer().apply {
enqueue(mockResponse)
start()
}
val appleServerUrl = when (attestationReceipt.environment) {
AppleAppAttestEnvironment.DEVELOPMENT -> ReceiptExchange.APPLE_DEVICE_CHECK_APP_ATTEST_DEVELOPMENT_URL
AppleAppAttestEnvironment.PRODUCTION -> ReceiptExchange.APPLE_DEVICE_CHECK_APP_ATTEST_PRODUCTION_URL
}
val mockWebServerUri = mockWebServer.url(appleServerUrl.path).toUri()
// Actual test
val receiptExchange = appleAppAttest.createReceiptExchange(
appleJwsGenerator = AppleJwsGeneratorImpl(
teamIdentifier = attestationReceipt.teamIdentifier,
keyIdentifier = "WURZELPFRO",
privateKeyPem = CertUtils.generateP256KeyPair().private.toPEM(),
clock = serverResponseClock,
),
receiptValidator = appleAppAttest.createReceiptValidator(
clock = serverResponseClock,
),
appleDeviceCheckUrl = mockWebServerUri,
appleReceiptExchangeHttpClientAdapter = SimpleAppleReceiptExchangeHttpClientAdapter(),
)
val receipt = receiptExchange.trade(
receiptP7 = attestationReceipt.receipt,
attestationPublicKey = attestationReceipt.publicKey,
)
mockWebServer.shutdown()
receipt.p7 shouldBe mockResponse.getBody()!!.readByteArray().fromBase64()
}
"ReceiptExchange returns same receipt for too early request with MockWebServer" {
val receiptSamples: List<ReceiptSample> = ReceiptSample.all
val responseReceipt = receiptSamples.first { it.properties.type == Receipt.Type.RECEIPT }
val appleAppAttest = AppleAppAttest(
app = App(responseReceipt.teamIdentifier, responseReceipt.bundleIdentifier),
appleAppAttestEnvironment = responseReceipt.environment,
)
val serverResponseClock = Clock.fixed(responseReceipt.timestamp, ZoneOffset.UTC)
val date = DateTimeFormatter
.RFC_1123_DATE_TIME
.withZone(serverResponseClock.zone)
.format(serverResponseClock.instant())
val mockResponse = MockResponse().apply {
setHeader("Server", "Apple")
setHeader("Date", date)
setHeader("Content-Length", 0)
setHeader("Connection", "keep-alive")
setHeader("X-B3-TraceId", "ae2f84c23e116eb5")
setHeader("Strict-Transport-Security", "max-age=31536000; includeSubdomains")
setHeader("X-Frame-Options", "SAMEORIGIN")
setHeader("X-Content-Type-Options", "nosniff")
setHeader("X-XSS-Protection", "1; mode=block")
setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)
}
val mockWebServer = MockWebServer().apply {
enqueue(mockResponse)
start()
}
val appleServerUrl = when (responseReceipt.environment) {
AppleAppAttestEnvironment.DEVELOPMENT -> ReceiptExchange.APPLE_DEVICE_CHECK_APP_ATTEST_DEVELOPMENT_URL
AppleAppAttestEnvironment.PRODUCTION -> ReceiptExchange.APPLE_DEVICE_CHECK_APP_ATTEST_PRODUCTION_URL
}
val mockWebServerUri = mockWebServer.url(appleServerUrl.path).toUri()
// Actual test
val receiptExchange = appleAppAttest.createReceiptExchange(
appleJwsGenerator = nullAppleJwsGenerator,
receiptValidator = appleAppAttest.createReceiptValidator(
clock = serverResponseClock,
),
appleDeviceCheckUrl = mockWebServerUri,
appleReceiptExchangeHttpClientAdapter = SimpleAppleReceiptExchangeHttpClientAdapter(),
sanityChecks = false,
)
val receipt = receiptExchange.trade(
receiptP7 = responseReceipt.receipt,
attestationPublicKey = responseReceipt.publicKey,
)
mockWebServer.shutdown()
receipt.p7 shouldBe responseReceipt.receipt
}
"ReceiptExchange throws ReceiptExchangeException.HttpError for an unsuccessful call to Apple's servers" {
// Test setup
val sample = ReceiptSample.all.random()
val appleAppAttest = sample.defaultAppleAppAttest()
// Actual test
val mockWebServer = MockWebServer().apply {
enqueue(MockResponse().apply { setResponseCode(403) })
start()
}
val receiptExchange = appleAppAttest.createReceiptExchange(
appleJwsGenerator = nullAppleJwsGenerator,
receiptValidator = appleAppAttest.createReceiptValidator(
clock = sample.timestamp.fixedUtcClock(),
),
appleDeviceCheckUrl = mockWebServer.url("/v1/attestationData").toUri(),
sanityChecks = false,
)
val exception = shouldThrow<ReceiptExchangeException.HttpError> {
receiptExchange.trade(
receiptP7 = sample.receipt,
attestationPublicKey = sample.publicKey,
)
}
mockWebServer.shutdown()
exception.shouldHaveMessage(
"Caught an error in Apple's response: Response(statusCode=403, " +
"headers=java.net.http.HttpHeaders@bc7b26f5 { {content-length=[0]} }, body=[])",
)
}
"Throws ReceiptExpired for a receipt which is too old" - {
val sample = ReceiptSample.all.random()
val appleAppAttest = sample.defaultAppleAppAttest()
val receipt = appleAppAttest.createReceiptValidator(
clock = sample.timestamp.fixedUtcClock(),
).validateReceipt(
receiptP7 = sample.receipt,
publicKey = sample.publicKey,
)
checkAll(Exhaustive.longs(-1L..1L)) { nanosOffset ->
val receiptExchange = appleAppAttest.createReceiptExchange(
appleJwsGenerator = nullAppleJwsGenerator,
receiptValidator = appleAppAttest.createReceiptValidator(
clock = receipt.payload.expirationTime.value.plusNanos(nanosOffset).fixedUtcClock(),
),
appleReceiptExchangeHttpClientAdapter = object : AppleReceiptExchangeHttpClientAdapter {
override fun post(
uri: URI,
authorizationHeader: Map<String, String>,
body: ByteArray,
): AppleReceiptExchangeHttpClientAdapter.Response {
throw IllegalAccessError("wurzelpfropf")
}
},
sanityChecks = true,
)
if (nanosOffset < 0L) {
"Accepts offset of ${nanosOffset}ns to expiry date" {
val exception = shouldThrow<IllegalAccessError> {
receiptExchange.trade(
receiptP7 = sample.receipt,
attestationPublicKey = sample.publicKey,
)
}
exception.shouldHaveMessage("wurzelpfropf")
}
} else {
"Rejects offset of ${nanosOffset}ns to expiry date" {
shouldThrow<ReceiptExchangeException.ReceiptExpired> {
receiptExchange.trade(
receiptP7 = sample.receipt,
attestationPublicKey = sample.publicKey,
)
}
}
}
}
}
"Returns same receipt for too early call" - {
ReceiptSample.all.forEach { sample ->
val appleAppAttest = sample.defaultAppleAppAttest()
val receipt = appleAppAttest.createReceiptValidator(
clock = sample.timestamp.fixedUtcClock(),
).validateReceipt(
receiptP7 = sample.receipt,
publicKey = sample.publicKey,
)
val receiptType = receipt.payload.type.value
"$receiptType/${sample.id}" - {
checkAll(Exhaustive.longs(-1L..1L)) { nanosOffset ->
val receiptExchange = appleAppAttest.createReceiptExchange(
appleJwsGenerator = nullAppleJwsGenerator,
receiptValidator = appleAppAttest.createReceiptValidator(
clock = when (receiptType) {
Receipt.Type.RECEIPT -> receipt.payload.notBefore!!.value.plusNanos(nanosOffset)
.fixedUtcClock()
Receipt.Type.ATTEST -> receipt.payload.creationTime.value.fixedUtcClock()
},
),
appleReceiptExchangeHttpClientAdapter = object : AppleReceiptExchangeHttpClientAdapter {
override fun post(
uri: URI,
authorizationHeader: Map<String, String>,
body: ByteArray,
): AppleReceiptExchangeHttpClientAdapter.Response {
throw IllegalAccessError("wurzelpfropf")
}
},
sanityChecks = true,
)
if (receiptType == Receipt.Type.RECEIPT && nanosOffset < 0L) {
"validty offset ${nanosOffset}ns: No remote call" {
val receiptNew = shouldNotThrowAny {
receiptExchange.trade(
receiptP7 = sample.receipt,
attestationPublicKey = sample.publicKey,
)
}
receiptNew.p7 shouldBe sample.receipt
}
} else {
"validty offset ${nanosOffset}ns: Remote call" {
val exception = shouldThrow<IllegalAccessError> {
receiptExchange.trade(
receiptP7 = sample.receipt,
attestationPublicKey = sample.publicKey,
)
}
exception.shouldHaveMessage("wurzelpfropf")
}
}
}
}
}
}
val appleDeviceCheckKid = "94M3Z58NQ7"
val appleDeviceCheckPrivateKeyPem = System.getenv("APPLE_KEY_P8_$appleDeviceCheckKid")
@Suppress("TooGenericExceptionThrown")
"receipt exchange works".config(enabled = appleDeviceCheckPrivateKeyPem != null) {
// Test setup
val now = Instant.now()
val sample = ReceiptSample.all.filter {
(it.properties.notBefore ?: Instant.EPOCH) < now && it.properties.expirationTime > now
}.maxByOrNull { it.timestamp } ?: throw RuntimeException("No suitable sample to trade found")
val appleAppAttest = sample.defaultAppleAppAttest()
// Actual test
val receiptExchange = appleAppAttest.createReceiptExchange(
appleJwsGenerator = AppleJwsGeneratorImpl(
teamIdentifier = sample.teamIdentifier,
keyIdentifier = appleDeviceCheckKid,
privateKeyPem = appleDeviceCheckPrivateKeyPem,
),
receiptValidator = appleAppAttest.createReceiptValidator(),
)
val receipt = receiptExchange.trade(
receiptP7 = sample.receipt,
attestationPublicKey = sample.publicKey,
)
if (!sample.receipt.contentEquals(receipt.p7)) {
with(receipt.payload) {
appId.value shouldBe appleAppAttest.app.appIdentifier
attestationCertificate.value.publicKey shouldBe sample.publicKey
attestationCertificate.value.publicKey.createAppleKeyId() shouldBe sample.keyId
if (sample.properties.type == Receipt.Type.RECEIPT) {
clientHash.value shouldBe sample.properties.clientHash
}
creationTime.value shouldBeGreaterThan Instant.now().minus(Duration.ofMinutes(5))
creationTime.value shouldBeLessThan Instant.now().plus(Duration.ofMinutes(5))
environment?.value shouldBe sample.properties.environment
expirationTime.value shouldBe creationTime.value.plus(Duration.ofDays(90))
if (notBefore != null) {
notBefore!!.value shouldBe creationTime.value.plus(Duration.ofDays(1))
}
when (sample.environment) {
AppleAppAttestEnvironment.DEVELOPMENT -> {
// In a development environment, Apple seems to clear the stored risk metric every
// now and then
riskMetric!!.value shouldBeGreaterThanOrEqual 1
}
AppleAppAttestEnvironment.PRODUCTION -> {
riskMetric!!.value shouldBeGreaterThanOrEqual (sample.properties.riskMetric ?: 0)
}
}
type.value shouldBe Receipt.Type.RECEIPT
}
}
}
}
}