# Security Improvements for Rialo CLI Representable Macro
## Overview
The `rialo-cli-representable` crate provides a procedural macro for deriving the `Representable` and `HumanReadable` traits. Recent security improvements have been implemented to prevent injection attacks and ensure safe code generation.
## Security Concerns Addressed
### 1. Function Name Injection Prevention
**Problem**: The original macro directly used function names from attributes without validation, potentially allowing malicious function names to be injected into generated code.
**Solution**: Implemented comprehensive function name validation that:
- Ensures function names are valid Rust identifiers
- Prevents path traversal attempts
- Blocks dangerous characters
- Validates length constraints
- Checks against reserved keywords
### 2. Input Validation
**Problem**: No validation of function names could lead to:
- Path traversal attacks (`my/function`)
- Reserved keyword conflicts (`fn`, `struct`, etc.)
- Control character injection
- Extremely long names causing compilation issues
**Solution**: Added `validate_function_name()` function with multiple security checks:
```rust
fn validate_function_name(function_name: &str, span: proc_macro2::Span) -> Result<(), Error> {
// Empty/whitespace check
if function_name.trim().is_empty() { /* error */ }
// Length constraints
if function_name.len() > 100 { /* error */ }
// Dangerous character check
let dangerous_chars = ['/', '\\', ':', '*', '?', '"', '<', '>', '|', '\0'];
// ... validation logic
// Control character check
if function_name.chars().any(|c| c.is_control()) { /* error */ }
// Valid identifier start check
if !first_char.is_alphabetic() && first_char != '_' { /* error */ }
// Reserved keyword check
let reserved_keywords = ["fn", "struct", "enum", /* ... */];
if reserved_keywords.contains(&function_name) { /* error */ }
}
```
## Security Checks Implemented
### Character Validation
- **Path separators**: `/`, `\`, `:`
- **Wildcards**: `*`, `?`
- **Quotes and brackets**: `"`, `<`, `>`, `|`
- **Control characters**: All ASCII control characters (0x00-0x1F, 0x7F)
- **Null bytes**: `\0`
### Identifier Rules
- Must start with a letter or underscore
- Can contain letters, numbers, and underscores only
- Must be a valid Rust identifier
### Reserved Keywords
- Prevents use of core Rust keywords that would cause compilation issues
- Focused on keywords most problematic in function name contexts
- Minimal, maintainable list rather than complete language specification
- Includes: `fn`, `struct`, `enum`, `trait`, `impl`, `mod`, `use`, `extern`, `crate`, `type`, `const`, `static`, `let`, `mut`, `ref`, `move`, `dyn`, `async`, `await`, `if`, `else`, `match`, `loop`, `while`, `for`, `in`, `return`, `break`, `continue`, `pub`, `priv`, `unsafe`, `where`, `as`, `box`, `do`, `final`, `override`, `self`, `Self`, `super`, `macro`, `macro_rules`, `try`, `union`
### Length Constraints
- Maximum function name length: 100 characters
- Prevents extremely long names that could cause compilation issues
## Error Handling
The macro now provides clear, actionable error messages:
```rust
// Example error messages:
"Function name cannot be empty or whitespace-only"
"Function name contains invalid character '/'. Function names must be valid Rust identifiers."
"Function name must start with a letter or underscore"
"Function name 'fn' is a reserved Rust keyword"
```
## Testing
Comprehensive test coverage ensures all security checks work correctly:
- Valid function names pass validation
- Invalid characters are rejected
- Reserved keywords are blocked
- Length constraints are enforced
- Control characters are prevented
- Path traversal attempts are blocked
## Usage Examples
### Valid Usage
```rust
#[derive(Representable)]
#[representable(human_readable = "my_display_function")]
struct MyStruct {
pub value: String,
}
fn my_display_function(data: &MyStruct) -> String {
format!("Value: {}", data.value)
}
```
### Invalid Usage (Will Compile with Security Errors)
```rust
// ❌ Path traversal attempt
#[representable(human_readable = "my/function")]
// ❌ Reserved keyword
#[representable(human_readable = "fn")]
// ❌ Dangerous character
#[representable(human_readable = "my*function")]
// ❌ Control character
#[representable(human_readable = "my\x00function")]
// ❌ Empty name
#[representable(human_readable = "")]
```
## Security Benefits
1. **Prevents Code Injection**: Malicious function names cannot be injected into generated code
2. **Path Traversal Protection**: Blocks attempts to use path separators in function names
3. **Keyword Conflict Prevention**: Avoids conflicts with Rust reserved keywords
4. **Input Sanitization**: All function names are validated before use
5. **Clear Error Messages**: Developers get immediate feedback on security violations
6. **Compile-time Safety**: Security issues are caught during compilation, not runtime
## Recommendations
1. **Always validate inputs**: The macro now does this automatically
2. **Use descriptive names**: Choose clear, meaningful function names
3. **Follow Rust conventions**: Use snake_case for function names
4. **Test security features**: Verify that invalid names are properly rejected
5. **Keep dependencies updated**: Ensure you're using the latest version with security improvements
## Reporting Security Issues
If you discover a security vulnerability in this crate, please report it to the Subzero Labs security team. Do not disclose security issues publicly until they have been addressed.