shep-macros 0.6.2

The DogConfig derive for shep plugins: marks a config field as a credential so shep renders it redacted
Documentation
//! The `DogConfig` derive, and nothing else.
//!
//! A dog publishes a JSON Schema for its config so shep can render a
//! settings pane. One field kind needs marking: a credential, shown
//! as `<set>` rather than its value. `schemars` can mark that by hand
//! with `#[schemars(extend("x-shep-secret" = true))]`. But the key is
//! a string an author can misspell silently. This derive turns that
//! into a compile error.
//!
//! Depend on `shep-client`, not this crate: it re-exports the derive
//! next to the `DogConfig` trait it implements.

#![forbid(unsafe_code)]

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{Attribute, Data, DeriveInput, Field, Meta, Token, parse_macro_input};

/// The attribute this derive claims. Only `#[shep(secret)]` is spelled with
/// it today.
const ATTR: &str = "shep";

/// The one option `#[shep(...)]` accepts.
const SECRET: &str = "secret";

/// Marks which of a dog's config fields are credentials, so shep can redact
/// them without the dog author ever typing the extension key that says so.
///
/// Derive it on the type a dog deserializes its config into, alongside
/// `schemars::JsonSchema`, and mark each credential field with
/// `#[shep(secret)]`. A struct and an enum both work, and the enum matters:
/// a bark sink is one, tagged by kind, with a webhook URL in every variant.
///
/// ```rust
/// use shep_client::dogs::DogConfig;
///
/// #[derive(serde::Deserialize, schemars::JsonSchema, DogConfig)]
/// #[serde(tag = "kind", rename_all = "snake_case")]
/// enum Sink {
///     Discord {
///         #[shep(secret)]
///         url: String,
///     },
///     Slack {
///         #[shep(secret)]
///         url: String,
///     },
/// }
///
/// // One name, not two: see below.
/// assert_eq!(Sink::SECRET_FIELDS, ["url"]);
/// ```
///
/// That example runs, which needs `shep-client` as a dev-dependency
/// of this crate. A cycle on paper, allowed since dev-dependencies
/// sit outside the library build graph. The derive's behaviour is
/// tested in `shep-client`, where the marking happens.
///
/// # What it expands to
///
/// An `impl shep_client::dogs::DogConfig`, carrying the names of the marked
/// fields and the extension key that marks them. The key comes from
/// `shep_core::dogs::SECRET_KEY` by way of `shep_client`'s re-export.
/// It is never spelled out here or in the dog:
///
/// ```rust,ignore
/// impl ::shep_client::dogs::DogConfig for Sink {
///     const SECRET_KEY: &'static str = ::shep_client::dogs::SECRET_KEY;
///     const SECRET_FIELDS: &'static [&'static str] = &["url"];
/// }
/// ```
///
/// One `"url"`, not two, for the two variants above. The list is
/// names, and a name repeated across variants is one name.
/// `schemars` builds a `oneOf`, one object per variant with its own
/// `properties`, for a tagged enum. A mark has to reach every
/// occurrence of the name, not a single top-level property.
///
/// # Renames
///
/// A field is named here by its Rust identifier. A
/// `#[serde(rename)]` on a marked field changes what the schema
/// calls it. The marker would then have no property to land on.
/// That is caught where the marking happens, in `shep_client`. It
/// refuses a name it cannot find rather than passing an unmarked
/// credential on.
///
/// A `#[serde(rename_all)]` on a tagged enum renames the variants,
/// not their fields, so a `url` inside one stays `url`.
///
/// # Compile errors
///
/// Deliberate refusals, each with its own message:
///
/// - `#[shep(secret)]` on an unnamed field (tuple struct or variant),
///   with no schema property to mark;
/// - `#[shep(...)]` on the type or on a variant, neither of which is a field;
/// - a union, which has no serde representation to build a schema from;
/// - `#[shep]` with no option in parentheses;
/// - `#[shep(secret = ...)]`, since `secret` is a flag and takes no value;
/// - any option other than `secret`, rejected as a likely misspelling of it.
///
/// A struct or variant with no fields, an unmarked tuple, and a
/// unit-variant enum are accepted and carry no marks. A dog whose config
/// holds no credential still wants the impl.
#[proc_macro_derive(DogConfig, attributes(shep))]
pub fn derive_dog_config(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand(&input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// The derive's whole body, in a form that can return an error instead of
/// a token stream.
fn expand(input: &DeriveInput) -> syn::Result<TokenStream2> {
    if let Some(attr) = find_shep_attribute(&input.attrs) {
        return Err(syn::Error::new_spanned(
            attr,
            "`#[shep(secret)]` marks a field, not the type: move it onto the \
             field that holds the credential",
        ));
    }

    let mut secrets: Vec<String> = Vec::new();
    for field in fields_of(input)? {
        if !is_secret(field)? {
            continue;
        }
        let Some(ident) = &field.ident else {
            return Err(syn::Error::new_spanned(
                field,
                "`#[shep(secret)]` cannot mark an unnamed field: a JSON Schema \
                 property has a name and this field has none, so the mark would \
                 have nothing to land on. Name the field.",
            ));
        };
        let name = ident.to_string();
        // Deduped rather than pushed blind. An internally tagged
        // enum repeats a field name across variants, like a bark
        // sink's `url`. The list holds names to look for, not
        // places to look.
        if !secrets.contains(&name) {
            secrets.push(name);
        }
    }

    let name = &input.ident;
    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
    Ok(quote! {
        impl #impl_generics ::shep_client::dogs::DogConfig for #name #ty_generics #where_clause {
            const SECRET_KEY: &'static str = ::shep_client::dogs::SECRET_KEY;
            const SECRET_FIELDS: &'static [&'static str] = &[#(#secrets),*];
        }
    })
}

/// Every field the type has, a struct's directly and an enum's
/// gathered from its variants.
///
/// Unit variants and unmarked tuples have no fields to collect, so they
/// come back empty. A union is refused outright: it has no serde
/// representation for a mark to land on. [`expand`] checks each
/// collected field once it knows which carry a mark.
fn fields_of(input: &DeriveInput) -> syn::Result<Vec<&Field>> {
    match &input.data {
        Data::Struct(data) => Ok(data.fields.iter().collect()),
        Data::Enum(data) => {
            let mut fields = Vec::new();
            for variant in &data.variants {
                if let Some(attr) = find_shep_attribute(&variant.attrs) {
                    return Err(syn::Error::new_spanned(
                        attr,
                        "`#[shep(secret)]` marks a field, not a variant: move \
                         it onto the field inside that holds the credential",
                    ));
                }
                fields.extend(variant.fields.iter());
            }
            Ok(fields)
        }
        Data::Union(_) => Err(syn::Error::new_spanned(
            &input.ident,
            "`DogConfig` cannot be derived for a union: a union has no serde \
             representation, so there is no schema for a mark to go into",
        )),
    }
}

/// Whether a field carries `#[shep(secret)]`.
///
/// Repeating the attribute on one field is accepted and marks it
/// once. It is redundant rather than wrong. A second error message
/// would be noise next to the one that matters: a misspelled option.
fn is_secret(field: &Field) -> syn::Result<bool> {
    let mut secret = false;
    for attr in &field.attrs {
        if !attr.path().is_ident(ATTR) {
            continue;
        }
        if !matches!(attr.meta, Meta::List(_)) {
            return Err(syn::Error::new_spanned(
                attr,
                "`#[shep]` needs an option in parentheses: the only one is \
                 `secret`, as in `#[shep(secret)]`",
            ));
        }
        attr.parse_nested_meta(|meta| {
            if !meta.path.is_ident(SECRET) {
                return Err(meta.error(
                    "unknown `shep` option: the only one is `secret`, as in \
                     `#[shep(secret)]`",
                ));
            }
            if meta.input.peek(Token![=]) {
                return Err(meta.error(
                    "`secret` is a flag and takes no value: write \
                     `#[shep(secret)]`",
                ));
            }
            secret = true;
            Ok(())
        })?;
    }
    Ok(secret)
}

/// The first `#[shep(...)]` in a list, for the places one does not belong.
fn find_shep_attribute(attrs: &[Attribute]) -> Option<&Attribute> {
    attrs.iter().find(|attr| attr.path().is_ident(ATTR))
}