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
use std::path::PathBuf;
use std::str::FromStr;

use url::Url;

use crate::config::{
  Binding,
  ConfigOrDefinition,
  ConfigurationTreeNode,
  ResourceDefinition,
  TcpPort,
  UdpPort,
  UrlResource,
  Volume,
};
use crate::WickConfiguration;

/// An audit report for a component or application.
#[derive(Debug, Clone, serde::Serialize)]
#[non_exhaustive]
pub struct Audit {
  /// The name of the audited element.
  pub name: String,
  /// The resources used by the audited element.
  #[serde(skip_serializing_if = "Vec::is_empty")]
  pub resources: Vec<AuditedResourceBinding>,
  /// The components the audited element imports.
  #[serde(skip_serializing_if = "Vec::is_empty")]
  pub imports: Vec<Audit>,
}

impl Audit {
  /// Audit a configuration tree.
  pub fn new(tree: &ConfigurationTreeNode<WickConfiguration>) -> Self {
    Self {
      name: tree.name.clone(),
      resources: tree
        .element
        .resources()
        .iter()
        .map(AuditedResourceBinding::from)
        .collect::<Vec<_>>(),
      imports: tree.children.iter().map(Self::config_or_def).collect::<Vec<_>>(),
    }
  }

  /// Audit a flattened list of configuration elements.
  pub fn new_flattened(elements: &[ConfigOrDefinition<WickConfiguration>]) -> Vec<Audit> {
    elements.iter().map(Self::config_or_def).collect::<Vec<_>>()
  }

  pub(crate) fn config_or_def(el: &ConfigOrDefinition<WickConfiguration>) -> Self {
    match el {
      crate::config::ConfigOrDefinition::Config(c) => Audit::new(c),
      crate::config::ConfigOrDefinition::Definition { id, .. } => Audit {
        name: id.clone(),
        resources: Vec::new(),
        imports: Vec::new(),
      },
    }
  }
}

impl From<&ResourceDefinition> for AuditedResource {
  fn from(value: &ResourceDefinition) -> Self {
    match value {
      ResourceDefinition::TcpPort(v) => Self::TcpPort(AuditedPort {
        port: *v.port.value_unchecked(),
        address: v.host.value_unchecked().clone(),
      }),
      ResourceDefinition::UdpPort(v) => Self::UdpPort(AuditedPort {
        port: *v.port.value_unchecked(),
        address: v.host.value_unchecked().clone(),
      }),
      ResourceDefinition::Url(v) => Self::Url(AuditedUrl::from(v.url.value_unchecked().clone())),
      ResourceDefinition::Volume(v) => Self::Volume(AuditedVolume {
        path: v.path().unwrap(),
      }),
    }
  }
}

/// A rendeder resource binding.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
pub struct AuditedResourceBinding {
  pub(crate) name: String,
  pub(crate) resource: AuditedResource,
}

impl From<AuditedResourceBinding> for ResourceDefinition {
  fn from(value: AuditedResourceBinding) -> Self {
    match value.resource {
      AuditedResource::TcpPort(v) => Self::TcpPort(TcpPort::new(v.address, v.port)),
      AuditedResource::UdpPort(v) => Self::UdpPort(UdpPort::new(v.address, v.port)),
      AuditedResource::Url(v) => Self::Url(UrlResource::new(v.url)),
      AuditedResource::Volume(v) => Self::Volume(Volume::new(v.path.to_string_lossy().to_string())),
    }
  }
}

impl std::fmt::Display for AuditedResourceBinding {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "{}: {}", self.name, self.resource)
  }
}

impl From<&Binding<ResourceDefinition>> for AuditedResourceBinding {
  fn from(value: &Binding<ResourceDefinition>) -> Self {
    Self {
      name: value.id.clone(),
      resource: AuditedResource::from(&value.kind),
    }
  }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
#[serde(tag = "kind")]

/// The possible types of resources. Resources are system-level resources and sensitive configuration.
pub enum AuditedResource {
  /// A variant representing a [crate::config::TcpPort] type.
  #[serde(rename = "wick/resource/tcpport@v1")]
  TcpPort(AuditedPort),
  /// A variant representing a [crate::config::UdpPort] type.
  #[serde(rename = "wick/resource/udpport@v1")]
  UdpPort(AuditedPort),
  /// A variant representing a [crate::config::UrlResource] type.
  #[serde(rename = "wick/resource/url@v1")]
  Url(AuditedUrl),
  /// A variant representing a [crate::config::Volume] type.
  #[serde(rename = "wick/resource/volume@v1")]
  Volume(AuditedVolume),
}

impl std::fmt::Display for AuditedResource {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      AuditedResource::TcpPort(v) => v.fmt(f),
      AuditedResource::UdpPort(v) => v.fmt(f),
      AuditedResource::Url(v) => v.fmt(f),
      AuditedResource::Volume(v) => v.fmt(f),
    }
  }
}

/// A summary of a UDP port resource.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
pub struct AuditedPort {
  pub(crate) port: u16,
  pub(crate) address: String,
}

impl std::fmt::Display for AuditedPort {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "{}:{}", self.address, self.port)
  }
}

/// A summary of a volume resource.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
pub struct AuditedVolume {
  pub(crate) path: PathBuf,
}

impl std::fmt::Display for AuditedVolume {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.write_str(&self.path.to_string_lossy())
  }
}

/// A summary of a URL resource.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
pub struct AuditedUrl {
  pub(crate) url: Url,
}

impl From<Url> for AuditedUrl {
  fn from(mut url: Url) -> Self {
    let _ = url.set_username("");
    let _ = url.set_password(None);
    Self { url }
  }
}

impl FromStr for AuditedUrl {
  type Err = url::ParseError;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    let mut url = Url::parse(s)?;
    let _ = url.set_username("");
    let _ = url.set_password(None);

    Ok(Self { url })
  }
}

impl std::fmt::Display for AuditedUrl {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.write_str(self.url.as_str())
  }
}