Archipelago companion-v0.5.10
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "archipelago-container"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_yaml = "0.9"
|
||||
serde_json = "1.0"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls"] }
|
||||
hyper = { version = "0.14", features = ["client", "http1"] }
|
||||
thiserror = "1.0"
|
||||
anyhow = "1.0"
|
||||
async-trait = "0.1"
|
||||
futures = "0.3"
|
||||
indexmap = { version = "2.0", features = ["serde"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1.0", features = ["v4"] }
|
||||
log = "0.4"
|
||||
tracing = "0.1"
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
|
||||
[lib]
|
||||
name = "archipelago_container"
|
||||
path = "src/lib.rs"
|
||||
@@ -0,0 +1,219 @@
|
||||
use anyhow::{Context, Result};
|
||||
use serde_json::{json, Value};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum BitcoinSimulationMode {
|
||||
Mock,
|
||||
Testnet,
|
||||
Mainnet,
|
||||
None,
|
||||
}
|
||||
|
||||
pub struct BitcoinSimulator {
|
||||
mode: BitcoinSimulationMode,
|
||||
rpc_url: Option<String>,
|
||||
mock_blockchain_info: Arc<RwLock<Value>>,
|
||||
}
|
||||
|
||||
impl BitcoinSimulator {
|
||||
pub fn new(mode: BitcoinSimulationMode) -> Self {
|
||||
let mock_blockchain_info = json!({
|
||||
"chain": "main",
|
||||
"blocks": 800000,
|
||||
"headers": 800000,
|
||||
"bestblockhash": "0000000000000000000123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
"difficulty": 50000000000.0,
|
||||
"mediantime": 1700000000,
|
||||
"verificationprogress": 1.0,
|
||||
"initialblockdownload": false,
|
||||
"chainwork": "0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"size_on_disk": 500000000000i64,
|
||||
"pruned": false,
|
||||
"softforks": {},
|
||||
"warnings": ""
|
||||
});
|
||||
|
||||
let rpc_url = match mode {
|
||||
BitcoinSimulationMode::Mock => None,
|
||||
BitcoinSimulationMode::Testnet => Some("http://localhost:18332".to_string()),
|
||||
BitcoinSimulationMode::Mainnet => Some("http://localhost:8332".to_string()),
|
||||
BitcoinSimulationMode::None => None,
|
||||
};
|
||||
|
||||
Self {
|
||||
mode,
|
||||
rpc_url,
|
||||
mock_blockchain_info: Arc::new(RwLock::new(mock_blockchain_info)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_bitcoin_available(&self) -> bool {
|
||||
match self.mode {
|
||||
BitcoinSimulationMode::Mock => true,
|
||||
BitcoinSimulationMode::Testnet | BitcoinSimulationMode::Mainnet => {
|
||||
// In real mode, we'd check if the container is running
|
||||
// For now, assume it's available if we have an RPC URL
|
||||
self.rpc_url.is_some()
|
||||
}
|
||||
BitcoinSimulationMode::None => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_bitcoin_rpc_url(&self) -> Option<String> {
|
||||
self.rpc_url.clone()
|
||||
}
|
||||
|
||||
pub async fn simulate_rpc_call(&self, method: &str, params: &[Value]) -> Result<Value> {
|
||||
match self.mode {
|
||||
BitcoinSimulationMode::Mock => self.mock_rpc_call(method, params).await,
|
||||
BitcoinSimulationMode::Testnet | BitcoinSimulationMode::Mainnet => {
|
||||
// Make actual RPC call to Bitcoin node
|
||||
self.real_rpc_call(method, params).await
|
||||
}
|
||||
BitcoinSimulationMode::None => Err(anyhow::anyhow!("Bitcoin simulation is disabled")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn mock_rpc_call(&self, method: &str, _params: &[Value]) -> Result<Value> {
|
||||
match method {
|
||||
"getblockchaininfo" => {
|
||||
let info = self.mock_blockchain_info.read().await;
|
||||
Ok(info.clone())
|
||||
}
|
||||
"getnetworkinfo" => Ok(json!({
|
||||
"version": 260000,
|
||||
"subversion": "/Bitcoin Core:26.0.0/",
|
||||
"protocolversion": 70016,
|
||||
"localservices": "000000000000040d",
|
||||
"localservicesnames": ["NETWORK", "WITNESS", "NETWORK_LIMITED"],
|
||||
"connections": 8,
|
||||
"connections_in": 4,
|
||||
"connections_out": 4,
|
||||
"networkactive": true,
|
||||
"networks": [],
|
||||
"relayfee": 0.00001000,
|
||||
"incrementalfee": 0.00001000,
|
||||
"localaddresses": [],
|
||||
"warnings": ""
|
||||
})),
|
||||
"getwalletinfo" => Ok(json!({
|
||||
"walletname": "wallet.dat",
|
||||
"walletversion": 169900,
|
||||
"balance": 0.0,
|
||||
"unconfirmed_balance": 0.0,
|
||||
"immature_balance": 0.0,
|
||||
"txcount": 0,
|
||||
"keypoololdest": 1700000000,
|
||||
"keypoolsize": 1000,
|
||||
"keypoolsize_hd_internal": 1000,
|
||||
"paytxfee": 0.00000000,
|
||||
"hdseedid": "0000000000000000000000000000000000000000",
|
||||
"private_keys_enabled": true,
|
||||
"avoid_reuse": false,
|
||||
"scanning": false
|
||||
})),
|
||||
"getblockcount" => Ok(json!(800000)),
|
||||
"getblockhash" => Ok(json!(
|
||||
"0000000000000000000123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
)),
|
||||
"getmempoolinfo" => Ok(json!({
|
||||
"loaded": true,
|
||||
"size": 100,
|
||||
"bytes": 100000,
|
||||
"usage": 200000,
|
||||
"total_fee": 0.00001000,
|
||||
"maxmempool": 300000000,
|
||||
"mempoolminfee": 0.00001000,
|
||||
"minrelaytxfee": 0.00001000
|
||||
})),
|
||||
"getpeerinfo" => Ok(json!([])),
|
||||
"getrawmempool" => Ok(json!([])),
|
||||
"estimatesmartfee" => Ok(json!({
|
||||
"feerate": 0.00001000,
|
||||
"blocks": 6
|
||||
})),
|
||||
_ => {
|
||||
// Default response for unknown methods
|
||||
Ok(json!(null))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn real_rpc_call(&self, method: &str, params: &[Value]) -> Result<Value> {
|
||||
let url = self
|
||||
.rpc_url
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("No RPC URL configured"))?;
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let request_body = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": method,
|
||||
"params": params
|
||||
});
|
||||
|
||||
// TODO: Get RPC credentials from config/secrets
|
||||
let response = client
|
||||
.post(url)
|
||||
.json(&request_body)
|
||||
.send()
|
||||
.await
|
||||
.context("Failed to send RPC request")?;
|
||||
|
||||
let response_json: Value = response
|
||||
.json::<Value>()
|
||||
.await
|
||||
.context("Failed to parse RPC response")?;
|
||||
|
||||
if let Some(error) = response_json.get("error") {
|
||||
return Err(anyhow::anyhow!("Bitcoin RPC error: {}", error));
|
||||
}
|
||||
|
||||
Ok(response_json.get("result").cloned().unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
pub fn mode(&self) -> &BitcoinSimulationMode {
|
||||
&self.mode
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for BitcoinSimulationMode {
|
||||
fn from(s: &str) -> Self {
|
||||
match s.to_lowercase().as_str() {
|
||||
"mock" => BitcoinSimulationMode::Mock,
|
||||
"testnet" => BitcoinSimulationMode::Testnet,
|
||||
"mainnet" => BitcoinSimulationMode::Mainnet,
|
||||
_ => BitcoinSimulationMode::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_mock_bitcoin_available() {
|
||||
let simulator = BitcoinSimulator::new(BitcoinSimulationMode::Mock);
|
||||
assert!(simulator.is_bitcoin_available());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_mock_getblockchaininfo() {
|
||||
let simulator = BitcoinSimulator::new(BitcoinSimulationMode::Mock);
|
||||
let result = simulator
|
||||
.simulate_rpc_call("getblockchaininfo", &[])
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.get("blocks").is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_none_bitcoin_not_available() {
|
||||
let simulator = BitcoinSimulator::new(BitcoinSimulationMode::None);
|
||||
assert!(!simulator.is_bitcoin_available());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
use crate::manifest::HealthCheck;
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
use tokio::time::interval;
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub enum HealthStatus {
|
||||
Healthy,
|
||||
Unhealthy,
|
||||
Unknown,
|
||||
Starting,
|
||||
}
|
||||
|
||||
pub struct HealthMonitor {
|
||||
container_name: String,
|
||||
health_check: Option<HealthCheck>,
|
||||
}
|
||||
|
||||
impl HealthMonitor {
|
||||
pub fn new(container_name: String, health_check: Option<HealthCheck>) -> Self {
|
||||
Self {
|
||||
container_name,
|
||||
health_check,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn check_health(&self) -> Result<HealthStatus> {
|
||||
if let Some(ref check) = self.health_check {
|
||||
match check.check_type.as_str() {
|
||||
"http" => self.check_http_health(check).await,
|
||||
"exec" => self.check_exec_health(check).await,
|
||||
_ => {
|
||||
warn!("Unknown health check type: {}", check.check_type);
|
||||
Ok(HealthStatus::Unknown)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// No health check defined, assume healthy if container is running
|
||||
Ok(HealthStatus::Unknown)
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_http_health(&self, check: &HealthCheck) -> Result<HealthStatus> {
|
||||
let endpoint = check
|
||||
.endpoint
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("HTTP health check missing endpoint"))?;
|
||||
|
||||
let url = if let Some(path) = &check.path {
|
||||
format!("{}{}", endpoint, path)
|
||||
} else {
|
||||
endpoint.clone()
|
||||
};
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(5))
|
||||
.build()
|
||||
.context("Failed to create HTTP client")?;
|
||||
|
||||
match client.get(&url).send().await {
|
||||
Ok(response) => {
|
||||
if response.status().is_success() {
|
||||
Ok(HealthStatus::Healthy)
|
||||
} else {
|
||||
Ok(HealthStatus::Unhealthy)
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Health check failed for {}: {}", self.container_name, e);
|
||||
Ok(HealthStatus::Unhealthy)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_exec_health(&self, check: &HealthCheck) -> Result<HealthStatus> {
|
||||
// Execute health check command in container
|
||||
let endpoint = check
|
||||
.endpoint
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Exec health check missing endpoint"))?;
|
||||
|
||||
use tokio::process::Command;
|
||||
|
||||
let output = Command::new("podman")
|
||||
.arg("exec")
|
||||
.arg(&self.container_name)
|
||||
.arg("sh")
|
||||
.arg("-c")
|
||||
.arg(endpoint)
|
||||
.output()
|
||||
.await
|
||||
.context("Failed to execute health check")?;
|
||||
|
||||
if output.status.success() {
|
||||
Ok(HealthStatus::Healthy)
|
||||
} else {
|
||||
Ok(HealthStatus::Unhealthy)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn monitor_health(
|
||||
&self,
|
||||
mut shutdown: tokio::sync::broadcast::Receiver<()>,
|
||||
on_status_change: impl Fn(HealthStatus) + Send + 'static,
|
||||
) -> Result<()> {
|
||||
let check = self.health_check.clone();
|
||||
let interval_duration = if let Some(ref check) = check {
|
||||
parse_duration(&check.interval).unwrap_or(Duration::from_secs(30))
|
||||
} else {
|
||||
Duration::from_secs(30)
|
||||
};
|
||||
|
||||
let mut interval = interval(interval_duration);
|
||||
let mut consecutive_failures = 0;
|
||||
let max_failures = check.as_ref().map(|c| c.retries).unwrap_or(3);
|
||||
|
||||
let mut last_status = HealthStatus::Unknown;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = interval.tick() => {
|
||||
match self.check_health().await {
|
||||
Ok(status) => {
|
||||
if status != last_status {
|
||||
info!("Health status changed for {}: {:?} -> {:?}",
|
||||
self.container_name, last_status, status);
|
||||
on_status_change(status.clone());
|
||||
last_status = status.clone();
|
||||
}
|
||||
|
||||
match status {
|
||||
HealthStatus::Healthy => {
|
||||
consecutive_failures = 0;
|
||||
}
|
||||
HealthStatus::Unhealthy => {
|
||||
consecutive_failures += 1;
|
||||
if consecutive_failures >= max_failures {
|
||||
error!("Container {} is unhealthy after {} failures",
|
||||
self.container_name, consecutive_failures);
|
||||
// Auto-restart is handled by the orchestrator-level health monitor
|
||||
// (core/archipelago/src/health_monitor.rs) which runs every 60s,
|
||||
// checks all container states via `podman ps`, and restarts
|
||||
// exited containers with exponential backoff (10s/30s/90s).
|
||||
// This per-container monitor is for manifest-driven health
|
||||
// tracking and status change callbacks only.
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Health check error for {}: {}", self.container_name, e);
|
||||
consecutive_failures += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = shutdown.recv() => {
|
||||
info!("Health monitoring stopped for {}", self.container_name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_duration(s: &str) -> Option<Duration> {
|
||||
let s = s.trim().to_lowercase();
|
||||
if s.ends_with('s') {
|
||||
let secs: u64 = s.trim_end_matches('s').parse().ok()?;
|
||||
Some(Duration::from_secs(secs))
|
||||
} else if s.ends_with('m') {
|
||||
let mins: u64 = s.trim_end_matches('m').parse().ok()?;
|
||||
Some(Duration::from_secs(mins * 60))
|
||||
} else if s.ends_with('h') {
|
||||
let hours: u64 = s.trim_end_matches('h').parse().ok()?;
|
||||
Some(Duration::from_secs(hours * 3600))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_duration() {
|
||||
assert_eq!(parse_duration("30s"), Some(Duration::from_secs(30)));
|
||||
assert_eq!(parse_duration("5m"), Some(Duration::from_secs(300)));
|
||||
assert_eq!(parse_duration("1h"), Some(Duration::from_secs(3600)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Container image signature verification (cosign).
|
||||
//!
|
||||
//! The manifest/catalog `image_signature` field is a *claim* that the image
|
||||
//! is signed with the fleet's cosign key. Verification runs at the pull
|
||||
//! choke points (`PodmanClient::pull_image`, `DockerRuntime::pull_image`);
|
||||
//! a declared signature that cannot be verified hard-fails the pull.
|
||||
//!
|
||||
//! Every manifest has carried the literal placeholder `cosign://...` since
|
||||
//! the field was introduced — that means "not signed yet" and is treated as
|
||||
//! no claim, so enforcement stays dormant until the signing ceremony
|
||||
//! publishes real signatures AND nodes carry the pinned cosign public key.
|
||||
//! Ship order matters: key + cosign binary reach the fleet first, real
|
||||
//! signature values in the catalog come after.
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// The literal placeholder every pre-ceremony manifest carries.
|
||||
pub const SIGNATURE_PLACEHOLDER: &str = "cosign://...";
|
||||
|
||||
/// Env override for the pinned cosign public key path (tests, staging).
|
||||
pub const COSIGN_PUBKEY_ENV: &str = "ARCHIPELAGO_COSIGN_PUBKEY";
|
||||
|
||||
const DEFAULT_PUBKEY_PATH: &str = "/etc/archipelago/cosign.pub";
|
||||
|
||||
const COSIGN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum SignatureClaim {
|
||||
/// No signature declared (field absent or empty).
|
||||
None,
|
||||
/// The literal `cosign://...` placeholder — manifest predates real signing.
|
||||
Placeholder,
|
||||
/// A real declared signature reference; MUST verify or the pull fails.
|
||||
Declared(String),
|
||||
}
|
||||
|
||||
pub fn classify_signature(signature: Option<&str>) -> SignatureClaim {
|
||||
match signature.map(str::trim) {
|
||||
None | Some("") => SignatureClaim::None,
|
||||
Some(SIGNATURE_PLACEHOLDER) => SignatureClaim::Placeholder,
|
||||
Some(s) => SignatureClaim::Declared(s.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn pinned_pubkey_path() -> PathBuf {
|
||||
std::env::var(COSIGN_PUBKEY_ENV)
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|_| PathBuf::from(DEFAULT_PUBKEY_PATH))
|
||||
}
|
||||
|
||||
/// Verify a declared image signature with the fleet's pinned cosign key.
|
||||
/// Any failure — missing key, missing cosign binary, verification error —
|
||||
/// is a hard error: an image that CLAIMS to be signed must never be pulled
|
||||
/// on a node that can't prove the claim.
|
||||
pub async fn verify_declared_signature(
|
||||
image: &str,
|
||||
sig_ref: &str,
|
||||
allow_insecure_registry: bool,
|
||||
) -> Result<()> {
|
||||
verify_with_key_path(
|
||||
image,
|
||||
sig_ref,
|
||||
&pinned_pubkey_path(),
|
||||
allow_insecure_registry,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn verify_with_key_path(
|
||||
image: &str,
|
||||
sig_ref: &str,
|
||||
key_path: &std::path::Path,
|
||||
allow_insecure_registry: bool,
|
||||
) -> Result<()> {
|
||||
if !key_path.exists() {
|
||||
bail!(
|
||||
"Image '{image}' declares signature '{sig_ref}' but the pinned cosign \
|
||||
public key is missing at {} (override with {COSIGN_PUBKEY_ENV}). \
|
||||
Refusing to pull an image whose signature claim cannot be verified.",
|
||||
key_path.display()
|
||||
);
|
||||
}
|
||||
|
||||
// Self-managed key => signatures aren't in the public Rekor transparency
|
||||
// log, so tlog verification must be disabled explicitly (cosign v2
|
||||
// defaults it on and would fail every private-key signature otherwise).
|
||||
let mut cmd = tokio::process::Command::new("cosign");
|
||||
cmd.arg("verify")
|
||||
.arg("--key")
|
||||
.arg(key_path)
|
||||
.arg("--insecure-ignore-tlog=true");
|
||||
if allow_insecure_registry {
|
||||
// podman's --tls-verify=false covers both plain HTTP and bad TLS;
|
||||
// cosign splits those into two flags — pass both to match.
|
||||
cmd.arg("--allow-insecure-registry");
|
||||
cmd.arg("--allow-http-registry");
|
||||
}
|
||||
cmd.arg(image);
|
||||
|
||||
let output = tokio::time::timeout(COSIGN_TIMEOUT, cmd.output())
|
||||
.await
|
||||
.map_err(|_| {
|
||||
anyhow::anyhow!(
|
||||
"cosign verify timed out after {}s for image '{image}'",
|
||||
COSIGN_TIMEOUT.as_secs()
|
||||
)
|
||||
})?
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to run cosign for image '{image}' which declares signature \
|
||||
'{sig_ref}' — is cosign installed? A declared signature cannot be \
|
||||
skipped."
|
||||
)
|
||||
})?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
bail!(
|
||||
"Signature verification FAILED for image '{image}' (declared: '{sig_ref}'): \
|
||||
{stderr}"
|
||||
);
|
||||
}
|
||||
|
||||
tracing::info!("cosign signature verified for image {image}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Shared pull-site gate: decide whether the pull may proceed.
|
||||
/// Returns Ok(()) for unsigned/placeholder claims (with a log line) and only
|
||||
/// after successful cosign verification for declared ones.
|
||||
pub async fn enforce_signature_claim(
|
||||
image: &str,
|
||||
signature: Option<&str>,
|
||||
allow_insecure_registry: bool,
|
||||
) -> Result<()> {
|
||||
match classify_signature(signature) {
|
||||
SignatureClaim::None => {
|
||||
tracing::debug!("image {image}: no signature declared, pulling unverified");
|
||||
Ok(())
|
||||
}
|
||||
SignatureClaim::Placeholder => {
|
||||
tracing::debug!(
|
||||
"image {image}: signature is the pre-ceremony placeholder, pulling unverified"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
SignatureClaim::Declared(sig_ref) => {
|
||||
verify_declared_signature(image, &sig_ref, allow_insecure_registry).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn absent_and_empty_signatures_are_no_claim() {
|
||||
assert_eq!(classify_signature(None), SignatureClaim::None);
|
||||
assert_eq!(classify_signature(Some("")), SignatureClaim::None);
|
||||
assert_eq!(classify_signature(Some(" ")), SignatureClaim::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_placeholder_is_not_a_claim() {
|
||||
assert_eq!(
|
||||
classify_signature(Some("cosign://...")),
|
||||
SignatureClaim::Placeholder
|
||||
);
|
||||
assert_eq!(
|
||||
classify_signature(Some(" cosign://... ")),
|
||||
SignatureClaim::Placeholder
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_values_are_declared_claims() {
|
||||
assert_eq!(
|
||||
classify_signature(Some("cosign://sha256-abc.sig")),
|
||||
SignatureClaim::Declared("cosign://sha256-abc.sig".to_string())
|
||||
);
|
||||
// Unknown schemes still count as a claim — better to fail closed on
|
||||
// a value we don't understand than to pull unverified.
|
||||
assert_eq!(
|
||||
classify_signature(Some("sigstore://whatever")),
|
||||
SignatureClaim::Declared("sigstore://whatever".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn declared_signature_without_pinned_key_hard_fails() {
|
||||
let err = verify_with_key_path(
|
||||
"registry.example/app:1.0",
|
||||
"cosign://sha256-abc.sig",
|
||||
std::path::Path::new("/nonexistent/cosign.pub"),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(err
|
||||
.to_string()
|
||||
.contains("pinned cosign public key is missing"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsigned_and_placeholder_claims_pass_the_gate() {
|
||||
enforce_signature_claim("registry.example/app:1.0", None, false)
|
||||
.await
|
||||
.unwrap();
|
||||
enforce_signature_claim("registry.example/app:1.0", Some("cosign://..."), false)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
pub mod bitcoin_simulator;
|
||||
pub mod health_monitor;
|
||||
pub mod image_verify;
|
||||
pub mod manifest;
|
||||
pub mod podman_client;
|
||||
pub mod port_manager;
|
||||
pub mod runtime;
|
||||
|
||||
pub use bitcoin_simulator::{BitcoinSimulationMode, BitcoinSimulator};
|
||||
pub use health_monitor::HealthMonitor;
|
||||
pub use manifest::{
|
||||
AppInterface, AppManifest, BuildConfig, ContainerConfig, Dependency, DerivedEnv, GeneratedCert,
|
||||
GeneratedFile, GeneratedSecret, HealthCheck, HookStep, HostCopy, HostFacts, LifecycleHooks,
|
||||
ManifestError, ResolvedSource, ResourceLimits, SecretEnv, SecretGenKind, SecretsProvider,
|
||||
SecurityPolicy, Volume,
|
||||
};
|
||||
pub use podman_client::{
|
||||
image_uses_insecure_registry, ContainerState, ContainerStatus, PodmanClient,
|
||||
};
|
||||
pub use port_manager::{PortError, PortManager};
|
||||
pub use runtime::{AutoRuntime, ContainerRuntime, DockerRuntime, PodmanRuntime};
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,175 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, RwLock};
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum PortError {
|
||||
#[error("Port {0} is already allocated to app {1}")]
|
||||
PortConflict(u16, String),
|
||||
#[error("App {0} has no allocated ports")]
|
||||
NoPortsAllocated(String),
|
||||
#[error("Lock poisoned: {0}")]
|
||||
LockPoisoned(String),
|
||||
}
|
||||
|
||||
pub struct PortManager {
|
||||
allocations: Arc<RwLock<HashMap<String, Vec<u16>>>>,
|
||||
port_to_app: Arc<RwLock<HashMap<u16, String>>>,
|
||||
port_offset: u16,
|
||||
}
|
||||
|
||||
impl PortManager {
|
||||
pub fn new(port_offset: u16) -> Self {
|
||||
Self {
|
||||
allocations: Arc::new(RwLock::new(HashMap::new())),
|
||||
port_to_app: Arc::new(RwLock::new(HashMap::new())),
|
||||
port_offset,
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocate ports for an app, applying the port offset
|
||||
pub fn allocate_ports(&self, app_id: &str, base_ports: &[u16]) -> Result<Vec<u16>, PortError> {
|
||||
let mut allocations = self
|
||||
.allocations
|
||||
.write()
|
||||
.map_err(|e| PortError::LockPoisoned(e.to_string()))?;
|
||||
let mut port_to_app = self
|
||||
.port_to_app
|
||||
.write()
|
||||
.map_err(|e| PortError::LockPoisoned(e.to_string()))?;
|
||||
let mut allocated_ports = Vec::new();
|
||||
|
||||
// Check for conflicts and allocate ports
|
||||
for &base_port in base_ports {
|
||||
let dev_port = base_port + self.port_offset;
|
||||
|
||||
// Check if port is already allocated
|
||||
if let Some(existing_app) = port_to_app.get(&dev_port) {
|
||||
if existing_app != app_id {
|
||||
return Err(PortError::PortConflict(dev_port, existing_app.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
allocated_ports.push(dev_port);
|
||||
port_to_app.insert(dev_port, app_id.to_string());
|
||||
}
|
||||
|
||||
// Store allocation for this app
|
||||
allocations.insert(app_id.to_string(), allocated_ports.clone());
|
||||
|
||||
Ok(allocated_ports)
|
||||
}
|
||||
|
||||
/// Get allocated ports for an app
|
||||
pub fn get_port_mapping(&self, app_id: &str) -> Result<Option<Vec<u16>>, PortError> {
|
||||
let allocations = self
|
||||
.allocations
|
||||
.read()
|
||||
.map_err(|e| PortError::LockPoisoned(e.to_string()))?;
|
||||
Ok(allocations.get(app_id).cloned())
|
||||
}
|
||||
|
||||
/// Get the dev port for a specific base port of an app
|
||||
pub fn get_dev_port(&self, app_id: &str, base_port: u16) -> Result<Option<u16>, PortError> {
|
||||
Ok(self.get_port_mapping(app_id)?.and_then(|ports| {
|
||||
ports
|
||||
.iter()
|
||||
.find(|&&p| p == base_port + self.port_offset)
|
||||
.copied()
|
||||
}))
|
||||
}
|
||||
|
||||
/// Release all ports allocated to an app
|
||||
pub fn release_ports(&self, app_id: &str) -> Result<(), PortError> {
|
||||
let mut allocations = self
|
||||
.allocations
|
||||
.write()
|
||||
.map_err(|e| PortError::LockPoisoned(e.to_string()))?;
|
||||
let mut port_to_app = self
|
||||
.port_to_app
|
||||
.write()
|
||||
.map_err(|e| PortError::LockPoisoned(e.to_string()))?;
|
||||
|
||||
if let Some(ports) = allocations.remove(app_id) {
|
||||
for port in ports {
|
||||
port_to_app.remove(&port);
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
Err(PortError::NoPortsAllocated(app_id.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a port is available
|
||||
pub fn is_port_available(&self, base_port: u16) -> Result<bool, PortError> {
|
||||
let dev_port = base_port + self.port_offset;
|
||||
let port_to_app = self
|
||||
.port_to_app
|
||||
.read()
|
||||
.map_err(|e| PortError::LockPoisoned(e.to_string()))?;
|
||||
Ok(!port_to_app.contains_key(&dev_port))
|
||||
}
|
||||
|
||||
/// Get all allocated ports
|
||||
pub fn get_all_allocations(&self) -> Result<HashMap<String, Vec<u16>>, PortError> {
|
||||
let allocations = self
|
||||
.allocations
|
||||
.read()
|
||||
.map_err(|e| PortError::LockPoisoned(e.to_string()))?;
|
||||
Ok(allocations.clone())
|
||||
}
|
||||
|
||||
/// Get port offset
|
||||
pub fn port_offset(&self) -> u16 {
|
||||
self.port_offset
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_port_allocation() {
|
||||
let manager = PortManager::new(10000);
|
||||
|
||||
let ports = manager.allocate_ports("app1", &[8332, 8333]).unwrap();
|
||||
assert_eq!(ports, vec![18332, 18333]);
|
||||
|
||||
let mapping = manager.get_port_mapping("app1").unwrap().unwrap();
|
||||
assert_eq!(mapping, vec![18332, 18333]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_port_conflict() {
|
||||
let manager = PortManager::new(10000);
|
||||
|
||||
manager.allocate_ports("app1", &[8332]).unwrap();
|
||||
|
||||
// Try to allocate the same port to another app
|
||||
let result = manager.allocate_ports("app2", &[8332]);
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_port_release() {
|
||||
let manager = PortManager::new(10000);
|
||||
|
||||
manager.allocate_ports("app1", &[8332]).unwrap();
|
||||
manager.release_ports("app1").unwrap();
|
||||
|
||||
// Port should now be available
|
||||
assert!(manager.is_port_available(8332).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_dev_port() {
|
||||
let manager = PortManager::new(10000);
|
||||
|
||||
manager.allocate_ports("app1", &[8332, 8333]).unwrap();
|
||||
|
||||
assert_eq!(manager.get_dev_port("app1", 8332).unwrap(), Some(18332));
|
||||
assert_eq!(manager.get_dev_port("app1", 8333).unwrap(), Some(18333));
|
||||
assert_eq!(manager.get_dev_port("app1", 9999).unwrap(), None);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user