| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! `braid hub api METHOD PATH`: any route of the hub's API, with the token |
| 5 | //! braid holds for the hub, and its answer printed as it came: what an |
| 6 | //! agent uses for a route no command covers. |
| 7 | |
| 8 | use std::io::{Read, Write}; |
| 9 | use std::path::PathBuf; |
| 10 | use std::process::ExitCode; |
| 11 | |
| 12 | use anyhow::{Context, Result, bail}; |
| 13 | use clap::Args; |
| 14 | |
| 15 | use super::creds::{self, HubEnv}; |
| 16 | use super::remote::HubError; |
| 17 | use super::social_common::{REFUSED, UNREACHABLE, exit_for}; |
| 18 | use crate::Cli; |
| 19 | |
| 20 | /// The long help of `hub api`. |
| 21 | pub(crate) const API_HELP: &str = |
| 22 | "Send one request to the hub's API and print its answer's body as it came, |
| 23 | with the token braid holds for the hub (BRAID_TOKEN, else the one `braid |
| 24 | login` saved). PATH starts with /v1, such as /v1/me or |
| 25 | /v1/r/OWNER/NAME/refs; docs/hub.md lists the routes. --data or --data-file |
| 26 | (- for standard input) give a JSON body. |
| 27 | |
| 28 | The exit status is 0 when the hub did it; 1 when it refused, with its error |
| 29 | printed on standard output; 3 when it could not be reached or failed."; |
| 30 | |
| 31 | /// The methods the API takes. |
| 32 | const METHODS: [&str; 6] = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]; |
| 33 | |
| 34 | /// The largest body sent: the protocol's largest JSON body. |
| 35 | const MAX_DATA: u64 = braid_hubproto::limits::MAX_JSON as u64; |
| 36 | |
| 37 | /// `hub api`. |
| 38 | #[derive(Debug, Args)] |
| 39 | pub(crate) struct ApiArgs { |
| 40 | /// The method: GET, HEAD, POST, PUT, PATCH or DELETE. |
| 41 | #[arg(value_name = "METHOD")] |
| 42 | pub(crate) method: String, |
| 43 | /// The route, from /v1 on, such as /v1/me. |
| 44 | #[arg(value_name = "PATH")] |
| 45 | pub(crate) path: String, |
| 46 | /// The request's JSON body. |
| 47 | #[arg(long, value_name = "JSON", conflicts_with = "data_file")] |
| 48 | pub(crate) data: Option<String>, |
| 49 | /// A file holding the request's JSON body; - reads standard input. |
| 50 | #[arg(long, value_name = "FILE")] |
| 51 | pub(crate) data_file: Option<PathBuf>, |
| 52 | /// The hub (default: BRAID_HUB_URL, else the hub signed in to last, |
| 53 | /// else the public hub). |
| 54 | #[arg(long, value_name = "URL")] |
| 55 | pub(crate) hub: Option<String>, |
| 56 | } |
| 57 | |
| 58 | /// Checks a route given on the command line: a path of the API, never an |
| 59 | /// address of its own, so that the token goes to the hub and nowhere else. |
| 60 | fn check_path(path: &str) -> Result<()> { |
| 61 | let route = path.split(['?', '#']).next().unwrap_or(""); |
| 62 | let fine = (route == "/v1" || route.starts_with("/v1/")) |
| 63 | && !path.contains("://") |
| 64 | && !path.chars().any(|c| c.is_control() || c.is_whitespace()) |
| 65 | && !route.split('/').any(|part| part == ".." || part == "."); |
| 66 | if !fine { |
| 67 | bail!( |
| 68 | "{path:?} is not a route of the API: give a path that starts with /v1, such as /v1/me" |
| 69 | ); |
| 70 | } |
| 71 | Ok(()) |
| 72 | } |
| 73 | |
| 74 | /// The body `args` give, read whole. |
| 75 | fn data(args: &ApiArgs) -> Result<Option<Vec<u8>>> { |
| 76 | if let Some(text) = &args.data { |
| 77 | return Ok(Some(text.clone().into_bytes())); |
| 78 | } |
| 79 | let Some(path) = &args.data_file else { |
| 80 | return Ok(None); |
| 81 | }; |
| 82 | let mut bytes = Vec::new(); |
| 83 | if path.as_os_str() == "-" { |
| 84 | std::io::stdin() |
| 85 | .lock() |
| 86 | .take(MAX_DATA + 1) |
| 87 | .read_to_end(&mut bytes) |
| 88 | .context("cannot read standard input")?; |
| 89 | } else { |
| 90 | std::fs::File::open(path) |
| 91 | .and_then(|file| file.take(MAX_DATA + 1).read_to_end(&mut bytes)) |
| 92 | .with_context(|| format!("cannot read {}", path.display()))?; |
| 93 | } |
| 94 | if bytes.len() as u64 > MAX_DATA { |
| 95 | bail!("the body is larger than {MAX_DATA} bytes, the most the hub takes"); |
| 96 | } |
| 97 | Ok(Some(bytes)) |
| 98 | } |
| 99 | |
| 100 | /// Writes an answer's body to standard output, as it came. |
| 101 | fn emit(bytes: &[u8]) -> Result<()> { |
| 102 | let mut out = std::io::stdout().lock(); |
| 103 | out.write_all(bytes)?; |
| 104 | if !bytes.is_empty() && !bytes.ends_with(b"\n") { |
| 105 | out.write_all(b"\n")?; |
| 106 | } |
| 107 | out.flush()?; |
| 108 | Ok(()) |
| 109 | } |
| 110 | |
| 111 | pub(crate) fn api(cli: &Cli, args: &ApiArgs) -> Result<ExitCode> { |
| 112 | let _ = cli; |
| 113 | let method = args.method.to_ascii_uppercase(); |
| 114 | if !METHODS.contains(&method.as_str()) { |
| 115 | bail!( |
| 116 | "{:?} is not a method the API takes: {}", |
| 117 | args.method, |
| 118 | METHODS.join(", ") |
| 119 | ); |
| 120 | } |
| 121 | check_path(&args.path)?; |
| 122 | let body = data(args)?; |
| 123 | let env = HubEnv::from_process(); |
| 124 | let creds = env.credentials()?; |
| 125 | let url = creds::hub_url(&env, &creds, args.hub.as_deref())?; |
| 126 | let (hub, _) = super::client(&env, &url)?; |
| 127 | let headers: &[(&str, &str)] = if body.is_some() { |
| 128 | &[("Content-Type", "application/json")] |
| 129 | } else { |
| 130 | &[] |
| 131 | }; |
| 132 | match hub.call(&method, &args.path, headers, body.as_deref()) { |
| 133 | Ok(answer) => { |
| 134 | emit(&answer)?; |
| 135 | Ok(ExitCode::SUCCESS) |
| 136 | } |
| 137 | Err(HubError::Api { status, body }) => { |
| 138 | emit(serde_json::to_string(&body)?.as_bytes())?; |
| 139 | Ok(ExitCode::from(if status < 500 { |
| 140 | REFUSED |
| 141 | } else { |
| 142 | UNREACHABLE |
| 143 | })) |
| 144 | } |
| 145 | Err(err) => { |
| 146 | eprintln!("braid: error: {err}"); |
| 147 | Ok(ExitCode::from(exit_for(&err))) |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | #[cfg(test)] |
| 153 | mod tests { |
| 154 | use super::*; |
| 155 | |
| 156 | #[test] |
| 157 | fn routes_of_the_api_only() { |
| 158 | for fine in [ |
| 159 | "/v1", |
| 160 | "/v1/me", |
| 161 | "/v1/r/ada/demo/refs", |
| 162 | "/v1/explore?q=braid", |
| 163 | ] { |
| 164 | assert!(check_path(fine).is_ok(), "{fine}"); |
| 165 | } |
| 166 | for bad in [ |
| 167 | "v1/me", |
| 168 | "/v2/me", |
| 169 | "/v1x", |
| 170 | "https://elsewhere.example/v1/me", |
| 171 | "/v1/../etc", |
| 172 | "/v1/me?next=https://elsewhere.example", |
| 173 | "/v1/a b", |
| 174 | "/v1/a\nb", |
| 175 | "//elsewhere.example/v1", |
| 176 | ] { |
| 177 | assert!(check_path(bad).is_err(), "{bad}"); |
| 178 | } |
| 179 | } |
| 180 | } |