secretspec_derive/lib.rs
1//! # SecretSpec Derive Macros
2//!
3//! This crate provides procedural macros for the SecretSpec library, enabling compile-time
4//! generation of strongly-typed secret structs from `secretspec.toml` configuration files.
5//!
6//! ## Overview
7//!
8//! The macro system reads your `secretspec.toml` at compile time and generates:
9//! - A `SecretSpec` struct with all secrets as fields (union of all profiles)
10//! - A `SecretSpecProfile` enum with profile-specific structs
11//! - A `Profile` enum representing available profiles
12//! - Type-safe loading methods with automatic validation
13//!
14//! ## Key Features
15//!
16//! - **Compile-time validation**: Invalid configurations are caught during compilation
17//! - **Type safety**: Secrets are accessed as struct fields, not strings
18//! - **Profile awareness**: Different types for different profiles (e.g., production vs development)
19//! - **Builder pattern**: Flexible configuration with method chaining
20//! - **Environment integration**: Automatic environment variable handling
21
22use proc_macro::TokenStream;
23use quote::{format_ident, quote};
24use secretspec::Config;
25use secretspec::codegen::{CodegenIr, IrField, build_ir, capitalize};
26use std::collections::{BTreeMap, HashSet};
27use syn::{LitStr, parse_macro_input};
28
29/// Holds metadata about a field in the generated struct.
30///
31/// This struct contains all the information needed to generate:
32/// - Struct field declarations
33/// - Field assignments from secret maps
34/// - Environment variable setters
35///
36/// # Fields
37///
38/// * `name` - The original secret name (e.g., "DATABASE_URL")
39/// * `field_type` - The Rust type for this field (String, PathBuf, or Option variants)
40/// * `is_optional` - Whether this field is optional across all profiles
41/// * `as_path` - Whether this field represents a path to a temporary file
42#[derive(Clone)]
43struct FieldInfo {
44 name: String,
45 field_type: proc_macro2::TokenStream,
46 is_optional: bool,
47 as_path: bool,
48}
49
50impl FieldInfo {
51 /// Creates a new FieldInfo instance.
52 ///
53 /// # Arguments
54 ///
55 /// * `name` - The secret name as defined in the config
56 /// * `field_type` - The generated Rust type (String, PathBuf, or Option variants)
57 /// * `is_optional` - Whether the field should be optional
58 /// * `as_path` - Whether this field represents a path to a temporary file
59 fn new(
60 name: String,
61 field_type: proc_macro2::TokenStream,
62 is_optional: bool,
63 as_path: bool,
64 ) -> Self {
65 Self {
66 name,
67 field_type,
68 is_optional,
69 as_path,
70 }
71 }
72
73 /// Build a `FieldInfo` from a shared-IR field. The IR is the single source
74 /// of the optionality/as_path decisions; this only maps them to a Rust type.
75 fn from_ir(field: &IrField) -> Self {
76 Self::new(
77 field.name.clone(),
78 ir_field_type(field),
79 field.optional,
80 field.as_path,
81 )
82 }
83
84 /// Get the field name as a Rust identifier.
85 ///
86 /// Converts the secret name to a valid Rust field name by:
87 /// - Converting to lowercase
88 /// - Preserving underscores
89 ///
90 /// # Example
91 ///
92 /// - "DATABASE_URL" becomes `database_url`
93 /// - "API_KEY" becomes `api_key`
94 fn field_name(&self) -> proc_macro2::Ident {
95 field_name_ident(&self.name)
96 }
97
98 /// Generate the struct field declaration.
99 ///
100 /// Creates a public field declaration for use in the generated struct.
101 ///
102 /// # Returns
103 ///
104 /// A token stream representing `pub field_name: FieldType`
105 ///
106 /// # Example Output
107 ///
108 /// ```ignore
109 /// pub database_url: String
110 /// pub api_key: Option<String>
111 /// ```
112 fn generate_struct_field(&self) -> proc_macro2::TokenStream {
113 let field_name = self.field_name();
114 let field_type = &self.field_type;
115 quote! { pub #field_name: #field_type }
116 }
117
118 /// Generate a field assignment from a secrets map.
119 ///
120 /// Creates code to assign a value from a HashMap<String, String> to this field.
121 /// Handles both required and optional fields appropriately.
122 ///
123 /// # Arguments
124 ///
125 /// * `source` - The token stream representing the source map (e.g., `secrets`)
126 ///
127 /// # Returns
128 ///
129 /// Token stream for the field assignment, with proper error handling for required fields
130 fn generate_assignment(&self, source: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
131 generate_secret_assignment(
132 &self.field_name(),
133 &self.name,
134 source,
135 self.is_optional,
136 self.as_path,
137 )
138 }
139
140 /// Generate environment variable setter.
141 ///
142 /// Creates code to set an environment variable from this field's value.
143 /// For optional fields, only sets the variable if a value is present.
144 /// For PathBuf fields, converts to string using to_string_lossy().
145 ///
146 /// # Safety
147 ///
148 /// The generated code uses `unsafe` because `std::env::set_var` is unsafe
149 /// in multi-threaded contexts. Users should ensure thread safety when calling
150 /// the generated `set_as_env_vars` method.
151 ///
152 /// # Returns
153 ///
154 /// Token stream that sets the environment variable when executed
155 fn generate_env_setter(&self) -> proc_macro2::TokenStream {
156 let field_name = self.field_name();
157 let env_name = &self.name;
158
159 match (self.is_optional, self.as_path) {
160 (true, true) => {
161 // Optional PathBuf
162 quote! {
163 if let Some(ref value) = self.#field_name {
164 unsafe {
165 std::env::set_var(#env_name, value.to_string_lossy().as_ref());
166 }
167 }
168 }
169 }
170 (true, false) => {
171 // Optional String
172 quote! {
173 if let Some(ref value) = self.#field_name {
174 unsafe {
175 std::env::set_var(#env_name, value);
176 }
177 }
178 }
179 }
180 (false, true) => {
181 // Required PathBuf
182 quote! {
183 unsafe {
184 std::env::set_var(#env_name, self.#field_name.to_string_lossy().as_ref());
185 }
186 }
187 }
188 (false, false) => {
189 // Required String
190 quote! {
191 unsafe {
192 std::env::set_var(#env_name, &self.#field_name);
193 }
194 }
195 }
196 }
197 }
198}
199
200/// Profile variant information for enum generation.
201///
202/// Represents a profile that will become an enum variant in the generated code.
203/// Handles the conversion from profile names to valid Rust enum variants.
204///
205/// # Fields
206///
207/// * `name` - The original profile name (e.g., "production", "development")
208/// * `capitalized` - The capitalized variant name (e.g., "Production", "Development")
209struct ProfileVariant {
210 name: String,
211 capitalized: String,
212}
213
214impl ProfileVariant {
215 /// Creates a new ProfileVariant with automatic capitalization.
216 ///
217 /// # Arguments
218 ///
219 /// * `name` - The profile name from the configuration
220 ///
221 /// # Example
222 ///
223 /// ```ignore
224 /// let variant = ProfileVariant::new("production".to_string());
225 /// // variant.name == "production"
226 /// // variant.capitalized == "Production"
227 /// ```
228 fn new(name: String) -> Self {
229 let capitalized = capitalize(&name);
230 Self { name, capitalized }
231 }
232
233 /// Convert the variant to a Rust identifier.
234 ///
235 /// # Returns
236 ///
237 /// A proc_macro2::Ident suitable for use as an enum variant
238 fn as_ident(&self) -> proc_macro2::Ident {
239 format_ident!("{}", self.capitalized)
240 }
241}
242
243/// Generates typed SecretSpec structs from your secretspec.toml file.
244///
245/// # Example
246/// ```ignore
247/// // In your main.rs or lib.rs:
248/// secretspec_derive::declare_secrets!("secretspec.toml");
249///
250/// use secretspec::Provider;
251///
252/// fn main() -> Result<(), Box<dyn std::error::Error>> {
253/// // Load with union types (safe for any profile) using the builder pattern
254/// let secrets = SecretSpec::builder()
255/// .with_provider(Provider::Keyring)
256/// .load()?;
257/// println!("Database URL: {}", secrets.secrets.database_url);
258///
259/// // Load with profile-specific types
260/// let profile_secrets = SecretSpec::builder()
261/// .with_provider(Provider::Keyring)
262/// .with_profile(Profile::Production)
263/// .load_profile()?;
264///
265/// match profile_secrets.secrets {
266/// SecretSpecProfile::Production { api_key, database_url, .. } => {
267/// println!("Production API key: {}", api_key);
268/// }
269/// _ => unreachable!(),
270/// }
271///
272/// Ok(())
273/// }
274/// ```
275#[proc_macro]
276pub fn declare_secrets(input: TokenStream) -> TokenStream {
277 let path = parse_macro_input!(input as LitStr).value();
278
279 // Get the manifest directory of the crate using the macro
280 let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
281 let full_path = std::path::Path::new(&manifest_dir).join(&path);
282
283 let config: Config = match Config::try_from(full_path.as_path()) {
284 Ok(config) => config,
285 Err(e) => {
286 let error = format!("Failed to parse TOML: {}", e);
287 return quote! { compile_error!(#error); }.into();
288 }
289 };
290
291 // Validate the configuration at compile time
292 if let Err(validation_errors) = validate_config_for_codegen(&config) {
293 let error_message = format!(
294 "Invalid secretspec configuration:\n{}",
295 validation_errors.join("\n")
296 );
297 return quote! { compile_error!(#error_message); }.into();
298 }
299
300 // Generate all the code
301 let output = generate_secret_spec_code(config);
302 output.into()
303}
304
305// ===== Core Helper Functions =====
306
307/// Validate configuration for code generation concerns only.
308///
309/// This performs compile-time validation to ensure the configuration can be
310/// converted into valid Rust code. This is different from runtime validation -
311/// we only check things that would prevent generating valid Rust code.
312///
313/// # Validation Checks
314///
315/// - Secret names must produce valid Rust identifiers
316/// - Secret names must not be Rust keywords
317/// - Profile names must produce valid enum variants
318/// - No duplicate field names within a profile (case-insensitive)
319///
320/// # Arguments
321///
322/// * `config` - The parsed project configuration
323///
324/// # Returns
325///
326/// - `Ok(())` if validation passes
327/// - `Err(Vec<String>)` containing all validation errors if any are found
328fn validate_config_for_codegen(config: &Config) -> Result<(), Vec<String>> {
329 let mut errors = Vec::new();
330
331 // Validate secret names produce valid Rust identifiers
332 validate_rust_identifiers(config, &mut errors);
333
334 // Validate profile names produce valid Rust enum variants
335 validate_profile_identifiers(config, &mut errors);
336
337 if errors.is_empty() {
338 Ok(())
339 } else {
340 Err(errors)
341 }
342}
343
344/// Validate all secret names produce valid Rust identifiers.
345///
346/// Checks that each secret name, when converted to a field name:
347/// - Forms a valid Rust identifier (alphanumeric + underscores)
348/// - Doesn't conflict with Rust keywords
349/// - Doesn't create duplicate field names within a profile
350///
351/// # Arguments
352///
353/// * `config` - The project configuration to validate
354/// * `errors` - Mutable vector to collect error messages
355///
356/// # Error Cases
357///
358/// - Secret names with invalid characters (e.g., "my-secret" with hyphen)
359/// - Secret names that are Rust keywords (e.g., "TYPE", "IMPL")
360/// - Multiple secrets producing the same field name (e.g., "API_KEY" and "api_key")
361fn validate_rust_identifiers(config: &Config, errors: &mut Vec<String>) {
362 let rust_keywords = [
363 "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum",
364 "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move",
365 "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super", "trait",
366 "true", "type", "unsafe", "use", "where", "while", "abstract", "become", "box", "do",
367 "final", "macro", "override", "priv", "typeof", "unsized", "virtual", "yield", "try",
368 ];
369
370 for (profile_name, profile_config) in &config.profiles {
371 let mut profile_field_names = HashSet::new();
372
373 for secret_name in profile_config.secrets.keys() {
374 let field_name = secret_name.to_lowercase();
375
376 // Check if it produces a valid Rust identifier
377 if !is_valid_rust_identifier(&field_name) {
378 errors.push(format!(
379 "Secret '{}' in profile '{}' produces invalid Rust field name '{}'",
380 secret_name, profile_name, field_name
381 ));
382 }
383
384 // Check for Rust keywords
385 if rust_keywords.contains(&field_name.as_str()) {
386 errors.push(format!(
387 "Secret '{}' in profile '{}' produces Rust keyword '{}' as field name",
388 secret_name, profile_name, field_name
389 ));
390 }
391
392 // Check for duplicate field names within the same profile
393 if !profile_field_names.insert(field_name.clone()) {
394 errors.push(format!(
395 "Profile '{}' has multiple secrets that produce the same field name '{}' (names are case-insensitive)",
396 profile_name, field_name
397 ));
398 }
399 }
400 }
401}
402
403/// Check if a string is a valid Rust identifier.
404///
405/// A valid Rust identifier must:
406/// - Start with a letter or underscore
407/// - Contain only letters, numbers, and underscores
408/// - Not be empty
409///
410/// # Arguments
411///
412/// * `s` - The string to validate
413///
414/// # Returns
415///
416/// `true` if the string is a valid Rust identifier, `false` otherwise
417///
418/// # Examples
419///
420/// ```ignore
421/// assert!(is_valid_rust_identifier("my_var"));
422/// assert!(is_valid_rust_identifier("_private"));
423/// assert!(!is_valid_rust_identifier("123start"));
424/// assert!(!is_valid_rust_identifier("my-var"));
425/// ```
426fn is_valid_rust_identifier(s: &str) -> bool {
427 if s.is_empty() {
428 return false;
429 }
430
431 let mut chars = s.chars();
432 if let Some(first) = chars.next() {
433 // First character must be alphabetic or underscore
434 if !first.is_alphabetic() && first != '_' {
435 return false;
436 }
437 // Remaining characters must be alphanumeric or underscore
438 chars.all(|c| c.is_alphanumeric() || c == '_')
439 } else {
440 false
441 }
442}
443
444/// Validate profile names produce valid Rust enum variants.
445///
446/// Ensures that each profile name, when capitalized, forms a valid Rust enum variant.
447///
448/// # Arguments
449///
450/// * `config` - The project configuration to validate
451/// * `errors` - Mutable vector to collect error messages
452///
453/// # Error Cases
454///
455/// - Profile names that start with numbers (e.g., "1production")
456/// - Profile names with invalid characters (e.g., "prod-env")
457fn validate_profile_identifiers(config: &Config, errors: &mut Vec<String>) {
458 for profile_name in config.profiles.keys() {
459 let variant_name = capitalize(profile_name);
460 if !is_valid_rust_identifier(&variant_name) {
461 errors.push(format!(
462 "Profile '{}' produces invalid Rust enum variant '{}'",
463 profile_name, variant_name
464 ));
465 }
466 }
467}
468
469/// Convert a secret name to a field identifier.
470///
471/// Converts environment variable style names to Rust field names by:
472/// - Converting to lowercase
473/// - Preserving underscores
474///
475/// # Arguments
476///
477/// * `name` - The secret name (typically uppercase with underscores)
478///
479/// # Returns
480///
481/// A proc_macro2::Ident suitable for use as a struct field
482///
483/// # Example
484///
485/// ```ignore
486/// let ident = field_name_ident("DATABASE_URL");
487/// // Generates: database_url
488/// ```
489fn field_name_ident(name: &str) -> proc_macro2::Ident {
490 format_ident!("{}", name.to_lowercase())
491}
492
493/// Map a shared-IR field's optionality and path-ness to its Rust type.
494///
495/// This is the only typing decision the derive macro still makes locally; the
496/// underlying optional/as_path facts come from [`secretspec::codegen`].
497fn ir_field_type(field: &IrField) -> proc_macro2::TokenStream {
498 match (field.optional, field.as_path) {
499 (true, true) => quote! { Option<std::path::PathBuf> },
500 (true, false) => quote! { Option<String> },
501 (false, true) => quote! { std::path::PathBuf },
502 (false, false) => quote! { String },
503 }
504}
505
506/// Generate a unified secret assignment from a HashMap.
507///
508/// Creates the code to assign a value from a secrets map to a struct field,
509/// with appropriate error handling based on whether the field is optional.
510///
511/// # Arguments
512///
513/// * `field_name` - The struct field identifier
514/// * `secret_name` - The key to look up in the map
515/// * `source` - Token stream representing the source map
516/// * `is_optional` - Whether to generate Option<T> or T assignment
517/// * `as_path` - Whether to generate PathBuf or String
518///
519/// # Generated Code
520///
521/// For required String fields:
522/// ```ignore
523/// field_name: source.get("SECRET_NAME")
524/// .ok_or_else(|| SecretSpecError::RequiredSecretMissing("SECRET_NAME".to_string()))?
525/// .expose_secret().to_string()
526/// ```
527///
528/// For required PathBuf fields:
529/// ```ignore
530/// field_name: std::path::PathBuf::from(source.get("SECRET_NAME")
531/// .ok_or_else(|| SecretSpecError::RequiredSecretMissing("SECRET_NAME".to_string()))?
532/// .expose_secret())
533/// ```
534///
535/// For optional fields:
536/// ```ignore
537/// field_name: source.get("SECRET_NAME").map(|s| s.expose_secret().to_string())
538/// field_name: source.get("SECRET_NAME").map(|s| std::path::PathBuf::from(s.expose_secret()))
539/// ```
540fn generate_secret_assignment(
541 field_name: &proc_macro2::Ident,
542 secret_name: &str,
543 source: proc_macro2::TokenStream,
544 is_optional: bool,
545 as_path: bool,
546) -> proc_macro2::TokenStream {
547 match (is_optional, as_path) {
548 (true, true) => {
549 // Optional PathBuf
550 quote! {
551 #field_name: #source.get(#secret_name).map(|s| std::path::PathBuf::from(s.expose_secret()))
552 }
553 }
554 (true, false) => {
555 // Optional String
556 quote! {
557 #field_name: #source.get(#secret_name).map(|s| s.expose_secret().to_string())
558 }
559 }
560 (false, true) => {
561 // Required PathBuf
562 quote! {
563 #field_name: std::path::PathBuf::from(
564 #source.get(#secret_name)
565 .ok_or_else(|| secretspec::SecretSpecError::RequiredSecretMissing(#secret_name.to_string()))?
566 .expose_secret()
567 )
568 }
569 }
570 (false, false) => {
571 // Required String
572 quote! {
573 #field_name: #source.get(#secret_name)
574 .ok_or_else(|| secretspec::SecretSpecError::RequiredSecretMissing(#secret_name.to_string()))?
575 .expose_secret()
576 .to_string()
577 }
578 }
579 }
580}
581
582/// Build the union struct's fields from the shared IR.
583///
584/// The IR already determined the union field set and each field's
585/// optionality/as_path; this just maps them to `FieldInfo`, keyed and ordered
586/// by name (the IR union is pre-sorted).
587fn union_field_info(ir: &CodegenIr) -> BTreeMap<String, FieldInfo> {
588 ir.union
589 .iter()
590 .map(|field| (field.name.clone(), FieldInfo::from_ir(field)))
591 .collect()
592}
593
594/// Profile variants for enum generation, taken from the shared IR.
595///
596/// The IR's profile list is already sorted and already substitutes a single
597/// `default` profile when the manifest declares none, so this is a direct map.
598fn profile_variants_from_ir(ir: &CodegenIr) -> Vec<ProfileVariant> {
599 ir.profiles
600 .iter()
601 .map(|name| ProfileVariant::new(name.clone()))
602 .collect()
603}
604
605// ===== Profile Generation Module =====
606
607/// Module for generating Profile enum and related implementations.
608///
609/// This module handles:
610/// - Profile enum definition
611/// - TryFrom implementations for string conversion
612/// - as_str() method for profile serialization
613mod profile_generation {
614 use super::*;
615
616 /// Generate just the Profile enum.
617 ///
618 /// Creates an enum with variants for each profile in the configuration.
619 ///
620 /// # Arguments
621 ///
622 /// * `variants` - List of profile variants to generate
623 ///
624 /// # Generated Code Example
625 ///
626 /// ```ignore
627 /// #[derive(Debug, Clone, Copy)]
628 /// pub enum Profile {
629 /// Development,
630 /// Production,
631 /// Staging,
632 /// }
633 /// ```
634 pub fn generate_enum(variants: &[ProfileVariant]) -> proc_macro2::TokenStream {
635 let enum_variants = variants.iter().map(|v| {
636 let ident = v.as_ident();
637 quote! { #ident }
638 });
639
640 quote! {
641 #[derive(Debug, Clone, Copy)]
642 pub enum Profile {
643 #(#enum_variants,)*
644 }
645 }
646 }
647
648 /// Generate TryFrom implementations for Profile.
649 ///
650 /// Creates implementations to convert strings to Profile enum variants,
651 /// supporting both &str and String inputs.
652 ///
653 /// # Arguments
654 ///
655 /// * `variants` - List of profile variants
656 ///
657 /// # Generated Code
658 ///
659 /// - `TryFrom<&str>` implementation with match arms for each profile
660 /// - `TryFrom<String>` implementation that delegates to &str
661 /// - Returns `SecretSpecError::InvalidProfile` for unknown profiles
662 pub fn generate_try_from_impls(variants: &[ProfileVariant]) -> proc_macro2::TokenStream {
663 let from_str_arms = variants.iter().map(|v| {
664 let ident = v.as_ident();
665 let str_val = &v.name;
666 quote! { #str_val => Ok(Profile::#ident) }
667 });
668
669 quote! {
670 impl std::convert::TryFrom<&str> for Profile {
671 type Error = secretspec::SecretSpecError;
672
673 fn try_from(value: &str) -> Result<Self, Self::Error> {
674 match value {
675 #(#from_str_arms,)*
676 _ => Err(secretspec::SecretSpecError::InvalidProfile(value.to_string())),
677 }
678 }
679 }
680
681 impl std::convert::TryFrom<String> for Profile {
682 type Error = secretspec::SecretSpecError;
683
684 fn try_from(value: String) -> Result<Self, Self::Error> {
685 Profile::try_from(value.as_str())
686 }
687 }
688 }
689 }
690
691 /// Generate as_str implementation for Profile.
692 ///
693 /// Creates a method to convert Profile enum variants back to their string representation.
694 ///
695 /// # Arguments
696 ///
697 /// * `variants` - List of profile variants
698 ///
699 /// # Generated Code Example
700 ///
701 /// ```ignore
702 /// impl Profile {
703 /// fn as_str(&self) -> &'static str {
704 /// match self {
705 /// Profile::Development => "development",
706 /// Profile::Production => "production",
707 /// }
708 /// }
709 /// }
710 /// ```
711 pub fn generate_as_str_impl(variants: &[ProfileVariant]) -> proc_macro2::TokenStream {
712 let to_str_arms = variants.iter().map(|v| {
713 let ident = v.as_ident();
714 let str_val = &v.name;
715 quote! { Profile::#ident => #str_val }
716 });
717
718 quote! {
719 impl Profile {
720 fn as_str(&self) -> &'static str {
721 match self {
722 #(#to_str_arms,)*
723 }
724 }
725 }
726 }
727 }
728
729 /// Generate all profile-related code.
730 ///
731 /// Combines all profile generation functions into a single token stream.
732 ///
733 /// # Arguments
734 ///
735 /// * `variants` - List of profile variants
736 ///
737 /// # Returns
738 ///
739 /// Complete token stream containing:
740 /// - Profile enum definition
741 /// - TryFrom implementations
742 /// - as_str() method
743 pub fn generate_all(variants: &[ProfileVariant]) -> proc_macro2::TokenStream {
744 let enum_def = generate_enum(variants);
745 let try_from_impls = generate_try_from_impls(variants);
746 let as_str_impl = generate_as_str_impl(variants);
747
748 quote! {
749 #enum_def
750 #try_from_impls
751 #as_str_impl
752 }
753 }
754}
755
756// ===== SecretSpec Generation Module =====
757
758/// Module for generating SecretSpec struct and related implementations.
759///
760/// This module handles:
761/// - SecretSpec struct (union of all secrets)
762/// - SecretSpecProfile enum (profile-specific types)
763/// - Loading implementations
764/// - Environment variable integration
765mod secret_spec_generation {
766 use super::*;
767
768 /// Generate the SecretSpec struct.
769 ///
770 /// Creates a struct containing all secrets from all profiles as fields.
771 /// This is the "union" type that can safely hold secrets from any profile.
772 ///
773 /// # Arguments
774 ///
775 /// * `field_info` - Map of all fields with their type information
776 ///
777 /// # Generated Code Example
778 ///
779 /// ```ignore
780 /// #[derive(Debug, serde::Serialize, serde::Deserialize)]
781 /// pub struct SecretSpec {
782 /// pub database_url: String,
783 /// pub api_key: Option<String>,
784 /// pub redis_url: Option<String>,
785 /// }
786 /// ```
787 pub fn generate_struct(field_info: &BTreeMap<String, FieldInfo>) -> proc_macro2::TokenStream {
788 let fields = field_info.values().map(|info| info.generate_struct_field());
789
790 quote! {
791 #[derive(Debug, serde::Serialize, serde::Deserialize)]
792 pub struct SecretSpec {
793 #(#fields,)*
794 }
795 }
796 }
797
798 /// Generate the SecretSpecProfile enum.
799 ///
800 /// Creates an enum where each variant contains only the secrets defined
801 /// for that specific profile. This provides stronger type safety when
802 /// working with profile-specific secrets.
803 ///
804 /// # Arguments
805 ///
806 /// * `profile_variants` - Generated enum variant definitions
807 ///
808 /// # Generated Code Example
809 ///
810 /// ```ignore
811 /// #[derive(Debug, serde::Serialize, serde::Deserialize)]
812 /// pub enum SecretSpecProfile {
813 /// Development {
814 /// database_url: String,
815 /// redis_url: Option<String>,
816 /// },
817 /// Production {
818 /// database_url: String,
819 /// api_key: String,
820 /// redis_url: String,
821 /// },
822 /// }
823 /// ```
824 pub fn generate_profile_enum(
825 profile_variants: &[proc_macro2::TokenStream],
826 ) -> proc_macro2::TokenStream {
827 quote! {
828 #[derive(Debug, serde::Serialize, serde::Deserialize)]
829 pub enum SecretSpecProfile {
830 #(#profile_variants,)*
831 }
832 }
833 }
834
835 /// Generate SecretSpecProfile enum variants.
836 ///
837 /// Creates the individual variants for the SecretSpecProfile enum,
838 /// each containing only the fields defined for that profile.
839 ///
840 /// # Arguments
841 ///
842 /// * `config` - The project configuration
843 /// * `field_info` - Field information (used for empty profile case)
844 /// * `variants` - Profile variants to generate
845 ///
846 /// # Returns
847 ///
848 /// Vector of token streams, each representing one enum variant
849 ///
850 /// # Special Cases
851 ///
852 /// - Empty profiles → generates a Default variant with all fields
853 /// - Each profile → generates variant with profile-specific fields
854 pub fn generate_profile_enum_variants(ir: &CodegenIr) -> Vec<proc_macro2::TokenStream> {
855 // The IR's per-profile field sets already handle the empty-profiles case
856 // (a single `default` profile carrying the union), so there is no special
857 // branch here: one variant per IR profile, with that profile's exact
858 // (raw, non-merged) fields.
859 ir.profile_fields
860 .iter()
861 .map(|profile| {
862 let variant_ident = ProfileVariant::new(profile.name.clone()).as_ident();
863 let fields = profile.fields.iter().map(|field| {
864 let field_name = field_name_ident(&field.name);
865 let field_type = ir_field_type(field);
866 quote! { #field_name: #field_type }
867 });
868 quote! {
869 #variant_ident {
870 #(#fields,)*
871 }
872 }
873 })
874 .collect()
875 }
876
877 /// Generate load_profile match arms.
878 ///
879 /// Creates the match arms for loading profile-specific secrets into
880 /// the appropriate SecretSpecProfile variant.
881 ///
882 /// # Arguments
883 ///
884 /// * `config` - The project configuration
885 /// * `field_info` - Field information (for empty profile case)
886 /// * `variants` - Profile variants to generate arms for
887 ///
888 /// # Returns
889 ///
890 /// Vector of match arms for the profile loading logic
891 ///
892 /// # Generated Code Example
893 ///
894 /// ```ignore
895 /// Profile::Production => Ok(SecretSpecProfile::Production {
896 /// database_url: secrets.get("DATABASE_URL")
897 /// .ok_or_else(|| SecretSpecError::RequiredSecretMissing("DATABASE_URL".to_string()))?
898 /// .clone(),
899 /// api_key: secrets.get("API_KEY").cloned(),
900 /// })
901 /// ```
902 pub fn generate_load_profile_arms(ir: &CodegenIr) -> Vec<proc_macro2::TokenStream> {
903 // One arm per IR profile, assigning that profile's exact fields. The
904 // empty-profiles case is already a single `default` profile in the IR.
905 ir.profile_fields
906 .iter()
907 .map(|profile| {
908 let variant_ident = ProfileVariant::new(profile.name.clone()).as_ident();
909 let assignments = profile.fields.iter().map(|field| {
910 generate_secret_assignment(
911 &field_name_ident(&field.name),
912 &field.name,
913 quote! { secrets },
914 field.optional,
915 field.as_path,
916 )
917 });
918 quote! {
919 Profile::#variant_ident => Ok(SecretSpecProfile::#variant_ident {
920 #(#assignments,)*
921 })
922 }
923 })
924 .collect()
925 }
926
927 /// Generate the shared load_internal implementation.
928 ///
929 /// Creates a helper function that handles the common loading logic
930 /// for both SecretSpec and SecretSpecProfile loading methods.
931 ///
932 /// # Generated Function
933 ///
934 /// The function:
935 /// 1. Loads the SecretSpec configuration
936 /// 2. Validates it with the given provider and profile
937 /// 3. Returns the validation result containing loaded secrets
938 pub fn generate_load_internal() -> proc_macro2::TokenStream {
939 quote! {
940 fn load_internal(
941 provider_str: Option<String>,
942 profile_str: Option<String>,
943 reason: Option<String>,
944 ) -> Result<secretspec::ValidatedSecrets, secretspec::SecretSpecError> {
945 let mut spec = secretspec::Secrets::load()?;
946 if let Some(provider) = provider_str {
947 spec.set_provider(provider);
948 }
949 if let Some(profile) = profile_str {
950 spec.set_profile(profile);
951 }
952 // Apply an explicit builder reason on top of any SECRETSPEC_REASON
953 // already resolved by `Secrets::load`. Required to satisfy the
954 // `require_reason` policy (default "agents") from typed SDK code,
955 // which otherwise has no way to supply a reason. A blank reason is
956 // ignored by `with_reason`, leaving the env-resolved value intact.
957 if let Some(reason) = reason {
958 spec = spec.with_reason(reason);
959 }
960 match spec.validate()? {
961 Ok(valid_secrets) => Ok(valid_secrets),
962 Err(validation_errors) => Err(secretspec::SecretSpecError::RequiredSecretMissing(
963 validation_errors.missing_required.join(", ")
964 ))
965 }
966 }
967 }
968 }
969
970 /// Generate SecretSpec implementation.
971 ///
972 /// Creates the impl block for SecretSpec with:
973 /// - builder() method for creating a builder
974 /// - load() method for loading with union types
975 /// - set_as_env_vars() method for environment variable integration
976 ///
977 /// # Arguments
978 ///
979 /// * `load_assignments` - Field assignments for the load method
980 /// * `env_setters` - Environment variable setter statements
981 /// * `_field_info` - Field information (currently unused)
982 ///
983 /// # Generated Methods
984 ///
985 /// - `builder()` - Creates a new SecretSpecBuilder
986 /// - `load()` - Loads secrets with optional provider/profile
987 /// - `set_as_env_vars()` - Sets all secrets as environment variables
988 pub fn generate_impl(
989 load_assignments: &[proc_macro2::TokenStream],
990 env_setters: Vec<proc_macro2::TokenStream>,
991 _field_info: &BTreeMap<String, FieldInfo>,
992 ) -> proc_macro2::TokenStream {
993 quote! {
994 impl SecretSpec {
995 /// Create a new builder for loading secrets
996 pub fn builder() -> SecretSpecBuilder {
997 SecretSpecBuilder::new()
998 }
999
1000 /// Load secrets with optional provider and/or profile
1001 /// Provider can be any type that implements Into<String> (e.g., &str, String, etc.)
1002 /// If provider is None, uses SECRETSPEC_PROVIDER env var or global config
1003 /// If profile is None, uses SECRETSPEC_PROFILE env var if set
1004 pub fn load<P>(provider: Option<P>, profile: Option<Profile>) -> Result<secretspec::Resolved<Self>, secretspec::SecretSpecError>
1005 where
1006 P: Into<String>,
1007 {
1008 // Convert options to strings
1009 let provider_str = provider.map(Into::into).or_else(|| std::env::var("SECRETSPEC_PROVIDER").ok());
1010
1011 let profile_str = match profile {
1012 Some(p) => Some(p.as_str().to_string()),
1013 None => std::env::var("SECRETSPEC_PROFILE").ok(),
1014 };
1015
1016 // The static `load` has no reason parameter; a reason is supplied
1017 // via the SECRETSPEC_REASON env var (honored by `Secrets::load`)
1018 // or through `SecretSpec::builder().with_reason(...)`.
1019 let validation_result = load_internal(provider_str, profile_str, None)?;
1020 let provider_name = validation_result.resolved.provider.clone();
1021 let profile = validation_result.resolved.profile.clone();
1022 let secrets = validation_result.resolved.secrets;
1023
1024 let data = Self {
1025 #(#load_assignments,)*
1026 };
1027
1028 Ok(secretspec::Resolved::new(
1029 data,
1030 provider_name,
1031 profile
1032 ))
1033 }
1034
1035 pub fn set_as_env_vars(&self) {
1036 #(#env_setters)*
1037 }
1038 }
1039 }
1040 }
1041}
1042
1043// ===== Builder Generation Module =====
1044
1045/// Module for generating the builder pattern implementation.
1046///
1047/// The builder provides a fluent API for configuring how secrets are loaded,
1048/// with support for:
1049/// - Custom providers (via URIs)
1050/// - Profile selection
1051/// - Type-safe loading (union or profile-specific)
1052mod builder_generation {
1053 use super::*;
1054
1055 /// Generate the builder struct definition.
1056 ///
1057 /// The builder uses boxed closures to defer provider/profile resolution
1058 /// until load time, allowing for flexible configuration.
1059 ///
1060 /// # Generated Struct
1061 ///
1062 /// ```ignore
1063 /// pub struct SecretSpecBuilder {
1064 /// provider: Option<Box<dyn FnOnce() -> Result<Box<dyn secretspec::Provider>, String>>>,
1065 /// profile: Option<Box<dyn FnOnce() -> Result<Profile, String>>>,
1066 /// reason: Option<String>,
1067 /// }
1068 /// ```
1069 pub fn generate_struct() -> proc_macro2::TokenStream {
1070 quote! {
1071 pub struct SecretSpecBuilder {
1072 provider: Option<Box<dyn FnOnce() -> Result<Box<dyn secretspec::Provider>, String>>>,
1073 profile: Option<Box<dyn FnOnce() -> Result<Profile, String>>>,
1074 reason: Option<String>,
1075 }
1076 }
1077 }
1078
1079 /// Generate builder basic methods.
1080 ///
1081 /// Creates the foundational builder methods:
1082 /// - Default implementation
1083 /// - new() constructor
1084 /// - with_provider() for setting provider
1085 /// - with_profile() for setting profile
1086 ///
1087 /// # Type Flexibility
1088 ///
1089 /// Both with_provider and with_profile accept anything that can be
1090 /// converted to the target type (Uri or Profile), providing flexibility:
1091 ///
1092 /// ```ignore
1093 /// builder.with_provider("keyring://") // &str
1094 /// .with_provider(Provider::Keyring) // Provider enum
1095 /// .with_profile("production") // &str
1096 /// .with_profile(Profile::Production) // Profile enum
1097 /// ```
1098 pub fn generate_basic_methods() -> proc_macro2::TokenStream {
1099 quote! {
1100 impl Default for SecretSpecBuilder {
1101 fn default() -> Self {
1102 Self::new()
1103 }
1104 }
1105
1106 impl SecretSpecBuilder {
1107 pub fn new() -> Self {
1108 Self {
1109 provider: None,
1110 profile: None,
1111 reason: None,
1112 }
1113 }
1114
1115 /// Set a human-readable reason for this session's secret access.
1116 ///
1117 /// Required to satisfy the project's `require_reason` policy
1118 /// (`[project].require_reason` in secretspec.toml, default `"agents"`)
1119 /// when loading from agent contexts, and recorded in the audit log.
1120 /// Mirrors the CLI `--reason` flag and `Secrets::with_reason`. A blank
1121 /// reason is ignored, falling back to the `SECRETSPEC_REASON` env var.
1122 pub fn with_reason<T>(mut self, reason: T) -> Self
1123 where
1124 T: Into<String>,
1125 {
1126 self.reason = Some(reason.into());
1127 self
1128 }
1129
1130 pub fn with_provider<T>(mut self, provider: T) -> Self
1131 where
1132 T: TryInto<Box<dyn secretspec::Provider>> + 'static,
1133 T::Error: std::fmt::Display + 'static,
1134 {
1135 self.provider = Some(Box::new(move || {
1136 provider.try_into()
1137 .map_err(|e| format!("Invalid provider: {}", e))
1138 }));
1139 self
1140 }
1141
1142 pub fn with_profile<T>(mut self, profile: T) -> Self
1143 where
1144 T: TryInto<Profile>,
1145 T::Error: std::fmt::Display
1146 {
1147 match profile.try_into() {
1148 Ok(p) => {
1149 self.profile = Some(Box::new(move || Ok(p)));
1150 }
1151 Err(e) => {
1152 let error_msg = format!("{}", e);
1153 self.profile = Some(Box::new(move || Err(error_msg)));
1154 }
1155 }
1156 self
1157 }
1158 }
1159 }
1160 }
1161
1162 /// Generate provider resolution logic.
1163 ///
1164 /// Creates code to resolve a provider from the builder's boxed closure.
1165 ///
1166 /// # Arguments
1167 ///
1168 /// * `provider_expr` - Expression to access the provider option
1169 ///
1170 /// # Generated Logic
1171 ///
1172 /// 1. If provider is set, call the closure to get the Provider instance
1173 /// 2. Convert any errors to SecretSpecError
1174 /// 3. Extract the provider name to pass to the loading system
1175 fn generate_provider_resolution(
1176 provider_expr: proc_macro2::TokenStream,
1177 ) -> proc_macro2::TokenStream {
1178 quote! {
1179 let provider_str = if let Some(provider_fn) = #provider_expr {
1180 let provider_box = provider_fn()
1181 .map_err(|e| secretspec::SecretSpecError::ProviderOperationFailed(e))?;
1182 // Get the full URI to pass as a string to set_provider (preserves vault info)
1183 Some(provider_box.uri())
1184 } else {
1185 None
1186 };
1187 }
1188 }
1189
1190 /// Generate profile resolution logic.
1191 ///
1192 /// Creates code to resolve a profile from the builder's boxed closure.
1193 ///
1194 /// # Arguments
1195 ///
1196 /// * `profile_expr` - Expression to access the profile option
1197 ///
1198 /// # Generated Logic
1199 ///
1200 /// 1. If profile is set, call the closure to get the Profile
1201 /// 2. Convert any errors to SecretSpecError
1202 /// 3. Convert Profile to string for the loading system
1203 fn generate_profile_resolution(
1204 profile_expr: proc_macro2::TokenStream,
1205 ) -> proc_macro2::TokenStream {
1206 quote! {
1207 let profile_str = if let Some(profile_fn) = #profile_expr {
1208 let profile = profile_fn()
1209 .map_err(|e| secretspec::SecretSpecError::InvalidProfile(e))?;
1210 Some(profile.as_str().to_string())
1211 } else {
1212 None
1213 };
1214 }
1215 }
1216
1217 /// Generate load methods for the builder.
1218 ///
1219 /// Creates two loading methods:
1220 /// - `load()` - Returns SecretSpec (union type)
1221 /// - `load_profile()` - Returns SecretSpecProfile (profile-specific type)
1222 ///
1223 /// # Arguments
1224 ///
1225 /// * `load_assignments` - Field assignments for union type
1226 /// * `load_profile_arms` - Match arms for profile-specific loading
1227 /// * `first_profile_variant` - Default profile if none specified
1228 ///
1229 /// # Key Differences
1230 ///
1231 /// - `load()` returns all secrets with optional fields for safety
1232 /// - `load_profile()` returns only profile-specific secrets with exact types
1233 pub fn generate_load_methods(
1234 load_assignments: &[proc_macro2::TokenStream],
1235 load_profile_arms: &[proc_macro2::TokenStream],
1236 first_profile_variant: &proc_macro2::Ident,
1237 ) -> proc_macro2::TokenStream {
1238 let resolve_provider_load = generate_provider_resolution(quote! { self.provider.take() });
1239 let resolve_profile_load = generate_profile_resolution(quote! { self.profile.take() });
1240 let resolve_provider_profile =
1241 generate_provider_resolution(quote! { self.provider.take() });
1242
1243 quote! {
1244 impl SecretSpecBuilder {
1245 pub fn load(mut self) -> Result<secretspec::Resolved<SecretSpec>, secretspec::SecretSpecError> {
1246 #resolve_provider_load
1247 #resolve_profile_load
1248 let reason_str = self.reason.take();
1249
1250 let validation_result = load_internal(provider_str, profile_str, reason_str)?;
1251 let provider_name = validation_result.resolved.provider.clone();
1252 let profile = validation_result.resolved.profile.clone();
1253 let secrets = validation_result.resolved.secrets;
1254
1255 let data = SecretSpec {
1256 #(#load_assignments,)*
1257 };
1258
1259 Ok(secretspec::Resolved::new(
1260 data,
1261 provider_name,
1262 profile
1263 ))
1264 }
1265
1266 pub fn load_profile(mut self) -> Result<secretspec::Resolved<SecretSpecProfile>, secretspec::SecretSpecError> {
1267 #resolve_provider_profile
1268 let reason_str = self.reason.take();
1269
1270 let (profile_str, selected_profile) = if let Some(profile_fn) = self.profile.take() {
1271 let profile = profile_fn()
1272 .map_err(|e| secretspec::SecretSpecError::InvalidProfile(e))?;
1273 (Some(profile.as_str().to_string()), profile)
1274 } else {
1275 // Check env var for profile. A blank value is treated as
1276 // unset (matching `secretspec::Secrets`) and a padded
1277 // value is trimmed, so a stray empty var or a `$(cat
1278 // file)` trailing newline neither errors here nor selects
1279 // a nonexistent profile.
1280 let profile_str = std::env::var("SECRETSPEC_PROFILE")
1281 .ok()
1282 .map(|s| s.trim().to_string())
1283 .filter(|s| !s.is_empty());
1284 let selected_profile = if let Some(ref profile_name) = profile_str {
1285 Profile::try_from(profile_name.as_str())?
1286 } else {
1287 Profile::#first_profile_variant
1288 };
1289 (profile_str, selected_profile)
1290 };
1291
1292 let validation_result = load_internal(provider_str, profile_str, reason_str)?;
1293 let provider_name = validation_result.resolved.provider.clone();
1294 let profile = validation_result.resolved.profile.clone();
1295 let secrets = validation_result.resolved.secrets;
1296
1297 let data_result: LoadResult<SecretSpecProfile> = match selected_profile {
1298 #(#load_profile_arms,)*
1299 };
1300 let data = data_result?;
1301
1302 Ok(secretspec::Resolved::new(
1303 data,
1304 provider_name,
1305 profile
1306 ))
1307 }
1308 }
1309 }
1310 }
1311
1312 /// Generate all builder-related code.
1313 ///
1314 /// Combines all builder components into a complete implementation.
1315 ///
1316 /// # Arguments
1317 ///
1318 /// * `load_assignments` - Field assignments for union loading
1319 /// * `load_profile_arms` - Match arms for profile loading
1320 /// * `first_profile_variant` - Default profile variant
1321 ///
1322 /// # Returns
1323 ///
1324 /// Complete token stream containing:
1325 /// - Builder struct definition
1326 /// - Basic builder methods
1327 /// - Loading methods (load and load_profile)
1328 pub fn generate_all(
1329 load_assignments: &[proc_macro2::TokenStream],
1330 load_profile_arms: &[proc_macro2::TokenStream],
1331 first_profile_variant: &proc_macro2::Ident,
1332 ) -> proc_macro2::TokenStream {
1333 let struct_def = generate_struct();
1334 let basic_methods = generate_basic_methods();
1335 let load_methods =
1336 generate_load_methods(load_assignments, load_profile_arms, first_profile_variant);
1337
1338 quote! {
1339 #struct_def
1340 #basic_methods
1341 #load_methods
1342 }
1343 }
1344}
1345
1346/// Main code generation function.
1347///
1348/// Orchestrates the entire code generation process, coordinating all modules
1349/// to produce the complete macro output.
1350///
1351/// # Arguments
1352///
1353/// * `config` - The validated project configuration
1354///
1355/// # Returns
1356///
1357/// Complete token stream containing all generated code
1358///
1359/// # Generation Process
1360///
1361/// 1. Analyze profiles and field types
1362/// 2. Generate Profile enum and implementations
1363/// 3. Generate SecretSpec struct (union type)
1364/// 4. Generate SecretSpecProfile enum (profile-specific types)
1365/// 5. Generate builder pattern implementation
1366/// 6. Combine all components with necessary imports
1367fn generate_secret_spec_code(config: Config) -> proc_macro2::TokenStream {
1368 // Reduce the manifest to the shared codegen IR once. Every typing decision
1369 // (union vs per-profile fields, optionality, as_path, profile list) comes
1370 // from here, so this macro and the other-language emitters cannot drift.
1371 let ir = build_ir(&config);
1372
1373 let profile_variants = profile_variants_from_ir(&ir);
1374
1375 // Union struct fields.
1376 let field_info = union_field_info(&ir);
1377
1378 // Generate field assignments for load()
1379 let load_assignments: Vec<_> = field_info
1380 .values()
1381 .map(|info| info.generate_assignment(quote! { secrets }))
1382 .collect();
1383
1384 // Generate env var setters
1385 let env_setters: Vec<_> = field_info
1386 .values()
1387 .map(|info| info.generate_env_setter())
1388 .collect();
1389
1390 // Generate profile components
1391 let profile_code = profile_generation::generate_all(&profile_variants);
1392
1393 // Generate SecretSpec components
1394 let secret_spec_struct = secret_spec_generation::generate_struct(&field_info);
1395 let profile_enum_variants = secret_spec_generation::generate_profile_enum_variants(&ir);
1396 let secret_spec_profile_enum =
1397 secret_spec_generation::generate_profile_enum(&profile_enum_variants);
1398 let load_profile_arms = secret_spec_generation::generate_load_profile_arms(&ir);
1399 let load_internal = secret_spec_generation::generate_load_internal();
1400 let secret_spec_impl =
1401 secret_spec_generation::generate_impl(&load_assignments, env_setters, &field_info);
1402
1403 // Get first profile variant for defaults
1404 // Get first profile variant for defaults
1405 let first_profile_variant = profile_variants
1406 .first()
1407 .map(|v| v.as_ident())
1408 .unwrap_or_else(|| format_ident!("Default"));
1409
1410 // Generate builder
1411 let builder_code = builder_generation::generate_all(
1412 &load_assignments,
1413 &load_profile_arms,
1414 &first_profile_variant,
1415 );
1416
1417 // Combine all components
1418 quote! {
1419 use ::secrecy::ExposeSecret;
1420
1421 #secret_spec_struct
1422 #secret_spec_profile_enum
1423 #profile_code
1424
1425
1426 // Type alias to help with type inference
1427 type LoadResult<T> = Result<T, secretspec::SecretSpecError>;
1428
1429 #load_internal
1430 #builder_code
1431 #secret_spec_impl
1432 }
1433}
1434
1435#[cfg(test)]
1436#[path = "tests.rs"]
1437mod derive_tests;