はじめに
kanade — 奏 は Windows・Linux・Apple Silicon macOS フリート向けの端末管理システムです。運用者は単一の CLI / SPA からスクリプト実行、ソフトウェア導入、インベントリ収集、数百台の PC のライブ性能データ表示を行えます。構成要素は次のとおりです。
| 構成要素 | 役割 |
|---|---|
| kanade-agent | 管理対象 PC 上で動く Windows サービス。NATS を購読し、コマンドを実行して結果を送り返します。 |
| kanade-backend | HTTP API + projector。状態を永続化し、SPA を配信し、operator 用エンドポイントを公開します。 |
| kanade-client | Windows と Apple Silicon macOS 14+ 向けの任意導入の Tauri エンドユーザーアプリ。macOS のネイティブ通知・自動起動連携は未実装です。 |
| NATS server | コマンド配信と結果集約のメッセージブローカー。エージェントはコマンドとテレメトリに NATS を使い、インストーラジョブはバックエンドの HTTP 経由で成果物を取得する場合もあります。 |
| kanade CLI | operator が使うコマンドライン。バイナリの publish、ジョブの起動、状態の照会を行います。 |
このサイトは 2 種類の読者を想定しています:
- 運用者 (kanade fleet の運用者) 向け — 各端末に ssh せずに各コンポーネントをアップデートする方法について解説しています(agent 経由のアップデート 参照)。
- 開発者 (agent が実行する PowerShell ジョブを作成する人) 向け — スクリプトが動作する仕組みや制限事項、最近の agent バージョンにおける変更点について解説しています(agent 向けスクリプトを書く 参照)。
詳細なプロトコル / on-wire 仕様は Spec にあります (旧 single-page ドキュメント。docs サイトが整うにつれて章別に分割予定)。
開発者クイックスタート
このガイドでは、ローカルの kanade 開発環境をセットアップして起動する手順を説明します。
1. 前提条件
開始する前に、Windows マシンに以下がインストールされていることを確認してください。
- Rust ツールチェーン (stable チャンネル)
- cargo-make (
cargo install --force cargo-makeでインストール) - bun (SPA の依存関係管理とビルド実行用)
- gsudo (ローカルのサービスデプロイテスト用)
- nats-server (PATH から実行可能であること)
2. 初回セットアップ
ワークスペースのルートで以下のコマンドを実行し、git の pre-push フックを登録し、apm.yml で定義されたエージェントスキルをインストールします。
cargo make setup
3. 開発サンドボックスの起動
単一のコマンドを使用するだけで、ローカルホスト上に完全に分離されたマルチコンポーネント開発スタックを起動できます。
cargo make dev
このタスクは、ループバックサンドボックス内で以下のサービスを並行して実行します。
- nats-dev: ポート
4223で待機する、認証なしの NATS ブローカー。 - backend-dev: 認証が無効化された、ポート
8081で待機する開発用 API サーバー。 - agent-dev: ポート
4223の開発用 NATS ブローカーと通信する、ローカルの開発用エージェント。 - web-dev:
http://localhost:5173で待機する、React SPA 用の Vite 開発サーバー。
Ctrl+C を押すことで、すべてのコンポーネントをクリーンに終了できます。
4. 複数エージェントフリートのシミュレーション
複数のマシンを管理しているときにのみ発生する動作(並行実行結果のプロジェクションや ID 衝突など)をデバッグするために、マルチエージェントサンドボックスを起動できます。
cargo make dev-fleet
これにより、NATS ブローカー、バックエンド、SPA に加えて、独立した ID(dev-pc-1、dev-pc-2、dev-pc-3)と隔離された状態データベースを持つ 3 つの個別開発用エージェントが起動します。
5. ローカルデプロイのテスト
Windows サービスとしてコンポーネントをインストールする全ライフサイクル(本番環境の模倣)をテストしたい場合は、ローカルデプロイスクリプトを使用します。
# Installs CLI, agent, backend, and NATS services locally via gsudo elevation
cargo make local-deploy
デプロイ後、実際の Windows サービスを確認して対話できます。完了したら、以下のタスクを使用してサービスを停止し、きれいに削除します。
cargo make local-undeploy
スクリーンショット
運用コンソールの実際の画面です。このページの画像はすべてデモスタック (cargo make demo) で撮影しています。モックバックエンドが 248 台の架空フリートを返すだけで、NATS もエージェントも実機もありません。氏名・ホスト名・サインインアカウントはすべて作り物で、実際の導入環境から取ったものは一枚もありません。
デスクトップは 1440×900、モバイルは 390×901 で撮影しています。
ここでは日本語表示のコンソールを載せています。英語版のページには同じ画面を英語表示で載せています。データはどちらも日本語のままです。フィクスチャが日本企業という設定で、ウィジェット名・グループ名・チェックの説明は運用者が書いたものだからです — 画面の翻訳対象ではありません。
フリートの全体像
ダッシュボードは、運用者が最初に見る数字から始まります。何台が報告しているか、何台が沈黙しているか、ブローカーのストリームが上限内か、直近24時間で何件のジョブが失敗したか。どの数字からも、その内訳のページへ辿れます。

下のピン留めウィジェットは運用者が定義したものです。分析ページで自分で作ったビューを、そのままダッシュボードに固定できます。
エージェント
死活だけを見るページです。どの端末がオンラインか、エージェントのバージョンはいくつか、最後に応答したのはいつか。詳細はインベントリの担当で、ここが答えるのは「居るかどうか」です。

列は選べます。上の画面ではこのフリートに不要な列を隠しています。表示列の選択はそのためのものです。
1台を見る
行を開くと、その端末自身の数字が出ます。エージェントが採取した CPU・メモリ・ディスク・ネットワークを、選んだ期間で表示します。エージェントは自分自身も計測しているので、「端末のせいか、こちらのせいか」にもグラフが答えられます。

端末が知り得ないことを持たせる
端末は自分について見えることしか報告できません。誰の机の上にあるのか、どの部門が費用を持っているのかは、端末には分からないままです。そこで各ホストは、運用者が編集できる自由な key/value のカードを持ちます — 利用者、メール、部署、拠点、資産管理番号、この端末が特別な理由を書いたメモ。

これらは決まったスキーマではなくただのフィールドで、API から書き込めます。ディレクトリ同期のジョブが display_name や department を最新に保てるのはそのためで、誰も手で入力しません。一度入れてしまえば、フリート全体に対して表示・検索できる列になります。
The writes go through the backend API (kanade meta set / rm / clear, or the per-key endpoint behind them), so they are authenticated, role-checked (operator or above) and audited. A directory-sync job that calls kanade meta set therefore needs a KANADE_AUTH_TOKEN even when it runs on the backend host; it touches only its own keys, so hand-entered ones survive.
画面を見る
報告を読むだけでは分からず、実際に見るしかないことがあります。その端末のページから画面を開いて、そのまま見られます。

このために端末側で何かを待ち受けたりはしません。エージェントはすでに外向きの接続を1本持っていて、セッションはその上を通ります。NAT の内側にいる PC も、拠点の回線にいる PC も、自宅の Wi-Fi にいる PC も、隣の席の1台とまったく同じ条件で見られます。端末へ内向きの経路を開くことはありません。ヘッダーには画面サイズと受信タイル数が出ます。更新が止まったセッションと、変化していない画面を映しているだけのセッションは、区別できるべきだからです。
上のデスクトップは合成画像です。デモスタックが描いたもので、実在の端末から取得したものではありません。
インベントリ
マニフェストが集めたものが、そのまま並びます。プローブは YAML ジョブに inventory: を付けた運用者製の PowerShell なので、列は「あなたが集めると決めたもの」です。固定スキーマではありません。行をクリックすると、その端末の全ファクトが開きます。

さらに開くと、その PC が報告したファクトが、プローブごとに1枚のカードで並びます。

何がいつ変わったか
各ファクトカードには履歴タブがあります。インベントリはスナップショットだけではありません。実行のたびに前回と差分を取るので、インストール済みアプリはそれ自身の時系列を持ちます — いつ現れ、どのバージョンを辿り、いつ消えたか。

ここでは何ひとつ「追跡する」と設定していません。プローブはインストール済みアプリの一覧を報告するだけで、追加・削除・変更の行は連続する実行を突き合わせた結果として出てきます。
コンプライアンス
ヘルスチェックのフリート横断ステータスを、チェックごとに件数付きでまとめます。チェックとは check: ヒントを持つジョブにすぎないので、追加するとはマニフェストを書くことです。kanade が検証できる項目のハードコード一覧、というものは存在しません。

肝は詳細列です。その端末がなぜ問題なのかを、その端末自身の言葉で書きます。
サポート期限
同じ仕組みを、設定ではなく日付に向けたものです。このチェックは各ホストの OS ビルドを読み、そのサポート終了日を引き当て、期限までの距離に応じて異常・警告・OK として報告します。今日は問題ないビルドが、誰かが気づこうと思うより何ヶ月も前に、自分から警告し始めます。

稼働状況
電源・セッション・スリープ・アクティブの区間を、Windows イベントログから再構成し、種別ごとのレーンで並べます。レーンの空白は、その種別のイベントが無い区間 — 電源オフ、またはアイドルです。

分析
ジョブが吐いたものを集計します。ここではアプリ利用時間・閲覧履歴・インベントリを出しています。ウィジェットは YAML で定義し、ダッシュボードに固定できます。

タブは決まったレポートの一覧ではありません。ひとつひとつがどれかのマニフェストが宣言した dashboard: の名前なので、その名前を名乗るウィジェットを書けば新しいタブが現れます。次の2つはフィクスチャに入っているものです。


グループ
宣言的なフリートグループです。動的グループはクエリを持ち、バックエンドが一定間隔で再評価するので、メタデータが変われば所属も追随します — エージェントに site と department を一度付ければ、異動した端末は自分で正しいグループに入ります。静的グループはメンバーを直接列挙するもので、クエリでは表せない所属のためにあります。

通知
クライアントアプリに通知を送り、誰が確認したかを追跡します。本文は Markdown(見出し・箇条書き・表・リンク)なので、全社通知を段落ではなく文書として書けます。

誰が確認し、誰が取り消したか
通知を開くと、宛先ごとに、その端末にサインインしていた本人と紐づけて追跡されます。状態は2つではなく3つです — 確認済み、まだ未確認、そして取消済(一度確認したあとに取り消した人)。取消済の行は両方の時刻を保持するので、「全員が読んだ」があとから静かに真に戻ることはありません。

ジョブ
マニフェストそのものを、タグ別にまとめた一覧です。kanade が端末で実行するものは、すべてこのどれかです。

マニフェストそのもの
開くと、運用者が書いた YAML がそのまま出ます。そこから生成したフォームではありません。コメントもブロックスカラーのインデントも往復して残ります。ソースを解析したオブジェクトから再直列化するのではなく、そのまま保存しているからです — 保存したファイルが、そのまま返ってきます。エディタはスキーマを理解しているので、フィールド名にカーソルを合わせると説明が出ます。

Git で管理されているマニフェストは、代わりに読み取り専用で開き、リポジトリ内のパスを示します。SPA 側の編集が正本から乖離することを許さない、ということです。
1回の実行
配信のたびに、その実行自身の結果が残ります。終了コード、ジョブとリクエストへ辿るための各種 ID、そしてホストが出力したそのままの内容です。失敗は赤いバッジ以上の価値があります — この例では、原因になった PowerShell のエラーがそのまま入っています。

監査ログ
すべての配信と、すべての運用者操作を、その裏にあるペイロードごと記録します。実行主体・アクション・対象で絞り込め、ペイロード本文の全文検索もできます。

アカウント
運用者アカウントと、そのページアクセスです。混同しやすい3状態を同時に出しています — 無制限、アカウント個別の許可リスト、そして共有の権限グループ。グループが設定されている場合はグループが優先し、アカウント個別のリストは(あっても)効きません。

自分のアカウント
二要素認証とパスワードは、ひとつのセルフサービスページにまとまっています。管理者を介さずに運用者自身が設定できます。登録はごく普通の TOTP で、任意の認証アプリで QR を読むか、セットアップキーを手入力します。候補の秘密鍵は実際のコードで確認できて初めて保存されるので、途中でやめた登録はアカウントを元のまま残します。

JetStream
ブローカー自身の健康状態です。バックエンドがブートストラップするストリーム・KVバケット・オブジェクトストアを、上限に対する使用量とともに一覧します。

