pub struct InternalContext(/* private fields */);Expand description
Type-safe wrapper for internal-only error contexts.
§Trust Boundary Enforcement
This newtype ensures internal diagnostic data cannot be accidentally exposed
externally. The Display implementation returns a redacted placeholder, not
actual content, preventing misuse in external-facing code paths.
§Access Patterns
payload(): Returns structured data for SOC logging (zero allocation)expose_sensitive(): Returns raw sensitive content (requiresSocAccesscapability)
Both methods require conscious choice and cannot be used accidentally via generic string formatting.
§Memory Safety
Implements ZeroizeOnDrop to clear owned string data. Sensitive variants
receive additional volatile write treatment in InternalContextField::drop()
to prevent compiler optimization of the clearing operation.
§No Clone/Copy Policy
Single-owner semantics prevent sensitive diagnostic data from being duplicated across memory regions, reducing attack surface for memory inspection.
Implementations§
Source§impl InternalContext
impl InternalContext
Sourcepub fn diagnostic(message: impl Into<Cow<'static, str>>) -> Self
pub fn diagnostic(message: impl Into<Cow<'static, str>>) -> Self
Sourcepub fn sensitive(message: impl Into<Cow<'static, str>>) -> Self
pub fn sensitive(message: impl Into<Cow<'static, str>>) -> Self
Create a sensitive internal context with best-effort memory clearing.
§Use Case
For internal diagnostics containing:
- Personally identifiable information (PII)
- Credentials or API keys
- Filesystem paths that reveal system topology
- Database connection strings
- Any data that could aid an attacker
§Memory Clearing Strategy
When this context is dropped:
- Owned string data is cleared via
zeroizecrate - Volatile writes prevent LLVM dead-store elimination
- Compiler fence prevents instruction reordering
This provides best-effort clearing against casual memory inspection and compiler optimizations. It does NOT provide guarantees against:
- Hardware cache persistence
- Allocator-level memory reuse
- Swap file or DMA copies
For cryptographic key material, use dedicated secure allocators.
§Example
InternalContext::sensitive(format!("Failed login for username: {}", username))Sourcepub fn lie(message: impl Into<Cow<'static, str>>) -> Self
pub fn lie(message: impl Into<Cow<'static, str>>) -> Self
Create an internal context marked as deceptive.
§Use Case
When internal logs themselves may be exfiltrated and you need to track
deceptive narratives without exposing them externally. The payload()
method will return this with a Lie marker to prevent SOC analysts from
treating it as authentic diagnostic data.
§Distinction from PublicContext::lie()
PublicContext::lie(): For external consumptionInternalContext::lie(): For internal tracking of deception operations
§Example
InternalContext::lie("Normal database query executed successfully")Sourcepub const fn classification(&self) -> &'static str
pub const fn classification(&self) -> &'static str
Get classification label for logging and metrics.
§Returns
Static string identifying the context type:
"InternalDiagnostic": Standard internal error information"Sensitive": Contains high-value data requiring special handling"InternalLie": Deceptive content tracked internally
§Use Case
For indexing in log aggregation systems, metrics collection, or routing different context types to different storage backends.
Sourcepub fn payload(&self) -> Option<InternalPayload<'_>>
pub fn payload(&self) -> Option<InternalPayload<'_>>
Get structured payload for internal logging without heap allocation.
§Returns
Some(InternalPayload::Truth(_)): For diagnostic contextsSome(InternalPayload::Lie(_)): For lie contexts (marked for SOC awareness)None: For sensitive contexts (useexpose_sensitive()instead)
§Performance
Zero allocation. The returned InternalPayload borrows directly from the
underlying Cow<'static, str>. Loggers can format this without heap use:
match context.payload() {
Some(payload) => println!("{}", payload), // No allocation
None => println!("[SENSITIVE REDACTED]"),
}§Rationale
Previous design allocated format!("[LIE] {}", msg) on every access.
This approach defers formatting to the logger, allowing:
- Zero-copy access to underlying data
- Logger-controlled formatting policy
- Better performance under high error rates
Sourcepub fn expose_sensitive(&self, _access: &SocAccess) -> Option<&str>
pub fn expose_sensitive(&self, _access: &SocAccess) -> Option<&str>
Expose raw sensitive content with capability-based access control.
§Access Control
Requires SocAccess capability token, which forces:
- Explicit privilege acquisition (cannot call accidentally)
- Grep-able sensitive data access points
- Future integration with RBAC or audit systems
§Security Contract
Caller must ensure returned data is sent ONLY to:
- Authenticated, encrypted, access-controlled endpoints
- SOC-exclusive dashboards with strict RBAC
- Encrypted internal logging with key rotation
- Forensic analysis workstations with air-gapped storage
Never send to:
- External SIEMs or cloud logging services
- Unencrypted log files
- Monitoring services that aggregate across trust boundaries
§Returns
Some(&str): Raw sensitive content (if this is a Sensitive context)None: If this is not a Sensitive context
§Why #[must_use]
Forces caller to explicitly handle the returned sensitive data rather than accidentally discarding it (which might indicate a logic error).
§Example
let access = SocAccess::acquire();
if let Some(sensitive) = context.expose_sensitive(&access) {
send_to_encrypted_soc_siem(sensitive);
}Trait Implementations§
Source§impl Debug for InternalContext
impl Debug for InternalContext
Source§fn fmt(&self, f: &mut Formatter<'_>) -> Result
fn fmt(&self, f: &mut Formatter<'_>) -> Result
Debug representation for internal development and diagnostics.
§Redaction Policy
- Diagnostic: Shows full content (for debugging)
- Sensitive: Redacted (to prevent accidental logging)
- Lie: Redacted (to prevent aggregation as factual data)
§Use Case
Primarily for unit tests and local development. Production logging should
use payload() or expose_sensitive() for explicit control.
Source§impl Display for InternalContext
impl Display for InternalContext
Source§fn fmt(&self, f: &mut Formatter<'_>) -> Result
fn fmt(&self, f: &mut Formatter<'_>) -> Result
Display implementation for internal contexts.
§Security Policy
This ALWAYS returns a redacted placeholder, never actual content. Internal contexts should not be formatted for external display under any circumstances. This implementation exists only to satisfy trait bounds in generic code.
§Correct Usage
- Use
payload()for SOC logging - Use
expose_sensitive()for controlled sensitive access - Do NOT use
DisplayorToStringon internal contexts