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