`rad-web` runs HTTP API and connects web app

Instead of `rad-web` just creating a session for an already running HTTP
API the command now starts the HTTP API, creates a session and opens the
authentication link.

Signed-off-by: Thomas Scholtes <geigerzaehler@axiom.fm>
This commit is contained in:
Thomas Scholtes 2023-12-02 10:59:51 +01:00 committed by cloudhead
parent 6f7c2dca91
commit 48dedc6e7e
No known key found for this signature in database
3 changed files with 133 additions and 55 deletions

17
Cargo.lock generated
View File

@ -872,9 +872,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]] [[package]]
name = "form_urlencoded" name = "form_urlencoded"
version = "1.2.0" version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652" checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456"
dependencies = [ dependencies = [
"percent-encoding", "percent-encoding",
] ]
@ -1620,9 +1620,9 @@ dependencies = [
[[package]] [[package]]
name = "idna" name = "idna"
version = "0.4.0" version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6"
dependencies = [ dependencies = [
"unicode-bidi", "unicode-bidi",
"unicode-normalization", "unicode-normalization",
@ -2161,9 +2161,9 @@ dependencies = [
[[package]] [[package]]
name = "percent-encoding" name = "percent-encoding"
version = "2.3.0" version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"
[[package]] [[package]]
name = "pin-project" name = "pin-project"
@ -2565,6 +2565,7 @@ dependencies = [
"tracing-logfmt", "tracing-logfmt",
"tracing-subscriber", "tracing-subscriber",
"ureq", "ureq",
"url",
] ]
[[package]] [[package]]
@ -3734,9 +3735,9 @@ dependencies = [
[[package]] [[package]]
name = "url" name = "url"
version = "2.4.1" version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "143b538f18257fac9cad154828a57c6bf5157e1aa604d4816b5995bf6de87ae5" checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633"
dependencies = [ dependencies = [
"form_urlencoded", "form_urlencoded",
"idna", "idna",

View File

@ -38,6 +38,7 @@ tracing = { version = "0.1.37", default-features = false, features = ["std", "lo
tracing-logfmt = { version = "0.2", optional = true } tracing-logfmt = { version = "0.2", optional = true }
tracing-subscriber = { version = "0.3", default-features = false, features = ["std", "ansi", "fmt"] } tracing-subscriber = { version = "0.3", default-features = false, features = ["std", "ansi", "fmt"] }
ureq = { version = "2.9", default-features = false, features = ["json"] } ureq = { version = "2.9", default-features = false, features = ["json"] }
url = { version = "2.5.0" }
[dependencies.radicle] [dependencies.radicle]
path = "../radicle" path = "../radicle"

View File

@ -1,7 +1,12 @@
use std::ffi::OsString; use std::ffi::OsString;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::process::Command;
use std::thread::sleep;
use std::time::Duration;
use anyhow::anyhow; use anyhow::{anyhow, Context};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use url::Url;
use radicle::crypto::{PublicKey, Signature, Signer}; use radicle::crypto::{PublicKey, Signature, Signer};
@ -10,19 +15,20 @@ use radicle_cli::terminal::args::{Args, Error, Help};
pub const HELP: Help = Help { pub const HELP: Help = Help {
name: "web", name: "web",
description: "Connect web with node", description: "Start HTTP API server and connect the web explorer to it",
version: env!("CARGO_PKG_VERSION"), version: env!("CARGO_PKG_VERSION"),
usage: r#" usage: r#"
Usage Usage
rad web [<option>...] rad web [<option>...] [<explorer-url>]
Runs the Radicle HTTP Daemon and opens a Radicle web explorer to authenticate with it.
Options Options
--backend, -b httpd to bind to --listen, -l Address to bind the HTTP daemon to (default: 127.0.0.1:8080)
--frontend, -f Web interface to bind to --connect, -c Connect the explorer to an already running daemon
--verbose, -v Verbose output --no-open Don't open the authentication URL automatically
--json Output as json
--help Print help --help Print help
"#, "#,
}; };
@ -36,10 +42,10 @@ pub struct SessionInfo {
#[derive(Debug)] #[derive(Debug)]
pub struct Options { pub struct Options {
pub backend: String, pub app_url: Url,
pub frontend: String, pub listen: SocketAddr,
pub json: bool, pub connect: bool,
pub verbose: bool, pub open: bool,
} }
impl Args for Options { impl Args for Options {
@ -47,24 +53,36 @@ impl Args for Options {
use lexopt::prelude::*; use lexopt::prelude::*;
let mut parser = lexopt::Parser::from_args(args); let mut parser = lexopt::Parser::from_args(args);
let mut backend = None; let mut listen = None;
let mut frontend = None; // SAFETY: This is a valid URL.
let mut json = false; #[allow(clippy::unwrap_used)]
let mut verbose = false; let mut app_url = Url::parse("https://app.radicle.xyz").unwrap();
let mut connect = false;
let mut open = true;
while let Some(arg) = parser.next()? { while let Some(arg) = parser.next()? {
match arg { match arg {
Long("verbose") | Short('v') => verbose = true, Long("listen") | Short('l') => {
Long("backend") | Short('b') => { listen = Some(
backend = Some(parser.value()?.to_string_lossy().to_string()) parser
.value()?
.to_string_lossy()
.as_ref()
.parse::<SocketAddr>()
.context("argument for '--listen' is not a valid socket address")?,
)
} }
Long("frontend") | Short('f') => { Long("connect") | Short('c') => {
frontend = Some(parser.value()?.to_string_lossy().to_string()) connect = true;
} }
Long("json") => json = true, Long("no-open") => open = false,
Long("help") | Short('h') => { Long("help") | Short('h') => {
return Err(Error::Help.into()); return Err(Error::Help.into());
} }
Value(val) => {
let val = val.to_string_lossy();
app_url = Url::parse(val.as_ref()).context("invalid explorer URL supplied")?;
}
_ => { _ => {
return Err(anyhow!(arg.unexpected())); return Err(anyhow!(arg.unexpected()));
} }
@ -73,10 +91,13 @@ impl Args for Options {
Ok(( Ok((
Options { Options {
json, open,
verbose, app_url,
backend: backend.unwrap_or(String::from("http://0.0.0.0:8080")), listen: listen.unwrap_or(SocketAddr::new(
frontend: frontend.unwrap_or(String::from("https://app.radicle.xyz")), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
8080,
)),
connect,
}, },
vec![], vec![],
)) ))
@ -90,33 +111,88 @@ pub fn sign(signer: Box<dyn Signer>, session: &SessionInfo) -> Result<Signature,
} }
pub fn run(options: Options, ctx: impl term::Context) -> anyhow::Result<()> { pub fn run(options: Options, ctx: impl term::Context) -> anyhow::Result<()> {
let session: SessionInfo = ureq::post(&format!("{}/api/v1/sessions", options.backend))
.call()?
.into_json()?;
let profile = ctx.profile()?; let profile = ctx.profile()?;
let runtime_and_handle = if !options.connect {
tracing_subscriber::fmt::init();
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("failed to create threaded runtime");
let httpd_handle = runtime.spawn(crate::run(crate::Options {
aliases: Default::default(),
listen: options.listen,
cache: None,
}));
Some((runtime, httpd_handle))
} else {
None
};
let mut num_retries = 30;
let response = loop {
num_retries -= 1;
sleep(Duration::from_millis(100));
match ureq::post(&format!("http://{}/api/v1/sessions", options.listen)).call() {
Ok(response) => {
break response;
}
Err(err) => {
if err.kind() == ureq::ErrorKind::ConnectionFailed && num_retries > 0 {
continue;
} else {
anyhow::bail!(err);
}
}
}
};
let session = response.into_json::<SessionInfo>()?;
let signer = profile.signer()?; let signer = profile.signer()?;
let signature = sign(signer, &session)?; let signature = sign(signer, &session)?;
if options.json { let mut auth_url = options.app_url.clone();
println!( auth_url
"{}", .path_segments_mut()
serde_json::json!({ .map_err(|_| anyhow!("URL not supported"))?
"sessionId": session.session_id, .push("session")
"publicKey": session.public_key, .push(&session.session_id);
"signature": signature,
}) auth_url
) .query_pairs_mut()
.append_pair("pk", &session.public_key.to_string())
.append_pair("sig", &signature.to_string())
.append_pair("addr", &options.listen.to_string());
if options.open {
#[cfg(target_os = "macos")]
let cmd_name = "open";
#[cfg(target_os = "linux")]
let cmd_name = "xdg-open";
let mut cmd = Command::new(cmd_name);
match cmd.arg(auth_url.as_str()).spawn()?.wait() {
Ok(exit_status) => {
if exit_status.success() {
term::success!("Opened {auth_url}");
} else { } else {
term::blank(); term::info!("Visit {auth_url} to connect");
term::info!("Open the following link to authenticate:"); }
term::info!( }
" 👉 {}/session/{}?pk={}&sig={}", Err(_) => {
options.frontend, term::info!("Visit {auth_url} to connect");
session.session_id, }
session.public_key, }
signature, } else {
); term::info!("Visit {auth_url} to connect");
term::blank(); }
if let Some((runtime, httpd_handle)) = runtime_and_handle {
runtime
.block_on(httpd_handle)?
.context("httpd server error")?;
} }
Ok(()) Ok(())