diff --git a/README.md b/README.md index 00bb40a..10a708e 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ Bear 目前所有流程都依賴「瀏覽器」:登入 `/login`、儀表板 La | `bear token` | ✅ 已實作(印出 PAT;`--refresh` 為用法錯誤) | | `bear logout` | ✅ 已實作(清除本機憑證;PAT 需至網頁撤銷) | | `bear status` | ✅ 已實作(純本機判定,顯示 PAT/環境變數模式) | -| `bear apps` | ⏳ 待 #5 規格與 alterminal/bear#28 API 就緒後實作 | +| `bear apps` | ✅ 已實作(`list`/`show`/`create`/`update`/`rotate-secret`/`toggle`;issue #10,對接 alterminal/bear#28 的 `/api/v1/apps` JSON API,admin PAT 限定) | | `bear profile`/`password`/`email`/`sessions`/`tokens`/`mfa` | ⏳ 規格已納入 `docs/commands.md` §3.7(#11);待 alterminal/bear#35 API 就緒後實作 | ### 建置與執行 diff --git a/docs/commands.md b/docs/commands.md index 5a76600..7367f06 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -183,9 +183,9 @@ issuer:https://alterminal.com --- -### 3.6 `bear apps`:App 管理指令群(P3,規劃中) +### 3.6 `bear apps`:App 管理指令群(P3,已實作) -> 依賴:bear 伺服器端 **App 管理 JSON API**(alterminal/bear#28,資源前綴 `/api/v1/apps`,PAT Bearer 認證、管理操作限 admin)。API 落地前本節僅為規格。 +> 依賴:bear 伺服器端 **App 管理 JSON API**(alterminal/bear#28,資源前綴 `/api/v1/apps`,PAT Bearer 認證、管理操作限 admin)。API 已上線(PR alterminal/bear#29),本節指令群已實作(issue #10);`--visibility`/`--status` 過濾目前由 CLI 全量列舉後本地套用(伺服器 list 端點尚無對應查詢參數)。 `bear apps` 是「資源群組」指令:`bear apps <動詞>`。這是第 1 節「扁平結構」原則的首個例外——App 的管理操作(列表、檢視、建立、更新、輪轉 secret、啟停用)若攤平命名會造成指令名爆炸(`bear apps-create`…),故收斂為單一群組;未來同類資源管理指令比照。 @@ -612,7 +612,7 @@ TOTP 兩因子管理(WebAuthn/passkey 不在範圍)。 | `token` | refresh token 輪轉換新 | 直接印出 PAT;`--refresh` 為用法錯誤(退出碼 2);`BEAR_TOKEN` 提供時優先印出 | | `logout` | `POST /revoke`(撤銷 refresh token) | 僅清除本機憑證;PAT 需至網頁 `/profile/tokens` 撤銷 | | `status` | 顯示 access token 剩餘秒數 | 純本機判定:顯示模式(PAT/BEAR_TOKEN 環境變數)與 issuer | -| `apps` | P3 暫緩 | 未實作;App 管理指令規格見 #5,伺服器端 API 見 alterminal/bear#28 | +| `apps` | P3 暫緩 | ✅ 已實作(issue #10):`list`/`show`/`create`/`update`/`rotate-secret`/`toggle`,對接 alterminal/bear#28 的 `/api/v1/apps` JSON API(PAT Bearer、admin 限定)。`client_id` → UUID 由 CLI 以 list 解析;一次性 `client_secret` 僅於 create/rotate-secret 成功當下輸出 | | `profile`/`password`/`email`/`sessions`/`tokens`/`mfa` | P3 暫緩 | 未實作;個人自助指令規格見 #11(§3.7),伺服器端 API 見 alterminal/bear#35 | 退出碼差異:`login`/`whoami` 的 token 無效(401)依 §3.1 為 `3`(本節實作一致)。 diff --git a/lib/bear_cli/api.ex b/lib/bear_cli/api.ex index 4835783..bec7eb9 100644 --- a/lib/bear_cli/api.ex +++ b/lib/bear_cli/api.ex @@ -51,4 +51,89 @@ defmodule BearCli.Api do end defp error_description(_), do: "invalid_token" + + # -- App 管理 API(alterminal/bear#28;PAT Bearer、admin 限定)-- + + @doc """ + `GET /api/v1/apps`:列出 App(分頁)。 + + `params` 為 keyword(`page:`/`per_page:`,可加 `visibility:`/`status:` 過濾)。 + 成功回 `{:ok, %{"data" => [apps], "page" => n, "per_page" => n, "total" => n}}`。 + """ + def apps_list(issuer, token, params \\ []) do + apps_request(issuer, token, :get, "/api/v1/apps", params: params) + end + + @doc "`GET /api/v1/apps/{id}`:單一 App(`client_secret` 永不回傳)。" + def apps_get(issuer, token, id) do + apps_request(issuer, token, :get, "/api/v1/apps/" <> URI.encode(id)) + end + + @doc """ + `POST /api/v1/apps`:建立 App。`method=client_secret` 且未給 + `client_secret` 時由伺服器產生,成功回應內含一次性明文 + (`%{"data" => app, "client_secret" => secret}`)。 + """ + def apps_create(issuer, token, attrs) do + apps_request(issuer, token, :post, "/api/v1/apps", json: attrs) + end + + @doc "`PUT /api/v1/apps/{id}`:部分更新(只送有給的欄位)。" + def apps_update(issuer, token, id, attrs) do + apps_request(issuer, token, :put, "/api/v1/apps/" <> URI.encode(id), json: attrs) + end + + @doc """ + `POST /api/v1/apps/{id}/rotate-secret`:輪轉 client secret,回應內含 + 一次性明文。PKCE App 回 422 `%{"error" => "pkce_app"}`。 + """ + def apps_rotate_secret(issuer, token, id) do + apps_request(issuer, token, :post, "/api/v1/apps/" <> URI.encode(id) <> "/rotate-secret", + json: %{} + ) + end + + @doc "`POST /api/v1/apps/{id}/toggle`:切換 active ↔ inactive。" + def apps_toggle(issuer, token, id) do + apps_request(issuer, token, :post, "/api/v1/apps/" <> URI.encode(id) <> "/toggle", json: %{}) + end + + # App 管理 API 共用請求。回傳: + # {:ok, body} | {:error, :unauthorized, desc} | {:error, :forbidden, desc} + # | {:error, :not_found, desc} | {:error, :unprocessable_entity, body} + # | {:error, :server_error, status} | {:error, :network, reason} + defp apps_request(issuer, token, method, path, extra \\ []) do + url = String.trim_trailing(issuer, "/") <> path + + opts = + [ + headers: [authorization: "Bearer " <> token, accept: "application/json"], + retry: false, + finch: [name: @finch] + ] + |> Keyword.merge(extra) + + case apply(Req, method, [url, opts]) do + {:ok, %Req.Response{status: status, body: body}} when status in 200..299 -> + {:ok, decode_body(body)} + + {:ok, %Req.Response{status: 401, body: body}} -> + {:error, :unauthorized, error_description(decode_body(body))} + + {:ok, %Req.Response{status: 403, body: body}} -> + {:error, :forbidden, error_description(decode_body(body))} + + {:ok, %Req.Response{status: 404, body: body}} -> + {:error, :not_found, error_description(decode_body(body))} + + {:ok, %Req.Response{status: 422, body: body}} -> + {:error, :unprocessable_entity, decode_body(body)} + + {:ok, %Req.Response{status: status}} -> + {:error, :server_error, status} + + {:error, exception} -> + {:error, :network, Exception.message(exception)} + end + end end diff --git a/lib/bear_cli/apps.ex b/lib/bear_cli/apps.ex new file mode 100644 index 0000000..015d9d3 --- /dev/null +++ b/lib/bear_cli/apps.ex @@ -0,0 +1,446 @@ +defmodule BearCli.Apps do + @moduledoc """ + `bear apps` 指令群(App 管理;docs/commands.md §3.6、issue #10)。 + + 對應伺服器端 App 管理 JSON API(alterminal/bear#28,`/api/v1/apps`、 + PAT Bearer、admin 限定)。認證沿用既有 PAT 憑證(`BEAR_TOKEN` 或憑證檔)。 + + API 路徑參數為資料庫 UUID,CLI 對外介面一律使用 `client_id`;show/ + update/rotate-secret/toggle 先以 list 比對解析(§7 開放問題 6 的結論)。 + + `client_secret` 僅於 create/rotate-secret 成功當下一次性輸出,不寫入 + 憑證檔/log/`--verbose`。 + + 退出碼:0 成功;1 404/422;2 用法錯誤;3 未登入或 401;6 網路/伺服器 + 錯誤;8 權限不足(403,僅限 admin)。 + """ + + alias BearCli.{Api, Config, Credentials} + + @list_per_page_fetch 100 + @max_fetch_pages 50 + + # -- 入口 -- + + @doc """ + 執行 `bear apps <動詞>`,回傳退出碼。 + + `opts[:apps_api]` 可注入假 API 模組供測試(需實作 `apps_list/3`、 + `apps_get/3`、`apps_create/3`、`apps_update/4`、`apps_rotate_secret/3`、 + `apps_toggle/3`)。 + """ + def run(verb, opts) do + api = opts[:apps_api] || Api + + with {:ok, ctx} <- context(opts) do + execute(verb, ctx, opts, api) + else + {:error, message, code} -> fail(opts, message, code) + end + end + + # -- 共用背景(token/issuer)-- + + defp context(opts) do + if token = Config.env_token() do + # BEAR_TOKEN 優先於憑證檔(不讀檔、不寫檔)。 + {:ok, %{token: token, issuer: resolve_issuer(opts, nil)}} + else + case Credentials.load() do + {:ok, creds} -> + token = creds["access_token"] + + if blank?(token) do + {:error, "憑證檔缺少 access_token,請重新 bear login", 7} + else + {:ok, %{token: token, issuer: resolve_issuer(opts, creds["issuer"])}} + end + + :error -> + {:error, "未登入(請先執行 bear login)", 3} + end + end + end + + defp resolve_issuer(opts, stored_issuer) do + opts[:issuer] || stored_issuer || Config.resolve_issuer(nil, opts[:config]) + end + + # -- 各動詞 -- + + defp execute(:list, ctx, opts, api) do + filters = + opts + |> Map.take([:visibility, :status]) + |> Enum.reject(fn {_k, v} -> blank?(v) end) + |> Map.new() + + if filters == %{} do + params = [page: opts[:page] || 1, per_page: opts[:per_page] || 20] + + case api.apps_list(ctx.issuer, ctx.token, params) do + {:ok, body} -> + apps = body["data"] || [] + page = body["page"] || params[:page] + per_page = body["per_page"] || params[:per_page] + total = body["total"] || length(apps) + render_list(opts, sort_apps(apps), page, per_page, total) + 0 + + {:error, _kind, _detail} = error -> + fail_api(opts, ctx, error) + end + else + # 伺服器 list 端點目前僅支援分頁(bear#28),無 visibility/status + # 過濾參數;有過濾時以全量列舉後在本地過濾、排序與分頁。 + with {:ok, all} <- fetch_all(ctx, api) do + filtered = + all + |> Enum.filter(&matches_filters?(&1, filters)) + |> sort_apps() + + page = opts[:page] || 1 + per_page = opts[:per_page] || 20 + page_apps = filtered |> Enum.drop((page - 1) * per_page) |> Enum.take(per_page) + render_list(opts, page_apps, page, per_page, length(filtered)) + 0 + else + {:error, message, code} -> fail(opts, message, code) + end + end + end + + defp execute(:show, ctx, opts, api) do + with {:ok, app} <- resolve_app(ctx, opts[:client_id_arg], api) do + case api.apps_get(ctx.issuer, ctx.token, app["id"]) do + {:ok, body} -> + show_app(body["data"] || %{}, opts) + 0 + + {:error, _kind, _detail} = error -> + fail_api(opts, ctx, error) + end + else + {:error, message, code} -> fail(opts, message, code) + end + end + + defp execute(:create, ctx, opts, api) do + attrs = build_attrs(opts, :create) + + case api.apps_create(ctx.issuer, ctx.token, attrs) do + {:ok, body} -> + app = body["data"] || %{} + secret = body["client_secret"] + + if opts[:json] do + output = %{ok: true, app: app} |> maybe_put(:client_secret, secret) + IO.puts(Jason.encode!(output)) + else + IO.puts("App 已建立:#{app["client_id"]}(#{app["visibility"]}/#{app["status"]})") + print_secret_block(secret, rotated?: false) + end + + 0 + + {:error, _kind, _detail} = error -> + fail_api(opts, ctx, error) + end + end + + defp execute(:update, ctx, opts, api) do + attrs = build_attrs(opts, :update) + + with {:ok, app} <- resolve_app(ctx, opts[:client_id_arg], api) do + case api.apps_update(ctx.issuer, ctx.token, app["id"], attrs) do + {:ok, body} -> + show_app(body["data"] || %{}, opts, summary?: true) + 0 + + {:error, _kind, _detail} = error -> + fail_api(opts, ctx, error) + end + else + {:error, message, code} -> fail(opts, message, code) + end + end + + defp execute(:"rotate-secret", ctx, opts, api) do + with {:ok, app} <- resolve_app(ctx, opts[:client_id_arg], api) do + case api.apps_rotate_secret(ctx.issuer, ctx.token, app["id"]) do + {:ok, body} -> + secret = body["client_secret"] + + if opts[:json] do + IO.puts(Jason.encode!(%{ok: true, client_secret: secret})) + else + print_secret_block(secret, rotated?: true) + end + + 0 + + {:error, _kind, _detail} = error -> + fail_api(opts, ctx, error) + end + else + {:error, message, code} -> fail(opts, message, code) + end + end + + defp execute(:toggle, ctx, opts, api) do + with {:ok, app} <- resolve_app(ctx, opts[:client_id_arg], api) do + case api.apps_toggle(ctx.issuer, ctx.token, app["id"]) do + {:ok, body} -> + updated = body["data"] || %{} + + if opts[:json] do + IO.puts( + Jason.encode!(%{ + ok: true, + app: %{client_id: updated["client_id"], status: updated["status"]} + }) + ) + else + IO.puts("#{app["client_id"]}:#{app["status"]} → #{updated["status"]}") + end + + 0 + + {:error, _kind, _detail} = error -> + fail_api(opts, ctx, error) + end + else + {:error, message, code} -> fail(opts, message, code) + end + end + + # -- client_id → UUID 解析 -- + + defp resolve_app(_ctx, nil, _api), do: {:error, "缺少 參數", 2} + + defp resolve_app(ctx, client_id, api) do + with {:ok, all} <- fetch_all(ctx, api) do + case Enum.find(all, &(&1["client_id"] == client_id)) do + nil -> {:error, "找不到 client_id 為 #{client_id} 的 App", 1} + app -> {:ok, app} + end + end + end + + # 全量列舉(分頁逐步拉取直到取完;設頁數上限避免無限迴圈)。 + defp fetch_all(ctx, api) do + do_fetch_all(ctx, api, 1, []) + end + + defp do_fetch_all(_ctx, _api, page, acc) when page > @max_fetch_pages, do: {:ok, acc} + + defp do_fetch_all(ctx, api, page, acc) do + case api.apps_list(ctx.issuer, ctx.token, page: page, per_page: @list_per_page_fetch) do + {:ok, body} -> + entries = body["data"] || [] + acc = acc ++ entries + total = body["total"] + + if entries == [] or length(entries) < @list_per_page_fetch or + (is_integer(total) and length(acc) >= total) do + {:ok, acc} + else + do_fetch_all(ctx, api, page + 1, acc) + end + + {:error, _kind, _detail} = error -> + {message, code} = format_api_error(ctx, error) + {:error, message, code} + end + end + + # -- 請求屬性組裝 -- + + # create:必填欄位已在解析層驗證(缺 → 用法錯誤 2),這裡只組裝。 + defp build_attrs(opts, :create) do + %{} + |> put_value("client_id", opts[:client_id]) + |> put_value("url", opts[:url]) + |> put_value("title", opts[:title]) + |> put_value("method", opts[:method]) + |> put_value("visibility", opts[:visibility]) + |> put_list("redirect_urls", opts[:redirect_url]) + |> put_list("post_logout_redirect_uris", opts[:post_logout_redirect_uri]) + |> put_list("scopes", opts[:scope]) + |> put_value("sub", opts[:sub]) + |> put_value("jwk_id", opts[:jwk_id]) + |> put_value("client_secret", opts[:secret]) + end + + # update:只送有給的欄位(部分更新);清單類整組覆寫。 + defp build_attrs(opts, :update) do + %{} + |> put_value("url", opts[:url]) + |> put_value("title", opts[:title]) + |> put_value("method", opts[:method]) + |> put_value("visibility", opts[:visibility]) + |> put_list("redirect_urls", opts[:redirect_url]) + |> put_list("post_logout_redirect_uris", opts[:post_logout_redirect_uri]) + |> put_list("scopes", opts[:scope]) + |> put_value("sub", opts[:sub]) + |> put_value("jwk_id", opts[:jwk_id]) + end + + defp put_value(map, _key, nil), do: map + defp put_value(map, _key, ""), do: map + defp put_value(map, key, value), do: Map.put(map, key, value) + + defp put_list(map, _key, nil), do: map + defp put_list(map, _key, []), do: map + defp put_list(map, key, values), do: Map.put(map, key, values) + + # -- 過濾與排序 -- + + defp matches_filters?(app, filters) do + Enum.all?(filters, fn {k, v} -> app[to_string(k)] == v end) + end + + defp sort_apps(apps), do: Enum.sort_by(apps, &{&1["client_id"] || "", &1["id"] || ""}) + + # -- 輸出 -- + + defp render_list(opts, apps, page, per_page, total) do + if opts[:json] do + IO.puts( + Jason.encode!(%{ok: true, page: page, per_page: per_page, total: total, apps: apps}) + ) + else + print_table(apps) + end + end + + @table_headers ["CLIENT ID", "TITLE", "VISIBILITY", "STATUS", "METHOD", "SCOPES"] + + defp print_table(apps) do + rows = + Enum.map(apps, fn app -> + [ + app["client_id"] || "", + app["title"] || "", + app["visibility"] || "", + app["status"] || "", + app["method"] || "", + Enum.join(app["scopes"] || [], ", ") + ] + end) + + widths = + Enum.with_index(@table_headers, fn _header, i -> + Enum.max([ + String.length(Enum.at(@table_headers, i)) + | Enum.map(rows, &String.length(Enum.at(&1, i))) + ]) + end) + + render_row = fn cells -> + cells + |> Enum.with_index() + |> Enum.map(fn {cell, i} -> String.pad_trailing(cell, Enum.at(widths, i)) end) + |> Enum.join(" ") + |> String.trim_trailing() + end + + IO.puts(render_row.(@table_headers)) + Enum.each(rows, fn cells -> IO.puts(render_row.(cells)) end) + end + + @app_fields ~w(client_id title url method visibility status scopes redirect_urls post_logout_redirect_uris sub jwk_id created_at updated_at) + + defp show_app(app, opts, summary? \\ false) + + defp show_app(app, opts, _summary?) do + if opts[:json] do + IO.puts(Jason.encode!(%{ok: true, app: app})) + else + Enum.each(@app_fields, fn key -> + IO.puts("#{String.pad_trailing(key, 26)}: #{format_app_value(app[key])}") + end) + end + end + + defp format_app_value(nil), do: "(無)" + defp format_app_value([]), do: "(無)" + defp format_app_value(values) when is_list(values), do: Enum.join(values, ", ") + defp format_app_value(value) when is_binary(value), do: value + defp format_app_value(value), do: to_string(value) + + # secret 只在成功當下一次性輸出(不寫入憑證檔/log/--verbose)。 + defp print_secret_block(nil, _opts), do: :ok + + defp print_secret_block(secret, rotated?: rotated?) do + lead = if rotated?, do: "client_secret 已輪轉", else: "client_secret" + IO.puts("#{lead}(只顯示這一次,請立即保存):") + IO.puts(" #{secret}") + end + + defp maybe_put(map, _key, nil), do: map + defp maybe_put(map, key, value), do: Map.put(map, key, value) + + # -- 錯誤處理 -- + + # API 錯誤 → 依 §3.6 群組共通退出碼輸出,回傳退出碼。 + defp fail_api(opts, ctx, error) do + {message, code} = format_api_error(ctx, error) + fail(opts, message, code) + end + + defp format_api_error(_ctx, {:error, :unauthorized, desc}) do + {"token 無效或已過期(#{desc}),請重新 bear login", 3} + end + + defp format_api_error(_ctx, {:error, :forbidden, _desc}) do + {"此操作需 admin 權限(HTTP 403)", 8} + end + + defp format_api_error(_ctx, {:error, :not_found, _desc}) do + {"找不到目標 App(HTTP 404)", 1} + end + + defp format_api_error(_ctx, {:error, :unprocessable_entity, %{"error" => "pkce_app"}}) do + {"此 App 為 PKCE,無 client secret 可輪轉", 1} + end + + defp format_api_error(_ctx, {:error, :unprocessable_entity, body}) do + details = + body + |> Map.get("errors", %{}) + |> Enum.map(fn {field, messages} -> + "#{field}: #{Enum.join(List.wrap(messages), "、")}" + end) + |> Enum.join(";") + + if details == "" do + {"驗證失敗(HTTP 422)", 1} + else + {"驗證失敗(HTTP 422):#{details}", 1} + end + end + + defp format_api_error(_ctx, {:error, :server_error, status}) do + {"伺服器回應 #{status}", 6} + end + + defp format_api_error(ctx, {:error, :network, reason}) do + {"無法連線到 #{ctx.issuer}:#{reason}", 6} + end + + defp fail(opts, message, code) do + if opts[:json] do + IO.puts(Jason.encode!(%{ok: false, error: message, code: code})) + else + IO.puts(:stderr, "錯誤:#{message}") + end + + code + end + + defp blank?(nil), do: true + + defp blank?(""), do: true + defp blank?(_), do: false +end diff --git a/lib/bear_cli/cli.ex b/lib/bear_cli/cli.ex index 8ee05d7..a9c14bc 100644 --- a/lib/bear_cli/cli.ex +++ b/lib/bear_cli/cli.ex @@ -8,7 +8,7 @@ defmodule BearCli.CLI do 優先使用該值,不讀寫本機憑證檔。 """ - alias BearCli.{Api, Config, Credentials} + alias BearCli.{Api, Apps, Config, Credentials} @global_switches [ issuer: :string, @@ -23,6 +23,48 @@ defmodule BearCli.CLI do @login_switches [token: :string, scope: :string, "client-id": :string] @token_switches [refresh: :boolean] + # -- apps 指令群(docs/commands.md §3.6)-- + # 注意:OptionParser 會把選項名的連字號正規化為底線 + # (--client-id → :client_id),switch 定義需用底線 atom。 + @apps_verbs ~w(list show create update rotate-secret toggle) + + @apps_list_switches [ + visibility: :string, + status: :string, + page: :integer, + per_page: :integer + ] + + @apps_create_switches [ + client_id: :string, + url: :string, + title: :string, + method: :string, + visibility: :string, + redirect_url: :keep, + post_logout_redirect_uri: :keep, + scope: :keep, + sub: :string, + jwk_id: :string, + secret: :string + ] + + @apps_update_switches [ + url: :string, + title: :string, + method: :string, + visibility: :string, + redirect_url: :keep, + post_logout_redirect_uri: :keep, + scope: :keep, + sub: :string, + jwk_id: :string + ] + + @visibilities ~w(public internal) + @statuses ~w(active inactive) + @methods ~w(client_secret PKCE) + # -- escript 入口 -- @doc "escript 主函式。執行後以 `System.halt/1` 設定退出碼。" @@ -114,6 +156,27 @@ defmodule BearCli.CLI do end end + defp parse_command("apps", args, global) do + case args do + [verb | rest] when verb in @apps_verbs -> + switches = apps_switches(verb) + + case OptionParser.parse(rest, strict: @global_switches ++ switches) do + {opts, positionals, []} -> + validate_apps(verb, positionals, merge_opts(global, opts_to_map(opts))) + + {_opts, _extra, [{opt, _} | _]} -> + {:error, "無法解析選項:#{opt}", 2} + end + + [] -> + {:error, "apps 缺少子指令(可用:#{Enum.join(@apps_verbs, " ")})", 2} + + [unknown | _] -> + {:error, "未知的 apps 子指令:#{unknown}(可用:#{Enum.join(@apps_verbs, " ")})", 2} + end + end + defp parse_command(unknown, _args, _global) do {:error, "未知指令:#{unknown}(可用 bear --help 查看說明)", 2} end @@ -131,10 +194,131 @@ defmodule BearCli.CLI do end end + # -- apps 解析輔助 -- + + defp apps_switches("list"), do: @apps_list_switches + defp apps_switches("show"), do: [] + defp apps_switches("create"), do: @apps_create_switches + defp apps_switches("update"), do: @apps_update_switches + defp apps_switches("rotate-secret"), do: [] + defp apps_switches("toggle"), do: [] + + # apps 子指令的本地用法驗證(§3.6:用法錯誤 → 退出碼 2)。 + defp validate_apps("list", [], opts) do + cond do + invalid_enum?(opts[:visibility], @visibilities, "--visibility") -> + usage_error(opts[:visibility], "--visibility", @visibilities) + + invalid_enum?(opts[:status], @statuses, "--status") -> + usage_error(opts[:status], "--status", @statuses) + + true -> + {:ok, {Apps, :list}, opts} + end + end + + defp validate_apps("list", extra, _opts), + do: {:error, "apps list 不接受位置參數:#{Enum.join(extra, " ")}", 2} + + defp validate_apps("show", [client_id], opts), + do: {:ok, {Apps, :show}, Map.put(opts, :client_id_arg, client_id)} + + defp validate_apps("show", [], _opts), do: {:error, "apps show 缺少 ", 2} + + defp validate_apps("show", extra, _opts), + do: {:error, "apps show 只接受一個 (多餘:#{Enum.join(Enum.drop(extra, 1), " ")})", 2} + + defp validate_apps("create", [], opts) do + missing = + [{"client-id", opts[:client_id]}, {"url", opts[:url]}, {"title", opts[:title]}] + |> Enum.filter(fn {_name, v} -> blank?(v) end) + |> Enum.map(&elem(&1, 0)) + + cond do + missing != [] -> + {:error, "apps create 缺少必選參數:#{Enum.join(missing, "、")}", 2} + + invalid_enum?(opts[:method], @methods, "--method") -> + usage_error(opts[:method], "--method", @methods) + + invalid_enum?(opts[:visibility], @visibilities, "--visibility") -> + usage_error(opts[:visibility], "--visibility", @visibilities) + + opts[:method] == "PKCE" and blank?(opts[:jwk_id]) -> + {:error, "method=PKCE 必須給 --jwk-id", 2} + + true -> + {:ok, {Apps, :create}, opts} + end + end + + defp validate_apps("create", extra, _opts), + do: {:error, "apps create 不接受位置參數:#{Enum.join(extra, " ")}", 2} + + defp validate_apps("update", [client_id], opts) do + cond do + invalid_enum?(opts[:method], @methods, "--method") -> + usage_error(opts[:method], "--method", @methods) + + invalid_enum?(opts[:visibility], @visibilities, "--visibility") -> + usage_error(opts[:visibility], "--visibility", @visibilities) + + opts[:method] == "PKCE" and blank?(opts[:jwk_id]) -> + {:error, "method=PKCE 必須給 --jwk-id", 2} + + true -> + {:ok, {Apps, :update}, Map.put(opts, :client_id_arg, client_id)} + end + end + + defp validate_apps("update", [], _opts), do: {:error, "apps update 缺少 ", 2} + + defp validate_apps("update", extra, _opts), + do: {:error, "apps update 只接受一個 (多餘:#{Enum.join(Enum.drop(extra, 1), " ")})", 2} + + defp validate_apps("rotate-secret", [client_id], opts), + do: {:ok, {Apps, :"rotate-secret"}, Map.put(opts, :client_id_arg, client_id)} + + defp validate_apps("rotate-secret", [], _opts), + do: {:error, "apps rotate-secret 缺少 ", 2} + + defp validate_apps("rotate-secret", extra, _opts), + do: + {:error, "apps rotate-secret 只接受一個 (多餘:#{Enum.join(Enum.drop(extra, 1), " ")})", + 2} + + defp validate_apps("toggle", [client_id], opts), + do: {:ok, {Apps, :toggle}, Map.put(opts, :client_id_arg, client_id)} + + defp validate_apps("toggle", [], _opts), do: {:error, "apps toggle 缺少 ", 2} + + defp validate_apps("toggle", extra, _opts), + do: {:error, "apps toggle 只接受一個 (多餘:#{Enum.join(Enum.drop(extra, 1), " ")})", 2} + + defp invalid_enum?(nil, _allowed, _flag), do: false + defp invalid_enum?(value, allowed, _flag), do: value not in allowed + + defp usage_error(value, flag, allowed) do + {:error, "#{flag} 不接受的值:#{value}(可用:#{Enum.join(allowed, "、")})", 2} + end + defp merge_opts(global, opts) do Map.merge(Map.new(global), Map.new(opts)) end + # keyword 轉 map:`:keep` 選項(@keep_keys)重複出現時收集為清單,其餘取最後值。 + @keep_keys ~w(redirect_url post_logout_redirect_uri scope)a + + defp opts_to_map(opts) do + Enum.reduce(opts, %{}, fn + {k, v}, acc when k in @keep_keys -> + Map.update(acc, k, [v], fn existing -> existing ++ [v] end) + + {k, v}, acc -> + Map.put(acc, k, v) + end) + end + # -- 分派 -- @doc """ @@ -156,6 +340,11 @@ defmodule BearCli.CLI do IO.puts(:stderr, "錯誤:#{message}") code + # apps 指令群({:ok, {module, verb}, opts} 形狀;注入的 api 模組同時作為 apps_api) + {:ok, {Apps, verb}, cmd_opts} when is_atom(verb) -> + apps_api = cmd_opts[:apps_api] || opts[:apps_api] || Api + Apps.run(verb, Map.put(cmd_opts, :apps_api, apps_api)) + {:ok, command, cmd_opts} -> cond do cmd_opts[:version] -> @@ -463,6 +652,19 @@ defmodule BearCli.CLI do token [--refresh] 印出 access token(PAT 模式下 --refresh 為用法錯誤) logout 登出(清除本機憑證) status 顯示登入狀態 + apps <動詞> App 管理(admin;bear apps --help 查看) + + apps 指令群(需 admin 權限的 PAT): + apps list [--visibility public|internal] [--status active|inactive] + [--page N] [--per-page N] + apps show + apps create --client-id ID --url URL --title TITLE + [--method client_secret|PKCE] [--visibility public|internal] + [--redirect-url URL]... [--post-logout-redirect-uri URI]... + [--scope SCOPE]... [--sub FIELD] [--jwk-id ID] [--secret SECRET] + apps update [同 create 的選項;只更新有給的欄位] + apps rotate-secret + apps toggle 全域選項: --issuer URL Bear(OIDC Provider)位址(預設 https://alterminal.com) diff --git a/test/bear_cli/apps_test.exs b/test/bear_cli/apps_test.exs new file mode 100644 index 0000000..5840514 --- /dev/null +++ b/test/bear_cli/apps_test.exs @@ -0,0 +1,517 @@ +defmodule BearCli.AppsTest do + @moduledoc """ + `bear apps` 指令群單元測試(issue #10):注入 fake API,涵蓋解析、 + 輸出、退出碼、client_id → UUID 解析與 401/403/404/422 分流。 + """ + use ExUnit.Case, async: false + + alias BearCli.{Apps, CLI} + + # -- fake API -- + + defmodule FakeApi do + @apps [ + %{ + "id" => "0192aaaa-0000-7000-8000-000000000001", + "client_id" => "my-app", + "title" => "My App", + "url" => "https://example.com", + "method" => "client_secret", + "status" => "active", + "visibility" => "public", + "scopes" => ["openid", "profile"], + "redirect_urls" => ["https://example.com/callback"], + "post_logout_redirect_uris" => [], + "sub" => "id", + "jwk_id" => nil, + "created_at" => "2026-09-07T00:00:00Z", + "updated_at" => "2026-09-07T00:00:00Z" + }, + %{ + "id" => "0192aaaa-0000-7000-8000-000000000002", + "client_id" => "internal-tool", + "title" => "Internal Tool", + "url" => "https://internal.example.com", + "method" => "PKCE", + "status" => "inactive", + "visibility" => "internal", + "scopes" => ["openid"], + "redirect_urls" => [], + "post_logout_redirect_uris" => [], + "sub" => "id", + "jwk_id" => "jwk-1", + "created_at" => "2026-09-06T00:00:00Z", + "updated_at" => "2026-09-06T00:00:00Z" + } + ] + + def apps, do: @apps + + def apps_list(_issuer, _token, params) do + if error = Process.get(:fake_api_error) do + error + else + page = params[:page] || 1 + per_page = params[:per_page] || 20 + + {:ok, + %{ + "data" => Enum.slice(@apps, (page - 1) * per_page, per_page), + "page" => page, + "per_page" => per_page, + "total" => length(@apps) + }} + end + end + + def apps_get(_issuer, _token, id) do + if error = Process.get(:fake_api_error) do + error + else + case Enum.find(@apps, &(&1["id"] == id)) do + nil -> {:error, :not_found, "not_found"} + app -> {:ok, %{"data" => app}} + end + end + end + + def apps_create(_issuer, _token, attrs) do + if error = Process.get(:fake_api_error) do + error + else + app = + %{ + "id" => "0192aaaa-0000-7000-8000-000000000003", + "client_id" => attrs["client_id"], + "title" => attrs["title"], + "url" => attrs["url"], + "method" => attrs["method"] || "client_secret", + "status" => "active", + "visibility" => attrs["visibility"] || "internal", + "scopes" => attrs["scopes"] || ["openid"], + "redirect_urls" => attrs["redirect_urls"] || [], + "post_logout_redirect_uris" => attrs["post_logout_redirect_uris"] || [], + "sub" => attrs["sub"] || "id", + "jwk_id" => attrs["jwk_id"], + "created_at" => "2026-09-08T00:00:00Z", + "updated_at" => "2026-09-08T00:00:00Z" + } + + {:ok, %{"data" => app, "client_secret" => "4f9c1d2e-new-secret"}} + end + end + + def apps_update(_issuer, _token, id, _attrs) do + if error = Process.get(:fake_api_error) do + error + else + case Enum.find(@apps, &(&1["id"] == id)) do + nil -> {:error, :not_found, "not_found"} + app -> {:ok, %{"data" => app}} + end + end + end + + def apps_rotate_secret(_issuer, _token, id) do + if error = Process.get(:fake_api_error) do + error + else + case Enum.find(@apps, &(&1["id"] == id)) do + %{"method" => "PKCE"} -> {:error, :unprocessable_entity, %{"error" => "pkce_app"}} + %{} -> {:ok, %{"client_secret" => "9a7b3c-rotated"}} + nil -> {:error, :not_found, "not_found"} + end + end + end + + def apps_toggle(_issuer, _token, id) do + if error = Process.get(:fake_api_error) do + error + else + case Enum.find(@apps, &(&1["id"] == id)) do + nil -> + {:error, :not_found, "not_found"} + + app -> + new_status = if app["status"] == "active", do: "inactive", else: "active" + {:ok, %{"data" => %{app | "status" => new_status}}} + end + end + end + end + + # -- 測試輔助 -- + + setup do + old_token = System.get_env("BEAR_TOKEN") + old_creds = System.get_env("BEAR_CREDENTIALS") + + on_exit(fn -> + restore(old_token, "BEAR_TOKEN") + restore(old_creds, "BEAR_CREDENTIALS") + end) + + System.put_env("BEAR_TOKEN", "admin-pat") + System.put_env("BEAR_CREDENTIALS", "/nonexistent/credentials.json") + :ok + end + + # 成功路徑:捕獲 stdout,回傳 {退出碼, stdout} + defp run_out(argv) do + ExUnit.CaptureIO.with_io(fn -> + CLI.dispatch(CLI.parse(argv), apps_api: FakeApi) + end) + end + + # 錯誤路徑:捕獲 stderr,回傳 {退出碼, stderr} + defp run_err(argv) do + ExUnit.CaptureIO.with_io(:stderr, "", fn -> + CLI.dispatch(CLI.parse(argv), apps_api: FakeApi) + end) + end + + defp with_api_error(error) do + Process.put(:fake_api_error, error) + end + + # -- list -- + + test "apps list renders table sorted by client_id" do + {code, out} = run_out(["apps", "list"]) + assert code == 0 + assert out =~ "CLIENT ID" + assert out =~ "internal-tool" + assert out =~ "my-app" + # 依 client_id 排序:internal-tool 在 my-app 之前 + assert String.contains?(out, "internal-tool") + assert :binary.match(out, "internal-tool") < :binary.match(out, "my-app") + end + + test "apps list --json outputs spec shape" do + {code, out} = run_out(["apps", "list", "--json"]) + assert code == 0 + + assert {:ok, decoded} = Jason.decode(out) + assert decoded["ok"] == true + assert decoded["page"] == 1 + assert decoded["per_page"] == 20 + assert decoded["total"] == 2 + assert Enum.any?(decoded["apps"], &(&1["client_id"] == "my-app")) + assert Enum.any?(decoded["apps"], &(&1["client_id"] == "internal-tool")) + end + + test "apps list --visibility/--status filters locally" do + {code, out} = run_out(["apps", "list", "--visibility", "public", "--status", "active"]) + assert code == 0 + assert out =~ "my-app" + refute out =~ "internal-tool" + end + + test "apps list server-side pagination (per-page 1, page 2)" do + # 無過濾 → 直接交給 API 分頁;fake API 第 2 頁(per_page=1)回傳第二筆 + {code, out} = run_out(["apps", "list", "--per-page", "1", "--page", "2"]) + assert code == 0 + assert out =~ "internal-tool" + refute out =~ "my-app" + end + + test "apps list 403 exits 8 with admin hint" do + with_api_error({:error, :forbidden, "Admin role required."}) + {code, err} = run_err(["apps", "list"]) + assert code == 8 + assert err =~ "admin" + end + + # -- show -- + + test "apps show resolves UUID and prints fields" do + {code, out} = run_out(["apps", "show", "my-app"]) + assert code == 0 + assert out =~ "client_id" + assert out =~ "my-app" + assert out =~ "https://example.com" + # secret 值不會出現(method 欄位的 "client_secret" 是合法輸出) + refute out =~ "4f9c1d2e" + refute out =~ "9a7b3c" + end + + test "apps show --json" do + {code, out} = run_out(["apps", "show", "my-app", "--json"]) + assert code == 0 + + assert {:ok, decoded} = Jason.decode(out) + assert decoded["ok"] == true + assert decoded["app"]["client_id"] == "my-app" + assert decoded["app"]["id"] == "0192aaaa-0000-7000-8000-000000000001" + end + + test "apps show unknown client_id exits 1" do + {code, err} = run_err(["apps", "show", "no-such-app"]) + assert code == 1 + assert err =~ "找不到" + end + + test "apps show without client-id exits 2" do + {code, err} = run_err(["apps", "show"]) + assert code == 2 + assert err =~ "缺少" + end + + # -- create -- + + test "apps create sends required attrs and prints one-time secret" do + {code, out} = + run_out([ + "apps", + "create", + "--client-id", + "new-app", + "--url", + "https://new.example.com", + "--title", + "New App", + "--visibility", + "public", + "--scope", + "openid", + "--scope", + "profile" + ]) + + assert code == 0 + assert out =~ "App 已建立:new-app" + assert out =~ "只顯示這一次" + assert out =~ "4f9c1d2e-new-secret" + end + + test "apps create --json includes client_secret once" do + {code, out} = + run_out([ + "apps", + "create", + "--client-id", + "new-app", + "--url", + "https://new.example.com", + "--title", + "New App", + "--json" + ]) + + assert code == 0 + + assert {:ok, decoded} = Jason.decode(out) + assert decoded["ok"] == true + assert decoded["client_secret"] == "4f9c1d2e-new-secret" + end + + test "apps create missing required exits 2" do + {code, err} = run_err(["apps", "create", "--client-id", "x"]) + assert code == 2 + assert err =~ "缺少必選參數" + assert err =~ "url" + assert err =~ "title" + end + + test "apps create invalid visibility exits 2" do + {code, err} = + run_err([ + "apps", + "create", + "--client-id", + "x", + "--url", + "https://x", + "--title", + "X", + "--visibility", + "bogus" + ]) + + assert code == 2 + assert err =~ "--visibility" + end + + test "apps create PKCE without jwk-id exits 2" do + {code, err} = + run_err([ + "apps", + "create", + "--client-id", + "x", + "--url", + "https://x", + "--title", + "X", + "--method", + "PKCE" + ]) + + assert code == 2 + assert err =~ "--jwk-id" + end + + test "apps create 422 renders field errors and exits 1" do + with_api_error( + {:error, :unprocessable_entity, %{"errors" => %{"client_id" => ["has already been taken"]}}} + ) + + {code, err} = + run_err([ + "apps", + "create", + "--client-id", + "my-app", + "--url", + "https://x", + "--title", + "X" + ]) + + assert code == 1 + assert err =~ "422" + assert err =~ "client_id" + end + + # -- update -- + + test "apps update sends only given fields" do + {code, out} = run_out(["apps", "update", "my-app", "--title", "Renamed"]) + assert code == 0 + assert out =~ "client_id" + assert out =~ "my-app" + end + + test "apps update --json" do + {code, out} = run_out(["apps", "update", "my-app", "--title", "Renamed", "--json"]) + assert code == 0 + + assert {:ok, decoded} = Jason.decode(out) + assert decoded["ok"] == true + assert decoded["app"]["client_id"] == "my-app" + end + + # -- rotate-secret -- + + test "apps rotate-secret prints one-time new secret" do + {code, out} = run_out(["apps", "rotate-secret", "my-app"]) + assert code == 0 + assert out =~ "已輪轉" + assert out =~ "9a7b3c-rotated" + end + + test "apps rotate-secret on PKCE app exits 1" do + {code, err} = run_err(["apps", "rotate-secret", "internal-tool"]) + assert code == 1 + assert err =~ "PKCE" + end + + # -- toggle -- + + test "apps toggle prints transition" do + {code, out} = run_out(["apps", "toggle", "my-app"]) + assert code == 0 + assert out =~ "my-app:active → inactive" + end + + test "apps toggle --json returns new status" do + {code, out} = run_out(["apps", "toggle", "my-app", "--json"]) + assert code == 0 + + assert {:ok, decoded} = Jason.decode(out) + assert decoded["ok"] == true + assert decoded["app"]["status"] == "inactive" + end + + # -- 認證分流 -- + + test "apps list 401 exits 3" do + with_api_error({:error, :unauthorized, "Invalid or expired token"}) + {code, err} = run_err(["apps", "list"]) + assert code == 3 + assert err =~ "bear login" + end + + test "apps list network error exits 6" do + with_api_error({:error, :network, "connection refused"}) + {code, err} = run_err(["apps", "list"]) + assert code == 6 + assert err =~ "無法連線" + end + + test "not logged in exits 3 without credentials" do + System.delete_env("BEAR_TOKEN") + {code, err} = run_err(["apps", "list"]) + assert code == 3 + assert err =~ "未登入" + end + + # -- 解析 -- + + test "apps without verb exits 2" do + assert {:error, msg, 2} = CLI.parse(["apps"]) + assert msg =~ "子指令" + end + + test "apps unknown verb exits 2" do + assert {:error, msg, 2} = CLI.parse(["apps", "frobnicate"]) + assert msg =~ "未知的 apps 子指令" + end + + test "apps list parses spec options" do + assert {:ok, {Apps, :list}, opts} = + CLI.parse([ + "apps", + "list", + "--visibility", + "public", + "--page", + "2", + "--per-page", + "5" + ]) + + assert opts[:visibility] == "public" + assert opts[:page] == 2 + assert opts[:per_page] == 5 + end + + test "apps create parses repeatable list options" do + assert {:ok, {Apps, :create}, opts} = + CLI.parse([ + "apps", + "create", + "--client-id", + "x", + "--url", + "https://x", + "--title", + "X", + "--redirect-url", + "https://a/cb", + "--redirect-url", + "https://b/cb", + "--scope", + "openid", + "--scope", + "email", + "--post-logout-redirect-uri", + "https://a/logout" + ]) + + assert opts[:redirect_url] == ["https://a/cb", "https://b/cb"] + assert opts[:scope] == ["openid", "email"] + assert opts[:post_logout_redirect_uri] == ["https://a/logout"] + end + + test "apps show keeps positional client-id" do + assert {:ok, {Apps, :show}, opts} = CLI.parse(["apps", "show", "my-app", "--json"]) + assert opts[:client_id_arg] == "my-app" + assert opts[:json] == true + end + + # -- 輔助 -- + + defp restore(nil, key), do: System.delete_env(key) + defp restore(value, key), do: System.put_env(key, value) +end