aboutsummaryrefslogtreecommitdiff
path: root/packages/taler-wallet-cli/src/lint.ts
blob: 2b888ccf48ac6873f38f8e89bbedee1a5da3e663 (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
/*
 This file is part of GNU Taler
 (C) 2021 Taler Systems S.A.

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

 GNU 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
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

/**
 * The deployment linter implements checks for a deployment
 * of the GNU Taler exchange.  It is meant to help sysadmins
 * when setting up an exchange.
 *
 * The linter does checks in the configuration and uses
 * various tools of the exchange in test mode (-t).
 *
 * To be able to run the tools as the right user, the linter should be
 * run as root.
 *
 * @author Florian Dold <dold@taler.net>
 */

/**
 * Imports.
 */
import {
  codecForExchangeKeysJson,
  codecForKeysManagementResponse,
  Configuration,
  decodeCrock,
} from "@gnu-taler/taler-util";
import {
  NodeHttpLib,
  readSuccessResponseJsonOrThrow,
} from "@gnu-taler/taler-wallet-core";
import { URL } from "url";
import { spawn } from "child_process";
import { delayMs } from "./harness/harness.js";

interface BasicConf {
  mainCurrency: string;
}

interface PubkeyConf {
  masterPublicKey: string;
}

const httpLib = new NodeHttpLib();

interface ShellResult {
  stdout: string;
  stderr: string;
  status: number;
}

interface LintContext {
  /**
   * Be more verbose.
   */
  verbose: boolean;

  /**
   * Always continue even after errors.
   */
  cont: boolean;

  cfg: Configuration;

  numErr: number;
}

/**
 * Run a shell command, return stdout.
 */
export async function sh(
  context: LintContext,
  command: string,
  env: { [index: string]: string | undefined } = process.env,
): Promise<ShellResult> {
  if (context.verbose) {
    console.log("executing command:", command);
  }
  return new Promise((resolve, reject) => {
    const stdoutChunks: Buffer[] = [];
    const stderrChunks: Buffer[] = [];
    const proc = spawn(command, {
      stdio: ["inherit", "pipe", "pipe"],
      shell: true,
      env: env,
    });
    proc.stdout.on("data", (x) => {
      if (x instanceof Buffer) {
        stdoutChunks.push(x);
      } else {
        throw Error("unexpected data chunk type");
      }
    });
    proc.stderr.on("data", (x) => {
      if (x instanceof Buffer) {
        stderrChunks.push(x);
      } else {
        throw Error("unexpected data chunk type");
      }
    });
    proc.on("exit", (code, signal) => {
      if (code != 0 && context.verbose) {
        console.log(`child process exited (${code} / ${signal})`);
      }
      const bOut = Buffer.concat(stdoutChunks).toString("utf-8");
      const bErr = Buffer.concat(stderrChunks).toString("utf-8");
      resolve({
        status: code ?? -1,
        stderr: bErr,
        stdout: bOut,
      });
    });
    proc.on("error", () => {
      reject(Error("Child process had error"));
    });
  });
}

function checkBasicConf(context: LintContext): BasicConf {
  const cfg = context.cfg;
  const currencyEntry = cfg.getString("taler", "currency");
  let mainCurrency: string | undefined;

  if (!currencyEntry.value) {
    context.numErr++;
    console.log("error: currency not defined in section TALER option CURRENCY");
    console.log("Aborting further checks.");
    process.exit(1);
  } else {
    mainCurrency = currencyEntry.value.toUpperCase();
  }

  if (mainCurrency === "KUDOS") {
    console.log(
      "warning: section TALER option CURRENCY contains toy currency value KUDOS",
    );
  }

  const roundUnit = cfg.getAmount("taler", "currency_round_unit");
  const ru = roundUnit.required();
  if (ru.currency.toLowerCase() != mainCurrency.toLowerCase()) {
    context.numErr++;
    console.log(
      "error: [TALER]/CURRENCY_ROUND_UNIT: currency does not match main currency",
    );
  }
  return { mainCurrency };
}

function checkCoinConfig(context: LintContext, basic: BasicConf): void {
  const cfg = context.cfg;
  const coinPrefix1 = "COIN_";
  const coinPrefix2 = "COIN-";
  let numCoins = 0;

  for (const secName of cfg.getSectionNames()) {
    if (!(secName.startsWith(coinPrefix1) || secName.startsWith(coinPrefix2))) {
      continue;
    }
    numCoins++;

    // FIXME: check that section is well-formed
  }

  if (numCoins == 0) {
    context.numErr++;
    console.log(
      "error: no coin denomination configured, please configure [coin-*] sections",
    );
  }
}

async function checkWireConfig(context: LintContext): Promise<void> {
  const cfg = context.cfg;
  const accountPrefix = "EXCHANGE-ACCOUNT-";
  const accountCredentialsPrefix = "EXCHANGE-ACCOUNTCREDENTIALS-";

  let accounts = new Set<string>();
  let credentials = new Set<string>();

  for (const secName of cfg.getSectionNames()) {
    if (secName.startsWith(accountPrefix)) {
      accounts.add(secName.slice(accountPrefix.length));
      // FIXME: check settings
    }

    if (secName.startsWith(accountCredentialsPrefix)) {
      credentials.add(secName.slice(accountCredentialsPrefix.length));
      // FIXME: check settings
    }
  }

  if (accounts.size === 0) {
    context.numErr++;
    console.log(
      "error: No accounts configured (no sections EXCHANGE-ACCOUNT-*).",
    );
    if (!context.cont) {
      console.log("Aborting further checks.");
      process.exit(1);
    }
  }

  for (const acc of accounts) {
    if (!credentials.has(acc)) {
      console.log(
        `warning: no credentials configured for exchange-account-${acc}`,
      );
    }
  }

  for (const acc of accounts) {
    // test credit history
    {
      const res = await sh(
        context,
        "su -l --shell /bin/sh " +
          `-c 'taler-exchange-wire-gateway-client -s exchange-accountcredentials-${acc} --credit-history' ` +
          "taler-exchange-wire",
      );
      if (res.status != 0) {
        context.numErr++;
        console.log(res.stdout);
        console.log(res.stderr);
        console.log(
          "error: Could not run taler-exchange-wire-gateway-client. Please review logs above.",
        );
        if (!context.cont) {
          console.log("Aborting further checks.");
          process.exit(1);
        }
      }
    }
  }

  // TWG client
  {
    const res = await sh(
      context,
      `su -l --shell /bin/sh -c 'taler-exchange-wirewatch -t' taler-exchange-wire`,
    );
    if (res.status != 0) {
      context.numErr++;
      console.log(res.stdout);
      console.log(res.stderr);
      console.log("error: Could not run wirewatch. Please review logs above.");
      if (!context.cont) {
        console.log("Aborting further checks.");
        process.exit(1);
      }
    }
  }

  // Wirewatch
  {
    const res = await sh(
      context,
      `su -l --shell /bin/sh -c 'taler-exchange-wirewatch -t' taler-exchange-wire`,
    );
    if (res.status != 0) {
      context.numErr++;
      console.log(res.stdout);
      console.log(res.stderr);
      console.log("error: Could not run wirewatch. Please review logs above.");
      if (!context.cont) {
        console.log("Aborting further checks.");
        process.exit(1);
      }
    }
  }

  // Closer
  {
    const res = await sh(
      context,
      `su -l --shell /bin/sh -c 'taler-exchange-closer -t' taler-exchange-closer`,
    );
    if (res.status != 0) {
      context.numErr++;
      console.log(res.stdout);
      console.log(res.stderr);
      console.log("error: Could not run closer. Please review logs above.");
      if (!context.cont) {
        console.log("Aborting further checks.");
        process.exit(1);
      }
    }
  }
}

async function checkAggregatorConfig(context: LintContext) {
  const res = await sh(
    context,
    "su -l --shell /bin/sh -c 'taler-exchange-aggregator -t' taler-exchange-aggregator",
  );
  if (res.status != 0) {
    context.numErr++;
    console.log(res.stdout);
    console.log(res.stderr);
    console.log("error: Could not run aggregator. Please review logs above.");
    if (!context.cont) {
      console.log("Aborting further checks.");
      process.exit(1);
    }
  }
}

async function checkCloserConfig(context: LintContext) {
  const res = await sh(
    context,
    `su -l --shell /bin/sh -c 'taler-exchange-closer -t' taler-exchange-closer`,
  );
  if (res.status != 0) {
    context.numErr++;
    console.log(res.stdout);
    console.log(res.stderr);
    console.log("error: Could not run closer. Please review logs above.");
    if (!context.cont) {
      console.log("Aborting further checks.");
      process.exit(1);
    }
  }
}

function checkMasterPublicKeyConfig(context: LintContext): PubkeyConf {
  const cfg = context.cfg;
  const pub = cfg.getString("exchange", "master_public_key");

  const pubDecoded = decodeCrock(pub.required());

  if (pubDecoded.length != 32) {
    context.numErr++;
    console.log("error: invalid master public key");
    if (!context.cont) {
      console.log("Aborting further checks.");
      process.exit(1);
    }
  }

  return {
    masterPublicKey: pub.required(),
  };
}

export async function checkExchangeHttpd(
  context: LintContext,
  pubConf: PubkeyConf,
): Promise<void> {
  const cfg = context.cfg;
  const baseUrlEntry = cfg.getString("exchange", "base_url");

  if (!baseUrlEntry.isDefined) {
    context.numErr++;
    console.log(
      "error: configuration needs to specify section EXCHANGE option BASE_URL",
    );
    if (!context.cont) {
      console.log("Aborting further checks.");
      process.exit(1);
    }
  }

  const baseUrl = baseUrlEntry.required();

  if (!baseUrl.startsWith("http")) {
    context.numErr++;
    console.log(
      "error: section EXCHANGE option BASE_URL needs to be an http or https URL",
    );
    if (!context.cont) {
      console.log("Aborting further checks.");
      process.exit(1);
    }
  }

  if (!baseUrl.endsWith("/")) {
    context.numErr++;
    console.log(
      "error: section EXCHANGE option BASE_URL needs to end with a slash",
    );
    if (!context.cont) {
      console.log("Aborting further checks.");
      process.exit(1);
    }
  }

  if (!baseUrl.startsWith("https://")) {
    console.log(
      "warning: section EXCHANGE option BASE_URL: it is recommended to serve the exchange via HTTPS",
    );
  }

  {
    const mgmtUrl = new URL("management/keys", baseUrl);
    const resp = await httpLib.get(mgmtUrl.href);

    const futureKeys = await readSuccessResponseJsonOrThrow(
      resp,
      codecForKeysManagementResponse(),
    );

    if (futureKeys.future_denoms.length > 0) {
      console.log(
        `warning: exchange has denomination keys that need to be signed by the offline signing procedure`,
      );
    }

    if (futureKeys.future_signkeys.length > 0) {
      console.log(
        `warning: exchange has signing keys that need to be signed by the offline signing procedure`,
      );
    }
  }

  // Check if we can use /keys already
  {
    const keysUrl = new URL("keys", baseUrl);

    const resp = await Promise.race([httpLib.get(keysUrl.href), delayMs(2000)]);

    if (!resp) {
      context.numErr++;
      console.log(
        "error: request to /keys timed out. " +
          "Make sure to sign and upload denomination and signing keys " +
          "with taler-exchange-offline.",
      );
      if (!context.cont) {
        console.log("Aborting further checks.");
        process.exit(1);
      }
    } else {
      const keys = await readSuccessResponseJsonOrThrow(
        resp,
        codecForExchangeKeysJson(),
      );

      if (keys.master_public_key !== pubConf.masterPublicKey) {
        context.numErr++;
        console.log(
          "error: master public key of exchange does not match public key of live exchange",
        );
        if (!context.cont) {
          console.log("Aborting further checks.");
          process.exit(1);
        }
      }
    }
  }

  // Check /wire
  {
    const keysUrl = new URL("wire", baseUrl);

    const resp = await Promise.race([httpLib.get(keysUrl.href), delayMs(2000)]);

    if (!resp) {
      context.numErr++;
      console.log(
        "error: request to /wire timed out. " +
          "Make sure to sign and upload accounts and wire fees " +
          "using the taler-exchange-offline tool.",
      );
      if (!context.cont) {
        console.log("Aborting further checks.");
        process.exit(1);
      }
    } else {
      if (resp.status !== 200) {
        console.log(
          "error:  Can't access exchange /wire.  Please check " +
            "the logs of taler-exchange-httpd for further information.",
        );
      }
    }
  }
}

/**
 * Do some basic checks in the configuration of a Taler deployment.
 */
export async function lintExchangeDeployment(
  verbose: boolean,
  cont: boolean,
): Promise<void> {
  if (process.getuid() != 0) {
    console.log(
      "warning: the exchange deployment linter is designed to be run as root",
    );
  }

  const cfg = Configuration.load();

  const context: LintContext = {
    cont,
    verbose,
    cfg,
    numErr: 0,
  };

  const basic = checkBasicConf(context);

  checkCoinConfig(context, basic);

  await checkWireConfig(context);

  await checkAggregatorConfig(context);

  await checkCloserConfig(context);

  const pubConf = checkMasterPublicKeyConfig(context);

  await checkExchangeHttpd(context, pubConf);

  if (context.numErr == 0) {
    console.log("Linting completed without errors.");
    process.exit(0);
  } else {
    console.log(`Linting completed with ${context.numErr} errors.`);
    process.exit(1);
  }
}