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
//! Audit events, and associated fields and types
//!
//! Includes possible events to log and statuses of those events

use crate::{crypto::KeyId, types::operations::ClientAction};

use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Display, Formatter};
use strum::{Display, EnumString};
use time::OffsetDateTime;
use uuid::Uuid;

use super::database::account::AccountId;

/// Options for the outcome of a given action in a [`AuditEvent`]

#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Display, EnumString)]
pub enum EventStatus {
    Started,
    Successful,
    Failed,
}

/// A single entry that specifies the actor, action, outcome, and
/// any related key for a logged audit event.
/// We expect database implementors to create [AuditEvent] instances for us. So
/// we make all fields public.
#[derive(Debug, Serialize, Deserialize)]
pub struct AuditEvent {
    pub audit_event_id: i64,
    pub account_id: AccountId,
    pub request_id: Uuid,
    pub key_id: Option<KeyId>,
    /// We use [OffsetDateTime] as this is compatible with SQLx. Easily
    /// convertible to a postgres' TIMESTAMPTZ type.
    pub timestamp: OffsetDateTime,
    pub client_action: ClientAction,
    pub status: EventStatus,
}

impl AuditEvent {
    pub fn request_id(&self) -> &Uuid {
        &self.request_id
    }

    pub fn action(&self) -> ClientAction {
        self.client_action
    }

    pub fn key_id(&self) -> Option<&KeyId> {
        self.key_id.as_ref()
    }

    pub fn date(&self) -> OffsetDateTime {
        self.timestamp
    }

    pub fn status(&self) -> EventStatus {
        self.status
    }
}

impl Display for AuditEvent {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Request ID: {}", self.request_id())?;
        if let Some(key_id) = self.key_id() {
            writeln!(f, "{key_id:?}")?;
        }
        writeln!(f, "{}", self.date())?;
        writeln!(f, "{}", self.action())?;
        writeln!(f, "{}", self.status())
    }
}

/// Options for which types of events to retrieve from the key server
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, EnumString, Display)]
#[strum(serialize_all = "kebab-case")]
pub enum EventType {
    All,
    SystemOnly,
    KeyOnly,
}

const ALL_ACTIONS: &[ClientAction] = &[
    ClientAction::Authenticate,
    ClientAction::CreateStorageKey,
    ClientAction::DeleteKey,
    ClientAction::ExportSecret,
    ClientAction::ExportSigningKey,
    ClientAction::GenerateSecret,
    ClientAction::GetUserId,
    ClientAction::ImportSigningKey,
    ClientAction::Logout,
    ClientAction::Register,
    ClientAction::RemoteGenerateSigningKey,
    ClientAction::RemoteSignBytes,
    ClientAction::RetrieveServerEncryptedBlob,
    ClientAction::RetrieveSecret,
    ClientAction::RetrieveAuditEvents,
    ClientAction::RetrieveSigningKey,
    ClientAction::RetrieveStorageKey,
    ClientAction::StoreServerEncryptedBlob,
    ClientAction::CheckSession,
];

const SYSTEM_ONLY_ACTIONS: &[ClientAction] = &[
    ClientAction::Authenticate,
    ClientAction::CreateStorageKey,
    ClientAction::GetUserId,
    ClientAction::Logout,
    ClientAction::Register,
    ClientAction::RetrieveAuditEvents,
    ClientAction::RetrieveStorageKey,
];

const KEY_ONLY_ACTIONS: &[ClientAction] = &[
    ClientAction::DeleteKey,
    ClientAction::ExportSecret,
    ClientAction::ExportSigningKey,
    ClientAction::GenerateSecret,
    ClientAction::ImportSigningKey,
    ClientAction::RemoteGenerateSigningKey,
    ClientAction::RemoteSignBytes,
    ClientAction::RetrieveServerEncryptedBlob,
    ClientAction::RetrieveSecret,
    ClientAction::RetrieveSigningKey,
    ClientAction::StoreServerEncryptedBlob,
];

impl EventType {
    pub fn client_actions(&self) -> &[ClientAction] {
        match self {
            Self::All => ALL_ACTIONS,
            Self::SystemOnly => SYSTEM_ONLY_ACTIONS,
            Self::KeyOnly => KEY_ONLY_ACTIONS,
        }
    }
}

/// Optional parameters to filter [`AuditEvent`]s by
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct AuditEventOptions {
    pub key_ids: Vec<KeyId>,
    #[serde(with = "time::serde::iso8601::option")]
    pub after_date: Option<OffsetDateTime>,
    #[serde(with = "time::serde::iso8601::option")]
    pub before_date: Option<OffsetDateTime>,
    pub request_id: Option<Uuid>,
}

#[cfg(test)]
mod tests {
    use strum::IntoEnumIterator;

    use super::*;

    /// The ALL_ACTIONS constant exists so that we can use it as a constant
    /// without something like `lazy_static!`. This test ensures that any
    /// actions added to `ClientAction` are covered by this constant.
    #[test]
    fn all_actions_constant_includes_all_actions() {
        for action in ClientAction::iter() {
            assert!(ALL_ACTIONS.contains(&action))
        }
    }
}