A0: review round 1 peer entry defaults and class strings
This commit is contained in:
1 parent
4bfb097be6
commit
0dbaf58c8c
10 files changed
+276
-32
No files matched your search
@@ -76,6 +76,8 @@ base64 = "0.23.1"
|
||||
[dev-dependencies]
|
||||
figment = { version = "0.10.19", features = ["test"] }
|
||||
rcgen = { version = "0.14", default-features = false, features = ["ring", "pem"] }
|
||||
# Pausable clock for tests. `full` does not include this, and the runtime build must not.
|
||||
tokio = { version = "1.53.3", features = ["test-util"] }
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
|
||||
@@ -48,6 +48,7 @@ Unit tests for validation and loader; a peer-less default config is byte-identic
|
||||
- A0 merged: C, D, E, B compile against the stubs; post in all their Logs.
|
||||
- `PeersConfig`/`PeerConfig`, the secrets loader (`Secret`, `load_token(&PeerConfig) -> Result<Secret, PeerError>`) and `config.example.toml` `[peers]` block for B and F.
|
||||
- The `peer` subcommand for the docs (F4).
|
||||
- 2026-10-19 (review round 1): `[[peers.peer]]` deserializes with `enabled` defaulting to true and `allow_plain_http` / `ca_file` optional, so the VM entry shape loads. `PeerRegistry::reload` returns `PeerConfigError` (alias of `config::ConfigError`). `class_str` no longer copies a peer's `BadRequest` text into `last_error`.
|
||||
|
||||
## Log
|
||||
|
||||
@@ -57,3 +58,15 @@ Unit tests for validation and loader; a peer-less default config is byte-identic
|
||||
- Contract discrepancy: section 3 declares `reload(&self, new: PeersConfig) -> Result<(), PeerConfigError>` but no `PeerConfigError` type exists in the contract or the tree. Implemented as `Result<(), crate::config::ConfigError>` (the existing error for invalid configuration). Please fix the name in contracts.md if that is not the intent.
|
||||
- `Cargo.toml`: added `url` (needed for the contract's `url::Url` field, already in `Cargo.lock` via reqwest) and `bytes` (contract's `Bytes` body type, already in the lock). `cargo tree -i openssl` still empty.
|
||||
- Logged in WS-C, WS-D and WS-E: stubs are available, compile against them.
|
||||
- 2026-10-19 A0 review round 1: addressed `loop/A0/review-1.md`.
|
||||
- Blocking: `PeerConfig` field defaults. `enabled` defaults to true, `allow_plain_http` to false, and `ca_file` may be omitted (the VM entry lists it as optional; without a default, beta's entry fails the same way `enabled` did). `Config::load` of that shape is `vm_peer_entries_load_when_enabled_and_ca_file_are_omitted` in `tests/peers_config.rs`; a toml parse of the same omission sits next to the type.
|
||||
- `proxy.rs` module comment now says the allowlist, `..` / encoded-slash rejection and the query allowlist belong in that module and are not implemented yet. REST and MCP still share `proxy::get`.
|
||||
- `reload` returns `peers::PeerConfigError`, a public alias of `config::ConfigError`. contracts.md already names that type, so it was not edited (not an owned file, and the name there is already the one the review asked the code to match). The earlier log line asking for a contracts.md rename is superseded by this alias.
|
||||
- `PeerError::class_str` returns the fixed token `bad_request` for `BadRequest`. The peer's message stays only in `peer_error_to_app` (D9). `check_once` stores `class_str()` in `last_error`, covered by `bad_request_last_error_is_a_class_string`.
|
||||
- `status` and `contains` parse the name and use `BTreeMap::get`; an unparseable name is an unknown peer. `get` parses and compares `PeerName` against `config.peer`. That field stays a `Vec` (serde order, contract section 1), so it is not a second map; a key compare is the lookup `.get` would do.
|
||||
- `FakeTransport` delay is asserted with a paused clock (`per_peer_isolation_and_delay`). That needs tokio's `test-util` feature, added as a dev-dependency only (`full` does not include it, and `cargo build` does not turn it on). `/api/v1/ping` without a bearer token is 401 on `server::build_router`, and 200 with one (`ping_without_a_token_is_unauthorized`). The handler's exact version assertion stays in `src/api/ping.rs`. `tests/integration.rs` was not edited: it is outside the owned files, and finding 7 allows this test to carry the 401 case.
|
||||
- `check_once` still leaves API `latency_ms` unset. A comment says the probe that replaces the stub is what measures it for `peer check`.
|
||||
- For WS-C: when `peers::routes()` is filled, assert `GET /api/v1/peers` is 404 when `state.peers` is `None`. The merge in `api/mod.rs` cannot be observed while `routes()` is empty, so no test was added here.
|
||||
- Not changed, on purpose:
|
||||
- `TODO.md` A0 box stays unticked. This round says the merger ticks it, and `TODO.md` is not an owned file. AGENTS.md's definition-of-done item 4 is the merger's step.
|
||||
- The direct `bytes` dependency stays. The body type in the transport contract is `bytes::Bytes`; axum only re-exports the same crate. Dropping the direct dep would not change the graph, and the 2026-10-19 log already records why it was added.
|
||||
+27
-2
@@ -6,6 +6,11 @@
|
||||
use crate::error::AppError;
|
||||
use crate::peers::types::{CheckClass, PeerName};
|
||||
|
||||
/// What [`crate::peers::registry::PeerRegistry::reload`] returns.
|
||||
///
|
||||
/// Same error as startup configuration, so a bad reload uses that wording.
|
||||
pub type PeerConfigError = crate::config::ConfigError;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum PeerError {
|
||||
/// Peer answered 401/403: our credential was refused.
|
||||
@@ -45,12 +50,15 @@ impl PeerError {
|
||||
}
|
||||
}
|
||||
|
||||
/// Short, secret-free class string used in status errors and messages.
|
||||
/// Fixed class token for status fields such as `last_error`.
|
||||
///
|
||||
/// A `BadRequest` payload is the peer's own text, so it stays out of
|
||||
/// this string. Callers that should see it use [`peer_error_to_app`].
|
||||
pub fn class_str(&self) -> String {
|
||||
match self {
|
||||
Self::Rejected => "unauthorized".into(),
|
||||
Self::NotFound => "not_found".into(),
|
||||
Self::BadRequest(m) => m.clone(),
|
||||
Self::BadRequest(_) => "bad_request".into(),
|
||||
Self::Http(code) => format!("http_{code}"),
|
||||
Self::Timeout => "timeout".into(),
|
||||
Self::Unreachable => "unreachable".into(),
|
||||
@@ -156,6 +164,23 @@ mod tests {
|
||||
assert!(!app.message().contains("/run/credentials"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_request_class_string_drops_the_peer_message() {
|
||||
let msg = "http://peer.example/path?token=abc";
|
||||
let err = PeerError::BadRequest(msg.into());
|
||||
assert_eq!(err.class_str(), "bad_request");
|
||||
assert!(!err.class_str().contains("http://"));
|
||||
assert!(!err.class_str().contains("token"));
|
||||
let app = peer_error_to_app(&name(), &err);
|
||||
assert_eq!(app.message(), format!("peer beta: {msg}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_config_error_is_the_process_config_error() {
|
||||
let err: PeerConfigError = crate::config::ConfigError::Invalid("peers".into());
|
||||
assert!(matches!(err, crate::config::ConfigError::Invalid(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coarse_class() {
|
||||
assert_eq!(PeerError::Rejected.class(), CheckClass::Unauthorized);
|
||||
|
||||
@@ -66,6 +66,8 @@ pub async fn check_once(
|
||||
headers: Vec::new(),
|
||||
accept: None,
|
||||
};
|
||||
// The GET is not timed, so `latency_ms` stays empty. The probe that
|
||||
// replaces this stub measures it; `peer check` prints that value.
|
||||
let api = match transport.get(peer, req, api_timeout).await {
|
||||
Ok(resp) if (200..300).contains(&resp.status) => ApiStatus {
|
||||
up: true,
|
||||
@@ -161,4 +163,24 @@ mod tests {
|
||||
assert!(!api.up);
|
||||
assert_eq!(api.auth, AuthState::Unknown);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bad_request_last_error_is_a_class_string() {
|
||||
let leaked = "http://10.1.2.3/path?token=abc";
|
||||
let fake = FakeTransport::new();
|
||||
fake.peer("beta")
|
||||
.respond_err("/api/v1/ping", PeerError::BadRequest(leaked.into()));
|
||||
let cfg = fake_peers_config(&["beta"]);
|
||||
let (_, api) = check_once(
|
||||
fake.as_ref(),
|
||||
&cfg.peer[0],
|
||||
Duration::from_secs(1),
|
||||
Duration::from_secs(1),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(api.last_error.as_deref(), Some("bad_request"));
|
||||
let stored = api.last_error.unwrap();
|
||||
assert!(!stored.contains("token"));
|
||||
assert!(!stored.contains("http://"));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -12,6 +12,6 @@ pub mod testing;
|
||||
pub mod transport;
|
||||
pub mod types;
|
||||
|
||||
pub use error::PeerError;
|
||||
pub use error::{PeerConfigError, PeerError};
|
||||
pub use registry::{PeerRegistry, ProxyOpts};
|
||||
pub use types::{PeerConfig, PeerName, PeerStatus, PeersConfig, Secret};
|
||||
+5
-3
@@ -1,8 +1,10 @@
|
||||
//! Proxy one GET to a peer.
|
||||
//!
|
||||
//! Path and query allowlists and caller header checks happen in the REST
|
||||
//! layer; this layer builds the outbound request and maps peer failures. It
|
||||
//! never forwards caller credentials.
|
||||
//! The path allowlist, rejection of `..` and encoded slashes, and the query
|
||||
//! allowlist belong in this module. They are not implemented yet: this stub
|
||||
//! forwards the request and maps peer failures. REST and MCP share this
|
||||
//! function, so those checks must not grow a second copy. Caller credentials
|
||||
//! are never forwarded.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
|
||||
+25
-15
@@ -5,8 +5,8 @@ use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::config::ConfigError;
|
||||
use crate::error::AppError;
|
||||
use crate::peers::error::PeerConfigError;
|
||||
use crate::peers::transport::{PeerResponse, PeerTransport};
|
||||
use crate::peers::types::{ApiStatus, PeerConfig, PeerName, PeerStatus, PeersConfig, ServerStatus};
|
||||
|
||||
@@ -82,19 +82,21 @@ impl PeerRegistry {
|
||||
}
|
||||
|
||||
pub fn status(&self, name: &str) -> Result<PeerStatus, AppError> {
|
||||
let Ok(key) = PeerName::parse(name) else {
|
||||
return Err(AppError::NotFound(format!("peer {name}: unknown peer")));
|
||||
};
|
||||
lock_read(&self.state)
|
||||
.statuses
|
||||
.values()
|
||||
.find(|s| s.name.as_str() == name)
|
||||
.get(&key)
|
||||
.cloned()
|
||||
.ok_or_else(|| AppError::NotFound(format!("peer {name}: unknown peer")))
|
||||
}
|
||||
|
||||
pub fn contains(&self, name: &str) -> bool {
|
||||
lock_read(&self.state)
|
||||
.statuses
|
||||
.keys()
|
||||
.any(|n| n.as_str() == name)
|
||||
let Ok(key) = PeerName::parse(name) else {
|
||||
return false;
|
||||
};
|
||||
lock_read(&self.state).statuses.contains_key(&key)
|
||||
}
|
||||
|
||||
pub fn config(&self) -> Arc<PeersConfig> {
|
||||
@@ -109,14 +111,10 @@ impl PeerRegistry {
|
||||
query: &[(String, String)],
|
||||
opts: ProxyOpts,
|
||||
) -> Result<PeerResponse, AppError> {
|
||||
let key = PeerName::parse(name).ok();
|
||||
let (peer, timeout) = {
|
||||
let st = lock_read(&self.state);
|
||||
let peer = st
|
||||
.config
|
||||
.peer
|
||||
.iter()
|
||||
.find(|p| p.name.as_str() == name)
|
||||
.cloned();
|
||||
let peer = key.and_then(|key| st.config.peer.iter().find(|p| p.name == key).cloned());
|
||||
(peer, Duration::from_secs(st.config.request_timeout_secs))
|
||||
};
|
||||
let peer = peer.ok_or_else(|| AppError::NotFound(format!("peer {name}: unknown peer")))?;
|
||||
@@ -126,7 +124,7 @@ impl PeerRegistry {
|
||||
/// Replace the peer set. Statuses of peers that survive a reload are kept
|
||||
/// so `since` survives a config change. Validation arrives with the
|
||||
/// config and secrets tasks; this body only swaps state.
|
||||
pub async fn reload(&self, new: PeersConfig) -> Result<(), ConfigError> {
|
||||
pub async fn reload(&self, new: PeersConfig) -> Result<(), PeerConfigError> {
|
||||
let mut st = lock_write(&self.state);
|
||||
let old = std::mem::take(&mut st.statuses);
|
||||
st.statuses = new
|
||||
@@ -191,6 +189,11 @@ mod tests {
|
||||
assert_eq!(err.message(), "peer nope: unknown peer");
|
||||
assert!(reg.contains("beta"));
|
||||
assert!(!reg.contains("nope"));
|
||||
assert!(!reg.contains("Beta"));
|
||||
assert!(!reg.contains("-beta"));
|
||||
let err = reg.status("Beta").unwrap_err();
|
||||
assert_eq!(err.code(), "not_found");
|
||||
assert_eq!(err.message(), "peer Beta: unknown peer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -226,6 +229,12 @@ mod tests {
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "not_found");
|
||||
assert_eq!(err.message(), "peer nope: unknown peer");
|
||||
|
||||
let err = reg
|
||||
.get("Beta", "/x", &[], ProxyOpts::default())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.message(), "peer Beta: unknown peer");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -241,7 +250,8 @@ mod tests {
|
||||
}
|
||||
let mut new = fake_peers_config(&["beta", "delta"]);
|
||||
new.peer[0].enabled = false;
|
||||
reg.reload(new).await.unwrap();
|
||||
let reloaded: Result<(), PeerConfigError> = reg.reload(new).await;
|
||||
reloaded.unwrap();
|
||||
|
||||
let snap = reg.snapshot();
|
||||
assert_eq!(snap.len(), 2);
|
||||
|
||||
+12
-2
@@ -400,7 +400,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn per_peer_isolation_and_delay() {
|
||||
let fake = FakeTransport::new();
|
||||
fake.peer("beta")
|
||||
@@ -419,15 +419,25 @@ mod tests {
|
||||
headers: vec![],
|
||||
accept: None,
|
||||
};
|
||||
let started = tokio::time::Instant::now();
|
||||
assert!(matches!(
|
||||
fake.get(beta, get(), Duration::from_secs(1)).await,
|
||||
Err(PeerError::Rejected)
|
||||
));
|
||||
// gamma keeps the default 404.
|
||||
assert!(started.elapsed() >= Duration::from_millis(5));
|
||||
|
||||
let started = tokio::time::Instant::now();
|
||||
let latency = fake.tcp_check(beta, Duration::from_secs(1)).await.unwrap();
|
||||
assert_eq!(latency, Duration::from_millis(1));
|
||||
assert!(started.elapsed() >= Duration::from_millis(5));
|
||||
|
||||
// gamma keeps the default 404 and is not delayed.
|
||||
let started = tokio::time::Instant::now();
|
||||
let r = fake
|
||||
.get(gamma, get(), Duration::from_secs(1))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.status, 404);
|
||||
assert_eq!(started.elapsed(), Duration::ZERO);
|
||||
}
|
||||
}
|
||||
@@ -87,15 +87,25 @@ impl fmt::Display for Secret {
|
||||
}
|
||||
}
|
||||
|
||||
fn peer_enabled_default() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// One validated `[[peers.peer]]` entry. The token itself is not held here;
|
||||
/// only the path of the externally managed file.
|
||||
///
|
||||
/// `enabled` defaults to true, `allow_plain_http` to false, and `ca_file`
|
||||
/// may be omitted: entries often carry only `name`, `url` and `token_file`.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PeerConfig {
|
||||
pub name: PeerName,
|
||||
pub url: Url,
|
||||
pub token_file: PathBuf,
|
||||
#[serde(default)]
|
||||
pub ca_file: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
pub allow_plain_http: bool,
|
||||
#[serde(default = "peer_enabled_default")]
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
@@ -280,6 +290,32 @@ mod tests {
|
||||
assert_eq!(c.tcp_interval_secs, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_entry_omits_optional_keys() {
|
||||
let c: PeersConfig = toml::from_str(
|
||||
r#"
|
||||
[[peer]]
|
||||
name = "beta"
|
||||
url = "http://beta:1984"
|
||||
token_file = "/run/credentials/skyg-linux-tracker.service/peer-beta"
|
||||
allow_plain_http = true
|
||||
|
||||
[[peer]]
|
||||
name = "delta"
|
||||
url = "https://delta:1984"
|
||||
token_file = "/run/credentials/skyg-linux-tracker.service/peer-delta"
|
||||
enabled = false
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(c.peer[0].enabled);
|
||||
assert!(c.peer[0].allow_plain_http);
|
||||
assert!(c.peer[0].ca_file.is_none());
|
||||
assert!(!c.peer[1].enabled);
|
||||
assert!(!c.peer[1].allow_plain_http);
|
||||
assert!(c.peer[1].ca_file.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_url_drops_normalized_root_path() {
|
||||
assert_eq!(
|
||||
|
||||
+133
-9
@@ -1,12 +1,15 @@
|
||||
//! Peer seams exercised end to end against the fake transport and fake
|
||||
//! sources: the peer-less default, the ping route, and registry reads.
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::body::{to_bytes, Body};
|
||||
use axum::http::{Request, StatusCode};
|
||||
use figment::Jail;
|
||||
use skyg_linux_tracker::api;
|
||||
use skyg_linux_tracker::config::Config;
|
||||
use skyg_linux_tracker::config::{CliOverrides, Config};
|
||||
use skyg_linux_tracker::peers::testing::{
|
||||
fake_peers_config, fake_state_with_peers, registry_with, static_registry, FakeTransport,
|
||||
};
|
||||
@@ -51,16 +54,137 @@ async fn peerless_default_is_off_and_unchanged() {
|
||||
assert!(!b.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(clippy::result_large_err)] // figment::Jail closures return figment::Error
|
||||
fn vm_peer_entries_load_when_enabled_and_ca_file_are_omitted() {
|
||||
Jail::expect_with(|jail| {
|
||||
jail.create_file(
|
||||
"peers.toml",
|
||||
r#"
|
||||
[server]
|
||||
bind = "0.0.0.0"
|
||||
|
||||
[peers]
|
||||
enabled = true
|
||||
tcp_interval_secs = 2
|
||||
tcp_timeout_secs = 1
|
||||
api_interval_secs = 3
|
||||
api_timeout_secs = 2
|
||||
fail_threshold = 2
|
||||
request_timeout_secs = 4
|
||||
|
||||
[[peers.peer]]
|
||||
name = "beta"
|
||||
url = "http://beta:1984"
|
||||
token_file = "/run/credentials/skyg-linux-tracker.service/peer-beta"
|
||||
allow_plain_http = true
|
||||
|
||||
[[peers.peer]]
|
||||
name = "gamma"
|
||||
url = "https://gamma:1984"
|
||||
token_file = "/run/credentials/skyg-linux-tracker.service/peer-gamma"
|
||||
ca_file = "/etc/ssl/private-ca.pem"
|
||||
allow_plain_http = false
|
||||
|
||||
[[peers.peer]]
|
||||
name = "delta"
|
||||
url = "https://delta:1984"
|
||||
token_file = "/run/credentials/skyg-linux-tracker.service/peer-delta"
|
||||
enabled = false
|
||||
"#,
|
||||
)?;
|
||||
let cfg = Config::load(Some(Path::new("peers.toml")), &CliOverrides::default())
|
||||
.expect("peer entries must deserialize");
|
||||
assert!(cfg.auth.enabled);
|
||||
assert_eq!(cfg.server.bind, IpAddr::V4(Ipv4Addr::UNSPECIFIED));
|
||||
assert!(cfg.peers.enabled);
|
||||
assert_eq!(cfg.peers.tcp_interval_secs, 2);
|
||||
assert_eq!(cfg.peers.api_timeout_secs, 2);
|
||||
assert_eq!(cfg.peers.request_timeout_secs, 4);
|
||||
assert_eq!(cfg.peers.max_response_bytes, 8 * 1024 * 1024);
|
||||
|
||||
let peer = |name: &str| {
|
||||
cfg.peers
|
||||
.peer
|
||||
.iter()
|
||||
.find(|p| p.name.as_str() == name)
|
||||
.unwrap()
|
||||
};
|
||||
let beta = peer("beta");
|
||||
assert!(beta.enabled);
|
||||
assert!(beta.allow_plain_http);
|
||||
assert!(beta.ca_file.is_none());
|
||||
assert_eq!(
|
||||
beta.token_file,
|
||||
PathBuf::from("/run/credentials/skyg-linux-tracker.service/peer-beta")
|
||||
);
|
||||
let gamma = peer("gamma");
|
||||
assert!(gamma.enabled);
|
||||
assert!(!gamma.allow_plain_http);
|
||||
assert_eq!(
|
||||
gamma.ca_file.as_deref(),
|
||||
Some(Path::new("/etc/ssl/private-ca.pem"))
|
||||
);
|
||||
let delta = peer("delta");
|
||||
assert!(!delta.enabled);
|
||||
assert!(!delta.allow_plain_http);
|
||||
assert!(delta.ca_file.is_none());
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ping_route_is_present_without_peers() {
|
||||
let app = api::router(skyg_linux_tracker::sources::fake::fake_state(
|
||||
Config::default(),
|
||||
));
|
||||
let (s, b) = get(&app, "/ping").await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
let v: serde_json::Value = serde_json::from_str(&b).unwrap();
|
||||
async fn ping_without_a_token_is_unauthorized() {
|
||||
let pool = sqlx::sqlite::SqlitePoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect("sqlite::memory:")
|
||||
.await
|
||||
.unwrap();
|
||||
skyg_linux_tracker::db::migrate(&pool).await.unwrap();
|
||||
let token = skyg_linux_tracker::auth::tokens::create(&pool, "ping")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut config = Config::default();
|
||||
config.auth.enabled = true;
|
||||
let mut state = skyg_linux_tracker::sources::fake::fake_state(config);
|
||||
state.db = Some(pool);
|
||||
let app = skyg_linux_tracker::server::build_router(state);
|
||||
|
||||
let (status, body, www) = request(&app, "/api/v1/ping", None).await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(www.as_deref(), Some("Bearer"));
|
||||
assert!(body.contains("unauthorized"));
|
||||
|
||||
let (status, body, _) = request(&app, "/api/v1/ping", Some(&format!("Bearer {token}"))).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let v: serde_json::Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(v["status"], "ok");
|
||||
assert!(v["version"].is_string());
|
||||
assert!(v["version"].as_str().is_some_and(|s| !s.is_empty()));
|
||||
}
|
||||
|
||||
async fn request(
|
||||
app: &axum::Router,
|
||||
uri: &str,
|
||||
authorization: Option<&str>,
|
||||
) -> (StatusCode, String, Option<String>) {
|
||||
let mut builder = Request::builder().uri(uri);
|
||||
if let Some(auth) = authorization {
|
||||
builder = builder.header("authorization", auth);
|
||||
}
|
||||
let resp = app
|
||||
.clone()
|
||||
.oneshot(builder.body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let status = resp.status();
|
||||
let www = resp
|
||||
.headers()
|
||||
.get(axum::http::header::WWW_AUTHENTICATE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::to_owned);
|
||||
let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
|
||||
(status, String::from_utf8(body.to_vec()).unwrap(), www)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
Reference in new issue
Block a user