Compare commits
4
Commits
ae055be9cc
..
v0.2.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5b4c0d756 | ||
|
|
5ab7c3a72b | ||
|
|
135e9777fa | ||
|
|
1e7f8678eb |
No files matched your search
@@ -59,7 +59,26 @@ jobs:
|
|||||||
(cd target/dist && rm -f "${name}.zip" && zip -r9 "${name}.zip" "$name")
|
(cd target/dist && rm -f "${name}.zip" && zip -r9 "${name}.zip" "$name")
|
||||||
echo "name=${name}" >> "$GITHUB_OUTPUT"
|
echo "name=${name}" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
echo "version=${version}" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- uses: actions/upload-artifact@v3
|
- uses: actions/upload-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: ${{ steps.package.outputs.name }}
|
name: ${{ steps.package.outputs.name }}
|
||||||
path: target/dist/${{ steps.package.outputs.name }}.zip
|
path: target/dist/${{ steps.package.outputs.name }}.zip
|
||||||
|
|
||||||
|
- name: Check tag matches crate version
|
||||||
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
|
run: |
|
||||||
|
if [ "${GITHUB_REF_NAME}" != "v${{ steps.package.outputs.version }}" ]; then
|
||||||
|
echo "Tag ${GITHUB_REF_NAME} does not match crate version v${{ steps.package.outputs.version }}" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Publish release
|
||||||
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
|
uses: https://gitea.com/actions/gitea-release-action@v1
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
name: ${{ github.ref_name }}
|
||||||
|
files: target/dist/${{ steps.package.outputs.name }}.zip
|
||||||
|
sha256sum: true
|
||||||
Generated
+4
-4
@@ -3340,7 +3340,7 @@ checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "reqlite-app"
|
name = "reqlite-app"
|
||||||
version = "0.2.0"
|
version = "0.2.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64 0.23.1",
|
"base64 0.23.1",
|
||||||
@@ -3368,7 +3368,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "reqlite-cli"
|
name = "reqlite-cli"
|
||||||
version = "0.2.0"
|
version = "0.2.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
@@ -3382,7 +3382,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "reqlite-core"
|
name = "reqlite-core"
|
||||||
version = "0.2.0"
|
version = "0.2.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"base64 0.23.1",
|
"base64 0.23.1",
|
||||||
@@ -3397,7 +3397,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "reqlite-http-curl"
|
name = "reqlite-http-curl"
|
||||||
version = "0.2.0"
|
version = "0.2.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"curl",
|
"curl",
|
||||||
"rcgen",
|
"rcgen",
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "2"
|
|||||||
members = ["crates/core", "crates/http-curl", "crates/app", "crates/cli"]
|
members = ["crates/core", "crates/http-curl", "crates/app", "crates/cli"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.2.0"
|
version = "0.2.2"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
rust-version = "1.98"
|
rust-version = "1.98"
|
||||||
|
|||||||
@@ -75,14 +75,19 @@ Other things worth knowing:
|
|||||||
form stay in sync.
|
form stay in sync.
|
||||||
- The **Auth** tab is a helper that writes the `Authorization` header. Basic
|
- The **Auth** tab is a helper that writes the `Authorization` header. Basic
|
||||||
auth is written as `Basic user password` and encoded when sent, like JetBrains.
|
auth is written as `Basic user password` and encoded when sent, like JetBrains.
|
||||||
|
*Custom header* sends auth in a header of your choice (e.g. `X-API-Key`); the
|
||||||
|
request is marked with `# @auth-header X-API-Key` so reqlite knows that header
|
||||||
|
is its auth.
|
||||||
- **Folder auth:** right-click a folder → *Folder auth…* (or a collection →
|
- **Folder auth:** right-click a folder → *Folder auth…* (or a collection →
|
||||||
*Default auth…*) to set auth that every request below it uses when it has no
|
*Default auth…*) to set auth that every request below it uses when it has no
|
||||||
`Authorization` header of its own. The nearest folder wins; a folder can also
|
`Authorization` header of its own. The nearest folder wins; a folder can also
|
||||||
say *None* to stop inheritance. In a request's Auth tab, *Inherit* (no
|
say *None* to stop inheritance. In a request's Auth tab, *Inherit* (no
|
||||||
header) uses it and *None* opts out with `# @no-auth`. It is stored in
|
header) uses it and *None* opts out with `# @no-auth`. It is stored in
|
||||||
`<folder>/.reqlite/folder.json` as `{ "auth": "Bearer {{token}}" }`
|
`<folder>/.reqlite/folder.json` as `{ "auth": "Bearer {{token}}" }`, or
|
||||||
(`null` = none); other `.http` tools ignore it. The CLI applies it too.
|
`{ "auth": { "header": "X-API-Key", "value": "{{api_key}}" } }` for a custom
|
||||||
- **Consolidate auth…** (same menus) removes `Authorization` headers that match
|
header (`null` = none); other `.http` tools ignore it. A request that already
|
||||||
|
sets the folder's custom header itself keeps its own value. The CLI applies it too.
|
||||||
|
- **Consolidate auth…** (same menus) removes auth headers that match
|
||||||
what the request would inherit. If the folder has no auth yet, it offers the
|
what the request would inherit. If the folder has no auth yet, it offers the
|
||||||
most used header as the folder's auth, and can pin requests that would
|
most used header as the folder's auth, and can pin requests that would
|
||||||
otherwise change (they get their current header, or `# @no-auth`).
|
otherwise change (they get their current header, or `# @no-auth`).
|
||||||
@@ -129,7 +134,7 @@ on:
|
|||||||
- Directives: `# @name`, `# @no-redirect`, `# @no-cookie-jar`, `# @no-log`,
|
- Directives: `# @name`, `# @no-redirect`, `# @no-cookie-jar`, `# @no-log`,
|
||||||
`# @timeout 30` / `500 ms`, `# @connection-timeout`. `# @insecure` is a
|
`# @timeout 30` / `500 ms`, `# @connection-timeout`. `# @insecure` is a
|
||||||
reqlite extension written by curl import for `-k`; `# @no-auth` is one that
|
reqlite extension written by curl import for `-k`; `# @no-auth` is one that
|
||||||
skips folder auth.
|
skips folder auth, and `# @auth-header <name>` marks a custom auth header.
|
||||||
- `#` and `//` comments.
|
- `#` and `//` comments.
|
||||||
|
|
||||||
Anything else (unknown directives, response handlers `> {% … %}` and
|
Anything else (unknown directives, response handlers `> {% … %}` and
|
||||||
|
|||||||
+16
-19
@@ -8,7 +8,9 @@ use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
|||||||
use reqlite_core::collection::{self, Collection};
|
use reqlite_core::collection::{self, Collection};
|
||||||
use reqlite_core::env::{self, Environments};
|
use reqlite_core::env::{self, Environments};
|
||||||
use reqlite_core::export::curl::to_curl;
|
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::folder::{
|
||||||
|
self, auth_mode, same_auth, with_inherited_auth, AuthHeader, AuthMode, FolderAuth, FolderSettings,
|
||||||
|
};
|
||||||
use reqlite_core::http::{HttpError, Response};
|
use reqlite_core::http::{HttpError, Response};
|
||||||
use reqlite_core::httpfile::{render_request, HttpFile};
|
use reqlite_core::httpfile::{render_request, HttpFile};
|
||||||
use reqlite_core::import::curl::{from_curl, looks_like_curl};
|
use reqlite_core::import::curl::{from_curl, looks_like_curl};
|
||||||
@@ -154,7 +156,7 @@ pub enum Action {
|
|||||||
/// `target` picks the auth to inherit when the folder has none.
|
/// `target` picks the auth to inherit when the folder has none.
|
||||||
ConsolidateAuth {
|
ConsolidateAuth {
|
||||||
dir: PathBuf,
|
dir: PathBuf,
|
||||||
target: Option<String>,
|
target: Option<AuthHeader>,
|
||||||
},
|
},
|
||||||
ApplyConsolidateAuth(ConsolidateAuth),
|
ApplyConsolidateAuth(ConsolidateAuth),
|
||||||
|
|
||||||
@@ -320,13 +322,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
|
|||||||
}
|
}
|
||||||
Action::HeadersEdited(id, headers) => edit(state, id, |r| r.headers = headers),
|
Action::HeadersEdited(id, headers) => edit(state, id, |r| r.headers = headers),
|
||||||
Action::BodyEdited(id, body) => edit(state, id, |r| r.body = body),
|
Action::BodyEdited(id, body) => edit(state, id, |r| r.body = body),
|
||||||
Action::AuthEdited(id, mode) => edit(state, id, |r| {
|
Action::AuthEdited(id, mode) => edit(state, id, |r| folder::set_auth_mode(r, &mode)),
|
||||||
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::SetNoRedirect(id, on) => edit(state, id, |r| r.directives.no_redirect = on),
|
||||||
Action::PickBodyFile(id) => fx.push(Effect::PickBodyFile(id)),
|
Action::PickBodyFile(id) => fx.push(Effect::PickBodyFile(id)),
|
||||||
Action::BodyFilePicked(id, path) => {
|
Action::BodyFilePicked(id, path) => {
|
||||||
@@ -1434,14 +1430,14 @@ fn slug_name(title: &str) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Works out what "Consolidate auth" on `dir` would do: which requests can
|
/// Works out what "Consolidate auth" on `dir` would do: which requests can
|
||||||
/// drop their own Authorization header and inherit `dir`'s auth instead.
|
/// drop their own auth header and inherit `dir`'s auth instead.
|
||||||
/// When `dir` has no auth of its own, `pick` (or what it already inherits,
|
/// When `dir` has no auth of its own, `pick` (or what it already inherits,
|
||||||
/// or the most used header) becomes its auth.
|
/// or the most used header) becomes its auth.
|
||||||
pub fn plan_consolidation(state: &AppState, dir: &Path, pick: Option<String>) -> Option<ConsolidateAuth> {
|
pub fn plan_consolidation(state: &AppState, dir: &Path, pick: Option<AuthHeader>) -> Option<ConsolidateAuth> {
|
||||||
let c = state.collection_of(dir)?;
|
let c = state.collection_of(dir)?;
|
||||||
let requests: Vec<_> = c.all_requests().filter(|(p, _, _)| p.starts_with(dir)).collect();
|
let requests: Vec<_> = c.all_requests().filter(|(p, _, _)| p.starts_with(dir)).collect();
|
||||||
|
|
||||||
let mut choices: Vec<(String, usize)> = Vec::new();
|
let mut choices: Vec<(AuthHeader, usize)> = Vec::new();
|
||||||
for (_, _, r) in &requests {
|
for (_, _, r) in &requests {
|
||||||
if let AuthMode::Own(v) = auth_mode(r) {
|
if let AuthMode::Own(v) = auth_mode(r) {
|
||||||
match choices.iter_mut().find(|(c, _)| same_auth(c, &v)) {
|
match choices.iter_mut().find(|(c, _)| same_auth(c, &v)) {
|
||||||
@@ -1549,7 +1545,7 @@ enum AuthFix {
|
|||||||
/// Drop its own header so it inherits.
|
/// Drop its own header so it inherits.
|
||||||
Inherit,
|
Inherit,
|
||||||
/// Pin the auth it sends today (a header, or `# @no-auth` for `None`).
|
/// Pin the auth it sends today (a header, or `# @no-auth` for `None`).
|
||||||
Keep(Option<String>),
|
Keep(Option<AuthHeader>),
|
||||||
}
|
}
|
||||||
|
|
||||||
fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec<Effect>) {
|
fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec<Effect>) {
|
||||||
@@ -1583,14 +1579,15 @@ fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec
|
|||||||
// The file may have changed since the plan was made.
|
// The file may have changed since the plan was made.
|
||||||
match (&edit, auth_mode(&r)) {
|
match (&edit, auth_mode(&r)) {
|
||||||
(AuthFix::Inherit, AuthMode::Own(_)) => {
|
(AuthFix::Inherit, AuthMode::Own(_)) => {
|
||||||
r.remove_header("Authorization");
|
folder::set_auth_mode(&mut r, &AuthMode::Inherit);
|
||||||
dropped += 1;
|
dropped += 1;
|
||||||
}
|
}
|
||||||
(AuthFix::Keep(before), AuthMode::Inherit) => {
|
(AuthFix::Keep(before), AuthMode::Inherit) => {
|
||||||
match before {
|
let mode = match before {
|
||||||
Some(v) => r.set_header("Authorization", v.as_str()),
|
Some(h) => AuthMode::Own(h.clone()),
|
||||||
None => folder::set_no_auth(&mut r, true),
|
None => AuthMode::NoAuth,
|
||||||
}
|
};
|
||||||
|
folder::set_auth_mode(&mut r, &mode);
|
||||||
pinned += 1;
|
pinned += 1;
|
||||||
}
|
}
|
||||||
_ => continue,
|
_ => continue,
|
||||||
@@ -1621,7 +1618,7 @@ fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec
|
|||||||
settings.auth = FolderAuth::Header(target.clone());
|
settings.auth = FolderAuth::Header(target.clone());
|
||||||
ops.push(FileOp::Write(folder::settings_path(&plan.dir), settings.to_json()));
|
ops.push(FileOp::Write(folder::settings_path(&plan.dir), settings.to_json()));
|
||||||
c.folders.insert(plan.dir.clone(), settings);
|
c.folders.insert(plan.dir.clone(), settings);
|
||||||
msg.push(txt::consolidate::set_folder(target));
|
msg.push(txt::consolidate::set_folder(&target.to_string()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if dropped > 0 {
|
if dropped > 0 {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ use reqlite_core::collection::{Collection, Node};
|
|||||||
use reqlite_core::env::EnvFile;
|
use reqlite_core::env::EnvFile;
|
||||||
use reqlite_core::http::{BodyStore, Timings};
|
use reqlite_core::http::{BodyStore, Timings};
|
||||||
|
|
||||||
use reqlite_core::folder::{AuthMode, FolderAuth};
|
use reqlite_core::folder::{AuthHeader, AuthMode, FolderAuth};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
@@ -1180,6 +1180,69 @@ fn requests_inherit_folder_auth_unless_they_opt_out() {
|
|||||||
assert_eq!(sent_auth(&mut s, own).as_deref(), Some("Bearer root"));
|
assert_eq!(sent_auth(&mut s, own).as_deref(), Some("Bearer root"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn sent_header(s: &mut AppState, id: TabId, name: &str) -> 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 v = request
|
||||||
|
.headers
|
||||||
|
.iter()
|
||||||
|
.find(|(n, _)| n.eq_ignore_ascii_case(name))
|
||||||
|
.map(|(_, v)| v.clone());
|
||||||
|
update(s, Action::Cancel(id));
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn folder_and_request_auth_can_use_a_custom_header() {
|
||||||
|
let mut s = state();
|
||||||
|
let root = with_collection(
|
||||||
|
&mut s,
|
||||||
|
&[("a.http", "### Plain\nGET http://x/a\n\n### Own\nGET http://x/b\n")],
|
||||||
|
);
|
||||||
|
let open = |s: &mut AppState, index| {
|
||||||
|
update(
|
||||||
|
s,
|
||||||
|
Action::OpenRequest {
|
||||||
|
file: root.join("a.http"),
|
||||||
|
index,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
active(s)
|
||||||
|
};
|
||||||
|
let plain = open(&mut s, 0);
|
||||||
|
let own = open(&mut s, 1);
|
||||||
|
|
||||||
|
let key = |v: &str| AuthHeader::custom("X-API-Key", v);
|
||||||
|
let fx = set_folder_auth(&mut s, root.clone(), FolderAuth::Header(key("k-root")));
|
||||||
|
assert_eq!(
|
||||||
|
writes(&fx),
|
||||||
|
vec![(
|
||||||
|
root.join(".reqlite/folder.json"),
|
||||||
|
"{\n \"auth\": {\n \"header\": \"X-API-Key\",\n \"value\": \"k-root\"\n }\n}\n".into()
|
||||||
|
)]
|
||||||
|
);
|
||||||
|
assert_eq!(sent_header(&mut s, plain, "x-api-key").as_deref(), Some("k-root"));
|
||||||
|
assert_eq!(sent_auth(&mut s, plain), None);
|
||||||
|
|
||||||
|
// A request's own custom header replaces the folder's.
|
||||||
|
update(&mut s, Action::AuthEdited(own, AuthMode::Own(key("k-own"))));
|
||||||
|
assert!(s
|
||||||
|
.tab(own)
|
||||||
|
.unwrap()
|
||||||
|
.source
|
||||||
|
.contains("# @auth-header X-API-Key\nGET http://x/b\nX-API-Key: k-own\n"));
|
||||||
|
assert_eq!(sent_header(&mut s, own, "x-api-key").as_deref(), Some("k-own"));
|
||||||
|
|
||||||
|
// Switching to Bearer drops the custom header and the directive.
|
||||||
|
update(&mut s, Action::AuthEdited(own, AuthMode::Own("Bearer t".into())));
|
||||||
|
let src = &s.tab(own).unwrap().source;
|
||||||
|
assert!(!src.contains("X-API-Key") && !src.contains("@auth-header"), "{src}");
|
||||||
|
assert_eq!(sent_auth(&mut s, own).as_deref(), Some("Bearer t"));
|
||||||
|
assert_eq!(sent_header(&mut s, own, "x-api-key"), None);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn folder_settings_files_are_reloaded_when_they_change() {
|
fn folder_settings_files_are_reloaded_when_they_change() {
|
||||||
let mut s = state();
|
let mut s = state();
|
||||||
@@ -1213,7 +1276,7 @@ fn consolidate(s: &mut AppState, dir: PathBuf, target: Option<&str>) -> Consolid
|
|||||||
s,
|
s,
|
||||||
Action::ConsolidateAuth {
|
Action::ConsolidateAuth {
|
||||||
dir,
|
dir,
|
||||||
target: target.map(str::to_string),
|
target: target.map(Into::into),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
match &s.dialog {
|
match &s.dialog {
|
||||||
@@ -1229,7 +1292,7 @@ fn consolidating_adopts_the_most_common_auth_as_the_collection_default() {
|
|||||||
let mut s = state();
|
let mut s = state();
|
||||||
let root = with_collection(&mut s, &[("a.http", MIXED)]);
|
let root = with_collection(&mut s, &[("a.http", MIXED)]);
|
||||||
let plan = consolidate(&mut s, root.clone(), None);
|
let plan = consolidate(&mut s, root.clone(), None);
|
||||||
assert_eq!(plan.target.as_deref(), Some("Bearer {{token}}"));
|
assert_eq!(plan.target, Some("Bearer {{token}}".into()));
|
||||||
assert!(plan.set_folder);
|
assert!(plan.set_folder);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
plan.choices,
|
plan.choices,
|
||||||
@@ -1295,11 +1358,7 @@ fn consolidating_keeps_subfolder_overrides_and_skips_unsaved_tabs() {
|
|||||||
update(&mut s, Action::UrlEdited(id, "http://x/edited".into()));
|
update(&mut s, Action::UrlEdited(id, "http://x/edited".into()));
|
||||||
|
|
||||||
let plan = consolidate(&mut s, root.clone(), Some("Basic ignored"));
|
let plan = consolidate(&mut s, root.clone(), Some("Basic ignored"));
|
||||||
assert_eq!(
|
assert_eq!(plan.target, Some("Bearer root".into()), "the folder's own auth wins");
|
||||||
plan.target.as_deref(),
|
|
||||||
Some("Bearer root"),
|
|
||||||
"the folder's own auth wins"
|
|
||||||
);
|
|
||||||
assert!(!plan.set_folder && plan.choices.is_empty());
|
assert!(!plan.set_folder && plan.choices.is_empty());
|
||||||
let own: Vec<(&str, bool)> = plan
|
let own: Vec<(&str, bool)> = plan
|
||||||
.own
|
.own
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use std::time::{Instant, SystemTime};
|
|||||||
use reqlite_core::collection::Node;
|
use reqlite_core::collection::Node;
|
||||||
use reqlite_core::cookies::CookieJar;
|
use reqlite_core::cookies::CookieJar;
|
||||||
use reqlite_core::env::Environments;
|
use reqlite_core::env::Environments;
|
||||||
use reqlite_core::folder::{self, FolderAuth, FolderSettings, InheritedAuth};
|
use reqlite_core::folder::{self, AuthHeader, FolderAuth, FolderSettings, InheritedAuth};
|
||||||
use reqlite_core::http::{BodyStore, Response};
|
use reqlite_core::http::{BodyStore, Response};
|
||||||
use reqlite_core::httpfile::{HttpFile, RequestKey};
|
use reqlite_core::httpfile::{HttpFile, RequestKey};
|
||||||
use reqlite_core::params::Param;
|
use reqlite_core::params::Param;
|
||||||
@@ -108,17 +108,17 @@ pub struct RequestRef {
|
|||||||
pub struct ConsolidateAuth {
|
pub struct ConsolidateAuth {
|
||||||
pub dir: PathBuf,
|
pub dir: PathBuf,
|
||||||
/// The auth requests in `dir` should inherit.
|
/// The auth requests in `dir` should inherit.
|
||||||
pub target: Option<String>,
|
pub target: Option<AuthHeader>,
|
||||||
/// `dir` doesn't have `target` as its own setting yet; applying writes it.
|
/// `dir` doesn't have `target` as its own setting yet; applying writes it.
|
||||||
pub set_folder: bool,
|
pub set_folder: bool,
|
||||||
/// Values to pick `target` from (with how many requests use each), when
|
/// Values to pick `target` from (with how many requests use each), when
|
||||||
/// `dir` has no auth of its own.
|
/// `dir` has no auth of its own.
|
||||||
pub choices: Vec<(String, usize)>,
|
pub choices: Vec<(AuthHeader, usize)>,
|
||||||
/// Requests with their own Authorization header.
|
/// Requests with their own auth header.
|
||||||
pub own: Vec<OwnAuth>,
|
pub own: Vec<OwnAuth>,
|
||||||
/// Requests that inherit today and would send something else once
|
/// Requests that inherit today and would send something else once
|
||||||
/// `target` is set on the folder.
|
/// `target` is set on the folder.
|
||||||
pub affected: Vec<(RequestRef, Option<String>)>,
|
pub affected: Vec<(RequestRef, Option<AuthHeader>)>,
|
||||||
/// Give the affected requests their current auth explicitly (a header,
|
/// Give the affected requests their current auth explicitly (a header,
|
||||||
/// or `# @no-auth`) so they keep sending what they send today.
|
/// or `# @no-auth`) so they keep sending what they send today.
|
||||||
pub keep_affected: bool,
|
pub keep_affected: bool,
|
||||||
@@ -129,9 +129,9 @@ pub struct ConsolidateAuth {
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct OwnAuth {
|
pub struct OwnAuth {
|
||||||
pub request: RequestRef,
|
pub request: RequestRef,
|
||||||
pub value: String,
|
pub value: AuthHeader,
|
||||||
/// What the request would inherit without its header.
|
/// What the request would inherit without its header.
|
||||||
pub inherits: Option<String>,
|
pub inherits: Option<AuthHeader>,
|
||||||
/// Remove the header.
|
/// Remove the header.
|
||||||
pub selected: bool,
|
pub selected: bool,
|
||||||
}
|
}
|
||||||
@@ -140,7 +140,7 @@ impl OwnAuth {
|
|||||||
/// Removing the header keeps the request sending the same thing.
|
/// Removing the header keeps the request sending the same thing.
|
||||||
pub fn same(&self) -> bool {
|
pub fn same(&self) -> bool {
|
||||||
self.inherits
|
self.inherits
|
||||||
.as_deref()
|
.as_ref()
|
||||||
.is_some_and(|i| folder::same_auth(i, &self.value))
|
.is_some_and(|i| folder::same_auth(i, &self.value))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -176,6 +176,11 @@ pub mod auth {
|
|||||||
pub const NOT_SET: &str = "Not set";
|
pub const NOT_SET: &str = "Not set";
|
||||||
pub const BASIC: &str = "Basic";
|
pub const BASIC: &str = "Basic";
|
||||||
pub const BEARER: &str = "Bearer token";
|
pub const BEARER: &str = "Bearer token";
|
||||||
|
pub const CUSTOM_HEADER: &str = "Custom header";
|
||||||
|
pub const HEADER_NAME: &str = "Header";
|
||||||
|
pub const VALUE: &str = "Value";
|
||||||
|
pub const CUSTOM_NOTE: &str =
|
||||||
|
"Sent as `Header: value` instead of Authorization; a request marks it with `# @auth-header Header`.";
|
||||||
pub const USERNAME: &str = "Username";
|
pub const USERNAME: &str = "Username";
|
||||||
pub const PASSWORD: &str = "Password";
|
pub const PASSWORD: &str = "Password";
|
||||||
pub const BASIC_NOTE: &str =
|
pub const BASIC_NOTE: &str =
|
||||||
@@ -184,7 +189,7 @@ pub mod auth {
|
|||||||
pub const HEADER_VALUE: &str = "Header value";
|
pub const HEADER_VALUE: &str = "Header value";
|
||||||
pub const NO_AUTH_SET: &str = "No Authorization header, not even the folder's (`# @no-auth`).";
|
pub const NO_AUTH_SET: &str = "No Authorization header, not even the folder's (`# @no-auth`).";
|
||||||
pub const CUSTOM: &str = "Custom Authorization header:";
|
pub const CUSTOM: &str = "Custom Authorization header:";
|
||||||
pub const SECRETS_NOTE: &str = "Auth is just the Authorization header; put secrets in the private env file.";
|
pub const SECRETS_NOTE: &str = "Auth is just a header; put secrets in the private env file.";
|
||||||
|
|
||||||
pub const NOT_IN_COLLECTION: &str = "Not in a collection, so there is nothing to inherit.";
|
pub const NOT_IN_COLLECTION: &str = "Not in a collection, so there is nothing to inherit.";
|
||||||
pub const USES: &str = "Uses";
|
pub const USES: &str = "Uses";
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
use base64::Engine;
|
use base64::Engine;
|
||||||
use egui::{Key, RichText, Ui};
|
use egui::{Key, RichText, Ui};
|
||||||
use reqlite_core::folder::{auth_mode, AuthMode, InheritedAuth};
|
use reqlite_core::folder::{auth_mode, AuthHeader, AuthMode, InheritedAuth};
|
||||||
use reqlite_core::params::Param;
|
use reqlite_core::params::Param;
|
||||||
use reqlite_core::{Body, Header, Method, Part, PartBody};
|
use reqlite_core::{Body, Header, Method, Part, PartBody};
|
||||||
|
|
||||||
@@ -520,16 +520,20 @@ pub enum AuthKind {
|
|||||||
None,
|
None,
|
||||||
Basic,
|
Basic,
|
||||||
Bearer,
|
Bearer,
|
||||||
|
/// A header other than Authorization, e.g. `X-API-Key`.
|
||||||
|
Custom,
|
||||||
|
/// An Authorization value that isn't Basic or Bearer.
|
||||||
Other,
|
Other,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AuthKind {
|
impl AuthKind {
|
||||||
/// The header value a newly picked kind starts with.
|
/// The header a newly picked kind starts with.
|
||||||
pub fn template(self) -> Option<String> {
|
pub fn template(self) -> AuthHeader {
|
||||||
match self {
|
match self {
|
||||||
AuthKind::Basic => Some("Basic {{username}} {{password}}".into()),
|
AuthKind::Basic => AuthHeader::authorization("Basic {{username}} {{password}}"),
|
||||||
AuthKind::Bearer => Some("Bearer {{token}}".into()),
|
AuthKind::Bearer => AuthHeader::authorization("Bearer {{token}}"),
|
||||||
_ => None,
|
AuthKind::Custom => AuthHeader::custom("X-API-Key", "{{api_key}}"),
|
||||||
|
_ => AuthHeader::authorization(""),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -561,8 +565,12 @@ fn auth_parts(value: Option<&str>) -> (AuthKind, String, String) {
|
|||||||
(AuthKind::Other, v.to_string(), String::new())
|
(AuthKind::Other, v.to_string(), String::new())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn header_kind(value: &str) -> AuthKind {
|
pub fn header_kind(h: &AuthHeader) -> AuthKind {
|
||||||
auth_parts(Some(value)).0
|
if h.is_authorization() {
|
||||||
|
auth_parts(Some(&h.value)).0
|
||||||
|
} else {
|
||||||
|
AuthKind::Custom
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A row of radio buttons; returns the kind picked when it changed.
|
/// A row of radio buttons; returns the kind picked when it changed.
|
||||||
@@ -579,9 +587,32 @@ pub fn auth_kind_row(ui: &mut Ui, current: AuthKind, kinds: &[(AuthKind, &str)])
|
|||||||
picked
|
picked
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The fields for an Authorization header value (Basic, Bearer or custom);
|
/// The fields for an auth header (Basic, Bearer, a custom header or a
|
||||||
/// returns the new value when it was edited.
|
/// custom Authorization value); returns the new header when it was edited.
|
||||||
pub fn auth_value_fields(ui: &mut Ui, value: &str, vars: &VarCtx, salt: &str) -> Option<String> {
|
pub fn auth_value_fields(ui: &mut Ui, header: &AuthHeader, vars: &VarCtx, salt: &str) -> Option<AuthHeader> {
|
||||||
|
if !header.is_authorization() {
|
||||||
|
let (mut name, mut value) = (header.name.clone(), header.value.clone());
|
||||||
|
let mut changed = false;
|
||||||
|
egui::Grid::new(("custom", salt)).num_columns(2).show(ui, |ui| {
|
||||||
|
ui.label(txt::auth::HEADER_NAME);
|
||||||
|
changed |= ui
|
||||||
|
.add(
|
||||||
|
egui::TextEdit::singleline(&mut name)
|
||||||
|
.desired_width(260.0)
|
||||||
|
.id_salt(("cn", salt)),
|
||||||
|
)
|
||||||
|
.changed();
|
||||||
|
ui.end_row();
|
||||||
|
ui.label(txt::auth::VALUE);
|
||||||
|
changed |= var_text_edit(ui, &mut value, Some(vars), "", 420.0, ("cv", salt)).changed();
|
||||||
|
ui.end_row();
|
||||||
|
});
|
||||||
|
ui.label(RichText::new(txt::auth::CUSTOM_NOTE).small().weak());
|
||||||
|
// A header needs a name; keep the old one while the field is empty.
|
||||||
|
let name = name.trim();
|
||||||
|
return (changed && !name.is_empty() && !name.contains(':')).then(|| AuthHeader::custom(name, value));
|
||||||
|
}
|
||||||
|
let value = header.value.as_str();
|
||||||
let (kind, a, b) = auth_parts(Some(value));
|
let (kind, a, b) = auth_parts(Some(value));
|
||||||
let mut out = None;
|
let mut out = None;
|
||||||
match kind {
|
match kind {
|
||||||
@@ -620,7 +651,7 @@ pub fn auth_value_fields(ui: &mut Ui, value: &str, vars: &VarCtx, salt: &str) ->
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
out
|
out.map(AuthHeader::authorization)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
|
fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
|
||||||
@@ -636,6 +667,7 @@ fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<
|
|||||||
(AuthKind::None, txt::common::NONE),
|
(AuthKind::None, txt::common::NONE),
|
||||||
(AuthKind::Basic, txt::auth::BASIC),
|
(AuthKind::Basic, txt::auth::BASIC),
|
||||||
(AuthKind::Bearer, txt::auth::BEARER),
|
(AuthKind::Bearer, txt::auth::BEARER),
|
||||||
|
(AuthKind::Custom, txt::auth::CUSTOM_HEADER),
|
||||||
];
|
];
|
||||||
if let Some(k) = auth_kind_row(ui, kind, &kinds) {
|
if let Some(k) = auth_kind_row(ui, kind, &kinds) {
|
||||||
acts.push(Action::AuthEdited(
|
acts.push(Action::AuthEdited(
|
||||||
@@ -643,7 +675,7 @@ fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<
|
|||||||
match k {
|
match k {
|
||||||
AuthKind::Inherit => AuthMode::Inherit,
|
AuthKind::Inherit => AuthMode::Inherit,
|
||||||
AuthKind::None => AuthMode::NoAuth,
|
AuthKind::None => AuthMode::NoAuth,
|
||||||
k => AuthMode::Own(k.template().unwrap_or_default()),
|
k => AuthMode::Own(k.template()),
|
||||||
},
|
},
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@@ -676,7 +708,7 @@ fn inherited(ui: &mut Ui, state: &AppState, tab: &Tab, acts: &mut Vec<Action>) {
|
|||||||
Some(InheritedAuth { from, value: Some(v) }) => {
|
Some(InheritedAuth { from, value: Some(v) }) => {
|
||||||
ui.horizontal_wrapped(|ui| {
|
ui.horizontal_wrapped(|ui| {
|
||||||
ui.label(txt::auth::USES);
|
ui.label(txt::auth::USES);
|
||||||
ui.label(RichText::new(&v).monospace());
|
ui.label(RichText::new(v.to_string()).monospace());
|
||||||
ui.label(txt::auth::from_folder(&c.folder_label(&from)));
|
ui.label(txt::auth::from_folder(&c.folder_label(&from)));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -737,6 +769,7 @@ mod tests {
|
|||||||
let (k, t, _) = auth_parts(Some("Bearer abc"));
|
let (k, t, _) = auth_parts(Some("Bearer abc"));
|
||||||
assert!(k == AuthKind::Bearer && t == "abc");
|
assert!(k == AuthKind::Bearer && t == "abc");
|
||||||
assert!(auth_parts(Some("Digest x")).0 == AuthKind::Other);
|
assert!(auth_parts(Some("Digest x")).0 == AuthKind::Other);
|
||||||
assert!(header_kind("Bearer {{t}}") == AuthKind::Bearer);
|
assert!(header_kind(&AuthHeader::authorization("Bearer {{t}}")) == AuthKind::Bearer);
|
||||||
|
assert!(header_kind(&AuthHeader::custom("X-API-Key", "Bearer x")) == AuthKind::Custom);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -197,7 +197,7 @@ fn node(ui: &mut Ui, state: &AppState, c: &CollectionState, n: &Node, acts: &mut
|
|||||||
});
|
});
|
||||||
let mut header = resp.header_response;
|
let mut header = resp.header_response;
|
||||||
if let reqlite_core::folder::FolderAuth::Header(v) = c.folder_auth(path) {
|
if let reqlite_core::folder::FolderAuth::Header(v) = c.folder_auth(path) {
|
||||||
header = header.on_hover_text(txt::sidebar::folder_auth_hover(&v));
|
header = header.on_hover_text(txt::sidebar::folder_auth_hover(&v.to_string()));
|
||||||
}
|
}
|
||||||
header.context_menu(|ui| {
|
header.context_menu(|ui| {
|
||||||
if ui.button(txt::sidebar::NEW_HTTP_FILE).clicked() {
|
if ui.button(txt::sidebar::NEW_HTTP_FILE).clicked() {
|
||||||
|
|||||||
@@ -215,12 +215,13 @@ fn folder_auth(ui: &mut egui::Ui, state: &AppState, ed: &FolderAuthEdit, acts: &
|
|||||||
(AuthKind::None, txt::common::NONE),
|
(AuthKind::None, txt::common::NONE),
|
||||||
(AuthKind::Basic, txt::auth::BASIC),
|
(AuthKind::Basic, txt::auth::BASIC),
|
||||||
(AuthKind::Bearer, txt::auth::BEARER),
|
(AuthKind::Bearer, txt::auth::BEARER),
|
||||||
|
(AuthKind::Custom, txt::auth::CUSTOM_HEADER),
|
||||||
];
|
];
|
||||||
if let Some(k) = auth_kind_row(ui, kind, &kinds) {
|
if let Some(k) = auth_kind_row(ui, kind, &kinds) {
|
||||||
acts.push(set(match k {
|
acts.push(set(match k {
|
||||||
AuthKind::Inherit => FolderAuth::Inherit,
|
AuthKind::Inherit => FolderAuth::Inherit,
|
||||||
AuthKind::None => FolderAuth::None,
|
AuthKind::None => FolderAuth::None,
|
||||||
k => FolderAuth::Header(k.template().unwrap_or_default()),
|
k => FolderAuth::Header(k.template()),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
ui.add_space(6.0);
|
ui.add_space(6.0);
|
||||||
@@ -231,7 +232,9 @@ fn folder_auth(ui: &mut egui::Ui, state: &AppState, ed: &FolderAuthEdit, acts: &
|
|||||||
FolderAuth::Inherit => {
|
FolderAuth::Inherit => {
|
||||||
let parent = ed.dir.parent().and_then(|p| c.inherited_auth(p));
|
let parent = ed.dir.parent().and_then(|p| c.inherited_auth(p));
|
||||||
let text = match parent {
|
let text = match parent {
|
||||||
Some(InheritedAuth { from, value: Some(v) }) => txt::auth::parent_uses(&v, &c.folder_label(&from)),
|
Some(InheritedAuth { from, value: Some(v) }) => {
|
||||||
|
txt::auth::parent_uses(&v.to_string(), &c.folder_label(&from))
|
||||||
|
}
|
||||||
Some(InheritedAuth { from, value: None }) => txt::auth::parent_none(&c.folder_label(&from)),
|
Some(InheritedAuth { from, value: None }) => txt::auth::parent_none(&c.folder_label(&from)),
|
||||||
None => txt::auth::NO_PARENT_AUTH.into(),
|
None => txt::auth::NO_PARENT_AUTH.into(),
|
||||||
};
|
};
|
||||||
@@ -290,13 +293,13 @@ fn consolidate_auth(ui: &mut egui::Ui, state: &AppState, plan: &ConsolidateAuth,
|
|||||||
ui.horizontal(|ui| {
|
ui.horizontal(|ui| {
|
||||||
ui.label(txt::consolidate::SHARED_AUTH);
|
ui.label(txt::consolidate::SHARED_AUTH);
|
||||||
if plan.choices.is_empty() {
|
if plan.choices.is_empty() {
|
||||||
ui.label(RichText::new(target).monospace());
|
ui.label(RichText::new(target.to_string()).monospace());
|
||||||
} else {
|
} else {
|
||||||
egui::ComboBox::from_id_salt("consolidate-target")
|
egui::ComboBox::from_id_salt("consolidate-target")
|
||||||
.selected_text(RichText::new(target).monospace())
|
.selected_text(RichText::new(target.to_string()).monospace())
|
||||||
.show_ui(ui, |ui| {
|
.show_ui(ui, |ui| {
|
||||||
for (v, n) in &plan.choices {
|
for (v, n) in &plan.choices {
|
||||||
let label = txt::consolidate::choice(v, *n);
|
let label = txt::consolidate::choice(&v.to_string(), *n);
|
||||||
if ui.selectable_label(v == target, label).clicked() && v != target {
|
if ui.selectable_label(v == target, label).clicked() && v != target {
|
||||||
acts.push(Action::ConsolidateAuth {
|
acts.push(Action::ConsolidateAuth {
|
||||||
dir: plan.dir.clone(),
|
dir: plan.dir.clone(),
|
||||||
@@ -345,17 +348,22 @@ fn consolidate_auth(ui: &mut egui::Ui, state: &AppState, plan: &ConsolidateAuth,
|
|||||||
.show(ui, |ui| {
|
.show(ui, |ui| {
|
||||||
for (i, o) in plan.own.iter().enumerate() {
|
for (i, o) in plan.own.iter().enumerate() {
|
||||||
let mut on = o.selected;
|
let mut on = o.selected;
|
||||||
let resp = ui.checkbox(&mut on, &o.request.label).on_hover_text(&o.value);
|
let resp = ui
|
||||||
|
.checkbox(&mut on, &o.request.label)
|
||||||
|
.on_hover_text(o.value.to_string());
|
||||||
if resp.changed() {
|
if resp.changed() {
|
||||||
let mut p = plan.clone();
|
let mut p = plan.clone();
|
||||||
p.own[i].selected = on;
|
p.own[i].selected = on;
|
||||||
acts.push(set(p));
|
acts.push(set(p));
|
||||||
}
|
}
|
||||||
if !o.same() {
|
if !o.same() {
|
||||||
let would = o.inherits.as_deref().unwrap_or(txt::common::NO_AUTH);
|
let would = o
|
||||||
|
.inherits
|
||||||
|
.as_ref()
|
||||||
|
.map_or(txt::common::NO_AUTH.into(), |h| h.to_string());
|
||||||
ui.indent(("diff", i), |ui| {
|
ui.indent(("diff", i), |ui| {
|
||||||
ui.label(
|
ui.label(
|
||||||
RichText::new(txt::consolidate::would_send(&o.value, would))
|
RichText::new(txt::consolidate::would_send(&o.value.to_string(), &would))
|
||||||
.small()
|
.small()
|
||||||
.color(ui.visuals().warn_fg_color),
|
.color(ui.visuals().warn_fg_color),
|
||||||
);
|
);
|
||||||
@@ -367,14 +375,14 @@ fn consolidate_auth(ui: &mut egui::Ui, state: &AppState, plan: &ConsolidateAuth,
|
|||||||
|
|
||||||
if plan.set_folder && !plan.affected.is_empty() {
|
if plan.set_folder && !plan.affected.is_empty() {
|
||||||
ui.add_space(8.0);
|
ui.add_space(8.0);
|
||||||
ui.label(txt::consolidate::affected(plan.affected.len(), target));
|
ui.label(txt::consolidate::affected(plan.affected.len(), &target.to_string()));
|
||||||
egui::ScrollArea::vertical()
|
egui::ScrollArea::vertical()
|
||||||
.id_salt("consolidate-affected")
|
.id_salt("consolidate-affected")
|
||||||
.max_height(120.0)
|
.max_height(120.0)
|
||||||
.show(ui, |ui| {
|
.show(ui, |ui| {
|
||||||
for (r, before) in &plan.affected {
|
for (r, before) in &plan.affected {
|
||||||
let now = before.as_deref().unwrap_or(txt::common::NO_AUTH);
|
let now = before.as_ref().map_or(txt::common::NO_AUTH.into(), |h| h.to_string());
|
||||||
ui.label(txt::consolidate::affected_item(&r.label, now));
|
ui.label(txt::consolidate::affected_item(&r.label, &now));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
let mut keep = plan.keep_affected;
|
let mut keep = plan.keep_affected;
|
||||||
|
|||||||
+203
-30
@@ -1,11 +1,13 @@
|
|||||||
//! Per-folder settings, a reqlite extension: `<folder>/.reqlite/folder.json`.
|
//! Per-folder settings, a reqlite extension: `<folder>/.reqlite/folder.json`.
|
||||||
//!
|
//!
|
||||||
//! For now it only holds the folder's default auth, an `Authorization`
|
//! For now it only holds the folder's default auth, a header that requests
|
||||||
//! header value that requests in the folder (and its subfolders) use when
|
//! in the folder (and its subfolders) use when they don't set auth
|
||||||
//! they don't set one themselves:
|
//! themselves. A string is an `Authorization` header value; an object names
|
||||||
|
//! some other header:
|
||||||
//!
|
//!
|
||||||
//! ```json
|
//! ```json
|
||||||
//! { "auth": "Bearer {{token}}" }
|
//! { "auth": "Bearer {{token}}" }
|
||||||
|
//! { "auth": { "header": "X-API-Key", "value": "{{api_key}}" } }
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! `"auth": null` means "no auth" (it stops inheritance from parent
|
//! `"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";
|
pub const FILE: &str = "folder.json";
|
||||||
/// `# @no-auth`: the request sends no auth even if its folder has one.
|
/// `# @no-auth`: the request sends no auth even if its folder has one.
|
||||||
pub const NO_AUTH_DIRECTIVE: &str = "no-auth";
|
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)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum FolderError {
|
pub enum FolderError {
|
||||||
@@ -40,8 +93,8 @@ pub enum FolderAuth {
|
|||||||
Inherit,
|
Inherit,
|
||||||
/// No auth for this folder, whatever the parents say.
|
/// No auth for this folder, whatever the parents say.
|
||||||
None,
|
None,
|
||||||
/// An `Authorization` header value, e.g. `Bearer {{token}}`.
|
/// A header, e.g. `Authorization: Bearer {{token}}`.
|
||||||
Header(String),
|
Header(AuthHeader),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
@@ -69,7 +122,20 @@ impl FolderSettings {
|
|||||||
None => FolderAuth::Inherit,
|
None => FolderAuth::Inherit,
|
||||||
Some(Value::Null) => FolderAuth::None,
|
Some(Value::Null) => FolderAuth::None,
|
||||||
Some(Value::String(s)) if s.trim().is_empty() => 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(_) => {
|
Some(_) => {
|
||||||
return Err(FolderError::Shape {
|
return Err(FolderError::Shape {
|
||||||
path: path.to_path_buf(),
|
path: path.to_path_buf(),
|
||||||
@@ -86,8 +152,11 @@ impl FolderSettings {
|
|||||||
FolderAuth::None => {
|
FolderAuth::None => {
|
||||||
map.insert("auth".into(), Value::Null);
|
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) => {
|
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());
|
map.extend(self.other.clone());
|
||||||
@@ -127,8 +196,8 @@ pub fn settings_dir(path: &Path) -> Option<&Path> {
|
|||||||
pub struct InheritedAuth {
|
pub struct InheritedAuth {
|
||||||
/// The folder whose setting applies.
|
/// The folder whose setting applies.
|
||||||
pub from: PathBuf,
|
pub from: PathBuf,
|
||||||
/// The header value; `None` when that folder says "no auth".
|
/// The header; `None` when that folder says "no auth".
|
||||||
pub value: Option<String>,
|
pub value: Option<AuthHeader>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Walks from `dir` up to `root` (inclusive) and returns the first folder
|
/// 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.
|
/// How a request gets its auth.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum AuthMode {
|
pub enum AuthMode {
|
||||||
/// It has its own `Authorization` header.
|
/// It has its own auth header: `Authorization`, or the one named by
|
||||||
Own(String),
|
/// `# @auth-header`.
|
||||||
|
Own(AuthHeader),
|
||||||
/// `# @no-auth`.
|
/// `# @no-auth`.
|
||||||
NoAuth,
|
NoAuth,
|
||||||
/// From its folder.
|
/// From its folder.
|
||||||
@@ -205,29 +284,58 @@ pub enum AuthMode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn auth_mode(req: &Request) -> AuthMode {
|
pub fn auth_mode(req: &Request) -> AuthMode {
|
||||||
match req.header("authorization") {
|
let custom = auth_header_directive(req).and_then(|n| Some(AuthHeader::custom(n, req.header(n)?)));
|
||||||
Some(v) => AuthMode::Own(v.to_string()),
|
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 if has_no_auth(req) => AuthMode::NoAuth,
|
||||||
None => AuthMode::Inherit,
|
None => AuthMode::Inherit,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The request as it is sent: with the inherited `Authorization` header
|
/// Changes how the request gets its auth: drops its current auth header
|
||||||
/// added when it inherits one.
|
/// (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> {
|
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())) {
|
match (auth_mode(req), inherited.and_then(|i| i.value.as_ref())) {
|
||||||
(AuthMode::Inherit, Some(v)) => {
|
(AuthMode::Inherit, Some(h)) if h.is_authorization() || req.header(&h.name).is_none() => {
|
||||||
let mut r = req.clone();
|
let mut r = req.clone();
|
||||||
r.set_header("Authorization", v);
|
r.set_header(&h.name, h.value.as_str());
|
||||||
Cow::Owned(r)
|
Cow::Owned(r)
|
||||||
}
|
}
|
||||||
_ => Cow::Borrowed(req),
|
_ => Cow::Borrowed(req),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether two header values are the same auth (ignoring spacing).
|
/// Whether two headers are the same auth (ignoring the name's case and the
|
||||||
pub fn same_auth(a: &str, b: &str) -> bool {
|
/// value's spacing).
|
||||||
a.split_whitespace().eq(b.split_whitespace())
|
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)]
|
#[cfg(test)]
|
||||||
@@ -240,7 +348,7 @@ mod tests {
|
|||||||
fn parses_and_writes_back() {
|
fn parses_and_writes_back() {
|
||||||
let p = Path::new("f.json");
|
let p = Path::new("f.json");
|
||||||
let s = FolderSettings::parse(r#"{ "auth": "Bearer {{t}}", "x": 1 }"#, p).unwrap();
|
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_eq!(FolderSettings::parse(&s.to_json(), p).unwrap(), s);
|
||||||
assert!(s.to_json().contains("\"x\": 1"));
|
assert!(s.to_json().contains("\"x\": 1"));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -251,6 +359,12 @@ mod tests {
|
|||||||
assert!(FolderSettings::parse("{}", p).unwrap().is_empty());
|
assert!(FolderSettings::parse("{}", p).unwrap().is_empty());
|
||||||
assert!(FolderSettings::parse(r#"{"auth": 3}"#, p).is_err());
|
assert!(FolderSettings::parse(r#"{"auth": 3}"#, p).is_err());
|
||||||
assert!(FolderSettings::parse("[]", 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]
|
#[test]
|
||||||
@@ -266,7 +380,7 @@ mod tests {
|
|||||||
fn inherits_from_the_nearest_folder_within_the_root() {
|
fn inherits_from_the_nearest_folder_within_the_root() {
|
||||||
let mut m = BTreeMap::new();
|
let mut m = BTreeMap::new();
|
||||||
let hdr = |s: &str| FolderSettings {
|
let hdr = |s: &str| FolderSettings {
|
||||||
auth: FolderAuth::Header(s.into()),
|
auth: FolderAuth::Header(AuthHeader::authorization(s)),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
m.insert(PathBuf::from("/"), hdr("outside"));
|
m.insert(PathBuf::from("/"), hdr("outside"));
|
||||||
@@ -282,7 +396,10 @@ mod tests {
|
|||||||
let get = |p: &Path| m.get(p);
|
let get = |p: &Path| m.get(p);
|
||||||
let root = Path::new("/c");
|
let root = Path::new("/c");
|
||||||
let a = inherited_auth(root, Path::new("/c/api/v2"), get).unwrap();
|
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();
|
let a = inherited_auth(root, Path::new("/c/public/x"), get).unwrap();
|
||||||
assert_eq!(a.value, None);
|
assert_eq!(a.value, None);
|
||||||
assert_eq!(inherited_auth(Path::new("/d"), Path::new("/d/x"), get), 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();
|
let modes: Vec<_> = f.requests().map(auth_mode).collect();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
modes,
|
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 {
|
let inh = InheritedAuth {
|
||||||
from: "/c".into(),
|
from: "/c".into(),
|
||||||
value: Some("Bearer folder".into()),
|
value: Some(AuthHeader::authorization("Bearer folder")),
|
||||||
};
|
};
|
||||||
let sent: Vec<_> = f
|
let sent: Vec<_> = f
|
||||||
.requests()
|
.requests()
|
||||||
@@ -316,7 +437,59 @@ mod tests {
|
|||||||
let mut r = f.request(2).unwrap().clone();
|
let mut r = f.request(2).unwrap().clone();
|
||||||
set_no_auth(&mut r, true);
|
set_no_auth(&mut r, true);
|
||||||
assert!(f.replace_request(2, &r).unwrap().ends_with("###\n# @no-auth\nGET /c\n"));
|
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]
|
#[test]
|
||||||
@@ -328,13 +501,13 @@ mod tests {
|
|||||||
std::fs::create_dir_all(dir.path().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();
|
std::fs::write(settings_path(dir.path()), r#"{"auth": "Bearer outside"}"#).unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
inherited_auth_on_disk(&api).unwrap().unwrap().value.as_deref(),
|
inherited_auth_on_disk(&api).unwrap().unwrap().value,
|
||||||
Some("Bearer outside")
|
Some(AuthHeader::authorization("Bearer outside"))
|
||||||
);
|
);
|
||||||
std::fs::write(root.join(crate::env::PUBLIC_FILE), "{}").unwrap();
|
std::fs::write(root.join(crate::env::PUBLIC_FILE), "{}").unwrap();
|
||||||
assert_eq!(inherited_auth_on_disk(&api).unwrap(), None);
|
assert_eq!(inherited_auth_on_disk(&api).unwrap(), None);
|
||||||
std::fs::write(settings_path(&api), r#"{"auth": "Bearer api"}"#).unwrap();
|
std::fs::write(settings_path(&api), r#"{"auth": "Bearer api"}"#).unwrap();
|
||||||
let a = inherited_auth_on_disk(&api).unwrap().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