B: cover token rotation and recovery against the in-process peer

This commit is contained in:
ari committed 2026-10-19 20:55:25 -04:00
1 parent c1a12abc19
commit 7dd79c3851
1 file changed
+46 -1
+46 -1
View File
@@ -67,6 +67,21 @@ fn token_file(contents: &str) -> std::path::PathBuf {
path
}
/// Overwrite a token file in place, as a credential rotation does.
fn replace_token(path: &Path, contents: &str) {
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)
.unwrap()
.write_all(contents.as_bytes())
.unwrap();
}
fn ping() -> PeerRequest {
PeerRequest {
path: "/api/v1/ping".into(),
@@ -146,6 +161,8 @@ async fn client_get_is_capped_and_does_not_follow_redirects() {
/// A second in-process `slinuxm` (fake sources) acting as the peer.
struct RunningPeer {
port: u16,
/// The token this peer accepts, when auth is on.
token: Option<String>,
shutdown: CancellationToken,
join: tokio::task::JoinHandle<anyhow::Result<()>>,
}
@@ -164,6 +181,7 @@ async fn start_peer_at(port: u16, auth: bool) -> RunningPeer {
config.server.port = port;
config.auth.enabled = auth;
let mut state = fake_state(config);
let mut token = None;
if auth {
let pool = SqlitePoolOptions::new()
.max_connections(1)
@@ -171,7 +189,7 @@ async fn start_peer_at(port: u16, auth: bool) -> RunningPeer {
.await
.unwrap();
skyg_linux_tracker::db::migrate(&pool).await.unwrap();
let _ = tokens::create(&pool, "peer-consumer").await.unwrap();
token = Some(tokens::create(&pool, "peer-consumer").await.unwrap());
state.db = Some(pool);
}
let shutdown = state.shutdown.clone();
@@ -185,6 +203,7 @@ async fn start_peer_at(port: u16, auth: bool) -> RunningPeer {
));
RunningPeer {
port,
token,
shutdown,
join,
}
@@ -284,3 +303,29 @@ async fn a_rejected_token_leaves_the_api_up_and_names_the_auth_state() {
peer.stop().await;
let _ = std::fs::remove_file(&token);
}
#[tokio::test]
async fn a_rotated_token_recovers_without_a_restart() {
let peer = start_peer_at(0, true).await;
let valid = peer.token.clone().expect("auth peer has a token");
let token = token_file("stale-token\n");
let shutdown = CancellationToken::new();
let reg = registry_for(peer.port, &token, shutdown.clone());
let rejected = wait_for(&reg, |s| {
s.api.last_checked.is_some() && s.api.auth == AuthState::Rejected
})
.await;
assert!(rejected.api.up, "a 401 proves the API is running");
// Rotation: the transport re-reads the file on every check, so no
// restart or SIGHUP is needed.
replace_token(&token, &format!("{valid}\n"));
let recovered = wait_for(&reg, |s| s.api.auth == AuthState::Ok).await;
assert!(recovered.api.up);
assert_eq!(recovered.api.last_error, None);
reg.shutdown().await;
peer.stop().await;
let _ = std::fs::remove_file(&token);
}