1 parent
ae055be9cc
commit
1e7f8678eb
9 files changed
+377
-97
No files matched your search
+203
-30
@@ -1,11 +1,13 @@
|
||||
//! 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:
|
||||
//! 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
|
||||
@@ -24,6 +26,57 @@ 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 {
|
||||
@@ -40,8 +93,8 @@ pub enum FolderAuth {
|
||||
Inherit,
|
||||
/// No auth for this folder, whatever the parents say.
|
||||
None,
|
||||
/// An `Authorization` header value, e.g. `Bearer {{token}}`.
|
||||
Header(String),
|
||||
/// A header, e.g. `Authorization: Bearer {{token}}`.
|
||||
Header(AuthHeader),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
@@ -69,7 +122,20 @@ impl FolderSettings {
|
||||
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(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(),
|
||||
@@ -86,8 +152,11 @@ impl FolderSettings {
|
||||
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(), Value::String(h.clone()));
|
||||
map.insert("auth".into(), serde_json::json!({ "header": h.name, "value": h.value }));
|
||||
}
|
||||
}
|
||||
map.extend(self.other.clone());
|
||||
@@ -127,8 +196,8 @@ pub fn settings_dir(path: &Path) -> Option<&Path> {
|
||||
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>,
|
||||
/// 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
|
||||
@@ -193,11 +262,21 @@ pub fn set_no_auth(req: &mut Request, on: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 `Authorization` header.
|
||||
Own(String),
|
||||
/// It has its own auth header: `Authorization`, or the one named by
|
||||
/// `# @auth-header`.
|
||||
Own(AuthHeader),
|
||||
/// `# @no-auth`.
|
||||
NoAuth,
|
||||
/// From its folder.
|
||||
@@ -205,29 +284,58 @@ pub enum AuthMode {
|
||||
}
|
||||
|
||||
pub fn auth_mode(req: &Request) -> AuthMode {
|
||||
match req.header("authorization") {
|
||||
Some(v) => AuthMode::Own(v.to_string()),
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// The request as it is sent: with the inherited `Authorization` header
|
||||
/// added when it inherits one.
|
||||
/// 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_deref())) {
|
||||
(AuthMode::Inherit, Some(v)) => {
|
||||
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("Authorization", v);
|
||||
r.set_header(&h.name, h.value.as_str());
|
||||
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())
|
||||
/// 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)]
|
||||
@@ -240,7 +348,7 @@ mod tests {
|
||||
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!(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!(
|
||||
@@ -251,6 +359,12 @@ mod tests {
|
||||
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]
|
||||
@@ -266,7 +380,7 @@ mod tests {
|
||||
fn inherits_from_the_nearest_folder_within_the_root() {
|
||||
let mut m = BTreeMap::new();
|
||||
let hdr = |s: &str| FolderSettings {
|
||||
auth: FolderAuth::Header(s.into()),
|
||||
auth: FolderAuth::Header(AuthHeader::authorization(s)),
|
||||
..Default::default()
|
||||
};
|
||||
m.insert(PathBuf::from("/"), hdr("outside"));
|
||||
@@ -282,7 +396,10 @@ mod tests {
|
||||
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")));
|
||||
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);
|
||||
@@ -294,11 +411,15 @@ mod tests {
|
||||
let modes: Vec<_> = f.requests().map(auth_mode).collect();
|
||||
assert_eq!(
|
||||
modes,
|
||||
vec![AuthMode::Own("Bearer own".into()), AuthMode::NoAuth, AuthMode::Inherit]
|
||||
vec![
|
||||
AuthMode::Own(AuthHeader::authorization("Bearer own")),
|
||||
AuthMode::NoAuth,
|
||||
AuthMode::Inherit
|
||||
]
|
||||
);
|
||||
let inh = InheritedAuth {
|
||||
from: "/c".into(),
|
||||
value: Some("Bearer folder".into()),
|
||||
value: Some(AuthHeader::authorization("Bearer folder")),
|
||||
};
|
||||
let sent: Vec<_> = f
|
||||
.requests()
|
||||
@@ -316,7 +437,59 @@ mod tests {
|
||||
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"));
|
||||
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]
|
||||
@@ -328,13 +501,13 @@ mod tests {
|
||||
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")
|
||||
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.as_deref()), (api, Some("Bearer api")));
|
||||
assert_eq!((a.from, a.value), (api, Some(AuthHeader::authorization("Bearer api"))));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user