514 lines
18 KiB
Rust
514 lines
18 KiB
Rust
//! Per-folder settings, a reqlite extension: `<folder>/.reqlite/folder.json`.
|
|
//!
|
|
//! For now it only holds the folder's default auth, a header that requests
|
|
//! in the folder (and its subfolders) use when they don't set auth
|
|
//! themselves. A string is an `Authorization` header value; an object names
|
|
//! some other header:
|
|
//!
|
|
//! ```json
|
|
//! { "auth": "Bearer {{token}}" }
|
|
//! { "auth": { "header": "X-API-Key", "value": "{{api_key}}" } }
|
|
//! ```
|
|
//!
|
|
//! `"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";
|
|
/// `# @auth-header X-API-Key`: the request's own auth is that header rather
|
|
/// than `Authorization`.
|
|
pub const AUTH_HEADER_DIRECTIVE: &str = "auth-header";
|
|
pub const AUTHORIZATION: &str = "Authorization";
|
|
|
|
/// The header auth is sent in: usually `Authorization`, but APIs that take a
|
|
/// key in a header of their own (`X-API-Key: …`) are common too.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct AuthHeader {
|
|
pub name: String,
|
|
pub value: String,
|
|
}
|
|
|
|
impl AuthHeader {
|
|
/// An `Authorization` header with this value.
|
|
pub fn authorization(value: impl Into<String>) -> Self {
|
|
Self {
|
|
name: AUTHORIZATION.into(),
|
|
value: value.into(),
|
|
}
|
|
}
|
|
|
|
pub fn custom(name: impl Into<String>, value: impl Into<String>) -> Self {
|
|
Self {
|
|
name: name.into(),
|
|
value: value.into(),
|
|
}
|
|
}
|
|
|
|
pub fn is_authorization(&self) -> bool {
|
|
self.name.eq_ignore_ascii_case(AUTHORIZATION)
|
|
}
|
|
}
|
|
|
|
/// An `Authorization` header value, like the string form in folder.json.
|
|
impl From<&str> for AuthHeader {
|
|
fn from(value: &str) -> Self {
|
|
Self::authorization(value)
|
|
}
|
|
}
|
|
|
|
/// The value for `Authorization`, `Name: value` for other headers.
|
|
impl std::fmt::Display for AuthHeader {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
if self.is_authorization() {
|
|
f.write_str(&self.value)
|
|
} else {
|
|
write!(f, "{}: {}", self.name, self.value)
|
|
}
|
|
}
|
|
}
|
|
|
|
#[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,
|
|
/// A header, e.g. `Authorization: Bearer {{token}}`.
|
|
Header(AuthHeader),
|
|
}
|
|
|
|
#[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(AuthHeader::authorization(s)),
|
|
Some(Value::Object(o)) => {
|
|
let field = |k: &str| o.get(k).and_then(Value::as_str).map(str::to_string);
|
|
match (field("header"), field("value")) {
|
|
(Some(name), Some(value)) if !name.trim().is_empty() => {
|
|
FolderAuth::Header(AuthHeader::custom(name.trim(), value))
|
|
}
|
|
_ => {
|
|
return Err(FolderError::Shape {
|
|
path: path.to_path_buf(),
|
|
})
|
|
}
|
|
}
|
|
}
|
|
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) if h.is_authorization() => {
|
|
map.insert("auth".into(), Value::String(h.value.clone()));
|
|
}
|
|
FolderAuth::Header(h) => {
|
|
map.insert("auth".into(), serde_json::json!({ "header": h.name, "value": h.value }));
|
|
}
|
|
}
|
|
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; `None` when that folder says "no auth".
|
|
pub value: Option<AuthHeader>,
|
|
}
|
|
|
|
/// 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()));
|
|
}
|
|
}
|
|
|
|
/// The header named by `# @auth-header`, if any.
|
|
fn auth_header_directive(req: &Request) -> Option<&str> {
|
|
req.directives
|
|
.other
|
|
.iter()
|
|
.find(|(n, v)| n == AUTH_HEADER_DIRECTIVE && !v.trim().is_empty())
|
|
.map(|(_, v)| v.trim())
|
|
}
|
|
|
|
/// How a request gets its auth.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum AuthMode {
|
|
/// It has its own auth header: `Authorization`, or the one named by
|
|
/// `# @auth-header`.
|
|
Own(AuthHeader),
|
|
/// `# @no-auth`.
|
|
NoAuth,
|
|
/// From its folder.
|
|
Inherit,
|
|
}
|
|
|
|
pub fn auth_mode(req: &Request) -> AuthMode {
|
|
let custom = auth_header_directive(req).and_then(|n| Some(AuthHeader::custom(n, req.header(n)?)));
|
|
if let Some(h) = custom {
|
|
return AuthMode::Own(h);
|
|
}
|
|
match req.header(AUTHORIZATION) {
|
|
Some(v) => AuthMode::Own(AuthHeader::authorization(v)),
|
|
None if has_no_auth(req) => AuthMode::NoAuth,
|
|
None => AuthMode::Inherit,
|
|
}
|
|
}
|
|
|
|
/// Changes how the request gets its auth: drops its current auth header
|
|
/// (and `# @auth-header` / `# @no-auth`), then writes the new one.
|
|
pub fn set_auth_mode(req: &mut Request, mode: &AuthMode) {
|
|
if let Some(n) = auth_header_directive(req).map(str::to_string) {
|
|
req.remove_header(&n);
|
|
}
|
|
req.remove_header(AUTHORIZATION);
|
|
req.directives
|
|
.other
|
|
.retain(|(n, _)| n != AUTH_HEADER_DIRECTIVE && n != NO_AUTH_DIRECTIVE);
|
|
match mode {
|
|
AuthMode::Own(h) => {
|
|
if !h.is_authorization() {
|
|
req.directives
|
|
.other
|
|
.push((AUTH_HEADER_DIRECTIVE.into(), h.name.clone()));
|
|
}
|
|
req.set_header(&h.name, h.value.as_str());
|
|
}
|
|
AuthMode::NoAuth => set_no_auth(req, true),
|
|
AuthMode::Inherit => {}
|
|
}
|
|
}
|
|
|
|
/// The request as it is sent: with the inherited auth header added when it
|
|
/// inherits one (a header the request already sets wins).
|
|
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_ref())) {
|
|
(AuthMode::Inherit, Some(h)) if h.is_authorization() || req.header(&h.name).is_none() => {
|
|
let mut r = req.clone();
|
|
r.set_header(&h.name, h.value.as_str());
|
|
Cow::Owned(r)
|
|
}
|
|
_ => Cow::Borrowed(req),
|
|
}
|
|
}
|
|
|
|
/// Whether two headers are the same auth (ignoring the name's case and the
|
|
/// value's spacing).
|
|
pub fn same_auth(a: &AuthHeader, b: &AuthHeader) -> bool {
|
|
a.name.eq_ignore_ascii_case(&b.name) && a.value.split_whitespace().eq(b.value.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(AuthHeader::authorization("Bearer {{t}}")));
|
|
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());
|
|
|
|
let s = FolderSettings::parse(r#"{"auth": {"header": "X-API-Key", "value": "{{k}}"}}"#, p).unwrap();
|
|
assert_eq!(s.auth, FolderAuth::Header(AuthHeader::custom("X-API-Key", "{{k}}")));
|
|
assert_eq!(FolderSettings::parse(&s.to_json(), p).unwrap(), s);
|
|
assert!(FolderSettings::parse(r#"{"auth": {"header": "", "value": "x"}}"#, p).is_err());
|
|
assert!(FolderSettings::parse(r#"{"auth": {"value": "x"}}"#, 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(AuthHeader::authorization(s)),
|
|
..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.map(|h| h.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(AuthHeader::authorization("Bearer own")),
|
|
AuthMode::NoAuth,
|
|
AuthMode::Inherit
|
|
]
|
|
);
|
|
let inh = InheritedAuth {
|
|
from: "/c".into(),
|
|
value: Some(AuthHeader::authorization("Bearer folder")),
|
|
};
|
|
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(
|
|
&AuthHeader::authorization("Basic a b"),
|
|
&AuthHeader::authorization("Basic a b")
|
|
));
|
|
assert!(!same_auth(
|
|
&AuthHeader::authorization("k"),
|
|
&AuthHeader::custom("X-API-Key", "k")
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn custom_header_auth() {
|
|
let f = HttpFile::parse(
|
|
"# @auth-header X-API-Key\nGET /a\nX-API-Key: own\n\n###\nGET /b\nX-API-Key: plain\n\n###\nGET /c\n",
|
|
);
|
|
let key = |s: &str| AuthHeader::custom("X-API-Key", s);
|
|
assert_eq!(f.request(0).map(auth_mode), Some(AuthMode::Own(key("own"))));
|
|
// Without the directive the header is just a header.
|
|
assert_eq!(f.request(1).map(auth_mode), Some(AuthMode::Inherit));
|
|
|
|
let inh = InheritedAuth {
|
|
from: "/c".into(),
|
|
value: Some(key("folder")),
|
|
};
|
|
let sent: Vec<_> = f
|
|
.requests()
|
|
.map(|r| {
|
|
with_inherited_auth(r, Some(&inh))
|
|
.header("x-api-key")
|
|
.map(str::to_string)
|
|
})
|
|
.collect();
|
|
assert_eq!(
|
|
sent,
|
|
vec![Some("own".into()), Some("plain".into()), Some("folder".into())]
|
|
);
|
|
|
|
// Switching kinds removes the old header and directive.
|
|
let mut r = f.request(0).unwrap().clone();
|
|
set_auth_mode(&mut r, &AuthMode::Own(AuthHeader::authorization("Bearer t")));
|
|
assert_eq!(r.header("x-api-key"), None);
|
|
assert_eq!(auth_mode(&r), AuthMode::Own(AuthHeader::authorization("Bearer t")));
|
|
set_auth_mode(&mut r, &AuthMode::Own(key("k2")));
|
|
assert_eq!(r.header("authorization"), None);
|
|
assert_eq!(auth_mode(&r), AuthMode::Own(key("k2")));
|
|
assert!(f
|
|
.replace_request(0, &r)
|
|
.unwrap()
|
|
.starts_with("# @auth-header X-API-Key\nGET /a\nX-API-Key: k2\n"));
|
|
set_auth_mode(&mut r, &AuthMode::NoAuth);
|
|
assert_eq!((r.header("x-api-key"), auth_mode(&r)), (None, AuthMode::NoAuth));
|
|
set_auth_mode(&mut r, &AuthMode::Inherit);
|
|
assert_eq!(auth_mode(&r), AuthMode::Inherit);
|
|
}
|
|
|
|
#[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,
|
|
Some(AuthHeader::authorization("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), (api, Some(AuthHeader::authorization("Bearer api"))));
|
|
}
|
|
}
|