Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion DEV_DOC.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@ WP_USER_EMAIL=<一般ユーザのユーザー名>
- `secrets/wp_admin_password.txt`: WordPressサイトの管理者アカウントのパスワード
- `secrets/wp_user_password.txt`: WordPressサイトの一般ユーザーのパスワード

ボーナスサービスを起動する場合(`make bonus`)は、以下も必要になる。

- `secrets/redis_password.txt`: Redisの`requirepass`に設定するパスワード
- `secrets/ftp_password.txt`: FTPユーザー`ftp_user`のパスワード
- `secrets/watcher_password.txt`: WatcherのBasic認証のパスワード

**注意**: これらは、対応する機能を使わない設定にしていてもファイル自体は存在している必要がある。Docker Composeはサービス定義に書かれたsecretを設定内容と無関係にマウントするため、ファイルが無いと`bind source path does not exist`でコンテナの作成に失敗する。特に`secrets/watcher_password.txt`は、`config/watcher.yml`で`auth.enabled: false`にしている場合でも必要になる。

## ビルドと起動(Makefile & Docker Compose)

```bash
Expand Down Expand Up @@ -113,4 +121,6 @@ mandatoryのnginxコンテナのビルド引数(`NGINX_CONF`)を切り替える
- 死活判定はTCP接続確認またはHTTP GETによるネットワークプローブのみで行い、Docker APIへの`docker.sock`経由アクセスは採用していない(理由はREADMEの「ボーナス」セクション参照)
- 各対象の稼働率(累積%)・Checkerの種類ごとの平均応答時間を集計して表示する
- ステータスが変化した際、Discord Webhookへ通知する(`config/watcher.yml`の`alert.webhook`で有効化・通知先URLを設定)
- 認証機能は未実装(bonusの「任意サービス」枠として、他の実装(config駆動・稼働率集計・アラート通知)を優先したため)
- ダッシュボード(`/`)とJSON API(`/api/status`)はBasic認証で保護している。有効化とユーザー名は`config/watcher.yml`の`auth`セクションで設定し、パスワードは起動時に`/run/secrets/watcher_password`から読み込む
- 資格情報の比較は、`crypto/sha256`で固定長にしてから`crypto/subtle.ConstantTimeCompare`で行う(比較対象の長さが漏れることと、比較にかかる時間から内容を推測されることの両方を避けるため)。ユーザー名とパスワードの判定を`&&`の短絡評価に任せず、両方を必ず評価してから結合している
- `/health`は認証の対象外(死活確認用エンドポイントとして、外部の監視ツールから無認証で叩けるようにするため)
12 changes: 11 additions & 1 deletion DEV_DOC.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@ The following passwords have to be set:
- `secrets/wp_admin_password.txt`: password of the administrator account of the WordPress site
- `secrets/wp_user_password.txt`: password of the regular user of the WordPress site

When the bonus services are started (`make bonus`), the following are needed as well:

- `secrets/redis_password.txt`: the password set as Redis's `requirepass`
- `secrets/ftp_password.txt`: password of the FTP user `ftp_user`
- `secrets/watcher_password.txt`: password for Watcher's Basic authentication

**Note**: these files have to exist even when the corresponding feature is configured to be off. Docker Compose mounts the secrets declared in a service definition regardless of what the configuration says, so a missing file makes container creation fail with `bind source path does not exist`. In particular, `secrets/watcher_password.txt` is required even when `auth.enabled: false` is set in `config/watcher.yml`.

## Building and Launching the Project (Makefile & Docker Compose)

```bash
Expand Down Expand Up @@ -113,4 +121,6 @@ Switching the `NGINX_CONF` build argument of the core nginx container makes it l
- Liveness is determined solely by network probing — a TCP connection check or an HTTP GET. Access to the Docker API through `docker.sock` is not used (see the "Bonus" section of the README for the reasoning)
- The uptime ratio (cumulative %) of each target and the average response time per checker type are aggregated and displayed
- When a status changes, a notification is sent to a Discord Webhook (enabled, together with the destination URL, in `alert.webhook` of `config/watcher.yml`)
- Authentication is not implemented (as the "service of choice" of the bonus part, the other work — configuration-driven targets, uptime aggregation and alert notification — was prioritized instead)
- The dashboard (`/`) and the JSON API (`/api/status`) are protected with Basic authentication. It is enabled, and the user name is set, in the `auth` section of `config/watcher.yml`; the password is read at startup from `/run/secrets/watcher_password`
- Credentials are compared by first reducing them to a fixed length with `crypto/sha256` and then using `crypto/subtle.ConstantTimeCompare`, which avoids both leaking the length of the compared values and allowing their content to be inferred from how long the comparison takes. The user name and the password checks are not left to the short-circuiting of `&&`: both are always evaluated before being combined
- `/health` is left outside authentication, so that external monitoring tools can reach the liveness endpoint without credentials
2 changes: 1 addition & 1 deletion README.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ Dockerのbridgeネットワークでは、各コンテナが独自のネット
- **Adminer**: 単一PHPファイルで完結するツールのため専用のWebサーバーを持たせず、mandatoryのnginxからphp-fpmへ直接fastcgi転送する構成にした。認証情報はブラウザのログイン画面で毎回入力する設計のため、コンテナ側にsecretsを持たせていない。
- **reversi(単純な静的サイト枠)**: 自作のC++製リバーシAIをEmscriptenでWebAssembly化し、ブラウザ完結で遊べる静的サイトとして提供する。ビルド時だけ必要な重いツールチェーン(Emscripten一式)をマルチステージビルドで最終イメージから除外している。配信自体は`python3 -m http.server`で行い、外部公開はmandatoryのnginxからの`proxy_pass`に統一した。
- **FTP Server**: WordPressのボリュームに直接アクセスできるFTP/FTPSサーバー。RFC 2577(FTP Security Considerations)が推奨する対策に従い、bounce attackの原因となる`PORT`コマンド(アクティブモード)を無効化し、パッシブモードのみを許可している。制御・データ両方の接続をTLSで暗号化するFTPSにも対応している。
- **Watcher(任意サービス枠)**: 各コンテナの死活状態・稼働率・平均応答時間を可視化する自作のGo製ダッシュボード。監視対象・チェック間隔・通知設定は外部のYAMLファイルで管理し、コードの再ビルドなしに変更できる。コンテナの実行状態を権威的に取得する手段(Docker APIへの`docker.sock`経由アクセス)は、コンテナに実質ホスト操作の全権限を渡すことになりセキュリティ上のリスクが大きく、監視対象がwatcher1つに閉じるこのプロジェクトの規模に見合わないと判断し、採用しなかった。そのため状態表示は「正常に稼働中」「異常あり(・停止中)」の2つに絞り、ネットワークレベルの疎通結果だけからコンテナの停止を断定するような表示はしていない。
- **Watcher(任意サービス枠)**: 各コンテナの死活状態・稼働率・平均応答時間を可視化する自作のGo製ダッシュボード。監視対象・チェック間隔・通知設定は外部のYAMLファイルで管理し、コードの再ビルドなしに変更できる。コンテナの実行状態を権威的に取得する手段(Docker APIへの`docker.sock`経由アクセス)は、コンテナに実質ホスト操作の全権限を渡すことになりセキュリティ上のリスクが大きく、監視対象がwatcher1つに閉じるこのプロジェクトの規模に見合わないと判断し、採用しなかった。そのため状態表示は「正常に稼働中」「異常あり(・停止中)」の2つに絞り、ネットワークレベルの疎通結果だけからコンテナの停止を断定するような表示はしていない。ダッシュボードとJSON APIはBasic認証で保護し、パスワードはDocker secret経由で渡している(通信自体が自己署名証明書によるTLSなので、資格情報が平文で流れることはない)。死活確認用の`/health`だけは、外部の監視ツールから無認証で叩けるよう認証の対象外にしている。

