summaryrefslogtreecommitdiff
path: root/src/backend/taler-merchant-httpd_helper.c
blob: 2cffa20c354e5158713d2c2a9320cfed7aafce6e (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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
/*
  This file is part of TALER
  (C) 2014--2021 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify it under the
  terms of the GNU Lesser General Public License as published by the Free Software
  Foundation; either version 3, or (at your option) any later version.

  TALER is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along with
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file taler-merchant-httpd_helper.c
 * @brief shared logic for various handlers
 * @author Christian Grothoff
 */
#include "platform.h"
#include <gnunet/gnunet_util_lib.h>
#include <taler/taler_util.h>
#include <taler/taler_json_lib.h>
#include "taler-merchant-httpd_helper.h"
#include <taler/taler_templating_lib.h>


/**
 * check @a payto_uris for well-formedness
 *
 * @param payto_uris JSON array of payto URIs (presumably)
 * @return true if they are all valid URIs (and this is an array of strings)
 */
bool
TMH_payto_uri_array_valid (const json_t *payto_uris)
{
  bool payto_ok = true;

  if (! json_is_array (payto_uris))
  {
    GNUNET_break_op (0);
    payto_ok = false;
  }
  else
  {
    unsigned int len = json_array_size (payto_uris);

    for (unsigned int i = 0; i<len; i++)
    {
      json_t *payto_uri = json_array_get (payto_uris,
                                          i);
      const char *uri;

      if (! json_is_string (payto_uri))
        payto_ok = false;
      uri = json_string_value (payto_uri);
      /* Test for the same payto:// URI being given twice */
      for (unsigned int j = 0; j<i; j++)
      {
        json_t *old_uri = json_array_get (payto_uris,
                                          j);
        if (json_equal (payto_uri,
                        old_uri))
        {
          GNUNET_break_op (0);
          payto_ok = false;
          break;
        }
      }
      if (! payto_ok)
        break;
      {
        char *err;

        if (NULL !=
            (err = TALER_payto_validate (uri)))
        {
          GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                      "Encountered invalid payto://-URI `%s': %s\n",
                      uri,
                      err);
          GNUNET_free (err);
          payto_ok = false;
          break;
        }
      }
    }
  }
  return payto_ok;
}


bool
TMH_location_object_valid (const json_t *location)
{
  const char *country = NULL;
  const char *subdivision = NULL;
  const char *district = NULL;
  const char *town = NULL;
  const char *town_loc = NULL;
  const char *postcode = NULL;
  const char *street = NULL;
  const char *building = NULL;
  const char *building_no = NULL;
  json_t *lines = NULL;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("country",
                               &country),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("country_subdivision",
                               &subdivision),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("district",
                               &district),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("town",
                               &town),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("town_location",
                               &town_loc),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("post_code",
                               &postcode),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("street",
                               &street),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("building_name",
                               &building),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("building_number",
                               &building_no),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_json ("address_lines",
                             &lines),
      NULL),
    GNUNET_JSON_spec_end ()
  };
  const char *ename;
  unsigned int eline;

  if (GNUNET_OK !=
      GNUNET_JSON_parse (location,
                         spec,
                         &ename,
                         &eline))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Invalid location for field %s\n",
                ename);
    return false;
  }
  if (NULL != lines)
  {
    size_t idx;
    json_t *line;

    if (! json_is_array (lines))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Invalid location for field %s\n",
                  "lines");
      return false;
    }
    json_array_foreach (lines, idx, line)
    {
      if (! json_is_string (line))
      {
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    "Invalid address line #%u in location\n",
                    (unsigned int) idx);
        return false;
      }
    }
  }
  return true;
}


