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

+340
View File
@@ -0,0 +1,340 @@
//! Per-folder settings, a reqlite extension: `<folder>/.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:
//!
//! ```json
//! { "auth": "Bearer {{token}}" }
//! ```
//!
//! `"auth": null` means "no auth" (it stops inheritance from parent
//! folders); a missing key inherits. The file at the collection root is the
//! collection default. A request opts out with `# @no-auth`. Other keys are
//! kept and written back unchanged.
use std::borrow::Cow;
use std::path::{Path, PathBuf};
use serde_json::{Map, Value};
use crate::model::Request;
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";
#[derive(Debug, thiserror::Error)]
pub enum FolderError {
#[error("{path}: {source}")]
Json { path: PathBuf, source: serde_json::Error },
#[error("{path}: expected an object")]
Shape { path: PathBuf },
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum FolderAuth {
/// Use the parent folder's auth.
#[default]
Inherit,
/// No auth for this folder, whatever the parents say.
None,
/// An `Authorization` header value, e.g. `Bearer {{token}}`.
Header(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct FolderSettings {
pub auth: FolderAuth,
/// Keys we don't interpret.
other: Map<String, Value>,
}
impl FolderSettings {
pub fn parse(text: &str, path: &Path) -> Result<Self, FolderError> {
if text.trim().is_empty() {
return Ok(Self::default());
}
let value: Value = serde_json::from_str(text).map_err(|source| FolderError::Json {
path: path.to_path_buf(),
source,
})?;
let Value::Object(mut map) = value else {
return Err(FolderError::Shape {
path: path.to_path_buf(),
});
};
let auth = match map.remove("auth") {
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(_) => {
return Err(FolderError::Shape {
path: path.to_path_buf(),
})
}
};
Ok(Self { auth, other: map })
}
pub fn to_json(&self) -> String {
let mut map = Map::new();
match &self.auth {
FolderAuth::Inherit => {}
FolderAuth::None => {
map.insert("auth".into(), Value::Null);
}
FolderAuth::Header(h) => {
map.insert("auth".into(), Value::String(h.clone()));
}
}
map.extend(self.other.clone());
let mut s = serde_json::to_string_pretty(&Value::Object(map)).unwrap();
s.push('\n');
s
}
/// Nothing worth keeping a file for.
pub fn is_empty(&self) -> bool {
self.auth == FolderAuth::Inherit && self.other.is_empty()
}
/// Reads the settings of `dir`; `None` when it has no settings file.
pub fn load(dir: &Path) -> Result<Option<Self>, FolderError> {
let path = settings_path(dir);
match std::fs::read_to_string(&path) {
Ok(text) => Self::parse(&text, &path).map(Some),
Err(_) => Ok(None),
}
}
}
/// `<dir>/.reqlite/folder.json`.
pub fn settings_path(dir: &Path) -> PathBuf {
dir.join(DIR).join(FILE)
}
/// The folder a settings file belongs to, if `path` is one.
pub fn settings_dir(path: &Path) -> Option<&Path> {
let parent = path.parent()?;
(path.file_name()? == FILE && parent.file_name()? == DIR).then(|| parent.parent())?
}
/// Auth a request in `dir` inherits.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InheritedAuth {
/// The folder whose setting applies.
pub from: PathBuf,
/// The header value; `None` when that folder says "no auth".
pub value: Option<String>,
}
/// Walks from `dir` up to `root` (inclusive) and returns the first folder
/// setting that isn't "inherit". `settings` looks up a folder's settings.
pub fn inherited_auth<'a>(
root: &Path,
dir: &Path,
settings: impl Fn(&Path) -> Option<&'a FolderSettings>,
) -> Option<InheritedAuth> {
for d in dir.ancestors() {
if !d.starts_with(root) {
break;
}
match settings(d).map(|s| &s.auth) {
None | Some(FolderAuth::Inherit) => {}
Some(FolderAuth::None) => {
return Some(InheritedAuth {
from: d.to_path_buf(),
value: None,
})
}
Some(FolderAuth::Header(h)) => {
return Some(InheritedAuth {
from: d.to_path_buf(),
value: Some(h.clone()),
})
}
}
}
None
}
/// For the command line, which has no collection: reads settings files from
/// `dir` upwards, stopping after the first folder that has an env file or a
/// `.git` folder (the collection or repository root).
pub fn inherited_auth_on_disk(dir: &Path) -> Result<Option<InheritedAuth>, FolderError> {
for d in dir.ancestors() {
if let Some(s) = FolderSettings::load(d)? {
if let Some(found) = inherited_auth(d, d, |_| Some(&s)) {
return Ok(Some(found));
}
}
let is_root = d.join(".git").exists()
|| d.join(crate::env::PUBLIC_FILE).is_file()
|| d.join(crate::env::PRIVATE_FILE).is_file();
if is_root {
break;
}
}
Ok(None)
}
/// Whether the request has `# @no-auth`.
pub fn has_no_auth(req: &Request) -> bool {
req.directives.other.iter().any(|(n, _)| n == NO_AUTH_DIRECTIVE)
}
pub fn set_no_auth(req: &mut Request, on: bool) {
req.directives.other.retain(|(n, _)| n != NO_AUTH_DIRECTIVE);
if on {
req.directives.other.push((NO_AUTH_DIRECTIVE.into(), String::new()));
}
}
/// How a request gets its auth.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthMode {
/// It has its own `Authorization` header.
Own(String),
/// `# @no-auth`.
NoAuth,
/// From its folder.
Inherit,
}
pub fn auth_mode(req: &Request) -> AuthMode {
match req.header("authorization") {
Some(v) => AuthMode::Own(v.to_string()),
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.
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)) => {
let mut r = req.clone();
r.set_header("Authorization", v);
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())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::httpfile::HttpFile;
use std::collections::BTreeMap;
#[test]
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!(FolderSettings::parse(&s.to_json(), p).unwrap(), s);
assert!(s.to_json().contains("\"x\": 1"));
assert_eq!(
FolderSettings::parse(r#"{"auth": null}"#, p).unwrap().auth,
FolderAuth::None
);
assert_eq!(FolderSettings::parse("{}", p).unwrap().auth, FolderAuth::Inherit);
assert!(FolderSettings::parse("{}", p).unwrap().is_empty());
assert!(FolderSettings::parse(r#"{"auth": 3}"#, p).is_err());
assert!(FolderSettings::parse("[]", p).is_err());
}
#[test]
fn settings_dir_of_a_path() {
assert_eq!(
settings_dir(Path::new("/c/api/.reqlite/folder.json")),
Some(Path::new("/c/api"))
);
assert_eq!(settings_dir(Path::new("/c/api/folder.json")), None);
}
#[test]
fn inherits_from_the_nearest_folder_within_the_root() {
let mut m = BTreeMap::new();
let hdr = |s: &str| FolderSettings {
auth: FolderAuth::Header(s.into()),
..Default::default()
};
m.insert(PathBuf::from("/"), hdr("outside"));
m.insert(PathBuf::from("/c"), hdr("Bearer root"));
m.insert(
PathBuf::from("/c/public"),
FolderSettings {
auth: FolderAuth::None,
..Default::default()
},
);
m.insert(PathBuf::from("/c/api/v2"), FolderSettings::default());
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")));
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);
}
#[test]
fn request_modes_and_sending() {
let f = HttpFile::parse("GET /a\nAuthorization: Bearer own\n\n###\n# @no-auth\nGET /b\n\n###\nGET /c\n");
let modes: Vec<_> = f.requests().map(auth_mode).collect();
assert_eq!(
modes,
vec![AuthMode::Own("Bearer own".into()), AuthMode::NoAuth, AuthMode::Inherit]
);
let inh = InheritedAuth {
from: "/c".into(),
value: Some("Bearer folder".into()),
};
let sent: Vec<_> = f
.requests()
.map(|r| {
with_inherited_auth(r, Some(&inh))
.header("authorization")
.map(str::to_string)
})
.collect();
assert_eq!(
sent,
vec![Some("Bearer own".into()), None, Some("Bearer folder".into())]
);
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"));
}
#[test]
fn on_disk_lookup_stops_at_the_collection_root() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("c");
let api = root.join("api");
std::fs::create_dir_all(api.join(DIR)).unwrap();
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")
);
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")));
}
}