### ボーナスの使い方

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ Five additional services are provided on top of the core setup.
- **Adminer**: since the tool is a single self-contained PHP file, it is given no web server of its own. Instead requests are forwarded over FastCGI from the core nginx straight to php-fpm. No secrets are given to the container, because the credentials are typed into the browser login form each time.
- **reversi (the simple static website)**: a self-written C++ Reversi AI compiled to WebAssembly with Emscripten and served as a static site that runs entirely in the browser. The heavy toolchain needed only at build time (the whole Emscripten SDK) is kept out of the final image by a multi-stage build. Serving itself is done by `python3 -m http.server`, and external publishing is unified under a `proxy_pass` from the core nginx.
- **FTP Server**: an FTP/FTPS server with direct access to the WordPress volume. Following the mitigation recommended by RFC 2577 (FTP Security Considerations), the `PORT` command (active mode) — the root cause of the bounce attack — is disabled, and only passive mode is allowed. FTPS is supported as well, encrypting both the control and the data connection with TLS.
- **Watcher (the service of choice)**: a self-written dashboard in Go that visualizes the liveness, uptime ratio and average response time of each container. Monitoring targets, check interval and notification settings are managed in an external YAML file and can be changed without rebuilding the code. The authoritative way to obtain a container's actual run state (reaching the Docker API through `docker.sock`) was considered and rejected: it effectively hands the container full control over the host's Docker, which is too large a security risk, and it does not justify itself at the scale of this project where Watcher would be its only consumer. Because of that, the status display is limited to "running normally" and "problem detected (or stopped)", and it never asserts that a container is stopped on the basis of network-level probing alone.
- **Watcher (the service of choice)**: a self-written dashboard in Go that visualizes the liveness, uptime ratio and average response time of each container. Monitoring targets, check interval and notification settings are managed in an external YAML file and can be changed without rebuilding the code. The authoritative way to obtain a container's actual run state (reaching the Docker API through `docker.sock`) was considered and rejected: it effectively hands the container full control over the host's Docker, which is too large a security risk, and it does not justify itself at the scale of this project where Watcher would be its only consumer. Because of that, the status display is limited to "running normally" and "problem detected (or stopped)", and it never asserts that a container is stopped on the basis of network-level probing alone. The dashboard and the JSON API are protected with Basic authentication, and the password is supplied through a Docker secret (the connection itself is TLS with a self-signed certificate, so the credentials never travel in plain text). Only `/health` is left outside authentication, so that external monitoring tools can reach it without credentials.

