use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use crate::error::{
DatasetError, IoOp, IoResultExt as _, IoStepExt as _, JsonResultExt as _, NumberResultExt as _,
Result,
};
use serde::Deserialize;
use crate::s3::sigv4::Credentials;
pub const DEFAULT_KEY_PREFIX: &str = "datasets/";
pub const DEFAULT_REGION: &str = "us-east-1";
pub const EXAMPLE_FILE: &str = "geolith.example.json";
pub const ENV_EXAMPLE_FILE: &str = ".env.example";
pub const DEFAULT_ENV_FILE: &str = ".env";
const PLACEHOLDERS: [&str; 3] = ["dataset", "country", "build_id"];
const KEY_ID_NAMES: [&str; 4] = [
"GEOLITH_STORAGE_ACCESS_KEY_ID",
"GEOLITH_R2_ACCESS_KEY_ID",
"DATASETS_R2_ACCESS_KEY_ID",
"AWS_ACCESS_KEY_ID",
];
const SECRET_NAMES: [&str; 4] = [
"GEOLITH_STORAGE_SECRET_ACCESS_KEY",
"GEOLITH_R2_SECRET_ACCESS_KEY",
"DATASETS_R2_SECRET_ACCESS_KEY",
"AWS_SECRET_ACCESS_KEY",
];
type Env<'a> = &'a dyn Fn(&str) -> Option<String>;
fn process_env(name: &str) -> Option<String> {
std::env::var(name).ok()
}
fn get(env: Env<'_>, name: &str) -> Option<String> {
env(name).filter(|value| !value.is_empty())
}
fn first(env: Env<'_>, names: &[&str]) -> Option<String> {
names.iter().find_map(|name| get(env, name))
}
fn path_of(home: Option<&Path>, text: &str) -> PathBuf {
match (text.strip_prefix("~/"), home) {
(Some(rest), Some(home)) => home.join(rest),
_ => PathBuf::from(text),
}
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct FileSettings {
data_root: Option<String>,
repo: Option<String>,
storage: FileStorage,
publish: FilePublish,
sources: FileSources,
alerts: FileAlerts,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct FileStorage {
endpoint: Option<String>,
region: Option<String>,
bucket: Option<String>,
prefix: Option<String>,
account_id: Option<String>,
credentials_file: Option<String>,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct FilePublish {
pointer_url: Option<String>,
page_url: Option<String>,
credentials_file: Option<String>,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct FileSources {
chirps_hosts: Option<Vec<String>>,
cdse_stac: Option<String>,
cdse_endpoint: Option<String>,
cdse_credentials_file: Option<String>,
boundaries_url_base: Option<String>,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct FileAlerts {
macos_notification: Option<bool>,
}
#[derive(Debug, Clone, Default)]
pub struct StorageSettings {
pub endpoint: Option<String>,
pub region: Option<String>,
pub bucket: Option<String>,
pub prefix: Option<String>,
pub account_id: Option<String>,
pub credentials_file: Option<PathBuf>,
pub env_credentials: Option<Credentials>,
}
#[derive(Debug, Clone, Default)]
pub struct PublishSettings {
pub pointer_url: Option<String>,
pub page_url: Option<String>,
pub credentials_file: Option<PathBuf>,
pub api_key: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct SourceSettings {
pub chirps_hosts: Vec<String>,
pub cdse_stac: Option<String>,
pub cdse_endpoint: Option<String>,
pub cdse_credentials_file: Option<PathBuf>,
pub cdse_env_credentials: Option<Credentials>,
pub boundaries_url_base: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct RunSettings {
pub dataset: Option<String>,
pub country: Option<String>,
pub country_config: Option<PathBuf>,
pub boundary_release: Option<String>,
pub boundary_tiles_revision: Option<String>,
pub baseline: Option<String>,
pub published_csv: Option<PathBuf>,
pub areas_dir: Option<PathBuf>,
pub crosswalk_csv: Option<PathBuf>,
pub lgd_dir: Option<PathBuf>,
pub cdse_today: Option<String>,
pub probe_timeout_ms: Option<u64>,
pub hostname: Option<String>,
pub min_free_gb: Option<u64>,
}
#[derive(Debug, Clone, Default)]
pub struct Deployment {
pub config_file: Option<PathBuf>,
pub env_file: Option<PathBuf>,
pub home: Option<PathBuf>,
pub path: Option<String>,
pub data_root: Option<PathBuf>,
pub repo: Option<PathBuf>,
pub storage: StorageSettings,
pub publish: PublishSettings,
pub sources: SourceSettings,
pub macos_notification: bool,
pub run: RunSettings,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
pub endpoint: String,
pub region: String,
pub bucket: String,
pub key_root: String,
}
impl Target {
pub fn check_bucket(&self, name: &str) -> Result<()> {
if name.is_empty() {
return Err(DatasetError::config(
"bucket \"\" refused: give a bucket name",
));
}
if name != self.bucket {
return Err(DatasetError::config(format!(
"bucket \"{name}\" refused: it is not storage.bucket (\"{}\")",
self.bucket
)));
}
Ok(())
}
}
fn missing(name: &str, env_name: &str) -> DatasetError {
DatasetError::config(format!(
"{name} is not set; see {EXAMPLE_FILE} or {ENV_EXAMPLE_FILE} (or set {env_name})"
))
}
fn parse_bool(name: &str, text: &str) -> Result<bool> {
match text.trim().to_ascii_lowercase().as_str() {
"true" | "1" | "yes" => Ok(true),
"false" | "0" | "no" => Ok(false),
_ => Err(DatasetError::config(format!(
"{name} \"{text}\" is not true or false"
))),
}
}
#[must_use]
pub fn url_host(url: &str) -> &str {
let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
rest.split('/').next().unwrap_or_default()
}
fn is_http_url(url: &str) -> bool {
url.split_once("://")
.is_some_and(|(scheme, _)| matches!(scheme, "http" | "https"))
&& !url_host(url).is_empty()
}
pub fn normalize_prefix(text: &str) -> Result<String> {
let trimmed = text.trim_matches('/');
let bad = trimmed.is_empty()
|| trimmed.split('/').any(|segment| {
segment.is_empty()
|| segment == "."
|| segment == ".."
|| !segment
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
});
if bad {
return Err(DatasetError::config(format!(
"storage.prefix \"{text}\" is not a key prefix: use segments of letters, digits, \
'.', '_' and '-' split by '/'"
)));
}
Ok(format!("{trimmed}/"))
}
fn check_template(name: &str, template: &str) -> Result<()> {
if !is_http_url(template) {
return Err(DatasetError::config(format!(
"{name} \"{template}\" is not an http(s) URL"
)));
}
let mut rest = template;
while let Some(open) = rest.find('{') {
let after = &rest[open + 1..];
let Some(close) = after.find('}') else {
return Err(DatasetError::config(format!(
"{name} \"{template}\" has a '{{' that is never closed"
)));
};
let word = &after[..close];
if !PLACEHOLDERS.contains(&word) {
return Err(DatasetError::config(format!(
"{name} has the unknown placeholder {{{word}}}: use {{dataset}}, {{country}} \
and {{build_id}}"
)));
}
rest = &after[close + 1..];
}
Ok(())
}
#[must_use]
pub fn fill_template(template: &str, dataset: &str, country: &str, build_id: &str) -> String {
template
.replace("{dataset}", dataset)
.replace("{country}", country)
.replace("{build_id}", build_id)
}
fn parse_env_text(text: &str) -> BTreeMap<String, String> {
let mut values = BTreeMap::new();
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let line = line
.strip_prefix("export")
.filter(|rest| rest.starts_with(char::is_whitespace))
.map_or(line, str::trim_start);
if let Some((key, value)) = line.split_once('=') {
values.insert(
key.trim().to_owned(),
value.trim().trim_matches('"').trim_matches('\'').to_owned(),
);
}
}
values
}
const fn wider_than_600(mode: u32) -> bool {
mode & 0o777 & !0o600 != 0
}
pub fn read_env_file(path: &Path) -> Result<BTreeMap<String, String>> {
let metadata = fs::metadata(path).io_at(IoOp::Read, path)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let mode = metadata.permissions().mode() & 0o777;
if wider_than_600(mode) {
return Err(DatasetError::config(format!(
"{} is mode {mode:o}, not 600: run `chmod 600 {}`",
path.display(),
path.display()
)));
}
}
let text = fs::read_to_string(path).io_at(IoOp::Read, path)?;
Ok(parse_env_text(&text))
}
fn pick_pair<'a>(
values: &'a BTreeMap<String, String>,
names: &[&str],
suffix: &str,
) -> Option<&'a str> {
names
.iter()
.find_map(|name| values.get(*name))
.or_else(|| {
values
.iter()
.find(|(name, _)| name.starts_with("RCLONE_CONFIG_") && name.ends_with(suffix))
.map(|(_, value)| value)
})
.map(String::as_str)
.filter(|value| !value.is_empty())
}
fn pair_of(values: &BTreeMap<String, String>) -> Option<Credentials> {
let key_id = pick_pair(values, &KEY_ID_NAMES, "_ACCESS_KEY_ID")?;
let secret = pick_pair(values, &SECRET_NAMES, "_SECRET_ACCESS_KEY")?;
Some(Credentials {
key_id: key_id.to_owned(),
secret: secret.to_owned(),
})
}
fn absolute_in(cwd: &Path, path: PathBuf) -> PathBuf {
if path.is_absolute() {
path
} else {
cwd.join(path)
}
}
fn load_env_file(
process: Env<'_>,
cwd: &Path,
) -> Result<(Option<PathBuf>, BTreeMap<String, String>)> {
let home = get(process, "HOME").map(PathBuf::from);
let path = match get(process, "GEOLITH_ENV_FILE") {
Some(text) => {
let path = absolute_in(cwd, path_of(home.as_deref(), &text));
if !path.is_file() {
return Err(DatasetError::config(format!(
"the env file {} does not exist (GEOLITH_ENV_FILE); see {ENV_EXAMPLE_FILE}",
path.display()
)));
}
path
}
None => {
let path = cwd.join(DEFAULT_ENV_FILE);
if !path.is_file() {
return Ok((None, BTreeMap::new()));
}
path
}
};
let values = read_env_file(&path)?;
Ok((Some(path), values))
}
impl Deployment {
pub fn load(flag: Option<&Path>) -> Result<Self> {
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
Self::load_with(flag, &process_env, &cwd)
}
fn load_with(flag: Option<&Path>, process: Env<'_>, cwd: &Path) -> Result<Self> {
let (env_file, dotenv) = load_env_file(process, cwd)?;
let layered = |name: &str| process(name).or_else(|| dotenv.get(name).cloned());
let env: Env<'_> = &layered;
let home = get(env, "HOME").map(PathBuf::from);
let path = match flag {
Some(path) => Some(path.to_path_buf()),
None => get(env, "GEOLITH_CONFIG").map(|path| path_of(home.as_deref(), &path)),
};
let path = path.map(|path| absolute_in(cwd, path));
let text = match &path {
Some(path) if path.is_file() => Some(
fs::read_to_string(path)
.io_step(format!("reading the config file {}", path.display()))?,
),
Some(path) => {
return Err(DatasetError::config(format!(
"the config file {} does not exist (--config or GEOLITH_CONFIG); see {EXAMPLE_FILE}",
path.display()
)));
}
None => None,
};
let mut deployment = Self::resolve(path.as_deref(), text.as_deref(), env)?;
deployment.env_file = env_file;
Ok(deployment)
}
pub fn resolve(source: Option<&Path>, text: Option<&str>, env: Env<'_>) -> Result<Self> {
let file: FileSettings = match (text, source) {
(Some(text), Some(path)) => serde_json::from_str(text)
.json_of(format!("parsing the config file {}", path.display()))?,
(Some(text), None) => serde_json::from_str(text).json_of("parsing the config file")?,
(None, _) => FileSettings::default(),
};
let home = get(env, "HOME").map(PathBuf::from);
let home_ref = home.as_deref();
let path_in = |env_names: &[&str], file: Option<&String>| -> Option<PathBuf> {
first(env, env_names)
.or_else(|| file.filter(|text| !text.is_empty()).cloned())
.map(|text| path_of(home_ref, &text))
};
let text_in = |env_names: &[&str], file: Option<&String>| -> Option<String> {
first(env, env_names).or_else(|| file.filter(|text| !text.is_empty()).cloned())
};
let prefix = text_in(&["DATASETS_KEY_PREFIX"], file.storage.prefix.as_ref())
.map(|text| normalize_prefix(&text))
.transpose()?;
let endpoint = text_in(&["DATASETS_R2_ENDPOINT"], file.storage.endpoint.as_ref());
if let Some(endpoint) = &endpoint
&& !is_http_url(endpoint)
{
return Err(DatasetError::config(format!(
"storage.endpoint \"{endpoint}\" is not an http(s) URL"
)));
}
let bucket = text_in(&["DATASETS_BUCKET"], file.storage.bucket.as_ref());
if let Some(bucket) = &bucket
&& (bucket.contains('/') || bucket.contains(char::is_whitespace))
{
return Err(DatasetError::config(format!(
"storage.bucket \"{bucket}\" is not a bucket name"
)));
}
let account_id = text_in(
&["DATASETS_R2_ACCOUNT", "GEOLITH_R2_ACCOUNT"],
file.storage.account_id.as_ref(),
);
if let Some(account) = &account_id
&& (account.contains('.') || account.contains('/'))
{
return Err(DatasetError::config(format!(
"storage.account_id \"{account}\" is not an account id"
)));
}
let storage = StorageSettings {
endpoint,
region: text_in(&["DATASETS_R2_REGION"], file.storage.region.as_ref()),
bucket,
prefix,
account_id,
credentials_file: path_in(
&["DATASETS_R2_ENV_FILE"],
file.storage.credentials_file.as_ref(),
),
env_credentials: first(env, &KEY_ID_NAMES)
.zip(first(env, &SECRET_NAMES))
.map(|(key_id, secret)| Credentials { key_id, secret }),
};
let pointer_url = text_in(&["DATASETS_POINTER_URL"], file.publish.pointer_url.as_ref());
if let Some(url) = &pointer_url {
check_template("publish.pointer_url", url)?;
}
let page_url = text_in(&["DATASETS_PAGE_URL"], file.publish.page_url.as_ref());
if let Some(url) = &page_url {
check_template("publish.page_url", url)?;
}
let publish = PublishSettings {
pointer_url,
page_url,
credentials_file: path_in(
&["DATASETS_SITE_KEY_FILE"],
file.publish.credentials_file.as_ref(),
),
api_key: get(env, "DATASETS_API_KEY"),
};
let chirps_hosts = match get(env, "CHIRPS_HOSTS") {
Some(hosts) => hosts.split_whitespace().map(str::to_owned).collect(),
None => file.sources.chirps_hosts.clone().unwrap_or_default(),
};
let sources = SourceSettings {
chirps_hosts,
cdse_stac: text_in(&["CDSE_STAC"], file.sources.cdse_stac.as_ref()),
cdse_endpoint: text_in(&["CDSE_S3_ENDPOINT"], file.sources.cdse_endpoint.as_ref()),
cdse_credentials_file: path_in(
&["CDSE_ENV_FILE"],
file.sources.cdse_credentials_file.as_ref(),
),
cdse_env_credentials: get(env, "CDSE_S3_ACCESS_KEY")
.zip(get(env, "CDSE_S3_SECRET_KEY"))
.map(|(key_id, secret)| Credentials { key_id, secret }),
boundaries_url_base: text_in(
&["BOUNDARIES_URL_BASE"],
file.sources.boundaries_url_base.as_ref(),
),
};
let probe_timeout_ms = match get(env, "DATASETS_PROBE_TIMEOUT_MS") {
Some(text) => Some(text.parse::<u64>().number_of({
format!("DATASETS_PROBE_TIMEOUT_MS \"{text}\" is not a number of milliseconds")
})?),
None => None,
};
let min_free_gb = match get(env, "DATASETS_MIN_FREE_GB") {
Some(text) => Some(text.trim().parse::<u64>().number_of({
format!("DATASETS_MIN_FREE_GB \"{text}\" is not a number of gigabytes")
})?),
None => None,
};
let run = RunSettings {
dataset: get(env, "DATASET"),
country: get(env, "COUNTRY").map(|cc| cc.trim().to_owned()),
country_config: get(env, "COUNTRY_CONFIG").map(PathBuf::from),
boundary_release: first(env, &["BOUNDARY_RELEASE", "OVERTURE_RELEASE"]),
boundary_tiles_revision: get(env, "BOUNDARY_TILES_REVISION"),
baseline: get(env, "BASELINE"),
published_csv: get(env, "PUBLISHED_CSV").map(PathBuf::from),
areas_dir: get(env, "GEOLITH_AREAS_DIR").map(PathBuf::from),
crosswalk_csv: env("CROSSWALK_CSV").map(PathBuf::from),
lgd_dir: get(env, "LGD_DIR").map(PathBuf::from),
cdse_today: get(env, "CDSE_TODAY"),
probe_timeout_ms,
hostname: get(env, "HOSTNAME"),
min_free_gb,
};
let macos_notification = if env("DATASETS_REFRESH_NO_ALERT").is_some() {
false
} else {
match get(env, "DATASETS_MACOS_NOTIFICATION") {
Some(text) => parse_bool("DATASETS_MACOS_NOTIFICATION", &text)?,
None => file.alerts.macos_notification.unwrap_or(true),
}
};
Ok(Self {
config_file: source.map(Path::to_path_buf),
env_file: None,
path: get(env, "PATH"),
data_root: path_in(&["DATA_ROOT"], file.data_root.as_ref()),
repo: path_in(&["GEOLITH_REPO"], file.repo.as_ref()),
home,
storage,
publish,
sources,
macos_notification,
run,
})
}
#[must_use]
pub fn key_root(&self) -> &str {
self.storage.prefix.as_deref().unwrap_or(DEFAULT_KEY_PREFIX)
}
pub fn target(&self) -> Result<Target> {
let endpoint = self
.storage
.endpoint
.clone()
.ok_or_else(|| missing("storage.endpoint", "DATASETS_R2_ENDPOINT"))?;
let bucket = self
.storage
.bucket
.clone()
.ok_or_else(|| missing("storage.bucket", "DATASETS_BUCKET"))?;
if let Some(account) = &self.storage.account_id {
let host = url_host(&endpoint);
if host.split('.').next() != Some(account.as_str()) {
return Err(DatasetError::config(format!(
"endpoint host {host} is not of storage.account_id"
)));
}
}
Ok(Target {
endpoint,
region: self
.storage
.region
.clone()
.unwrap_or_else(|| DEFAULT_REGION.to_owned()),
bucket,
key_root: self.key_root().to_owned(),
})
}
pub fn storage_credentials(&self) -> Result<Credentials> {
if let Some(pair) = &self.storage.env_credentials {
return Ok(pair.clone());
}
let Some(path) = &self.storage.credentials_file else {
return Err(DatasetError::config(format!(
"storage credentials are not set: name a storage.credentials_file or set \
GEOLITH_STORAGE_ACCESS_KEY_ID and GEOLITH_STORAGE_SECRET_ACCESS_KEY; see \
{EXAMPLE_FILE}"
)));
};
let values = read_env_file(path)?;
pair_of(&values).ok_or_else(|| {
DatasetError::config({
format!(
"{} holds no access key id and secret (GEOLITH_STORAGE_ACCESS_KEY_ID and \
GEOLITH_STORAGE_SECRET_ACCESS_KEY)",
path.display()
)
})
})
}
pub fn publish_key(&self) -> Result<Option<String>> {
if let Some(key) = &self.publish.api_key {
return Ok(Some(key.clone()));
}
let Some(path) = &self.publish.credentials_file else {
return Ok(None);
};
let values = read_env_file(path)?;
values
.get("DATASETS_API_KEY")
.filter(|key| !key.is_empty())
.cloned()
.map(Some)
.ok_or_else(|| {
DatasetError::config(format!("{} holds no DATASETS_API_KEY", path.display()))
})
}
#[must_use]
pub fn publish_urls(
&self,
dataset: &str,
country: &str,
build_id: &str,
) -> (Option<String>, Option<String>) {
let fill = |template: &Option<String>| {
template
.as_deref()
.map(|template| fill_template(template, dataset, country, build_id))
};
(
fill(&self.publish.pointer_url),
fill(&self.publish.page_url),
)
}
pub fn cdse_credentials(&self) -> Result<Option<Credentials>> {
if let Some(pair) = &self.sources.cdse_env_credentials {
return Ok(Some(pair.clone()));
}
let Some(path) = self.sources.cdse_credentials_file.as_deref() else {
return Ok(None);
};
if !path.is_file() {
return Ok(None);
}
let values = read_env_file(path)?;
Ok(values
.get("CDSE_S3_ACCESS_KEY")
.zip(values.get("CDSE_S3_SECRET_KEY"))
.filter(|(key_id, secret)| !key_id.is_empty() && !secret.is_empty())
.map(|(key_id, secret)| Credentials {
key_id: key_id.clone(),
secret: secret.clone(),
}))
}
}
static CURRENT: OnceLock<Deployment> = OnceLock::new();
pub fn init(deployment: Deployment) {
let _ = CURRENT.set(deployment);
}
#[must_use]
pub fn current() -> &'static Deployment {
CURRENT.get_or_init(|| Deployment::resolve(None, None, &process_env).unwrap_or_default())
}
#[cfg(test)]
mod tests {
use super::*;
fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> + use<> {
let map: BTreeMap<String, String> = pairs
.iter()
.map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
.collect();
move |name| map.get(name).cloned()
}
const FILE: &str = r#"{
"data_root": "/srv/data",
"storage": {
"endpoint": "http://127.0.0.1:9000",
"region": "eu-test-1",
"bucket": "made-up-bucket",
"prefix": "mirror/ds",
"credentials_file": "~/keys/store.env"
},
"publish": {
"pointer_url": "https://api.example.test/v1/{dataset}/{country}/current.json",
"page_url": "https://example.test/data/{country}/{dataset}"
},
"sources": {"chirps_hosts": ["https://a.example.test", "https://b.example.test"]},
"alerts": {"macos_notification": false}
}"#;
#[test]
fn the_file_fills_every_section() {
let env = env_of(&[("HOME", "/home/op")]);
let d = Deployment::resolve(None, Some(FILE), &env).expect("resolves");
assert_eq!(d.data_root, Some(PathBuf::from("/srv/data")));
assert_eq!(d.key_root(), "mirror/ds/");
assert_eq!(
d.storage.credentials_file,
Some(PathBuf::from("/home/op/keys/store.env"))
);
assert_eq!(d.sources.chirps_hosts.len(), 2);
assert!(!d.macos_notification);
let target = d.target().expect("a full storage section");
assert_eq!(
target,
Target {
endpoint: "http://127.0.0.1:9000".to_owned(),
region: "eu-test-1".to_owned(),
bucket: "made-up-bucket".to_owned(),
key_root: "mirror/ds/".to_owned(),
}
);
}
#[test]
fn an_environment_value_beats_the_file() {
let env = env_of(&[
("DATASETS_BUCKET", "env-bucket"),
("DATA_ROOT", "/env/root"),
("DATASETS_KEY_PREFIX", "env-prefix/"),
]);
let d = Deployment::resolve(None, Some(FILE), &env).expect("resolves");
let target = d.target().expect("target");
assert_eq!(target.bucket, "env-bucket");
assert_eq!(target.key_root, "env-prefix/");
assert_eq!(d.data_root, Some(PathBuf::from("/env/root")));
assert_eq!(target.endpoint, "http://127.0.0.1:9000");
}
#[test]
fn an_empty_deployment_has_neutral_defaults_and_names_what_is_missing() {
let d = Deployment::resolve(None, None, &env_of(&[])).expect("resolves");
assert_eq!(d.key_root(), "datasets/");
assert!(d.macos_notification);
let error = d.target().unwrap_err().to_string();
assert!(
error.contains("storage.endpoint is not set; see geolith.example.json"),
"{error}"
);
let mut half = d.clone();
half.storage.endpoint = Some("http://127.0.0.1:9000".to_owned());
let error = half.target().unwrap_err().to_string();
assert!(
error.contains("storage.bucket is not set; see geolith.example.json"),
"{error}"
);
assert!(d.storage_credentials().is_err());
assert_eq!(d.publish_urls("rainfall", "in", "b"), (None, None));
}
#[test]
fn a_bad_value_is_refused_by_name() {
let refused = |json: &str| {
geolith::error::report(
&Deployment::resolve(None, Some(json), &env_of(&[])).unwrap_err(),
)
};
assert!(refused(r#"{"storage":{"endpoint":"ftp://x"}}"#).contains("storage.endpoint"));
assert!(refused(r#"{"storage":{"prefix":"a/../b"}}"#).contains("storage.prefix"));
assert!(refused(r#"{"storage":{"bucket":"a/b"}}"#).contains("storage.bucket"));
assert!(refused(r#"{"storage":{"account_id":"a.b"}}"#).contains("storage.account_id"));
assert!(
refused(r#"{"publish":{"pointer_url":"https://x/{nope}"}}"#)
.contains("unknown placeholder {nope}")
);
assert!(refused(r#"{"publish":{"page_url":"x"}}"#).contains("publish.page_url"));
assert!(refused(r#"{"storage":{"bucket_name":"x"}}"#).contains("bucket_name"));
let error = Deployment::resolve(
None,
None,
&env_of(&[("DATASETS_PROBE_TIMEOUT_MS", "soon")]),
)
.unwrap_err()
.to_string();
assert!(error.contains("DATASETS_PROBE_TIMEOUT_MS"), "{error}");
}
#[test]
fn the_account_guard_refuses_a_host_of_another_account() {
let json = r#"{"storage":{"endpoint":"https://acct1.store.example.test",
"bucket":"b","account_id":"acct1"}}"#;
let d = Deployment::resolve(None, Some(json), &env_of(&[])).expect("resolves");
assert!(d.target().is_ok());
let other = r#"{"storage":{"endpoint":"https://acct2.store.example.test",
"bucket":"b","account_id":"acct1"}}"#;
let d = Deployment::resolve(None, Some(other), &env_of(&[])).expect("resolves");
let error = d.target().unwrap_err().to_string();
assert!(error.contains("acct2.store.example.test"), "{error}");
assert!(error.contains("storage.account_id"), "{error}");
}
#[test]
fn only_the_configured_bucket_passes_the_guard() {
let d = Deployment::resolve(None, Some(FILE), &env_of(&[])).expect("resolves");
let target = d.target().expect("target");
assert!(target.check_bucket("made-up-bucket").is_ok());
let error = target.check_bucket("other-bucket").unwrap_err().to_string();
assert!(error.contains("not storage.bucket"), "{error}");
assert!(target.check_bucket("").is_err());
}
#[test]
fn publish_urls_fill_their_placeholders() {
let d = Deployment::resolve(None, Some(FILE), &env_of(&[])).expect("resolves");
let (pointer, page) = d.publish_urls("ndvi", "us", "2026-11-20.20261120T0000Z");
assert_eq!(
pointer.as_deref(),
Some("https://api.example.test/v1/ndvi/us/current.json")
);
assert_eq!(page.as_deref(), Some("https://example.test/data/us/ndvi"));
}
#[test]
fn a_prefix_is_normalised_with_a_trailing_slash() {
assert_eq!(normalize_prefix("a/b").expect("ok"), "a/b/");
assert_eq!(normalize_prefix("/a/b/").expect("ok"), "a/b/");
assert!(normalize_prefix("").is_err());
assert!(normalize_prefix("/").is_err());
assert!(normalize_prefix("a b").is_err());
assert!(normalize_prefix("a//b").is_err());
}
fn secret_file(dir: &Path, name: &str, text: &str) -> PathBuf {
let path = dir.join(name);
fs::write(&path, text).expect("write");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("chmod");
}
path
}
#[test]
fn credentials_come_from_a_600_file_and_a_0644_one_is_refused() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = secret_file(
dir.path(),
"store.env",
"# keys\nexport GEOLITH_STORAGE_ACCESS_KEY_ID=\"kid\"\nGEOLITH_STORAGE_SECRET_ACCESS_KEY=sec\n",
);
let json = format!(
r#"{{"storage":{{"credentials_file":"{}"}}}}"#,
path.display()
);
let d = Deployment::resolve(None, Some(&json), &env_of(&[])).expect("resolves");
let pair = d.storage_credentials().expect("pair");
assert_eq!((pair.key_id.as_str(), pair.secret.as_str()), ("kid", "sec"));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).expect("chmod");
let error = d.storage_credentials().unwrap_err().to_string();
assert!(error.contains("chmod 600"), "{error}");
}
}
#[test]
fn an_rclone_remote_file_supplies_the_pair_whatever_the_remote_is_called() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = secret_file(
dir.path(),
"rclone.env",
"RCLONE_CONFIG_MYSTORE_ENDPOINT=https://elsewhere.test\n\
RCLONE_CONFIG_MYSTORE_ACCESS_KEY_ID=rid\n\
RCLONE_CONFIG_MYSTORE_SECRET_ACCESS_KEY=rsecret\n",
);
let values = read_env_file(&path).expect("pairs");
let pair = pair_of(&values).expect("pair");
assert_eq!(
(pair.key_id.as_str(), pair.secret.as_str()),
("rid", "rsecret")
);
}
#[test]
fn environment_credentials_win_over_the_file() {
let env = env_of(&[
("GEOLITH_STORAGE_ACCESS_KEY_ID", "envid"),
("GEOLITH_STORAGE_SECRET_ACCESS_KEY", "envsecret"),
]);
let d = Deployment::resolve(None, Some(FILE), &env).expect("resolves");
assert_eq!(d.storage_credentials().expect("pair").key_id, "envid");
}
#[test]
fn the_publish_key_is_read_from_its_file_and_absent_without_one() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = secret_file(dir.path(), "site.env", "OTHER=1\nDATASETS_API_KEY=abc\n");
let json = format!(
r#"{{"publish":{{"credentials_file":"{}"}}}}"#,
path.display()
);
let d = Deployment::resolve(None, Some(&json), &env_of(&[])).expect("resolves");
assert_eq!(d.publish_key().expect("key").as_deref(), Some("abc"));
let none = Deployment::resolve(None, None, &env_of(&[])).expect("resolves");
assert_eq!(none.publish_key().expect("no key"), None);
}
#[test]
fn a_named_config_file_must_exist_and_nothing_under_home_is_read_by_default() {
let dir = tempfile::tempdir().expect("a temp dir");
let cwd = tempfile::tempdir().expect("an empty working dir");
let home = dir.path().display().to_string();
let env = env_of(&[("HOME", &home)]);
let missing = dir.path().join("nope.json");
let error = Deployment::load_with(Some(&missing), &env, cwd.path())
.unwrap_err()
.to_string();
assert!(error.contains("nope.json"), "{error}");
let old = dir.path().join(".config").join("geolith");
fs::create_dir_all(&old).expect("mkdir");
fs::write(
old.join("geolith.json"),
r#"{"storage":{"bucket":"from-home"}}"#,
)
.expect("write");
secret_file(
&old,
"cdse.env",
"CDSE_S3_ACCESS_KEY=a\nCDSE_S3_SECRET_KEY=b\n",
);
let d = Deployment::load_with(None, &env, cwd.path()).expect("no file is fine");
assert!(d.config_file.is_none());
assert!(d.env_file.is_none());
assert_eq!(d.storage.bucket, None);
assert_eq!(d.sources.cdse_credentials_file, None);
assert_eq!(d.cdse_credentials().expect("no keys"), None);
let named = dir.path().join("named.json");
fs::write(&named, r#"{"storage":{"bucket":"from-flag"}}"#).expect("write");
let d = Deployment::load_with(Some(&named), &env, cwd.path()).expect("flag file");
assert_eq!(d.storage.bucket.as_deref(), Some("from-flag"));
assert_eq!(d.config_file.as_deref(), Some(named.as_path()));
let env_named = named.display().to_string();
let env = env_of(&[("HOME", &home), ("GEOLITH_CONFIG", &env_named)]);
let d = Deployment::load_with(None, &env, cwd.path()).expect("env file");
assert_eq!(d.storage.bucket.as_deref(), Some("from-flag"));
}
#[test]
fn the_env_file_sits_between_the_process_and_the_json() {
let cwd = tempfile::tempdir().expect("a working dir");
secret_file(
cwd.path(),
".env",
"# operator values\nRELEASE_PAT=unrelated\nDATASETS_BUCKET=dotenv-bucket\n\
DATA_ROOT=/dotenv/root\nexport GEOLITH_STORAGE_ACCESS_KEY_ID=\"dkid\"\n\
GEOLITH_STORAGE_SECRET_ACCESS_KEY='dsecret'\nDATASETS_API_KEY=dkey\n",
);
let json = cwd.path().join("geolith.json");
fs::write(
&json,
r#"{"storage":{"endpoint":"http://127.0.0.1:9000","bucket":"json-bucket"},
"data_root":"/json/root","repo":"/json/repo"}"#,
)
.expect("write");
let env = env_of(&[("DATA_ROOT", "/process/root")]);
let d = Deployment::load_with(Some(&json), &env, cwd.path()).expect("resolves");
assert_eq!(
d.env_file.as_deref(),
Some(cwd.path().join(".env").as_path())
);
assert_eq!(d.data_root, Some(PathBuf::from("/process/root")));
assert_eq!(d.storage.bucket.as_deref(), Some("dotenv-bucket"));
assert_eq!(d.storage.endpoint.as_deref(), Some("http://127.0.0.1:9000"));
assert_eq!(d.repo, Some(PathBuf::from("/json/repo")));
let pair = d.storage_credentials().expect("pair from .env");
assert_eq!(
(pair.key_id.as_str(), pair.secret.as_str()),
("dkid", "dsecret")
);
assert_eq!(d.publish_key().expect("key").as_deref(), Some("dkey"));
let env = env_of(&[("DATASETS_BUCKET", "")]);
let d = Deployment::load_with(None, &env, cwd.path()).expect("resolves");
assert_eq!(d.storage.bucket, None);
}
#[test]
fn geolith_env_file_names_the_file_and_must_exist() {
let cwd = tempfile::tempdir().expect("a working dir");
let other = tempfile::tempdir().expect("another dir");
secret_file(cwd.path(), ".env", "DATASETS_BUCKET=cwd-bucket\n");
let named = secret_file(other.path(), "ops.env", "DATASETS_BUCKET=named-bucket\n");
let named_text = named.display().to_string();
let env = env_of(&[("GEOLITH_ENV_FILE", &named_text)]);
let d = Deployment::load_with(None, &env, cwd.path()).expect("resolves");
assert_eq!(d.storage.bucket.as_deref(), Some("named-bucket"));
assert_eq!(d.env_file.as_deref(), Some(named.as_path()));
let home = other.path().display().to_string();
let env = env_of(&[("HOME", &home), ("GEOLITH_ENV_FILE", "~/ops.env")]);
let d = Deployment::load_with(None, &env, cwd.path()).expect("resolves");
assert_eq!(d.storage.bucket.as_deref(), Some("named-bucket"));
let gone = other.path().join("gone.env").display().to_string();
let env = env_of(&[("GEOLITH_ENV_FILE", &gone)]);
let error = Deployment::load_with(None, &env, cwd.path())
.unwrap_err()
.to_string();
assert!(error.contains("gone.env"), "{error}");
assert!(error.contains("GEOLITH_ENV_FILE"), "{error}");
}
#[cfg(unix)]
#[test]
fn an_env_file_wider_than_600_is_refused_and_a_narrower_one_read() {
use std::os::unix::fs::PermissionsExt as _;
let cwd = tempfile::tempdir().expect("a working dir");
let path = secret_file(cwd.path(), ".env", "DATASETS_BUCKET=b\n");
fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).expect("chmod");
let error = format!(
"{:#}",
Deployment::load_with(None, &env_of(&[]), cwd.path()).unwrap_err()
);
assert!(error.contains("mode 640"), "{error}");
assert!(error.contains("chmod 600"), "{error}");
assert!(!error.contains("DATASETS_BUCKET=b"), "{error}");
fs::set_permissions(&path, fs::Permissions::from_mode(0o400)).expect("chmod");
let d = Deployment::load_with(None, &env_of(&[]), cwd.path()).expect("0400 is read");
assert_eq!(d.storage.bucket.as_deref(), Some("b"));
}
#[test]
fn only_owner_read_and_write_pass_the_mode_check() {
for (mode, wide) in [
(0o600, false),
(0o400, false),
(0o200, false),
(0o000, false),
(0o700, true),
(0o640, true),
(0o604, true),
(0o644, true),
(0o666, true),
] {
assert_eq!(wider_than_600(mode), wide, "mode {mode:o}");
}
}
#[test]
fn every_json_field_has_an_environment_name() {
let env = env_of(&[
("DATA_ROOT", "/e/data"),
("GEOLITH_REPO", "/e/repo"),
("DATASETS_R2_ENDPOINT", "https://acct9.store.example.test"),
("DATASETS_R2_REGION", "auto"),
("DATASETS_BUCKET", "e-bucket"),
("DATASETS_KEY_PREFIX", "e/p"),
("DATASETS_R2_ACCOUNT", "acct9"),
("DATASETS_R2_ENV_FILE", "/e/store.env"),
(
"DATASETS_POINTER_URL",
"https://api.e.test/{dataset}/{country}",
),
("DATASETS_PAGE_URL", "https://e.test/{country}/{dataset}"),
("DATASETS_SITE_KEY_FILE", "/e/site.env"),
("CHIRPS_HOSTS", "https://c1.e.test https://c2.e.test"),
("CDSE_STAC", "https://stac.e.test"),
("CDSE_S3_ENDPOINT", "https://s3.e.test"),
("CDSE_ENV_FILE", "/e/cdse.env"),
("BOUNDARIES_URL_BASE", "https://b.e.test"),
("DATASETS_MACOS_NOTIFICATION", "false"),
]);
let d = Deployment::resolve(None, None, &env).expect("resolves");
assert_eq!(d.data_root, Some(PathBuf::from("/e/data")));
assert_eq!(d.repo, Some(PathBuf::from("/e/repo")));
assert_eq!(
d.target().expect("target"),
Target {
endpoint: "https://acct9.store.example.test".to_owned(),
region: "auto".to_owned(),
bucket: "e-bucket".to_owned(),
key_root: "e/p/".to_owned(),
}
);
assert_eq!(d.storage.account_id.as_deref(), Some("acct9"));
assert_eq!(
d.storage.credentials_file,
Some(PathBuf::from("/e/store.env"))
);
assert_eq!(
d.publish_urls("rainfall", "in", "x"),
(
Some("https://api.e.test/rainfall/in".to_owned()),
Some("https://e.test/in/rainfall".to_owned())
)
);
assert_eq!(
d.publish.credentials_file,
Some(PathBuf::from("/e/site.env"))
);
assert_eq!(
d.sources.chirps_hosts,
vec!["https://c1.e.test", "https://c2.e.test"]
);
assert_eq!(d.sources.cdse_stac.as_deref(), Some("https://stac.e.test"));
assert_eq!(
d.sources.cdse_endpoint.as_deref(),
Some("https://s3.e.test")
);
assert_eq!(
d.sources.cdse_credentials_file,
Some(PathBuf::from("/e/cdse.env"))
);
assert_eq!(
d.sources.boundaries_url_base.as_deref(),
Some("https://b.e.test")
);
assert!(!d.macos_notification);
}
#[test]
fn the_notification_switch_reads_its_env_name_and_no_alert_wins() {
let on = r#"{"alerts":{"macos_notification":true}}"#;
let resolve = |pairs: &[(&str, &str)]| Deployment::resolve(None, Some(on), &env_of(pairs));
assert!(resolve(&[]).expect("file").macos_notification);
assert!(
!resolve(&[("DATASETS_MACOS_NOTIFICATION", "No")])
.expect("env")
.macos_notification
);
let off = r#"{"alerts":{"macos_notification":false}}"#;
let d = Deployment::resolve(
None,
Some(off),
&env_of(&[("DATASETS_MACOS_NOTIFICATION", "1")]),
)
.expect("env over file");
assert!(d.macos_notification);
assert!(
!resolve(&[
("DATASETS_MACOS_NOTIFICATION", "true"),
("DATASETS_REFRESH_NO_ALERT", "")
])
.expect("silenced")
.macos_notification
);
let error = resolve(&[("DATASETS_MACOS_NOTIFICATION", "maybe")])
.unwrap_err()
.to_string();
assert!(error.contains("DATASETS_MACOS_NOTIFICATION"), "{error}");
}
#[test]
fn no_other_module_reads_the_environment() {
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in fs::read_dir(dir).expect("read_dir") {
let path = entry.expect("entry").path();
if path.is_dir() {
walk(&path, out);
} else if path.extension().is_some_and(|ext| ext == "rs") {
out.push(path);
}
}
}
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut files = Vec::new();
walk(&root, &mut files);
assert!(files.len() > 30, "found only {} files", files.len());
let needle = ["env", "::var"].concat();
let offenders: Vec<String> = files
.iter()
.filter(|path| path.file_name().is_some_and(|name| name != "settings.rs"))
.filter(|path| {
fs::read_to_string(path)
.expect("read")
.contains(needle.as_str())
})
.map(|path| path.display().to_string())
.collect();
assert!(
offenders.is_empty(),
"read the environment through dataset::settings: {offenders:?}"
);
}
}