Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! # Snapshot Model

use chrono::{DateTime, Utc};
use geekorm::{Connection, prelude::*};
use log::debug;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, str::FromStr};

use crate::{
    KonarrError,
    models::{Alerts, Dependencies, ProjectSnapshots, Projects, security::SecuritySeverity},
};

pub mod metadata;
pub mod sboms;

pub use metadata::{SnapshotMetadata, SnapshotMetadataKey};

/// HashMap of Alerts Summary
pub type AlertsSummary = HashMap<SecuritySeverity, u16>;

/// Snapshot Model
#[derive(Table, Debug, Default, Clone, Serialize, Deserialize)]
pub struct Snapshot {
    /// Primary Key
    #[geekorm(primary_key, auto_increment)]
    pub id: PrimaryKey<i32>,

    /// Snapshot State
    #[geekorm(new = "SnapshotState::Created")]
    pub state: SnapshotState,

    /// Datetime Created
    #[geekorm(new = "Utc::now()")]
    pub created_at: DateTime<Utc>,

    /// Last Updated / Checked for Changes
    #[serde(default)]
    #[geekorm(update = "Some(Utc::now())")]
    pub updated_at: Option<DateTime<Utc>>,

    /// SBOM (Bill of Materials) as Binary Data
    #[serde(default)]
    sbom: Option<Vec<u8>>,

    /// Error Message (if any)
    pub error: Option<String>,

    /// Components
    #[geekorm(skip)]
    #[serde(skip)]
    pub components: Vec<Dependencies>,

    /// Count of the Components
    #[geekorm(skip)]
    #[serde(skip)]
    pub components_count: usize,

    /// Snapshot Metadata
    #[geekorm(skip)]
    #[serde(skip)]
    pub metadata: HashMap<SnapshotMetadataKey, SnapshotMetadata>,

    /// Snapshot Alerts
    #[geekorm(skip)]
    #[serde(skip)]
    pub alerts: Vec<Alerts>,
}

impl Snapshot {
    /// Get all Snapshots
    pub async fn all(connection: &Connection<'_>) -> Result<Vec<Self>, crate::KonarrError> {
        Ok(Snapshot::query(
            connection,
            Snapshot::query_select()
                .order_by("created_at", QueryOrder::Asc)
                .build()?,
        )
        .await?)
    }

    /// Count snapshots dependencies
    pub async fn count_dependencies(
        &self,
        connection: &Connection<'_>,
    ) -> Result<usize, crate::KonarrError> {
        Ok(Dependencies::row_count(
            connection,
            Dependencies::query_count()
                .where_eq("snapshot_id", self.id)
                .build()?,
        )
        .await? as usize)
    }

    /// Fetch Project for the Snapshot
    pub async fn fetch_project(
        &self,
        connection: &Connection<'_>,
    ) -> Result<Projects, crate::KonarrError> {
        let snaps = ProjectSnapshots::fetch_by_snapshot_id(connection, self.id).await?;
        let snap = snaps.first().ok_or_else(|| geekorm::Error::NoRowsFound {
            query: format!("Cannot find first project snapshot: {}", self.id),
        })?;
        Ok(Projects::fetch_by_primary_key(connection, snap.project_id.clone()).await?)
        // TODO: Add JOIN
        // // SELECT * FROM Projects JOIN ProjectSnapshots ON Projects.id = ProjectSnapshots.project_id WHERE ProjectSnapshots.snapshot_id = 35
        // Ok(Projects::query_first(
        //     connection,
        //     Projects::query_select()
        //         .join(ProjectSnapshots::table())
        //         .where_eq("ProjectSnapshots.snapshot_id", self.id)
        //         .limit(1)
        //         .build()?,
        // )
        // .await?)
    }

    /// Set the state of the Snapshot
    pub async fn set_state(
        &mut self,
        connection: &Connection<'_>,
        state: SnapshotState,
    ) -> Result<(), KonarrError> {
        log::debug!("Processing SBOM for Snapshot: {:?}", self);
        self.state = state;
        // Clear error if not failed
        if self.state != SnapshotState::Failed {
            self.error = None;
        }
        self.updated_at = Some(Utc::now());
        self.update(connection).await?;
        Ok(())
    }