### Running the Bonus Services

Expand Down
23 changes: 20 additions & 3 deletions USER_DOC.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ make hosts
| `secrets/wp_admin_password.txt` | WordPress管理者アカウントのパスワード |
| `secrets/wp_user_password.txt` | WordPress一般ユーザーのパスワード |

`make bonus`でボーナスサービスも起動する場合は、以下の3ファイルも必要になる。

| ファイル | 用途 |
|---|---|
| `secrets/redis_password.txt` | Redisの接続パスワード |
| `secrets/ftp_password.txt` | FTPユーザー(`ftp_user`)のパスワード |
| `secrets/watcher_password.txt` | Watcherのダッシュボードを閲覧するためのパスワード |

**注意**: `secrets/watcher_password.txt`は、Watcherの認証を無効(`config/watcher.yml`で`auth.enabled: false`)にしている場合でも必要になる。Docker Composeは設定の内容に関わらずsecretをマウントするため、ファイルが存在しないとコンテナの作成自体が失敗する。

管理者ユーザー名等の非機密情報は`srcs/.env`に記載する。

## サービスが正しく動作しているかの確認方法
Expand Down Expand Up @@ -105,7 +115,14 @@ WordPressサイトのファイルへFTP/FTPSでアクセスできる。

### Watcher

`https://<login>.42.fr:8082/` にアクセスすると、各サービスの死活状態・稼働率・平均応答時間が一覧表示される(5秒間隔で自動更新)。認証は設けていないため、誰でも閲覧できる。
`https://<login>.42.fr:8082/` にアクセスすると、各サービスの死活状態・稼働率・平均応答時間が一覧表示される(5秒間隔で自動更新)。

閲覧にはBasic認証が必要で、アクセスするとブラウザがログインダイアログを表示する。

| 項目 | 値 |
|---|---|
| ユーザー名 | `config/watcher.yml`の`auth.username`(既定は`watcher`) |
| パスワード | `secrets/watcher_password.txt` の中身 |

- `/api/status`: 同内容をJSON形式で取得できるAPI
- `/health`: watcher自身の死活確認用エンドポイント
- `/api/status`: 同内容をJSON形式で取得できるAPI(こちらもBasic認証が必要)
- `/health`: watcher自身の死活確認用エンドポイント(外部の監視ツールから叩けるよう、認証の対象外)
23 changes: 20 additions & 3 deletions USER_DOC.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ Passwords are stored as plain files under the `secrets/` directory of the reposi
| `secrets/wp_admin_password.txt` | Password of the WordPress administrator account |
| `secrets/wp_user_password.txt` | Password of the regular WordPress user |

When the bonus services are started as well with `make bonus`, the following three files are needed too.

| File | Purpose |
|---|---|
| `secrets/redis_password.txt` | Connection password for Redis |
| `secrets/ftp_password.txt` | Password of the FTP user (`ftp_user`) |
| `secrets/watcher_password.txt` | Password used to view the Watcher dashboard |

**Note**: `secrets/watcher_password.txt` is required even when Watcher's authentication is turned off (`auth.enabled: false` in `config/watcher.yml`). Docker Compose mounts the secret regardless of what the configuration says, so if the file does not exist the container cannot even be created.

