summaryrefslogtreecommitdiff
path: root/nexus/src/test/kotlin/EbicsTest.kt
blob: 19646d6af62fd52c3a0fcfe4842dadf398ac6af3 (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
import io.ktor.server.application.*
import io.ktor.http.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import kotlinx.coroutines.runBlocking
import org.jetbrains.exposed.sql.transactions.transaction
import org.junit.Test
import org.w3c.dom.Document
import tech.libeufin.nexus.*
import tech.libeufin.nexus.bankaccount.addPaymentInitiation
import tech.libeufin.nexus.bankaccount.fetchBankAccountTransactions
import tech.libeufin.nexus.bankaccount.submitAllPaymentInitiations
import tech.libeufin.nexus.ebics.*
import tech.libeufin.nexus.iso20022.NexusPaymentInitiationData
import tech.libeufin.nexus.iso20022.createPain001document
import tech.libeufin.nexus.server.FetchLevel
import tech.libeufin.nexus.server.FetchSpecAllJson
import tech.libeufin.nexus.server.Pain001Data
import tech.libeufin.sandbox.*
import tech.libeufin.util.*
import tech.libeufin.util.ebics_h004.EbicsRequest
import tech.libeufin.util.ebics_h004.EbicsResponse
import tech.libeufin.util.ebics_h004.EbicsTypes
import tech.libeufin.util.ebics_h005.Ebics3Request

/**
 * These test cases run EBICS CCT and C52, mixing ordinary operations
 * and some error cases.
 */

/**
 * Data to make the test server return for EBICS
 * phases.  Currently only init is supported.
 */
data class EbicsResponses(
    val init: String,
    val download: String? = null,
    val receipt: String? = null
)

/**
 * Minimal server responding always the 'init' field of a EbicsResponses
 * object to a download EBICS message.  Suitable to set arbitrary data
 * in said response.  Signs the response assuming the client is the one
 * created in MakeEnv.kt.
 */
fun getCustomEbicsServer(r: EbicsResponses, endpoint: String = "/ebicsweb"): Application.() -> Unit {
    val ret: Application.() -> Unit = {
        install(ContentNegotiation) {
            register(ContentType.Text.Xml, XMLEbicsConverter())
            register(ContentType.Text.Plain, XMLEbicsConverter())
        }
        routing {
            post(endpoint) {
                val requestDocument = this.call.receive<Document>()
                val req = requestDocument.toObject<EbicsRequest>()
                val clientKey = CryptoUtil.loadRsaPublicKey(userKeys.enc.public.encoded)
                val msgId = EbicsOrderUtil.generateTransactionId()
                val resp: EbicsResponse = if (
                    req.header.mutable.transactionPhase == EbicsTypes.TransactionPhaseType.INITIALISATION
                ) {
                    val payload = prepareEbicsPayload(r.init, clientKey)
                    EbicsResponse.createForDownloadInitializationPhase(
                        msgId,
                        1,
                        4096,
                        payload.second, // for key material
                        payload.first // actual payload
                    )
                } else {
                    // msgId doesn't have to match the one used for the init phase.
                    EbicsResponse.createForDownloadReceiptPhase(msgId, true)
                }
                val sigEbics = XMLUtil.signEbicsResponse(
                    resp,
                    CryptoUtil.loadRsaPrivateKey(bankKeys.auth.private.encoded)
                )
                call.respond(sigEbics)
            }
        }
    }
    return ret
}

class DownloadAndSubmit {
    // Downloads a C52 report from the bank.
    @Test
    fun download() {
        withNexusAndSandboxUser {
            wireTransfer(
                "admin",
                "foo",
                "default",
                "Show up in logging!",
                "TESTKUDOS:1"
            )
            wireTransfer(
                "admin",
                "foo",
                "default",
                "Exist in logging!",
                "TESTKUDOS:5"
            )
            testApplication {
                application(sandboxApp)
                runBlocking {
                    fetchBankAccountTransactions(
                        client,
                        fetchSpec = FetchSpecAllJson(
                            level = FetchLevel.REPORT,
                            bankConnection = "foo"
                        ),
                        accountId = "foo"
                    )
                }
                transaction {
                    // FIXME: assert on the subject.
                    assert(
                        NexusBankTransactionEntity[1].amount == "1" &&
                                NexusBankTransactionEntity[2].amount == "5"
                    )
                }
            }
        }
    }

    // Uploads one payment instruction to the bank.
    @Test
    fun upload() {
        withNexusAndSandboxUser {
            testApplication {
                application(sandboxApp)
                val conn = EbicsBankConnectionProtocol()
                runBlocking {
                    // Create Pain.001 to be submitted.
                    addPaymentInitiation(
                        Pain001Data(
                            creditorIban = getIban(),
                            creditorBic = "SANDBOXX",
                            creditorName = "Tester",
                            subject = "test payment",
                            sum = "1",
                            currency = "TESTKUDOS"
                        ),
                        transaction {
                            NexusBankAccountEntity.findByName(
                                "foo"
                            ) ?: throw Exception("Test failed")
                        }
                    )
                    conn.submitPaymentInitiation(
                        client,
                        1L
                    )
                }
                transaction {
                    val payment = BankAccountTransactionEntity[1]
                    assert(payment.debtorIban == FOO_USER_IBAN &&
                            payment.subject == "test payment" &&
                            payment.direction == "DBIT"
                    )
                }
            }
        }
    }

    /**
     * Upload one payment instruction charging one IBAN
     * that does not belong to the requesting EBICS subscriber.
     */
    @Test
    fun unallowedDebtorIban() {
        withNexusAndSandboxUser {
            testApplication {
                application(sandboxApp)
                runBlocking {
                    val bar = transaction { NexusBankAccountEntity.findByName("bar") }
                    val painMessage = createPain001document(
                        NexusPaymentInitiationData(
                            debtorIban = bar!!.iban,
                            debtorBic = bar.bankCode,
                            debtorName = bar.accountHolder,
                            currency = "TESTKUDOS",
                            amount = "1",
                            creditorIban = getIban(),
                            creditorName = "Get",
                            creditorBic = "SANDBOXX",
                            paymentInformationId = "entropy-0",
                            preparationTimestamp = 1970L,
                            subject = "Unallowed",
                            messageId = "entropy-1",
                            endToEndId = null,
                            instructionId = null
                        )
                    )
                    val unallowedSubscriber = transaction { getEbicsSubscriberDetails("foo") }
                    var thrown = false
                    try {
                        doEbicsUploadTransaction(
                            client,
                            unallowedSubscriber,
                            EbicsUploadSpec(
                                orderType = "CCT",
                                isEbics3 = false,
                                orderParams = EbicsStandardOrderParams()
                            ),
                            painMessage.toByteArray(Charsets.UTF_8)
                        )
                    } catch (e: EbicsProtocolError) {
                        if (e.ebicsTechnicalCode ==
                                EbicsReturnCode.EBICS_ACCOUNT_AUTHORISATION_FAILED
                        )
                            thrown = true
                    }
                    assert(thrown)
                }
            }
        }
    }

    /**
     * Submits one pain.001 document with the wrong currency and checks
     * that the bank responded with EBICS_PROCESSING_ERROR.
     */
    @Test
    fun unsupportedCurrency() {
        withNexusAndSandboxUser {
            testApplication {
                application(sandboxApp)
                runBlocking {
                    // Create Pain.001 to be submitted.
                    addPaymentInitiation(
                        Pain001Data(
                            creditorIban = getIban(),
                            creditorBic = "SANDBOXX",
                            creditorName = "Tester",
                            subject = "test payment",
                            sum = "1",
                            currency = "EUR" // EUR not supported.
                        ),
                        transaction {
                            NexusBankAccountEntity.findByName("foo") ?: throw Exception("Test failed")
                        }
                    )
                    var thrown = false
                    try {
                        submitAllPaymentInitiations(client, "foo")
                    } catch (e: EbicsProtocolError) {
                        if (e.ebicsTechnicalCode == EbicsReturnCode.EBICS_PROCESSING_ERROR)
                            thrown = true
                    }
                    assert(thrown)
                }
            }
        }
    }

    /**
     * Test that pain.001 amounts ALSO have max 2 fractional digits, like Taler's.
     * That makes Sandbox however NOT completely compatible with the pain.001 standard,
     * since this allows up to 5 fractional digits.  */
    @Test
    fun testFractionalDigits() {
        withNexusAndSandboxUser {
            testApplication {
                application(sandboxApp)
                runBlocking {
                    // Create Pain.001 with excessive amount.
                    addPaymentInitiation(
                        Pain001Data(
                            creditorIban = getIban(),
                            creditorBic = "SANDBOXX",
                            creditorName = "Tester",
                            subject = "test payment",
                            sum = "1.001", // wrong 3 fractional digits.
                            currency = "TESTKUDOS"
                        ),
                        "foo"
                    )
                    assertException<EbicsProtocolError>({ submitAllPaymentInitiations(client, "foo") })
                }
            }
        }
    }

    // Test the EBICS error message in case of debt threshold being surpassed
    @Test
    fun testDebit() {
        withNexusAndSandboxUser {
            testApplication {
                application(sandboxApp)
                runBlocking {
                    // Create Pain.001 with excessive amount.
                    addPaymentInitiation(
                        Pain001Data(
                            creditorIban = getIban(),
                            creditorBic = "SANDBOXX",
                            creditorName = "Tester",
                            subject = "test payment",
                            sum = "1000000",
                            currency = "TESTKUDOS"
                        ),
                        "foo"
                    )
                    assertException<EbicsProtocolError>(
                        { submitAllPaymentInitiations(client, "foo") },
                        {
                            val nexusEbicsException = it as EbicsProtocolError
                            assert(
                                EbicsReturnCode.EBICS_AMOUNT_CHECK_FAILED.errorCode ==
                                nexusEbicsException.ebicsTechnicalCode?.errorCode
                            )
                        }
                    )
                }
            }
        }
    }
}

class EbicsTest {

    @Test
    fun genEbics3Upload() {
        withTestDatabase {
            prepNexusDb()
            val foo = transaction { getEbicsSubscriberDetails("foo") }
            val uploadDoc = createEbicsRequestForUploadInitialization(
                subscriberDetails = foo,
                ebics3OrderService = Ebics3Request.OrderDetails.Service().apply {
                    serviceName = "OTH"
                    scope = "BIL"
                    serviceOption = "CH002LMF"
                    messageName = Ebics3Request.OrderDetails.Service.MessageName().apply {
                        value = "csv"
                    }
                },
                null,
                prepareUploadPayload(
                    foo,
                    "foo".toByteArray(),
                    isEbics3 = true
                )
            )
            assert(XMLUtil.validateFromString(uploadDoc))
        }
    }

    /**
     * Tests the validity of EBICS 3.0 messages.
     */
    @Test
    fun genEbics3Download() {
        withTestDatabase {
            prepNexusDb()
            val foo = transaction { getEbicsSubscriberDetails("foo") }
            val downloadDoc = createEbicsRequestForDownloadInitialization(
                subscriberDetails = foo,
                ebics3OrderService = Ebics3Request.OrderDetails.Service().apply {
                    messageName = Ebics3Request.OrderDetails.Service.MessageName().apply {
                        value = "camt.054"
                        version = "04"
                    }
                    scope = "CH"
                    serviceName = "REP"
                    container = Ebics3Request.OrderDetails.Service.Container().apply {
                        containerType = "ZIP"
                    }
                },
                orderParams = EbicsStandardOrderParams()
            )
            assert(XMLUtil.validateFromString(downloadDoc))
        }
    }
}