    /// Set the state of the Snapshot and add an error message
    pub async fn set_error(
        &mut self,
        connection: &Connection<'_>,
        error: impl Into<String>,
    ) -> Result<(), crate::KonarrError> {
        let error = error.into();

        log::error!("Failed to process SBOM: {:?}", error);
        self.state = SnapshotState::Failed;
        self.error = Some(error);
        self.updated_at = Some(Utc::now());
        self.update(connection).await?;
        Ok(())
    }

    /// Reset error and state of the Snapshot
    pub async fn reset_error(
        &mut self,
        connection: &Connection<'_>,
    ) -> Result<(), crate::KonarrError> {
        self.state = SnapshotState::Created;
        self.error = None;
        self.updated_at = Some(Utc::now());
        self.update(connection).await?;
        Ok(())
    }

    /// Rescan the Project
    pub async fn rescan(&mut self, connection: &Connection<'_>) -> Result<(), crate::KonarrError> {
        self.set_metadata(connection, SnapshotMetadataKey::Rescan, "true")
            .await?;
        Ok(())
    }

    /// Fetch Dependencies for the Snapshot
    pub async fn fetch_dependencies(
        &self,
        connection: &Connection<'_>,
        page: &Page,
    ) -> Result<Vec<Dependencies>, crate::KonarrError> {
        Dependencies::query(
            connection,
            Dependencies::query_select()
                .where_eq("snapshot_id", self.id)
                .page(page)
                .build()?,
        )
        .await
        .map_err(|e| e.into())
    }

    /// Fetch all Dependencies for the Snapshot
    pub async fn fetch_all_dependencies(
        &self,
        connection: &Connection<'_>,
    ) -> Result<Vec<Dependencies>, crate::KonarrError> {
        let mut deps = Dependencies::query(
            connection,
            Dependencies::query_select()
                .where_eq("snapshot_id", self.id)
                .build()?,
        )
        .await?;

        for dep in deps.iter_mut() {
            dep.fetch(connection).await?;
        }
        Ok(deps)
    }

    /// Get Metadata by Key
    pub fn metadata(&self, key: impl Into<SnapshotMetadataKey>) -> Option<&SnapshotMetadata> {
        self.metadata.get(&key.into())
    }

    /// Find Metadata by Key
    pub fn find_metadata(&self, key: &str) -> Option<&SnapshotMetadata> {
        let key = SnapshotMetadataKey::from_str(key).ok()?;
        self.metadata.get(&key)
    }
    /// Find Metadata by Key and return as usize
    pub fn find_metadata_usize(&self, key: &str) -> usize {
        self.find_metadata(key).map_or(0, |m| m.as_i32() as usize)
    }

    /// Set Metadata for the Snapshot
    pub async fn set_metadata(
        &mut self,
        connection: &Connection<'_>,
        key: impl Into<SnapshotMetadataKey>,
        value: &str,
    ) -> Result<(), crate::KonarrError> {
        let key = key.into();
        SnapshotMetadata::update_or_create(connection, self.id, &key, value).await?;
        Ok(())
    }

    /// Fetch Snapshot by ID
    pub async fn fetch_metadata(
        &mut self,
        connection: &Connection<'_>,
    ) -> Result<(), crate::KonarrError> {
        let metadata = SnapshotMetadata::query(
            connection,
            SnapshotMetadata::query_select()
                .where_eq("snapshot_id", self.id)
                .build()?,
        )
        .await?;

        self.metadata = metadata.into_iter().map(|m| (m.key.clone(), m)).collect();

        Ok(())
    }

    /// Update Metadata for the Snapshot if it exists and is different
    pub async fn update_metadata(
        &mut self,
        connection: &Connection<'_>,
        key: impl Into<SnapshotMetadataKey>,
        value: impl Into<Value>,
    ) -> Result<(), crate::KonarrError> {
        let key = key.into();
        let value: Value = value.into();
        let value_data: Vec<u8> = match value {
            Value::Integer(i) => i.to_string().into_bytes(),
            Value::Boolean(b) => b.to_string().into_bytes(),
            _ => todo!("Unsupported value type"),
        };
        let value_str = String::from_utf8_lossy(&value_data).to_string();

        if let Some(meta) = self.metadata.get(&key) {
            if meta.value != value_data {
                log::debug!("Updating Snapshot({}) {}: \"{}\"", self.id, key, value_str);
                SnapshotMetadata::update_or_create(connection, self.id, &key, value_data).await?;
            } else {
                log::debug!("Snapshot({}) {}: {}", self.id, key, value_str);
            }
        } else {
            log::debug!("Adding Snapshot({}) {}: {}", self.id, key, value_str);
            SnapshotMetadata::update_or_create(connection, self.id, &key, value_data).await?;
        }
        Ok(())
    }

