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 {