Activity の履歴検索 API
GET /api/results は従来どおり結果の JSON 配列を返します(#1666)。 pc_id、job_id、exec_id、stdout、stderr は正規表現です。 アンカーのない PC001 は PC0010 にも一致します。識別子の完全一致を 指定する場合は ^PC001$ を使い、識別子中の正規表現メタ文字をエスケープ してください。安全に完全一致と判定できる識別子のパターンだけが SQL の 等価条件へ変換されます。出力の正規表現は出力全体に適用されます。
since と until は RFC 3339 形式で指定する started_at の包含下限・上限です。 省略した側には時刻制限がありません。since が until より後、年が 0〜9999 の範囲外、不正な日時、不正なカーソルは HTTP 400 になります。 limit は返却件数で、既定値は 50、指定可能範囲は 1〜1000 です。
一般の正規表現検索は1リクエストにつき最大10,000行、stdout または stderr の検索では最大1,000行を調べます。この上限は保持履歴の検索可能範囲 を意味しません。次のレスポンスヘッダーで継続の要否を判定します。
| ヘッダー | 意味 |
|---|---|
X-Results-Scanned | 今回調べた候補行数 |
X-Results-Stop-Reason | limit_reached: 返却件数に到達、scan_limit_reached: 走査上限に到達、end_of_range: 指定範囲を走査し終えた |
X-Results-Next-Cursor | 古い履歴が残る場合に返す継続トークン |
配列が空でも scan_limit_reached なら、まだ一致が残っている可能性があります。 次のリクエストは検索条件と時刻境界を保ち、cursor にトークンを渡します。 カーソルは検索条件に紐づくため、条件を変える場合は破棄してください。 順序は started_at DESC, result_id DESC で、同時刻の行も継続できます。 end_of_range が示す完了は指定範囲に対するもので、保持履歴全体とは限りません。
Activity の「Search older history」で継続し、「Previous window」で戻れます。 「Back to newest」は検索を最初からやり直します。期間プリセットの下限は ページ間で固定され、フィルター変更や検索のやり直しで再設定されます。
ダークテーマ
既定では OS の設定に追随し、ブラウザごとにライト/ダークへ固定もできます。
![]() | ![]() |
![]() | ![]() |
スマートフォンでは
1024px を下回ると、データテーブルは表であることをやめます。各行がカードになり、値には列名が付きます。横スクロールも、セルを読むためのピンチズームもありません。
![]() | ![]() | ![]() |
クライアントアプリ
利用者の手元に届く側です。端末に常駐する小さなトレイアプリで、本人が見るヘルスタブ、問い合わせずに自分で実行できるジョブ、確認を求められる通知が入っています。同じ端末のエージェントと名前付きパイプで話し、バックエンドへは直接つながりません。
アプリ自身のウィンドウサイズである 880×560 で、日本語のみ掲載しています。クライアントアプリには i18n の層が無く、文字列がソースに直接書かれているため、英語版の画面というものが存在しません。
利用者に見てほしい2つを、開いた直後に出します。

端末ヘルス
運用者がコンプライアンスページで見ているのと同じチェックを、反対側から見たものです。警告には運用者自身が書いた説明と対処が付くので、最初の一手が「問い合わせる」にはなりません。

通知
通知ページから送られ、誰が確認したかまで追跡されます。開くと、運用者が書いた Markdown がそのまま描画されます — 見出し、番号付きの手順、表、引用、リンク。


セルフサービス
運用者が利用者に公開したジョブを、カテゴリ別に並べます。中身はどれも普通のマニフェストで、ここに出るかどうかは運用者が決めるだけです。
![]() | ![]() |
ジョブは実行前に確認を挟めます(マニフェストの confirm: に、運用者自身の文面で)。実行中は出力が流れていくので、沈黙のあと完了だけが現れる、ということになりません。
![]() | ![]() |
カタログは同じ仕組みを、インストールに向けたものです。

自分で動かす
cargo make demo # 運用コンソール
cargo make demo-client # クライアントアプリ
あとは http://localhost:5173 を開き、任意のユーザー名とパスワードでサインインするだけです。他に何も起動しておく必要はありません。モックが何をカバーしているか、どう足すかは crates/kanade-backend/web/demo/README.md にあります。
システムアーキテクチャ
kanade は Windows・Linux・Apple Silicon macOS 端末を非同期に管理します。利用可能なインベントリ、セッション、デスクトップ機能はプラットフォームごとに異なります。
コンポーネントトポロジー
システムは 5 つの主要コンポーネントで構成されており、イベント駆動型の pub/sub 構造を介して調整されます。
graph TD
subgraph Operator Session
CLI[kanade CLI]
SPA[React SPA]
end
subgraph Server Infrastructure
Backend[kanade-backend]
NATS[NATS Broker / JetStream]
end
subgraph Managed Endpoints
Agent1[kanade-agent PC-1]
Agent2[kanade-agent PC-2]
Client[kanade-client Tauri App]
end
CLI -->|Command / Query API| Backend
SPA -->|REST / WebSockets| Backend
Backend <-->|State/PubSub| NATS
Agent1 <-->|NATS Connection| NATS
Agent2 <-->|NATS Connection| NATS
Client <-->|KLP local IPC| Agent1
1. kanade-agent
各ホストの常駐実行エンジンです。Windows サービス、Linux systemd サービス、macOS launchd デーモンとして動作します。
- 役割: コア実行エンジン。
- 通信: アウトバウンド専用の NATS 接続を確立します。インバウンドポートを開かないため、ファイアウォールに優しい設計です。
- 機能: ジョブ実行、インベントリ・性能データの報告、自己更新を行います。Windows PowerShell、PowerShell 7 (
pwsh)、shに対応し、選択したシェルは対象ホストへの導入が必要です。Windows 固有のセンサーやジョブが自動的に他の OS で動くわけではありません。
2. kanade-backend
中央の HTTP API およびプロジェクションサーバーです。
- 役割: コマンドの調整、受信テレメトリの処理、およびオペレーター用 Web インターフェースの提供。
- 状態管理: イベント、アクティビティログ、およびステータスレコードをローカルの SQLite データベースに永続化します。
- プロジェクターパターン: NATS コマンドレスポンスストリームを購読し、受信したペイロードを解析して、リアルタイムで状態テーブルに反映(投影)します。
3. NATS ブローカー (with JetStream)
フリート全体のメッセージ転送レイヤーです。
- 役割: 軽量かつ高スループットなメッセージブローカー。
- JetStream: コマンドストリーム、ジョブ登録、およびファイルストレージ(パッケージやエージェントスクリプトを配信するための NATS オブジェクトストアバケットを使用)を保持します。
- 疎結合: バックエンドとエージェントを切り離します。バックエンドがオフラインまたは再起動中であっても、エージェントは実行を継続して送信トレイにレコードをキャッシュし、接続が再開されたらそれらをプッシュします。
4. kanade-client
エンドポイント上のログインユーザーのデスクトップセッションで動作する、オプションの Tauri デスクトップアプリケーションです。
- 役割: エンドユーザーとの対話(プロンプトダイアログ、通知、ユーザー向けダッシュボードなど)を提供します。
- 通信: セキュリティで保護されたローカル IPC メカニズムを介して、ローカルの
kanade-agentと状態を共有します。
5. kanade CLI
オペレーター向けの主要なコマンドラインツールです。
- 役割: ソフトウェアアップデートのパッケージングと公開、ジョブマニフェストの送信と実行、およびコマンドラインからのライブフリートインベントリの照会。
セキュリティと信頼性の設計
アウトバウンド専用接続
エージェントは外向きの NATS 接続を開始します(WebSocket 構成も含みます)。パッケージ導入ジョブはバックエンドの HTTP API から成果物を取得することもあります。管理対象端末に受信用ネットワークリスナーは不要ですが、ローカル KLP IPC は別です。誰がコマンドを発行できるかは、ブローカーの認証・権限とコマンド署名ポリシーに依存します。
エージェントのジョブ実行ユーザー
PowerShell スクリプトは実行ごとのステージングディレクトリを使います。Windows では %ProgramData%\Kanade\agent-scripts、macOS では専用のステージングルート、それ以外の Unix では一時ディレクトリです。ジョブは run_as: system、user、system_gui を指定でき、対応範囲は OS ごとに異なります。実行ユーザーとステージングの保護であり、信頼できないスクリプトのサンドボックスではありません。本番の system ジョブは LocalSystem / root で動きます。macOS の実行ユーザー規則 を参照してください。
運用概要
kanade の day-2 運用は 2 つのフローに分かれます:
-
直接インストール — まっさらなホストにバイナリと config を置いて Windows サービスを登録します。最初の agent、最初の backend、NATS サーバーをブートストラップするときに使います。スクリプト:
scripts/deploy/agent.ps1、scripts/deploy/backend.ps1、scripts/deploy/nats.ps1。対象ホスト上で手動で実行します。 -
agent 経由のアップデート — agent がいったん動き出せば、その agent 自身が ssh / RDP なしで同じホスト上の他コンポーネントをインストール・更新できます。operator はバイナリとスクリプト本体をブローカーに publish し、ジョブを起動。agent が fetch・検証・swap・サービス再起動を行います。day-2 運用の大半はこれ。
agent 経由フローの形は、何をアップデートする場合でも同じです:
operator host ─► kanade CLI ─► backend HTTP API ─► NATS ─► agent
│ │
├── publish binary ────────────► fetches from
│ to OBJECT_APP_PACKAGES OBJECT_APP_PACKAGES
├── publish script ────────────► fetches from
│ to OBJECT_SCRIPTS OBJECT_SCRIPTS
├── register / update job ─────► reads job manifest
│ from `jobs` KV
└── exec job ──────────────────► PowerShell child
runs the script
図は Windows のインストーラジョブを示しています。Linux には bundle/setup スクリプトと複数 OS に対応するエージェントのロールアウトがあります。Linux 導入 と macOS エージェント導入 を参照してください。
コンポーネント別ガイド:
- kanade-backend — HTTP / projector バイナリ
- kanade-client — Tauri 製のエンドユーザーアプリ
- NATS サーバー — ブローカー本体 (はい、ブローカー越しにブローカーをアップデートできます)
- kanade-agent 自身 — agent の self-update 経路 (他 3 つと違い、汎用の OBJECT_APP_PACKAGES + script ペアではなく専用の rollout バケットを使います)
Enabling passkey sign-in
Use Operator Settings → Server Settings → Passkeys to configure and enable WebAuthn. This is the only supported configuration path; passkeys are disabled by default. Enter the externally trusted RP ID and HTTPS origins explicitly, save, and check the effective state. Updates apply without a restart and invalidate pending ceremonies across backend instances. See configuration reference for validation rules, credential management and multi-instance routing requirements. Existing password/TOTP login and recovery continue to work.
インストールとデプロイ
複数 OS 向けの kanade deploy 設計とスクリプト廃止の条件は SPEC §2.13 にあります。型付きスキーマ・検証と計画の永続化は実装済みですが、本番の型付き配送と deploy CLI は未提供です。移行中は以下の現行手順を使ってください。設計の対象は登録済みエージェントで、エージェント導入画面のワンライナーは変更しません。
このセクションでは、本番環境またはステージング環境で kanade コンポーネントをネイティブの Windows サービスとしてブートストラップする方法を詳しく説明します。
デプロイモデル
本ページでは、本番ホストと対象端末の kanade コンポーネントを Windows サービスとして動かし、自動起動と設定済みのサービスマネージャーによる回復を利用します。
| サービス名 | トリプル / バイナリ | 設定ソース | 典型的なターゲット |
|---|---|---|---|
| KanadeNats | nats-server.exe | トークンを埋め込んだ設定ファイル / ACL | 中央サーバー |
| KanadeBackend | kanade-backend.exe | 保護されたレジストリ / 設定ファイル | 中央サーバー |
| KanadeAgent | kanade-agent.exe | 設定ファイル / ACL で保護されたレジストリ / ローカル状態 DB | 管理対象エンドポイント |
1. 前提条件
- ホスト OS: Windows 10/11 または Windows Server 2016+。
- gsudo: 標準のユーザシェルから管理者権限でインストールを実行する(または管理者権限の PowerShell プロンプトからコマンドを実行する)ために必要です。
- ネットワークルーティング: 管理対象エンドポイントが TCP 経由で NATS サーバーポート(デフォルト
4222)に到達できる必要があります。
2. NATS サーバー (ブローカー) のセットアップ
NATS サーバーはメッセージングのコアとして機能します。
scripts/build-release.ps1 -Roles natsを使用して、デプロイメントバンドルをステージングします。- 管理者権限でサービスをデプロイします:
# 管理者権限の PowerShell プロンプト & "dist\nats\deploy-nats.ps1" -NatsToken "your-secure-nats-token" -Recreate
KanadeNats サービスを LocalSystem で登録し、JetStream データディレクトリを作成します。導入先の NATS 設定ファイルにトークンを埋め込み、アクセスを SYSTEM と Administrators に制限します。
Optional: per-role users instead of the shared token
By default the broker runs on the single shared token above. To run the three role users (agent, backend, breakglass) instead, deliberately:
# Default cost 8 requires a long random password (32 random alphanumeric characters recommended).
# Hashes only, minted with scripts/ops/nats-password-hash.ps1 (or .sh); never plaintext.
$env:KANADE_NATS_AGENT_PASSWORD_HASH = '<hash>'
$env:KANADE_NATS_BACKEND_PASSWORD_HASH = '<hash>'
$env:KANADE_NATS_BREAKGLASS_PASSWORD_HASH = '<hash>'
& "dist\nats\deploy-nats.ps1" -UseNatsUsers # switch
& "dist\nats\deploy-nats.ps1" -UseNatsToken -NatsToken "your-secure-nats-token" # revert
-UseNatsUsers replaces the authorization block of the installed config with an include of nats-server.users.conf (the template with the hashes substituted) and gives both files the SYSTEM + Administrators ACL; -UseNatsToken restores the shipped token block (hand edits inside it are not restored) and removes the users file. The service is stopped and started by the script as always (-NoStart defers the start). On Linux the equivalent is KANADE_NATS_AUTH_MODE=users|token for setup.sh, recorded so re-runs keep it, with a manual systemctl restart nats-server to apply it (see deploy/linux/README.md).
For the recommended bcrypt cost 8 and broker burst measurements, see Choosing the bcrypt cost.
The switch is atomic: a config cannot hold both a token and users, and a client presenting a token is rejected once users exist. Every agent, backend and CLI host must already hold a user pair before the broker flips; follow the separately documented readiness procedure first.
Expected authentication mode and connection findings
The backend watches how every connection to the broker authenticated and raises a warning when that is not what you intended, so that a switch to per-role NATS users that failed or silently reverted, or a broker that authenticates nobody, does not go unnoticed. The broker's own report is the source (its monitoring endpoint, polled every minute), not anything an agent says about itself.
Setting. Settings → Server → Expected NATS authentication (the nats_auth_mode server setting) is either token (the default, today's shared token) or users (per-role users). It is an expectation only: it changes nothing about how any process connects, it just defines what counts as unexpected. Set it to users when you switch the broker to the users block, and back to token if you switch back.
Findings. Each connection is judged by the mode you expect, the role it announces in its connection name (kanade-<role>[/identity]) and the user the broker reports it authenticated as:
| finding | when | severity |
|---|---|---|
broker_open | positive broker evidence of access without an authenticated identity (no-auth), in either mode | critical |
token_reverted | users expected, but the connection used the shared token | critical |
role_user_mismatch | users expected, but the user is not the announced role's (agent, backend, breakglass for the CLI), e.g. the backend user on an agent connection | warning |
credential_unnameable | users expected, but the credential could not be named | info |
Under token, the shared token is expected and only broker_open is reported. The announced role is chosen by the client, so a mismatch is evidence of a misconfigured or misused host, while a match proves nothing: it is only the connection's claim, compared against the broker's word.
Findings are grouped by kind and announced role, so a whole fleet reverting at once is a handful of entries, each with a connection count and at most five registered host names. A finding is raised when it first appears, shows as a banner on the Dashboard, and is marked resolved when it is gone (a later recurrence is raised again). While the backend's own broker connection cannot prove the mode, user names read as unknown, so expect credential_unnameable entries until it reconnects.
Acceptance evidence and uncertainty. A TCP connection is already visible in /connz?auth=1 after INFO, before CONNECT or successful authentication. A server-issued cid, an empty/missing authorized_user, a client name, language, version, RTT, or elapsed time alone does not prove access without authentication. The projector brackets its paged connz walk with /varz, checking server id, startup/configuration timestamps and response/page metadata. A restart, reload, identity change, malformed/missing response or timeout invalidates the poll. Pages are sorted by ascending CID and overlap at the preceding boundary CID. New connections append and do not by themselves prevent resolution; a missing boundary, duplicate/reordered CID or incomplete walk holds resolutions, while usable positive observations can still raise findings. The cumulative total_connections counter is not a completeness condition. Offset pagination is not an atomic snapshot: the boundary checks detect skipped prefixes, not every possible race or a change immediately after the final response.
With no reported identity on TCP, application message traffic (in/out messages) or a live subscription proves the client was allowed to use the protocol. Positive traffic must also be consistent with broker policy: explicit auth_required: true plus a missing identity stays unproven. Counters can predate a second CONNECT, whose options are overwritten before re-authentication. All three counters and the client kind/transport must be present; missing is not zero. An explicit TCP auth_required: false also proves that listener is open. The normally omitted false field is conservatively unknown, not inferred false: a silent open connection can remain unproven until application activity is seen. The backend normally has subscriptions, so an active open broker remains visible without waiting for a grace period. An idle authentication-required TCP connection within the broker's own auth_timeout is auth-pending; after that budget, or without enough monitoring evidence, it is auth-unproven. Expiry never proves acceptance. These are different from unknown, which still means a reported credential cannot safely be named and retains credential_unnameable handling. Pending/unproven connections do not replace an agent's last observed credential.
TCP auth policy and timeouts are never applied to WebSocket connections. WS can have separate authorization, credentials from cookies, or no_auth_user. The current monitoring fields do not expose its effective authorization policy. Without a reported identity, even positive traffic remains auth-unproven with reason listener_auth_unproven: counters may predate a second CONNECT whose replacement credentials will be rejected. This also limits detection of truly open WS listeners; TCP acceptance evidence remains available. A reported identity takes precedence over activity. Cookie/token auth retains redaction. WS user values stay unknown because a live TCP user login cannot prove that another listener's value is a username rather than a secret. no_auth_user assigns a broker identity, so this audit cannot distinguish that fallback from a credentialed login as the same user: it is not proof of a fully open broker. WS authentication without an identity remains unproven. MQTT/leaf/unknown transports without a reported identity are also unproven. This audit trusts the configured monitoring endpoint to be the broker and to honor auth=1; it does not test listener reachability or actively probe production with empty credentials.
Any pending/unproven observation holds existing finding resolutions; it does not block a new finding proven by another connection. Health reports authentication_uncertain, with pending_connections and unproven_connections counts (including partial-poll observations for incomplete). The optional uncertainty_reasons map breaks those observations down using fixed, secret-free EvidenceReason codes: pre_connect_pending, incomplete_monitoring, listener_auth_unproven, invalid_connection_start, auth_policy_conflict, and acceptance_unproven. Codes describe evidence limitations, not a proven cause. The notice ledger's hold_resolve_kinds policy preserves existing notices while allowing positive findings from other connections, including new critical alerts. Counts and reason maps are null when unavailable or stale. The aggregate metadata uses a JSON envelope in the existing audit-state TEXT field; legacy plain statuses remain readable. Connection evidence uses the existing retention ledger described below; Observed.connection retains broker identifiers and timestamps alongside the classified label. auth-pending/auth-unproven never contribute finding evidence. External consumers should use the health API rather than interpret that internal field.
The unnamed critical observed on 2026-10-18 from 02:24:58.636897559 UTC to 02:25:58.230333505 UTC after an OOM-triggered broker restart is a likely false positive. The pre-CONNECT window is reproducible on authentication-required NATS 2.14.3, but retained historical connection evidence cannot establish that this was the exact cause of that incident.
The evidence rules follow NATS 2.14.3's monitoring implementation and monitoring documentation. Its protocol parser gates application operations while awaiting authentication; its CONNECT handler sets metadata before checking authentication, and authentication implementation handles listener overrides and fallback identities.
Regression checks use fixtures, local HTTP mocks and disposable brokers only:
cargo test --locked -p kanade-backend nats_auth
cargo test --locked -p kanade-backend nats_conns
cargo test --locked -p kanade-backend live_connz -- --ignored
cargo make check
The live tests need nats-server on PATH and permission to bind loopback sockets. They exercise INFO-before-CONNECT, rejected credentialless CONNECT, anonymous authenticated token/user connections, reconnects, an open broker, WS token overrides and WS no_auth_user. Run against the supported broker version when upgrading; fixtures do not substitute for checking changed semantics.
Grace after a switch. When you change the expected mode, new findings are held back for 5 minutes. Switching re-authenticates every client, and each reconnects with backoff while the poll only looks once a minute, so for a few polls the broker's view is a mix of old and new; the window keeps those stragglers from being reported against the mode you just chose. Re-saving the same mode does not start it again, and findings already open still update and resolve during it. The Dashboard says when the window is open.
Reading it from outside. GET /api/health/fleet carries a nats_auth block: expected_mode, grace_until, poll_status, open_total (the connections covered) and findings[] (kind, subject, severity, count, sample_hosts, first_seen_at, occurrence_id). It does not change the response's status or HTTP code, so an existing monitor keeps behaving as before; a monitor that should alert on this must read nats_auth.findings. A poll_status other than ok means the audit could not judge the whole broker (authentication_uncertain, incomplete, endpoint_unreadable, settings_unreadable, state_unreadable, stale, or pending before its first poll), and an empty list is then not a clean result.
What is never shown. The reported value of a connection may be a secret on some broker builds, so findings carry fixed vocabularies (kind, severity, the role bucket agent / backend / cli / unnamed / other), counts, registered host samples and an occurrence reference. Admin-only connection evidence adds broker-issued identifiers and parsed timestamps, as described below. Neither the credential, nor the reported user name, nor the raw connection name is copied into notice evidence.
Retained NATS authentication evidence
Each new occurrence has its own numeric occurrence_id in the authenticated fleet health finding. The aggregate backend_notices row remains compatible; reopening it does not overwrite earlier occurrences. Dashboard's admin-only NATS authentication evidence and resolved history details and GET /api/notices/nats-auth expose the latest 100 occurrences, including resolved ones. Pass ?before=<oldest-id> to page backwards. Viewers and operators cannot read this endpoint. Existing service-token and auth-disabled administrator semantics still apply. Identifiers are selectable and copyable for log searches.
A host claim is saved only for an agent role whose exact pc_id is registered; registration does not authenticate the claim. Stored host text removes control characters and is limited to 64 Unicode characters. Other sample text is bounded by typed timestamps, fixed role/credential vocabularies, decimal u64 cids and ASCII alphanumeric server IDs of at most 64 bytes. Invalid identifiers are rejected rather than truncated. Older samples have no host field; it is not backfilled. The Dashboard separates broker identifiers and credential classes from untrusted client role/host claims.
A sample records the broker-issued decimal cid, server_id and broker startup timestamp (/varz.start), backend first/last observation times (page fetch completion, before settings/database work), broker page observation time, and connection start/last activity timestamps when supplied. Occurrence timestamps describe notice processing; individual sample timestamps describe page acquisition. A cid alone, or server_id alone, must not be treated as a restart identity. The collector reads /varz before and after the paginated /connz walk and checks each page's server_id, timestamp and duplicate cids, within the existing 20-second timeout. Missing identity or an inconsistent/restarted broker rejects the snapshot, reports an unreadable poll and leaves open findings unresolved. A paging cap reports an incomplete poll and likewise cannot resolve findings. This is a best-effort walk of live connections, not an atomic broker snapshot.
Evidence includes only a fixed credential class (user, shared-token, no-auth, unknown), a fixed claimed_role bucket and an optional bounded registered host claim. Role and host are untrusted client claims, unlike broker-issued connection identifiers. Aggregate notifications also retain registered host samples. Raw authorized_user, tokens, passwords, connection names, arbitrary client metadata and unrestricted monitoring responses are never copied into connection evidence. Peer addresses are deliberately omitted: proxies and loopback commonly identify an intermediary rather than the originating client. The admin boundary limits exposure of retained connection correlation data.
Per occurrence, at most the first 10 sampled identities and 10 most recently observed other identities are retained, deduplicated by server_id/start/cid, within a 32 KiB JSON limit. Each sample and the latest occurrence observation record whether their poll was complete; partial polls may undercount connections. Broker IDs are limited to 64 alphanumeric bytes; other context is parsed timestamps or fixed vocabulary. sampled_out indicates sample/size omissions. Evidence updates on each successful poll even if group counts/host samples have not changed. Ledger changes, occurrence creation, resolution and evidence updates commit in one SQLite transaction.
Samples expire 30 days after their last observation, including samples in open findings. Resolved occurrences expire 30 days after resolution and are also capped at the newest 1000. Cleanup runs when the projector starts and every poll (including failed polls); an offline backend performs cleanup when restarted. There are only the classifier's fixed kind/role buckets of open occurrences. SQLite backups must use the operator's corresponding retention/access policy; logical expiry does not securely erase old database pages or backups.
Old notices have no recoverable connection evidence; the UI labels absent or expired evidence accordingly. The identifiers lost in the 2026-10-18 incident cannot be reconstructed by this migration. Last observed is not a disconnect time. Connections that open and close between minute polls can be missed, and wiping the projection database loses these snapshots permanently. Retained evidence uses the same authentication classification as aggregate findings through Observed and the shared evaluate_observed adapter. Pending and unproven connections do not contribute finding samples or resolve existing occurrences. The additive evidence migration is named 20261018000000_nats_auth_evidence.sql.
3. バックエンド API & SPA のデプロイ
バックエンドは、オペレーター接続を管理し、イベントログを処理します。
scripts/build-release.ps1 -Roles backendを使用して、バックエンドバイナリと React SPA バンドルをステージングします。- サービスをデプロイします:
# 管理者権限の PowerShell プロンプト & "dist\backend\deploy-backend.ps1" ` -NatsToken "your-secure-nats-token" ` -StaticToken "your-operator-spa-bearer-token" ` -ForceConfig -Recreate
-NatsToken: バックエンドをローカルの NATS サーバーに安全に接続します。-StaticToken: オペレーターの CLI/SPA ログインに必要な API ベアラートークンを定義します。
デプロイスクリプトは、KanadeBackend Windows サービスを登録し、適切な ACL を設定して、エンドポイントを検証します。
4. 対象エンドポイントへのエージェントのインストール
管理対象のすべてのエンドポイント PC にエージェントをインストールします。
scripts/build-release.ps1 -Roles agentを使用して、エージェントバンドルをステージングします。dist/agentフォルダの内容を対象 PC にコピーします。- 対象 PC 上で、インストーラーを実行します:
# 管理者権限の PowerShell プロンプト & ".\deploy-agent.ps1" -NatsToken "your-secure-nats-token" -ForceConfig -Recreate
スクリプトの動作:
kanade-agent.exeをインストール先ディレクトリに配置します。- Windows レジストリパス (
HKLM:\SOFTWARE\Kanade\agent) 内の設定と NATS トークンを保護します。 - KanadeAgent サービスを登録して起動します。
Agent-role NATS user in generated installers
deploy-agent.ps1 also accepts -NatsUser / -NatsPassword (the shell scripts take KANADE_NATS_USER / KANADE_NATS_PASSWORD), both or neither. The installers the backend generates (Windows ZIP, Linux / macOS tarball) embed such a pair when the server settings' agent_install section holds both a user and a password, next to the token, so machines installed from now on already carry the credential the broker may later require.
- The pair is the agent role's credential and is shared by all agents by design. The backend's own credential and the break-glass credential must never be entered in these settings.
- It is write-only, like the token: the API returns only
nats_user_set/nats_password_set, and a settings update that omits both keeps the stored pair. A settings update that sets only one of the two is rejected, so replacing the password means sending the user again. - A generated
README.txtstates whether a user pair is included, without revealing it; with no paragraph about it, none was embedded and the installer is exactly what it was before this setting existed.
サービスが起動すると、エージェントはアウトバウンド NATS 接続を確立し、コマンドストリームを購読し、オンラインのハートビートをフリートバックエンドに報告します。
Switching the broker to role-level users
This is the operating procedure for moving the NATS broker from the single shared token to the three role users (agent, backend, breakglass), with the revert, and for checking readiness before and fallout after.
Nothing here is run by any automation. No installer, scheduled job, backend task or agent performs this procedure or any step of it. The broker is switched only by a person running the deployment script on the broker host, and the checks below are run by that person. The expected-mode setting in the backend only changes what is reported as unexpected; it changes how no process connects.
Why it needs a procedure
A broker configuration cannot hold both a token and users. The moment it is reloaded with users, a client that presents only the token is refused. A host that is not ready is therefore locked out at that instant, and because a locked-out host also disappears from the broker's connection list and stops heartbeating, it looks exactly like a powered-off one. Two consequences:
- readiness has to be established beforehand, from outside the broker;
- the damage has to be measured afterwards by comparison with what was alive before.
Both are done with scripts/ops/nats-switch-check.ps1, which talks only to the backend HTTP API with an API token. It never connects to the broker and never prints a credential.
Choosing the bcrypt cost
Use cost 8 with a long random password, preferably 32 randomly generated alphanumeric characters, for each role. The hash helpers default to 8 and still accept an explicit cost. A higher cost adds no practical protection against guessing a 32-character random password, but consumes broker CPU on every authentication and can turn a reconnect storm into minutes of downtime. This recommendation depends on randomness: a memorable or reused password is not a substitute. Below cost 10, the helpers warn for fewer than 24 characters, letters only, digits only, or a case-insensitive run of password, qwerty, letmein, welcome, admin, or kanade. This heuristic does not prove randomness; no warning is not a strength guarantee. Warnings do not refuse the input, and the nats CLI's existing minimum-length refusal remains in force.
These measurements came from crates/kanade-shared/tests/nats_auth_burst.rs against a real nats-server 2.14.3, using the role-level users configuration and the real kanade_shared::nats_client connect path. The host had an AMD EPYC 7551 shared vCPU allocation, 2 vCPU and approximately 1 GB RAM. The burst had N = 50 clients connecting simultaneously, at broker startup and again after broker restart. Absolute times belong to that machine; re-measure on the real production broker host with the fleet's load.
| bcrypt cost | One verification, one thread | 50-client startup / restart burst |
|---|---|---|
| 8 | ~25 ms | All 50 authenticated; median 4–5 s, maximum 7.5 s, with authorization timeout 10 s and 30 s |
| 9 | ~95 ms | All 50 authenticated, but median 66–88 s with authorization timeout 30 s; with the shipped 2 s, median 60–78 s and approximately 500–600 Authentication Timeout answers |
| 10 | ~190 ms | Practically none authenticated within 90–120 s (0–2 of 50), with the shipped 2 s and with 10 s and 30 s |
| 11 | ~375 ms | None or almost none authenticated (0–1 of 50), with the shipped 2 s |
| 12 | ~720 ms | Burst not measured |
A user-credential connect makes the broker perform two bcrypt verifications: the client's credential probe and the real connection. Retries repeat that work. authorization { timeout } is accepted in both token and users configurations; the default 2 s was verified to be enforced. Raising it did not rescue cost 9/10, so the limit is not only the broker's authorization timeout. Client-side probe/connect timeouts are a suspected amplifier, still requiring separate investigation. The cost 8 results above are not a guarantee for the shipped 2 s timeout or for 200 clients.
The probe logs state changes using fixed codes: nats_probe_accepted, nats_probe_rejected (broker authorization violation only), and nats_probe_inconclusive (including TLS, proxy, timeout and reachability failures). Inconclusive attempts do not count as credential refusals. These diagnostics contain no destination or broker error text, and acceptance alone does not establish a WebSocket connection's authenticated username.
A collapse looks like Authentication Timeout in both client and broker logs, clients repeatedly retrying, and heartbeats absent for minutes after a broker restart. Do not interpret that as a successful switch merely because the broker process is running.
To measure on the real broker host, make nats-server available in PATH and run the same ignored test in release mode:
KANADE_AUTH_BURST_N=200 KANADE_AUTH_BURST_COSTS=8,9,10 cargo test -p kanade-shared --release --test nats_auth_burst -- --ignored --nocapture
Compare startup and restart results with the fleet's reconnect timeouts and recovery deadlines before switching production.
Prerequisites
- Client versions. User credentials arrived in 0.61.0 (the release whose client library presents a configured user and falls back to the token). Agents, the backend and the break-glass CLI all need at least that. The script's
-MinAgentVersiondefaults to0.61.0. The shipped users configuration additionally assumes two later fixes: a connection-liveness probe that does not publish to_INBOX, and an agent that never overwrites object-store objects (so it needs no stream purge right). They are not in tag0.62.1; use the first release that contains them and pass it as-MinAgentVersion. With an older agent behind the current users file, a host can connect but then hit permission violations. - Credentials are distributed. Every agent holds the agent role's user pair, delivered by the credential distribution jobs (or by the generated installer carrying the pair). The check job that reports whether the pair is present must have run on every host.
- The check job is not part of this repository, so the script has no default for
-CheckName. The contract it expects: the check reports only whether both user and password are present (never a value), registers fleet-wide, and reportsokonly when both are. If the name is wrong or the check is not fleet-wide, every host simply showsno-check-result. Readinessmust list nothing (step 1 below).
- The check job is not part of this repository, so the script has no default for
- Backend and break-glass hosts are provisioned by their own deployment scripts (
deploy-backend.ps1/ the backend setup script with-NatsUser/-NatsPassword; the break-glass credential by hand on the operator machines). These are not distributed to agents and are not covered by the script: use the manual checklist below. - A tested way to reach the broker host that does not depend on the broker, the backend or the fleet: console, RDP/SSH from a management network, whatever you have. Test it before; the revert needs it.
- The old configuration is kept. Know where the token and the previous installed
nats-server.confare. The deployment script's revert restores the shipped token block only; hand edits made inside that block are not restored. - The broker service restarts itself (Windows service recovery,
Restart=on-failureon Linux), and so do the agents (below). - An API token for the backend, in
KANADE_API_TOKEN(or-Token), and the backend URL inKANADE_BACKEND_URL(or-BackendUrl). Prefer anhttps://URL: the token travels in the request header. - The deployment switch is available in the release you deploy from. The switch and the revert are made by an opt-in mode of the broker deployment scripts (Windows and Linux paths), which is separate work from this page. Before relying on this procedure, confirm in that release's deployment documentation and scripts that a users mode and a way back to the token both exist, record the release or artifact you will run them from, and read their exact usage. If either is missing, stop: there is no supported switch or emergency revert to follow.
Manual checklist: backend and break-glass
Tick every line before the switch; the script cannot see these.
- The backend host holds the backend user pair and runs a 0.61.0+ backend (check the version it reports and its log for a user connection).
- The backend's own credential is not the agent pair and is not in the installer settings.
- The break-glass CLI on each operator machine is 0.61.0+, holds the break-glass pair, and has been exercised once against a broker running the users configuration (a rehearsal broker is fine).
- You know which of these hosts is also an agent host. If the backend host runs an agent, a backend lock-out also shows as that agent vanishing.
The order
All commands are run from a checkout of the repository on a machine that can reach the backend. Use pwsh (PowerShell 7) where you can: it lets the script take the backend's own clock from the response Date header. On Windows PowerShell 5.1 it falls back to the local clock and says so; keep the clock correct.
1. Readiness
./scripts/ops/nats-switch-check.ps1 -Mode Readiness -CheckName <credential-check> `
-MinAgentVersion 0.61.0 # or the first release with the two later fixes
It lists every registered agent that is not ready, with the reason, and exits 1 if there is any. A host is ready only if all hold:
| reason | meaning |
|---|---|
agent-version-too-old(..) / agent-version-unknown | the agent is older than the minimum, or reports no parseable version |
no-recent-heartbeat | not online now and not seen within -RecentWithinHours (default 24) |
no-check-result | the check job has never reported for this host |
check-not-ok(<status>) | the check reported something other than ok |
check-stale | the check's last result is older than the backend's staleness window |
check-older-than-CheckedSince | with -CheckedSince <UTC date>, an ok from before the distribution does not count |
Continue only when it prints "every registered agent is ready". Exit code 2 means the backend could not be read and nothing was determined.
What it cannot know: an ok is the agent's own report that a pair is present, not proof that the values are correct or that the broker will accept them; hosts that never registered are invisible; the backend and break-glass are not covered.
The backend API has no per-host "online" field, so the script uses last_heartbeat against the backend's own two-minute alive threshold, and joins /api/agents with /api/checks by pc_id.
2. Snapshot
./scripts/ops/nats-switch-check.ps1 -Mode Snapshot -SnapshotPath before.json
Records the hosts alive now (hostname, agent version, last heartbeat, authenticated NATS user as the backend reports it). Hosts already offline are deliberately left out so they are never counted as lock-outs. It will not overwrite an existing file without -Force.
3. Switch
On the broker host, with the broker deployment's opt-in users mode (prerequisite 8). Use exactly the options its own documentation gives for your release; this page does not repeat them, because they belong to the deployment scripts and can differ between releases. Applying the mode must reload or restart the broker; note whether your path does that itself or leaves it to you.
Write down the UTC time at which the broker applied the new configuration; Compare needs it as -SwitchedAt. Then set Settings → Server → Expected NATS authentication to users so the backend reports anything unexpected. Its findings are held back for five minutes after that change, which does not affect the script.
4. Compare, after the fleet has had time to reconnect
./scripts/ops/nats-switch-check.ps1 -Mode Compare -SnapshotPath before.json `
-SwitchedAt 2026-01-01T09:00:00Z -WaitSeconds <see below> -MaxDisappeared 0
A locked-out host still looks alive for up to two minutes after its last heartbeat, so the script refuses to judge sooner than that plus one heartbeat interval (-HeartbeatSeconds, default 60; set it to your fleet's configured interval) and exits 3 "too early". -WaitSeconds makes it wait before reading. Run it again after waiting rather than reading a partial answer.
How long to wait is the larger of two numbers, both counted from the switch time you wrote down:
- the script's own floor: 120 s plus the fleet's heartbeat interval; and
- four times the worst reconnect time measured for your clients (below), plus the fleet's heartbeat interval.
The second term used to be a guess. An agent that has lost its connection does not heartbeat again until it has reconnected, and on a reconnect the client's credential selection first probes the broker with each credential it holds and then connects for real, so a reconnect is several round trips with their own timeouts and the client's reconnect backoff in between, not one. On a slow or busy machine that can add up to tens of seconds. Comparing sooner than that reads agents that are still reconnecting as disappeared.
How the reconnect time was measured
The conformance suite (nats_role_conformance, run by the Integration workflow on Ubuntu, Windows and macOS) times it on every run. It restarts the broker, or on Linux and macOS reloads it from the token to the users block with every live connection cut through a proxy, under a running real backend and agent, and counts from the instant before the restart or reload until each of these has worked again, all measured side by side from that same instant:
- the agent's next heartbeat, seen by an observer connected straight to the broker;
- the backend's ping of the agent returning 200;
- a break-glass
kanade runcompleting; - a fresh call made with the agent role and with the backend role through the real
connecthelper (so the helper's probe is inside the number).
Conditions of that measurement, which are not your fleet's: a loopback broker on a hosted CI runner, three test processes running in parallel on the machine, the agent heartbeating every second (so the heartbeat adds about one second, not your interval), and the broker version the workflow pins (NATS_SERVER_VERSION). A real fleet has network latency, a busy broker, many clients reconnecting at once and a longer heartbeat interval; those make it slower, not faster. The CI figure is therefore a lower bound on what to expect and not a recovery guarantee. The right number for your fleet comes from rehearsing on a few hosts: note when each host's first heartbeat arrives after a switch of a test broker or one site, and take the worst.
The distribution per operating system (count, minimum, median, 95th percentile, maximum, and how many waits hit their bound) is written to the Integration workflow's step summary, and a manual run of the workflow can repeat the suite (conformance_repeat) to collect more samples. Read the reconnect rows and use the worst one on your clients' operating system as the figure above. If it is tens of seconds even on a loopback runner, plan the wait in minutes, not in the two or three the old example implied.
It prints:
- Disappeared: alive in the snapshot, not alive now. These are the lock-out candidates.
- Heartbeated after the switch and alive now: indirect evidence of reconnection.
- New hosts: alive now and not in the snapshot.
- Live hosts by authenticated NATS user. Expected: every agent as
agent. Unexpected:shared-token(still on the old token),no-auth(the broker authenticated nobody),unknown, another role's user, or absent (never correlated, which is unknown and not "old credential"). Values last changed before the switch are noted, because the backend keeps the last value it saw.
The exit code is 1 when more hosts disappeared than -MaxDisappeared. If no host from the snapshot is alive it says the backend itself is probably locked out; revert first and look at the backend host.
If the backend cannot be reached it retries (-Retries, -RetryDelaySeconds) telling you so, because it may be reconnecting to the broker. If it still fails it exits 2 saying plainly that this is not an empty result.
5. Decide
- Disappeared count within what you accepted, and the user table shows only
agent: keep the switch and go to Afterwards. - A handful disappeared: decide per host with the next section while the rest of the fleet runs; reverting for a few hosts is usually wrong.
- Many disappeared, a non-
agentuser on live hosts, or the backend looks locked out: revert (below), re-runComparewith the same snapshot to confirm the fleet is back, and find out why before trying again.
Revert
On the broker host (through the way you tested in the prerequisites): use the same deployment path's token mode to restore the token configuration, then reload or restart the broker. Know the exact revert command before the switch (prerequisite 8) and keep it where you can reach it without the fleet. Hand edits made inside the shipped token block are not restored by it.
Set the expected authentication mode back to token. Confirm client recovery and service-manager restart settings as described in the next section. Confirm with:
./scripts/ops/nats-switch-check.ps1 -Mode Compare -SnapshotPath before.json `
-SwitchedAt <time of the revert, UTC> -WaitSeconds <as in step 4> -MaxDisappeared 0
Recovery deadlines and the production switch gate
Do not switch production until the release containing the recovery watchdog has passed a manual Integration dispatch with conformance_repeat=20 and zero failures on Ubuntu, Windows and macOS. The previous release's promises were not sufficient: a process could stay alive without heartbeats. The injected-fault tests and the repeated conformance results must both pass.
The client recovery targets, counted from when the broker becomes reachable and accepts the newly provisioned credential, are:
- resume communication within 30 s (
RESUME_BOUND); or - exit non-zero within 195 s (
EXIT_BOUND) so supervision can restart it.
These recovery bounds assume the broker can authenticate the fleet's reconnects within the clients' own timeouts. A high bcrypt cost can break that assumption; see Choosing the bcrypt cost.
These timers are defined in crates/kanade-shared/src/nats_client.rs and all derive from the protocol PING interval, set explicitly to 60 s (async-nats' default). A reconnect attempt allows the 4 s backoff, 3 s probe plus 1 s guard, and 5 s handshake; 30 s allows two attempts plus slack. An inconclusive probe skips the attempt instead of guessing from the previous broker mode.
The watchdog observes each connection's own receive progress. Idle clients send a protocol PING every 60 s and the broker's PONG is the progress, so liveness costs no traffic beyond the library's default and needs no subject permission or application message. A flush alone proves only a local write. Every 5 s the watchdog runs a purely local check (counters and a queued flush); it makes no network connection while receive progress is recent. Only after 180 s (three ping intervals, two full intervals of margin) without receive progress does it open a fresh credential witness. If the witness connects or is explicitly refused while the original connection still has no progress, the process logs the failure and exits. The exit budget adds the 5 s check interval, 5 s flush timeout and 5 s witness timeout to the 180 s stall threshold: 195 s, inside the 5-minute target. Supervision starts immediately after client creation, before subscriptions or resource bootstrap can block; fatal failure bypasses application shutdown so it cannot extend this deadline.
After a broker outage the watchdog first lets a client that is still in its reconnect backoff try again. A witness that cannot reach the broker never causes an exit and is repeated at most every 30 s; the first witness that reaches it again gives the client a further 30 s to resume, and any received progress clears the outage state, so a later genuine stall is judged against the normal 180 s threshold. The expected wait for a client that is merely reconnecting is therefore its reconnect backoff (up to 4 s) plus the handshake, well inside the 30 s resume bound; a silently stranded client costs up to 195 s before its restart.
A broker that is unavailable, or whose mode cannot be determined by the probe, is waited for indefinitely. The deadlines assume the client can reach and authenticate to the broker; they are not a network outage deadline. Repeated actual credential refusals still fail visibly. A single refusal is retried by the pinned connection library and does not trigger an immediate exit. Restart coverage applies on all three operating systems; signal-based reload coverage is provided by conformance on Linux and macOS only.
Service-manager delay is additional: Windows recovery actions wait 5 s, then 15 s, then up to 60 s; systemd uses RestartSec=5; launchd uses ThrottleInterval=10. Thus the slowest configured restart after a watchdog exit is 255 s from broker availability on Windows, 200 s on systemd, and 205 s on launchd, before application startup and the next heartbeat. Start-rate limits or disabled recovery can prevent a restart; check them before the switch. The CLI is not a service: its caller must rerun it after non-zero exit.
Expected logs
During a restart, expect event: disconnected, IO errors and possibly expected INFO, got nothing. A refused user probe during token mode is expected. NATS credential selected names the selected shape (user or token) without exposing credentials. An inconclusive probe logs NATS credential probe inconclusive; deferring this attempt at debug level.
On recovery, expect event: connected and resumed heartbeats. If the original client stalls while a witness reaches the broker, expect NATS client made no receive progress while a fresh credential witness reached the broker; exiting for a supervised restart, followed by a non-zero process exit and the service manager's restart. Persistent wrong credentials log the NATS broker keeps refusing this role's credential; a terminated task logs NATS connection task has terminated. A live, silent process after the deadline is a defect requiring investigation, not an expected switch state.
Credential badges on WebSocket connections
The Agents table distinguishes a named identity from unknown (the credential name is unproven), auth-pending (observed before authentication acceptance within the broker deadline), and auth-unproven (acceptance itself cannot be established). None of these uncertainty states is an authentication failure, and none changes command-signing status. The acceptance sentinels must never appear as green named-user badges.
A successful user/password handshake through the actual WSS reverse-proxy URL establishes acceptance of that probe. It does not prove another connection's identity or the complete listener policy. WebSocket token, no_auth_user and cookie overrides are independent of the backend's TCP connection. The badge therefore remains unproven when listener-specific identity evidence is absent; do not reinstall an agent, rotate credentials or change broker settings just to change that badge.
Even validating the effective configuration and matching its digest is insufficient to treat arbitrary authorized_user values as authenticated identities. On the tested broker, a users-authenticated WebSocket client can also supply an ignored nkey CONNECT field. /connz reports that field in preference to the username actually checked, including another configured username (see the upstream getRawAuthUser and user/password validation). The real-broker WSS regression test authenticates as one user while reporting another, then checks that SQLite, credential health and evidence history retain only the safe unknown classification. Negative handshakes are checked for broker authorization errors through the same TLS proxy; TLS verification uses a disposable trusted certificate and is never disabled.
The WSS override regression also exercises anonymous no_auth_user, the broker's user_cookie/pass_cookie and token_cookie paths, and broker rejection of missing or incorrect cookies. The WSS lifecycle regression changes a password with a real broker reload, rejects the old password, checks the replacement connection id, and restarts the broker behind the same proxy. Old broker identities and expired credential-health observations remain unusable as identity evidence. These cases run in the existing integration CI job alongside the other live_connz_ tests.
broker が生成する identity proof(v2)
WSS 接続の名前には broker が認証に成功した結果を使う。CONNECT の nkey/name、旧 authorized_user、期待する認証モード、名前の allowlist、 probe の成否を認証結果の代用にはしない。producer は tools/nats-identity/producer.patch と auth_identity.go にあり、 build.py の SHA-256 で固定した公式 nats-server 2.14.3 のソースに適用する。 公式 signed tag v2.14.3 の commit は 9b17a586be69c9ff36e4c84a421ca47da410b561、tag archive の SHA-256 は dba5286035ce9017b897ea24a783551dc28b07ad50c78da5471ead2bcfab3e86。 tag と commit の archive 内の全ファイル内容が一致することも確認した。 2.14.1 用 patch は fuzz・offset なしで適用でき、producer 本体や契約は変更しない。 クライアントの wire protocol、認証判断、権限、JetStream、Caddy は変更しない。
v2 は認証結果と一緒に取得する情報の重複を除いた契約である。v1 の 接続ごとの server id/start、cid/start/transport のコピーを廃止し、 既存の監視応答の外側で共有する。情報の結び付けは次のとおり。
| 場所 | 結び付けと検証 |
|---|---|
| /varz | server_id、start、auth_identity_version=2、auth_identity_generation。同じ epoch が監視 walk の前後で一致すること |
| /connz の共通部分 | server_id と auth_identity_server_start が /varz の id/start に一致すること。時刻・ページ境界も既存の検査を通す |
| 各 connections 要素 | broker 発行の cid、start、type。認証結果と同じ既存の接続ロック内でコピーし、cid が非ゼロ、start が broker 開始以降・現在以前、type が nats/websocket であること |
| 各要素の auth_identity | version=2、generation、sequence、state、mechanism、source、任意の public_user。accepted の generation は /varz と一致し、sequence は非ゼロであること |
public_user は認証で検証されたサーバー側の username のみである。 構成内の全 secret との平文・bcrypt 衝突検査を通し、ASCII の英数字と ._- のみ、最大64文字、予約ラベル以外に制限する。User オブジェクト、 パスワード、token、JWT、鍵、CONNECT の任意の主張、peer address は この metadata に含めない。cookie 経由でも認証結果を使い、source=cookie で区別する。token は shared-token、anonymous/no_auth_user は no-auth、 NKey/JWT/TLS mapping/delegated/custom は auth-accepted-unnameable とし、 pending/validated、rejected、stale を名前に変換しない。
設定の検査は設定構築時だけ行う。今回の最適化は、同じ設定内の同一 secret を重複除去し、各bcryptハッシュを一度解析し、平文衝突を先に除外する。 ハッシュ比較の結果や secret をグローバルにキャッシュしない。 認証時には小さな結果を保存し、監視時には既存の接続ロックで値をコピーする。 固定のstate/mechanism/sourceは1 byteの型付き列挙値で保持し、監視時だけ 従来どおりの文字列に展開する。no_auth_userのstickyな由来も同じ状態に保持し、 CONNECTの再処理やreloadで消さない。公開するv2契約や認証判断は変更しない。 v2 は ConnInfo に値を直接保持するため、監視時の接続ごとの別ヒープ 割り当てを減らせる。PUB/SUB の通常配送経路には処理を追加しない。 設定・認証・監視が無費用になるわけではない。
観測時刻と broker 時計との差は60秒以内に制限する。名前と90秒の期限は 同じ選択済み接続に由来し、失効処理とともに同じトランザクションで保存する。 期限はconnection.observed_atから計算し、書込ロック取得後にも再判定する。 監査やDB保存が遅れても、保存時刻から新たに90秒へ延命しない。 Agents API は読取時にも期限を検査し、期限切れなら名前をunknownへ置換して nats_user_sinceにもその失効時刻を返す。poll 失敗時には名前を失効させる。 認証待ちの新しい cid が併存しても、選択した認証済み接続の期限が欠けない。 nats_authのpoll_statusとpending/unproven件数は、poll記録そのものの鮮度で 判断する。単一agentの期限切れで、別の新しいpollの分類や件数を消さない。
配布・更新・rollback
これは上流 NATS に含まれる機能ではなく、固定ソースへの fork patch である。 operator がビルド・配布・更新保守するか、上流への採用が必要である。 新しい Kanade と producer を同じ v2 契約で配布する。v1 は未サポート扱いで、 互換 shim で名前を回復しない。未改造・旧版・不明版・metadata 欠落・不整合は unknown/auth-unproven に留める。producer を未改造版に戻せば次のpollで 名前が失効する。既存バイナリの置換には broker の再起動が必要で、すべての 接続が再接続する。新 epoch は再認証まで未証明である。reload でも generation を更新し、古い認証結果を再利用しない。権限や認証方式を緩めて 表示を緑にする運用はしない。
検証は Python 3.11 以上(native package fixture の tomllib)、Go 1.27.2 (.tool-versions と integration.yml)、Bun、Python TLS proxy、OpenSSL が必要。 グローバル設定を変更せず、対応する Python を子プロセスにも選ぶこと (docs/local-verification.md を参照)。python3 tools/nats-identity/verify.py は 固定ソースから producer をビルドし、Go race テスト、実 broker の WSS/TCP と producer 由来の Agents browser テストを実行する。 2件のpositiveテストと必須browserテストの実行を検査し、空振りは成功にしない。 本作業で本番の設定変更、再起動、配布、採用判断は行っていない。
過去の NATS 2.14.1 初回測定(最適化前、保持した結果)
初回は revision d0d12836 の結果を measurements-initial.json に内容を変えず 保持した。Go 1.27.2、Darwin arm64、8 CPU の同一ホストで各負荷5サンプル。 default は GOMAXPROCS=4/GOMEMLIMIT=off、constrained は GOMAXPROCS=1/GOMEMLIMIT=768MiB。中央値は以下のとおり。初回は variantごとに5回まとめて実行しており、後述の交互順序とは異なる。
| profile | 負荷 | baseline ms/op | patched ms/op | 時間差 | B/op(baseline → patched) | allocs/op(baseline → patched) |
|---|---|---|---|---|---|---|
| default | TCP・平文password churn | 0.482 | 0.637 | +32.08% | 62888 → 64182 | 179 → 179 |
| default | connz・128接続 | 0.505 | 0.787 | +55.74% | 132171 → 204187 | 395 → 525 |
| default | 監視付き64B request/reply | 0.181 | 0.195 | +7.89% | 1318 → 1336 | 21 → 21 |
| default | cold config・同一bcryptハッシュ×3 | 0.328 | 412.581 | +125816.99% | 129349 → 182872 | 445 → 856 |
| constrained | TCP・平文password churn | 0.532 | 0.488 | -8.25% | 62946 → 64220 | 180 → 180 |
| constrained | connz・128接続 | 0.542 | 0.836 | +54.30% | 131930 → 204016 | 394 → 523 |
| constrained | 監視付き64B request/reply | 0.171 | 0.174 | +1.74% | 1318 → 1325 | 21 → 21 |
| constrained | cold config・同一bcryptハッシュ×3 | 0.343 | 415.702 | +121045.97% | 129354 → 182816 | 445 → 854 |
特にdefaultのTCP churnは 482047 → 636671 ns/op(+32.08%)。 5サンプルの範囲もbaseline 468165–538897、patched 580087–712285 ns/opで 重ならない。これをnoiseとは扱わない。constrainedの中央値 531838 → 487958 ns/op(−8.25%)とは別の結果である。 defaultのconnz応答は46503 → 91203 byte、約96%増だった。 3ユーザーのconfig構築は327661 → 412580854 ns/opであり、 初回の大きな設定費用を省略しない。このfixtureは3人が同一の cost-8 bcryptハッシュを共有していた。WSS接続費用や独立ハッシュの費用は この初回測定からは分からない。client_bytesはResetTimerより前に報告したため 初回出力には残っておらず、初回のchurn B/opを保持メモリと解釈してはいけない。
過去の NATS 2.14.1 最適化後の比較
measurements-2.14.1.json は当時の measurements.json を変更せず保持したもので、 以下はすべて 2.14.1 の過去測定である。同ファイルは各profile/variant/6負荷を5回ずつ記録し、生のGo出力、 各sample、中央値、差分、固定ソース・patch・producer・benchmarkのSHA-256、 初回結果のSHA-256を含む。measure.py は計測前に現在のソースから両variantを 再構築する。同一benchmarkコード、NATS 2.14.1/Go 1.27.2、500ms、 count=1を使い、第1/3/5回をbaseline→patched、第2/4回を逆順にした。 元の4負荷、client_bytesの計時後報告、独立ハッシュのcold config、 WSS負荷を含む全20プロセス・120 workload sampleが成功した。
Darwinでは各プロセスの前に、sysctlで読み取ったTCP MSLの2倍+1秒 (今回は31秒)を計時外で待つ。連続churnによる送信元ポート枯渇を 未改造baselineでも再現したためで、49152–65535の範囲で16,247回目の接続が EADDRNOTAVAIL(errno 49)になった。待機なしの不完全な比較は採用していない。 OS設定は変更せず、失敗したsampleの自動再試行や除外もしない。 失敗時にはGoの出力を保存できる形で表示し、比較全体を失敗にする。 初回とは実行順序・待機・ホスト状態が異なるため、異なる回の絶対時間差を すべてコードの高速化に帰属させない。
| profile | 負荷 | baseline ms/op | patched ms/op | 時間差 | B/op(baseline → patched) | allocs/op(baseline → patched) |
|---|---|---|---|---|---|---|
| default | TCP・平文password churn | 0.177 | 0.175 | -1.31% | 62905 → 62974 | 180 → 180 |
| default | connz・128接続 | 0.170 | 0.212 | +24.71% | 131843 → 156609 | 393 → 395 |
| default | 監視付き64B request/reply | 0.060 | 0.060 | +0.22% | 1271 → 1276 | 21 → 21 |
| default | cold config・同一bcryptハッシュ×3 | 0.112 | 49.139 | +43641.32% | 129334 → 149494 | 445 → 753 |
| default | cold config・独立salt/異なるpassword×3 | 0.112 | 146.924 | +131642.14% | 129334 → 181348 | 445 → 830 |
| default | WSS・bcrypt cost 8 churn | 17.511 | 17.461 | -0.28% | 216584 → 216469 | 1132 → 1132 |
| constrained | TCP・平文password churn | 0.183 | 0.180 | -1.42% | 62920 → 62981 | 180 → 180 |
| constrained | connz・128接続 | 0.180 | 0.222 | +23.46% | 131683 → 156369 | 393 → 394 |
| constrained | 監視付き64B request/reply | 0.052 | 0.052 | +0.79% | 1267 → 1269 | 21 → 21 |
| constrained | cold config・同一bcryptハッシュ×3 | 0.120 | 49.112 | +40781.31% | 129332 → 149452 | 445 → 753 |
| constrained | cold config・独立salt/異なるpassword×3 | 0.121 | 147.226 | +121555.31% | 129331 → 181376 | 445 → 829 |
| constrained | WSS・bcrypt cost 8 churn | 17.495 | 17.477 | -0.10% | 212124 → 212153 | 1131 → 1131 |
同一ハッシュのconfig構築は今回約49 msだが、重複比較9回を3回に減らせた ケースである。独立salt・異なるpasswordの3ハッシュでは3候補×3ハッシュの 衝突検査が必要で、約147 msが残る。baselineの約0.11–0.12 msとは依然として 大きな差がある。初回の約413/416 msとの時間差には手法・ホスト状態の差もある。 検査の省略、bcrypt costの引き下げ、warm cache hitへの置換はしていない。 credential生成は計時外だが、NewServerとpolicyは毎op冷状態で構築する。 64ユーザー超、cost 12超、distinct secret 256超、重み付き比較仕事量4096超では 名前を出さない安全側の上限も維持している。
今回のTCP churnはdefault -1.31%、constrained -1.42%でsample範囲は重なる。 defaultはbaseline 0.173015–0.178042、patched 0.172427–0.175990 msだった。 ただし初回の非重複範囲と+32.08%をnoiseとして取り消すものではない。 型・保持メモリ・計測条件も変わっているため、今回の差だけで全環境での 接続費用を保証しない。認証snapshotの保存や同期そのものは残る。
connz生成・JSON化はdefaultでbaseline比時間+24.71%、B/op +18.78%、 応答46393 → 65144 byte(約40.4%、1接続あたり約147 byte増)。 constrainedでは時間+23.46%、応答46394 → 65140 byteだった。 初回patchedの応答約91 KBより小さく、defaultのallocs/opは525から395へ減ったが、 これはbroker内の生成・JSON化の比較であり、HTTPや監視ネットワークは含まない。 response_bytesは各sample末尾のserialized応答長の5回の中央値である。 v2の共有フィールドと値コピーで冗長性は減るが、監視費用は残る。 auth=1の比較であり、auth=0でもConnInfoの値fieldのため構造体は拡大する。 auth=0の時間・allocationは今回測定していない。
保持メモリは両profileでclient構造体6872 → 6904 byte、増分32 byte。 identity_state_bytesも32 byteで、64-bitのgeneration/sequence、安全な名前セルへの ポインタ、3つの1-byte列挙値とstickyな由来を保持する。名前セルは設定内の 安全な公開名ごとに1つ作り、既存のimmutableな文字列を参照する。 接続ごと・認証ごとの文字列コピーや名前セルの確保、secret構造体のコピーはない。 セルはprivateなUserオブジェクトの内部ポインタではない。 churnのB/op差はdefault +69 byte、constrained +61 byteであり、 構造体だけの増分とは区別する。client_bytesはstack、socket、TLS、 allocatorやRSS全体の測定ではなく、32 byteからRSS増分を断定しない。 名前はproducer・consumerとも最大64 byteで、接続が参照する公開名の寿命は 延び得るが、新たなidentity履歴やsecret-bearingなグローバルキャッシュは作らない。 監視用ConnInfoのv2値fieldは64-bit型定義からの計算では88 byte。 既定10000件のclosed ringもこの空fieldを持つため、fieldだけで880000 byte相当が 増える。閉じた接続の新metadataは保存しないが、この容量のtradeoffは残る。
監視付きrequest/replyは10msごとにconnzを生成し、64 byteを1往復ずつ送る。 今回の中央値からの逐次処理率はdefault約16641 → 16606 req/s、 constrained約19262 → 19111 req/s。allocs/opはすべて21のままである。 PUB/SUBの通常配送経路には処理を追加していないが、この逐次負荷を 並列PUB/SUBの最大throughputやtail latencyの保証にはしない。
追加WSS負荷は、一時的なP-256証明書を検証する新しいTLS/WebSocket接続で、 cost-8 bcryptユーザー1人のCONNECTとflushを毎op実行する。 証明書・hash生成は計時外、接続・TLS・bcrypt認証は計時内である。 TLSはbrokerで直接終端し、Caddyや遠隔ネットワークを再現していない。 defaultは約17.51 → 17.46 ms、constrained約17.49 → 17.48 msで範囲は重なる。 producerで高速化できたとの結論や、初回TCP churnの回帰の相殺には使わない。 実TLS proxyを経由するpositive/negative試験は別途verifyで維持している。
単一Darwinホストのmicrobenchmarkであり、GOMEMLIMITはGoのsoft heap limitに すぎない。1 GiB Linux VM・swapなしでの試験ではない。長期RSS、 接続storm、JetStream負荷、p95/p99、本番Caddyや本番のbcrypt costは未評価である。 全sampleと初回結果を保持し、失敗を隠すための再試行やsampleの選別はしない。 設定時の約147 msと監視の残存増分は運用上のtradeoffで、本番採用の許可ではない。 採用・配布・本番での再起動は、所有者の別判断が必要である。
NATS 2.14.3 互換性と最終ソースの再測定
本番より古い 2.14.1 に戻さないため、CI の broker pin と source build を 公式 2.14.3 に揃えた。producer.patch、auth_identity.go、Go テスト、 benchmark は変更していない。v2、認証判断、privacy guard、sticky no_auth_user、compact snapshot、reload/restart/rollback/expiry の契約を維持する。 archive は版別にキャッシュし、build 時に固定 SHA-256 を照合する。
この worktree で以下を実行した(mise exec は子プロセスにも指定版を渡す)。
mise exec -- python3 tools/nats-identity/verify.py
mise exec -- python3 -m unittest discover -s tools/nats-identity -p test_measure.py
mise exec -- python3 -m unittest discover -s scripts/ci -p test_magi_e2e.py
mise exec -- python3 tools/nats-identity/measure.py
verify は実 broker の go test -race -v ./server -run '^TestAuthIdentity' -count=1 で top-level 6件と sticky no_auth_user の2 subtest を成功させた。 続く cargo test --locked -p kanade-backend --bin kanade-backend live_identity_producer_ -- --ignored は 2 passed、0 failed、0 ignored。 KANADE_IDENTITY_BROWSER=1 を必須にし、実 producer から SQLite と本物の Agents API に到達する browser テストの 1 passed も内部で検査した。 測定の欠落・重複・空iteration・必須metricとPASSの欠落を拒否する3テスト、 CI pin/tool準備と空振りcount検査の15テストも成功した。 count検査のnegative fixtureが表示する ERROR は期待された出力である。
measurements.json は 2.14.3 の最終ソースから baseline/patched を再構築した 比較で、生のGo出力、全120 workload sample(20プロセス)、中央値、差分、 source commit/URL/archive・patch・producer・benchmark・build/measure driver・ producer test・両binaryのSHA-256、および過去2.14.1結果のSHA-256を含む。 Darwin arm64/8 CPU、Go 1.27.2、各profile/variant/6負荷を5回、 500ms/count=1、順序は第1/3/5回 baseline→patched、第2/4回は逆。 default は GOMAXPROCS=4/GOMEMLIMIT=off、constrained は 1/768MiB。 TCP MSLから算出した31秒を各プロセス前に計時外で待ち、失敗・再試行・ sample除外なしで全件成功した。元の診断出力と実行件数の検査は維持している。
| profile | 負荷 | baseline ms/op | patched ms/op | 時間差 | B/op(baseline → patched) | allocs/op(baseline → patched) |
|---|---|---|---|---|---|---|
| default | TCP・平文password churn | 0.209 | 0.240 | +15.01% | 62905 → 62965 | 180 → 179 |
| default | connz・128接続 | 0.213 | 0.332 | +55.84% | 131901 → 156643 | 393 → 395 |
| default | 監視付き64B request/reply | 0.077 | 0.093 | +21.83% | 1278 → 1290 | 21 → 21 |
| default | cold config・同一bcryptハッシュ×3 | 0.153 | 70.356 | +45993.27% | 129345 → 149492 | 445 → 753 |
| default | cold config・独立salt/異なるpassword×3 | 0.151 | 187.382 | +124252.58% | 129339 → 181128 | 445 → 830 |
| default | WSS・bcrypt cost 8 churn | 20.863 | 21.593 | +3.50% | 216717 → 217917 | 1134 → 1135 |
| constrained | TCP・平文password churn | 0.195 | 0.185 | -4.92% | 62920 → 62989 | 180 → 180 |
| constrained | connz・128接続 | 0.191 | 0.258 | +34.98% | 131692 → 156389 | 393 → 394 |
| constrained | 監視付き64B request/reply | 0.060 | 0.059 | -1.23% | 1270 → 1274 | 21 → 21 |
| constrained | cold config・同一bcryptハッシュ×3 | 0.142 | 51.782 | +36269.90% | 129341 → 149469 | 445 → 753 |
| constrained | cold config・独立salt/異なるpassword×3 | 0.131 | 147.297 | +112546.04% | 129335 → 181348 | 445 → 829 |
| constrained | WSS・bcrypt cost 8 churn | 18.027 | 17.625 | -2.23% | 212117 → 212173 | 1131 → 1131 |
default のTCP +15.01%と監視付きrequest/reply +21.83%、connzの default +55.84%/constrained +34.98%は、今回観測した回帰として報告する。 過去2.14.1の小さい中央値差を根拠に「影響なし」とはしない。 TCP は208658 → 239972 ns/op、範囲はbaseline 182608–347971、 patched 176228–315932。request/reply は76600 → 93322 ns/op、 範囲60375–143714/60084–106958で、どちらも範囲は重なる。 connz のdefault範囲も173597–414810/215387–430153 ns/opと広い。 単一ホストのこの比較だけから、上流2.14.3の変更が原因だとも、 重なる範囲を理由に回帰が存在しないとも断定しない。再測定による選別はしていない。 逐次request/replyの中央値からの処理率はdefault約13055 → 10716 req/s、 constrained約16748 → 16956 req/sで、p95/p99や最大throughputではない。
connzの応答長はdefault 46391 → 65143 byte(+40.42%)、 constrained 46391 → 65138 byte(+40.41%)。B/opは両profileとも約18.75%増。 client_bytesは両profileで6872 → 6904、identity_state_bytesは32である。 Go 1.27.2 の internal/runtime/gc/sizeclasses.go の6784/6912 byte境界と、 pointer-bearing objectの8 byte headerを使う runtime/msize.go の丸めでは、 6880/6912 byteの両方が6912 byte classに入り、clientのallocation classは跨がない。 これは型サイズとallocatorソースからの判定で、RSSの実測や全構造体の allocation class検証ではない。ConnInfo値fieldの88 byte、既定closed ringの field相当880000 byte、auth=0でも構造体が拡大するtradeoffも残る。
cold bcrypt configは約52–70 ms(同一hash)/147–187 ms(独立hash)であり、 検査省略、bcrypt cost低下、warm cacheへの置換では隠していない。 1 GiB Linux/swapなし、長期RSS、storm、JetStream混在負荷、p95/p99、 本番Caddyと本番bcrypt costは未評価である。機能互換性の成功は、 これらの性能・運用リスクの解消や配布・再起動の承認を意味しない。 本作業で本番変更・配布・publishは行っていない。
Telling a locked-out host from an offline one
From the backend alone you cannot (the script says so every time). Use evidence outside the broker:
- Was it alive just before? It is in the snapshot, with a last heartbeat seconds before the switch: consistent with either lock-out or power loss, but a host that had been dark for hours before is not a lock-out.
- What did the backend last record for it?
shared-tokenas its last NATS user means it was on the old token and never reported the new user. A missing user means never correlated, not "old credential". - Reach the machine without the broker: ping or power state from your management tooling, then the agent service state and its log. A lock-out shows a running (or restart-looping) agent and authorization errors in the log; a powered-off host shows nothing.
- Broker side, on the broker host: the server log shows authorization violations for refused connections.
Dotted pc_ids
A pc_id is the agent's [agent] id, and on Linux and macOS that is often an OS hostname with dots (m1air.local, host.example.com). Each dot makes another subject token, so the permission lists in the users configuration cannot use a single * where the pc_id goes. A pc_id of up to 4 dot-separated labels is supported (host.sub.example.com is the longest shape intended); the lists spell out one pattern per label count wherever a wildcard cannot express "one or more tokens".
A pc_id with 5 or more labels is refused up front, on the token configuration too: the agent exits at startup with an error naming the limit, kanade run and kanade agent logs fail before sending anything, and the backend API answers 400. Under the users configuration such an agent would otherwise connect and then lose every publish.
Before the switch, list the registered pc_ids and look for any with 5 or more labels (that is, 4 or more dots). Give those hosts a shorter [agent] id first; an existing deployment that has one will not start the agent after the upgrade that adds this check.
How a lock-out looks if a host slips through (for example an agent built before the limit existed): the agent connects as agent, so the backend shows it with the new user, but nothing it publishes arrives. The host goes silent in the SPA, and the broker log shows lines such as
Publish Violation - Subject "heartbeat.m1air.local"
(logged against the agent user), and likewise for host_perf., obs. and the other subjects that carry the pc_id. Fix the id and restart the agent; it needs no broker change.
Hosts that stay out
Use the same evidence path. A host that is powered off returns when someone powers it on and needs nothing. A host that is running but refused has no working user pair or an agent that predates user credentials: put the pair on it (the deployment script with -NatsUser / -NatsPassword) or upgrade it, and restart the agent service; it then connects as soon as the credential is present. If you cannot fix it by hand soon, and the host matters, revert, fix the stragglers, and run Readiness again; do not leave a fleet of unreachable machines in place hoping they recover.
New machines during the window
A machine installed while the broker runs the users configuration needs the agent role's user pair at install time, or it cannot connect. Use an installer generated with the agent pair set in the backend's installer settings, and still carrying the token (a revert needs it). Such a host is not in the snapshot; it shows up under New hosts and in the user counts. A host installed with the token only is refused and is invisible to the backend, so it cannot be seen by any of this; after a successful switch, check that no installer in circulation lacks the pair.
Afterwards
- Confirm connections are all the expected role users: the user table from a fresh
Compareshows onlyagentfor agents, and the backend's Expected NATS authentication findings are empty. - Only then plan the removal of the shared token from hosts and from the installer settings. That is a separate, later step: while the token is still stored, a revert still works. Do not remove it in the same window.
Rehearsal
Run the whole sequence once against a throwaway broker before the first real switch. Nothing in the rehearsal touches production.
- Throwaway broker. Start a separate
nats-serveron its own port and store directory (the development broker uses port 4223), first with the shared token, using a configuration copied from the shipped one. Prepare the users configuration from the shipped template with bcrypt hashes of throwaway passwords. - Backend pointed at that broker, with its own data directory and API token, and a few agents with distinct ids, in these states:
- normal: user pair and token, current version;
- pair not distributed: the token only (on purpose);
- old version: the oldest agent you have;
- stopped: a registered agent that is not running.
- Readiness with a check job that reports for them (or, with none, expect every host to be
no-check-result; rehearse the other reasons and the exit code anyway). Confirm it names the undistributed, old and stopped hosts and exits 1. Fix them (or accept them) until the list is empty or known. - Snapshot, then switch the throwaway broker with a reload signal (not a restart), noting the UTC time.
- Compare too early (expect exit 3), then after the wait. Confirm the deliberately unprepared agent shows as disappeared, the normal ones show as
agent, and-MaxDisappearedabove and below the real count gives exit 0 and 1. - Reproduce a lock-out and walk the "locked-out vs offline" section on it, including finding the authorization errors in the broker log.
- Pause the backend API briefly while running
Compare, to see the retry messages and the exit 2 when it stays down. - Revert to the token, restart the unprepared agent if its service manager does not, and
Compareagainst the same snapshot to confirm the fleet is back.
The conformance test (nats_role_conformance, see the README) covers the broker-side behaviour of this switch with live processes; the rehearsal covers your hosts, tooling and access path, which is what goes wrong in practice.
agent 経由のアップデート
既存の Windows インストーラジョブは、登録済みエージェント経由でバックエンド、クライアント、ブローカーを更新します。エージェント自身の更新は Linux と Apple Silicon macOS にも対応します。Linux バックエンドは別の bundle/setup 経路を使い、macOS Client の配布連携は未実装です。資格情報、接続性、稼働中のエージェントが必要で、オフライン復旧にはホストへの直接アクセスが必要な場合があります。
この章はコンポーネントごとに 1 ページずつあります:
全コンポーネントで共通の仕組み:
| バケット / ストリーム | 用途 |
|---|---|
OBJECT_APP_PACKAGES | 汎用バイナリストレージ (backend、client、NATS サーバーなど)。キーは <name>/<version>。 |
OBJECT_SCRIPTS | マニフェストが script_object で参照する PowerShell スクリプト本体。キーは <name>/<version>。 |
OBJECT_AGENT_RELEASES | agent バイナリ専用。agent の rollout 専用の watcher / target_version フローを持つので APP_PACKAGES とは別バケットになっています。 |
agent_config (KV) | レイヤード config — global / グループ別 / PC 別。target_version はここに置かれます。 |
jobs (KV) | ジョブカタログ。各エントリは operator が exec できるマニフェストです。 |
CLI コマンド一覧:
kanade app, kanade script and kanade agent (publish / rollout / current / logs) talk to the backend HTTP API, not to NATS: they need KANADE_AUTH_TOKEN (see kanade login) for an account with the operator role, and no broker token. Publishes and deletes are audited against that account by the backend. Operators who previously relied on the NATS token alone must now export KANADE_AUTH_TOKEN; without it the backend answers 401 / 403. The NATS user pair in the server settings' agent_install section is the agent role's credential, shared by all agents by design, and the backend- generated installers embed it (alongside the token) only when both halves are set. The backend's own credential and the break-glass credential never go in those settings.
kanade agent publish is capped by the backend at 64 MB for the whole upload (a normal agent binary is well under that). app publish additionally downloads the package back from the backend and checks its digest before reporting success.
| コマンド | 動作 |
|---|---|
kanade app publish <name> <file> [--version <version>] | Upload to OBJECT_APP_PACKAGES through the backend API. |
kanade script publish <name> <version> <file> | Upload to OBJECT_SCRIPTS through the backend API. |
kanade job create <yaml> | jobs KV にジョブマニフェストを upsert。 |
kanade exec <job-id> --pcs <pc1>,<pc2> | 登録済みジョブを PC 群に対して起動。 |
kanade agent publish <file> [--version <version>] | Upload an agent binary through the backend API (must be an official kanade-agent carrying release metadata; the version is read from it and --version, if given, must match — see Agent release admission). |
kanade agent rollout <version> --pc \| --group \| --global | Flip target_version on the chosen scope; agents pick it up via their self-update watcher. Goes through the backend API. |
kanade agent current | Print the global target_version (group / pc overlays are not shown; use kanade config get --group/--pc). |
kanade agent logs <pc_id> [--tail <n>] | Tail an online agent's log via the backend API. |
kanade-backend のアップデート
backend は管理対象ホスト 1 台 (またはそれ以上) で Windows サービスとして動いています。agent 経由のアップデートとは、そのホスト上で稼働する agent がサービスを停止し、バイナリを差し替えて再起動することを指します。これにより、operator は対象ホストに一度もログインする必要がありません。
end-to-end フロー
┌── operator host ──────────────────────────────────────────┐
│ 1. build kanade-backend.exe │
│ 2. kanade app publish kanade-backend <exe> --version <v> │
│ 3. edit deploy-backend.ps1 (set $AgentSource* knobs) │
│ 4. kanade script publish deploy-backend <v> <edited.ps1> │
│ 5. kanade job create install-kanade-backend.yaml │
│ 6. kanade exec install-kanade-backend --pcs <host> │
└────────────────────────────────────────────────────────────┘
│
▼
┌── target host (running kanade-agent as LocalSystem) ──────┐
│ • agent receives the Command on commands.pc.<host> │
│ • fetches deploy-backend.ps1 from OBJECT_SCRIPTS │
│ sha-verifies it (`script_object` machinery, #214) │
│ • stages it under │
│ C:\ProgramData\Kanade\agent-scripts\<UUID>\ │
│ kanade-<UUID>.ps1 │
│ • runs `powershell -File <launcher>` (PR #230 fix) │
│ • launcher invokes the user script via `& '...'` │
│ so [CmdletBinding()] / param() headers parse │
│ • script downloads kanade-backend.exe from │
│ OBJECT_APP_PACKAGES (via /api/app-packages/…) │
│ sha-verifies it (separate hash, on the exe itself) │
│ • Stop-Service KanadeBackend │
│ • copy exe over C:\Program Files\Kanade\… │
│ • Start-Service KanadeBackend │
│ • exit 0 — result published to NATS │
└────────────────────────────────────────────────────────────┘
sha チェックが 2 段ある理由は意図的: スクリプト本体のハッシュは agent が実行前に検証 (スクリプトの完全性)、バイナリのハッシュはスクリプトが swap 前に検証 (バイナリの完全性、operator が $AgentSourceSha256 で指定)。
ステップごとの手順
1. kanade-backend をビルド
cargo build --release -p kanade-backend
出力: target/release/kanade-backend.exe。
2. バイナリを publish
kanade app publish kanade-backend target/release/kanade-backend.exe --version 0.43.0
これでバイナリが OBJECT_APP_PACKAGES/kanade-backend/0.43.0 にアップロードされ、sha-256 digest が表示されます。digest を控えておきましょう — 後でスクリプトに lowercase-hex 形式で書き込みます。
3. scripts/deploy/backend.ps1 を編集
ローカルコピーを作って、先頭の 4 つの $Agent* ノブをセットします:
$AgentSourceUrl = 'http://kanade-backend.example.com:8080'
$AgentSourceVersion = '0.43.0'
$AgentSourceSha256 = '<kanade-backend.exe の lowercase hex>'
$AgentSourceAuthToken = '<backend HTTP API 用 bearer>'
スクリプトの他の部分は触らないでください。このノブによって「agent モード」(backend からダウンロード) と「手動インストールモード」(ローカルフォルダからの読み込み) が切り替わります。
$AgentSourceSha256はGet-FileHash kanade-backend.exe -Algorithm SHA256の hex 形式の値です。
kanade app publishの出力にある base64url 形式しか手元にない場合は decode します。CLI から出る base64 は URL-safe で padding なしのことがあるので、FromBase64Stringに通す前に padding を補う必要があります:$b64 = '<paste the SHA-256= value here, without the SHA-256= prefix>' $b64 = $b64.Replace('-', '+').Replace('_', '/') if ($b64.Length % 4) { $b64 += '=' * (4 - $b64.Length % 4) } [BitConverter]::ToString([Convert]::FromBase64String($b64)).Replace('-', '').ToLowerInvariant()Python の場合:
python -c "import base64; print(base64.urlsafe_b64decode('<b64>' + '=' * (-len('<b64>') % 4)).hex())"
$AgentSourceAuthTokenは 2026-05-26 の live test 以降必須です。backend の/api/app-packages/<name>/<ver>エンドポイントは token なしだと HTTP 401 を返します。auth なしの lab 環境のときだけ空のままで問題ありません。
4. 編集したスクリプトを publish
kanade script publish deploy-backend 0.43.0 .\deploy-backend.edited.ps1
アップロード先は OBJECT_SCRIPTS/deploy-backend/0.43.0。
5. ジョブを登録 / 更新
リポジトリの configs/jobs/installers/install-kanade-backend.yaml がテンプレートです。version: と script_object: をいま publish したバージョンに合わせて編集してから upsert:
id: install-kanade-backend
version: 0.43.0
execute:
shell: powershell
script_object: deploy-backend/0.43.0
timeout: 300s
run_as: system
require_approval: true
kanade job create configs/jobs/installers/install-kanade-backend.yaml
run_as: systemは必須です:Stop-Service/Start-Service/sc.exeはいずれも admin が必要です。本番環境では agent は LocalSystem で動いているので問題ありません。
6. 起動
kanade exec install-kanade-backend --pcs <backend-host>
CLI はすぐに exec_id を返します。実際のインストールは対象ホスト上で非同期に走ります。
7. 確認
backend の results エンドポイントを叩く (もしくは SPA の Activity ビューを見る):
curl -H "Authorization: Bearer <token>" `
"http://<backend>/api/results?limit=5"
自分の exec_id が exit_code: 0 で、stdout が kanade-backend <new-version> で終わっていれば成功です。
ありがちなトラブル
| 症状 | 原因 | 対処 |
|---|---|---|
stderr に [CmdletBinding()] / param() の parse error | agent が 0.42.2 より古い (-Command モードで動いている) | まず kanade agent rollout で agent をアップグレード (agent self-update 参照)。 |
Start-BitsTransfer : HTTP status 401 | $AgentSourceAuthToken が空だが backend が auth を要求している | 値をセットする。 |
Start-BitsTransfer : The transfer encountered an error / ジョブ状態が TransientError | BITS サービスが停止しているか、対象マシンの WinHTTP から $AgentSourceUrl に到達できない | Get-Service BITS で確認。WinHTTP のプロキシは netsh winhttp show proxy で確認します (BITS が使うのは WinHTTP であって IE/WinINet ではありません)。 |
sha256 mismatch — expected=<x> actual=<y> | スクリプトの hash が publish されたバイナリと一致しない | 再 publish するか hash を計算し直す。スクリプトは swap の 前 に abort するので、既存のインストールは無事です。 |
| ジョブは実行されたが kanade-backend が起動してこない | 対象ホストでのサービス起動失敗 / config の不整合 | 対象ホストの C:\ProgramData\Kanade\logs\backend.*.log を確認してください。kanade agent logs <pc> が取得するのはエージェントのログのみです。バックエンド停止中はそのログをホスト上で取得してください。 |
kanade-client のアップデート
本ページは Windows インストーラジョブの手順です。macOS GUI / パッケージのビルドと未実装の配布連携は MACOS.md を参照してください。
Tauri デスクトップクライアントは backend と同じやり方で端末に配布します: バイナリは OBJECT_APP_PACKAGES、スクリプトは OBJECT_SCRIPTS、ジョブは jobs KV。形は backend のアップデート と同じで、スクリプト内容とパッケージ名だけが違います。
backend のアップデートとの違い
| 項目 | kanade-backend | kanade-client |
|---|---|---|
| (再) 起動するサービス | KanadeBackend (Windows サービス) | なし — クライアントはユーザーが起動する |
| インストール先 | %ProgramFiles%\Kanade\kanade-backend.exe | %ProgramFiles%\Kanade\kanade-client.exe |
| リポジトリ内のスクリプト | scripts/deploy/backend.ps1 | configs/jobs/installers/scripts/install-kanade-client.ps1 (マニフェストの script_file パス) |
| マニフェストの参照方法 | script_object: deploy-backend/<v> | script_file: scripts/install-kanade-client.ps1 (マニフェスト YAML からの相対パス; kanade job create 時に inline 展開) |
| atomic swap のやり方 | サービス停止 → コピー → サービス起動 | <exe>.new にステージ → Move-Item → <exe>.old を削除 |
| インベントリへの射影 | なし (backend は自分自身でバージョンを報告) | inventory: ブロックが PC ごとのクライアントバージョンを SPA Inventory ページに出す |
両方の形が使えます —
script_object(OBJECT_SCRIPTS から hash で参照、agent が必要時に fetch) とscript_file(kanade job create時にスクリプト本体をマニフェストに inline 展開)。client マニフェストは歴史的経緯で どちらの形式もサポートされています —script_object(OBJECT_SCRIPTS からハッシュで参照、agent が必要に応じて取得) とscript_file(kanade job create時にスクリプト本体をマニフェストにインライン展開)。クライアントマニフェストは歴史的経緯でscript_fileを使用し、backend マニフェストは Object Store パスのテストのためにscript_objectへ書き換えられました。
ステップごとの手順
1. kanade-client をビルド
cargo build --release -p kanade-client
出力: target/release/kanade-client.exe。
2. バイナリを publish
kanade app publish kanade-client target/release/kanade-client.exe --version 0.42.0
3. configs/jobs/installers/scripts/install-kanade-client.ps1 を編集
先頭の 3 つのノブをセット:
$BackendBase = 'http://kanade-backend.example.com:8080'
$Version = '0.42.0'
$ExpectedSha256 = '<kanade-client.exe の lowercase hex>'
backend auth が有効なら
$ClientSourceAuthTokenを backend の bearer にセットしてください(agent が/api/*に使うのと同じトークンです)。/api/app-packages/kanade-client/<v>ルートが認証なしの開発環境やスモークテスト環境では空のままで問題ありません。scripts/deploy/backend.ps1 の$AgentSourceAuthTokenノブと同じ構成です。
4. ジョブを登録 / 更新
configs/jobs/installers/install-kanade-client.yaml:
id: install-kanade-client
version: 0.42.0
execute:
shell: powershell
script_file: scripts/install-kanade-client.ps1 # `job create` 時に inline 展開 (マニフェスト YAML からの相対パス)
timeout: 180s
run_as: system
require_approval: true
inventory:
display:
- { field: version, label: Version }
- { field: path, label: Install path }
summary:
- { field: version, label: Client version }
kanade job create configs/jobs/installers/install-kanade-client.yaml
inventory:ブロックは projector に「スクリプトの stdout は単一の JSON blob で、version/pathフィールドが SPA の Inventory ページに反映される」と伝えます。operator は fleet 全体のテーブルから取り残し端末を見つけられ、ssh は不要です。
5. 起動
kanade exec install-kanade-client --pcs <host1>,<host2>
もしくはグループ単位で:
kanade exec install-kanade-client --groups office
6. SPA で確認
SPA の Inventory ページを開く (もしくは /api/inventory?app=kanade-client を叩く) と、対象ホストが新しいバージョンを報告しているはずです。
NATS サーバーのアップデート
管理対象ホスト上のブローカーをアップデートするのは最も特徴的なケースです。なぜなら agent は ブローカー越しにブローカーと話す ためです。NATS を停止するとジョブの途中で agent との接続が切断されます。これに対しては、2 つの仕組みが組み合わさって対処しています:
- 再接続。 agent の NATS クライアントはブローカー再起動時に自動再接続します。人の介入は不要。
- outbox。 ブローカーが落ちている間に発生したジョブ結果は
%ProgramData%\Kanade\outbox\に貯められ、接続が戻り次第再送されます。新しい NATS サーバーが立ち上がるとすぐに result row が backend に届きます。
したがってフローは backend のアップデート と同じです。スクリプトはサービスを停止してバイナリを差し替え再起動し、agent はブローカーの切断期間を透過的に許容します。
NATS アップデート固有の注意点
| 懸念 | 実際 |
|---|---|
| result row はロストする? | いいえ — outbox がブローカー停止中を跨いで保持し、再接続時に drain します。 |
| SPA からアップデートできる? | はい、他のジョブと同じです — kanade exec install-kanade-nats --pcs <broker-host>。 |
| NATS が再起動してこなかったら? | result は outbox にずっと残ります。operator はブローカーホストの outbox/ を復帰失敗の早期サインとして監視することが推奨されます。 |
| 新しい NATS バージョンに互換性がなかったら (JetStream のアップグレードなど)? | まず canary 1 台に rollout (--pcs <one-broker>)、outbox と backend の健全性を見てから fleet 全体に展開。SPA クエリには 5 分の cache TTL があるので canary の状態は数分以内に反映されます。 |
手動インストール (ブートストラップ)
初回インストール (ブローカーホストにまだ agent がない状態) では直接ワークフローを使います:
.\scripts\build-release.ps1 -Roles nats # fetches nats-server.exe
# from github.com/nats-io/nats-server/releases
.\scripts\deploy\nats.ps1 -NatsToken '<token>'
これで nats-server.exe を %ProgramFiles%\Kanade\ に、nats-server.conf を %ProgramData%\Kanade\config\ にインストールし (bearer token を平文で保存するため ACL は SYSTEM + Administrators に絞ります)、KanadeNats Windows サービスを登録し、TCP 4222 (broker) を開放し、サービスを起動します。
monitoring (8222) は意図的に開放しません。古いデプロイが作った規則があれば削除します。このエンドポイントには独自の認証が無く、リポジトリ内の利用側はすべてループバック経由で読むためです。同梱の nats-server.conf もそれに合わせて 127.0.0.1 にバインドしています。
agent 経由のアップデート (定常運用)
scripts/deploy/nats.ps1 には $AgentSource* のノブがあります (#234)。ブローカー自身もフリート経由で更新できるので、ブローカーのホストに RDP する必要はありません。
1. nats-server.exe をビルド or 取得
どちらか:
.\scripts\build-release.ps1 -Roles nats # fetches the binary
…もしくは github.com/nats-io/nats-server/releases から直接ダウンロード。
2. バイナリを publish
kanade app publish nats-server .\nats-server.exe --version 2.10.20
3. deploy-nats.ps1 を編集
パターンは deploy/backend.ps1 と同じです:
$AgentSourceUrl = 'http://kanade-backend.example.com:8080'
$AgentSourceVersion = '2.10.20'
$AgentSourceSha256 = '<nats-server.exe の lowercase hex>'
$AgentSourceAuthToken = '<backend HTTP API 用 bearer>'
4. publish + 登録 + exec
kanade script publish deploy-nats 2.10.20 .\deploy-nats.edited.ps1
kanade job create configs/jobs/installers/install-kanade-nats.yaml
kanade exec install-kanade-nats --pcs <broker-host>
ジョブマニフェストは configs/jobs/installers/install-kanade-nats.yaml にあります:
id: install-kanade-nats
version: 2.10.20
execute:
shell: powershell
script_object: deploy-nats/2.10.20
timeout: 300s
run_as: system
require_approval: true
5. 確認
ブローカーが復帰すると outbox が drain され、/api/results に result row が出てきます。新しい NATS バージョンはブローカーの monitoring エンドポイントで確認しますが、monitoring はループバックにバインドされ firewall でも開放していないので、ブローカーのホスト上で実行してください:
curl http://127.0.0.1:8222/varz | python -m json.tool | rg version
それ以外の場所からは、ポートではなくフリートに尋ねます — いま更新を実行したのと同じ agent-exec の経路です:
kanade exec collect-broker-health --pcs <broker-host>
なぜ独立した「broker update」機構が要らないのか
初期の設計では「ブローカー越しにブローカーを更新する鶏卵問題」を避けるために専用のブートストラップチャネル (agent が broker update 専用に使う並列 NATS 接続) を検討していました。outbox + 再接続のペアによってこれは不要に: 結果は「失われる」のではなく「遅延するだけ」。トランスポートはひとつ、メンタルモデルもひとつで済みます。
kanade-agent 自身のアップデート
agent の self-update は唯一 OBJECT_APP_PACKAGES + script_object ジョブを 使わない コンポーネントです。agent は ssh なしで現在実行中の自分自身のバイナリを差し替える必要があり、汎用 install ジョブよりタイトなループのため専用の仕組みを持っています。
仕組み
| バケット / キー | 用途 |
|---|---|
OBJECT_AGENT_RELEASES | エージェントバイナリ。キーは Windows が <version>、Linux が <version>-linux-<arch>、macOS が <version>-macos-aarch64 です。専用の更新 watcher のため OBJECT_APP_PACKAGES と分離しています。 |
agent_config.<scope>.target_version | 各スコープ (global / グループ / pc) があるべきバージョン。agent の self_update ループがこれを watch しています。 |
フロー:
1. agent.self_update watches agent_config for target_version
2. If target_version != my agent_version:
a. Pull the platform-specific agent_releases key to staging
b. Sha-verify against the bucket's recorded digest
c. Copy to <exe>.new, rename the old/new binary, exit(64); the service supervisor restarts it
d. New binary boots, watcher arms again, loop closes
rollout watcher は cold broker (ホスト再起動後に agent と broker が同時に立ち上がる、など) に耐えなければなりません。#226 以前は最初の get_object_store 呼び出しで Err(_) => return; してしまうと watcher が恒久的に死んでいて、その起動セッション中は agent が二度と self-update しませんでした。#226 以降は watcher が backoff で再試行し、broker に到達できるまであきらめません。
ステップごとの手順
1. agent をビルド
cargo build --release -p kanade-agent
出力: target/release/kanade-agent.exe。
2. publish
kanade agent publish target/release/kanade-agent.exe
The version comes from the release metadata embedded in the binary — no --version flag is needed, and if you pass one it must match. The backend refuses anything that is not an official kanade-agent carrying that metadata (see Agent release admission). It then streams the file to the backend API, so KANADE_AUTH_TOKEN (see kanade login) for an account with the operator role is required; no NATS broker token is involved, and the backend records the publish against that account. The backend caps the whole upload at 64 MB. Linux ELF and macOS Mach-O agents are published the same way.
3. roll out
スコープを選びます。canary 1 台から:
kanade agent rollout 0.42.2 --pc canary-01
ping で確認:
kanade ping canary-01 # agent_version should flip to 0.42.2
# within a few seconds
問題なければ範囲を広げる:
kanade agent rollout 0.42.2 --group office --jitter 5m
# or fleet-wide
kanade agent rollout 0.42.2 --global --jitter 30m
--jitterは実際の swap タイミングをある幅で分散させ、大きな fan-out 時に全ホストの OS サービスマネージャを同時に叩かないようにします。100 台以上の fleet では推奨。
4. 確認
kanade agent current
# → global.target_version = 0.42.2
あとは SPA の Agents ページ (もしくは /api/agents) で fleet 全体をスポットチェック: agent_version 列は jitter + 約 30 秒の heartbeat 間隔以内に新バージョンに収束するはず。
ありがちなトラブル
| 症状 | 原因 | 対処 |
|---|---|---|
kanade agent rollout が "version not in OBJECT_AGENT_RELEASES" と言う | typo もしくはスコープ違い | kanade agent current と認証付き HTTP API の GET /api/agents/releases で再確認してください。 |
数分経っても kanade ping <host> が古いバージョンを返す | agent が self-update しなかった — watcher が死んでいる (#226 以前の agent) か、ホストが broker に到達できない | 対象ホストの %ProgramData%\Kanade\logs\agent.*.log を確認してください。self_update のログ("checking target_version")がなければ古いエージェントの可能性があります。deploy-agent.ps1 で手動導入してください。 |
agent が flap する: 起動するも exit_code: 1 ですぐ落ちる | このホストでは新バイナリが起動できない (config の不整合、依存欠落など)。SCM の failure-actions により再起動が試みられるが再びクラッシュする — Event Viewer に Service Control Manager のエラーが連続して記録される | ロールバックは kanade agent rollout <prev-version> --pc <host> です。ただし、対象を処理できるまでエージェントが稼働する必要があります。起動できない場合はホスト上で以前のバイナリへ修復してください。watcher に到達しないエージェントは rollout では復旧できません。 |
なぜ別のバケット / スコープか?
OBJECT_APP_PACKAGES は <name>/<version> をキーにした汎用 blob ストアです。agent rollout パターンに必要なのは:
- agent の変更だけに反応する watcher (たくさんの名前が入ったバケットを poll するのではなく、特定の 1 つの KV キーを安価に watch)。
- 「既知の全バージョン」ではなくスコープごとの「現在の target」セマンティクス —
agent_config.<scope>.target_versionこそが「自分は何を動かすべきか」の答えで、agent 側で列挙する必要がない。 - operator 向け UX (
kanade agent publish/rollout) がkanade app publishとは別サブコマンドツリーに分けるに足るくらい違う。
というわけで agent は OBJECT_AGENT_RELEASES + レイヤード config KV を、他のコンポーネントは OBJECT_APP_PACKAGES + アプリ別ジョブを共有します。
Agent release admission
POST /api/agents/publish (what kanade agent publish, both fleet-deploy scripts and any direct HTTP caller use) only registers a file in the agent_releases Object Store if the file proves it is the kanade-agent binary. The backend decides; the CLI repeats the same check only to fail fast. POST /api/app-packages/{name}/{version} and app_packages are unaffected and still accept any file.
What is checked
Before anything is written to the Object Store, the backend parses the upload (it is never executed, so foreign-platform files are safe):
- OS / CPU from the executable itself: Windows PE x86_64 / aarch64, Linux ELF x86_64 / aarch64, thin arm64 macOS Mach-O. File names are ignored. The container must be a linked executable: PE executable (no DLL), Mach-O
MH_EXECUTE, or ELFET_EXEC/ET_DYNwith a nonzero entry point forET_DYN(PIE). Intermediate objects (ET_REL,MH_OBJECT), shared libraries and core dumps are rejected even if they carry valid agent metadata. - A release-metadata section, found through the container's section table:
.kanade(PE, ELF) or__DATA,__kanade(Mach-O). Missing, duplicated, truncated, wrongly framed, unknown-schema or non-JSON sections are rejected. Identifying bytes elsewhere in the file (appended or in other sections) do not count. - Product is exactly
kanade-agent. ThekanadeCLI, backend, client and any renamed copy of them are refused. - Platform in the metadata equals the platform of the container.
- Version: the embedded version is the release version and the key is derived from it. A
versionform field /--versionis optional; if given (ignoring surrounding whitespace and one leadingv) it must equal the embedded version. On Windows a VERSIONINFO that contradicts the embedded version is refused too.
A refusal is HTTP 400 with the reason and what to do; nothing is stored, and an existing release under the same key is left byte-for-byte untouched.
This identifies the product the build system stamped; it is not a signature and does not authenticate a deliberately forged binary (publishing already requires an authenticated operator).
Legacy binaries
Agents built before this metadata existed (up to v0.80.0) carry no section and are refused, whether or not --version is passed; there is no bypass flag. Releases already in the Object Store are not re-checked or changed: being stored does not mean they were verified. To re-publish an old version, rebuild it from a source tree that embeds the metadata.
How the metadata gets into the agent
crates/kanade-agent/build.rs がエンベロープ(KNAGMETA、schema 1、CARGO_PKG_VERSION と Cargo target から得た JSON {product, version, platform})を生成し、src/release_metadata.rs が専用セクションへリンクします。main から読み取るため LTO、--gc-sections / -dead_strip、strip でも保持されます。埋め込むのは agent crate のみです。補助スクリプト scripts/ci/release-post-build.sh はビルド済みバイナリ(macOS では署名後)と配布アーカイブを scripts/ci/verify-agent-dist.py で読み取り専用検証し、メタデータの欠落や不整合時に非ゼロを返します。導入済みバイナリの変更や再署名は行いません。
現在の kata 管理 release.yml はこの補助スクリプトを呼びません。CLI / バックエンドへのアップロード時の検証は有効ですが、release workflow の成功だけでは配布アーカイブのメタデータ検査が実行された証拠になりません。
Upgrade / release ordering
The first release containing this change (the one after v0.80.0, call it N) must be rolled out in this order:
- Release
N(CI verifies the agent artifacts carry the metadata). - Update the backend to
N. From now on only metadata-bearing agents can be published; old agents already in the store keep working. - Publish the
Nagents withkanade agent publish(or the fleet-deploy scripts) for each platform. - Roll out with
kanade agent rollout N …as usual. Running agents older thanNneed no change: they self-update from the store exactly as before, and the store now only receives real agents.
Publishing before step 2 would still work but would be unprotected; do not publish a legacy-built agent after step 2 — it is refused.
kanade をホストから取り除く (undeploy)
本番でのロールバック経路。rollout で何かが壊れた、ホストを廃止する、再インストール用にまっさらな状態に戻したい — そんなときホストから kanade を剥がすために、deploy と対になる undeploy スクリプトをコンポーネントごとに 1 本ずつ用意しています。
| 構成要素 | Deploy | Undeploy |
|---|---|---|
| Agent | scripts/deploy/agent.ps1 | scripts/undeploy/agent.ps1 |
| Backend | scripts/deploy/backend.ps1 | scripts/undeploy/backend.ps1 |
| NATS server | scripts/deploy/nats.ps1 | scripts/undeploy/nats.ps1 |
| Client (Tauri) | configs/jobs/installers/scripts/install-kanade-client.ps1 (エージェント経由) | scripts/undeploy/client.ps1 |
4本とも管理者専用かつ冪等です。アンインストールが途中で終わったあとに再実行しても安全ですし、対象がすでに無い状態で実行しても安全です (各ステップが「not present, skipping」と記録して次に進みます)。
デフォルトの姿勢: 安全側
フラグなしで実行するとスクリプトは:
- Windows サービスを停止します。
- SCM からサービスを unregister します (エントリが実際に消えるまで待つので、後続の再 deploy が pending な削除と race しません)。
%ProgramFiles%\Kanade\からインストール済みバイナリを削除します。中途半端な<exe>.new/<exe>.oldの swap 残骸もまとめて削除。- deploy スクリプトが作成した inbound のファイアウォールルールを削除します (
-KeepFirewallで skip 可 — 外部の WAF / グループポリシーがルールを管理している場合に有用)。 %ProgramData%\Kanade\配下 (config、log、JetStream データ、SQLite DB、…) は 残します。フォレンジック / rollback / 再 deploy が state を失わずに進められるように。HKLM:\SOFTWARE\kanade\<role>\*のレジストリ secret も 残します。
よくあるケース —「この端末の kanade がおかしいので、状態を壊さずに外したい」— にはこれで十分です。
-Purge: 破壊的クリーンアップ
追加で:
- そのコンポーネント固有の
%ProgramData%\Kanade\配下エントリを削除します。重要なのは そのコンポーネント自身のファイルだけ — agent / backend / NATS は同じ root を共有しているので、各スクリプトは他のコンポーネントのファイルには触れません。 - 対応する
HKLM:\SOFTWARE\kanade\<role>\*キーを削除します (-KeepSecretsを併せて渡すとスキップ — 複数コンポーネントで同じ bearer を共有しているときに有用)。
| 構成要素 | -Purge が削除するもの |
|---|---|
| Agent | config\agent.toml、logs\agent.*.log、outbox\、HKLM:\SOFTWARE\kanade\agent\ |
| Backend | config\backend.toml、data\*.db* (SQLite — 過去の results / inventory が消える)、logs\backend.*.log、HKLM:\SOFTWARE\kanade\backend\ |
| NATS | config\nats-server.conf、nats\ (JetStream — KV / Object Store / streams すべて消える)、logs\nats*.log |
| Client | 追加削除なし。-Purge は未実装のプレースホルダーで、ユーザーごとのウィンドウサイズなどの状態を保持します。 |
⚠️
undeploy-nats.ps1 -Purgeとundeploy-backend.ps1 -Purgeは破壊的です。前者はフリート全体の JetStream 状態(agent_releases、app_packages、scripts、jobs、agent_config、results stream)を消し、後者は永続アカウント、承認、スケジューラ完了記録を含むバックエンド SQLite を消します。別途バックアップがなければ復旧できません。 スクリプトは実行前に警告を表示します。
ロールバックの定石
canary 1 台で rollout が壊れたとき
# On the canary, as Admin:
.\scripts\undeploy\agent.ps1 # safe default
# kanade is now off the host. Re-deploy when ready:
.\scripts\deploy\agent.ps1 -SourceDir C:\path\to\prev-version
ホストを恒久的に廃止する
.\scripts\undeploy\agent.ps1 -Purge
dev box を再インストール用にまっさらにする
.\scripts\undeploy\agent.ps1 -Purge
.\scripts\undeploy\backend.ps1 -Purge # ⚠️ SQLite gone
.\scripts\undeploy\nats.ps1 -Purge # ⚠️ JetStream gone
.\scripts\undeploy\client.ps1
# Client user state and registration/shortcut artifacts may remain.
state は触らず壊れたサービスだけ作り直す
.\scripts\undeploy\backend.ps1 # safe default: SQLite intact
.\scripts\deploy\backend.ps1 -Recreate # fresh service registration, same data
undeploy がやらないこと
- この端末が居なくなったことをフリートの他の部分に通知はしません。バックエンドはハートビートが時効になるまで (
/api/agentsの staleness 閾値) 「エージェント」に載せ続けます。SPA から即座に消したい場合は、undeploy のあとバックエンド API で行を削除してください。 - デプロイ済みバイナリを以前のバージョンへ戻すことはしません。このスクリプトの語彙では「ロールバック」は「完全に削除する」という意味です。古いバージョンへ入れ替えたい場合は、そのバイナリが入ったフォルダに対して対応する
deploy-*.ps1を実行し直してください。 - エージェント削除時に NATS 側の状態は変更しません。PC ごとの target pin は
kanade config unset --pc <pc> target_version、そのスコープ全体はkanade config clear --pc <pc>で削除します。認証付きバックエンド API を使い、operator 権限が必要です。 - client スクリプトが削除するのは実行ファイルと swap 残骸のみです。ユーザー状態、プロトコル登録、ショートカットは削除せず、
-Purgeもこれらの削除を実装していません。
macOS code signing (stable identity)
macOS TCC (Files and Folders, Documents, Photos, Full Disk Access) keys grants on the binary's code identity. The linker's ad-hoc signature uses the cdhash as its identity — it changes on every build, so every self-update looks like a brand-new binary and prompts for privacy permissions again. Verify grant persistence on the actual installed launch path.
The release workflow therefore signs kanade-agent (and any other shipped macOS binary) with a stable self-signed code-signing certificate. The designated requirement stays identical across versions, so a one-time grant (or an MDM PPPC profile) survives updates. No Apple Developer ID or notarization is involved; spctl still rejects the binary, which is fine for a launchd-run command-line tool.
How it works
- Signing (
signhook):scripts/ci/macos-codesign.sh signruns right after the release build and before artifact packaging. It imports the certificate from repo secrets (MACOS_SIGN_CERT_P12_BASE64,MACOS_SIGN_CERT_PASSWORD) into an ephemeral keychain and signs each binary:codesign --force --sign <sha1> --keychain <kc> --identifier <id> -r="designated => identifier \"<id>\" and certificate leaf = H\"<sha1>\"" --timestamp=none <bin> - Post-package verification (
verify-disthook): Runs after packaging and before uploading artifacts. This step is strictly secretless: it unpacks the shippeddist/*.tar.gzand verifies the binaries against the pinned fingerprint indeploy/macos/signing-cert.sha1. - Integrity checks:
codesign --verify --strict -vensures Mach-O code directory validity.- Designated requirement verification checks that the binary specifies
identifier "com.kanade.agent"andcertificate leaf = H"<sha1>". - Rejects unstable
cdhashconstraints so ad-hoc or fallback signatures never pass unnoticed.
- Strict enforcement:
deploy/macos/signing-cert.sha1is required for official releases. Missing, invalid, or mismatched fingerprints fail the build.- Releases never fall back silently to ad-hoc linker signatures.
- This policy also applies to fork and
workflow_dispatchrelease builds: missing secrets fail the macOS matrix entry and block publication. There is no unsigned-release opt-out. Ordinary pull-request checks do not need the production secrets; the signing integration test uses a disposable test certificate and never publishes its binaries.
One-time setup
1. Reuse the established certificate
Before creating anything, list secret names only:
gh secret list --repo kanadehq/kanade --json name --jq '.[].name'
Check for both MACOS_SIGN_CERT_P12_BASE64 and MACOS_SIGN_CERT_PASSWORD. Secret presence does not prove that the pinned fingerprint matches the stored certificate. GitHub does not return secret values. The operator must derive the public fingerprint from the securely archived established certificate, or supply its public certificate for comparison. Do not export or log the private key, P12 contents, or password to perform this check. Do not replace an existing certificate merely because its private key cannot be read back from GitHub.
Provisioning status: both secret names (MACOS_SIGN_CERT_P12_BASE64 and MACOS_SIGN_CERT_PASSWORD) are present in the repository, checked by name only. The current pin in deploy/macos/signing-cert.sha1 has not been matched to the certificate stored in that secret, because GitHub never returns secret values. A syntactically valid pin is not evidence of a match. If it differs, macos-codesign.sh sign fails on the imported-vs-pinned comparison and blocks the release by design; that is an operator provisioning item, not something to patch around. The operator must confirm the established certificate's public SHA-1 (or replace the pin with it) before the next release.
Only if no established identity exists: create the certificate
Creating a new certificate is an explicit operator provisioning decision. It changes the TCC identity if a certificate was previously used. Reuse the existing P12 and certificate whenever available.
Keychain Access: Certificate Assistant → Create a Certificate…, name Kanade Code Signing, Identity Type Self Signed Root, Certificate Type Code Signing. Set a long validity (e.g. 3650 days) and export it as .p12.
Or with openssl:
cat > cs.cnf <<'CNF'
[req]
distinguished_name = dn
x509_extensions = ext
prompt = no
[dn]
CN = Kanade Code Signing
[ext]
keyUsage = critical, digitalSignature
extendedKeyUsage = critical, codeSigning
basicConstraints = critical, CA:false
CNF
openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 3650 -config cs.cnf
# -legacy: macOS `security import` rejects OpenSSL 3's default AES/PBKDF2 p12
openssl pkcs12 -export -legacy -inkey key.pem -in cert.pem -out kanade-sign.p12
2. Store it in the repo secrets
base64 -i kanade-sign.p12 | gh secret set MACOS_SIGN_CERT_P12_BASE64
gh secret set MACOS_SIGN_CERT_PASSWORD
Back up the .p12 file in a secure password vault or encrypted backup; losing the private key requires rotating the identity and invalidates all existing grants.
3. Pin the certificate SHA-1
openssl x509 -in cert.pem -noout -fingerprint -sha1 | sed 's/.*=//; s/://g' | tr 'A-F' 'a-f' \
> deploy/macos/signing-cert.sha1
Commit deploy/macos/signing-cert.sha1. Official builds require this pinned fingerprint to match the certificate used for signing.
Granting access on devices
MDM-managed Macs (PPPC profile)
<key>Services</key>
<dict>
<key>SystemPolicyAllFiles</key>
<array>
<dict>
<key>Identifier</key><string>com.kanade.agent</string>
<key>IdentifierType</key><string>bundleID</string>
<key>CodeRequirement</key>
<string>identifier "com.kanade.agent" and certificate leaf = H"<SHA1 OF THE CERT>"</string>
<key>Allowed</key><true/>
</dict>
</array>
</dict>
Manual
System Settings → Privacy & Security → Full Disk Access → + → add /usr/local/bin/kanade-agent (⇧⌘G to type the path). Once, per device.
Migration and operational caveats
One-time migration grant vs recurring update prompts
- Expected one-time regrant: Moving an installation from an ad-hoc signed binary (cdhash requirement) to the stable self-signed identity requires exactly one manual permission grant or PPPC profile deployment.
- Recurring prompts are regressions: If an update between two versions signed with the stable certificate triggers a privacy prompt, this indicates an identity regression (such as an accidental fallback to linker ad-hoc signing or a changed leaf fingerprint).
- Do not use workarounds: Never reset TCC permissions (
tccutil reset ...) or re-sign running agent binaries on production devices as a workaround. Investigate the binary's code requirement withcodesign -dr - /usr/local/bin/kanade-agentand verify CI release signing artifacts.
Key storage, validity, and rotation
- The private key
.p12must be archived securely. - Certificate expiry must be tracked. Rotating the certificate changes the leaf SHA-1, requiring
deploy/macos/signing-cert.sha1updates and re-granting permissions across all managed machines. - The self-update mechanism (
crates/kanade-agent/src/self_update.rs) copies downloaded Mach-O binaries verbatim and only alters permissions bits (0o755). Nothing on the client device strips or re-signs the executable.
Kata template integration
.github/workflows/release.ymlis kata-managed. The missing-hook guard, the post-buildsignhook and the post-packageverify-disthook callingscripts/ci/release-post-build.share part of the upstream release templates (yukimemi/pj-rust-workspaceandyukimemi/pj-rust-cli), and the workspace revision recorded in.kata/applied.tomlincludes them, sokata applyregenerates them instead of removing them.crates/kanade-shared/tests/check_release_signing.rsstill asserts the guard and the sign → package → verify → upload order, so a future template change that drops the integration fails CI.
macOS remote viewing (phase 1)
ブラウザーの Remote Screen は、ログインユーザーの 主ディスプレイのみ を macOS 14 Sonoma 以降 で表示できます。リリース配布とインストーラの対応は Apple Silicon のみです。キャプチャ実装には Intel 用コードもありますが、Intel エージェントの配備をサポートするという意味ではありません。ScreenCaptureKit の SCScreenshotManager を使い、非推奨の CGDisplayCreateImage API は使いません。古い macOS エージェントは他の操作を継続できますが、リモート表示は未対応と報告します。
Sessions are strictly read-only: no Accessibility permission is needed, no input subject is subscribed, and requests enabling input or selecting a secondary display are refused. The backend's existing operator role, Remote feature, PC access and audit consent checks still apply.
Deployment and permission
Update both backend and agent. Use the normal installed agent executable and LaunchDaemon service, with an executable path and parent directories traversable by the console user. A daemon running as root cannot capture the desktop itself: it starts the same installed executable with --session-capture, through launchctl asuser and sudo -n -u (run_as: user). The child receives a fresh explicit user environment, never daemon credentials. A non-root development agent may capture only when it is the current console owner. No logged-in user means a refused session, not a silent capture of the login window.
The root LaunchDaemon checks the console user at startup and every five seconds, independently of viewers, jobs and broker connectivity. An already signed-in user is handled at startup; login and user switching launch a short-lived --screen-permission-check <uid> helper in the foreground user's GUI session. It uses the same installed executable and user-session launch builder as capture. The helper only checks permission: it never captures or transmits pixels.
If CGPreflightScreenCaptureAccess reports access, the helper exits silently. Otherwise, after the daemon durably records request intent, it calls CGRequestScreenCaptureAccess so macOS can offer its system permission flow and Settings registration where supported. The exact dialog, Settings entry and TCC responsible executable remain unverified on an installed signed agent; the shared launch route alone does not prove attribution.
On the target Mac, as the logged-in user:
- Follow the system permission flow to System Settings → Privacy & Security → Screen Recording, or Screen & System Audio Recording on newer versions. If no dialog appears, open that pane directly. A prior denial does not imply macOS will prompt again.
- Enable the entry macOS identifies for the installed capture context. Verify its actual executable/signing identity; do not assume a matching display name proves attribution. The request is intended to avoid manual
+file selection where the OS supports registration; record any OS limitation during acceptance. - Stop and reconnect the browser viewer to create a fresh capture child. If it still reports missing permission, restart the installed agent service and reconnect. Honor any macOS restart instruction.
試行はセッションと、UID・導入パス・署名 identity ごとの永続履歴で重複を抑制します。要求前の失敗は 60 秒、10 分、1 時間、その後は最大 6 時間の永続 backoff で再試行し、有限の試行回数上限はありません。要求 intent を記録した後は、拒否やクラッシュ、サービス再起動後も再要求しません。ログアウト、ユーザー切替、30 秒の timeout で helper を停止しますが、OS ダイアログは残る場合があります。通常のエージェント処理は継続します。再要求のために履歴を削除しないでください。Kanade は権限を付与したり TCC 同意を変更したりできません。TCC の対象は起動経路に依存するため、OS が示す実際の項目を確認してください。Terminal への許可だけでは LaunchDaemon 経路の確認になりません。リリース向けには 安定したコード署名手順 を参照してください。ad-hoc 開発ビルドや identity / パス変更には再許可が必要な場合があります。拒否の回避目的で署名 identity、entitlement、プライバシー DB を変更しないでください。
A capability in fresh ping/heartbeat replies distinguishes supported from unsupported agents. It describes implementation/OS support, not permission or a currently usable desktop. Older agents omit it: the backend attempts Start rather than guessing. A missing remote responder can mean an older/unsupported agent or a connection problem; it does not prove the agent is offline.
Lifecycle and limits
The agent accepts Start only after the first valid JPEG tile, with an 8-second initialization deadline (below NATS's 10-second request default and the backend's 15-second start deadline). Enumeration and screenshot operations each have a 3-second native timeout. Initialization errors return the actual permission, missing-user/display or capture failure reason. Repeated Start with the same ID is idempotent; a different session cannot take over. Stop must name the owning session and is idempotent after shutdown.
Capture polls full screenshots at up to 10 fps, using the existing BGRA-to-JPEG encoder, horizontal tile splitting, payload limits, NATS frame headers and browser canvas. Framework image dimensions are used for actual transmitted geometry; pixels are copied into owned tightly packed BGRA storage rather than assuming a framework row stride. A static desktop still emits snapshots. This costs more bandwidth/CPU than Windows dirty rectangles; the requested fps is a ceiling.
Stop, viewer disconnect, initialization failure, child exit, stream timeout, publish failure and loss of the control subscription release the child. A stdin lifetime pipe also stops capture if the daemon dies, even on a static screen. The parent kills/reaps the dedicated child process group; an old publisher's completion cannot clear a replacement session. Runtime capture failure appears as a screen-unavailable gap with a reason: stop and reconnect.
No multiple-display selection, input control, Retina/native-pixel refinements, HDR fidelity guarantees or broad lock/sleep/display-change recovery are included. Protected content may be blank. Logout/user switch ends capture; reconnect in the new logged-in session. Headless or locked/unavailable desktops are not promised to work. Native SDK compilation requires Xcode Command Line Tools with a macOS 14+ SDK; the bridge is embedded in the agent, with no separately installed helper or Swift runtime requirement.
Manual acceptance procedure
Use a test Mac with a visible logged-in desktop, the installed signed agent and a backend connected to the same broker. Do not treat a development-shell test as proof of installed TCC behavior.
First run the installed signed-agent onboarding acceptance procedure. It covers startup before/after login without viewers or jobs, the actual dialog, exact Settings entry and responsible executable, denial/pending-dialog deduplication, user switching, grant persistence and later viewing through the normal capture path. Use fresh test accounts without resetting or altering TCC. A Terminal grant or Files and Folders entry does not prove Screen Recording authorization. Record unverified attribution explicitly; no live acceptance has been performed.
- With Screen Recording denied for the installed capture context, connect from an authorized operator account and accept the audit notice. Expect a refusal describing Settings, console user, permission target, restart and reconnect. Other agent operations/ping should still work.
- Enable permission through the OS flow above, reconnect, and record whether a service restart is additionally needed. Confirm a changing clock, a moving window and text in all four corners appear right-side up with correct colors and no padded/corrupted rows. Check the reported size matches the canvas; test a noisy full-screen image to exercise tile splitting.
- Confirm mouse/keyboard activity in the browser does not control the Mac. On a test broker/control client, Start with
allow_input: trueoroutput_index: 1must be refused without launching capture. - Open a second viewer: it must be refused while the first holds the display. Close/Stop the first, then reconnect the second. Retry Start/Stop with the same session ID, and send a Stop naming a different ID: it must not disrupt the owner. Repeat connect/disconnect and check Activity Monitor for orphaned
--session-capturechildren or continuing CPU use. - On a static desktop, terminate the capture child, then kill/restart the agent service separately. Expect an unavailable reason after child failure, no orphan after parent failure, and successful reconnect after restarting. Log out/switch users: no pixels from another user's session should leak; reconnect only after login and permission checks succeed for that user.
- Check a pre-14 Mac or another unsupported platform reports unsupported. Check an older agent without capability reporting still attempts Start and gives a responder/version/support/connection explanation when no subscriber exists. Disconnect an agent from NATS and verify the UI does not assert that every missing responder means offline.
- Verify viewer-only accounts, accounts lacking the Remote feature or target PC access, and sockets without audit consent remain refused. Run the Windows viewer smoke test to check DXGI capture and reconnect behavior are unchanged.
Automated tests cover protocol compatibility, framing/JPEG tile splitting, read-only/output refusal, startup failure and session ownership/cleanup. They do not establish desktop capture quality, TCC attribution/grant persistence, the installed LaunchDaemon launch chain, logout or sleep/lock behavior. Record the OS, signing/deployment route and results of the steps above before rollout.
ブローカーのサイジングとスケーリング
kanade は単一の NATS + JetStream ブローカーの上で動きます。フリートが大きくなる (数百台 → 数千台) と、スケーリングのボトルネックになるのはエージェントではなくブローカーです。このページでは、エージェント1台あたりのフットプリント、#512 の作業で何が変わったか、単一ノードで注意すべき限界、そしてスケールアップ中に実測値を採取して起動スプレイを入れるかブローカーを増強/クラスタ化するかを判断する方法を扱います。
エージェント1台あたりの consumer フットプリント
稼働中のエージェントはそれぞれ JetStream の consumer をいくつか保持します。KV watch ごとに ordered push consumer が1つ、それに加えてコマンド再生用の durable consumer が1つです:
| Consumer | 由来 |
|---|---|
agent_config watch (キーで絞り込み) | config_supervisor |
agent_groups watch (所属 → 実効 config) | config_supervisor |
agent_groups watch (所属 → 購読) | groups.rs |
schedules watch | local_scheduler |
jobs watch | local_scheduler |
fleet_config の freeze watch (単一キー) | local_scheduler |
EXEC durable replay | command_replay |
つまりエージェント1台あたり約7 consumerです。この数はエージェントごとにほぼ固定で、キーで絞り込んでも減りません。したがってブローカー側の総数はフリートに比例して増えます:
| フリート規模 | ブローカー上の consumer 数 (概算) |
|---|---|
| 15 | 約 105 |
| 500 | 約 3,500 |
| 3,000 | 約 21,000 |
v0.43.96 で変わったこと (と変わらなかったこと)
#512 (v0.43.96 で出荷) が叩いたのは超線形のコストであって、consumer の数ではありません:
#832—agent_configのキー絞り込み watch。 エージェントはバケット全体 (watch_all) ではなく、global、pcs.<self>、自分のgroups.<g>だけを watch します。これで2つの爆発が消えます:- PC 単位の書き込みファンアウト:
pcs.<id>1件への書き込みが全 N エージェントに届かなくなりました (以前は届いていて、N−1 台が分類しては捨てていました)。 - 再接続時の再同期ストーム: 再同期はバケット全体に対する
keys()+ キーごとの走査ではなく、エージェントあたり 3〜5 回の直接getになりました。総計で O(N²) → O(N) です。
- PC 単位の書き込みファンアウト:
#839— 単一キーの freeze watch。fleet_configはKEY_FREEZEしか持たないので、freeze の watcher はwatch_all+ クライアント側フィルタではなくwatch(KEY_FREEZE)を使います。
変わっていないのは、エージェント1台あたり約7 consumer というフットプリントと、schedules / jobs の watch_all です (これらは全エージェントがターゲティング判定のために評価する共有カタログで、無くすにはサーバー側ターゲティングという別の変更が要ります)。したがって 3,000 台では依然として約 21,000 consumer と、同期した再接続による接続/consumer 作成のバーストを見込んでおく必要があります。
単一ノードの限界と再接続の群れ
単一ノードの JetStream でサイジングすべきものは2つです:
-
定常状態のフットプリント — 3,000 台での約 21,000 consumer は JetStream のメタ (Raft) 層に載り、メモリとファイルハンドルを消費します。目標 N に合わせてブローカーホストの RAM と JetStream の
max_file/max_memoryを設定し、メタ層の健全性を監視してください。 -
再接続の群れ (herd) — 多数のエージェントが_同一の瞬間に_再接続すると (ブローカー再起動、朝の電源投入の波、多数の PC を巻き込むネットワーク事象)、接続を張り直して consumer をバースト的に作り直します。キー絞り込みによって各エージェントの再同期はすでに数回の安価な
getまで落ちているので、危険な O(N²) の読み込みストームは消えています。ただし接続 + consumer 作成のバーストは依然として O(N) で、しかも同期しています。なお、ランダムで_同期していない_再接続 (ノート PC 1台の wifi 瞬断) は群れではありません。群れになるのはフリート全体が同期した事象だけです。
ストレージ: 50 GB のファイルストア、リソース単位の上限、保持期間
RAM と consumer はサイジングの話の半分にすぎず、もう半分はディスクです。JetStream のデータはすべて1つのディレクトリ (store_dir: C:/ProgramData/Kanade/nats/jetstream) の下に置かれ、ブローカー全体として max_file_store: 50GB (configs/nats-server.conf) で制限されます。これは全ストリームと全オブジェクトストアで共有されるソフト上限であって、ストリーム単位のものではありません。埋まっていくと何が起きるか:
- 自前の保持設定を持つリソースは古いものから退避し (
DiscardPolicy::Old)、健全なままです。 - 上限を持たないリソースは退避できません。そのためファイルストアが一杯になると、フリート全体で_あらゆる_ JetStream publish が「insufficient storage resources available」(エラー 10077) で失敗し始めます — エージェントの結果アップロード、collect バンドルのアップロード、publish、KV put。読み取りは動き続け、死ぬのは書き込み側です。上限の無いリソースは、上限のあるリソースの取り分も押しのけます。
したがって全リソースが上限を持たねばならず、実際に持っています:
-
ストリーム (
RESULTS/INVENTORY/AUDIT/OBS_EVENTS/NOTIFICATIONS/EXEC/EVENTS) はそれぞれmax_ageとmax_bytesを持ちます (bootstrap.rs、合計で約 5.3 GiB を確保)。これらは転送 + 再生のバッファであり、永続的な記録はバックエンドの SQLite です。運用者が見たいと思う履歴より上限を短く取れるのはそのためです。 -
オブジェクトストアはバケットごとに
max_bytesで制限され、SPA から再起動なしで変更できます (設定 → server → オブジェクトストアのディスク上限、#1247)。空欄にすると以下の組み込み既定値に戻ります:バケット 既定の上限 格納するもの result_output1,024 MiB 大きすぎる stdout/stderr の blob (数秒で SQLite に投影されます) agent_releases2,048 MiB エージェントの実行ファイル (約20バージョン) app_packages5,120 MiB 運用者が用意したインストーラ scripts256 MiB マニフェストのスクリプト本体 collections5,120 MiB collect ジョブのバンドル ( max_ageもあり、収集バンドルの保持期間 で変更できます)バックエンドは設定値を裏側の
OBJ_*ストリームへ起動のたびと保存のたびに反映します。上限が導入される前に作られたバケットにも上限が行き渡るのはこの仕組みによります。既定の合計確保量は約 13.5 GiB で、ストリームと合わせて 50 GB に十分収まるよう設計されています。 -
Recovery. If a stream or bucket has drifted from its expected config or is corrupted, repair it with the
natsCLI and an administrative credential, not withkanade. The backend recreates anything missing the next time it starts. This works even when the backend cannot start (a drifted stream config makes its startup bootstrap fail), because the scripts talk to the broker directly. Stopkanade-backendfirst (its projectors hold durable consumers) and start it again afterwards:# delete one stream / KV bucket / object store (asks you to type the name) ./scripts/ops/jetstream-delete.ps1 -Kind stream -Name RESULTS -Server nats://127.0.0.1:4222 -Creds ./admin.creds # wipe everything kanade uses: dry run first, then add -Yes ./scripts/ops/jetstream-reset.ps1 -Server nats://127.0.0.1:4222 -Creds ./admin.creds ./scripts/ops/jetstream-reset.ps1 -Server nats://127.0.0.1:4222 -Creds ./admin.creds -YesBoth need the
natsCLI onPATHand also readNATS_URL,NATS_CREDS,NATS_USERandNATS_PASSWORD. Deleting a resource deletes its data. -
SQLite (投影) も_無制限ではありません_。バックエンドのクリーンアップタスクが5分ごとに、区切られたバッチで刈り取ります —
execution_results/executions/obs_events/inventory_historyが 90 日、audit_logが 365 日、host_perf_samplesが 30 日、process_perf_samplesが 7 日です。どの DB の窓も、対応するストリームの窓より意図的に長く取ってあります。ストリームが再生できるものは必ず SQLite に既にある、ということです。残りのテーブルは upsert/replace 型 (現在の状態ぶんの大きさ) で、死んだエージェントはagent_prune_days(これも ServerSettings のノブ) で刈られます。
リソースごとの実使用量 (使用バイト数と上限) は SPA の JetStream ページにあります。ブローカーの現在の設定を読むので、上限を変えると次回の読み込みで反映されます。
打ち手 (優先順)
- まずブローカーのサイジング。 目標 N での定常 consumer 数を賄えるだけの RAM とファイル上限を、この単一ノードに与えてください。これが主たる打ち手で、他はすべて副次的です。
- 起動スプレイ — 実測したときだけ。 再接続の再同期の前に PC ごとの決定的な遅延 (
hash(pc_id)) を入れれば、consumer 作成と接続のバーストを一定の窓に均せます。これは設計判断としてまだ製品に入っていません。PR1 ですでに二次の項は消えており、async-nats の再接続バックオフとnats_retryの ±25% ジッタがある程度はバーストを散らしているからです。またスプレイは、群れではない単発の瞬断も含めてすべての再接続に遅延を足すので、実際に群れがブローカーを苦しめていないかぎり差し引きで損になります。データで判断してください (次節)。同期した事象で consumer 作成の遅延、接続の滞留、JetStream API のエラーが見えたなら、スプレイを入れます (Disconnected → Connected後の最初の同期だけに限定し、数秒で頭打ちにします)。 - エージェントあたりの consumer を減らす。 可能なら watch をまとめ (freeze watch はすでに単一キー、2本の
agent_groupswatch は統合の候補)、KV の履歴は浅く保ちます (agent_config/agent_groupsはhistory: 1)。 - JetStream をクラスタ化する。 1ノードで抱えられる量を超えたら、JetStream クラスタへ移ります。これが最後の手段であり、最も大きな変更です。
規模での実測 (事後分析)
本番のブローカーを立ち上がりの最中にライブで眺めるのは、たいてい無理です。代わりに同梱の collect: ジョブで数値を採取し、あとからバンドルを見てください。
バックエンド / NATS のホスト上で、できれば同期した再接続事象の最中か直後に実行します (スプレイの是非を決めるのは群れの瞬間です):
kanade exec collect-broker-health --pcs <backend-host-id>
このジョブ (configs/jobs/collect-broker-health.yaml) はブローカーを約3分にわたってサンプリングし、バンドルを OBJECT_COLLECTIONS にアップロードします。SPA の 収集 ページからダウンロードしてください (zip をそのままレビュー担当に渡しても構いません)。読み取り専用で、事前準備は一切不要です。NATS の認証なしの HTTP monitoring ポート (既定 8222 の /jsz エンドポイント) を読むだけなので、SYSTEM の PATH に nats CLI を置く必要も、トークンも要りません。必要なら対象側で KANADE_BH_SAMPLES / KANADE_BH_INTERVAL_SEC (ブローカーの http_port が違う場合は KANADE_BH_MON_PORT も) で窓を調整できます。
バンドルの内容:
- 時系列 (
connz-*.json、jsz-*.json) — サンプルごとの接続数 (/connz) と JetStream の consumer 数 (/jsz)。群れの瞬間にここが跳ねていれば、それがスプレイの signal です。 - consumer フットプリント (
jsz-full.json) —/jsz?consumers=true&streams=true。consumer の全リストで、合計が約 7N であることと、どのストリームが抱えているかを確認できます。 - サーバーの健全性/リソース (
varz.json、healthz.json) —/varz(メモリ、CPU、接続数、slow consumer) と/healthzの状態。 - ログの末尾 (秘匿情報は伏せ済み) — backend と nats-server。
何を見るか
- サンプルを通して consumer/接続数がなめらかで、
/healthzが健全、/varzのメモリ/CPU に余裕がある → ブローカーはその事象を吸収できています。スプレイは不要で、N に先回りしてサイジングを続けるだけです。 - 事象の時点で接続の滞留や consumer 作成の遅延がとがっている、JetStream API がエラーを返す、メモリ/CPU が張り付く → 群れは実在します → 起動スプレイ (打ち手2) を入れる、あるいはブローカーを増強します。
#828のダウングレード・フラッピングの回帰は、このジョブではなくOBS_EVENTSのagent_updateタイムラインから (バックエンド API 経由で) 別途確認します。そのデータはすでにフリート全体に対して問い合わせ可能です。
agent 向けスクリプトを書く
agent が実行する PowerShell スクリプトは ほぼ 通常の .ps1 ファイルです。このページは、スクリプトのソースを見るだけでは分からない罠をまとめます。
agent はスクリプトをディスクに staging してから -File で実行する
PR #230 (agent version 0.42.0+) 以降、agent は次の動作をします:
- スクリプト本体を temp の
.ps1に書き出します。Windows なら%ProgramData%\Kanade\agent-scripts\<UUID>\kanade-<UUID>.ps1、それ以外 (dev のみ) なら$TMPDIR/kanade-agent-<UUID>/kanade-<UUID>.ps1。 - Writes a launcher
.ps1next to it that sets UTF-8 console encoding then& '<your-script>' @args, and re-raises your script'sexit N/ terminating error as the job's exit code (if (-not $?) { exit $LASTEXITCODE }). powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File <launcher>を spawn します。
結果として、あなたのスクリプトでは:
- 先頭に
[CmdletBinding()]やparam(...)を 書けます。launcher の call-operator 境界が独自スコープを生み、その中ではヘッダーが有効です。 $PSCommandPathが operator のソースパスと一致することを 期待しないでください — staged 後の temp ファイルパスになります。$PSScriptRootに 書き込まないでください (次節参照)。
0.42.0 より前のエージェントは powershell -Command "<body>" を使っており、これは本文をコマンドライン式として解析するため [CmdletBinding()] を構文エラーとして弾きます。stderr に「Unexpected token '[CmdletBinding()]'」が出ていたら、その端末のエージェントが古すぎます。更新してください (エージェントの自己更新 を参照)。
run_as: user のとき $PSScriptRoot は読み取り専用
run_as: user (または system_gui) のとき、子プロセスはログオン中のユーザーとして動きます — staged ファイルを書いた LocalSystem の agent ではありません。staging ディレクトリは %ProgramData% から ACL を継承していて、Users には Read & Execute は許可されるが Modify は許可されません。
つまり:
# OK from any run_as
Get-ChildItem $PSScriptRoot # list contents
Get-Content $PSScriptRoot\anything # read
# NG from run_as: user (access denied)
New-Item -Path $PSScriptRoot\out.txt
Set-Content -Path $PSScriptRoot\log.log
代わりに $env:TEMP、$env:LOCALAPPDATA、ユーザープロファイル配下の絶対パスのいずれかに書いてください。run_as: system (SYSTEM が自分の staged dir に書ける) であっても、スクリプト終了時にディレクトリは掃除されるので、隣接ファイル書き込みはいずれにせよ壊れやすいです。
実行 identity 一覧
run_as: (マニフェスト) | 子プロセスの identity | $PSScriptRoot を読める | $PSScriptRoot に書ける | admin 権限あり |
|---|---|---|---|---|
system (デフォルト) | LocalSystem | ✓ | ✓ (ただし無意味、GC される) | はい |
user | ログオン中のユーザー | ✓ | ✗ access denied | いいえ |
system_gui | LocalSystem (ユーザーセッション内) | ✓ | ✓ (ただし無意味、GC される) | はい |
system_gui は「PsExec の -i -s」パターンです。管理者権限を持ちつつ、ユーザーのデスクトップセッションから見える形で動きます (昇格と対話ウィンドウの両方を必要とする GUI ツールに有用です)。
stdout vs Write-Host
The backend's result projector reads stdout as the script's output. For jobs with hint blocks (inventory:, check:, collect:, etc.), the projector extracts JSON payloads delimited by #KANADE-<KIND>-BEGIN and #KANADE-<KIND>-END fences (e.g. #KANADE-INVENTORY-BEGIN / #KANADE-INVENTORY-END).
For single-hint jobs without fences, backward compatibility allows parsing the entire stdout as a single JSON object. However, for multi-hint jobs (e.g. combining inventory: and check:), fenced blocks are required so each hint handler can extract its respective payload.
Do NOT use Write-Host for progress chatter. Write-Host output bleeds INTO the captured stdout stream, which can mess up unfenced JSON parsing or clutter log output.
Send progress chatter to stderr via [Console]::Error.WriteLine(...). stderr is captured into the result's separate stderr field, which the projector ignores.
[Console]::Error.WriteLine("Downloading...") # → stderr (logged, ignored by projector)
Write-Output "#KANADE-INVENTORY-BEGIN"
Write-Output ($obj | ConvertTo-Json -Compress)
Write-Output "#KANADE-INVENTORY-END"
Fencing stdout payloads ensures clean extraction even if other output is present, and allows a single job script to provide inventory facts, health check state, and file collection metadata in a single run (#821). See configs/jobs/installers/scripts/install-kanade-client.ps1 for a worked example.
デフォルトで UTF-8
launcher はスクリプト起動前に [Console]::OutputEncoding = UTF-8 と $OutputEncoding = UTF-8 を設定するので、ホストのシステムコードページに関係なくあなたの stdout / stderr は UTF-8 になります。日本語 / DE / KR / CN を含む operator スクリプトも、ホスト個別の workaround なしに SPA Activity ビューで正しく表示されます。
明示的に OEM / CP932 / Shift-JIS 出力が必要なら ($OutputEncoding を無視する legacy CLI を呼ぶケースなど)、launcher の prelude が走ったあとにスクリプト内で自分で設定してください — あなたの代入が優先されます。
ネイティブコマンドの exit code
スクリプトが成功した native コマンドで終わると全体の exit は 0 — これは PowerShell のデフォルトです。native コマンドが失敗 ($LASTEXITCODE -ne 0) してハンドリングしないと、PowerShell は依然として 0 で終了します — $ErrorActionPreference = 'Stop' は 救ってくれません。
Windows PowerShell 5.1 (Windows エンドポイントのデフォルト、agent の
powershell.exeが解決する先) は$ErrorActionPreferenceに関わらず native コマンドの非ゼロ exit を non-terminating として扱います。PowerShell 7.3+ で$PSNativeCommandUseErrorActionPreference = $trueが追加されてこれを terminating にできますが、デプロイターゲットでは使えません。必ず$LASTEXITCODEを明示的にチェックしてください。
The agent does NOT auto-propagate a leftover $LASTEXITCODE — that would exit nonzero even when your script handled the native error gracefully. The launcher only re-raises an explicit exit N or a terminating error, so the job's exit code matches running your script with powershell -File. If you want the script's exit code to reflect a specific native call, propagate it yourself:
& git pull
if ($LASTEXITCODE -ne 0) { throw "git pull failed with exit code $LASTEXITCODE" }
# ネイティブの終了コードをそのまま伝播させたい場合は:
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
通常は throw のほうが望ましい — クリーンな PowerShell エラーレコードを生成し (trap { … break } クリーンアップパターンが捕まえられる) かつ非ゼロで終わるからです。exit $LASTEXITCODE は呼び出し側が正確な exit code を気にする場合に向きます。
タイムアウト
マニフェストの timeout: は agent によって適用されます。発火すると agent は PowerShell プロセスに child.kill() を呼びます — graceful な shutdown も trap も finally もありません。それを前提に設計してください:
- スクリプトが
timeout * 0.6で終わるように実行時間を見積もり、余裕を残す。 - 明示的解放が要るリソース (staging dir、lock ファイル) のクリーンアップには
trap { ... ; break }を使う —trapは terminating エラーで発火し、agent の kill では発火しません。timeout ケースには頼らないこと。 - 協調的なキャンセルが必要なら、番兵ファイルやレジストリ値をポーリングして早めに抜けてください。エージェントからスクリプトへ、穏当に「切り上げろ」と伝える手段はありません。
実行中ジョブの kill
kanade kill <exec_id> は agent が購読する kill メッセージを publish します。受信すると agent は child.kill() を呼びます — timeout 経路と同じ hard-kill。operator にはただちに Killed マークの result row が届き、終了前に agent がキャプチャできた stdout / stderr が付きます。
開発者ワークフローとコントリビューション
このドキュメントでは、kanade コードベースで作業するコントリビューター向けの標準的な開発ワークフロー、lint/テストの要件、および VCS ブランチのガイドラインについて説明します。
1. クオリティゲート (Pre-Push & CI)
プッシュや PR の送信を行う前に、ローカルのテストスイートがすべてグリーンである必要があります。これは GitHub Actions で実行される自動チェックと同じものです。
# フォーマットチェック、clippy チェック、ターゲットテスト、および cargo ロックチェックを実行します
cargo make check
- FMT & Clippy: 私たちは厳格なゼロワーニングポリシーを維持しています。強力な設計上の正当な理由がない限り、
#[allow(clippy::...)]を散布しないでください。 - TDD (テスト駆動開発): Kent Beck の TDD 手法に従ってください。最初に失敗するテストを書いて「何を」行うかを定義し、次にそれを満たすコードを実装します。
2. renri によるワークツリー管理
隔離された機能開発のために、私たちは renri を使用して軽量なリポジトリワークツリーを管理します。これにより、ステージの汚染を防ぎ、メインチェックアウトをクリーンに保ち、瞬時にタスクを切り替えることができます。
なぜ renri なのか?
Git と Jujutsu (jj) がコロケーションされた環境では、ワークツリーを手動で管理するのは複雑になります。renri は、VCS 固有のワークツリー作成(設定されている場合は jj を優先)とクリーンアップを自動的にラッピングすることで、これを簡素化します。
よく使うコマンド
# 隔離されたワークツリーを作成します (存在するならデフォルトで Jujutsu を使用)
renri add feat/your-awesome-feature --from main@origin
# Git ネイティブのワークツリーを強制的に作成します (jj をバイパス)
renri --vcs git add feat/your-awesome-feature --from origin/main
# マージ後にワークツリーをクリーンアップして削除します
renri remove feat/your-awesome-feature -y --non-interactive
# 古くなった、または破損したワークツリーをガベージコレクションしてクリーンアップします
renri prune
注意: ワークツリー作成時に自動的に cargo-make の on-add フックが呼び出され、リモートの参照を取得して APM 設定を直ちにセットアップします。
3. コロケーションされた Jujutsu (jj) & Git ワークフロー
開発環境は、Git と Jujutsu がコロケーションされるよう設定されています。ローカルのバージョン管理には、安全で競合のないコミットモデルを持つ jj を好んで使用します。
ガイドライン
mainへの直接プッシュ禁止: すべての変更は Pull Request 経由でマージされる必要があります。- ブランチ/ブックマークの命名規則:
feat/...は新機能用。fix/...はバグ修正用。chore/...はインフラ、依存関係の更新、またはリリース用。
- コミットメッセージ: コミットメッセージ、PR タイトル、本文は英語で記述してください。
- バージョン更新: リリースのバージョン更新は、
mainへの PR と自動タグ付けパイプラインを介してのみ管理されます。手動でgit tagを実行しないでください。
4. ドキュメントポリシー
ドキュメントは、コードの変更と常に完全に同期している必要があります。機能を追加または変更した場合は常に、以下を実行してください:
- コード内のコメントや docstring を更新し、「なぜ」そのようにしたのかを説明します(「どのように」やっているかを単に再記述するコメントは避けてください)。
- 関連する book ページ(
book/src/配下に英語で記述)を更新します。 - 翻訳テンプレートジェネレーターを実行して、ローカライズカタログ(ポファイル)を同期します。
仕様 (旧 single-page)
フルのプロトコル / on-wire 仕様はまだ book に取り込まれていません。オーソリティはリポジトリの single-file 版です:
このセクション配下に章分割するのは、operator / 開発者ガイドが落ち着いてからの follow-up とします。
設定リファレンス
kanade サービスは、TOML ファイル、環境変数、またはレジストリパスから読み込まれる構造化された設定に依存しています。
1. エージェント設定
両サービスの設定探索順は --config <path>、空でない KANADE_AGENT_CONFIG / KANADE_BACKEND_CONFIG、存在する標準ファイルの順です(Windows は %ProgramData%\Kanade\config\agent.toml / backend.toml、Unix は /etc/kanade/agent.toml / backend.toml)。作業ディレクトリへの fallback や既定設定の自動生成はなく、設定がなければエラーです。TOML は teravars テンプレートなので、環境変数が項目を変えるのはテンプレートが明示的に参照した場合のみです。
開発用設定 (configs/agent.dev.toml)
[vars]
hostname = '{{ system.host }}'
pc_id = '{{ env(name="KANADE_DEV_AGENT_ID", default=vars.hostname) }}'
[agent]
id = '{{ vars.pc_id }}'
nats_url = 'nats://127.0.0.1:4223'
[log]
path = './target/dev-data/agents/{{ vars.pc_id }}/agent.log'
level = 'info'
設定パラメータ
| フィールド | 型 | 説明 |
|---|---|---|
agent.id | String | 大文字小文字を区別する正確なホスト識別子 (pc_id) です。ハードウェア UUID ではありません。開発テンプレートは KANADE_DEV_AGENT_ID を受け付けます。 |
agent.nats_url | String | ブローカーのアドレス。KANADE_NATS_URL は CLI の --server を指定するもので、このサービス設定項目を上書きしません。 |
log.level | String | ログフィルター。RUST_LOG が上書きします。 |
log.path | Path | 日次ローテーションするログの出力先。 |
log.keep_days | 整数 | 当日を含む日次ファイルの保持数。既定は 14、0 はファイルへのログ出力を無効にします。 |
データディレクトリは TOML の項目ではありません。KANADE_AGENT_DATA_DIR が Windows の %ProgramData%\Kanade\data または Unix の /var/lib/kanade を上書きします。Linux / macOS の setup スクリプトは明示的に /var/lib/kanade-agent を使います。
Per-PC job concurrency
max_local_concurrent lives in the layered agent_config store, not the agent TOML file. It applies to backend schedules, agent-local schedules, and operator runs from the CLI or administration SPA. One agent shares a single budget across these paths. User-triggered kanade-client actions are exempt: they start without waiting for or consuming a slot. They do not interrupt jobs already running.
When no scope sets the limit, the agent uses its locally available logical CPU count (falling back to 1 if detection fails). The backend leaves this automatic value as null; it never substitutes the backend host's CPU count. An explicit limit must be an integer of at least 1. Scopes apply in order: built-in automatic default → global → groups → PC.
kanade config set max_local_concurrent=4
kanade config set --group low-power max_local_concurrent=2
kanade config set --pc EXACT-HOSTNAME max_local_concurrent=1
kanade config unset --pc EXACT-HOSTNAME max_local_concurrent
kanade config (get, set, unset, clear, effective) talks to the backend HTTP API, not to NATS: it needs KANADE_AUTH_TOKEN (an operator-role token to change anything, like the other HTTP subcommands) and no broker token. Automation that calls kanade config must therefore authenticate with an auth token. The backend does each set / unset as a compare-and-swap on that one field, so a concurrent rollout writing target_version on the same scope is not overwritten, and a request that would change nothing writes nothing. Each change is recorded in the audit log under the caller's account; the audit entry is published after the write and is best-effort, not atomic with it. effective prints the backend's resolved view; its warnings are the backend's rendered text.
unset restores inheritance; when all applicable scopes omit the field, CPU-based sizing resumes. Updates apply without restarting the agent. Reducing the limit lets existing jobs finish and holds new jobs until enough slots are free. A job keeps its slot through retries, collection and finalize. Jitter happens before admission. Queued jobs can be killed and are skipped if their starting deadline expires. Waiting does not consume the script timeout or emit a running lifecycle event. Execution gates (version pin, revocation, staleness and deadline) are checked before jitter and again after admission.
Compatibility note: runs_on: agent schedules previously omitted their starting deadline from local commands. They now enforce starting_deadline from the local fire time, including jitter and slot waiting. Existing schedules whose jitter exceeds that deadline can therefore report a deadline skip even with a free slot. Keep the deadline longer than the maximum jitter plus the acceptable queue wait, or omit it when late execution is acceptable. Kill delivery is best effort: if the broker subscription fails, the agent logs a warning and continues waiting under the same capacity and deadline rules.
A critical job can opt out for every execution of that manifest:
execute:
shell: powershell
script: 'Write-Output "critical action"'
timeout: 30s
bypass_local_limit: true
Exempt jobs consume no slots, so total host concurrency can exceed the limit. The budget is agent-process-wide; it assumes one agent service per PC. constraints.max_concurrent remains a separate backend, fleet-wide per-job limit. This setting does not fix its jitter accounting issue (#1373).
2. バックエンド設定
バックエンドも上記と同じ探索順です。開発時は --config configs/backend.dev.toml を渡すか、cargo make backend-dev を使ってください。
開発用設定 (configs/backend.dev.toml)
[server]
bind = '127.0.0.1:8081'
[nats]
url = 'nats://127.0.0.1:4223'
[db]
sqlite_path = './target/dev-data/backend.db'
[log]
path = './target/dev-data/backend.log'
level = 'info'
設定パラメータ
| フィールド | 型 | 説明 |
|---|---|---|
server.bind | String | HTTP / WebSocket の待受アドレス。 |
server.public_url | 任意の文字列 | アカウントメール用の公開 SPA ベース URL。プロキシ経由の場合やリクエストヘッダー由来のリンク生成を避ける場合に設定してください。 |
nats.url | String | ブローカーのアドレス。 |
nats.monitor_url | 任意の文字列 | 監視エンドポイントのベース URL。既定はブローカーホストの HTTP、ポート 8222 です。 |
db.sqlite_path | Path | SQLite ファイルのパス。 |
log.path, log.level, log.keep_days | エージェントと同じログ設定項目。 |
KANADE_BIND_ADDR、DATABASE_URL、KANADE_NATS_URL はこれらのサービス設定を上書きしません。認証設定は [auth] TOML セクションではありません。KANADE_AUTH_DISABLE は値に関係なく存在するだけで認証を無効にします(0 でも無効化)。開発専用です。本番では JwtSecret / KANADE_JWT_SECRET、StaticToken / KANADE_AUTH_STATIC_TOKEN、BootstrapAdminPassword / KANADE_BOOTSTRAP_ADMIN_PASSWORD などのバックエンド secret を使います。
SMTP 接続設定は [mail] TOML セクションではなく server_settings.mail(設定 → サーバー)にあり、バックエンド再起動後に反映されます。SMTP パスワードは別の MailPassword / KANADE_MAIL_PASSWORD secret のままです。
3. Windows レジストリ統合
本番の NATS トークンや管理 API bearer トークンなどは、ACL で保護された Windows レジストリ値に保存します。暗号化保存ではなく平文 REG_SZ です。Windows 以外では対応する環境変数を使います。
キーパス
- エージェント設定:
HKLM:\SOFTWARE\Kanade\agent - バックエンド設定:
HKLM:\SOFTWARE\Kanade\backend
導入スクリプトはレジストリの ACL を設定し、読み取りを SYSTEM と Administrators に制限します。
Passkeys (WebAuthn)
Passkeys are configured only in Operator Settings → Server Settings → Passkeys (the persisted server_settings KV document). There is no TOML setting. New installations default to disabled. An operator sets the RP ID, allowed origins (one per line), optional display name (default: Kanade), and explicitly enables passkeys. The update API uses nested per-field PATCH semantics: omission preserves a field, null clears it, and an origins array replaces the whole array. Invalid configurations are rejected before saving.
The RP ID must be a lowercase ASCII domain name without scheme, port or path. Origins must be HTTPS bare origins matching that domain or a subdomain; HTTP is accepted only for localhost. Values are never derived from request headers. Saving valid settings takes effect immediately, without restarting, on all backend instances. The settings card reports the effective enabled/disabled state and configuration/read failures. Each change invalidates outstanding registration and sign-in challenges, including a change back to an earlier RP. A ceremony's final authoritative settings read is its commit boundary: a settings write after that read applies to subsequent ceremonies.
Credential listing, removal and administrator reset remain available when passkey sign-in is disabled. Enrollment/removal still require the current password and, when enabled, TOTP. Password/TOTP sign-in and account recovery remain available. RP changes can make credentials registered under another RP unusable; register new credentials for the configured RP.
Configuration is shared across backends, but in-flight challenges remain in process memory. Route both steps of each ceremony to the same backend (sticky sessions); restarting that backend discards its outstanding challenges. Keep the backend behind a trusted proxy that appends the real client IP for throttling.










