H: merge token loaders and peer helpers One loader in secrets.rs (header validity, canonicalised credentials dir) is used by the client; the deny-CIDR parser, loopback test and plain-http warning live once in config.rs
This commit is contained in:
1 parent
c478bef930
commit
39c1c91695
6 files changed
+178
-178
No files matched your search
+54
-139
@@ -7,7 +7,7 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll};
|
||||
@@ -25,11 +25,11 @@ use rustls::{ClientConfig, RootCertStore};
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
||||
|
||||
use crate::config::ConfigError;
|
||||
use crate::peers::config::{denied, deny_networks, plain_http_allowed, plain_http_off_loopback};
|
||||
use crate::peers::error::{PeerConfigError, PeerError};
|
||||
use crate::peers::secrets::load_token;
|
||||
use crate::peers::transport::{PeerBody, PeerRequest, PeerResponse, PeerTransport};
|
||||
use crate::peers::types::{PeerConfig, PeerName, PeersConfig, Secret};
|
||||
|
||||
const MAX_TOKEN_BYTES: u64 = 4096;
|
||||
use crate::peers::types::{PeerConfig, PeerName, PeersConfig};
|
||||
|
||||
/// Paths the health loops probe. They skip the concurrency limits: a held
|
||||
/// follow stream must not make a healthy peer look saturated and down.
|
||||
@@ -41,17 +41,6 @@ const HEALTHZ_PATH: &str = "/healthz";
|
||||
/// so this only catches a connection that stopped without closing.
|
||||
const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
/// Parse the deny list once, so startup and reload reject the same values.
|
||||
pub(crate) fn deny_networks(list: &[String]) -> Result<Vec<IpNet>, PeerConfigError> {
|
||||
list.iter()
|
||||
.map(|s| {
|
||||
s.parse::<IpNet>().map_err(|_| {
|
||||
ConfigError::Invalid(format!("peers.deny_cidrs entry {s:?} is not a CIDR"))
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct Limits {
|
||||
global: Arc<Semaphore>,
|
||||
per_peer_n: usize,
|
||||
@@ -173,31 +162,19 @@ impl ReqwestTransport {
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
/// The request happens on every check and proxy call, so the warning is
|
||||
/// repeated once per peer rather than once per request.
|
||||
fn warn_plain_http(&self, peer: &PeerConfig) {
|
||||
if peer.url.scheme() != "http" || url_is_loopback(&peer.url) {
|
||||
if !plain_http_off_loopback(peer) {
|
||||
return;
|
||||
}
|
||||
let mut seen = Self::lock(&self.plain_warned);
|
||||
if seen.insert(peer.name.clone()) {
|
||||
tracing::warn!(
|
||||
peer = %peer.name,
|
||||
"plain HTTP to a non-loopback peer; the bearer token travels in clear"
|
||||
);
|
||||
crate::peers::config::warn_plain_http(peer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The URL parser already knows the host kind: an IPv6 literal is
|
||||
/// `Host::Ipv6`, never the bracketed string `host_str()` renders.
|
||||
fn url_is_loopback(url: &url::Url) -> bool {
|
||||
match url.host() {
|
||||
Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
|
||||
Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
|
||||
Some(url::Host::Domain(name)) => name.eq_ignore_ascii_case("localhost"),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rules that must hold before resolving anything. The same rules are
|
||||
/// enforced when the config is validated; repeating them here keeps the
|
||||
/// transport safe when it is built from an unvalidated `PeersConfig`.
|
||||
@@ -211,16 +188,12 @@ fn validate_target(peer: &PeerConfig) -> Result<(), PeerError> {
|
||||
if peer.url.query().is_some() || peer.url.fragment().is_some() {
|
||||
return Err(PeerError::Unreachable);
|
||||
}
|
||||
if peer.url.scheme() == "http" && !url_is_loopback(&peer.url) && !peer.allow_plain_http {
|
||||
if !plain_http_allowed(peer) {
|
||||
return Err(PeerError::Unreachable);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn denied(ip: IpAddr, deny: &[IpNet]) -> bool {
|
||||
deny.iter().any(|net| net.contains(&ip))
|
||||
}
|
||||
|
||||
/// Resolve the peer host and reject denied addresses before any connection is
|
||||
/// made. Every address is returned so a peer that listens on one family is not
|
||||
/// reported as down when its name also resolves to the other; the set is
|
||||
@@ -332,58 +305,6 @@ fn request_url(peer: &PeerConfig, req: &PeerRequest) -> Result<url::Url, PeerErr
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
fn load_token(path: &Path) -> Result<Secret, PeerError> {
|
||||
let creds = std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from);
|
||||
load_token_in(path, creds.as_deref())
|
||||
}
|
||||
|
||||
fn load_token_in(path: &Path, credentials_dir: Option<&Path>) -> Result<Secret, PeerError> {
|
||||
let meta = std::fs::metadata(path).map_err(|_| PeerError::TokenFile("missing".into()))?;
|
||||
if !meta.is_file() {
|
||||
return Err(PeerError::TokenFile("not a file".into()));
|
||||
}
|
||||
if meta.len() > MAX_TOKEN_BYTES {
|
||||
return Err(PeerError::TokenFile("too large".into()));
|
||||
}
|
||||
if !under_credentials(path, credentials_dir) {
|
||||
let mode = {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
meta.permissions().mode()
|
||||
};
|
||||
if mode & 0o077 != 0 {
|
||||
return Err(PeerError::TokenFile("group or world readable".into()));
|
||||
}
|
||||
}
|
||||
let mut bytes = std::fs::read(path).map_err(|_| PeerError::TokenFile("unreadable".into()))?;
|
||||
if bytes.len() as u64 > MAX_TOKEN_BYTES {
|
||||
return Err(PeerError::TokenFile("too large".into()));
|
||||
}
|
||||
if bytes.last() == Some(&b'\n') {
|
||||
bytes.pop();
|
||||
if bytes.last() == Some(&b'\r') {
|
||||
bytes.pop();
|
||||
}
|
||||
}
|
||||
if bytes.is_empty() {
|
||||
return Err(PeerError::TokenFile("empty".into()));
|
||||
}
|
||||
if bytes.iter().any(|b| *b == b'\n' || *b == b'\r' || *b == 0) {
|
||||
return Err(PeerError::TokenFile("invalid".into()));
|
||||
}
|
||||
let text = String::from_utf8(bytes).map_err(|_| PeerError::TokenFile("invalid".into()))?;
|
||||
if HeaderValue::from_str(&format!("Bearer {text}")).is_err() {
|
||||
return Err(PeerError::TokenFile("invalid".into()));
|
||||
}
|
||||
Ok(Secret::new(text))
|
||||
}
|
||||
|
||||
fn under_credentials(path: &Path, credentials_dir: Option<&Path>) -> bool {
|
||||
match credentials_dir {
|
||||
Some(dir) if !dir.as_os_str().is_empty() => path.starts_with(dir),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_io(err: std::io::Error) -> PeerError {
|
||||
if err.kind() == std::io::ErrorKind::TimedOut {
|
||||
return PeerError::Timeout;
|
||||
@@ -580,8 +501,8 @@ impl PeerTransport for ReqwestTransport {
|
||||
let deny = self.deny_list();
|
||||
let (pin, addrs) = resolve_target(peer, &deny).await?;
|
||||
self.warn_plain_http(peer);
|
||||
let token_path = peer.token_file.clone();
|
||||
let secret = tokio::task::spawn_blocking(move || load_token(&token_path))
|
||||
let owned = peer.clone();
|
||||
let secret = tokio::task::spawn_blocking(move || load_token(&owned))
|
||||
.await
|
||||
.map_err(|_| PeerError::TokenFile("unreadable".into()))??;
|
||||
let ca_path = peer.ca_file.clone();
|
||||
@@ -664,6 +585,7 @@ mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use axum::http::HeaderValue as Hv;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
@@ -745,46 +667,49 @@ mod tests {
|
||||
port
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_file_rules() {
|
||||
let ok = write_token("abc\n", 0o600);
|
||||
let secret = load_token_in(&ok, None).unwrap();
|
||||
assert_eq!(secret.expose(), "abc");
|
||||
assert!(!format!("{secret:?}").contains("abc"));
|
||||
let _ = std::fs::remove_file(&ok);
|
||||
|
||||
let crlf = write_token("abc\r\n", 0o600);
|
||||
assert_eq!(load_token_in(&crlf, None).unwrap().expose(), "abc");
|
||||
let _ = std::fs::remove_file(&crlf);
|
||||
|
||||
// One trailing newline is stripped. A second one would land in the
|
||||
// header, so the file is rejected rather than forwarded.
|
||||
let doubled = write_token("abc\n\n", 0o600);
|
||||
assert!(load_token_in(&doubled, None).is_err());
|
||||
let _ = std::fs::remove_file(&doubled);
|
||||
|
||||
for (body, mode) in [("\n", 0o600), ("", 0o600), ("x", 0o644), ("x", 0o640)] {
|
||||
let path = write_token(body, mode);
|
||||
assert!(load_token_in(&path, None).is_err(), "{body:?} {mode:o}");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
/// The client has no loader of its own: a token file the shared loader
|
||||
/// refuses is a `TokenFile` error and never reaches the wire.
|
||||
#[tokio::test]
|
||||
async fn a_refused_token_file_sends_nothing() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let asked = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let seen = Arc::clone(&asked);
|
||||
tokio::spawn(async move {
|
||||
if tokio::time::timeout(Duration::from_millis(500), listener.accept())
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
seen.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
});
|
||||
let transport = ReqwestTransport::new(&limits(4, 8, 1024)).unwrap();
|
||||
for (body, mode) in [
|
||||
("ok-token\r\nsmuggled: 1\n", 0o600),
|
||||
("ok-token\0", 0o600),
|
||||
("ok-token\n", 0o644),
|
||||
("", 0o600),
|
||||
] {
|
||||
let token = write_token(body, mode);
|
||||
let err = transport
|
||||
.get(
|
||||
&peer(port, &token, None),
|
||||
req("/api/v1/ping"),
|
||||
Duration::from_secs(2),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, PeerError::TokenFile(_)),
|
||||
"{body:?} {mode:o}: {err:?}"
|
||||
);
|
||||
assert!(!format!("{err:?}").contains("ok-token"));
|
||||
let _ = std::fs::remove_file(&token);
|
||||
}
|
||||
|
||||
let big = write_token(&"a".repeat(4097), 0o600);
|
||||
assert!(matches!(
|
||||
load_token_in(&big, None),
|
||||
Err(PeerError::TokenFile(_))
|
||||
));
|
||||
let _ = std::fs::remove_file(&big);
|
||||
|
||||
let loose = write_token("secret-value\n", 0o644);
|
||||
let dir = loose.parent().unwrap();
|
||||
assert!(load_token_in(&loose, Some(dir)).is_ok());
|
||||
let err = load_token_in(&loose, None).unwrap_err();
|
||||
assert!(matches!(err, PeerError::TokenFile(_)));
|
||||
assert!(!format!("{err:?}").contains("secret-value"));
|
||||
let _ = std::fs::remove_file(&loose);
|
||||
|
||||
assert!(load_token_in(Path::new("/no/such/token"), None).is_err());
|
||||
assert!(
|
||||
!asked.load(std::sync::atomic::Ordering::SeqCst),
|
||||
"a peer was contacted without a usable token"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1175,16 +1100,6 @@ mod tests {
|
||||
url::Url::parse(s).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_hosts_as_the_url_parser_reports_them() {
|
||||
assert!(url_is_loopback(&url("http://127.0.0.1:9")));
|
||||
assert!(url_is_loopback(&url("http://[::1]:9")));
|
||||
assert!(url_is_loopback(&url("http://localhost:9")));
|
||||
assert!(url_is_loopback(&url("http://LOCALHOST:9")));
|
||||
assert!(!url_is_loopback(&url("http://10.0.0.1:9")));
|
||||
assert!(!url_is_loopback(&url("http://beta:9")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ipv6_plain_http_to_loopback_needs_no_opt_in() {
|
||||
let mut p = peer(9, Path::new("/tmp/does-not-matter"), None);
|
||||
|
||||
+73
-27
@@ -19,7 +19,7 @@ use crate::peers::types::{PeerConfig, PeersConfig, MAX_PEERS};
|
||||
pub fn validate(cfg: &PeersConfig) -> Result<(), ConfigError> {
|
||||
timeout_below("tcp", cfg.tcp_timeout_secs, cfg.tcp_interval_secs)?;
|
||||
timeout_below("api", cfg.api_timeout_secs, cfg.api_interval_secs)?;
|
||||
let deny = parse_deny(&cfg.deny_cidrs)?;
|
||||
let deny = deny_networks(&cfg.deny_cidrs)?;
|
||||
if cfg.peer.len() > MAX_PEERS {
|
||||
return Err(ConfigError::Invalid(format!(
|
||||
"at most {MAX_PEERS} peers may be configured (got {})",
|
||||
@@ -75,17 +75,58 @@ fn timeout_below(kind: &str, timeout: u64, interval: u64) -> Result<(), ConfigEr
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_deny(cidrs: &[String]) -> Result<Vec<IpNet>, ConfigError> {
|
||||
/// Parse the deny list. Config validation and the transport both call this,
|
||||
/// so startup and reload reject exactly the same values.
|
||||
pub(crate) fn deny_networks(cidrs: &[String]) -> Result<Vec<IpNet>, ConfigError> {
|
||||
cidrs
|
||||
.iter()
|
||||
.map(|cidr| {
|
||||
cidr.parse::<IpNet>().map_err(|err| {
|
||||
ConfigError::Invalid(format!("deny_cidrs entry {cidr:?} is not a CIDR ({err})"))
|
||||
ConfigError::Invalid(format!(
|
||||
"peers.deny_cidrs entry {cidr:?} is not a CIDR ({err})"
|
||||
))
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Is `ip` inside the deny list? An IPv4-mapped IPv6 address is canonicalised
|
||||
/// first, so `::ffff:169.254.169.254` matches the IPv4 metadata range.
|
||||
pub(crate) fn denied(ip: IpAddr, deny: &[IpNet]) -> bool {
|
||||
let ip = ip.to_canonical();
|
||||
deny.iter().any(|net| net.contains(&ip))
|
||||
}
|
||||
|
||||
/// The URL parser already knows the host kind: an IPv6 literal is
|
||||
/// `Host::Ipv6`, never the bracketed string `host_str()` renders.
|
||||
pub(crate) fn url_is_loopback(url: &Url) -> bool {
|
||||
match url.host() {
|
||||
Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
|
||||
Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
|
||||
Some(url::Host::Ipv6(ip)) => IpAddr::V6(ip).to_canonical().is_loopback(),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `http://` to a host that is not loopback sends the bearer token in clear.
|
||||
pub(crate) fn plain_http_off_loopback(peer: &PeerConfig) -> bool {
|
||||
peer.url.scheme() == "http" && !url_is_loopback(&peer.url)
|
||||
}
|
||||
|
||||
/// One wording for the warning, whether it comes from config validation or
|
||||
/// from the transport.
|
||||
pub(crate) fn warn_plain_http(peer: &PeerConfig) {
|
||||
tracing::warn!(
|
||||
peer = %peer.name,
|
||||
"plain http to a non-loopback host; the bearer token travels in cleartext"
|
||||
);
|
||||
}
|
||||
|
||||
/// The plain-`http` opt-in rule, shared by validation and the transport.
|
||||
pub(crate) fn plain_http_allowed(peer: &PeerConfig) -> bool {
|
||||
!plain_http_off_loopback(peer) || peer.allow_plain_http
|
||||
}
|
||||
|
||||
fn validate_peer(
|
||||
section_enabled: bool,
|
||||
peer: &PeerConfig,
|
||||
@@ -161,14 +202,15 @@ fn validate_url(
|
||||
}
|
||||
// A name is not an address yet, so it cannot be matched here.
|
||||
if let Some(ip) = host_ip(url) {
|
||||
if deny.iter().any(|net| net.contains(&ip)) {
|
||||
if denied(ip, deny) {
|
||||
return Err(ConfigError::Invalid(format!(
|
||||
"peer {}: host {ip} is in deny_cidrs",
|
||||
peer.name
|
||||
"peer {}: host {} is in deny_cidrs",
|
||||
peer.name,
|
||||
ip.to_canonical()
|
||||
)));
|
||||
}
|
||||
}
|
||||
if url.scheme() == "http" && !is_loopback(url) {
|
||||
if plain_http_off_loopback(peer) {
|
||||
if !peer.allow_plain_http {
|
||||
return Err(ConfigError::Invalid(format!(
|
||||
"peer {}: plain http to a non-loopback host requires allow_plain_http = true",
|
||||
@@ -176,34 +218,20 @@ fn validate_url(
|
||||
)));
|
||||
}
|
||||
if section_enabled && peer.enabled {
|
||||
tracing::warn!(
|
||||
peer = %peer.name,
|
||||
"plain http to a non-loopback host; the bearer token travels in cleartext"
|
||||
);
|
||||
warn_plain_http(peer);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn host_ip(url: &Url) -> Option<IpAddr> {
|
||||
// An IPv4-mapped IPv6 literal (`[::ffff:169.254.169.254]`) must be
|
||||
// matched against the IPv4 deny list, so canonicalise before comparing.
|
||||
match url.host()? {
|
||||
url::Host::Ipv4(ip) => Some(IpAddr::V4(ip)),
|
||||
url::Host::Ipv6(ip) => Some(IpAddr::V6(ip).to_canonical()),
|
||||
url::Host::Ipv6(ip) => Some(IpAddr::V6(ip)),
|
||||
url::Host::Domain(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_loopback(url: &Url) -> bool {
|
||||
match url.host() {
|
||||
Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
|
||||
Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
|
||||
Some(url::Host::Ipv6(ip)) => IpAddr::V6(ip).to_canonical().is_loopback(),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::PathBuf;
|
||||
@@ -465,9 +493,27 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_detection_covers_localhost_and_127() {
|
||||
assert!(is_loopback(&Url::parse("http://LOCALHOST:1984").unwrap()));
|
||||
assert!(is_loopback(&Url::parse("http://127.0.0.2:1984").unwrap()));
|
||||
assert!(!is_loopback(&Url::parse("http://10.0.0.1:1984").unwrap()));
|
||||
fn loopback_detection_covers_localhost_and_both_families() {
|
||||
assert!(url_is_loopback(
|
||||
&Url::parse("http://LOCALHOST:1984").unwrap()
|
||||
));
|
||||
assert!(url_is_loopback(
|
||||
&Url::parse("http://127.0.0.2:1984").unwrap()
|
||||
));
|
||||
assert!(url_is_loopback(&Url::parse("http://[::1]:1984").unwrap()));
|
||||
assert!(url_is_loopback(
|
||||
&Url::parse("http://[::ffff:127.0.0.1]:1984").unwrap()
|
||||
));
|
||||
assert!(!url_is_loopback(
|
||||
&Url::parse("http://10.0.0.1:1984").unwrap()
|
||||
));
|
||||
assert!(!url_is_loopback(&Url::parse("http://beta:1984").unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deny_networks_rejects_a_bad_cidr_once_for_every_caller() {
|
||||
assert!(deny_networks(&["10.0.0.0/8".into()]).is_ok());
|
||||
let err = deny_networks(&["nope".into()]).unwrap_err();
|
||||
assert!(message(err).contains("peers.deny_cidrs"));
|
||||
}
|
||||
}
|
||||
@@ -303,7 +303,7 @@ impl PeerRegistry {
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
crate::peers::registry::client::deny_networks(&new.deny_cidrs)?;
|
||||
crate::peers::config::deny_networks(&new.deny_cidrs)?;
|
||||
}
|
||||
let params = LoopConfig::from_config(&new);
|
||||
{
|
||||
|
||||
+47
-8
@@ -13,9 +13,17 @@ use crate::peers::types::{PeerConfig, Secret};
|
||||
/// Bearer tokens are short. A larger file is refused before the rest is read.
|
||||
pub const MAX_TOKEN_BYTES: usize = 4 * 1024;
|
||||
|
||||
/// The only place a token file's contents become a header value: a token that
|
||||
/// cannot be sent verbatim as `Bearer <token>` is refused here, never
|
||||
/// forwarded, so a stray CR, LF or NUL cannot split or terminate the request.
|
||||
fn header_safe(text: &str) -> bool {
|
||||
!text.bytes().any(|b| matches!(b, b'\r' | b'\n' | 0))
|
||||
&& axum::http::HeaderValue::from_str(&format!("Bearer {text}")).is_ok()
|
||||
}
|
||||
|
||||
/// Read `peer.token_file`, trimming one trailing newline.
|
||||
///
|
||||
/// Group- and world-readable files are rejected unless the path is inside
|
||||
/// Group- and world-accessible files are rejected unless the path is inside
|
||||
/// `$CREDENTIALS_DIRECTORY` (systemd's credential dir is not mode 0600; the
|
||||
/// directory itself is the protection).
|
||||
pub fn load_token(peer: &PeerConfig) -> Result<Secret, PeerError> {
|
||||
@@ -58,6 +66,9 @@ pub fn load_token_at(
|
||||
return Err(PeerError::TokenFile("empty".into()));
|
||||
}
|
||||
let text = String::from_utf8(buf).map_err(|_| PeerError::TokenFile("not utf-8".into()))?;
|
||||
if !header_safe(&text) {
|
||||
return Err(PeerError::TokenFile("invalid".into()));
|
||||
}
|
||||
Ok(Secret::new(text))
|
||||
}
|
||||
|
||||
@@ -67,9 +78,10 @@ fn oversize() -> PeerError {
|
||||
|
||||
fn reject_group_or_world_readable(meta: &std::fs::Metadata) -> Result<(), PeerError> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
// Other users who can read the file can call the peer as this consolidator.
|
||||
if meta.permissions().mode() & 0o044 != 0 {
|
||||
return Err(PeerError::TokenFile("group or world readable".into()));
|
||||
// Other users who can reach the file can call the peer as this
|
||||
// consolidator, and one who can write it can swap the token.
|
||||
if meta.permissions().mode() & 0o077 != 0 {
|
||||
return Err(PeerError::TokenFile("group or world accessible".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -131,10 +143,12 @@ mod tests {
|
||||
assert!(!format!("{loaded:?}").contains("pending"));
|
||||
assert!(!format!("{loaded}").contains("pending"));
|
||||
|
||||
// Only one newline is trimmed; a second one would end the header line
|
||||
// early, so the file is refused rather than forwarded.
|
||||
std::fs::write(&path, b"pending\n\n").unwrap();
|
||||
assert_eq!(
|
||||
load_token_at(&peer(path.clone()), None).unwrap().expose(),
|
||||
"pending\n"
|
||||
token_err(load_token_at(&peer(path.clone()), None).unwrap_err()),
|
||||
"invalid"
|
||||
);
|
||||
std::fs::write(&path, b"next\r\n").unwrap();
|
||||
assert_eq!(load_token(&peer(path)).unwrap().expose(), "next");
|
||||
@@ -171,6 +185,31 @@ mod tests {
|
||||
assert!(!err.contains('\u{ff}'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_that_cannot_be_a_header_value_are_refused() {
|
||||
let dir = TempDir::new("peer-secret");
|
||||
for (name, body) in [
|
||||
("crlf", b"a\r\nb\n".to_vec()),
|
||||
("mid-newline", b"a\nb".to_vec()),
|
||||
("mid-cr", b"a\rb".to_vec()),
|
||||
("nul", b"a\0b".to_vec()),
|
||||
("del", b"a\x7fb".to_vec()),
|
||||
] {
|
||||
let path = dir.write(name, &body, 0o600);
|
||||
assert_eq!(
|
||||
token_err(load_token_at(&peer(path), None).unwrap_err()),
|
||||
"invalid",
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
// A visible token with no control characters still loads.
|
||||
let ok = dir.write("ok", b"slinuxm_abc-123\n", 0o600);
|
||||
assert_eq!(
|
||||
load_token_at(&peer(ok), None).unwrap().expose(),
|
||||
"slinuxm_abc-123"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_readable_files_are_rejected_unless_under_the_credentials_dir() {
|
||||
let dir = TempDir::new("peer-secret");
|
||||
@@ -182,7 +221,7 @@ mod tests {
|
||||
let outside = dir.write("creds-evil/token", format!("{SECRET}\n").as_bytes(), 0o640);
|
||||
|
||||
let err = token_err(load_token_at(&peer(outside.clone()), Some(&creds)).unwrap_err());
|
||||
assert!(err.contains("group or world readable"), "{err}");
|
||||
assert!(err.contains("group or world accessible"), "{err}");
|
||||
assert!(!err.contains("SHOULD_NOT_LEAK"), "{err}");
|
||||
|
||||
let loaded = load_token_at(&peer(inside), Some(creds.as_path())).unwrap();
|
||||
@@ -214,7 +253,7 @@ mod tests {
|
||||
// The link lives under the credential directory, its target does not:
|
||||
// the target's mode decides, so the loose file is refused.
|
||||
let err = token_err(load_token_at(&peer(link), Some(&creds)).unwrap_err());
|
||||
assert!(err.contains("group or world readable"), "{err}");
|
||||
assert!(err.contains("group or world accessible"), "{err}");
|
||||
|
||||
// A private target behind the same link is fine.
|
||||
std::fs::set_permissions(
|
||||
|
||||
Reference in new issue
Block a user