bool
TMH_products_array_valid (const json_t *products)
{
  const json_t *product;
  size_t idx;
  bool valid = true;

  if (! json_is_array (products))
  {
    GNUNET_break_op (0);
    return false;
  }
  json_array_foreach ((json_t *) products, idx, product)
  {
    const char *product_id = NULL;
    const char *description;
    json_t *description_i18n = NULL;
    uint64_t quantity = 0;
    const char *unit = NULL;
    struct TALER_Amount price = { .value = 0 };
    const char *image_data_url = NULL;
    json_t *taxes = NULL;
    struct GNUNET_TIME_Timestamp delivery_date = { 0 };
    struct GNUNET_JSON_Specification spec[] = {
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_string ("product_id",
                                 &product_id),
        NULL),
      GNUNET_JSON_spec_string ("description",
                               &description),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_json ("description_i18n",
                               &description_i18n),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_uint64 ("quantity",
                                 &quantity),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_string ("unit",
                                 &unit),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        TALER_JSON_spec_amount ("price",
                                TMH_currency,
                                &price),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_string ("image",
                                 &image_data_url),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_json ("taxes",
                               &taxes),
        NULL),
      GNUNET_JSON_spec_mark_optional (
        GNUNET_JSON_spec_timestamp ("delivery_date",
                                    &delivery_date),
        NULL),
      GNUNET_JSON_spec_end ()
    };
    const char *ename;
    unsigned int eline;

    if (GNUNET_OK !=
        GNUNET_JSON_parse (product,
                           spec,
                           &ename,
                           &eline))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Invalid product #%u for field %s\n",
                  (unsigned int) idx,
                  ename);
      return false;
    }
    if ( (NULL != image_data_url) &&
         (! TMH_image_data_url_valid (image_data_url)) )
    {
      GNUNET_break_op (0);
      valid = false;
    }
    if ( (NULL != taxes) &&
         (! TMH_taxes_array_valid (taxes)) )
    {
      GNUNET_break_op (0);
      valid = false;
    }
    if ( (NULL != description_i18n) &&
         (! TALER_JSON_check_i18n (description_i18n)) )
    {
      GNUNET_break_op (0);
      valid = false;
    }
    GNUNET_JSON_parse_free (spec);
    if (! valid)
      break;
  }

  return valid;
}


bool
TMH_image_data_url_valid (const char *image_data_url)
{
  if (0 == strcmp (image_data_url,
                   ""))
    return true;
  if (0 != strncasecmp ("data:image/",
                        image_data_url,
                        strlen ("data:image/")))
  {
    GNUNET_break_op (0);
    return false;
  }
  if (NULL == strstr (image_data_url,
                      ";base64,"))
  {
    GNUNET_break_op (0);
    return false;
  }
  if (! TALER_url_valid_charset (image_data_url))
  {
    GNUNET_break_op (0);
    return false;
  }
  return true;
}


bool
TMH_template_contract_valid (const json_t *template_contract)
{
  const char *summary;
  struct TALER_Amount amount = { .value = 0};
  uint32_t minimum_age = 0;
  struct GNUNET_TIME_Relative pay_duration = { 0 };
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_string ("summary",
                               &summary),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      TALER_JSON_spec_amount ("amount",
                              TMH_currency,
                              &amount),
      NULL),
    GNUNET_JSON_spec_uint32 ("minimum_age",
                             &minimum_age),
    GNUNET_JSON_spec_relative_time ("pay_duration",
                                    &pay_duration),
    GNUNET_JSON_spec_end ()
  };
  const char *ename;
  unsigned int eline;

  if (GNUNET_OK !=
      GNUNET_JSON_parse (template_contract,
                         spec,
                         &ename,
                         &eline))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Invalid template_contract for field %s\n",
                ename);
    return false;
  }
  return true;
}


bool
TMH_taxes_array_valid (const json_t *taxes)
{
  json_t *tax;
  size_t idx;

  if (! json_is_array (taxes))
    return false;
  json_array_foreach (taxes, idx, tax)
  {
    struct TALER_Amount amount;
    const char *name;
    struct GNUNET_JSON_Specification spec[] = {
      GNUNET_JSON_spec_string ("name",
                               &name),
      TALER_JSON_spec_amount_any ("tax",
                                  &amount),
      GNUNET_JSON_spec_end ()
    };
    enum GNUNET_GenericReturnValue res;

    res = TALER_MHD_parse_json_data (NULL,
                                     tax,
                                     spec);
    if (GNUNET_OK != res)
    {
      GNUNET_break_op (0);
      return false;
    }
  }
  return true;
}


