trace2e_core/traceability/
api.rs

1//! Traceability API definitions.
2//!
3//! This module defines the core API types for the trace2e traceability system, which provides
4//! comprehensive data lineage tracking and compliance enforcement across distributed systems.
5//!
6//! The API is organized into three main communication patterns:
7//!
8//! ## Process-to-Middleware (P2M) API
9//! Enables processes to register resources (files, network streams) and request I/O operations
10//! with traceability guarantees. Processes must first enroll their resources before performing
11//! tracked I/O operations.
12//!
13//! ## Middleware-to-Middleware (M2M) API  
14//! Facilitates communication between distributed middleware instances for cross-node compliance
15//! checking, flow coordination, and provenance synchronization.
16//!
17//! ## Operator-to-Middleware (O2M) API
18//! Provides administrative interfaces for policy management, compliance configuration, and
19//! provenance querying by external operators and organizations.
20//!
21//! ## Internal Service APIs
22//! Defines request/response types for internal services:
23//! - **Sequencer**: Resource management and flow control
24//! - **Provenance**: Data lineage tracking and ancestry management  
25//! - **Compliance**: Policy enforcement and authorization decisions
26
27use std::collections::{HashMap, HashSet};
28
29use super::core::compliance::{ConfidentialityPolicy, Policy};
30use crate::traceability::naming::Resource;
31
32/// Process-to-Middleware (P2M) request types.
33///
34/// These requests are initiated by application processes to the middleware for resource
35/// enrollment and I/O operation authorization. The workflow typically follows:
36/// 1. Enroll resources using `LocalEnroll` or `RemoteEnroll`
37/// 2. Request I/O permission using `IoRequest`  
38/// 3. Report operation completion using `IoReport`
39#[derive(Debug, Clone)]
40pub enum P2mRequest {
41    /// Register a file resource with the middleware for traceability tracking.
42    ///
43    /// Must be called before any I/O operations on the file. The middleware will
44    /// create appropriate resource identifiers and establish compliance policies.
45    LocalEnroll {
46        /// Process identifier that opened the file
47        pid: i32,
48        /// File descriptor assigned by the operating system
49        fd: i32,
50        /// Absolute or relative path to the file
51        path: String,
52    },
53
54    /// Register a network stream resource with the middleware for traceability tracking.
55    ///
56    /// Used for TCP connections.
57    /// Both endpoints must be specified to enable proper flow tracking.
58    RemoteEnroll {
59        /// Process identifier that opened the stream
60        pid: i32,
61        /// File descriptor assigned by the operating system  
62        fd: i32,
63        /// Local socket address (e.g., "127.0.0.1:8080")
64        local_socket: String,
65        /// Remote peer socket address (e.g., "192.168.1.100:9000")
66        peer_socket: String,
67    },
68
69    /// Request authorization to perform an I/O operation on a previously enrolled resource.
70    ///
71    /// The middleware will evaluate compliance policies, check data lineage requirements,
72    /// and coordinate with remote middleware instances if necessary before granting access.
73    IoRequest {
74        /// Process identifier requesting the operation
75        pid: i32,
76        /// File descriptor for the target resource
77        fd: i32,
78        /// Direction of data flow: true for output (write), false for input (read)
79        output: bool,
80    },
81
82    /// Report the completion status of a previously authorized I/O operation.
83    ///
84    /// This enables the middleware to update provenance records, release flow reservations,
85    /// and maintain accurate audit trails for compliance purposes.
86    IoReport {
87        /// Process identifier that performed the operation
88        pid: i32,
89        /// File descriptor for the resource
90        fd: i32,
91        /// Grant identifier returned from the corresponding `IoRequest`
92        grant_id: u128,
93        /// Operation outcome: true for success, false for failure
94        result: bool,
95    },
96}
97
98/// Process-to-Middleware (P2M) response types.
99///
100/// Responses sent from the middleware back to application processes following P2M requests.
101#[derive(Debug, Clone, Eq, PartialEq)]
102pub enum P2mResponse {
103    /// Authorization granted for an I/O operation with a unique grant identifier.
104    ///
105    /// Returned in response to `P2mRequest::IoRequest` when the operation is permitted
106    /// by current policies. The grant ID must be included in the subsequent `IoReport`.
107    Grant(u128),
108
109    /// Acknowledgment of successful request processing.
110    ///
111    /// Returned for `LocalEnroll`, `RemoteEnroll`, and `IoReport` requests to confirm
112    /// the operation was completed successfully.
113    Ack,
114}
115
116/// Middleware-to-Middleware (M2M) request types.
117///
118/// These requests enable communication between distributed middleware instances to maintain
119/// consistent compliance policies and provenance records across the network. Used primarily
120/// for cross-node data flows and distributed policy enforcement.
121#[derive(Debug, Clone)]
122pub enum M2mRequest {
123    /// Request compliance policies for a destination resource from its authoritative middleware.
124    ///
125    /// Used when a local middleware needs to evaluate whether a data flow to a remote
126    /// resource is permitted. The source middleware queries the destination middleware
127    /// to obtain current policies before authorizing the operation.
128    GetDestinationCompliance {
129        /// Source resource where data originates
130        source: Resource,
131        /// Destination resource where data will be written
132        destination: Resource,
133    },
134
135    /// Request compliance policies for source resources from their authoritative middleware.
136    ///
137    /// Used by destination middleware to verify that incoming data flows comply with
138    /// source policies and organizational requirements.
139    GetSourceCompliance {
140        /// IP address of the authoritative middleware for the source resources
141        authority_ip: String,
142        /// Set of source resources to query policies for
143        resources: HashSet<Resource>,
144    },
145
146    /// Update provenance records on the destination middleware following a cross-node data flow.
147    ///
148    /// Transfers lineage information from source to destination to maintain complete
149    /// provenance chains across distributed systems.
150    UpdateProvenance {
151        /// Provenance data from source resources organized by node ID
152        source_prov: HashMap<String, HashSet<Resource>>,
153        /// Destination resource receiving the data and provenance updates
154        destination: Resource,
155    },
156}
157
158/// Middleware-to-Middleware (M2M) response types.
159///
160/// Responses sent between middleware instances for distributed coordination and policy exchange.
161#[derive(Debug, Clone, Eq, PartialEq)]
162pub enum M2mResponse {
163    /// Compliance policies for requested source resources.
164    ///
165    /// Maps each resource to its current policy, enabling the requesting middleware
166    /// to evaluate flow compliance before authorization.
167    SourceCompliance(HashMap<Resource, Policy>),
168
169    /// Compliance policy for a specific destination resource.
170    ///
171    /// Contains the current policy that will be applied to incoming data flows
172    /// to the requested destination resource.
173    DestinationCompliance(Policy),
174
175    /// Acknowledgment of successful request processing.
176    ///
177    /// Confirms that provenance updates or other operations completed successfully.
178    Ack,
179}
180
181/// Operator-to-Middleware (O2M) request types.
182///
183/// Administrative requests from external operators, compliance officers, and organizations
184/// for policy management and provenance analysis. These operations typically require
185/// elevated privileges and are used for governance and audit purposes.
186pub enum O2mRequest {
187    /// Retrieve current compliance policies for a set of resources.
188    ///
189    /// Enables operators to audit current policy configurations and verify
190    /// compliance with organizational or regulatory requirements.
191    GetPolicies(HashSet<Resource>),
192
193    /// Set a complete compliance policy for a specific resource.
194    ///
195    /// Replaces the existing policy with a new configuration that defines
196    /// confidentiality, integrity, and access control requirements.
197    SetPolicy {
198        /// Target resource to apply the policy to
199        resource: Resource,
200        /// New policy configuration
201        policy: Policy,
202    },
203
204    /// Set confidentiality requirements for a specific resource.
205    ///
206    /// Updates only the confidentiality aspects of the resource's policy,
207    /// leaving other policy components unchanged.
208    SetConfidentiality {
209        /// Target resource to update
210        resource: Resource,
211        /// New confidentiality policy requirements
212        confidentiality: ConfidentialityPolicy,
213    },
214
215    /// Set integrity level requirements for a specific resource.
216    ///
217    /// Updates the minimum integrity level required for data flows involving
218    /// this resource, typically on a scale from 0 (lowest) to higher values.
219    SetIntegrity {
220        /// Target resource to update
221        resource: Resource,
222        /// Minimum integrity level (higher values indicate stricter requirements)
223        integrity: u32,
224    },
225
226    /// Mark a resource as deleted for compliance and audit purposes.
227    ///
228    /// Indicates that the resource has been removed from the system while
229    /// preserving its historical provenance for audit trails.
230    SetDeleted(Resource),
231
232    /// Grant consent for data processing operations on a resource.
233    ///
234    /// Sets the consent flag to allow data flows and processing operations
235    /// that require explicit permission, typically for privacy compliance.
236    SetConsent(Resource),
237
238    /// Retrieve the complete provenance lineage for a resource.
239    ///
240    /// Returns all upstream resources and middleware nodes that have contributed
241    /// data to the specified resource, enabling full traceability analysis.
242    GetReferences(Resource),
243}
244
245/// Operator-to-Middleware (O2M) response types.
246///
247/// Responses sent to operators and administrators following policy management and
248/// provenance query requests.
249#[derive(Debug, Clone, Eq, PartialEq)]
250pub enum O2mResponse {
251    /// Current compliance policies for the requested resources.
252    ///
253    /// Maps each requested resource to its current policy configuration,
254    /// enabling operators to review and audit policy settings.
255    Policies(HashMap<Resource, Policy>),
256
257    /// Acknowledgment of successful policy update or configuration change.
258    ///
259    /// Confirms that policy modifications, consent grants, or deletion
260    /// markings were applied successfully.
261    Ack,
262
263    /// Complete provenance lineage for the requested resource.
264    ///
265    /// Maps node IDs to sets of resources, showing the complete ancestry
266    /// and data flow history for traceability analysis.
267    References(HashMap<String, HashSet<Resource>>),
268}
269
270/// Sequencer service request types.
271///
272/// Internal API for the sequencer service, which manages resource reservations and flow
273/// coordination to prevent race conditions and ensure consistent ordering of operations
274/// across the distributed system.
275#[derive(Debug, Clone)]
276pub enum SequencerRequest {
277    /// Reserve exclusive access for a data flow from source to destination.
278    ///
279    /// Prevents concurrent modifications to the destination resource while
280    /// a flow is being processed, ensuring data consistency and atomic operations.
281    ReserveFlow {
282        /// Source resource providing data
283        source: Resource,
284        /// Destination resource receiving data
285        destination: Resource,
286    },
287
288    /// Release a previously reserved flow to allow subsequent operations.
289    ///
290    /// Must be called after flow completion to free the destination resource
291    /// for other operations and maintain system throughput.
292    ReleaseFlow {
293        /// Destination resource to release from reservation
294        destination: Resource,
295    },
296}
297
298/// Sequencer service response types.
299///
300/// Responses from the sequencer service confirming flow reservation and release operations.
301#[derive(Debug, Clone, Eq, PartialEq)]
302pub enum SequencerResponse {
303    /// Confirmation that the requested flow has been successfully reserved.
304    ///
305    /// Indicates that exclusive access has been granted and the flow operation
306    /// may proceed without interference from concurrent operations.
307    FlowReserved,
308
309    /// Confirmation that the flow reservation has been successfully released.
310    ///
311    /// Returns the source and destination resources that were involved in the
312    /// flow, if available, for logging and audit purposes.
313    FlowReleased {
314        /// Source resource that was part of the released flow
315        source: Option<Resource>,
316        /// Destination resource that was part of the released flow
317        destination: Option<Resource>,
318    },
319}
320
321/// Provenance service request types.
322///
323/// Internal API for the provenance service, which tracks data lineage and ancestry
324/// relationships across resources and operations. Maintains comprehensive audit trails
325/// for compliance and data governance purposes.
326#[derive(Debug, Clone)]
327pub enum ProvenanceRequest {
328    /// Retrieve the complete provenance lineage for a resource.
329    ///
330    /// Returns all upstream resources and nodes that have contributed data
331    /// to the specified resource, enabling full traceability analysis.
332    GetReferences(Resource),
333
334    /// Record a new data flow relationship between source and destination resources.
335    ///
336    /// Updates the destination's provenance to include the source resource,
337    /// maintaining the complete lineage chain for audit and compliance purposes.
338    UpdateProvenance {
339        /// Source resource providing data
340        source: Resource,
341        /// Destination resource receiving data and provenance updates
342        destination: Resource,
343    },
344
345    /// Update destination provenance with pre-computed source lineage data.
346    ///
347    /// Used for cross-node flows where source provenance has been collected
348    /// from remote middleware instances and needs to be merged with local records.
349    UpdateProvenanceRaw {
350        /// Pre-computed provenance data organized by source node ID
351        source_prov: HashMap<String, HashSet<Resource>>,
352        /// Destination resource to receive the provenance updates
353        destination: Resource,
354    },
355}
356
357/// Provenance service response types.
358///
359/// Responses from the provenance service containing lineage data and update confirmations.
360#[derive(Debug, Clone, Eq, PartialEq)]
361pub enum ProvenanceResponse {
362    /// Complete provenance lineage for the requested resource.
363    ///
364    /// Maps node IDs to sets of resources, showing all upstream dependencies
365    /// and data sources that have contributed to the resource's current state.
366    Provenance(HashMap<String, HashSet<Resource>>),
367
368    /// Confirmation that provenance was successfully updated with new lineage data.
369    ///
370    /// Indicates that the destination resource's ancestry records now include
371    /// the specified source resource or provenance information.
372    ProvenanceUpdated,
373
374    /// Notification that no provenance update was needed.
375    ///
376    /// Returned when the source resource is already included in the destination's
377    /// provenance, avoiding duplicate entries in the lineage records.
378    ProvenanceNotUpdated,
379}
380
381/// Compliance service request types.
382///
383/// Internal API for the compliance service, which manages policies, evaluates authorization
384/// decisions, and enforces organizational and regulatory requirements for data flows.
385#[derive(Debug, Clone)]
386pub enum ComplianceRequest {
387    /// Evaluate whether a proposed data flow complies with all applicable policies.
388    ///
389    /// Compares source resource policies against destination requirements to determine
390    /// if the flow should be authorized. Considers confidentiality, integrity, consent,
391    /// and other policy constraints.
392    EvalPolicies {
393        /// Policies for source resources organized by authority node ID
394        source_policies: HashMap<String, HashMap<Resource, Policy>>,
395        /// Destination resource receiving the data
396        destination: Resource,
397    },
398
399    /// Retrieve the current compliance policy for a specific resource.
400    ///
401    /// Returns the complete policy configuration including confidentiality,
402    /// integrity, consent, and deletion status for the requested resource.
403    GetPolicy(Resource),
404
405    /// Retrieve current compliance policies for multiple resources.
406    ///
407    /// Batch operation to efficiently query policy configurations for
408    /// multiple resources in a single request.
409    GetPolicies(HashSet<Resource>),
410
411    /// Set a complete compliance policy for a specific resource.
412    ///
413    /// Replaces the existing policy with new configuration that defines
414    /// all aspects of compliance requirements for the resource.
415    SetPolicy {
416        /// Target resource to apply the policy to
417        resource: Resource,
418        /// New complete policy configuration
419        policy: Policy,
420    },
421
422    /// Update confidentiality requirements for a specific resource.
423    ///
424    /// Modifies only the confidentiality aspects of the resource's policy
425    /// while preserving other policy components.
426    SetConfidentiality {
427        /// Target resource to update
428        resource: Resource,
429        /// New confidentiality policy requirements
430        confidentiality: ConfidentialityPolicy,
431    },
432
433    /// Update integrity level requirements for a specific resource.
434    ///
435    /// Sets the minimum integrity level required for operations involving
436    /// this resource, typically on a numerical scale.
437    SetIntegrity {
438        /// Target resource to update
439        resource: Resource,
440        /// Minimum required integrity level
441        integrity: u32,
442    },
443
444    /// Mark a resource as deleted for compliance tracking.
445    ///
446    /// Updates the resource's policy to reflect its deletion status while
447    /// maintaining historical records for audit purposes.
448    SetDeleted(Resource),
449
450    /// Update consent status for data processing operations on a resource.
451    ///
452    /// Sets or revokes consent for operations that require explicit permission,
453    /// typically for privacy and regulatory compliance.
454    SetConsent {
455        /// Target resource to update consent for
456        resource: Resource,
457        /// Consent status: true to grant, false to revoke
458        consent: bool,
459    },
460}
461
462/// Compliance service response types.
463///
464/// Responses from the compliance service containing authorization decisions, policy data,
465/// and update confirmations.
466#[derive(Debug, Clone, Eq, PartialEq)]
467pub enum ComplianceResponse {
468    /// Authorization granted for the requested data flow operation.
469    ///
470    /// Indicates that all policy evaluations passed and the operation
471    /// complies with organizational and regulatory requirements.
472    Grant,
473
474    /// Current compliance policy for the requested resource.
475    ///
476    /// Contains the complete policy configuration including confidentiality,
477    /// integrity, consent, and other compliance requirements.
478    Policy(Policy),
479
480    /// Current compliance policies for multiple requested resources.
481    ///
482    /// Maps each requested resource to its current policy configuration
483    /// for batch policy queries.
484    Policies(HashMap<Resource, Policy>),
485
486    /// Confirmation that a policy update was successfully applied.
487    ///
488    /// Indicates that policy modifications, consent changes, or other
489    /// compliance configuration updates completed successfully.
490    PolicyUpdated,
491
492    /// Notification that no policy update was needed.
493    ///
494    /// Returned when the requested policy change would result in no
495    /// actual modification to the current configuration.
496    PolicyNotUpdated,
497}
498
499#[derive(Debug, Eq, PartialEq)]
500pub enum ConsentRequest {
501    /// Request consent for a data flow operation.
502    ///
503    /// Requests consent from the resource owner for a data flow operation.
504    RequestConsent {
505        /// Source resource providing data
506        source: Resource,
507        /// Destination resource receiving data
508        destination: (Option<String>, Resource),
509    },
510    /// Retrieve all pending consent requests.
511    ///
512    /// Returns a list of all data flow operations currently awaiting consent.
513    PendingRequests,
514    /// Set consent decision for a specific data flow operation.
515    ///
516    /// Updates the consent status for a pending data flow operation.
517    SetConsent {
518        /// Source resource providing data
519        source: Resource,
520        /// Destination resource receiving data
521        destination: (Option<String>, Resource),
522        /// Consent decision: true to grant, false to deny
523        consent: bool,
524    },
525}
526
527#[derive(Debug)]
528#[allow(clippy::type_complexity)]
529pub enum ConsentResponse {
530    /// Consent granted or denied for a data flow.
531    Consent(bool),
532    /// List of all pending consent requests.
533    PendingRequests(
534        Vec<((Resource, Option<String>, Resource), tokio::sync::broadcast::Sender<bool>)>,
535    ),
536    /// Acknowledgment of successful consent decision update.
537    Ack,
538}