    /// Fetch Alerts for the Snapshot
    pub async fn fetch_alerts(
        &mut self,
        connection: &Connection<'_>,
    ) -> Result<&Vec<Alerts>, crate::KonarrError> {
        let mut alerts = Alerts::fetch_by_snapshot_id(connection, self.id).await?;
        for alert in alerts.iter_mut() {
            alert.fetch_advisory_id(connection).await?;
        }

        log::debug!("Found {} Alerts for Snapshot({})", alerts.len(), self.id);
        self.alerts = alerts;

        Ok(&self.alerts)
    }

    /// Count the number of Alerts for the Snapshot
    pub async fn fetch_alerts_count(
        &self,
        connection: &Connection<'_>,
    ) -> Result<usize, crate::KonarrError> {
        Ok(Alerts::row_count(
            connection,
            Alerts::query_count()
                .where_eq("snapshot_id", self.id)
                .build()?,
        )
        .await? as usize)
    }

    /// Fetch Alerts for the Snapshot with Pagination
    pub async fn fetch_alerts_page(
        &self,
        connection: &Connection<'_>,
        page: &Page,
    ) -> Result<Vec<Alerts>, crate::KonarrError> {
        log::debug!(
            "Fetching alerts for snapshot: {} (page: {})",
            self.id,
            page.page(),
        );
        let mut alerts = Alerts::query(
            connection,
            Alerts::query_select()
                .where_eq("snapshot_id", self.id)
                .page(page)
                .build()?,
        )
        .await?;

        for alert in alerts.iter_mut() {
            alert.fetch(connection).await?;
        }
        Ok(alerts)
    }

    /// Calculate a Summary of the Alerts and store in Metadata
    pub async fn calculate_alerts_summary(
        &mut self,
        connection: &Connection<'_>,
    ) -> Result<AlertsSummary, KonarrError> {
        let mut summary: HashMap<SecuritySeverity, u16> = HashMap::new();

        let mut alerts = Alerts::fetch_by_snapshot_id(connection, self.id).await?;
        log::debug!("Calculating Alert Summary for {} Alerts", alerts.len());

        for alert in alerts.iter_mut() {
            let advisory = alert.fetch_advisory_id(connection).await?;
            let severity = advisory.severity.clone();

            *summary.entry(severity).or_insert(0) += 1;
        }

        self.calculate_alerts(connection, &summary).await?;
        Ok(summary)
    }

    /// Calculate the Alert Totals
    pub async fn calculate_alerts(
        &mut self,
        connection: &Connection<'_>,
        summary: &HashMap<SecuritySeverity, u16>,
    ) -> Result<(), KonarrError> {
        debug!("Calculating Alert Totals for Snapshot({})", self.id);

        let mut total = 0;
        for (severity, count) in summary {
            self.set_metadata(
                connection,
                &format!("security.alerts.{}", severity.to_string().to_lowercase()),
                &count.to_string(),
            )
            .await?;
            total += count;
        }

        self.set_metadata(
            connection,
            SnapshotMetadataKey::SecurityAlertTotal,
            total.to_string().as_str(),
        )
        .await?;
        log::debug!("Alert Summary for Snapshot({}): {:?}", self.id, total);

        Ok(())
    }
}

/// Snapshot State
#[derive(Data, Debug, Clone, Default, PartialEq, Eq)]
pub enum SnapshotState {
    /// Snapshot Created (but not processed)
    #[default]
    Created,
    /// Snapshot Processing (in progress)
    Processing,
    /// Snapshot Completed (finished and ready for use)
    Completed,
    /// Snapshot is Stale (older than the latest snapshot for the project)
    Stale,
    /// Summary (this is for servers with no SBOM, just a summary of the children)
    Summary,
    /// Snapshot Failed (error during processing)
    Failed,
}