Crate Architecture#
The token-privilege crate architecture implements a safe Rust wrapper for Windows process token privilege and elevation detection APIs through strict unsafe code isolation and cross-platform abstraction. The architecture is designed around a single principle: all unsafe Win32 FFI calls are confined to src/ffi.rs with pub(crate) visibility only, enabling downstream consumers to use #![forbid(unsafe_code)] in their own codebases while still accessing Windows token privilege functionality.
The crate employs a layered module organization that separates concerns between FFI boundaries, safe business logic, and public API surface. RAII handle management through the OwnedHandle type ensures proper cleanup of Windows token handles, preventing resource leaks even on error paths. On non-Windows platforms, the crate compiles without Windows-specific dependencies and provides const fn stubs that return Err(UnsupportedPlatform), ensuring a uniform API surface across all platforms.
The architecture leverages Rust 2024 edition with MSRV 1.85 and enforces strict code quality through Clippy lints including undocumented_unsafe_blocks=deny, panic=deny, and unwrap_used=deny. This architectural design ensures both memory safety and API ergonomics, providing a foundation for security-sensitive Windows privilege management operations.
Note: As of the latest repository commit, the token-privilege repository contains only project scaffolding and configuration files. The architecture described in this document is based on the detailed commit instructions that define the intended design and implementation patterns for the crate.
Module Organization#
The crate's module structure follows a three-layer architecture that strictly isolates unsafe FFI operations from safe public APIs. The module organization is reflected in the commit scope taxonomy, which requires specific scope identifiers for different architectural layers.
Core/API Modules#
The public API layer consists of modules that expose safe interfaces to consumers:
lib- Entry point module that re-exports public types and functions, provides platform-specific stubs for non-Windows systemserror- DefinesTokenPrivilegeErrortype using thiserror 2.0 for idiomatic error handlingelevation- Elevation detection functionality (is_elevated)privilege- Privilege query operations (is_privilege_enabled,has_privilege,enumerate_privileges)privileges- Namespace for Windows privilege constants (e.g.,SE_MANAGE_VOLUME)
Unsafe Boundary Modules#
The FFI isolation layer contains all unsafe code and Windows API interactions:
ffi- All unsafe Win32 FFI calls, RAIIOwnedHandletype, Windows API wrappers; strictlypub(crate)visibilitysafety- Safety invariant documentation and contracts for unsafe operationssecurity- Security-specific concerns and threat model documentation
Module Visibility Strategy#
The architecture enforces a strict visibility boundary:
- Public modules (
elevation,privilege,privileges,error) are exposed throughsrc/lib.rsre-exports - FFI module is marked
pub(crate)and never appears in the public API surface - Safe wrappers in public modules consume FFI functions internally but present safe interfaces externally
This strategy enables downstream crates to add #![forbid(unsafe_code)] to their own code while still using token-privilege functionality, as all unsafe operations are hidden behind safe abstractions.
Safe FFI Wrapping Patterns#
The crate implements a comprehensive strategy for safe FFI wrapping that isolates all unsafe code to a single module while providing safe, ergonomic interfaces to consumers. This pattern is enforced through tooling, code review practices, and strict linting.
Unsafe Code Isolation#
All unsafe code is strictly confined to src/ffi.rs. The architecture enforces this through several mechanisms:
- Single unsafe module: Only
ffi.rscontainsunsafeblocks; all other modules use safe Rust exclusively - Commit discipline: Any change involving
unsafemust useffiorsafetycommit scope and document safety invariants in the commit body - Linting enforcement:
undocumented_unsafe_blocks=denyClippy lint requires safety documentation for every unsafe block - Visibility restriction: The
ffimodule is markedpub(crate), preventing external code from accessing unsafe operations
RAII Handle Management#
Windows token handles require explicit cleanup via CloseHandle. The architecture uses RAII patterns to guarantee correct resource management:
// Conceptual implementation (actual code not yet committed)
pub(crate) struct OwnedHandle(HANDLE);
impl Drop for OwnedHandle {
fn drop(&mut self) {
// SAFETY: Handle was obtained from a valid Windows API call
// and is guaranteed to be valid until this drop is called.
// CloseHandle is safe to call exactly once on a valid handle.
unsafe {
CloseHandle(self.0);
}
}
}
This pattern ensures:
- Automatic cleanup: Token handles are closed when
OwnedHandlegoes out of scope - Exception safety: Handles are closed even if an error or panic occurs
- No double-free: The type system prevents calling
CloseHandlemultiple times - Leak prevention: All
GetTokenInformationpaths properly close handles
FFI Safety Contract#
The documentation strategy includes a dedicated "safety contract section for unsafe FFI boundaries" that specifies:
- Preconditions: What invariants must hold before calling an unsafe function
- Postconditions: What guarantees the function provides after execution
- Validity requirements: Lifetime and validity constraints on pointers and handles
- Thread safety: Whether FFI functions can be called concurrently
- Panic safety: How the code behaves if a panic occurs during FFI operations
Every unsafe block must include a // SAFETY: comment explaining why the operation is safe and what invariants guarantee its correctness.
Cross-Platform Strategy#
The crate provides a unified API surface across all platforms while compiling platform-specific implementations only where needed. This is achieved through conditional compilation and stub functions rather than runtime platform detection.
Windows Platform Implementation#
On Windows targets (cfg(windows)), the crate compiles full implementations:
- Win32 API bindings: Uses the
windowscrate 0.62.2 as a conditional dependency, only included when compiling for Windows - FFI layer: All unsafe Win32 calls in
src/ffi.rsinteract with token privilege APIs likeGetTokenInformation,OpenProcessToken, andLookupPrivilegeValueW - Full functionality: Complete elevation detection and privilege management operations
The Windows-specific features are enabled only when the windows dependency is available, preventing unnecessary binary bloat on other platforms.
Non-Windows Platform Stubs#
On non-Windows platforms (cfg(not(windows))), the crate provides stub implementations that maintain API compatibility:
// Conceptual implementation (actual code not yet committed)
#[cfg(not(windows))]
pub const fn is_elevated() -> Result<bool, TokenPrivilegeError> {
Err(TokenPrivilegeError::UnsupportedPlatform)
}
#[cfg(not(windows))]
pub const fn has_privilege(name: &str) -> Result<bool, TokenPrivilegeError> {
Err(TokenPrivilegeError::UnsupportedPlatform)
}
Key characteristics of the stub strategy:
const fnstubs: Stubs are const functions, allowing compile-time evaluation and zero runtime overhead- Consistent errors: All operations return
Err(UnsupportedPlatform)rather than panicking or having undefined behavior - API parity: Function signatures match exactly between Windows and non-Windows builds
- No dependencies: The
windowscrate is not compiled on non-Windows platforms, reducing build time and binary size
Platform-Gated Testing#
The testing strategy accounts for platform differences:
- Windows tests: Full integration tests verify actual privilege operations and elevation detection
- Non-Windows tests: Tests verify that stub functions return
UnsupportedPlatformerrors correctly - CI matrix: Cross-platform CI runs on
windows-latestand other platforms to ensure API consistency
Public API Surface#
The public API is designed for ergonomic access to Windows token privilege operations while maintaining type safety and explicit error handling.
Core Functions#
Elevation Detection
// Conceptual API signature
pub fn is_elevated() -> Result<bool, TokenPrivilegeError>
Checks if the current process token is running with elevated privileges (administrator rights on Windows). Returns true if elevated, false if not elevated, or an error on failure.
Privilege Status Queries
// Conceptual API signatures
pub fn is_privilege_enabled(name: &str) -> Result<bool, TokenPrivilegeError>
pub fn has_privilege(name: &str) -> Result<bool, TokenPrivilegeError>
is_privilege_enabled: Checks if a specific privilege is currently enabled for the process tokenhas_privilege: Checks if the process token has been granted a privilege, regardless of whether it's enabled
Privilege Enumeration
// Conceptual API signature
pub fn enumerate_privileges() -> Result<Vec<PrivilegeInfo>, TokenPrivilegeError>
Returns a list of all privileges associated with the current process token, including their enabled/disabled state.
Types#
PrivilegeInfo
// Conceptual structure
pub struct PrivilegeInfo {
pub name: String,
pub enabled: bool,
pub attributes: u32,
}
Represents information about a single privilege in the process token.
TokenPrivilegeError
// Conceptual error enum using thiserror
#[derive(Error, Debug)]
pub enum TokenPrivilegeError {
#[error("operation not supported on this platform")]
UnsupportedPlatform,
#[error("invalid privilege name: {0}")]
InvalidPrivilegeName(String),
#[error("Windows API error: {0}")]
WindowsApiError(#[from] std::io::Error),
// Additional variants...
}
Comprehensive error type covering all failure modes with descriptive messages.
Privilege Constants#
The privileges module provides constants for Windows privilege names:
// Conceptual constants
pub mod privileges {
pub const SE_DEBUG_PRIVILEGE: &str = "SeDebugPrivilege";
pub const SE_MANAGE_VOLUME: &str = "SeManageVolumePrivilege";
pub const SE_BACKUP_PRIVILEGE: &str = "SeBackupPrivilege";
pub const SE_RESTORE_PRIVILEGE: &str = "SeRestorePrivilege";
// ... additional SE_* constants
}
Design Principles#
The API adheres to several key principles:
- No unsafe exposure: Consumers never interact with unsafe code directly
- Explicit error handling: All operations return
Resulttypes; no panics or unwraps - Platform transparency: Same API on all platforms with clear
UnsupportedPlatformerrors - Type safety: Strong typing prevents misuse (e.g., string constants for privilege names)
- Idiomatic Rust: Follows Rust naming conventions and error handling patterns
Dependency Choices#
The crate's dependency strategy balances functionality, security, and minimal external dependencies. All dependencies are carefully selected to serve specific architectural needs.
Runtime Dependencies#
thiserror 2.0.18 - Error Type Derivation
- Purpose: Provides procedural macros for deriving
std::error::Errorimplementations - Usage:
TokenPrivilegeErrorenum uses#[derive(Error)]for idiomatic error handling - Rationale: Standard in the Rust ecosystem for error types; compile-time code generation with zero runtime overhead
- Version: 2.0.18 from the 2.0 series
windows 0.62.2 - Win32 API Bindings
- Purpose: Provides safe bindings to Windows APIs
- Platform gating:
cfg(windows)only - not compiled on other platforms - Features: Minimal feature flags for token privilege APIs only (reduces compilation time and binary size)
- API access:
GetTokenInformation,OpenProcessToken,LookupPrivilegeValueW,CloseHandle - Rationale: Official Microsoft-maintained bindings; type-safe FFI layer
- Version: 0.62.2 from the 0.62 series
Development Dependencies#
proptest 1.10.0 - Property-Based Testing
- Purpose: Generate random test cases to verify invariants hold across input space
- Usage: Test privilege name validation, error path handling, edge cases
- Scope:
[dev-dependencies]only - not included in production builds - Rationale: Catches corner cases that hand-written unit tests might miss
- Version: 1.10.0 from the 1.x series
Dependency Management#
The dependencies are managed through:
depscommit scope: All dependency changes require explicit documentation- Minimal features: Only enable necessary features from the
windowscrate - Version pinning: Specific versions in Cargo.toml to ensure reproducible builds
- Security auditing: Tools like cargo-audit (configured in mise.toml) check for known vulnerabilities
Current Implementation Status#
The Cargo.toml currently has no dependencies listed, as the source code has not yet been committed. The dependency configuration described above reflects the intended architecture based on project documentation.
Linting and Code Quality#
The crate enforces strict code quality standards through Clippy lints and additional tooling. These standards are particularly important for FFI code where subtle bugs can lead to memory unsafety.
Clippy Lint Configuration#
The intended Clippy configuration enforces safety and quality guarantees:
[lints.clippy]
pedantic = "warn"
undocumented_unsafe_blocks = "deny"
panic = "deny"
unwrap_used = "deny"
pedantic = "warn"
- Enables the full pedantic lint group covering code quality, idiomatic patterns, and potential bugs
- Includes lints for unnecessary clones, inefficient algorithms, style inconsistencies
- Set to
warnrather thandenyto allow pragmatic overrides where justified
undocumented_unsafe_blocks = "deny"
- Compilation fails if any
unsafeblock lacks a// SAFETY:comment - Forces developers to explicitly document why each unsafe operation is sound
- Critical for FFI code where safety depends on invariants not checked by the compiler
panic = "deny"
- Prohibits direct panic calls (
panic!(),unreachable!(),unimplemented!()) - Enforces error handling through
Resulttypes - Prevents undefined behavior in FFI contexts where panics could violate C ABI contracts
unwrap_used = "deny"
- Bans
.unwrap(),.expect(), and similar panic-inducing operations - Forces explicit error propagation with
?or error handling with pattern matching - Ensures all error paths are handled explicitly
Tooling Ecosystem#
The mise.toml configuration includes additional quality tools:
Security and Dependency Auditing
- cargo-audit: Checks dependencies against the RustSec advisory database for known security vulnerabilities
- cargo-deny: Enforces license compatibility, checks for supply chain issues, validates dependency sources
Code Quality
- cargo-machete: Detects unused dependencies to keep the dependency tree minimal
- Clippy: Installed as a Rust toolchain component for linting
Testing and Coverage
- cargo-nextest: Modern test runner with better performance and output formatting
- cargo-llvm-cov: Code coverage analysis to identify untested code paths
Current Status#
No lints are currently configured in Cargo.toml as the project contains only scaffolding. However, Clippy is installed and the lint configuration will be added when source code is committed.
Testing and Verification#
The crate implements a comprehensive testing strategy that accounts for platform differences, FFI correctness, and safety invariants.
Testing Approach#
Platform-Gated Tests
The testing strategy handles Windows and non-Windows platforms differently:
// Conceptual test structure
#[cfg(windows)]
#[test]
fn test_is_elevated_returns_bool() {
// On Windows: verify actual elevation detection
let result = is_elevated();
assert!(result.is_ok());
assert!(matches!(result.unwrap(), true | false));
}
#[cfg(not(windows))]
#[test]
fn test_is_elevated_returns_unsupported_platform() {
// On non-Windows: verify stub returns correct error
let result = is_elevated();
assert!(matches!(result, Err(TokenPrivilegeError::UnsupportedPlatform)));
}
Key testing patterns:
- Windows tests: Verify actual privilege operations, handle elevation, test edge cases with real Win32 APIs
- Non-Windows tests: Verify stub functions return
UnsupportedPlatformconsistently - Shared tests: API surface compatibility tests that run on all platforms
Property-Based Testing
Uses proptest for generating test cases:
// Conceptual proptest usage
proptest! {
#[test]
fn privilege_name_validation(name in "\\PC*") {
// Verify behavior with arbitrary privilege name inputs
let result = has_privilege(&name);
// Should either succeed or return InvalidPrivilegeName
assert!(result.is_ok() || matches!(
result,
Err(TokenPrivilegeError::InvalidPrivilegeName(_))
));
}
}
Test Execution#
cargo-nextest
The crate uses cargo-nextest as the test runner:
- Parallel test execution with better isolation
- Clearer output formatting with test grouping
- JUnit XML output for CI integration
- Retry flaky tests automatically
Continuous Integration
The CI strategy runs tests across platforms:
windows-latest: Full integration tests with real Windows APIs- Linux/macOS: Stub behavior verification
- Cross-platform matrix: Ensures API consistency across all targets
Code Coverage#
cargo-llvm-cov provides code coverage analysis:
- Line-level coverage reporting
- Branch coverage for conditional logic
- Identifies untested FFI paths and error handling branches
- Platform-specific coverage reports
Commit Verification#
The commit verification process includes:
just ci-check: Runs full CI validation locally before pushingcargo nextest run: Execute test suite- Clippy checks: Ensure all lints pass
- Format checks: Verify code formatting with rustfmt
- Safety review: Commits touching FFI require safety impact documentation
Documentation Strategy#
The crate provides comprehensive documentation through multiple channels: rustdoc API documentation, an mdbook user guide, and inline safety documentation for FFI code.
mdbook Configuration#
The project uses mdbook with extensive plugins to build user-facing documentation:
Core Plugins
- mdbook-linkcheck: Validates all links in documentation, preventing dead links
- mdbook-mermaid: Enables mermaid diagrams for architecture and flow visualizations
- mdbook-tabs: Provides tabbed content for platform-specific examples
- mdbook-toc: Generates tables of contents for long pages
- mdbook-admonish: Adds styled callout boxes (warnings, notes, tips)
Integration Plugins
- mdbook-open-on-gh: Links documentation sections directly to source code on GitHub
- mdbook-i18n-helpers: Supports internationalization for multi-language documentation
This plugin ecosystem enables rich, interactive documentation that can show platform-specific code examples side-by-side and visualize the architecture with diagrams.
Safety Documentation#
The documentation requirements include a dedicated "safety contract section for unsafe FFI boundaries" covering:
Safety Contracts
// Conceptual documentation structure
/// # Safety
///
/// ## Preconditions
/// - `handle` must be a valid token handle obtained from `OpenProcessToken`
/// - `handle` must not have been closed by a previous `CloseHandle` call
/// - The caller must have appropriate privileges to query token information
///
/// ## Postconditions
/// - If successful, returns token elevation information
/// - The handle remains valid after this call (non-consuming)
/// - On error, the handle is still valid and must be closed by the caller
///
/// ## Invariants
/// - This function does not transfer ownership of the handle
/// - Thread-safe: can be called concurrently with different handles
/// - Panic-safe: will not panic; all errors are returned via Result
unsafe fn get_token_elevation(handle: HANDLE) -> Result<bool, TokenPrivilegeError>
Required Documentation Elements
- Preconditions that must hold before calling unsafe functions
- Postconditions guaranteeing function behavior after execution
- Ownership and lifetime semantics for handles and pointers
- Thread safety properties
- Panic safety guarantees
API Documentation#
Standard rustdoc documentation covers:
- Module documentation: Overview of each module's purpose and design
- Function documentation: Parameter descriptions, return values, example usage
- Type documentation: Struct field meanings, enum variant semantics
- Error documentation: When each error variant occurs and how to handle it
- Examples: Inline code examples showing common usage patterns
Documentation Testing#
Rust's doctests ensure example code remains correct:
/// Check if the current process is elevated.
///
/// # Examples
///
/// ```
/// # use token_privilege::is_elevated;
/// let elevated = is_elevated()?;
/// if elevated {
/// println!("Running with admin rights");
/// }
/// # Ok::<(), token_privilege::TokenPrivilegeError>(())
/// ```
pub fn is_elevated() -> Result<bool, TokenPrivilegeError>
Doctests are compiled and executed as part of cargo test, ensuring documentation examples stay in sync with the actual API.
Rust Edition and MSRV#
The crate adopts Rust 2024 edition with a minimum supported Rust version (MSRV) of 1.85.
Rust 2024 Edition#
The crate is configured to use edition = "2024" in Cargo.toml, representing the latest Rust edition:
Benefits
- Access to latest language features and improvements
- Modern module system semantics
- Enhanced pattern matching capabilities
- Improved type inference and diagnostics
Implications
- Requires recent Rust toolchain for development
- Forward-compatible with future Rust releases
- May limit adoption by projects using older Rust versions
MSRV 1.85#
The minimum supported Rust version is 1.85:
Rationale
- Edition 2024 support requires Rust 1.85 or later
- Access to modern language features needed for safe FFI abstractions
- Recent improvements to const evaluation (used in platform stubs)
- Better error diagnostics for unsafe code
Maintenance
- MSRV will be tracked in CI to prevent accidental breakage
- Updates to MSRV will be considered breaking changes
- Dependencies must respect the MSRV constraint
The choice of Rust 2024 and MSRV 1.85 prioritizes modern language features and safety guarantees over compatibility with older Rust toolchains, reflecting the crate's focus on correctness and security.
Usage Examples#
These examples demonstrate how consumers would use the token-privilege crate in their applications. All examples assume the source code has been implemented according to the architecture described in this document.
Basic Elevation Check#
use token_privilege::is_elevated;
fn main() -> Result<(), Box<dyn std::error::Error>> {
match is_elevated()? {
true => println!("Running with elevated privileges"),
false => println!("Running without elevated privileges"),
}
Ok(())
}
On Windows, this queries the process token's elevation status. On non-Windows platforms, it returns Err(TokenPrivilegeError::UnsupportedPlatform).
Checking Specific Privileges#
use token_privilege::{has_privilege, privileges};
fn main() -> Result<(), Box<dyn std::error::Error>> {
if has_privilege(privileges::SE_DEBUG_PRIVILEGE)? {
println!("Can debug other processes");
// Proceed with debugging operations
} else {
println!("Cannot debug - insufficient privileges");
}
Ok(())
}
The privileges module provides constants for all Windows privilege names, ensuring type-safe privilege queries.
Enumerating All Privileges#
use token_privilege::enumerate_privileges;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let privileges = enumerate_privileges()?;
println!("Process has {} privileges:", privileges.len());
for priv_info in privileges {
let status = if priv_info.enabled { "enabled" } else { "disabled" };
println!(" {} ({})", priv_info.name, status);
}
Ok(())
}
Cross-Platform Code with #![forbid(unsafe_code)]#
#![forbid(unsafe_code)] // Enforced at compile time
use token_privilege::{is_elevated, TokenPrivilegeError};
fn require_admin() -> Result<(), TokenPrivilegeError> {
match is_elevated() {
Ok(true) => {
println!("Admin access confirmed");
Ok(())
}
Ok(false) => {
eprintln!("This operation requires administrator privileges");
Err(TokenPrivilegeError::InsufficientPrivileges)
}
Err(TokenPrivilegeError::UnsupportedPlatform) => {
println!("Privilege checking not available on this platform");
Ok(()) // Gracefully degrade
}
Err(e) => Err(e),
}
}
This demonstrates the key architectural goal: consumer code can forbid unsafe entirely while still accessing Windows token privilege functionality, because all unsafe operations are hidden within the crate's FFI layer.
Related Architecture Patterns#
The token-privilege crate architecture exemplifies several important patterns in Rust systems programming:
Safe FFI Wrapper Pattern#
Isolating all unsafe FFI calls to a dedicated, non-public module (ffi.rs with pub(crate) visibility) creates a clear safety boundary. This pattern enables:
- Auditing: Security audits can focus on a single module containing all unsafe code
- Encapsulation: Public APIs never expose raw FFI types or unsafe operations
- Downstream safety: Consumers can use
#![forbid(unsafe_code)]in their own code - Testability: Safe wrappers can be tested without direct FFI interactions
RAII Resource Management#
Using Rust's Drop trait for automatic resource cleanup (OwnedHandle for Windows handles) ensures:
- Exception safety: Resources are cleaned up even if panics or errors occur
- No resource leaks: The type system guarantees cleanup at scope exit
- Composability: RAII types can be composed without manual cleanup logic
- Ergonomics: Consumers don't need to remember explicit cleanup calls
Type-Driven Safety#
Leveraging Rust's type system to enforce safety invariants:
- Ownership types:
OwnedHandleowns the handle and prevents use-after-free - Visibility:
pub(crate)prevents external code from bypassing safety layers - Result types: Explicit error handling with
Result<T, E>instead of panics - Const stubs:
const fnstubs provide compile-time platform behavior
Cross-Platform Abstraction#
Compile-time platform selection via cfg(windows):
- Zero overhead: Non-Windows builds have no Windows dependencies or runtime checks
- API consistency: Same function signatures across all platforms
- Explicit errors: Platform limitations reported via
UnsupportedPlatformerror variant - Build optimization: Only relevant code paths compiled for each target
Zero-Overhead Abstractions#
The architecture maintains Rust's zero-cost abstraction principle:
- RAII cleanup: Compiled to direct
CloseHandlecalls with no runtime wrapper overhead - Const stubs: Platform stubs are
const fn, potentially optimized away at compile time - Inline FFI wrappers: Small FFI wrapper functions can be inlined by the optimizer
- No virtual dispatch: All types and calls are statically known at compile time
These patterns combine to create an architecture that provides both memory safety guarantees and performance characteristics equivalent to hand-written C code, while offering a more ergonomic and maintainable API surface.
Relevant Code Files#
The following table describes the intended code file structure. Note: These files do not yet exist in the repository; this structure is based on the architectural design documented in commit instructions.
| File | Purpose | Visibility | Key Components |
|---|---|---|---|
src/lib.rs | Crate entry point, public API re-exports, platform stubs for non-Windows | Public | Module declarations, re-exports, cfg-gated stubs |
src/ffi.rs | All unsafe Win32 FFI calls, Windows API wrappers | pub(crate) only | OwnedHandle RAII type, unsafe blocks, FFI bindings |
src/elevation.rs | Elevation detection implementation | Public (via lib.rs) | is_elevated() function, token elevation queries |
src/privilege.rs | Privilege query operations | Public (via lib.rs) | is_privilege_enabled(), has_privilege(), enumerate_privileges() |
src/privileges.rs | Windows privilege name constants | Public (via lib.rs) | SE_DEBUG_PRIVILEGE, SE_MANAGE_VOLUME, etc. |
src/error.rs | Error type definitions | Public (via lib.rs) | TokenPrivilegeError enum with thiserror derives |
Cargo.toml | Package metadata, dependencies, lints | Config | Package info, thiserror, windows crate, Clippy config |
.github/commit-instructions.md | Architecture documentation, commit conventions | Docs | Module scopes, safety requirements, API surface |
Key Architectural Files#
src/ffi.rs - The critical safety boundary where all unsafe code resides. Contains:
- Windows API function bindings (
GetTokenInformation,OpenProcessToken, etc.) OwnedHandlestruct implementing Drop for automaticCloseHandle- All unsafe blocks with mandatory
// SAFETY:documentation - Private helper functions wrapping Win32 calls
src/lib.rs - The orchestration layer that:
- Declares all public modules
- Re-exports public types and functions for convenient consumer access
- Provides
#[cfg(not(windows))]stub implementations returningUnsupportedPlatform - Maintains consistent API surface across all platforms
src/error.rs - Comprehensive error handling:
TokenPrivilegeErrorenum covering all failure modes#[derive(Error)]from thiserror for automatic Error trait implementation- Platform-specific error variants (
UnsupportedPlatform,WindowsApiError) - Descriptive error messages for debugging
Configuration Files#
Cargo.toml - Defines the crate's external interface:
- Package metadata (name, version, edition, MSRV)
- Dependency specifications with platform gating
[lints.clippy]section enforcing code quality- Feature flags if needed for optional functionality
.github/commit-instructions.md - Documents architectural decisions:
- Required commit message scopes mapping to modules
- Safety documentation requirements for unsafe code
- Platform behavior expectations
- API surface contracts