Skip to main content

this_env/env/
structs.rs

1//this.env/env/src/env/structs.rs
2// by suiGn
3//! Contains the core data structures and types used in the `this.env` crate.
4use chrono::{DateTime, Utc};
5use crate::middleware::env_request::EnvRequestInfo;
6use serde::{Serialize, Deserialize};
7use std::collections::HashMap;
8/// Endorser signature and approval status
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct Endorsement {
11    pub endorser: String,
12    pub approved: bool,
13    pub timestamp: u64,
14}
15
16/// Represents the type of environment where an identity operates.
17///
18/// # Examples
19///
20/// ```
21/// use this_env::env::EnvType;
22/// let t = EnvType::Localhost;
23/// ```
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub enum EnvType {
26    Localhost,
27    RemoteWeb,
28    Extension,
29    Desktop,
30    P2P,
31}
32
33/// Represents the level of trust assigned to an environment.
34///
35/// # Examples
36///
37/// ```
38/// use this_env::env::TrustLevel;
39/// let trust = TrustLevel::High;
40/// ```
41#[derive(Debug, Clone, Serialize, Deserialize)]
42pub enum TrustLevel { 
43    Untrusted,
44    Low,
45    Medium,
46    High,
47    Full,
48}
49
50/// Represents metadata and analytics for a specific route within an environment.
51#[derive(Debug, Clone, Serialize, Deserialize, Default)]
52pub struct RouteInfo {
53    /// Number of times this route was accessed.
54    pub hit_count: u64,
55    /// Timestamp of the last time this route was accessed.
56    pub last_seen: DateTime<Utc>,
57    /// Key-value metadata for this specific route.
58    pub metadata: HashMap<String, String>,
59}
60
61// Implement ToSql and FromSql for EnvType and TrustLevel
62use rusqlite::{ToSql, Result as SqlResult};
63use rusqlite::types::{FromSql, FromSqlError, ValueRef, ToSqlOutput, Value};
64impl ToSql for EnvType {
65    fn to_sql(&self) -> SqlResult<ToSqlOutput<'_>> {
66        Ok(ToSqlOutput::Owned(Value::Text(match self {
67            EnvType::Localhost => "Localhost",
68            EnvType::RemoteWeb => "RemoteWeb",
69            EnvType::Extension => "Extension",
70            EnvType::Desktop => "Desktop",
71            EnvType::P2P => "P2P",
72        }.to_string())))
73    }
74}
75
76impl FromSql for EnvType {
77    fn column_result(value: ValueRef<'_>) -> Result<Self, FromSqlError> {
78        match value.as_str()? {
79            "Localhost" => Ok(EnvType::Localhost),
80            "RemoteWeb" => Ok(EnvType::RemoteWeb),
81            "Extension" => Ok(EnvType::Extension),
82            "Desktop" => Ok(EnvType::Desktop),
83            "P2P" => Ok(EnvType::P2P),
84            _ => Err(FromSqlError::InvalidType),
85        }
86    }
87}
88
89impl ToSql for TrustLevel {
90    fn to_sql(&self) -> SqlResult<ToSqlOutput<'_>> {
91        Ok(ToSqlOutput::Owned(Value::Text(match self {
92            TrustLevel::Untrusted => "Untrusted",
93            TrustLevel::Low => "Low",
94            TrustLevel::Medium => "Medium",
95            TrustLevel::High => "High",
96            TrustLevel::Full => "Full",
97        }.to_string())))
98    }
99}
100
101
102impl FromSql for TrustLevel {
103    fn column_result(value: ValueRef<'_>) -> Result<Self, FromSqlError> {
104        match value.as_str()? {
105            "Untrusted" => Ok(TrustLevel::Untrusted),
106            "Low" => Ok(TrustLevel::Low),
107            "Medium" => Ok(TrustLevel::Medium),
108            "High" => Ok(TrustLevel::High),
109            "Full" => Ok(TrustLevel::Full),
110            _ => Err(FromSqlError::InvalidType),
111        }
112    }
113}
114
115/// Represents the endorsement evaluation result for a given environment.
116#[derive(Debug, Clone, Serialize, Deserialize)]
117pub enum EnvStatus {
118    /// The environment has been approved by at least one endorser.
119    Approved {
120        env_request: EnvRequestInfo,
121    },
122    /// The environment has been explicitly blocked.
123    Blocked {
124        env_request: EnvRequestInfo,
125        reason: String,
126    },
127    /// The environment has no endorsements and is pending approval.
128    PendingApproval {
129        env_request: EnvRequestInfo,
130        reason: String,
131    },
132}
133
134#[derive(Debug, Clone, Serialize, Deserialize)]
135pub struct EnvRequestLog {
136    pub timestamp: String,
137    pub method: String,
138    pub path: String,
139    pub ip: Option<String>,
140    pub host: String,
141    pub headers: String,
142    pub decision: String,
143    pub reason: String,
144    pub domain: String,
145}
146
147
148use crate::middleware::env_request::EnvRequest;
149impl From<EnvRequest> for EnvRequestLog {
150    fn from(req: EnvRequest) -> Self {
151        match req {
152            EnvRequest::Http(http) => Self {
153                timestamp: Utc::now().to_rfc3339(),
154                method: http.method,
155                path: http.path,
156                ip: http.ip,
157                host: http.host.clone(),
158                headers: serde_json::to_string(&http.headers).unwrap_or_default(),
159                decision: String::new(),
160                reason: String::new(),
161                domain: http.headers.get("domain").cloned().unwrap_or_else(|| http.host.clone()),
162            },
163            EnvRequest::Ws(ws) => Self {
164                timestamp: Utc::now().to_rfc3339(),
165                method: "WS".into(),
166                path: "".into(),
167                ip: ws.ip,
168                host: ws.host.clone(),
169                headers: serde_json::to_string(&ws.headers).unwrap_or_default(),
170                decision: String::new(),
171                reason: String::new(),
172                domain: ws.headers.get("domain").cloned().unwrap_or_else(|| ws.host.clone()),
173            },
174            EnvRequest::Cli(_) => Self {
175                timestamp: Utc::now().to_rfc3339(),
176                method: "CLI".into(),
177                path: "".into(),
178                ip: None,
179                host: "localhost".into(),
180                headers: "{}".into(),
181                decision: String::new(),
182                reason: String::new(),
183                domain: "localhost".into(),
184            },
185        }
186    }
187}