Skip to main content

qn/
context.rs

1//! Runtime context shared by every command.
2//!
3//! Builds the `QuicknodeSdk` from `GlobalArgs` and attaches an `OutputCtx`.
4
5use std::io::IsTerminal;
6
7use quicknode_sdk::{
8    AdminConfig, HttpConfig, KvStoreConfig, QuicknodeSdk, SdkFullConfig, SqlConfig, StreamsConfig,
9    WebhooksConfig,
10};
11
12use crate::config;
13use crate::errors::CliError;
14use crate::output::{Format, OutputCtx};
15
16/// Top-level flags inherited by every subcommand.
17#[derive(Debug, Clone, Default)]
18pub struct GlobalArgs {
19    pub api_key: Option<String>,
20    /// `--config-file`: alternate config TOML. `None` means the default path
21    /// (`~/.config/qn/config.toml`).
22    pub config_file: Option<std::path::PathBuf>,
23    /// `None` means the user didn't pass `--format`; resolve via config file
24    /// (then the TTY-aware default: `Table` on a TTY, `Json` off) when we
25    /// build the [`Ctx`].
26    pub format: Option<Format>,
27    pub wide: bool,
28    pub no_color: bool,
29    pub quiet: bool,
30    pub verbose: bool,
31    pub no_input: bool,
32    pub yes_count: u8,
33    /// Max automatic retries for read-only API calls (see `crate::retry`).
34    /// `Default` yields 0 (no retries) — the CLI default of 3 comes from clap.
35    pub retries: u32,
36    pub base_url: Option<String>,
37}
38
39impl GlobalArgs {
40    /// Resolve the output format: CLI flag > config file > TTY-aware default
41    /// (`Table` on a TTY, `Json` off).
42    /// Used by [`Ctx::from_global`] and `auth` (which doesn't build a Ctx).
43    pub fn resolve_format(&self, stdout_is_tty: bool) -> Format {
44        self.resolve_output(stdout_is_tty).0
45    }
46
47    /// Resolve `(format, wide)` together so we only read the config file once.
48    ///
49    /// For each: CLI flag > config file > built-in default. The format default
50    /// is TTY-aware: `Table` when stdout is a terminal, `Json` otherwise (so
51    /// agents / piped callers get a structured format by default). `--wide` is
52    /// purely additive — the flag sets it true; the config file can also set
53    /// it true; otherwise it's false.
54    pub fn resolve_output(&self, stdout_is_tty: bool) -> (Format, bool) {
55        let (cfg_format, cfg_wide) = self.load_output_config();
56        resolve_output_inner(self.format, self.wide, cfg_format, cfg_wide, stdout_is_tty)
57    }
58
59    /// The config file to read: `--config-file` if given, else the default path.
60    pub fn resolve_config_path(&self) -> Option<std::path::PathBuf> {
61        self.config_file.clone().or_else(config::config_path)
62    }
63
64    fn load_output_config(&self) -> (Option<Format>, bool) {
65        let Some(p) = self.resolve_config_path() else {
66            return (None, false);
67        };
68        match config::load_from(&p) {
69            Ok(Some(cfg)) => (cfg.output.format, cfg.output.wide),
70            _ => (None, false),
71        }
72    }
73}
74
75/// Pure form of [`GlobalArgs::resolve_output`] — separated so it can be
76/// exhaustively unit-tested without touching the real config file. CLI values
77/// win; otherwise we fall back to config; otherwise the TTY-aware default.
78fn resolve_output_inner(
79    flag_format: Option<Format>,
80    flag_wide: bool,
81    cfg_format: Option<Format>,
82    cfg_wide: bool,
83    stdout_is_tty: bool,
84) -> (Format, bool) {
85    let format = flag_format.or(cfg_format).unwrap_or(if stdout_is_tty {
86        Format::Table
87    } else {
88        Format::Json
89    });
90    let wide = flag_wide || cfg_wide;
91    (format, wide)
92}
93
94/// The `User-Agent` sent with every API request. Mirrors the SDK's own shape
95/// (`quicknode-sdk-<lang>/<ver> (<os>-<arch>; …)`) with the CLI as the product:
96/// `quicknode-cli/<version> (<os>-<arch>)`.
97pub fn user_agent() -> String {
98    format!(
99        "quicknode-cli/{} ({}-{})",
100        env!("CARGO_PKG_VERSION"),
101        std::env::consts::OS,
102        std::env::consts::ARCH,
103    )
104}
105
106/// Base SDK config shared by every construction site (`Ctx::from_global` and
107/// the `auth` commands): the API key plus the CLI `User-Agent`. Custom headers
108/// in `HttpConfig` override SDK-managed headers of the same name, which is the
109/// SDK's supported way to replace its auto-generated `User-Agent`.
110pub fn sdk_config(api_key: String) -> SdkFullConfig {
111    let mut full = SdkFullConfig::from_api_key(api_key);
112    let mut headers = std::collections::HashMap::new();
113    headers.insert("User-Agent".to_string(), user_agent());
114    full.http = Some(HttpConfig {
115        headers: Some(headers),
116        ..Default::default()
117    });
118    full
119}
120
121pub struct Ctx {
122    pub sdk: QuicknodeSdk,
123    pub out: OutputCtx,
124    pub global: GlobalArgs,
125}
126
127impl Ctx {
128    /// Construct the SDK + output ctx from `global`. Resolves the API key per
129    /// the documented precedence: flag > config file (`--config-file` path if
130    /// given, else the default). If neither supplies a key we return
131    /// `CliError::NoApiKey` — regular commands do not prompt; the user is
132    /// directed to `qn auth login`.
133    pub fn from_global(global: GlobalArgs) -> Result<Self, CliError> {
134        let config_path = global.resolve_config_path();
135        let stdout_is_tty = std::io::stdout().is_terminal();
136        let (format, wide) = global.resolve_output(stdout_is_tty);
137
138        let (api_key, _) = config::resolve_api_key(
139            global.api_key.as_deref(),
140            config_path.as_deref(),
141            false,
142            || unreachable!("prompt disabled for non-auth commands"),
143        )?;
144
145        let mut full = sdk_config(api_key);
146
147        // --base-url applies to every sub-client. Useful for wiremock tests and
148        // on-prem mirrors. Each sub-client has its own base path under the host
149        // so we suffix correctly.
150        if let Some(base) = &global.base_url {
151            let trimmed = validate_base_url(base)?;
152            let trimmed = trimmed.as_str();
153            full.admin = Some(AdminConfig {
154                base_url: Some(format!("{trimmed}/v0/")),
155            });
156            full.streams = Some(StreamsConfig {
157                base_url: Some(format!("{trimmed}/streams/rest/v1/")),
158            });
159            full.webhooks = Some(WebhooksConfig {
160                base_url: Some(format!("{trimmed}/webhooks/rest/v1/")),
161            });
162            full.kvstore = Some(KvStoreConfig {
163                base_url: Some(format!("{trimmed}/kv/rest/v1/")),
164            });
165            full.sql = Some(SqlConfig {
166                base_url: Some(format!("{trimmed}/sql/rest/v1/")),
167            });
168        }
169
170        let sdk = QuicknodeSdk::new(&full)?;
171        let out = OutputCtx::detect_with(
172            format,
173            global.no_color,
174            global.quiet,
175            global.verbose,
176            wide,
177            stdout_is_tty,
178            std::env::var_os("NO_COLOR"),
179            std::env::var("TERM").ok(),
180        );
181
182        Ok(Self { sdk, out, global })
183    }
184}
185
186/// Validates a user-supplied `--base-url` and returns it with any trailing
187/// slash stripped. Rejects non-http(s) schemes, embedded userinfo, query/
188/// fragment, and non-root paths so we can't accidentally splice attacker-
189/// controlled segments into the SDK's hard-coded sub-client paths.
190fn validate_base_url(base: &str) -> Result<String, CliError> {
191    let parsed = url::Url::parse(base)
192        .map_err(|_| CliError::Arg(format!("--base-url '{base}' is not a valid URL")))?;
193    match parsed.scheme() {
194        "http" | "https" => {}
195        other => {
196            return Err(CliError::Arg(format!(
197                "--base-url scheme '{other}' is not allowed; use http or https"
198            )))
199        }
200    }
201    if !parsed.username().is_empty() || parsed.password().is_some() {
202        return Err(CliError::Arg(
203            "--base-url must not contain userinfo (username/password)".into(),
204        ));
205    }
206    if parsed.query().is_some() || parsed.fragment().is_some() {
207        return Err(CliError::Arg(
208            "--base-url must not contain a query string or fragment".into(),
209        ));
210    }
211    if !matches!(parsed.path(), "" | "/") {
212        return Err(CliError::Arg("--base-url must not contain a path".into()));
213    }
214    Ok(base.trim_end_matches('/').to_string())
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    #[test]
222    fn flag_format_wins_over_config_and_tty_default() {
223        let (f, _) =
224            resolve_output_inner(Some(Format::Json), false, Some(Format::Yaml), false, true);
225        assert_eq!(f, Format::Json);
226        let (f, _) =
227            resolve_output_inner(Some(Format::Json), false, Some(Format::Yaml), false, false);
228        assert_eq!(f, Format::Json);
229    }
230
231    #[test]
232    fn config_format_wins_over_tty_default() {
233        let (f, _) = resolve_output_inner(None, false, Some(Format::Yaml), false, true);
234        assert_eq!(f, Format::Yaml);
235        let (f, _) = resolve_output_inner(None, false, Some(Format::Yaml), false, false);
236        assert_eq!(f, Format::Yaml);
237    }
238
239    #[test]
240    fn default_is_table_when_stdout_is_a_tty() {
241        let (f, _) = resolve_output_inner(None, false, None, false, true);
242        assert_eq!(f, Format::Table);
243    }
244
245    #[test]
246    fn default_is_json_when_stdout_is_not_a_tty() {
247        let (f, _) = resolve_output_inner(None, false, None, false, false);
248        assert_eq!(f, Format::Json);
249    }
250
251    #[test]
252    fn config_toon_overrides_non_tty_default() {
253        let (f, _) = resolve_output_inner(None, false, Some(Format::Toon), false, false);
254        assert_eq!(f, Format::Toon);
255    }
256
257    #[test]
258    fn wide_is_additive_between_flag_and_config() {
259        // Flag alone.
260        let (_, w) = resolve_output_inner(None, true, None, false, true);
261        assert!(w);
262        // Config alone.
263        let (_, w) = resolve_output_inner(None, false, None, true, true);
264        assert!(w);
265        // Both.
266        let (_, w) = resolve_output_inner(None, true, None, true, true);
267        assert!(w);
268        // Neither.
269        let (_, w) = resolve_output_inner(None, false, None, false, true);
270        assert!(!w);
271    }
272
273    #[test]
274    fn base_url_accepts_plain_http_and_https() {
275        assert_eq!(
276            validate_base_url("https://api.quicknode.com").unwrap(),
277            "https://api.quicknode.com"
278        );
279        assert_eq!(
280            validate_base_url("http://127.0.0.1:8080/").unwrap(),
281            "http://127.0.0.1:8080"
282        );
283    }
284
285    #[test]
286    fn base_url_rejects_non_http_schemes() {
287        for bad in ["file:///etc/passwd", "ftp://x", "javascript:alert(1)"] {
288            assert!(validate_base_url(bad).is_err(), "should reject {bad}");
289        }
290    }
291
292    #[test]
293    fn base_url_rejects_userinfo() {
294        assert!(validate_base_url("https://user:pass@evil/").is_err());
295        assert!(validate_base_url("https://user@evil/").is_err());
296    }
297
298    #[test]
299    fn base_url_rejects_path_query_fragment() {
300        assert!(validate_base_url("https://x/extra/path").is_err());
301        assert!(validate_base_url("https://x/?q=1").is_err());
302        assert!(validate_base_url("https://x/#frag").is_err());
303    }
304
305    #[test]
306    fn base_url_rejects_garbage() {
307        assert!(validate_base_url("not a url").is_err());
308        assert!(validate_base_url("").is_err());
309    }
310
311    #[test]
312    fn user_agent_identifies_the_cli() {
313        let ua = user_agent();
314        assert!(ua.starts_with("quicknode-cli/"), "ua={ua}");
315        assert!(ua.contains(env!("CARGO_PKG_VERSION")), "ua={ua}");
316    }
317
318    #[test]
319    fn sdk_config_sets_the_user_agent_header_and_nothing_else() {
320        let cfg = sdk_config("k".to_string());
321        let http = cfg.http.expect("http config should be set");
322        assert_eq!(
323            http.headers.as_ref().and_then(|h| h.get("User-Agent")),
324            Some(&user_agent())
325        );
326        // SDK defaults (timeout, pooling) must stay untouched.
327        assert_eq!(http.timeout_secs, None);
328        assert_eq!(http.pool_max_idle_per_host, None);
329    }
330}