use std::io::Write as _;
pub use shep_core::dogs::SECRET_KEY;
use shep_core::dogs::{SCHEMA_FLAG, SHEP_PROTOCOL_KEY, VERSION_FLAG};
pub use shep_macros::DogConfig;
pub trait DogConfig {
const SECRET_KEY: &'static str;
const SECRET_FIELDS: &'static [&'static str];
}
#[cfg(feature = "schema")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecretFieldMissing {
pub field: &'static str,
}
#[cfg(feature = "schema")]
impl core::fmt::Display for SecretFieldMissing {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"the field `{}` is marked `#[shep(secret)]` but this type's own \
schema has no property of that name, so the credential would go \
out unmarked. A `#[serde(rename)]` on the field, or a \
`rename_all_fields` on the type, renames the property and leaves \
the mark with nothing to land on.",
self.field
)
}
}
#[cfg(feature = "schema")]
impl core::error::Error for SecretFieldMissing {}
#[cfg(feature = "schema")]
pub fn config_schema<T: DogConfig + schemars::JsonSchema>()
-> Result<schemars::Schema, SecretFieldMissing> {
let mut schema = schemars::SchemaGenerator::default().into_root_schema_for::<T>();
let mut found: Vec<&'static str> = Vec::new();
if let Some(root) = schema.as_object_mut() {
mark_secrets_in_object(root, T::SECRET_FIELDS, T::SECRET_KEY, &mut found);
}
for field in T::SECRET_FIELDS {
if !found.contains(field) {
return Err(SecretFieldMissing { field });
}
}
Ok(schema)
}
#[cfg(feature = "schema")]
const DEFS: &str = "$defs";
#[cfg(feature = "schema")]
fn mark_secrets_in_object(
map: &mut serde_json::Map<String, serde_json::Value>,
secrets: &[&'static str],
key: &str,
found: &mut Vec<&'static str>,
) {
if let Some(serde_json::Value::Object(properties)) = map.get_mut("properties") {
for name in secrets {
if let Some(serde_json::Value::Object(property)) = properties.get_mut(*name) {
property.insert(key.to_owned(), serde_json::Value::Bool(true));
if !found.contains(name) {
found.push(name);
}
}
}
}
for (keyword, value) in map.iter_mut() {
if keyword == DEFS {
continue;
}
mark_secrets(value, secrets, key, found);
}
}
#[cfg(feature = "schema")]
fn mark_secrets(
node: &mut serde_json::Value,
secrets: &[&'static str],
key: &str,
found: &mut Vec<&'static str>,
) {
match node {
serde_json::Value::Object(map) => mark_secrets_in_object(map, secrets, key, found),
serde_json::Value::Array(items) => {
for item in items {
mark_secrets(item, secrets, key, found);
}
}
_ => {}
}
}
#[cfg(feature = "schema")]
pub fn probe<T: DogConfig + schemars::JsonSchema>(name: &str, version: &str) {
match first_argument().as_deref() {
Some(VERSION_FLAG) => answer(&version_answer(name, version)),
Some(SCHEMA_FLAG) => match schema_answer::<T>() {
Ok(json) => answer(&json),
Err(err) => {
eprintln!("{err}");
std::process::exit(1);
}
},
_ => (),
}
}
#[cfg(not(feature = "schema"))]
pub fn probe<T: DogConfig>(name: &str, version: &str) {
match first_argument().as_deref() {
Some(VERSION_FLAG) => answer(&version_answer(name, version)),
Some(SCHEMA_FLAG) => std::process::exit(0),
_ => (),
}
}
fn first_argument() -> Option<String> {
std::env::args().nth(1)
}
fn answer(text: &str) -> ! {
let mut stdout = std::io::stdout();
let _ = write!(stdout, "{text}");
let _ = stdout.flush();
std::process::exit(0);
}
fn version_answer(name: &str, version: &str) -> String {
format!(
"{name} {version}\n{SHEP_PROTOCOL_KEY}: {}\n",
crate::PROTOCOL_VERSION
)
}
#[cfg(feature = "schema")]
fn schema_answer<T: DogConfig + schemars::JsonSchema>() -> Result<String, SecretFieldMissing> {
let schema = config_schema::<T>()?;
let json = serde_json::to_string_pretty(&schema).expect("a schemars Schema always serializes");
Ok(format!("{json}\n"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_version_answer_parses_with_the_shepherds_own_parser() {
let answer = version_answer("shep-otel", "0.1.3");
let parsed = shep_core::dogs::parse_version_answer(&answer)
.expect("the answer shep's own parser cannot read is the bug this pins");
assert_eq!(parsed.version, "0.1.3");
assert_eq!(parsed.protocol, Some(crate::PROTOCOL_VERSION));
}
#[cfg(feature = "schema")]
mod schema {
use super::*;
#[derive(schemars::JsonSchema, DogConfig)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct Webhook {
#[shep(secret)]
url: String,
channel: String,
}
#[derive(schemars::JsonSchema, DogConfig)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
enum Sink {
Discord {
#[shep(secret)]
url: String,
quiet: bool,
},
Slack {
#[shep(secret)]
url: String,
},
}
#[derive(schemars::JsonSchema, DogConfig)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct Renamed {
#[shep(secret)]
#[serde(rename = "webhook_url")]
url: String,
}
#[derive(schemars::JsonSchema)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct Inner {
token: String,
}
#[derive(schemars::JsonSchema, DogConfig)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct Outer {
#[shep(secret)]
token: String,
inner: Inner,
}
#[derive(schemars::JsonSchema, DogConfig)]
#[allow(dead_code, reason = "read by the generated schema, not by Rust")]
struct RenamedOuter {
#[shep(secret)]
#[serde(rename = "api_token")]
token: String,
inner: Inner,
}
#[test]
fn a_secret_field_carries_the_marker_and_a_plain_one_does_not() {
let schema = config_schema::<Webhook>().expect("`url` is a real property");
let props = schema
.as_value()
.get("properties")
.expect("a derived struct schema has properties");
assert_eq!(
props.get("url").and_then(|url| url.get(SECRET_KEY)),
Some(&serde_json::Value::Bool(true)),
"the marked field carries the marker"
);
assert_eq!(
props.get("channel").and_then(|it| it.get(SECRET_KEY)),
None,
"the unmarked field carries nothing"
);
}
#[test]
fn a_marker_reaches_every_variant_of_a_tagged_enum_and_no_plain_field() {
let schema =
config_schema::<Sink>().expect("`url` is a real property in both variants");
let variants = schema
.as_value()
.get("oneOf")
.and_then(|it| it.as_array())
.expect("a tagged enum is a oneOf");
assert_eq!(variants.len(), 2);
for variant in variants {
let props = variant
.get("properties")
.expect("each variant carries its own properties");
assert_eq!(
props.get("url").and_then(|url| url.get(SECRET_KEY)),
Some(&serde_json::Value::Bool(true)),
"every occurrence of the marked name is marked"
);
assert_eq!(
props.get("quiet").and_then(|it| it.get(SECRET_KEY)),
None,
"a plain field in the same variant carries nothing"
);
}
}
#[test]
fn a_renamed_secret_field_is_an_error_rather_than_a_silent_pass() {
assert_eq!(
config_schema::<Renamed>(),
Err(SecretFieldMissing { field: "url" })
);
}
#[test]
fn a_like_named_property_of_a_nested_type_is_left_plain() {
let schema = config_schema::<Outer>().expect("`token` is a real property of the root");
let schema = schema.as_value();
assert_eq!(
schema.pointer("/properties/token/x-shep-secret"),
Some(&serde_json::Value::Bool(true)),
"the root's own marked field carries the marker"
);
assert_eq!(
schema.pointer("/$defs/Inner/properties/token/x-shep-secret"),
None,
"a stranger that shares the name is not the marked field"
);
}
#[test]
fn a_renamed_secret_field_is_an_error_even_when_a_nested_type_has_the_old_name() {
assert_eq!(
config_schema::<RenamedOuter>(),
Err(SecretFieldMissing { field: "token" })
);
}
}
}