dmsc/c/
auth.rs

1//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
2//!
3//! This file is part of DMSC.
4//! The DMSC project belongs to the Dunimd Team.
5//!
6//! Licensed under the Apache License, Version 2.0 (the "License");
7//! You may not use this file except in compliance with the License.
8//! You may obtain a copy of the License at
9//!
10//!     http://www.apache.org/licenses/LICENSE-2.0
11//!
12//! Unless required by applicable law or agreed to in writing, software
13//! distributed under the License is distributed on an "AS IS" BASIS,
14//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15//! See the License for the specific language governing permissions and
16//! limitations under the License.
17
18//! # Auth Module C API
19//!
20//! This module provides C language bindings for DMSC's authentication and authorization
21//! subsystem. The authentication module is responsible for handling user authentication,
22//! session management, permission verification, and OAuth authentication flows. This C API
23//! enables C/C++ applications to integrate with DMSC's security features without requiring
24//! Rust runtime dependencies.
25//!
26//! ## Module Architecture
27//!
28//! The authentication module consists of five primary components:
29//!
30//! - **DMSCAuthConfig**: Centralized configuration container for authentication parameters.
31//!   Manages JWT secret keys, session timeouts, token expiration settings, and OAuth
32//!   provider configurations. This configuration object is required for initializing
33//!   authentication managers and controls security policy enforcement across the system.
34//!
35//! - **DMSCJWTManager**: JSON Web Token (JWT) generation and validation handler.
36//!   Provides token creation with custom claims, signature verification using HMAC-SHA256,
37//!   expiration checking, and audience validation. The JWT manager supports both access
38//!   tokens and refresh tokens with configurable expiration periods. It implements RFC 7519
39//!   specification for secure stateless authentication in distributed systems.
40//!
41//! - **DMSCSessionManager**: Server-side session state management for stateful authentication.
42//!   Maintains active user sessions in memory with configurable timeout policies. Supports
43//!   session creation, validation, renewal, and invalidation. The session manager uses
44//!   DashMap for thread-safe concurrent access in multi-threaded server environments.
45//!
46//! - **DMSCPermissionManager**: Role-based access control (RBAC) permission evaluator.
47//!   Manages user roles, permissions, and resource access policies. Supports hierarchical
48//!   role definitions with permission inheritance. The permission manager provides efficient
49//!   permission checking for high-throughput authorization decisions.
50//!
51//! - **DMSCOAuthManager**: OAuth 2.0 authentication flow handler for third-party integrations.
52//!   Implements authorization code flow for web applications, implicit flow for single-page
53//!   applications, and client credentials flow for machine-to-machine communication. Supports
54//!   multiple OAuth providers with configurable redirect URIs and scope requirements.
55//!
56//! ## Memory Management
57//!
58//! All C API objects use opaque pointers with manual memory management. The caller is
59//! responsible for freeing allocated objects using the provided destructor functions.
60//! Objects must not be used after being freed to prevent use-after-free vulnerabilities.
61//! Null pointer checks must be performed before accessing any object methods or fields.
62//!
63//! ## Thread Safety
64//!
65//! All underlying Rust implementations use synchronization primitives appropriate for
66//! concurrent access. The C API itself is not thread-safe; callers must implement their
67//! own synchronization when accessing objects from multiple threads simultaneously.
68//!
69//! ## Error Handling
70//!
71//! Functions return null pointers or error codes (-1) to indicate failure conditions.
72//! Callers should check return values and handle errors appropriately. Memory allocation
73//! failures and invalid arguments are the primary error conditions.
74//!
75//! ## Usage Example
76//!
77//! ```c
78//! // Create authentication configuration
79//! CDMSCAuthConfig* config = dmsc_auth_config_new();
80//!
81//! // Create JWT manager with secret and expiration
82//! CDMSCJWTManager* jwt = dmsc_jwt_manager_new("your-secret-key", 3600);
83//!
84//! // Generate token for authenticated user
85//! const char* token = dmsc_jwt_manager_generate(jwt, "user-id", "admin");
86//!
87//! // Validate token on subsequent requests
88//! bool valid = dmsc_jwt_manager_validate(jwt, token);
89//!
90//! // Cleanup resources
91//! dmsc_jwt_manager_free(jwt);
92//! dmsc_auth_config_free(config);
93//! ```
94//!
95//! ## Dependencies
96//!
97//! This module depends on the following core DMSC modules:
98//!
99//! - `crate::auth`: Rust implementation of authentication logic
100//! - `crate::prelude`: Common types and traits
101//!
102//! ## Feature Flags
103//!
104//! The authentication module is enabled by default with the "auth" feature flag.
105//! Disable this feature to reduce binary size in deployments that do not require
106//! authentication capabilities.
107
108use crate::auth::{DMSCAuthConfig, DMSCJWTManager, DMSCSessionManager, DMSCPermissionManager, DMSCOAuthManager};
109use std::ffi::c_char;
110
111c_wrapper!(CDMSCAuthConfig, DMSCAuthConfig);
112
113c_wrapper!(CDMSCJWTManager, DMSCJWTManager);
114
115c_wrapper!(CDMSCSessionManager, DMSCSessionManager);
116
117c_wrapper!(CDMSCPermissionManager, DMSCPermissionManager);
118
119c_wrapper!(CDMSCOAuthManager, DMSCOAuthManager);
120
121c_constructor!(dmsc_auth_config_new, CDMSCAuthConfig, DMSCAuthConfig, DMSCAuthConfig::default());
122
123c_destructor!(dmsc_auth_config_free, CDMSCAuthConfig);
124
125/// Creates a new CDMSCJWTManager instance with specified secret and expiration.
126///
127/// Initializes a JWT manager for token generation and validation. The manager uses
128/// HMAC-SHA256 (HS256) algorithm for signing tokens. The secret key must be kept
129/// confidential and should be at least 256 bits (32 bytes) for adequate security.
130///
131/// # Parameters
132///
133/// - `secret`: Pointer to null-terminated C string containing the JWT signing secret.
134///   Must not be NULL. Empty strings are accepted but provide minimal security.
135/// - `expiry_secs`: Token expiration time in seconds from issuance. Tokens will be
136///   rejected as expired after this duration. Typical values range from 300 (5 minutes)
137///   for sensitive operations to 86400 (24 hours) for long-lived sessions.
138///
139/// # Returns
140///
141/// Pointer to newly allocated CDMSCJWTManager on success, or NULL if:
142/// - `secret` parameter is NULL
143/// - Memory allocation fails
144/// - Secret contains invalid UTF-8 sequences
145///
146/// # Security Considerations
147///
148/// The secret key should be:
149/// - Generated using cryptographically secure random number generator
150/// - Stored securely (environment variables, secrets manager)
151/// - Rotated periodically in production environments
152/// - Unique per environment (development, staging, production)
153///
154/// # Example
155///
156/// ```c
157/// CDMSCJWTManager* jwt = dmsc_jwt_manager_new(
158///     "your-256-bit-secret-key-here",
159///     3600  // 1 hour expiration
160/// );
161/// if (jwt == NULL) {
162///     // Handle initialization failure
163/// }
164/// ```
165#[no_mangle]
166pub extern "C" fn dmsc_jwt_manager_new(secret: *const c_char, expiry_secs: u64) -> *mut CDMSCJWTManager {
167    if secret.is_null() {
168        return std::ptr::null_mut();
169    }
170    unsafe {
171        let secret_str = match std::ffi::CStr::from_ptr(secret).to_str() {
172            Ok(s) => s,
173            Err(_) => return std::ptr::null_mut(),
174        };
175        let manager = DMSCJWTManager::create(secret_str.to_string(), expiry_secs);
176        Box::into_raw(Box::new(CDMSCJWTManager::new(manager)))
177    }
178}
179
180c_destructor!(dmsc_jwt_manager_free, CDMSCJWTManager);
181
182/// Creates a new CDMSCSessionManager instance with specified session timeout.
183///
184/// Initializes a session manager for stateful authentication sessions. Sessions track
185/// authenticated user state and provide automatic timeout management for security.
186///
187/// # Parameters
188///
189/// - `timeout_secs`: Session idle timeout in seconds. Sessions are considered expired
190///   if no activity occurs within this duration. The timeout is reset on each
191///   authenticated request. Typical values range from 300 to 1800 seconds.
192///
193/// # Returns
194///
195/// Pointer to newly allocated CDMSCSessionManager. Never returns NULL as the
196/// implementation uses unwrap for default configuration.
197///
198/// # Session Behavior
199///
200/// Active sessions will be invalidated after:
201/// - `timeout_secs` seconds of inactivity
202/// - Explicit call to session invalidation function
203/// - Server shutdown or process termination
204///
205/// Expired sessions remain in memory until:
206/// - Automatic cleanup interval runs
207/// - Session count exceeds maximum capacity
208/// - Manual cleanup function is called
209#[no_mangle]
210pub extern "C" fn dmsc_session_manager_new(timeout_secs: u64) -> *mut CDMSCSessionManager {
211    let manager = DMSCSessionManager::new(timeout_secs);
212    Box::into_raw(Box::new(CDMSCSessionManager::new(manager)))
213}
214
215c_destructor!(dmsc_session_manager_free, CDMSCSessionManager);
216
217/// Creates a new CDMSCPermissionManager instance.
218///
219/// Initializes an empty permission manager with default configuration. Roles and
220/// permissions must be added through configuration or management APIs before use.
221///
222/// # Returns
223///
224/// Pointer to newly allocated CDMSCPermissionManager. Never returns NULL.
225///
226/// # Initial State
227///
228/// A newly created permission manager:
229/// - Contains no roles
230/// - Has no role assignments
231/// - Has no resource permissions defined
232///
233/// # Configuration
234///
235/// Before the permission manager can evaluate access, it must be configured with:
236/// - Role definitions (hierarchy, permissions per role)
237/// - User role assignments
238/// - Resource permission mappings
239#[no_mangle]
240pub extern "C" fn dmsc_permission_manager_new() -> *mut CDMSCPermissionManager {
241    let manager = DMSCPermissionManager::new();
242    Box::into_raw(Box::new(CDMSCPermissionManager::new(manager)))
243}
244
245c_destructor!(dmsc_permission_manager_free, CDMSCPermissionManager);