feat(cli): add pic routes + pic admins subcommands

Closes the audit's Critical "operator can't deploy a serverless endpoint
end-to-end from the CLI" finding. Two new subcommand families bring the
CLI coverage from 14 commands to ~25:

- pic routes {ls, create, rm, check, match}: full route CRUD plus the
  dry-run conflict checker and the URL matcher already exposed by the
  dashboard. The create form accepts --path-kind, --host-kind, and
  --dispatch (sync|async) so async routes can finally be created
  headlessly. The ls output adds a dispatch column.

- pic admins {ls, create, show, set, rm}: per-instance admin user
  management. Create reads passwords from stdin via --password - so
  shell history never sees the cleartext. Set is a JSON-Merge-Patch
  shape that lets operators deactivate accounts or rotate roles
  without touching the dashboard.

Six new ignored integration tests follow the established #[ignore]
pattern (DATABASE_URL gates them). They cover the happy-path round
trip, the async-dispatch persistence path, the password-required
error path, and the capability gate (a Member sees HTTP 403). All
pass against the local dev stack with PICLOUD_DEV_MODE=true +
PICLOUD_DEV_INSECURE_KEY=i-understand-this-is-insecure.

The `pic members` and `pic domains` subcommands the audit mentioned
are deferred — the apps_api shape may shift in v1.2 with per-app
roles and rebuilding the CLI surface twice would be churn.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-06-10 21:35:09 +02:00
parent 649246213e
commit 59645e8159
9 changed files with 1177 additions and 2 deletions

View File

@@ -0,0 +1,181 @@
//! `pic admins` subcommands: `ls`, `create`, `show`, `set`, `rm`.
//!
//! All endpoints require `Capability::InstanceManageUsers` (owner /
//! admin). Member accounts get a 403.
use std::io::{IsTerminal, Read, Write};
use anyhow::{anyhow, Context, Result};
use picloud_shared::InstanceRole;
use crate::client::{AdminDto, Client, CreateAdminBody, PatchAdminBody};
use crate::config;
use crate::output::{KvBlock, OutputMode, Table};
pub async fn ls(mode: OutputMode) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let admins = client.admins_list().await?;
let mut table = Table::new([
"id",
"username",
"role",
"active",
"email",
"created_at",
"last_login_at",
]);
for a in admins {
table.row([
a.id.to_string(),
a.username,
a.instance_role.as_str().to_string(),
a.is_active.to_string(),
a.email.unwrap_or_else(|| "-".into()),
a.created_at.to_rfc3339(),
a.last_login_at
.map(|t| t.to_rfc3339())
.unwrap_or_else(|| "-".into()),
]);
}
table.print(mode);
Ok(())
}
/// Resolve the password the user wants to set:
/// * `Some("-")` → read from stdin (no echo when interactive).
/// * `Some(other)` → use the inline value (handy for non-interactive
/// callers, but logs to shell history; warn when interactive).
/// * `None` → require explicit `--password`.
fn resolve_password(password_arg: Option<&str>) -> Result<String> {
match password_arg {
None => Err(anyhow!(
"missing --password; pass --password - to read from stdin"
)),
Some("-") => read_password_from_stdin(),
Some(inline) => Ok(inline.to_string()),
}
}
fn read_password_from_stdin() -> Result<String> {
let stdin = std::io::stdin();
if stdin.is_terminal() {
// Prompt without echoing — rpassword would be cleaner, but the
// CLI already avoids extra crates. Print a one-line prompt so
// the user knows we're waiting for input.
eprint!("Password: ");
std::io::stderr().flush().ok();
let mut buf = String::new();
stdin
.lock()
.read_line(&mut buf)
.context("read password from stdin")?;
Ok(buf.trim_end_matches(['\n', '\r']).to_string())
} else {
// Piped input — read everything, strip trailing newline.
let mut buf = String::new();
stdin
.lock()
.read_to_string(&mut buf)
.context("read password from stdin")?;
Ok(buf.trim_end_matches(['\n', '\r']).to_string())
}
}
trait ReadLine {
fn read_line(&mut self, buf: &mut String) -> std::io::Result<usize>;
}
impl<T: std::io::BufRead> ReadLine for T {
fn read_line(&mut self, buf: &mut String) -> std::io::Result<usize> {
std::io::BufRead::read_line(self, buf)
}
}
pub async fn create(
username: &str,
password: Option<&str>,
role: InstanceRole,
email: Option<&str>,
mode: OutputMode,
) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let pw = resolve_password(password)?;
if pw.is_empty() {
return Err(anyhow!("password must not be empty"));
}
let body = CreateAdminBody {
username,
password: &pw,
instance_role: role,
email,
};
let created = client.admins_create(&body).await?;
print_admin(&created, mode);
Ok(())
}
pub async fn show(id: &str, mode: OutputMode) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let a = client.admins_get(id).await?;
print_admin(&a, mode);
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub async fn set(
id: &str,
username: Option<&str>,
password: Option<&str>,
active: Option<bool>,
role: Option<InstanceRole>,
mode: OutputMode,
) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
// Only resolve the password if --password was passed.
let pw_owned;
let password_ref: Option<&str> = if let Some(raw) = password {
pw_owned = resolve_password(Some(raw))?;
Some(pw_owned.as_str())
} else {
None
};
let body = PatchAdminBody {
username,
password: password_ref,
is_active: active,
instance_role: role,
};
let updated = client.admins_patch(id, &body).await?;
print_admin(&updated, mode);
Ok(())
}
pub async fn rm(id: &str) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
client.admins_delete(id).await?;
println!("Deleted admin {id}");
Ok(())
}
fn print_admin(a: &AdminDto, mode: OutputMode) {
let mut block = KvBlock::new();
block
.field("id", a.id.to_string())
.field("username", a.username.clone())
.field("instance_role", a.instance_role.as_str().to_string())
.field("is_active", a.is_active.to_string())
.field("email", a.email.clone().unwrap_or_else(|| "-".into()))
.field("created_at", a.created_at.to_rfc3339())
.field(
"last_login_at",
a.last_login_at
.map(|t| t.to_rfc3339())
.unwrap_or_else(|| "-".into()),
);
block.print(mode);
}

