summaryrefslogtreecommitdiff
path: root/nexus/src/test/kotlin/TalerTest.kt
blob: f877203b30f62e504c3b076271b2eaeef10f88e0 (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
import com.fasterxml.jackson.databind.ObjectMapper
import io.ktor.client.call.*
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 kotlinx.coroutines.*
import org.jetbrains.exposed.sql.transactions.transaction
import org.junit.Ignore
import org.junit.Test
import tech.libeufin.nexus.bankaccount.fetchBankAccountTransactions
import tech.libeufin.nexus.bankaccount.submitAllPaymentInitiations
import tech.libeufin.nexus.ingestFacadeTransactions
import tech.libeufin.nexus.maybeTalerRefunds
import tech.libeufin.nexus.server.*
import tech.libeufin.nexus.talerFilter
import tech.libeufin.sandbox.sandboxApp
import tech.libeufin.sandbox.wireTransfer
import tech.libeufin.util.NotificationsChannelDomains

// This class tests the features related to the Taler facade.
class TalerTest {
    val mapper = ObjectMapper()

    // Checking that a call to POST /transfer results in
    // an outgoing payment in GET /history/outgoing.
    @Test
    fun historyOutgoingTest() {
        withNexusAndSandboxUser {
            testApplication {
                application(nexusApp)
                client.post("/facades/foo-facade/taler-wire-gateway/transfer") {
                    contentType(ContentType.Application.Json)
                    basicAuth("foo", "foo") // exchange's credentials
                    expectSuccess = true
                    setBody("""
                        { "request_uid": "twg_transfer_0",
                          "amount": "TESTKUDOS:3",
                          "exchange_base_url": "http://exchange.example.com/",
                          "wtid": "T0",
                          "credit_account": "payto://iban/${BAR_USER_IBAN}?receiver-name=Bar"
                        
                        }
                    """.trimIndent())
                }
            }
            /* The EBICS layer sends the payment instruction to the bank here.
             *  and the reconciliation mechanism in Nexus should detect that one
             *  outgoing payment was indeed the one instructed via the TWG.  The
             *  reconciliation will make the outgoing payment visible via /history/outgoing.
             *  The following block achieve this by starting Sandbox and sending all
             *  the prepared payments to it.
             */
            testApplication {
                application(sandboxApp)
                submitAllPaymentInitiations(client, "foo")
                /* Now downloads transactions from the bank, where the payment
                   submitted in the previous block is expected to appear as outgoing.
                 */
                fetchBankAccountTransactions(
                    client,
                    fetchSpec = FetchSpecAllJson(
                        level = FetchLevel.REPORT,
                        "foo"
                    ),
                    "foo"
                )
            }
            /**
             * Now Nexus starts again, in order to serve /history/outgoing
             * along the TWG.
             */
            testApplication {
                application(nexusApp)
                val r = client.get("/facades/foo-facade/taler-wire-gateway/history/outgoing?delta=5") {
                    expectSuccess = true
                    contentType(ContentType.Application.Json)
                    basicAuth("foo", "foo")
                }
                val j = mapper.readTree(r.readBytes())
                val wtidFromTwg = j.get("outgoing_transactions").get(0).get("wtid").asText()
                assert(wtidFromTwg == "T0")
            }
        }
    }

    // Tests that incoming Taler txs arrive via EBICS.
    @Test
    fun historyIncomingTestEbics() {
        historyIncomingTest(
            testedAccount = "foo",
            connType = BankConnectionType.EBICS
        )
    }

    // Tests that incoming Taler txs arrive via x-libeufin-bank.
    @Test
    fun historyIncomingTestXLibeufinBank() {
        historyIncomingTest(
            testedAccount = "bar",
            connType = BankConnectionType.X_LIBEUFIN_BANK
        )
    }

    // Tests that even if one call is long-polling, other calls
    @Test
    fun servingTest() {
        withTestDatabase {
            prepNexusDb()
            testApplication {
                application(nexusApp)
                // This call blocks for 90 seconds
                val currentTime = System.currentTimeMillis()
                runBlocking {
                    launch {
                        val r = client.get("/facades/foo-facade/taler-wire-gateway/history/incoming?delta=5&start=0&long_poll_ms=5000") {
                            expectSuccess = true
                            contentType(ContentType.Application.Json)
                            basicAuth("foo", "foo") // user & pw always equal.
                        }
                        assert(r.status.value == HttpStatusCode.NoContent.value)
                    }
                    val R = client.get("/") {
                        expectSuccess = true
                    }
                    val latestTime = System.currentTimeMillis()
                    assert(R.status.value == HttpStatusCode.OK.value
                            && (latestTime - currentTime) < 2000
                    )
                }
            }
        }
    }

    // Downloads Taler txs via the default connection of 'testedAccount'.
    // This allows to test the Taler logic on different connection types.
    fun historyIncomingTest(testedAccount: String, connType: BankConnectionType) {
        val reservePub = "GX5H5RME193FDRCM1HZKERXXQ2K21KH7788CKQM8X6MYKYRBP8F0"
        withNexusAndSandboxUser {
            testApplication {
                application(nexusApp)
                runBlocking {
                    /**
                     * This block issues the request by long-polling and
                     * lets the execution proceed where the actions to unblock
                     * the polling are taken.
                     */
                    launch {
                        val r = client.get("/facades/${testedAccount}-facade/taler-wire-gateway/history/incoming?delta=5&start=0&long_poll_ms=30000") {
                            expectSuccess = true
                            contentType(ContentType.Application.Json)
                            basicAuth(testedAccount, testedAccount) // user & pw always equal.
                        }
                        assertWithPrint(
                            r.status.value == HttpStatusCode.OK.value,
                            "Long-polling history had status: ${r.status.value} and" +
                                    " body: ${r.bodyAsText()}"
                        )
                        val j = mapper.readTree(r.readBytes())
                        val reservePubFromTwg = j.get("incoming_transactions").get(0).get("reserve_pub").asText()
                        assert(reservePubFromTwg == reservePub)
                    }
                    launch {
                        delay(500)
                        /**
                         * FIXME: this test never gets the server to wait notifications from the DBMS.
                         * Somehow, the wire transfer arrives always before the blocking await on the DBMS.
                         */
                        newNexusBankTransaction(
                            currency = "KUDOS",
                            value = "10",
                            subject = reservePub,
                            creditorAcct = testedAccount,
                            connType = connType
                        )
                        ingestFacadeTransactions(
                            bankAccountId = testedAccount, // bank account local to Nexus.
                            facadeType = NexusFacadeType.TALER,
                            incomingFilterCb = ::talerFilter,
                            refundCb = ::maybeTalerRefunds
                        )
                    }
                }
            }
        }
    }

    @Ignore // Ignoring because no assert takes place.
    @Test // Triggering a refund because of a duplicate reserve pub.
    fun refundTest() {
        withNexusAndSandboxUser {
            // Creating a Taler facade for the user 'foo'.
            testApplication {
                application(nexusApp)
                client.post("/facades") {
                    expectSuccess = true
                    contentType(ContentType.Application.Json)
                    basicAuth("foo", "foo")
                    setBody("""
                        { "name":"foo-facade",
                          "type":"taler-wire-gateway",
                          "config": {
                            "bankAccount":"foo",
                            "bankConnection":"foo",
                            "currency":"TESTKUDOS",
                            "reserveTransferLevel":"report"
                          }
                    }""".trimIndent()
                    )
                }
            }
            wireTransfer(
                "bar",
                "foo",
                demobank = "default",
                "5WFM8PXN7Y315RVZFJ280299B94W1HR1AAHH6XNDYEJBC0T3E5N0",
                "TESTKUDOS:3"
            )
            testApplication {
                application(sandboxApp)
                // Nexus downloads the fresh transaction.
                fetchBankAccountTransactions(
                    client,
                    fetchSpec = FetchSpecAllJson(
                        level = FetchLevel.REPORT,
                        "foo"
                    ),
                    "foo"
                )
            }
            wireTransfer(
                "bar",
                "foo",
                demobank = "default",
                "5WFM8PXN7Y315RVZFJ280299B94W1HR1AAHH6XNDYEJBC0T3E5N0",
                "TESTKUDOS:3"
            )
            testApplication {
                application(sandboxApp)
                // Nexus downloads the new transaction, having a duplicate subject.
                fetchBankAccountTransactions(
                    client,
                    fetchSpec = FetchSpecAllJson(
                        level = FetchLevel.REPORT,
                        "foo"
                    ),
                    "foo"
                )
            }
        }
    }
}