Added custom auth support
windows / build (push) Successful in 5m0s

This commit is contained in:
Torbjörn Molin committed 2026-11-09 12:56:54 +01:00
1 parent ae055be9cc
commit 1e7f8678eb
9 files changed
+377 -97

No files matched your search

+16 -19
View File
@@ -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<String>,
target: Option<AuthHeader>,
},
ApplyConsolidateAuth(ConsolidateAuth),
@@ -320,13 +322,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
}
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<String>) -> Option<ConsolidateAuth> {
pub fn plan_consolidation(state: &AppState, dir: &Path, pick: Option<AuthHeader>) -> Option<ConsolidateAuth> {
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<String>),
Keep(Option<AuthHeader>),
}
fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec<Effect>) {
@@ -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 {
+67 -8
View File
@@ -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<String> {
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
+8 -8
View File
@@ -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<String>,
pub target: Option<AuthHeader>,
/// `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<OwnAuth>,
/// Requests that inherit today and would send something else once
/// `target` is set on the folder.
pub affected: Vec<(RequestRef, Option<String>)>,
pub affected: Vec<(RequestRef, Option<AuthHeader>)>,
/// 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<String>,
pub inherits: Option<AuthHeader>,
/// 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))
}
}
+6 -1
View File
@@ -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";
+48 -15
View File
@@ -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<String> {
/// 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<String> {
/// 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<AuthHeader> {
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<Action>) {
@@ -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<Action>) {
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);
}
}
+1 -1
View File
@@ -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() {
+19 -11
View File
@@ -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;