struct TMH_WireMethod *
TMH_setup_wire_account (const char *payto_uri)
{
  struct TMH_WireMethod *wm;
  char *emsg;

  if (NULL != (emsg = TALER_payto_validate (payto_uri)))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Invalid URI `%s': %s\n",
                payto_uri,
                emsg);
    GNUNET_free (emsg);
    return NULL;
  }

  wm = GNUNET_new (struct TMH_WireMethod);
  GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE,
                              &wm->wire_salt,
                              sizeof (wm->wire_salt));
  wm->payto_uri = GNUNET_strdup (payto_uri);
  TALER_merchant_wire_signature_hash (payto_uri,
                                      &wm->wire_salt,
                                      &wm->h_wire);
  wm->wire_method
    = TALER_payto_get_method (payto_uri);
  wm->active = true;
  return wm;
}


enum GNUNET_GenericReturnValue
TMH_check_auth_config (struct MHD_Connection *connection,
                       const json_t *jauth,
                       const char **auth_token)
{
  bool auth_wellformed = false;
  const char *auth_method = json_string_value (json_object_get (jauth,
                                                                "method"));

  *auth_token = NULL;
  if (NULL == auth_method)
  {
    GNUNET_break_op (0);
  }
  else if (0 == strcmp (auth_method,
                        "external"))
  {
    auth_wellformed = true;
  }
  else if (0 == strcmp (auth_method,
                        "token"))
  {
    *auth_token = json_string_value (json_object_get (jauth,
                                                      "token"));
    if (NULL == *auth_token)
    {
      GNUNET_break_op (0);
    }
    else
    {
      if (0 != strncasecmp (RFC_8959_PREFIX,
                            *auth_token,
                            strlen (RFC_8959_PREFIX)))
        GNUNET_break_op (0);
      else
        auth_wellformed = true;
    }
  }

  if (! auth_wellformed)
  {
    GNUNET_break_op (0);
    return (MHD_YES ==
            TALER_MHD_reply_with_error (connection,
                                        MHD_HTTP_BAD_REQUEST,
                                        TALER_EC_MERCHANT_PRIVATE_POST_INSTANCES_BAD_AUTH,
                                        "bad authentication config")) ?
           GNUNET_NO : GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Generate binary UUID from client-provided UUID-string.
 *
 * @param uuids string intpu
 * @param[out] uuid set to binary UUID
 */
void
TMH_uuid_from_string (const char *uuids,
                      struct GNUNET_Uuid *uuid)
{
  struct GNUNET_HashCode hc;

  GNUNET_CRYPTO_hash (uuids,
                      strlen (uuids),
                      &hc);
  GNUNET_static_assert (sizeof (hc) > sizeof (*uuid));
  memcpy (uuid,
          &hc,
          sizeof (*uuid));
}


/**
 * Closure for #trigger_webhook_cb.
 *
 * @param instance which is the instance we work with
 * @param root JSON data to fill into the template
 * @param rv, query of the TALER_TEMPLATEING_fill
 */
struct Trigger
{
  const char *instance;

  const json_t *root;

  enum GNUNET_DB_QueryStatus rv;

};

/**
 * Typically called by `TMH_trigger_webhook`.
 *
 * @param[in,out] cls a `struct Trigger` with information about the webhook
 * @param webhook_serial reference to the configured webhook template.
 * @param event_type is the event/action of the webhook
 * @param url to make request to
 * @param http_method use for the webhook
 * @param header_template of the webhook
 * @param body_template of the webhook
 */
static void
trigger_webhook_cb (void *cls,
                    uint64_t webhook_serial,
                    const char *event_type,
                    const char *url,
                    const char *http_method,
                    const char *header_template,
                    const char *body_template)
{
  struct Trigger *t = cls;
  void *header = NULL;
  void *body = NULL;
  size_t header_size;
  size_t body_size;

  if (NULL != header_template)
  {
    int ret;

    ret = TALER_TEMPLATING_fill (header_template,
                                 t->root,
                                 &header,
                                 &header_size);
    if (0 != ret)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Failed to expand webhook header template for webhook %llu (%d)\n",
                  (unsigned long long) webhook_serial,
                  ret);
      t->rv = GNUNET_DB_STATUS_HARD_ERROR;
      return;
    }
    GNUNET_assert ('\0' == ((const char *) header)[header_size-1]);
  }
  if (NULL != body_template)
  {
    int ret;
    ret = TALER_TEMPLATING_fill (body_template,
                                 t->root,
                                 &body,
                                 &body_size);
    if (0 != ret)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Failed to expand webhook header template for webhook %llu (%d)\n",
                  (unsigned long long) webhook_serial,
                  ret);
      t->rv = GNUNET_DB_STATUS_HARD_ERROR;
      return;
    }
    GNUNET_assert ('\0' == ((const char *) body)[body_size-1]);
  }
  t->rv = TMH_db->insert_pending_webhook (TMH_db->cls,
                                          t->instance,
                                          webhook_serial,
                                          url,
                                          http_method,
                                          header,
                                          body);
  free (header);
  free (body);
}


/**
 * TMH_trigger_webhook is a function that need to be use when someone
 * pay. Merchant need to have a notification.
 *
 * @param instance that we need to send the webhook as a notification
 * @param event of the webhook
 * @param args argument of the function
 */
enum GNUNET_DB_QueryStatus
TMH_trigger_webhook (const char *instance,
                     const char *event,
                     const json_t *args)
{
  struct Trigger t = {
    .instance = instance,
    .root = args
  };
  enum GNUNET_DB_QueryStatus qs;

  qs = TMH_db->lookup_webhook_by_event (TMH_db->cls,
                                        instance,
                                        event,
                                        &trigger_webhook_cb,
                                        &t);
  if (qs < 0)
    return qs;
  return t.rv;
}