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

+296 -7
View File
@@ -1,12 +1,14 @@
//! `Action`s (what happened) and the pure `update` function that applies them
//! to [`AppState`] and returns [`Effect`]s (what to do outside: I/O, dialogs).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
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::http::{HttpError, Response};
use reqlite_core::httpfile::{render_request, HttpFile};
use reqlite_core::import::curl::{from_curl, looks_like_curl};
@@ -48,8 +50,9 @@ pub enum Action {
ParamsEdited(TabId, Vec<Param>),
HeadersEdited(TabId, Vec<Header>),
BodyEdited(TabId, Body),
/// Sets (`Some`) or removes (`None`) the Authorization header.
AuthEdited(TabId, Option<String>),
/// Sets the request's own Authorization header, `# @no-auth`, or
/// neither (it inherits its folder's auth).
AuthEdited(TabId, AuthMode),
SourceEdited(TabId, String),
SetRequestTab(TabId, RequestTab),
SetResponseTab(TabId, ResponseTab),
@@ -139,6 +142,21 @@ pub enum Action {
DeleteFile(PathBuf),
DuplicateFile(PathBuf),
// Folder auth.
/// Opens the folder auth editor for a folder (or the collection root).
EditFolderAuth(PathBuf),
SetFolderAuth {
dir: PathBuf,
auth: FolderAuth,
},
/// Opens (or re-plans) the "Consolidate auth" dialog for a folder;
/// `target` picks the auth to inherit when the folder has none.
ConsolidateAuth {
dir: PathBuf,
target: Option<String>,
},
ApplyConsolidateAuth(ConsolidateAuth),
// Environments.
SelectEnv(Option<String>),
OpenEnvEditor,
@@ -301,9 +319,12 @@ 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, value) => edit(state, id, |r| match value {
Some(v) => r.set_header("Authorization", v),
None => r.remove_header("Authorization"),
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::SetNoRedirect(id, on) => edit(state, id, |r| r.directives.no_redirect = on),
Action::PickBodyFile(id) => fx.push(Effect::PickBodyFile(id)),
@@ -719,6 +740,42 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
}
}
// ---------------------------------------------------- folder auth
Action::EditFolderAuth(dir) => {
if let Some(c) = state.collection_of(&dir) {
state.dialog = Some(Dialog::FolderAuth(FolderAuthEdit {
auth: c.folder_auth(&dir),
dir,
}));
}
}
Action::SetFolderAuth { dir, auth } => {
state.dialog = None;
let Some(c) = state.collection_of_mut(&dir) else {
return fx;
};
let mut settings = c.folders.get(&dir).cloned().unwrap_or_default();
settings.auth = auth;
let path = folder::settings_path(&dir);
let op = if settings.is_empty() {
c.folders.remove(&dir).map(|_| FileOp::Delete(path))
} else {
let json = settings.to_json();
c.folders.insert(dir, settings);
Some(FileOp::Write(path, json))
};
if let Some(op) = op {
fx.push(Effect::FileOps {
ops: vec![op],
rescan: None,
});
}
}
Action::ConsolidateAuth { dir, target } => {
state.dialog = plan_consolidation(state, &dir, target).map(Dialog::ConsolidateAuth);
}
Action::ApplyConsolidateAuth(plan) => apply_consolidation(state, plan, &mut fx),
// ---------------------------------------------------- environments
Action::SelectEnv(e) => {
let Some(root) = state.current_collection().map(|c| c.root.clone()) else {
@@ -786,7 +843,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
let Some(t) = state.tab(id) else { return fx };
let resolver = state.resolver_for(t);
match resolve_request(
&t.request,
&with_inherited_auth(&t.request, state.inherited_auth_for(t).as_ref()),
&resolver,
&state.base_dir_for(t),
&state.settings.request_options(),
@@ -1014,7 +1071,9 @@ fn send(state: &mut AppState, id: TabId, fx: &mut Vec<Effect>) {
}
let resolver = state.resolver_for(t);
let base_dir = state.base_dir_for(t);
let resolved = resolve_request(&t.request, &resolver, &base_dir, &state.settings.request_options());
let inherited = state.inherited_auth_for(t);
let req = with_inherited_auth(&t.request, inherited.as_ref());
let resolved = resolve_request(&req, &resolver, &base_dir, &state.settings.request_options());
let mut resolved = match resolved {
Ok(r) => r,
Err(e) => {
@@ -1208,6 +1267,8 @@ fn collection_loaded(state: &mut AppState, c: Collection, fx: &mut Vec<Effect>)
// A rescan: keep environments and choices, take the new tree.
existing.tree = c.tree;
existing.files = c.files;
existing.folders = c.folders;
existing.folder_errors = c.folder_errors;
let ids: Vec<(TabId, PathBuf)> = state
.tabs
.iter()
@@ -1227,6 +1288,8 @@ fn collection_loaded(state: &mut AppState, c: Collection, fx: &mut Vec<Effect>)
root: c.root,
tree: c.tree,
files: c.files,
folders: c.folders,
folder_errors: c.folder_errors,
envs: Environments::default(),
selected_env: None,
env_error: None,
@@ -1245,6 +1308,20 @@ fn file_changed(state: &mut AppState, path: PathBuf, text: Option<String>, fx: &
return;
};
let root = c.root.clone();
if let Some(dir) = folder::settings_dir(&path) {
let dir = dir.to_path_buf();
c.folder_errors.clear();
match text.map(|t| FolderSettings::parse(&t, &path)) {
None => {
c.folders.remove(&dir);
}
Some(Ok(s)) => {
c.folders.insert(dir, s);
}
Some(Err(e)) => c.folder_errors.push(e.to_string()),
}
return;
}
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if name == env::PUBLIC_FILE || name == env::PRIVATE_FILE {
// Only the env files at the collection root count.
@@ -1356,6 +1433,218 @@ fn slug_name(title: &str) -> String {
reqlite_core::import::postman::slug(title)
}
/// Works out what "Consolidate auth" on `dir` would do: which requests can
/// drop their own Authorization 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> {
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();
for (_, _, r) in &requests {
if let AuthMode::Own(v) = auth_mode(r) {
match choices.iter_mut().find(|(c, _)| same_auth(c, &v)) {
Some(c) => c.1 += 1,
None => choices.push((v, 1)),
}
}
}
choices.sort_by_key(|c| std::cmp::Reverse(c.1));
let current = c.inherited_auth(dir).and_then(|i| i.value);
let (target, set_folder) = match c.folder_auth(dir) {
FolderAuth::Header(h) => {
choices.clear();
(Some(h), false)
}
_ => {
let target = pick
.or_else(|| current.clone())
.or_else(|| choices.first().map(|c| c.0.clone()));
let same_as_now = matches!((&current, &target), (Some(a), Some(b)) if same_auth(a, b));
(target.clone(), target.is_some() && !same_as_now)
}
};
// Folder settings as they will be after applying.
let mut new_settings = c.folders.get(dir).cloned().unwrap_or_default();
if let Some(t) = &target {
new_settings.auth = FolderAuth::Header(t.clone());
}
let after = |d: &Path| {
folder::inherited_auth(&c.root, d, |x| {
if set_folder && x == dir {
Some(&new_settings)
} else {
c.folders.get(x)
}
})
.and_then(|i| i.value)
};
let dirty = |file: &Path, index: usize| {
state.tabs.iter().any(|t| {
t.is_dirty()
&& t.origin
.as_ref()
.is_some_and(|o| o.file == file && o.key.index == index)
})
};
let mut plan = ConsolidateAuth {
dir: dir.to_path_buf(),
target,
set_folder,
choices,
own: Vec::new(),
affected: Vec::new(),
keep_affected: true,
skipped_dirty: Vec::new(),
};
for (file, index, r) in requests {
let fdir = file.parent().unwrap_or(dir);
let request = RequestRef {
file: file.clone(),
index,
label: format!(
"{} › {}",
c.relative(file).display(),
r.display_name().unwrap_or(r.url.as_str())
),
};
let item = match auth_mode(r) {
AuthMode::Own(value) => {
let mut own = OwnAuth {
request,
value,
inherits: after(fdir),
selected: false,
};
own.selected = own.same();
Some(Ok(own))
}
AuthMode::Inherit => {
let before = c.inherited_auth(fdir).and_then(|i| i.value);
let changes = match (&before, &after(fdir)) {
(Some(a), Some(b)) => !same_auth(a, b),
(a, b) => a.is_some() != b.is_some(),
};
changes.then_some(Err((request, before)))
}
AuthMode::NoAuth => None,
};
match item {
Some(Ok(own)) if dirty(file, index) => plan.skipped_dirty.push(own.request),
Some(Err((request, _))) if dirty(file, index) => plan.skipped_dirty.push(request),
Some(Ok(own)) => plan.own.push(own),
Some(Err(affected)) => plan.affected.push(affected),
None => {}
}
}
Some(plan)
}
/// What consolidating does to one request.
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>),
}
fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec<Effect>) {
state.dialog = None;
let mut edits: BTreeMap<PathBuf, Vec<(usize, AuthFix)>> = BTreeMap::new();
for o in plan.own.iter().filter(|o| o.selected) {
edits
.entry(o.request.file.clone())
.or_default()
.push((o.request.index, AuthFix::Inherit));
}
if plan.keep_affected && plan.set_folder {
for (r, before) in &plan.affected {
edits
.entry(r.file.clone())
.or_default()
.push((r.index, AuthFix::Keep(before.clone())));
}
}
let mut ops = Vec::new();
let (mut dropped, mut pinned) = (0, 0);
for (path, list) in edits {
let Some(mut f) = file_of(state, &path).cloned() else {
continue;
};
for (index, edit) in list {
let Some(mut r) = f.request(index).cloned() else {
continue;
};
// The file may have changed since the plan was made.
match (&edit, auth_mode(&r)) {
(AuthFix::Inherit, AuthMode::Own(_)) => {
r.remove_header("Authorization");
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),
}
pinned += 1;
}
_ => continue,
}
if let Some(text) = f.replace_request(index, &r) {
f = HttpFile::parse(text);
}
}
if file_of(state, &path).is_some_and(|old| old.text() != f.text()) {
ops.push(FileOp::Write(path.clone(), f.text().to_string()));
insert_file(state, &path, f.text().to_string());
let clean: Vec<TabId> = state
.tabs
.iter()
.filter(|t| !t.is_dirty() && t.origin.as_ref().is_some_and(|o| o.file == path))
.map(|t| t.id)
.collect();
for id in clean {
reload_tab_from_file(state, id, &path);
}
}
}
let mut msg = Vec::new();
if plan.set_folder {
if let (Some(target), Some(c)) = (&plan.target, state.collection_of_mut(&plan.dir)) {
let mut settings = c.folders.get(&plan.dir).cloned().unwrap_or_default();
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(format!("set the folder auth to `{target}`"));
}
}
if dropped > 0 {
msg.push(format!("{dropped} request(s) now inherit it"));
}
if pinned > 0 {
msg.push(format!("{pinned} request(s) keep their auth explicitly"));
}
if !plan.skipped_dirty.is_empty() {
msg.push(format!("{} with unsaved edits skipped", plan.skipped_dirty.len()));
}
if !ops.is_empty() {
fx.push(Effect::FileOps { ops, rescan: None });
}
if msg.is_empty() {
state.set_info("Auth: nothing to change");
} else {
let mut text = msg.join(", ");
text[..1].make_ascii_uppercase();
state.set_info(text);
}
}
fn save(state: &mut AppState, id: TabId, fx: &mut Vec<Effect>) {
let Some(t) = state.tab(id) else { return };
if let Some(e) = &t.source_error {
+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");
}
+2
View File
@@ -10,6 +10,7 @@ use std::time::Duration;
use notify::{RecursiveMode, Watcher};
use reqlite_core::collection;
use reqlite_core::env::{self, Environments};
use reqlite_core::folder;
use reqlite_core::http::{BodyStore, DynHttpClient, ResolvedRequest};
use reqlite_core::CancelToken;
use tokio::runtime::Handle;
@@ -505,6 +506,7 @@ fn is_relevant(p: &Path) -> bool {
return false;
}
collection::is_http_file(p)
|| folder::settings_dir(p).is_some()
|| p.file_name()
.is_some_and(|n| n == env::PUBLIC_FILE || n == env::PRIVATE_FILE)
}
+99
View File
@@ -9,6 +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::http::{BodyStore, Response};
use reqlite_core::httpfile::{HttpFile, RequestKey};
use reqlite_core::params::Param;
@@ -74,6 +75,10 @@ pub enum Dialog {
Prompt(Prompt),
/// Confirm a destructive collection operation.
ConfirmDelete(DeleteTarget),
/// Editing a folder's (or the collection's) default auth.
FolderAuth(FolderAuthEdit),
/// Making requests in a folder inherit its auth.
ConsolidateAuth(ConsolidateAuth),
/// Result of a Postman import.
ImportSummary {
root: PathBuf,
@@ -82,6 +87,63 @@ pub enum Dialog {
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FolderAuthEdit {
pub dir: PathBuf,
pub auth: FolderAuth,
}
/// A request in a collection, for lists in dialogs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestRef {
pub file: PathBuf,
pub index: usize,
pub label: String,
}
/// The plan shown by the "Consolidate auth" dialog. Built by
/// `action::plan_consolidation`; the UI only changes the choices in it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConsolidateAuth {
pub dir: PathBuf,
/// The auth requests in `dir` should inherit.
pub target: Option<String>,
/// `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 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>)>,
/// 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,
/// Requests skipped because their tab has unsaved edits.
pub skipped_dirty: Vec<RequestRef>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OwnAuth {
pub request: RequestRef,
pub value: String,
/// What the request would inherit without its header.
pub inherits: Option<String>,
/// Remove the header.
pub selected: bool,
}
impl OwnAuth {
/// Removing the header keeps the request sending the same thing.
pub fn same(&self) -> bool {
self.inherits
.as_deref()
.is_some_and(|i| folder::same_auth(i, &self.value))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeleteTarget {
Request { file: PathBuf, index: usize, label: String },
@@ -126,6 +188,9 @@ pub struct CollectionState {
pub root: PathBuf,
pub tree: Node,
pub files: BTreeMap<PathBuf, HttpFile>,
/// Folder settings (default auth) by folder.
pub folders: BTreeMap<PathBuf, FolderSettings>,
pub folder_errors: Vec<String>,
pub envs: Environments,
pub selected_env: Option<String>,
pub env_error: Option<String>,
@@ -153,6 +218,25 @@ impl CollectionState {
pub fn contains(&self, p: &Path) -> bool {
p.starts_with(&self.root)
}
/// The auth requests in `dir` inherit from their folders.
pub fn inherited_auth(&self, dir: &Path) -> Option<InheritedAuth> {
folder::inherited_auth(&self.root, dir, |d| self.folders.get(d))
}
/// The folder's own auth setting.
pub fn folder_auth(&self, dir: &Path) -> FolderAuth {
self.folders.get(dir).map(|s| s.auth.clone()).unwrap_or_default()
}
/// `dir` relative to the root, for messages ("the collection" for the root).
pub fn folder_label(&self, dir: &Path) -> String {
if dir == self.root {
format!("the collection “{}”", self.name())
} else {
format!("the folder {}", self.relative(dir).display())
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -429,6 +513,21 @@ impl AppState {
}
}
/// The folder whose auth a tab's request inherits: its file's folder, or
/// for untitled tabs the root of the current collection.
pub fn auth_dir_for(&self, tab: &Tab) -> Option<PathBuf> {
match &tab.origin {
Some(o) => self.collection_of(&o.file).and(o.file.parent()).map(Path::to_path_buf),
None => self.current_collection().map(|c| c.root.clone()),
}
}
/// The auth a tab's request inherits from its folders.
pub fn inherited_auth_for(&self, tab: &Tab) -> Option<InheritedAuth> {
let dir = self.auth_dir_for(tab)?;
self.collection_for_tab(tab)?.inherited_auth(&dir)
}
/// Whether `name` comes from the private env file (shown masked).
pub fn is_private_var(&self, tab: &Tab, name: &str) -> bool {
self.collection_for_tab(tab).is_some_and(|c| {
+135 -34
View File
@@ -2,6 +2,7 @@
use base64::Engine;
use egui::{Key, RichText, Ui};
use reqlite_core::folder::{auth_mode, AuthMode, InheritedAuth};
use reqlite_core::params::Param;
use reqlite_core::{Body, Header, Method, Part, PartBody};
@@ -136,7 +137,7 @@ pub fn editor(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mu
RequestTab::Params => params(ui, tab, vars, acts),
RequestTab::Headers => headers(ui, tab, vars, acts),
RequestTab::Body => body(ui, state, tab, vars, acts),
RequestTab::Auth => auth(ui, tab, vars, acts),
RequestTab::Auth => auth(ui, state, tab, vars, acts),
RequestTab::Source => source(ui, tab, vars, acts),
});
}
@@ -512,13 +513,25 @@ fn body(ui: &mut Ui, _state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec
}
#[derive(PartialEq, Clone, Copy)]
enum AuthKind {
pub enum AuthKind {
Inherit,
None,
Basic,
Bearer,
Other,
}
impl AuthKind {
/// The header value a newly picked kind starts with.
pub fn template(self) -> Option<String> {
match self {
AuthKind::Basic => Some("Basic {{username}} {{password}}".into()),
AuthKind::Bearer => Some("Bearer {{token}}".into()),
_ => None,
}
}
}
/// Splits an Authorization header into what the Auth tab shows.
fn auth_parts(value: Option<&str>) -> (AuthKind, String, String) {
let Some(v) = value else {
@@ -546,48 +559,43 @@ fn auth_parts(value: Option<&str>) -> (AuthKind, String, String) {
(AuthKind::Other, v.to_string(), String::new())
}
fn auth(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
let id = tab.id;
let header = tab.request.header("authorization");
let (kind, a, b) = auth_parts(header);
pub fn header_kind(value: &str) -> AuthKind {
auth_parts(Some(value)).0
}
/// A row of radio buttons; returns the kind picked when it changed.
pub fn auth_kind_row(ui: &mut Ui, current: AuthKind, kinds: &[(AuthKind, &str)]) -> Option<AuthKind> {
let mut picked = None;
ui.horizontal(|ui| {
ui.label("Type:");
for (k, label) in [
(AuthKind::None, "None"),
(AuthKind::Basic, "Basic"),
(AuthKind::Bearer, "Bearer token"),
] {
if ui.radio(kind == k, label).clicked() && kind != k {
acts.push(Action::AuthEdited(
id,
match k {
AuthKind::None => None,
AuthKind::Basic => Some("Basic {{username}} {{password}}".into()),
AuthKind::Bearer => Some("Bearer {{token}}".into()),
AuthKind::Other => unreachable!(),
},
));
for &(k, label) in kinds {
if ui.radio(current == k, label).clicked() && current != k {
picked = Some(k);
}
}
});
ui.add_space(6.0);
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> {
let (kind, a, b) = auth_parts(Some(value));
let mut out = None;
match kind {
AuthKind::None => {
ui.label(RichText::new("No Authorization header.").weak());
}
AuthKind::Basic => {
let (mut u, mut p) = (a, b);
let mut changed = false;
egui::Grid::new(("basic", id)).num_columns(2).show(ui, |ui| {
egui::Grid::new(("basic", salt)).num_columns(2).show(ui, |ui| {
ui.label("Username");
changed |= var_text_edit(ui, &mut u, Some(vars), "", 260.0, ("bu", id)).changed();
changed |= var_text_edit(ui, &mut u, Some(vars), "", 260.0, ("bu", salt)).changed();
ui.end_row();
ui.label("Password");
changed |= var_text_edit(ui, &mut p, Some(vars), "", 260.0, ("bp", id)).changed();
changed |= var_text_edit(ui, &mut p, Some(vars), "", 260.0, ("bp", salt)).changed();
ui.end_row();
});
if changed {
acts.push(Action::AuthEdited(id, Some(format!("Basic {u} {p}"))));
out = Some(format!("Basic {u} {p}"));
}
ui.label(
RichText::new("Written as `Authorization: Basic user password`; it is base64-encoded when sent, like JetBrains does.")
@@ -599,14 +607,61 @@ fn auth(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
let mut t = a;
ui.horizontal(|ui| {
ui.label("Token");
if var_text_edit(ui, &mut t, Some(vars), "{{token}}", 420.0, ("bt", id)).changed() {
acts.push(Action::AuthEdited(id, Some(format!("Bearer {t}"))));
if var_text_edit(ui, &mut t, Some(vars), "{{token}}", 420.0, ("bt", salt)).changed() {
out = Some(format!("Bearer {t}"));
}
});
}
AuthKind::Other => {
ui.label(format!("Custom Authorization header: {a}"));
ui.label(RichText::new("Edit it in the Headers tab.").weak());
_ => {
let mut v = value.to_string();
ui.horizontal(|ui| {
ui.label("Header value");
if var_text_edit(ui, &mut v, Some(vars), "", 420.0, ("bo", salt)).changed() {
out = Some(v.clone());
}
});
}
}
out
}
fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
let id = tab.id;
let mode = auth_mode(&tab.request);
let kind = match &mode {
AuthMode::Own(v) => header_kind(v),
AuthMode::NoAuth => AuthKind::None,
AuthMode::Inherit => AuthKind::Inherit,
};
let kinds = [
(AuthKind::Inherit, "Inherit"),
(AuthKind::None, "None"),
(AuthKind::Basic, "Basic"),
(AuthKind::Bearer, "Bearer token"),
];
if let Some(k) = auth_kind_row(ui, kind, &kinds) {
acts.push(Action::AuthEdited(
id,
match k {
AuthKind::Inherit => AuthMode::Inherit,
AuthKind::None => AuthMode::NoAuth,
k => AuthMode::Own(k.template().unwrap_or_default()),
},
));
}
ui.add_space(6.0);
match &mode {
AuthMode::Inherit => inherited(ui, state, tab, acts),
AuthMode::NoAuth => {
ui.label(RichText::new("No Authorization header, not even the folder's (`# @no-auth`).").weak());
}
AuthMode::Own(v) => {
if kind == AuthKind::Other {
ui.label("Custom Authorization header:");
}
if let Some(v) = auth_value_fields(ui, v, vars, &format!("tab{id}")) {
acts.push(Action::AuthEdited(id, AuthMode::Own(v)));
}
}
}
ui.add_space(6.0);
@@ -617,6 +672,51 @@ fn auth(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
);
}
/// What an inheriting request sends, and buttons to change it.
fn inherited(ui: &mut Ui, state: &AppState, tab: &Tab, acts: &mut Vec<Action>) {
let Some(c) = state.collection_for_tab(tab) else {
ui.label(RichText::new("Not in a collection, so there is nothing to inherit.").weak());
return;
};
match state.inherited_auth_for(tab) {
Some(InheritedAuth { from, value: Some(v) }) => {
ui.horizontal_wrapped(|ui| {
ui.label("Uses");
ui.label(RichText::new(&v).monospace());
ui.label(format!("from {}.", c.folder_label(&from)));
});
}
Some(InheritedAuth { from, value: None }) => {
ui.label(format!("No auth: {} is set to send none.", c.folder_label(&from)));
}
None => {
ui.label(RichText::new("No auth: no folder above this request has auth set.").weak());
}
}
let dir = state.auth_dir_for(tab);
ui.horizontal(|ui| {
if let Some(dir) = dir.as_ref().filter(|d| **d != c.root) {
if ui.button("Folder auth…").on_hover_text(c.folder_label(dir)).clicked() {
acts.push(Action::EditFolderAuth(dir.clone()));
}
}
if ui
.button("Collection default…")
.on_hover_text("Auth for every request in the collection that doesn't set its own")
.clicked()
{
acts.push(Action::EditFolderAuth(c.root.clone()));
}
});
if tab.origin.is_none() {
ui.label(
RichText::new("Untitled requests use the collection default.")
.small()
.weak(),
);
}
}
fn source(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
let id = tab.id;
if let Some(e) = &tab.source_error {
@@ -647,5 +747,6 @@ 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);
}
}
+34 -1
View File
@@ -95,6 +95,8 @@ fn collection(ui: &mut Ui, state: &AppState, c: &CollectionState, current: bool,
ui.close();
}
ui.separator();
auth_menu_items(ui, &c.root, "Default auth…", acts);
ui.separator();
if ui.button("Close collection").clicked() {
acts.push(Action::CloseCollection(c.root.clone()));
ui.close();
@@ -134,6 +136,9 @@ fn collection(ui: &mut Ui, state: &AppState, c: &CollectionState, current: bool,
if let Some(e) = &c.env_error {
ui.colored_label(ui.visuals().error_fg_color, format!("Environments: {e}"));
}
for e in &c.folder_errors {
ui.colored_label(ui.visuals().error_fg_color, format!("Folder settings: {e}"));
}
if let Node::Folder { children, .. } = &c.tree {
if children.is_empty() {
ui.label(RichText::new("No .http files yet.").weak());
@@ -148,6 +153,28 @@ fn collection(ui: &mut Ui, state: &AppState, c: &CollectionState, current: bool,
});
}
fn auth_menu_items(ui: &mut Ui, dir: &Path, edit_label: &str, acts: &mut Vec<Action>) {
if ui
.button(edit_label)
.on_hover_text("Auth for the requests in here that don't set their own")
.clicked()
{
acts.push(Action::EditFolderAuth(dir.to_path_buf()));
ui.close();
}
if ui
.button("Consolidate auth…")
.on_hover_text("Make requests in here inherit one shared auth")
.clicked()
{
acts.push(Action::ConsolidateAuth {
dir: dir.to_path_buf(),
target: None,
});
ui.close();
}
}
fn new_file_prompt(dir: &Path) -> Action {
Action::ShowDialog(Some(Dialog::Prompt(Prompt {
kind: PromptKind::NewFile { dir: dir.to_path_buf() },
@@ -167,11 +194,17 @@ fn node(ui: &mut Ui, state: &AppState, c: &CollectionState, n: &Node, acts: &mut
node(ui, state, c, ch, acts);
}
});
resp.header_response.context_menu(|ui| {
let mut header = resp.header_response;
if let reqlite_core::folder::FolderAuth::Header(v) = c.folder_auth(path) {
header = header.on_hover_text(format!("Auth: {v}"));
}
header.context_menu(|ui| {
if ui.button("New .http file…").clicked() {
acts.push(new_file_prompt(path));
ui.close();
}
ui.separator();
auth_menu_items(ui, path, "Folder auth…", acts);
});
}
Node::File { name, path } => {
+259 -2
View File
@@ -2,11 +2,15 @@
use egui::{Context, Id, Key, RichText};
use reqlite_core::env::{EnvFile, EnvVar, SHARED_ENV};
use reqlite_core::folder::{FolderAuth, InheritedAuth};
use super::widgets::{method_color, status_color};
use super::request::{auth_kind_row, auth_value_fields, header_kind, AuthKind};
use super::widgets::{method_color, status_color, VarCtx};
use crate::action::Action;
use crate::settings::{ProxyMode, Settings, ThemeChoice};
use crate::state::{AppState, DeleteTarget, Dialog, EnvEditor, Prompt, PromptKind, QuickOpen};
use crate::state::{
AppState, ConsolidateAuth, DeleteTarget, Dialog, EnvEditor, FolderAuthEdit, Prompt, PromptKind, QuickOpen,
};
pub fn show(ctx: &Context, state: &AppState, acts: &mut Vec<Action>) {
if let Some(d) = &state.dialog {
@@ -125,6 +129,8 @@ fn dialog(ctx: &Context, state: &AppState, d: &Dialog, acts: &mut Vec<Action>) {
});
}
Dialog::Prompt(p) => prompt(ui, state, p, acts),
Dialog::FolderAuth(ed) => folder_auth(ui, state, ed, acts),
Dialog::ConsolidateAuth(plan) => consolidate_auth(ui, state, plan, acts),
Dialog::ConfirmDelete(target) => {
let what = match target {
DeleteTarget::Request { label, .. } => format!("the request “{label}”"),
@@ -175,6 +181,257 @@ fn dialog(ctx: &Context, state: &AppState, d: &Dialog, acts: &mut Vec<Action>) {
}
}
fn folder_auth(ui: &mut egui::Ui, state: &AppState, ed: &FolderAuthEdit, acts: &mut Vec<Action>) {
let Some(c) = state.collection_of(&ed.dir) else {
acts.push(Action::ShowDialog(None));
return;
};
let is_root = ed.dir == c.root;
ui.heading(if is_root {
"Collection default auth"
} else {
"Folder auth"
});
ui.label(RichText::new(c.relative(&ed.dir).display().to_string()).weak());
ui.add_space(4.0);
let set = |auth: FolderAuth| {
Action::ShowDialog(Some(Dialog::FolderAuth(FolderAuthEdit {
dir: ed.dir.clone(),
auth,
})))
};
let kind = match &ed.auth {
FolderAuth::Inherit => AuthKind::Inherit,
FolderAuth::None => AuthKind::None,
FolderAuth::Header(v) => header_kind(v),
};
let kinds = [
(AuthKind::Inherit, if is_root { "Not set" } else { "Inherit" }),
(AuthKind::None, "None"),
(AuthKind::Basic, "Basic"),
(AuthKind::Bearer, "Bearer token"),
];
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()),
}));
}
ui.add_space(6.0);
match &ed.auth {
FolderAuth::Inherit if is_root => {
ui.label(RichText::new("Requests that don't set auth send none.").weak());
}
FolderAuth::Inherit => {
let parent = ed.dir.parent().and_then(|p| c.inherited_auth(p));
let text = match parent {
Some(InheritedAuth { from, value: Some(v) }) => format!("Uses `{v}` from {}.", c.folder_label(&from)),
Some(InheritedAuth { from, value: None }) => format!("No auth, as set on {}.", c.folder_label(&from)),
None => "No auth: no parent folder has auth set.".into(),
};
ui.label(RichText::new(text).weak());
}
FolderAuth::None => {
ui.label(RichText::new("Requests here send no auth unless they set their own.").weak());
}
FolderAuth::Header(v) => {
let resolver = c.envs.resolver(c.selected_env.as_deref(), &[]);
let env = c.selected_env.as_deref().unwrap_or(SHARED_ENV);
let is_private = |name: &str| c.envs.is_private(env, name);
let vars = VarCtx {
resolver: &resolver,
is_private: &is_private,
};
if let Some(v) = auth_value_fields(ui, v, &vars, "folder-auth") {
acts.push(set(FolderAuth::Header(v)));
}
}
}
ui.add_space(6.0);
ui.label(
RichText::new(
"Used by requests in this folder and its subfolders that have no Authorization header of their own. \
Saved in .reqlite/folder.json (other .http tools ignore it).",
)
.small()
.weak(),
);
ui.add_space(8.0);
ui.horizontal(|ui| {
if ui.button("Save").clicked() {
acts.push(Action::SetFolderAuth {
dir: ed.dir.clone(),
auth: ed.auth.clone(),
});
}
if ui.button("Cancel").clicked() {
acts.push(Action::ShowDialog(None));
}
});
}
fn consolidate_auth(ui: &mut egui::Ui, state: &AppState, plan: &ConsolidateAuth, acts: &mut Vec<Action>) {
let Some(c) = state.collection_of(&plan.dir) else {
acts.push(Action::ShowDialog(None));
return;
};
let set = |plan: ConsolidateAuth| Action::ShowDialog(Some(Dialog::ConsolidateAuth(plan)));
ui.heading("Consolidate auth");
ui.label(format!(
"Let requests in {} inherit one shared auth instead of each carrying its own Authorization header.",
c.folder_label(&plan.dir)
));
ui.add_space(6.0);
let Some(target) = &plan.target else {
ui.label("None of these requests has an Authorization header, and there is no auth to inherit.");
ui.add_space(8.0);
if ui.button("OK").clicked() {
acts.push(Action::ShowDialog(None));
}
return;
};
ui.horizontal(|ui| {
ui.label("Shared auth:");
if plan.choices.is_empty() {
ui.label(RichText::new(target).monospace());
} else {
egui::ComboBox::from_id_salt("consolidate-target")
.selected_text(RichText::new(target).monospace())
.show_ui(ui, |ui| {
for (v, n) in &plan.choices {
let label = format!("{v} ({n} request{})", if *n == 1 { "" } else { "s" });
if ui.selectable_label(v == target, label).clicked() && v != target {
acts.push(Action::ConsolidateAuth {
dir: plan.dir.clone(),
target: Some(v.clone()),
});
}
}
});
}
});
if plan.set_folder {
ui.label(
RichText::new(format!(
"It will be saved as the auth of {}.",
c.folder_label(&plan.dir)
))
.weak(),
);
} else {
ui.label(RichText::new(format!("{} already uses it.", c.folder_label(&plan.dir))).weak());
}
ui.add_space(8.0);
if plan.own.is_empty() {
ui.label("No request here has its own Authorization header.");
} else {
ui.horizontal(|ui| {
ui.label(RichText::new("Remove the Authorization header from:").strong());
if ui
.small_button("Matching")
.on_hover_text("Only those that send the same thing")
.clicked()
{
let mut p = plan.clone();
p.own.iter_mut().for_each(|o| o.selected = o.same());
acts.push(set(p));
}
if ui.small_button("All").clicked() {
let mut p = plan.clone();
p.own.iter_mut().for_each(|o| o.selected = true);
acts.push(set(p));
}
if ui.small_button("None").clicked() {
let mut p = plan.clone();
p.own.iter_mut().for_each(|o| o.selected = false);
acts.push(set(p));
}
});
egui::ScrollArea::vertical()
.id_salt("consolidate-own")
.max_height(220.0)
.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);
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("no auth");
ui.indent(("diff", i), |ui| {
ui.label(
RichText::new(format!("has `{}`; would send `{would}` instead", o.value))
.small()
.color(ui.visuals().warn_fg_color),
);
});
}
}
});
}
if plan.set_folder && !plan.affected.is_empty() {
ui.add_space(8.0);
ui.label(format!(
"{} request(s) without a header of their own would start sending `{target}`:",
plan.affected.len()
));
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("no auth");
ui.label(format!("• {} (now: {now})", r.label));
}
});
let mut keep = plan.keep_affected;
if ui
.checkbox(&mut keep, "Keep what they send today")
.on_hover_text("Gives them their current header, or `# @no-auth`")
.changed()
{
let mut p = plan.clone();
p.keep_affected = keep;
acts.push(set(p));
}
}
if !plan.skipped_dirty.is_empty() {
ui.add_space(6.0);
ui.label(
RichText::new(format!(
"Skipped, because their tabs have unsaved edits: {}",
plan.skipped_dirty
.iter()
.map(|r| r.label.as_str())
.collect::<Vec<_>>()
.join(", ")
))
.weak(),
);
}
ui.add_space(8.0);
let anything = plan.set_folder
|| plan.own.iter().any(|o| o.selected)
|| (plan.keep_affected && plan.set_folder && !plan.affected.is_empty());
ui.horizontal(|ui| {
if ui.add_enabled(anything, egui::Button::new("Apply")).clicked() {
acts.push(Action::ApplyConsolidateAuth(plan.clone()));
}
if ui.button("Cancel").clicked() {
acts.push(Action::ShowDialog(None));
}
});
}
fn prompt(ui: &mut egui::Ui, state: &AppState, p: &Prompt, acts: &mut Vec<Action>) {
ui.heading(&p.title);
let mut value = p.value.clone();
+7 -3
View File
@@ -6,10 +6,14 @@ fn ui_symbols_exist_in_the_bundled_fonts() {
let mut harness = egui_kittest::Harness::new_ui(|_ui| {});
harness.step();
let ctx = harness.ctx.clone();
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/ui");
let src_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
// `update` builds some labels too (dialog lists, status messages).
let files = std::fs::read_dir(src_dir.join("ui"))
.unwrap()
.map(|e| e.unwrap().path())
.chain([src_dir.join("action.rs"), src_dir.join("state.rs")]);
let mut missing = Vec::new();
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
for path in files {
let src = std::fs::read_to_string(&path).unwrap();
for (n, line) in src.lines().enumerate() {
// Only string literals in code matter, not comments.
+68
View File
@@ -170,3 +170,71 @@ fn opens_a_collection_and_shows_its_requests() {
});
assert_eq!(client.seen.lock().unwrap()[0].url, "http://dev/users");
}
#[test]
fn folder_auth_and_consolidate_dialogs() {
let rt = tokio::runtime::Runtime::new().unwrap();
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("api")).unwrap();
std::fs::write(
dir.path().join("api/users.http"),
"### List users\nGET http://x/users\nAuthorization: Bearer {{token}}\n\n### Me\nGET http://x/me\n",
)
.unwrap();
let client = Arc::new(FakeClient::default());
let mut h = harness(&rt, client.clone());
let root = std::fs::canonicalize(dir.path()).unwrap();
h.state_mut().dispatch(Action::OpenCollection(root.clone()));
step_until(&mut h, "the collection", |h| !h.state().state.collections.is_empty());
h.state_mut().dispatch(Action::ConsolidateAuth {
dir: root.clone(),
target: None,
});
h.step();
h.step();
assert!(h.query_by_label("Consolidate auth").is_some());
h.get_by_label("Apply").click();
step_until(&mut h, "the folder settings file", |_| {
root.join(".reqlite/folder.json").is_file()
});
step_until(&mut h, "the rewritten file", |_| {
std::fs::read_to_string(root.join("api/users.http")).is_ok_and(|t| !t.contains("Authorization"))
});
// The request without a header got `# @no-auth`, so it sends nothing.
h.state_mut().dispatch(Action::OpenRequest {
file: root.join("api/users.http"),
index: 1,
});
h.step();
let tab = h.state().state.active.unwrap();
h.state_mut()
.dispatch(Action::SetRequestTab(tab, reqlite_app::state::RequestTab::Auth));
h.step();
assert!(h.query_by_label_contains("@no-auth").is_some());
h.state_mut()
.dispatch(Action::SetRequestTab(tab, reqlite_app::state::RequestTab::Params));
h.state_mut().dispatch(Action::EditFolderAuth(root.join("api")));
h.step();
h.step();
assert!(h.query_by_label("Folder auth").is_some());
h.get_by_label("Bearer token").click();
h.step();
// The URL bar has a Save button too, so save through the dialog's state.
let Some(reqlite_app::state::Dialog::FolderAuth(ed)) = h.state().state.dialog.clone() else {
panic!("no folder auth dialog")
};
assert_eq!(
ed.auth,
reqlite_core::folder::FolderAuth::Header("Bearer {{token}}".into())
);
h.state_mut().dispatch(Action::SetFolderAuth {
dir: ed.dir,
auth: ed.auth,
});
step_until(&mut h, "the api folder settings", |_| {
root.join("api/.reqlite/folder.json").is_file()
});
}