Non-confidential values such as the administrator's user name are written in `srcs/.env`.

## Verifying That Services Are Running Correctly
Expand Down Expand Up @@ -105,7 +115,14 @@ The files of the WordPress site can be accessed over FTP/FTPS.

### Watcher

Opening `https://<login>.42.fr:8082/` shows a list of the liveness, uptime ratio and average response time of each service (refreshed automatically every 5 seconds). No authentication is in place, so anyone can view it.
Opening `https://<login>.42.fr:8082/` shows a list of the liveness, uptime ratio and average response time of each service (refreshed automatically every 5 seconds).

Viewing it requires Basic authentication; the browser presents a login dialog on access.

| Field | Value |
|---|---|
| Username | `auth.username` in `config/watcher.yml` (`watcher` by default) |
| Password | the contents of `secrets/watcher_password.txt` |

- `/api/status`: an API returning the same content in JSON
- `/health`: an endpoint for checking the liveness of Watcher itself
- `/api/status`: an API returning the same content in JSON (Basic authentication required as well)
- `/health`: an endpoint for checking the liveness of Watcher itself (left outside authentication so that external monitoring tools can reach it)
4 changes: 4 additions & 0 deletions srcs/docker-compose.bonus.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,13 @@ services:
container_name: watcher
ports:
- "8082:8082"
secrets:
- watcher_password

secrets:
redis_password:
file: ../secrets/redis_password.txt
ftp_password:
file: ../secrets/ftp_password.txt
watcher_password:
file: ../secrets/watcher_password.txt
22 changes: 20 additions & 2 deletions srcs/requirements/bonus/watcher/cmd/watcher/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"crypto/tls"
"log"
"net/http"
"os"
"strings"
"time"

"watcher/internal/alert"
Expand Down Expand Up @@ -54,8 +56,24 @@ func main() {
}
go monitor.Start(store, targets, interval)

http.HandleFunc("/", server.IndexHandler(store))
http.HandleFunc("/api/status", server.StatusAPIHandler(store))
var authPassword string
if cfg.Auth.Enabled {
b, err := os.ReadFile("/run/secrets/watcher_password")
if err != nil {
log.Fatalf("failed to read watcher password: %v", err)
}
authPassword = strings.TrimSpace(string(b))
}

protect := func(h http.HandlerFunc) http.HandlerFunc {
if !cfg.Auth.Enabled {
return h
}
return server.BasicAuth(cfg.Auth.Username, authPassword, h)
}

http.HandleFunc("/", protect(server.IndexHandler(store)))
http.HandleFunc("/api/status", protect(server.StatusAPIHandler(store)))
http.HandleFunc("/health", server.HealthCheckHandler())

fs := http.FileServer(http.Dir("web/static"))
Expand Down
4 changes: 4 additions & 0 deletions srcs/requirements/bonus/watcher/config/watcher.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,7 @@ alert:
webhook:
enabled: false
urls: []

auth:
enabled: true
username: watcher
6 changes: 6 additions & 0 deletions srcs/requirements/bonus/watcher/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ type Config struct {
Default DefaultConfig `yaml:"default"`
Targets []TargetConfig `yaml:"targets"`
Alert AlertConfig `yaml:"alert"`
Auth AuthConfig `yaml:"auth"`
}

type AuthConfig struct {
Enabled bool `yaml:"enabled"`
Username string `yaml:"username"`
}

type MonitorConfig struct {
Expand Down
23 changes: 23 additions & 0 deletions srcs/requirements/bonus/watcher/internal/server/server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package server

import (
"crypto/sha256"
"crypto/subtle"
"encoding/json"
"fmt"
"html/template"
Expand Down Expand Up @@ -66,3 +68,24 @@ func HealthCheckHandler() http.HandlerFunc {
w.Write([]byte("OK"))
}
}

func BasicAuth(username, password string, next http.HandlerFunc) http.HandlerFunc {
expectedUser := sha256.Sum256([]byte(username))
expectedPass := sha256.Sum256([]byte(password))

return func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if ok {
gotUser := sha256.Sum256([]byte(user))
gotPass := sha256.Sum256([]byte(pass))
userMatch := subtle.ConstantTimeCompare(gotUser[:], expectedUser[:]) == 1
passMatch := subtle.ConstantTimeCompare(gotPass[:], expectedPass[:]) == 1
if userMatch && passMatch {
next(w, r)
return
}
}
w.Header().Set("WWW-Authenticate", `Basic realm="watcher", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}
}
Loading