View File

@@ -1,7 +1,9 @@
pub mod admins;
pub mod api_keys;
pub mod apps;
pub mod login;
pub mod logout;
pub mod logs;
pub mod routes;
pub mod scripts;
pub mod whoami;

View File

@@ -0,0 +1,184 @@
//! `pic routes` subcommands: `ls`, `create`, `rm`, `check`, `match`.
use anyhow::{anyhow, Result};
use picloud_shared::{AppId, DispatchMode, HostKind, PathKind};
use crate::client::{CheckRouteBody, Client, CreateRouteBody, MatchRouteBody};
use crate::config;
use crate::output::{KvBlock, OutputMode, Table};
pub async fn ls(script_id: &str, mode: OutputMode) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let routes = client.routes_list_for_script(script_id).await?;
let mut table = Table::new([
"id",
"method",
"host",
"path_kind",
"path",
"dispatch",
"created_at",
]);
for r in routes {
table.row([
r.id.to_string(),
r.method.clone().unwrap_or_else(|| "ANY".into()),
host_label(r.host_kind, &r.host),
path_kind_label(r.path_kind).to_string(),
r.path.clone(),
dispatch_label(r.dispatch_mode).to_string(),
r.created_at.to_rfc3339(),
]);
}
table.print(mode);
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub async fn create(
script_id: &str,
method: Option<&str>,
path: &str,
path_kind: PathKind,
host: &str,
host_kind: HostKind,
host_param_name: Option<&str>,
dispatch_mode: DispatchMode,
) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let body = CreateRouteBody {
host_kind,
host,
host_param_name,
path_kind,
path,
method,
dispatch_mode,
};
let r = client.routes_create(script_id, &body).await?;
println!(
"Created route {} ({} {} {})",
r.id,
r.method.unwrap_or_else(|| "ANY".into()),
host_label(r.host_kind, &r.host),
r.path
);
Ok(())
}
pub async fn rm(route_id: &str) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
client.routes_delete(route_id).await?;
println!("Deleted route {route_id}");
Ok(())
}
pub async fn check(
app: &str,
method: Option<&str>,
path: &str,
path_kind: PathKind,
host: &str,
host_kind: HostKind,
mode: OutputMode,
) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let app_id = resolve_app_id(&client, app).await?;
let body = CheckRouteBody {
app_id,
host_kind,
host: host.to_string(),
path_kind,
path: path.to_string(),
method: method.map(str::to_string),
};
let resp = client.routes_check(&body).await?;
let mut block = KvBlock::new();
block.field("ok", resp.ok.to_string());
if let Some(reason) = resp.conflict_reason {
block.field("conflict_reason", reason);
}
if let Some(r) = resp.conflicting_route {
block
.field("conflicting_route_id", r.id.to_string())
.field(
"conflicting_method",
r.method.unwrap_or_else(|| "ANY".into()),
)
.field("conflicting_host", host_label(r.host_kind, &r.host))
.field("conflicting_path", r.path);
}
block.print(mode);
Ok(())
}
pub async fn match_route(app: &str, url: &str, method: &str, mode: OutputMode) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let app_id = resolve_app_id(&client, app).await?;
let resp = client
.routes_match(&MatchRouteBody {
app_id,
url,
method,
})
.await?;
let mut block = KvBlock::new();
match resp.matched {
None => {
block.field("matched", "false");
}
Some(m) => {
block
.field("matched", "true")
.field("route_id", m.route_id)
.field("script_id", m.script_id.to_string());
if !m.params.is_empty() {
for (k, v) in m.params {
block.field(format!("param.{k}"), v);
}
}
if let Some(rest) = m.rest {
block.field("rest", rest);
}
}
}
block.print(mode);
Ok(())
}
async fn resolve_app_id(client: &Client, ident: &str) -> Result<AppId> {
// Accept either a slug or a UUID. The apps_get endpoint takes both.
let lookup = client
.apps_get(ident)
.await
.map_err(|e| anyhow!("resolve app `{ident}`: {e}"))?;
Ok(lookup.app.id)
}
const fn dispatch_label(d: DispatchMode) -> &'static str {
match d {
DispatchMode::Sync => "sync",
DispatchMode::Async => "async",
}
}
const fn path_kind_label(k: PathKind) -> &'static str {
match k {
PathKind::Exact => "exact",
PathKind::Prefix => "prefix",
PathKind::Param => "param",
}
}
fn host_label(kind: HostKind, host: &str) -> String {
match kind {
HostKind::Any => "*".to_string(),
HostKind::Strict => host.to_string(),
HostKind::Wildcard => format!("*.{host}"),
}
}