Per collection/folder auth

This commit is contained in:
Torbjörn Molin committed 2026-10-19 12:38:38 +02:00
1 parent d5e7b484fc
commit 47ee07d9ff
16 files changed
+1569 -58

No files matched your search

+241
View File
@@ -8,6 +8,8 @@ use reqlite_core::collection::{Collection, Node};
use reqlite_core::env::EnvFile;
use reqlite_core::http::{BodyStore, Timings};
use reqlite_core::folder::{AuthMode, FolderAuth};
use super::*;
fn state() -> AppState {
@@ -59,6 +61,8 @@ fn with_collection_at(s: &mut AppState, root: &str, files: &[(&str, &str)]) -> P
.iter()
.map(|(n, t)| (root.join(n), HttpFile::parse(t.to_string())))
.collect(),
folders: Default::default(),
folder_errors: Vec::new(),
};
let fx = update(s, Action::CollectionLoaded(Ok(c)));
assert!(fx.iter().any(|e| matches!(e, Effect::Watch(_))));
@@ -1085,3 +1089,240 @@ fn renaming_an_edited_or_untitled_tab_is_an_edit_that_save_writes() {
assert_eq!(s.tab(untitled).unwrap().title(), "Scratch");
assert!(s.tab(untitled).unwrap().source.starts_with("### Scratch\n"));
}
fn sent_auth(s: &mut AppState, id: TabId) -> 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 auth = request
.headers
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case("authorization"))
.map(|(_, v)| v.clone());
update(s, Action::Cancel(id));
auth
}
fn set_folder_auth(s: &mut AppState, dir: PathBuf, auth: FolderAuth) -> Vec<Effect> {
update(s, Action::SetFolderAuth { dir, auth })
}
#[test]
fn requests_inherit_folder_auth_unless_they_opt_out() {
let mut s = state();
let root = with_collection(
&mut s,
&[
(
"a.http",
"### Plain\nGET http://x/a\n\n### Own\nGET http://x/b\nAuthorization: Bearer own\n",
),
("api/b.http", "GET http://x/c\n"),
],
);
update(
&mut s,
Action::OpenRequest {
file: root.join("a.http"),
index: 0,
},
);
let plain = active(&s);
update(
&mut s,
Action::OpenRequest {
file: root.join("a.http"),
index: 1,
},
);
let own = active(&s);
update(
&mut s,
Action::OpenRequest {
file: root.join("api/b.http"),
index: 0,
},
);
let nested = active(&s);
assert_eq!(sent_auth(&mut s, plain), None);
let fx = set_folder_auth(&mut s, root.clone(), FolderAuth::Header("Bearer root".into()));
assert_eq!(
writes(&fx),
vec![(
root.join(".reqlite/folder.json"),
"{\n \"auth\": \"Bearer root\"\n}\n".into()
)]
);
assert_eq!(sent_auth(&mut s, plain).as_deref(), Some("Bearer root"));
assert_eq!(sent_auth(&mut s, own).as_deref(), Some("Bearer own"));
assert_eq!(sent_auth(&mut s, nested).as_deref(), Some("Bearer root"));
// A subfolder overrides, and "no auth" stops inheritance.
set_folder_auth(&mut s, root.join("api"), FolderAuth::Header("Basic u p".into()));
assert_eq!(sent_auth(&mut s, nested).as_deref(), Some("Basic dTpw"));
set_folder_auth(&mut s, root.join("api"), FolderAuth::None);
assert_eq!(sent_auth(&mut s, nested), None);
// Back to inherit: the empty settings file is removed.
let fx = set_folder_auth(&mut s, root.join("api"), FolderAuth::Inherit);
assert!(fx.iter().any(|e| matches!(e, Effect::FileOps { ops, .. } if ops == &vec![FileOp::Delete(root.join("api/.reqlite/folder.json"))])));
assert_eq!(sent_auth(&mut s, nested).as_deref(), Some("Bearer root"));
// The Auth tab's None writes `# @no-auth`; Inherit removes it again.
update(&mut s, Action::AuthEdited(plain, AuthMode::NoAuth));
assert!(s.tab(plain).unwrap().source.contains("# @no-auth\nGET"));
assert_eq!(sent_auth(&mut s, plain), None);
update(&mut s, Action::AuthEdited(plain, AuthMode::Inherit));
assert!(!s.tab(plain).unwrap().source.contains("@no-auth"));
assert!(!s.tab(plain).unwrap().is_dirty());
update(&mut s, Action::AuthEdited(own, AuthMode::Inherit));
assert_eq!(sent_auth(&mut s, own).as_deref(), Some("Bearer root"));
}
#[test]
fn folder_settings_files_are_reloaded_when_they_change() {
let mut s = state();
let root = with_collection(&mut s, &[("a.http", "GET http://x/a\n")]);
let path = root.join(".reqlite/folder.json");
update(
&mut s,
Action::FileChangedOnDisk {
path: path.clone(),
text: Some(r#"{"auth": "Bearer t"}"#.into()),
},
);
let c = s.collection(&root).unwrap();
assert_eq!(c.folder_auth(&root), FolderAuth::Header("Bearer t".into()));
update(
&mut s,
Action::FileChangedOnDisk {
path: path.clone(),
text: Some("nope".into()),
},
);
assert_eq!(s.collection(&root).unwrap().folder_errors.len(), 1);
update(&mut s, Action::FileChangedOnDisk { path, text: None });
let c = s.collection(&root).unwrap();
assert_eq!(c.folder_auth(&root), FolderAuth::Inherit);
assert!(c.folder_errors.is_empty());
}
fn consolidate(s: &mut AppState, dir: PathBuf, target: Option<&str>) -> ConsolidateAuth {
update(
s,
Action::ConsolidateAuth {
dir,
target: target.map(str::to_string),
},
);
match &s.dialog {
Some(Dialog::ConsolidateAuth(p)) => p.clone(),
d => panic!("{d:?}"),
}
}
const MIXED: &str = "### A\nGET http://x/a\nAuthorization: Bearer {{token}}\n\n### B\nGET http://x/b\nAuthorization: Bearer {{token}}\n\n### C\nGET http://x/c\nAuthorization: Basic u p\n\n### D\nGET http://x/d\n\n### E\n# @no-auth\nGET http://x/e\n";
#[test]
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!(plan.set_folder);
assert_eq!(
plan.choices,
vec![("Bearer {{token}}".into(), 2), ("Basic u p".into(), 1)]
);
let selected: Vec<(&str, bool)> = plan
.own
.iter()
.map(|o| (o.request.label.as_str(), o.selected))
.collect();
assert_eq!(
selected,
vec![("a.http › A", true), ("a.http › B", true), ("a.http › C", false)]
);
// D has no auth today and would start sending the token.
assert_eq!(plan.affected.len(), 1);
assert_eq!(plan.affected[0].0.label, "a.http › D");
let fx = update(&mut s, Action::ApplyConsolidateAuth(plan));
let w = writes(&fx);
assert_eq!(w.len(), 2);
assert_eq!(
w[0].1,
"### A\nGET http://x/a\n\n### B\nGET http://x/b\n\n### C\nGET http://x/c\nAuthorization: Basic u p\n\n### D\n# @no-auth\nGET http://x/d\n\n### E\n# @no-auth\nGET http://x/e\n"
);
assert_eq!(
w[1],
(
root.join(".reqlite/folder.json"),
"{\n \"auth\": \"Bearer {{token}}\"\n}\n".into()
)
);
assert!(s.dialog.is_none());
// Doing it again finds nothing more to do.
let plan = consolidate(&mut s, root.clone(), None);
assert!(!plan.set_folder && plan.affected.is_empty());
assert_eq!(plan.own.len(), 1);
assert!(!plan.own[0].selected);
}
#[test]
fn consolidating_keeps_subfolder_overrides_and_skips_unsaved_tabs() {
let mut s = state();
let root = with_collection(
&mut s,
&[
("a.http", "GET http://x/a\nAuthorization: Bearer root\n"),
("v2/b.http", "### B\nGET http://x/b\nAuthorization: Bearer root\n\n### C\nGET http://x/c\nAuthorization: Bearer v2\n"),
("v2/c.http", "GET http://x/d\nAuthorization: Bearer root\n"),
],
);
set_folder_auth(&mut s, root.clone(), FolderAuth::Header("Bearer root".into()));
set_folder_auth(&mut s, root.join("v2"), FolderAuth::Header("Bearer v2".into()));
update(
&mut s,
Action::OpenRequest {
file: root.join("v2/c.http"),
index: 0,
},
);
let id = active(&s);
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!(!plan.set_folder && plan.choices.is_empty());
let own: Vec<(&str, bool)> = plan
.own
.iter()
.map(|o| (o.request.label.as_str(), o.selected))
.collect();
// B would inherit v2's token, so removing its header isn't the default.
assert_eq!(
own,
vec![
("a.http › http://x/a", true),
("v2/b.http › B", false),
("v2/b.http › C", true)
]
);
assert_eq!(plan.skipped_dirty.len(), 1);
let w = writes(&update(&mut s, Action::ApplyConsolidateAuth(plan)));
let files: Vec<_> = w.iter().map(|(p, _)| p.clone()).collect();
assert_eq!(files, vec![root.join("a.http"), root.join("v2/b.http")]);
assert_eq!(
w[1].1,
"### B\nGET http://x/b\nAuthorization: Bearer root\n\n### C\nGET http://x/c\n"
);
assert!(s.tab(id).unwrap().is_dirty(), "the unsaved tab is left alone");
}