summaryrefslogtreecommitdiff
path: root/nexus/src/test/kotlin/SandboxAccessApiTest.kt
blob: b283389055c113d063c5293b5490afe6b6225692 (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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import io.ktor.util.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.time.delay
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.transactions.transaction
import org.junit.Ignore
import org.junit.Test
import tech.libeufin.nexus.bankaccount.getBankAccount
import tech.libeufin.sandbox.*
import java.util.*
import kotlin.concurrent.schedule

class SandboxAccessApiTest {
    val mapper = ObjectMapper()
    private fun getTxs(respJson: String): JsonNode {
        val mapper = ObjectMapper()
        return mapper.readTree(respJson).get("transactions")
    }

    /**
     * Testing that ..access-api/withdrawals/{wopid} and
     * ..access-api/accounts/{account_name}/withdrawals/{wopid}
     * are handled in the same way.
     */
    @Test
    fun doubleUriStyle() {
        // Creating one withdrawal operation.
        withTestDatabase {
            prepSandboxDb()
            val wo: TalerWithdrawalEntity = transaction {
                TalerWithdrawalEntity.new {
                    this.amount = "TESTKUDOS:3.3"
                    walletBankAccount = getBankAccountFromLabel("foo")
                    selectedExchangePayto = "payto://iban/SANDBOXX/${BAR_USER_IBAN}"
                    reservePub = "not used"
                    selectionDone = true
                }
            }
            testApplication {
                application(sandboxApp)
                // Showing withdrawal info.
                val get_with_account = client.get("/demobanks/default/access-api/accounts/foo/withdrawals/${wo.wopid}") {
                    expectSuccess = true
                }
                val get_without_account = client.get("/demobanks/default/access-api/withdrawals/${wo.wopid}") {
                    expectSuccess = true
                }
                assert(get_without_account.bodyAsText() == get_with_account.bodyAsText())
                assert(get_with_account.bodyAsText() == get_without_account.bodyAsText())
                // Confirming a withdrawal.
                val confirm_with_account = client.post("/demobanks/default/access-api/accounts/foo/withdrawals/${wo.wopid}/confirm") {
                    expectSuccess = true
                }
                val confirm_without_account = client.post("/demobanks/default/access-api/withdrawals/${wo.wopid}/confirm") {
                    expectSuccess = true
                }
                assert(confirm_with_account.status.value == confirm_without_account.status.value)
                assert(confirm_with_account.bodyAsText() == confirm_without_account.bodyAsText())
                // Aborting one withdrawal.
                var wo_to_abort = transaction {
                    TalerWithdrawalEntity.new {
                        this.amount = "TESTKUDOS:3.3"
                        walletBankAccount = getBankAccountFromLabel("foo")
                        selectedExchangePayto = "payto://iban/SANDBOXX/${BAR_USER_IBAN}"
                        reservePub = "not used"
                        selectionDone = true
                    }
                }
                val abort_with_account = client.post("/demobanks/default/access-api/accounts/foo/withdrawals/${wo_to_abort.wopid}/abort") {
                    expectSuccess = true
                }
                wo_to_abort = transaction {
                    TalerWithdrawalEntity.new {
                        this.amount = "TESTKUDOS:3.3"
                        walletBankAccount = getBankAccountFromLabel("foo")
                        selectedExchangePayto = "payto://iban/SANDBOXX/${BAR_USER_IBAN}"
                        reservePub = "not used"
                        selectionDone = true
                    }
                }
                val abort_without_account = client.post("/demobanks/default/access-api/withdrawals/${wo_to_abort.wopid}/abort") {
                    expectSuccess = true
                }
                assert(abort_with_account.status.value == abort_without_account.status.value)
                // Not checking the content as they abort two different operations.
            }
        }
    }

    // Move funds between accounts.
    @Test
    fun wireTransfer() {
        withTestDatabase {
            prepSandboxDb()
            testApplication {
                application(sandboxApp)
                runBlocking {
                    // Foo gives 20 to Bar
                    client.post("/demobanks/default/access-api/accounts/foo/transactions") {
                        expectSuccess = true
                        contentType(ContentType.Application.Json)
                        basicAuth("foo", "foo")
                        setBody("""{
                            "paytoUri": "payto://iban/${BAR_USER_IBAN}?message=test",
                            "amount": "TESTKUDOS:20"
                        }""".trimIndent()
                        )
                    }
                    // Foo checks its balance: -20
                    var R = client.get("/demobanks/default/access-api/accounts/foo") {
                        basicAuth("foo", "foo")
                    }
                    val mapper = ObjectMapper()
                    var j = mapper.readTree(R.readBytes())
                    val expectDebitOf20 = j.get("balance").get("amount").asText()
                    println("Expect debit of 20: $expectDebitOf20")
                    val testkudos20regex = "^TESTKUDOS:20(.00)?$".toRegex()
                    assert(testkudos20regex.matches(expectDebitOf20))
                    assert(j.get("balance").get("credit_debit_indicator").asText().lowercase() == "debit")
                    // Bar checks its balance: 20
                    R = client.get("/demobanks/default/access-api/accounts/bar") {
                        basicAuth("bar", "bar")
                    }
                    j = mapper.readTree(R.readBytes())
                    assert(testkudos20regex.matches(j.get("balance").get("amount").asText()))
                    assert(j.get("balance").get("credit_debit_indicator").asText().lowercase() == "credit")
                    // Foo tries with an invalid amount
                    R = client.post("/demobanks/default/access-api/accounts/foo/transactions") {
                        contentType(ContentType.Application.Json)
                        basicAuth("foo", "foo")
                        setBody("""{
                            "paytoUri": "payto://iban/${BAR_USER_IBAN}?message=test",
                            "amount": "TESTKUDOS:20.001"
                        }""".trimIndent()
                        )
                    }
                    assert(R.status.value == HttpStatusCode.BadRequest.value)
                }
            }
        }
    }

    // Tests the time range filter of Access API's GET /transactions
    @Test
    fun timeRangedTransactions() {
        withTestDatabase {
            prepSandboxDb()
            testApplication {
                application(sandboxApp)
                var R = client.get("/demobanks/default/access-api/accounts/foo/transactions") {
                    expectSuccess = true
                    basicAuth("foo", "foo")
                }
                assert(getTxs(R.bodyAsText()).size() == 0) // Checking that no transactions exist.
                wireTransfer(
                    "admin",
                    "foo",
                    "default",
                    "#0",
                    "TESTKUDOS:2"
                )
                R = client.get("/demobanks/default/access-api/accounts/foo/transactions") {
                    expectSuccess = true
                    basicAuth("foo", "foo")
                }
                assert(getTxs(R.bodyAsText()).size() == 1) // Checking that #0 shows up.
                // Asking up to a point in the past, where no txs should exist.
                R = client.get("/demobanks/default/access-api/accounts/foo/transactions?until_ms=3000") {
                    expectSuccess = true
                    basicAuth("foo", "foo")
                }
                assert(getTxs(R.bodyAsText()).size() == 0) // Not expecting any transaction.
                // Moving the transaction back in the past
                transaction {
                    val tx_0 = BankAccountTransactionEntity.find {
                        BankAccountTransactionsTable.subject eq "#0" and
                                (BankAccountTransactionsTable.direction eq "CRDT")
                    }.first()
                    tx_0.date = 10000
                }
                // Picking the past transaction from one including time range,
                // therefore expecting one entry in the result
                R = client.get("/demobanks/default/access-api/accounts/foo/transactions?from_ms=9000&until_ms=11000") {
                    expectSuccess = true
                    basicAuth("foo", "foo")
                }
                assert(getTxs(R.bodyAsText()).size() == 1)
                // Not enough txs to fill the second page, expecting no txs therefore.
                R = client.get("/demobanks/default/access-api/accounts/foo/transactions?page=2&size=1") {
                    expectSuccess = true
                    basicAuth("foo", "foo")
                }
                assert(getTxs(R.bodyAsText()).size() == 0)
                // Creating one more tx and asking the second 1-sized page, expecting therefore one result.
                wireTransfer(
                    "admin",
                    "foo",
                    "default",
                    "#1",
                    "TESTKUDOS:2"
                )
                R = client.get("/demobanks/default/access-api/accounts/foo/transactions?page=2&size=1") {
                    expectSuccess = true
                    basicAuth("foo", "foo")
                }
                assert(getTxs(R.bodyAsText()).size() == 1)
            }
        }
    }

    // Tests for #7482
    @Test
    fun highAmountWithdraw() {
        withTestDatabase {
            prepSandboxDb(usersDebtLimit = 900000000)
            testApplication {
                application(sandboxApp)
                // Create the operation.
                val r = client.post("/demobanks/default/access-api/accounts/foo/withdrawals") {
                    expectSuccess = true
                    setBody("{\"amount\": \"TESTKUDOS:500000000\"}")
                    contentType(ContentType.Application.Json)
                    basicAuth("foo", "foo")
                }
                println(r.bodyAsText())
                val j = mapper.readTree(r.readBytes())
                val op = j.get("withdrawal_id").asText()
                // Select exchange and specify a reserve pub.
                client.post("/demobanks/default/integration-api/withdrawal-operation/$op") {
                    expectSuccess = true
                    contentType(ContentType.Application.Json)
                    setBody("""{
                        "selected_exchange":"payto://iban/${BAR_USER_IBAN}",
                        "reserve_pub": "not-used"
                    }""".trimIndent())
                }
                // Confirm the operation.
                client.post("/demobanks/default/access-api/accounts/foo/withdrawals/$op/confirm") {
                    expectSuccess = true
                    basicAuth("foo", "foo")
                }
                // Check the withdrawal amount in the unique transaction.
                val t = client.get("/demobanks/default/access-api/accounts/foo/transactions") {
                    basicAuth("foo", "foo")
                }
                val amount = mapper.readTree(t.readBytes()).get("transactions").get(0).get("amount").asText()
                assert(amount == "500000000")
            }
        }
    }
    @Test
    fun withdrawWithHighBalance() {
        withTestDatabase {
            prepSandboxDb()
            /**
             * A problem appeared (Sandbox responding "insufficient funds")
             * when B - A > T, where B is the balance, A the potential amount
             * to withdraw and T is the debit threshold for the user.  T is
             * 1000 here, therefore setting B as 2000 and A as 1 should get
             * this case tested.
             */
            wireTransfer(
                "admin",
                "foo",
                "default",
                "bring balance to high amount",
                "TESTKUDOS:2000"
            )
            testApplication {
                this.application(sandboxApp)
                runBlocking {
                    client.post("/demobanks/default/access-api/accounts/foo/withdrawals") {
                        expectSuccess = true
                        setBody("{\"amount\": \"TESTKUDOS:1\"}")
                        contentType(ContentType.Application.Json)
                        basicAuth("foo", "foo")
                    }
                }
            }
        }
    }
    // Check successful and failing case due to insufficient funds.
    @Test
    fun debitWithdraw() {
        withTestDatabase {
            prepSandboxDb()
            testApplication {
                this.application(sandboxApp)
                runBlocking {
                    // Normal, successful withdrawal.
                    client.post("/demobanks/default/access-api/accounts/foo/withdrawals") {
                        expectSuccess = true
                        setBody("{\"amount\": \"TESTKUDOS:1\"}")
                        contentType(ContentType.Application.Json)
                        basicAuth("foo", "foo")
                    }
                    // Withdrawal over the debit threshold.
                    val r: HttpResponse = client.post("/demobanks/default/access-api/accounts/foo/withdrawals") {
                        expectSuccess = false
                        contentType(ContentType.Application.Json)
                        basicAuth("foo", "foo")
                        setBody("{\"amount\": \"TESTKUDOS:99999999999\"}")
                    }
                    assert(HttpStatusCode.Conflict.value == r.status.value)
                }
            }
        }
    }

    /**
     * Tests that 'admin' and 'bank' are not possible to register
     * and that after 'admin' logs in it gets access to the bank's
     * main account.
     */ // FIXME: avoid giving Content-Type at every request.
    @Test
    fun adminRegisterAndLoginTest() {
        withTestDatabase {
            prepSandboxDb()
            testApplication {
                application(sandboxApp)
                runBlocking {
                    val registerAdmin = mapper.writeValueAsString(object {
                        val username = "admin"
                        val password = "y"
                    })
                    val registerBank = mapper.writeValueAsString(object {
                        val username = "bank"
                        val password = "y"
                    })
                    for (b in mutableListOf<String>(registerAdmin, registerBank)) {
                        val r = client.post("/demobanks/default/access-api/testing/register") {
                            setBody(b)
                            contentType(ContentType.Application.Json)
                            expectSuccess = false
                        }
                        assert(r.status.value == HttpStatusCode.Forbidden.value)
                    }
                    // Set arbitrary balance to the bank.
                    wireTransfer(
                        "foo",
                        "admin",
                        "default",
                        "setting the balance",
                        "TESTKUDOS:99"
                    )
                    // Get admin's balance.  Not asserting; it
                    // fails on != 200 responses.
                    val r = client.get("/demobanks/default/access-api/accounts/admin") {
                        expectSuccess = true
                        basicAuth("admin", "foo")
                    }
                    println(r)
                }
            }
        }
    }

    // Checks that the debit threshold belongs to the balance response.
    @Test
    fun debitInfoCheck() {
        withTestDatabase {
            prepSandboxDb()
            testApplication {
                application(sandboxApp)
                var r = client.get("/demobanks/default/access-api/accounts/foo") {
                    expectSuccess = true
                    basicAuth("foo", "foo")
                }
                // Checking that the response holds the debit threshold.
                val mapper = ObjectMapper()
                var respJson = mapper.readTree(r.bodyAsText())
                var debitThreshold = respJson.get("debitThreshold").asText()
                assert(debitThreshold == "1000")
                r = client.get("/demobanks/default/access-api/accounts/admin") {
                    expectSuccess = true
                    basicAuth("admin", "foo")
                }
                respJson = mapper.readTree(r.bodyAsText())
                debitThreshold = respJson.get("debitThreshold").asText()
                assert(debitThreshold == "10000")
            }
        }
    }

    @Test
    fun registerTest() {
        // Test IBAN conflict detection.
        withSandboxTestDatabase {
            testApplication {
                application(sandboxApp)
                runBlocking {
                    val bodyFoo = mapper.writeValueAsString(object {
                        val username = "x"
                        val password = "y"
                        val iban = FOO_USER_IBAN
                    })
                    val bodyBar = mapper.writeValueAsString(object {
                        val username = "y"
                        val password = "y"
                        val iban = FOO_USER_IBAN // conflicts
                    })
                    val bodyBaz = mapper.writeValueAsString(object {
                        val username = "y"
                        val password = "y"
                        val iban = BAR_USER_IBAN
                    })
                    // Succeeds.
                    client.post("/demobanks/default/access-api/testing/register") {
                        setBody(bodyFoo)
                        contentType(ContentType.Application.Json)
                        expectSuccess = true
                    }
                    // Hits conflict, because of the same IBAN.
                    val r = client.post("/demobanks/default/access-api/testing/register") {
                        setBody(bodyBar)
                        expectSuccess = false
                        contentType(ContentType.Application.Json)
                    }
                    assert(r.status.value == HttpStatusCode.Conflict.value)
                    // Succeeds, because of a new IBAN.
                    client.post("/demobanks/default/access-api/testing/register") {
                        setBody(bodyBaz)
                        expectSuccess = true
                        contentType(ContentType.Application.Json)
                    }
                }
            }

        }
    }

    /**
     * This test checks that the bank hangs before responding with the list
     * of transactions, in case there is none to return.  The timing checks
     * that the server hangs for as long as the unblocking payment takes place
     * but NOT as long as the long_poll_ms parameter would suggest.  This last
     * check ensures that the response can only contain the artificial unblocking
     * payment (that happens after a certain timeout).
     */
    @Test
    fun longPolledTransactions() {
        val unblockingTxTimer = Timer()
        val testStartTime = System.currentTimeMillis()
        withTestDatabase {
            prepSandboxDb()
            testApplication {
                application(sandboxApp)
                runBlocking {
                    launch {
                        // long polls at most 50 seconds.
                        val R = client.get("/demobanks/default/access-api/accounts/foo/transactions?long_poll_ms=50000") {
                            expectSuccess = true
                            basicAuth("foo", "foo")
                        }
                        assert(getTxs(R.bodyAsText()).size() == 1)
                        val testEndTime = System.currentTimeMillis()
                        val timeDiff = (testEndTime - testStartTime) / 1000L
                        /**
                         * Now checking that the server responded after the unblocking tx
                         * took place and before the long poll timeout would occur.
                         */
                        println(timeDiff)
                        assert(timeDiff in 4 .. 39)
                    }
                    unblockingTxTimer.schedule(
                        delay = 4000L, // unblocks the server in (at least) 4 seconds.
                        action = {
                            wireTransfer(
                                "admin",
                                "foo",
                                "default",
                                "#9",
                                "TESTKUDOS:2"
                            )
                        }
                    )
                }
            }
        }
    }
}