From 1e7f8678ebe52067f22f099f951484a5302a17e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torbj=C3=B6rn=20Molin?= Date: Mon, 9 Nov 2026 12:56:54 +0100 Subject: [PATCH] Added custom auth support --- README.md | 13 +- crates/app/src/action.rs | 35 +++-- crates/app/src/action/tests.rs | 75 +++++++++-- crates/app/src/state.rs | 16 +-- crates/app/src/strings.rs | 7 +- crates/app/src/ui/request.rs | 63 ++++++--- crates/app/src/ui/sidebar.rs | 2 +- crates/app/src/ui/windows.rs | 30 +++-- crates/core/src/folder.rs | 233 ++++++++++++++++++++++++++++----- 9 files changed, 377 insertions(+), 97 deletions(-) diff --git a/README.md b/README.md index d291035..ec34c1c 100644 --- a/README.md +++ b/README.md @@ -75,14 +75,19 @@ Other things worth knowing: form stay in sync. - The **Auth** tab is a helper that writes the `Authorization` header. Basic auth is written as `Basic user password` and encoded when sent, like JetBrains. + *Custom header* sends auth in a header of your choice (e.g. `X-API-Key`); the + request is marked with `# @auth-header X-API-Key` so reqlite knows that header + is its auth. - **Folder auth:** right-click a folder → *Folder auth…* (or a collection → *Default auth…*) to set auth that every request below it uses when it has no `Authorization` header of its own. The nearest folder wins; a folder can also say *None* to stop inheritance. In a request's Auth tab, *Inherit* (no header) uses it and *None* opts out with `# @no-auth`. It is stored in - `/.reqlite/folder.json` as `{ "auth": "Bearer {{token}}" }` - (`null` = none); other `.http` tools ignore it. The CLI applies it too. -- **Consolidate auth…** (same menus) removes `Authorization` headers that match + `/.reqlite/folder.json` as `{ "auth": "Bearer {{token}}" }`, or + `{ "auth": { "header": "X-API-Key", "value": "{{api_key}}" } }` for a custom + header (`null` = none); other `.http` tools ignore it. A request that already + sets the folder's custom header itself keeps its own value. The CLI applies it too. +- **Consolidate auth…** (same menus) removes auth headers that match what the request would inherit. If the folder has no auth yet, it offers the most used header as the folder's auth, and can pin requests that would otherwise change (they get their current header, or `# @no-auth`). @@ -129,7 +134,7 @@ on: - Directives: `# @name`, `# @no-redirect`, `# @no-cookie-jar`, `# @no-log`, `# @timeout 30` / `500 ms`, `# @connection-timeout`. `# @insecure` is a reqlite extension written by curl import for `-k`; `# @no-auth` is one that - skips folder auth. + skips folder auth, and `# @auth-header ` marks a custom auth header. - `#` and `//` comments. Anything else (unknown directives, response handlers `> {% … %}` and diff --git a/crates/app/src/action.rs b/crates/app/src/action.rs index 089bd1f..9c0c2d0 100644 --- a/crates/app/src/action.rs +++ b/crates/app/src/action.rs @@ -8,7 +8,9 @@ use std::time::{Instant, SystemTime, UNIX_EPOCH}; use reqlite_core::collection::{self, Collection}; use reqlite_core::env::{self, Environments}; use reqlite_core::export::curl::to_curl; -use reqlite_core::folder::{self, auth_mode, same_auth, with_inherited_auth, AuthMode, FolderAuth, FolderSettings}; +use reqlite_core::folder::{ + self, auth_mode, same_auth, with_inherited_auth, AuthHeader, AuthMode, FolderAuth, FolderSettings, +}; use reqlite_core::http::{HttpError, Response}; use reqlite_core::httpfile::{render_request, HttpFile}; use reqlite_core::import::curl::{from_curl, looks_like_curl}; @@ -154,7 +156,7 @@ pub enum Action { /// `target` picks the auth to inherit when the folder has none. ConsolidateAuth { dir: PathBuf, - target: Option, + target: Option, }, ApplyConsolidateAuth(ConsolidateAuth), @@ -320,13 +322,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { } Action::HeadersEdited(id, headers) => edit(state, id, |r| r.headers = headers), Action::BodyEdited(id, body) => edit(state, id, |r| r.body = body), - Action::AuthEdited(id, mode) => edit(state, id, |r| { - match &mode { - AuthMode::Own(v) => r.set_header("Authorization", v.as_str()), - AuthMode::NoAuth | AuthMode::Inherit => r.remove_header("Authorization"), - } - folder::set_no_auth(r, mode == AuthMode::NoAuth); - }), + Action::AuthEdited(id, mode) => edit(state, id, |r| folder::set_auth_mode(r, &mode)), Action::SetNoRedirect(id, on) => edit(state, id, |r| r.directives.no_redirect = on), Action::PickBodyFile(id) => fx.push(Effect::PickBodyFile(id)), Action::BodyFilePicked(id, path) => { @@ -1434,14 +1430,14 @@ fn slug_name(title: &str) -> String { } /// Works out what "Consolidate auth" on `dir` would do: which requests can -/// drop their own Authorization header and inherit `dir`'s auth instead. +/// drop their own auth header and inherit `dir`'s auth instead. /// When `dir` has no auth of its own, `pick` (or what it already inherits, /// or the most used header) becomes its auth. -pub fn plan_consolidation(state: &AppState, dir: &Path, pick: Option) -> Option { +pub fn plan_consolidation(state: &AppState, dir: &Path, pick: Option) -> Option { let c = state.collection_of(dir)?; let requests: Vec<_> = c.all_requests().filter(|(p, _, _)| p.starts_with(dir)).collect(); - let mut choices: Vec<(String, usize)> = Vec::new(); + let mut choices: Vec<(AuthHeader, usize)> = Vec::new(); for (_, _, r) in &requests { if let AuthMode::Own(v) = auth_mode(r) { match choices.iter_mut().find(|(c, _)| same_auth(c, &v)) { @@ -1549,7 +1545,7 @@ enum AuthFix { /// Drop its own header so it inherits. Inherit, /// Pin the auth it sends today (a header, or `# @no-auth` for `None`). - Keep(Option), + Keep(Option), } fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec) { @@ -1583,14 +1579,15 @@ fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec // The file may have changed since the plan was made. match (&edit, auth_mode(&r)) { (AuthFix::Inherit, AuthMode::Own(_)) => { - r.remove_header("Authorization"); + folder::set_auth_mode(&mut r, &AuthMode::Inherit); dropped += 1; } (AuthFix::Keep(before), AuthMode::Inherit) => { - match before { - Some(v) => r.set_header("Authorization", v.as_str()), - None => folder::set_no_auth(&mut r, true), - } + let mode = match before { + Some(h) => AuthMode::Own(h.clone()), + None => AuthMode::NoAuth, + }; + folder::set_auth_mode(&mut r, &mode); pinned += 1; } _ => continue, @@ -1621,7 +1618,7 @@ fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec settings.auth = FolderAuth::Header(target.clone()); ops.push(FileOp::Write(folder::settings_path(&plan.dir), settings.to_json())); c.folders.insert(plan.dir.clone(), settings); - msg.push(txt::consolidate::set_folder(target)); + msg.push(txt::consolidate::set_folder(&target.to_string())); } } if dropped > 0 { diff --git a/crates/app/src/action/tests.rs b/crates/app/src/action/tests.rs index 12046dc..2f46936 100644 --- a/crates/app/src/action/tests.rs +++ b/crates/app/src/action/tests.rs @@ -8,7 +8,7 @@ use reqlite_core::collection::{Collection, Node}; use reqlite_core::env::EnvFile; use reqlite_core::http::{BodyStore, Timings}; -use reqlite_core::folder::{AuthMode, FolderAuth}; +use reqlite_core::folder::{AuthHeader, AuthMode, FolderAuth}; use super::*; @@ -1180,6 +1180,69 @@ fn requests_inherit_folder_auth_unless_they_opt_out() { assert_eq!(sent_auth(&mut s, own).as_deref(), Some("Bearer root")); } +fn sent_header(s: &mut AppState, id: TabId, name: &str) -> Option { + let fx = update(s, Action::Send(id)); + let Some(Effect::SendRequest { request, .. }) = fx.first() else { + panic!("not sent: {:?}", s.tab(id).unwrap().error) + }; + let v = request + .headers + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.clone()); + update(s, Action::Cancel(id)); + v +} + +#[test] +fn folder_and_request_auth_can_use_a_custom_header() { + let mut s = state(); + let root = with_collection( + &mut s, + &[("a.http", "### Plain\nGET http://x/a\n\n### Own\nGET http://x/b\n")], + ); + let open = |s: &mut AppState, index| { + update( + s, + Action::OpenRequest { + file: root.join("a.http"), + index, + }, + ); + active(s) + }; + let plain = open(&mut s, 0); + let own = open(&mut s, 1); + + let key = |v: &str| AuthHeader::custom("X-API-Key", v); + let fx = set_folder_auth(&mut s, root.clone(), FolderAuth::Header(key("k-root"))); + assert_eq!( + writes(&fx), + vec![( + root.join(".reqlite/folder.json"), + "{\n \"auth\": {\n \"header\": \"X-API-Key\",\n \"value\": \"k-root\"\n }\n}\n".into() + )] + ); + assert_eq!(sent_header(&mut s, plain, "x-api-key").as_deref(), Some("k-root")); + assert_eq!(sent_auth(&mut s, plain), None); + + // A request's own custom header replaces the folder's. + update(&mut s, Action::AuthEdited(own, AuthMode::Own(key("k-own")))); + assert!(s + .tab(own) + .unwrap() + .source + .contains("# @auth-header X-API-Key\nGET http://x/b\nX-API-Key: k-own\n")); + assert_eq!(sent_header(&mut s, own, "x-api-key").as_deref(), Some("k-own")); + + // Switching to Bearer drops the custom header and the directive. + update(&mut s, Action::AuthEdited(own, AuthMode::Own("Bearer t".into()))); + let src = &s.tab(own).unwrap().source; + assert!(!src.contains("X-API-Key") && !src.contains("@auth-header"), "{src}"); + assert_eq!(sent_auth(&mut s, own).as_deref(), Some("Bearer t")); + assert_eq!(sent_header(&mut s, own, "x-api-key"), None); +} + #[test] fn folder_settings_files_are_reloaded_when_they_change() { let mut s = state(); @@ -1213,7 +1276,7 @@ fn consolidate(s: &mut AppState, dir: PathBuf, target: Option<&str>) -> Consolid s, Action::ConsolidateAuth { dir, - target: target.map(str::to_string), + target: target.map(Into::into), }, ); match &s.dialog { @@ -1229,7 +1292,7 @@ fn consolidating_adopts_the_most_common_auth_as_the_collection_default() { let mut s = state(); let root = with_collection(&mut s, &[("a.http", MIXED)]); let plan = consolidate(&mut s, root.clone(), None); - assert_eq!(plan.target.as_deref(), Some("Bearer {{token}}")); + assert_eq!(plan.target, Some("Bearer {{token}}".into())); assert!(plan.set_folder); assert_eq!( plan.choices, @@ -1295,11 +1358,7 @@ fn consolidating_keeps_subfolder_overrides_and_skips_unsaved_tabs() { update(&mut s, Action::UrlEdited(id, "http://x/edited".into())); let plan = consolidate(&mut s, root.clone(), Some("Basic ignored")); - assert_eq!( - plan.target.as_deref(), - Some("Bearer root"), - "the folder's own auth wins" - ); + assert_eq!(plan.target, Some("Bearer root".into()), "the folder's own auth wins"); assert!(!plan.set_folder && plan.choices.is_empty()); let own: Vec<(&str, bool)> = plan .own diff --git a/crates/app/src/state.rs b/crates/app/src/state.rs index c51c859..bc442a8 100644 --- a/crates/app/src/state.rs +++ b/crates/app/src/state.rs @@ -9,7 +9,7 @@ use std::time::{Instant, SystemTime}; use reqlite_core::collection::Node; use reqlite_core::cookies::CookieJar; use reqlite_core::env::Environments; -use reqlite_core::folder::{self, FolderAuth, FolderSettings, InheritedAuth}; +use reqlite_core::folder::{self, AuthHeader, FolderAuth, FolderSettings, InheritedAuth}; use reqlite_core::http::{BodyStore, Response}; use reqlite_core::httpfile::{HttpFile, RequestKey}; use reqlite_core::params::Param; @@ -108,17 +108,17 @@ pub struct RequestRef { pub struct ConsolidateAuth { pub dir: PathBuf, /// The auth requests in `dir` should inherit. - pub target: Option, + pub target: Option, /// `dir` doesn't have `target` as its own setting yet; applying writes it. pub set_folder: bool, /// Values to pick `target` from (with how many requests use each), when /// `dir` has no auth of its own. - pub choices: Vec<(String, usize)>, - /// Requests with their own Authorization header. + pub choices: Vec<(AuthHeader, usize)>, + /// Requests with their own auth header. pub own: Vec, /// Requests that inherit today and would send something else once /// `target` is set on the folder. - pub affected: Vec<(RequestRef, Option)>, + pub affected: Vec<(RequestRef, Option)>, /// Give the affected requests their current auth explicitly (a header, /// or `# @no-auth`) so they keep sending what they send today. pub keep_affected: bool, @@ -129,9 +129,9 @@ pub struct ConsolidateAuth { #[derive(Debug, Clone, PartialEq, Eq)] pub struct OwnAuth { pub request: RequestRef, - pub value: String, + pub value: AuthHeader, /// What the request would inherit without its header. - pub inherits: Option, + pub inherits: Option, /// Remove the header. pub selected: bool, } @@ -140,7 +140,7 @@ impl OwnAuth { /// Removing the header keeps the request sending the same thing. pub fn same(&self) -> bool { self.inherits - .as_deref() + .as_ref() .is_some_and(|i| folder::same_auth(i, &self.value)) } } diff --git a/crates/app/src/strings.rs b/crates/app/src/strings.rs index 0ac54a5..d88dc01 100644 --- a/crates/app/src/strings.rs +++ b/crates/app/src/strings.rs @@ -176,6 +176,11 @@ pub mod auth { pub const NOT_SET: &str = "Not set"; pub const BASIC: &str = "Basic"; pub const BEARER: &str = "Bearer token"; + pub const CUSTOM_HEADER: &str = "Custom header"; + pub const HEADER_NAME: &str = "Header"; + pub const VALUE: &str = "Value"; + pub const CUSTOM_NOTE: &str = + "Sent as `Header: value` instead of Authorization; a request marks it with `# @auth-header Header`."; pub const USERNAME: &str = "Username"; pub const PASSWORD: &str = "Password"; pub const BASIC_NOTE: &str = @@ -184,7 +189,7 @@ pub mod auth { pub const HEADER_VALUE: &str = "Header value"; pub const NO_AUTH_SET: &str = "No Authorization header, not even the folder's (`# @no-auth`)."; pub const CUSTOM: &str = "Custom Authorization header:"; - pub const SECRETS_NOTE: &str = "Auth is just the Authorization header; put secrets in the private env file."; + pub const SECRETS_NOTE: &str = "Auth is just a header; put secrets in the private env file."; pub const NOT_IN_COLLECTION: &str = "Not in a collection, so there is nothing to inherit."; pub const USES: &str = "Uses"; diff --git a/crates/app/src/ui/request.rs b/crates/app/src/ui/request.rs index 11c5a68..1d90e93 100644 --- a/crates/app/src/ui/request.rs +++ b/crates/app/src/ui/request.rs @@ -2,7 +2,7 @@ use base64::Engine; use egui::{Key, RichText, Ui}; -use reqlite_core::folder::{auth_mode, AuthMode, InheritedAuth}; +use reqlite_core::folder::{auth_mode, AuthHeader, AuthMode, InheritedAuth}; use reqlite_core::params::Param; use reqlite_core::{Body, Header, Method, Part, PartBody}; @@ -520,16 +520,20 @@ pub enum AuthKind { None, Basic, Bearer, + /// A header other than Authorization, e.g. `X-API-Key`. + Custom, + /// An Authorization value that isn't Basic or Bearer. Other, } impl AuthKind { - /// The header value a newly picked kind starts with. - pub fn template(self) -> Option { + /// The header a newly picked kind starts with. + pub fn template(self) -> AuthHeader { match self { - AuthKind::Basic => Some("Basic {{username}} {{password}}".into()), - AuthKind::Bearer => Some("Bearer {{token}}".into()), - _ => None, + AuthKind::Basic => AuthHeader::authorization("Basic {{username}} {{password}}"), + AuthKind::Bearer => AuthHeader::authorization("Bearer {{token}}"), + AuthKind::Custom => AuthHeader::custom("X-API-Key", "{{api_key}}"), + _ => AuthHeader::authorization(""), } } } @@ -561,8 +565,12 @@ fn auth_parts(value: Option<&str>) -> (AuthKind, String, String) { (AuthKind::Other, v.to_string(), String::new()) } -pub fn header_kind(value: &str) -> AuthKind { - auth_parts(Some(value)).0 +pub fn header_kind(h: &AuthHeader) -> AuthKind { + if h.is_authorization() { + auth_parts(Some(&h.value)).0 + } else { + AuthKind::Custom + } } /// A row of radio buttons; returns the kind picked when it changed. @@ -579,9 +587,32 @@ pub fn auth_kind_row(ui: &mut Ui, current: AuthKind, kinds: &[(AuthKind, &str)]) picked } -/// The fields for an Authorization header value (Basic, Bearer or custom); -/// returns the new value when it was edited. -pub fn auth_value_fields(ui: &mut Ui, value: &str, vars: &VarCtx, salt: &str) -> Option { +/// The fields for an auth header (Basic, Bearer, a custom header or a +/// custom Authorization value); returns the new header when it was edited. +pub fn auth_value_fields(ui: &mut Ui, header: &AuthHeader, vars: &VarCtx, salt: &str) -> Option { + if !header.is_authorization() { + let (mut name, mut value) = (header.name.clone(), header.value.clone()); + let mut changed = false; + egui::Grid::new(("custom", salt)).num_columns(2).show(ui, |ui| { + ui.label(txt::auth::HEADER_NAME); + changed |= ui + .add( + egui::TextEdit::singleline(&mut name) + .desired_width(260.0) + .id_salt(("cn", salt)), + ) + .changed(); + ui.end_row(); + ui.label(txt::auth::VALUE); + changed |= var_text_edit(ui, &mut value, Some(vars), "", 420.0, ("cv", salt)).changed(); + ui.end_row(); + }); + ui.label(RichText::new(txt::auth::CUSTOM_NOTE).small().weak()); + // A header needs a name; keep the old one while the field is empty. + let name = name.trim(); + return (changed && !name.is_empty() && !name.contains(':')).then(|| AuthHeader::custom(name, value)); + } + let value = header.value.as_str(); let (kind, a, b) = auth_parts(Some(value)); let mut out = None; match kind { @@ -620,7 +651,7 @@ pub fn auth_value_fields(ui: &mut Ui, value: &str, vars: &VarCtx, salt: &str) -> }); } } - out + out.map(AuthHeader::authorization) } fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec) { @@ -636,6 +667,7 @@ fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec< (AuthKind::None, txt::common::NONE), (AuthKind::Basic, txt::auth::BASIC), (AuthKind::Bearer, txt::auth::BEARER), + (AuthKind::Custom, txt::auth::CUSTOM_HEADER), ]; if let Some(k) = auth_kind_row(ui, kind, &kinds) { acts.push(Action::AuthEdited( @@ -643,7 +675,7 @@ fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec< match k { AuthKind::Inherit => AuthMode::Inherit, AuthKind::None => AuthMode::NoAuth, - k => AuthMode::Own(k.template().unwrap_or_default()), + k => AuthMode::Own(k.template()), }, )); } @@ -676,7 +708,7 @@ fn inherited(ui: &mut Ui, state: &AppState, tab: &Tab, acts: &mut Vec) { Some(InheritedAuth { from, value: Some(v) }) => { ui.horizontal_wrapped(|ui| { ui.label(txt::auth::USES); - ui.label(RichText::new(&v).monospace()); + ui.label(RichText::new(v.to_string()).monospace()); ui.label(txt::auth::from_folder(&c.folder_label(&from))); }); } @@ -737,6 +769,7 @@ mod tests { let (k, t, _) = auth_parts(Some("Bearer abc")); assert!(k == AuthKind::Bearer && t == "abc"); assert!(auth_parts(Some("Digest x")).0 == AuthKind::Other); - assert!(header_kind("Bearer {{t}}") == AuthKind::Bearer); + assert!(header_kind(&AuthHeader::authorization("Bearer {{t}}")) == AuthKind::Bearer); + assert!(header_kind(&AuthHeader::custom("X-API-Key", "Bearer x")) == AuthKind::Custom); } } diff --git a/crates/app/src/ui/sidebar.rs b/crates/app/src/ui/sidebar.rs index a287a50..2c5d065 100644 --- a/crates/app/src/ui/sidebar.rs +++ b/crates/app/src/ui/sidebar.rs @@ -197,7 +197,7 @@ fn node(ui: &mut Ui, state: &AppState, c: &CollectionState, n: &Node, acts: &mut }); let mut header = resp.header_response; if let reqlite_core::folder::FolderAuth::Header(v) = c.folder_auth(path) { - header = header.on_hover_text(txt::sidebar::folder_auth_hover(&v)); + header = header.on_hover_text(txt::sidebar::folder_auth_hover(&v.to_string())); } header.context_menu(|ui| { if ui.button(txt::sidebar::NEW_HTTP_FILE).clicked() { diff --git a/crates/app/src/ui/windows.rs b/crates/app/src/ui/windows.rs index d5b0b94..1cc95f0 100644 --- a/crates/app/src/ui/windows.rs +++ b/crates/app/src/ui/windows.rs @@ -215,12 +215,13 @@ fn folder_auth(ui: &mut egui::Ui, state: &AppState, ed: &FolderAuthEdit, acts: & (AuthKind::None, txt::common::NONE), (AuthKind::Basic, txt::auth::BASIC), (AuthKind::Bearer, txt::auth::BEARER), + (AuthKind::Custom, txt::auth::CUSTOM_HEADER), ]; if let Some(k) = auth_kind_row(ui, kind, &kinds) { acts.push(set(match k { AuthKind::Inherit => FolderAuth::Inherit, AuthKind::None => FolderAuth::None, - k => FolderAuth::Header(k.template().unwrap_or_default()), + k => FolderAuth::Header(k.template()), })); } ui.add_space(6.0); @@ -231,7 +232,9 @@ fn folder_auth(ui: &mut egui::Ui, state: &AppState, ed: &FolderAuthEdit, acts: & FolderAuth::Inherit => { let parent = ed.dir.parent().and_then(|p| c.inherited_auth(p)); let text = match parent { - Some(InheritedAuth { from, value: Some(v) }) => txt::auth::parent_uses(&v, &c.folder_label(&from)), + Some(InheritedAuth { from, value: Some(v) }) => { + txt::auth::parent_uses(&v.to_string(), &c.folder_label(&from)) + } Some(InheritedAuth { from, value: None }) => txt::auth::parent_none(&c.folder_label(&from)), None => txt::auth::NO_PARENT_AUTH.into(), }; @@ -290,13 +293,13 @@ fn consolidate_auth(ui: &mut egui::Ui, state: &AppState, plan: &ConsolidateAuth, ui.horizontal(|ui| { ui.label(txt::consolidate::SHARED_AUTH); if plan.choices.is_empty() { - ui.label(RichText::new(target).monospace()); + ui.label(RichText::new(target.to_string()).monospace()); } else { egui::ComboBox::from_id_salt("consolidate-target") - .selected_text(RichText::new(target).monospace()) + .selected_text(RichText::new(target.to_string()).monospace()) .show_ui(ui, |ui| { for (v, n) in &plan.choices { - let label = txt::consolidate::choice(v, *n); + let label = txt::consolidate::choice(&v.to_string(), *n); if ui.selectable_label(v == target, label).clicked() && v != target { acts.push(Action::ConsolidateAuth { dir: plan.dir.clone(), @@ -345,17 +348,22 @@ fn consolidate_auth(ui: &mut egui::Ui, state: &AppState, plan: &ConsolidateAuth, .show(ui, |ui| { for (i, o) in plan.own.iter().enumerate() { let mut on = o.selected; - let resp = ui.checkbox(&mut on, &o.request.label).on_hover_text(&o.value); + let resp = ui + .checkbox(&mut on, &o.request.label) + .on_hover_text(o.value.to_string()); if resp.changed() { let mut p = plan.clone(); p.own[i].selected = on; acts.push(set(p)); } if !o.same() { - let would = o.inherits.as_deref().unwrap_or(txt::common::NO_AUTH); + let would = o + .inherits + .as_ref() + .map_or(txt::common::NO_AUTH.into(), |h| h.to_string()); ui.indent(("diff", i), |ui| { ui.label( - RichText::new(txt::consolidate::would_send(&o.value, would)) + RichText::new(txt::consolidate::would_send(&o.value.to_string(), &would)) .small() .color(ui.visuals().warn_fg_color), ); @@ -367,14 +375,14 @@ fn consolidate_auth(ui: &mut egui::Ui, state: &AppState, plan: &ConsolidateAuth, if plan.set_folder && !plan.affected.is_empty() { ui.add_space(8.0); - ui.label(txt::consolidate::affected(plan.affected.len(), target)); + ui.label(txt::consolidate::affected(plan.affected.len(), &target.to_string())); egui::ScrollArea::vertical() .id_salt("consolidate-affected") .max_height(120.0) .show(ui, |ui| { for (r, before) in &plan.affected { - let now = before.as_deref().unwrap_or(txt::common::NO_AUTH); - ui.label(txt::consolidate::affected_item(&r.label, now)); + let now = before.as_ref().map_or(txt::common::NO_AUTH.into(), |h| h.to_string()); + ui.label(txt::consolidate::affected_item(&r.label, &now)); } }); let mut keep = plan.keep_affected; diff --git a/crates/core/src/folder.rs b/crates/core/src/folder.rs index d7d1cab..53d9cc5 100644 --- a/crates/core/src/folder.rs +++ b/crates/core/src/folder.rs @@ -1,11 +1,13 @@ //! Per-folder settings, a reqlite extension: `/.reqlite/folder.json`. //! -//! For now it only holds the folder's default auth, an `Authorization` -//! header value that requests in the folder (and its subfolders) use when -//! they don't set one themselves: +//! For now it only holds the folder's default auth, a header that requests +//! in the folder (and its subfolders) use when they don't set auth +//! themselves. A string is an `Authorization` header value; an object names +//! some other header: //! //! ```json //! { "auth": "Bearer {{token}}" } +//! { "auth": { "header": "X-API-Key", "value": "{{api_key}}" } } //! ``` //! //! `"auth": null` means "no auth" (it stops inheritance from parent @@ -24,6 +26,57 @@ pub const DIR: &str = ".reqlite"; pub const FILE: &str = "folder.json"; /// `# @no-auth`: the request sends no auth even if its folder has one. pub const NO_AUTH_DIRECTIVE: &str = "no-auth"; +/// `# @auth-header X-API-Key`: the request's own auth is that header rather +/// than `Authorization`. +pub const AUTH_HEADER_DIRECTIVE: &str = "auth-header"; +pub const AUTHORIZATION: &str = "Authorization"; + +/// The header auth is sent in: usually `Authorization`, but APIs that take a +/// key in a header of their own (`X-API-Key: …`) are common too. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuthHeader { + pub name: String, + pub value: String, +} + +impl AuthHeader { + /// An `Authorization` header with this value. + pub fn authorization(value: impl Into) -> Self { + Self { + name: AUTHORIZATION.into(), + value: value.into(), + } + } + + pub fn custom(name: impl Into, value: impl Into) -> Self { + Self { + name: name.into(), + value: value.into(), + } + } + + pub fn is_authorization(&self) -> bool { + self.name.eq_ignore_ascii_case(AUTHORIZATION) + } +} + +/// An `Authorization` header value, like the string form in folder.json. +impl From<&str> for AuthHeader { + fn from(value: &str) -> Self { + Self::authorization(value) + } +} + +/// The value for `Authorization`, `Name: value` for other headers. +impl std::fmt::Display for AuthHeader { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.is_authorization() { + f.write_str(&self.value) + } else { + write!(f, "{}: {}", self.name, self.value) + } + } +} #[derive(Debug, thiserror::Error)] pub enum FolderError { @@ -40,8 +93,8 @@ pub enum FolderAuth { Inherit, /// No auth for this folder, whatever the parents say. None, - /// An `Authorization` header value, e.g. `Bearer {{token}}`. - Header(String), + /// A header, e.g. `Authorization: Bearer {{token}}`. + Header(AuthHeader), } #[derive(Debug, Clone, PartialEq, Eq, Default)] @@ -69,7 +122,20 @@ impl FolderSettings { None => FolderAuth::Inherit, Some(Value::Null) => FolderAuth::None, Some(Value::String(s)) if s.trim().is_empty() => FolderAuth::None, - Some(Value::String(s)) => FolderAuth::Header(s), + Some(Value::String(s)) => FolderAuth::Header(AuthHeader::authorization(s)), + Some(Value::Object(o)) => { + let field = |k: &str| o.get(k).and_then(Value::as_str).map(str::to_string); + match (field("header"), field("value")) { + (Some(name), Some(value)) if !name.trim().is_empty() => { + FolderAuth::Header(AuthHeader::custom(name.trim(), value)) + } + _ => { + return Err(FolderError::Shape { + path: path.to_path_buf(), + }) + } + } + } Some(_) => { return Err(FolderError::Shape { path: path.to_path_buf(), @@ -86,8 +152,11 @@ impl FolderSettings { FolderAuth::None => { map.insert("auth".into(), Value::Null); } + FolderAuth::Header(h) if h.is_authorization() => { + map.insert("auth".into(), Value::String(h.value.clone())); + } FolderAuth::Header(h) => { - map.insert("auth".into(), Value::String(h.clone())); + map.insert("auth".into(), serde_json::json!({ "header": h.name, "value": h.value })); } } map.extend(self.other.clone()); @@ -127,8 +196,8 @@ pub fn settings_dir(path: &Path) -> Option<&Path> { pub struct InheritedAuth { /// The folder whose setting applies. pub from: PathBuf, - /// The header value; `None` when that folder says "no auth". - pub value: Option, + /// The header; `None` when that folder says "no auth". + pub value: Option, } /// Walks from `dir` up to `root` (inclusive) and returns the first folder @@ -193,11 +262,21 @@ pub fn set_no_auth(req: &mut Request, on: bool) { } } +/// The header named by `# @auth-header`, if any. +fn auth_header_directive(req: &Request) -> Option<&str> { + req.directives + .other + .iter() + .find(|(n, v)| n == AUTH_HEADER_DIRECTIVE && !v.trim().is_empty()) + .map(|(_, v)| v.trim()) +} + /// How a request gets its auth. #[derive(Debug, Clone, PartialEq, Eq)] pub enum AuthMode { - /// It has its own `Authorization` header. - Own(String), + /// It has its own auth header: `Authorization`, or the one named by + /// `# @auth-header`. + Own(AuthHeader), /// `# @no-auth`. NoAuth, /// From its folder. @@ -205,29 +284,58 @@ pub enum AuthMode { } pub fn auth_mode(req: &Request) -> AuthMode { - match req.header("authorization") { - Some(v) => AuthMode::Own(v.to_string()), + let custom = auth_header_directive(req).and_then(|n| Some(AuthHeader::custom(n, req.header(n)?))); + if let Some(h) = custom { + return AuthMode::Own(h); + } + match req.header(AUTHORIZATION) { + Some(v) => AuthMode::Own(AuthHeader::authorization(v)), None if has_no_auth(req) => AuthMode::NoAuth, None => AuthMode::Inherit, } } -/// The request as it is sent: with the inherited `Authorization` header -/// added when it inherits one. +/// Changes how the request gets its auth: drops its current auth header +/// (and `# @auth-header` / `# @no-auth`), then writes the new one. +pub fn set_auth_mode(req: &mut Request, mode: &AuthMode) { + if let Some(n) = auth_header_directive(req).map(str::to_string) { + req.remove_header(&n); + } + req.remove_header(AUTHORIZATION); + req.directives + .other + .retain(|(n, _)| n != AUTH_HEADER_DIRECTIVE && n != NO_AUTH_DIRECTIVE); + match mode { + AuthMode::Own(h) => { + if !h.is_authorization() { + req.directives + .other + .push((AUTH_HEADER_DIRECTIVE.into(), h.name.clone())); + } + req.set_header(&h.name, h.value.as_str()); + } + AuthMode::NoAuth => set_no_auth(req, true), + AuthMode::Inherit => {} + } +} + +/// The request as it is sent: with the inherited auth header added when it +/// inherits one (a header the request already sets wins). pub fn with_inherited_auth<'a>(req: &'a Request, inherited: Option<&InheritedAuth>) -> Cow<'a, Request> { - match (auth_mode(req), inherited.and_then(|i| i.value.as_deref())) { - (AuthMode::Inherit, Some(v)) => { + match (auth_mode(req), inherited.and_then(|i| i.value.as_ref())) { + (AuthMode::Inherit, Some(h)) if h.is_authorization() || req.header(&h.name).is_none() => { let mut r = req.clone(); - r.set_header("Authorization", v); + r.set_header(&h.name, h.value.as_str()); Cow::Owned(r) } _ => Cow::Borrowed(req), } } -/// Whether two header values are the same auth (ignoring spacing). -pub fn same_auth(a: &str, b: &str) -> bool { - a.split_whitespace().eq(b.split_whitespace()) +/// Whether two headers are the same auth (ignoring the name's case and the +/// value's spacing). +pub fn same_auth(a: &AuthHeader, b: &AuthHeader) -> bool { + a.name.eq_ignore_ascii_case(&b.name) && a.value.split_whitespace().eq(b.value.split_whitespace()) } #[cfg(test)] @@ -240,7 +348,7 @@ mod tests { fn parses_and_writes_back() { let p = Path::new("f.json"); let s = FolderSettings::parse(r#"{ "auth": "Bearer {{t}}", "x": 1 }"#, p).unwrap(); - assert_eq!(s.auth, FolderAuth::Header("Bearer {{t}}".into())); + assert_eq!(s.auth, FolderAuth::Header(AuthHeader::authorization("Bearer {{t}}"))); assert_eq!(FolderSettings::parse(&s.to_json(), p).unwrap(), s); assert!(s.to_json().contains("\"x\": 1")); assert_eq!( @@ -251,6 +359,12 @@ mod tests { assert!(FolderSettings::parse("{}", p).unwrap().is_empty()); assert!(FolderSettings::parse(r#"{"auth": 3}"#, p).is_err()); assert!(FolderSettings::parse("[]", p).is_err()); + + let s = FolderSettings::parse(r#"{"auth": {"header": "X-API-Key", "value": "{{k}}"}}"#, p).unwrap(); + assert_eq!(s.auth, FolderAuth::Header(AuthHeader::custom("X-API-Key", "{{k}}"))); + assert_eq!(FolderSettings::parse(&s.to_json(), p).unwrap(), s); + assert!(FolderSettings::parse(r#"{"auth": {"header": "", "value": "x"}}"#, p).is_err()); + assert!(FolderSettings::parse(r#"{"auth": {"value": "x"}}"#, p).is_err()); } #[test] @@ -266,7 +380,7 @@ mod tests { fn inherits_from_the_nearest_folder_within_the_root() { let mut m = BTreeMap::new(); let hdr = |s: &str| FolderSettings { - auth: FolderAuth::Header(s.into()), + auth: FolderAuth::Header(AuthHeader::authorization(s)), ..Default::default() }; m.insert(PathBuf::from("/"), hdr("outside")); @@ -282,7 +396,10 @@ mod tests { let get = |p: &Path| m.get(p); let root = Path::new("/c"); let a = inherited_auth(root, Path::new("/c/api/v2"), get).unwrap(); - assert_eq!((a.from.as_path(), a.value.as_deref()), (root, Some("Bearer root"))); + assert_eq!( + (a.from.as_path(), a.value.map(|h| h.value).as_deref()), + (root, Some("Bearer root")) + ); let a = inherited_auth(root, Path::new("/c/public/x"), get).unwrap(); assert_eq!(a.value, None); assert_eq!(inherited_auth(Path::new("/d"), Path::new("/d/x"), get), None); @@ -294,11 +411,15 @@ mod tests { let modes: Vec<_> = f.requests().map(auth_mode).collect(); assert_eq!( modes, - vec![AuthMode::Own("Bearer own".into()), AuthMode::NoAuth, AuthMode::Inherit] + vec![ + AuthMode::Own(AuthHeader::authorization("Bearer own")), + AuthMode::NoAuth, + AuthMode::Inherit + ] ); let inh = InheritedAuth { from: "/c".into(), - value: Some("Bearer folder".into()), + value: Some(AuthHeader::authorization("Bearer folder")), }; let sent: Vec<_> = f .requests() @@ -316,7 +437,59 @@ mod tests { let mut r = f.request(2).unwrap().clone(); set_no_auth(&mut r, true); assert!(f.replace_request(2, &r).unwrap().ends_with("###\n# @no-auth\nGET /c\n")); - assert!(same_auth("Basic a b", "Basic a b")); + assert!(same_auth( + &AuthHeader::authorization("Basic a b"), + &AuthHeader::authorization("Basic a b") + )); + assert!(!same_auth( + &AuthHeader::authorization("k"), + &AuthHeader::custom("X-API-Key", "k") + )); + } + + #[test] + fn custom_header_auth() { + let f = HttpFile::parse( + "# @auth-header X-API-Key\nGET /a\nX-API-Key: own\n\n###\nGET /b\nX-API-Key: plain\n\n###\nGET /c\n", + ); + let key = |s: &str| AuthHeader::custom("X-API-Key", s); + assert_eq!(f.request(0).map(auth_mode), Some(AuthMode::Own(key("own")))); + // Without the directive the header is just a header. + assert_eq!(f.request(1).map(auth_mode), Some(AuthMode::Inherit)); + + let inh = InheritedAuth { + from: "/c".into(), + value: Some(key("folder")), + }; + let sent: Vec<_> = f + .requests() + .map(|r| { + with_inherited_auth(r, Some(&inh)) + .header("x-api-key") + .map(str::to_string) + }) + .collect(); + assert_eq!( + sent, + vec![Some("own".into()), Some("plain".into()), Some("folder".into())] + ); + + // Switching kinds removes the old header and directive. + let mut r = f.request(0).unwrap().clone(); + set_auth_mode(&mut r, &AuthMode::Own(AuthHeader::authorization("Bearer t"))); + assert_eq!(r.header("x-api-key"), None); + assert_eq!(auth_mode(&r), AuthMode::Own(AuthHeader::authorization("Bearer t"))); + set_auth_mode(&mut r, &AuthMode::Own(key("k2"))); + assert_eq!(r.header("authorization"), None); + assert_eq!(auth_mode(&r), AuthMode::Own(key("k2"))); + assert!(f + .replace_request(0, &r) + .unwrap() + .starts_with("# @auth-header X-API-Key\nGET /a\nX-API-Key: k2\n")); + set_auth_mode(&mut r, &AuthMode::NoAuth); + assert_eq!((r.header("x-api-key"), auth_mode(&r)), (None, AuthMode::NoAuth)); + set_auth_mode(&mut r, &AuthMode::Inherit); + assert_eq!(auth_mode(&r), AuthMode::Inherit); } #[test] @@ -328,13 +501,13 @@ mod tests { std::fs::create_dir_all(dir.path().join(DIR)).unwrap(); std::fs::write(settings_path(dir.path()), r#"{"auth": "Bearer outside"}"#).unwrap(); assert_eq!( - inherited_auth_on_disk(&api).unwrap().unwrap().value.as_deref(), - Some("Bearer outside") + inherited_auth_on_disk(&api).unwrap().unwrap().value, + Some(AuthHeader::authorization("Bearer outside")) ); std::fs::write(root.join(crate::env::PUBLIC_FILE), "{}").unwrap(); assert_eq!(inherited_auth_on_disk(&api).unwrap(), None); std::fs::write(settings_path(&api), r#"{"auth": "Bearer api"}"#).unwrap(); let a = inherited_auth_on_disk(&api).unwrap().unwrap(); - assert_eq!((a.from, a.value.as_deref()), (api, Some("Bearer api"))); + assert_eq!((a.from, a.value), (api, Some(AuthHeader::authorization("Bearer api")))); } }