Fastify+Let's Encryptでhttpsサーバーを立てる

# はじめに

そういえばFastifyで[Let's Encrypt](https://letsencrypt.org/)を導入したことなかったのを思い出したので検証のためにやってみた。ついでにLet's Encryptの記事を書いてなかった気がするので証明書作成の方法も丁寧に書いておこうと思う。

環境
- AWS EC2 Ubuntu 20.04の適当なインスタンス
- セキュリティグループで HTTPS(443)を開けておく
- インスタンスにドメインを割り当てておく今回はテスト用に `letsencrypttest.bathtimefish.com` をRoute53で割り当てた

# Let's Encryptで証明書を発行する

まずは `certbot` をインストールする

```shell
sudo apt update
sudo apt upgrade
sudo apt install -y certbot
```

対話形式でStandaloneな証明書を発行する

```shell
sudo certbot certonly --standalone
```

いろいろ聞かれる。メールアドレスを入力

```shell
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator standalone, Installer None
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): hoge@bathtimefish.com
```

同意する

```shell
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A
```

はい

```
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y
```

ドメイン名を入力する

```shell
lease enter in your domain name(s) (comma and/or space separated)  (Enter 'c'
to cancel): letsencrypttest.bathtimefish.com
```

証明書ができた

```
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for letsencrypttest.bathtimefish.com
Waiting for verification...
Cleaning up challenges

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/letsencrypttest.bathtimefish.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/letsencrypttest.bathtimefish.com/privkey.pem
   Your cert will expire on 2021-07-03. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot
   again. To non-interactively renew *all* of your certificates, run
   "certbot renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le
```

証明書は `/etc/letsencrypt/live/[ドメイン名]` 下に作成される

```shell
sudo ls /etc/letsencrypt/live/letsencrypttest.bathtimefish.com
README	cert.pem  chain.pem  fullchain.pem  privkey.pem
```

要はこいつをFastifyで読み込めば良い

# httpsサーバーを作成する

node.jsをセットアップする

```shell
sudo apt install -y nodejs npm
sudo npm i -g n
sudo n latest
sudo npm i -S typescript ts-node 
sudo apt remove nodejs
sudo apt autoclean
```

サーバー開発に必要なものをセットアップする

```shell
mkdir -p ./work && cd $_
npm i -S fastify
npm i -D @types/node
npx tsc --init
```

コードは以下

```index.ts
import * as fs from 'fs';
import * as http2 from 'http2';
import fastify from 'fastify';

const certPath = '/etc/letsencrypt/live/letsencrypttest.bathtimefish.com';

const server = fastify({
  logger: true,
  http2: true,
  https: {
    key: fs.readFileSync(`${certPath}/privkey.pem`),
    cert: fs.readFileSync(`${certPath}/fullchain.pem`)
  },
});

server.get('/', function (request, reply) {
  reply.code(200).send({ hello: 'world' });
});

server.listen(443, '0.0.0.0', (err, address) => {
  if (err) {
    console.error(err);
    process.exit(1);
  }
});
```

# 実行する

証明書が`/etc`下にあるのとポート443を使うので`sudo`付きで実行する。

```shell
sudo ts-node index.ts
```

ローカルでhttpsアクセスしてみる

```
curl https://letsencrypttest.bathtimefish.com/
{"hello":"world"}
```

うまくいった。

# おわりに

expressと似たような感じでFastifyでも簡単にhttps化できる。Fastifyのノウハウってけっこう少ない気がするのでこういうtipsもちょっとずつ書いていったほうがいいかな。忘れるし。