Skip to content

Commit

Permalink
segregate types in the order and response modules
Browse files Browse the repository at this point in the history
most types used in Order are in order.rs
most types used in CommandResponse are in response.rs
types relevant to TLS certificates are in certificate.rs
  • Loading branch information
Keksoj committed Mar 10, 2023
1 parent 9dc490f commit 4bd9c6f
Show file tree
Hide file tree
Showing 37 changed files with 1,514 additions and 1,528 deletions.
18 changes: 11 additions & 7 deletions bin/src/acme.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
use std::{fs::File, io::Write, iter, net::SocketAddr, thread, time};

use acme_lib::{create_p384_key, persist::FilePersist, Directory, DirectoryUrl};
use anyhow::{bail, Context};
use mio::net::UnixStream;
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use tiny_http::{Response, Server};

use sozu_command_lib::{
certificate::{calculate_fingerprint, split_certificate_chain},
certificate::{
calculate_fingerprint, split_certificate_chain, CertificateAndKey, CertificateFingerprint,
TlsVersion,
},
channel::Channel,
config::Config,
order::{CommandResponse, CommandStatus, Order},
worker::{
AddCertificate, Backend, CertificateAndKey, CertificateFingerprint, HttpFrontend, PathRule,
RemoveBackend, ReplaceCertificate, Route, RulePosition, TlsVersion,
order::{AddCertificate, Order, RemoveBackend, ReplaceCertificate},
response::{
Backend, CommandResponse, CommandStatus, HttpFrontend, PathRule, Route, RulePosition,
},
};
use std::{fs::File, io::Write, iter, net::SocketAddr, thread, time};
use tiny_http::{Response, Server};

use crate::util;

Expand Down
11 changes: 6 additions & 5 deletions bin/src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use std::{collections::BTreeMap, net::SocketAddr};

use clap::{Parser, Subcommand};
use sozu_command_lib::worker::{LoadBalancingAlgorithms, TlsVersion};

use sozu_command_lib::{certificate::TlsVersion, order::LoadBalancingAlgorithms};

#[derive(Parser, PartialEq, Eq, Clone, Debug)]
#[clap(author, version, about)]
Expand Down Expand Up @@ -433,11 +434,11 @@ pub enum Route {
}

#[allow(clippy::from_over_into)]
impl std::convert::Into<sozu_command_lib::worker::Route> for Route {
fn into(self) -> sozu_command_lib::worker::Route {
impl std::convert::Into<sozu_command_lib::response::Route> for Route {
fn into(self) -> sozu_command_lib::response::Route {
match self {
Route::Deny => sozu_command_lib::worker::Route::Deny,
Route::Id { id } => sozu_command_lib::worker::Route::ClusterId(id),
Route::Deny => sozu_command_lib::response::Route::Deny,
Route::Id { id } => sozu_command_lib::response::Route::ClusterId(id),
}
}
}
Expand Down
9 changes: 5 additions & 4 deletions bin/src/command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@ use serde::{Deserialize, Serialize};

use sozu_command_lib::{
config::Config,
order::{CommandResponse, CommandResponseContent, CommandStatus, Event, Order, RunState},
order::{InnerOrder, MetricsConfiguration, Order},
response::{
CommandResponse, CommandResponseContent, CommandStatus, Event, ProxyResponse,
ProxyResponseContent, ProxyResponseStatus, RunState,
},
scm_socket::{Listeners, ScmSocket},
state::ConfigState,
worker::{
InnerOrder, MetricsConfiguration, ProxyResponse, ProxyResponseContent, ProxyResponseStatus,
},
};

use crate::{
Expand Down
14 changes: 6 additions & 8 deletions bin/src/command/orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,15 @@ use sozu_command_lib::{
buffer::fixed::Buffer,
config::Config,
logging,
order::{
CommandResponse, CommandResponseContent, CommandStatus, FrontendFilters, ListedFrontends,
ListenersList, Order, RunState, WorkerInfo,
},
order::{FrontendFilters, InnerOrder, MetricsConfiguration, Order, QueryClusterType},
parser::parse_several_commands,
response::{
AggregatedMetricsData, CommandResponse, CommandResponseContent, CommandStatus,
ListedFrontends, ListenersList, ProxyResponseContent, ProxyResponseStatus, QueryAnswer,
RunState, WorkerInfo,
},
scm_socket::Listeners,
state::get_cluster_ids_by_domain,
worker::{
AggregatedMetricsData, InnerOrder, MetricsConfiguration, ProxyResponseContent,
ProxyResponseStatus, QueryAnswer, QueryClusterType,
},
};

use sozu::metrics::METRICS;
Expand Down
4 changes: 2 additions & 2 deletions bin/src/command/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ use nix::{sys::signal::kill, unistd::Pid};
use sozu_command_lib::{
channel::Channel,
config::Config,
order::{Order, RunState, WorkerInfo},
order::{InnerOrder, Order},
response::{ProxyResponse, RunState, WorkerInfo},
scm_socket::ScmSocket,
worker::{InnerOrder, ProxyResponse},
};

/// An instance of Sōzu, as seen from the main process
Expand Down
6 changes: 4 additions & 2 deletions bin/src/ctl/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ use rand::{distributions::Alphanumeric, thread_rng, Rng};
use serde::Serialize;

use sozu_command_lib::{
order::{CommandResponse, CommandResponseContent, CommandStatus, Order, RunState, WorkerInfo},
worker::{QueryCertificateType, QueryClusterDomain, QueryClusterType, QueryMetricsOptions},
order::{
Order, QueryCertificateType, QueryClusterDomain, QueryClusterType, QueryMetricsOptions,
},
response::{CommandResponse, CommandResponseContent, CommandStatus, RunState, WorkerInfo},
};

use crate::ctl::{
Expand Down
10 changes: 4 additions & 6 deletions bin/src/ctl/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@ use std::{
use anyhow::{self, bail, Context};
use prettytable::{Row, Table};

use sozu_command_lib::{
order::{CommandResponseContent, ListedFrontends, ListenersList, WorkerInfo},
worker::{
AggregatedMetricsData, ClusterMetricsData, FilteredData, QueryAnswer,
QueryAnswerCertificate, QueryAnswerMetrics, Route, WorkerMetrics,
},
use sozu_command_lib::response::{
AggregatedMetricsData, ClusterMetricsData, CommandResponseContent, FilteredData,
ListedFrontends, ListenersList, QueryAnswer, QueryAnswerCertificate, QueryAnswerMetrics, Route,
WorkerInfo, WorkerMetrics,
};

pub fn print_listeners(listeners_list: ListenersList) {
Expand Down
6 changes: 1 addition & 5 deletions bin/src/ctl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,7 @@ use std::time::Duration;

use anyhow::Context;

use sozu_command_lib::{
channel::Channel,
config::Config,
order::{CommandResponse, Order},
};
use sozu_command_lib::{channel::Channel, config::Config, order::Order, response::CommandResponse};

use crate::{
cli::{self, *},
Expand Down
17 changes: 10 additions & 7 deletions bin/src/ctl/request_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@ use std::net::SocketAddr;
use anyhow::{bail, Context};

use sozu_command_lib::{
certificate::{calculate_fingerprint, split_certificate_chain},
certificate::{
calculate_fingerprint, split_certificate_chain, CertificateAndKey, CertificateFingerprint,
TlsVersion,
},
config::{Config, FileListenerProtocolConfig, Listener, ProxyProtocolConfig},
order::{FrontendFilters, Order},
worker::{
ActivateListener, AddCertificate, Backend, CertificateAndKey, CertificateFingerprint,
Cluster, DeactivateListener, HttpFrontend, ListenerType, LoadBalancingParams,
MetricsConfiguration, PathRule, RemoveBackend, RemoveCertificate, RemoveListener,
ReplaceCertificate, RulePosition, TcpFrontend, TcpListenerConfig, TlsVersion,
order::{
ActivateListener, AddCertificate, Cluster, DeactivateListener, ListenerType,
LoadBalancingParams, MetricsConfiguration, RemoveBackend, RemoveCertificate,
RemoveListener, ReplaceCertificate,
},
order::{FrontendFilters, Order},
response::{Backend, HttpFrontend, PathRule, RulePosition, TcpFrontend, TcpListenerConfig},
};

use crate::{
Expand Down
2 changes: 1 addition & 1 deletion bin/src/upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use serde::{Deserialize, Serialize};
use tempfile::tempfile;

use sozu_command_lib::{
channel::Channel, config::Config, order::RunState, state::ConfigState, worker::InnerOrder,
channel::Channel, config::Config, order::InnerOrder, response::RunState, state::ConfigState,
};

use crate::{
Expand Down
4 changes: 2 additions & 2 deletions bin/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ use sozu_command_lib::{
channel::Channel,
config::Config,
logging::target_to_backend,
order::Order,
order::{InnerOrder, Order},
ready::Ready,
response::ProxyResponse,
scm_socket::{Listeners, ScmSocket},
state::ConfigState,
worker::{InnerOrder, ProxyResponse},
};

use crate::{command::Worker, logging, util};
Expand Down
116 changes: 116 additions & 0 deletions command/src/certificate.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,123 @@
use std::{error, fmt, str::FromStr};

use anyhow::{self, Context};
use hex::FromHex;
use pem::parse;
use serde::de::{self, Visitor};
use sha2::{Digest, Sha256};

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CertificateAndKey {
pub certificate: String,
pub certificate_chain: Vec<String>,
pub key: String,
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub versions: Vec<TlsVersion>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TlsVersion {
SSLv2,
SSLv3,
#[serde(rename = "TLSv1")]
TLSv1_0,
#[serde(rename = "TLSv1.1")]
TLSv1_1,
#[serde(rename = "TLSv1.2")]
TLSv1_2,
#[serde(rename = "TLSv1.3")]
TLSv1_3,
}

#[derive(Debug)]
pub struct ParseErrorTlsVersion;

impl fmt::Display for ParseErrorTlsVersion {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Cannot find the TLS version")
}
}

impl error::Error for ParseErrorTlsVersion {
fn description(&self) -> &str {
"Cannot find the TLS version"
}

fn cause(&self) -> Option<&dyn error::Error> {
None
}
}

impl FromStr for TlsVersion {
type Err = ParseErrorTlsVersion;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"SSLv2" => Ok(TlsVersion::SSLv2),
"SSLv3" => Ok(TlsVersion::SSLv3),
"TLSv1" => Ok(TlsVersion::TLSv1_0),
"TLSv1.1" => Ok(TlsVersion::TLSv1_1),
"TLSv1.2" => Ok(TlsVersion::TLSv1_2),
"TLSv1.3" => Ok(TlsVersion::TLSv1_3),
_ => Err(ParseErrorTlsVersion {}),
}
}
}

//FIXME: make fixed size depending on hash algorithm
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CertificateFingerprint(pub Vec<u8>);

impl fmt::Debug for CertificateFingerprint {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "CertificateFingerprint({})", hex::encode(&self.0))
}
}

impl fmt::Display for CertificateFingerprint {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", hex::encode(&self.0))
}
}

impl serde::Serialize for CertificateFingerprint {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&hex::encode(&self.0))
}
}

struct CertificateFingerprintVisitor;

impl<'de> Visitor<'de> for CertificateFingerprintVisitor {
type Value = CertificateFingerprint;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("the certificate fingerprint must be in hexadecimal format")
}

fn visit_str<E>(self, value: &str) -> Result<CertificateFingerprint, E>
where
E: de::Error,
{
FromHex::from_hex(value)
.map_err(|e| E::custom(format!("could not deserialize hex: {e:?}")))
.map(CertificateFingerprint)
}
}

impl<'de> serde::Deserialize<'de> for CertificateFingerprint {
fn deserialize<D>(deserializer: D) -> Result<CertificateFingerprint, D::Error>
where
D: serde::de::Deserializer<'de>,
{
deserializer.deserialize_str(CertificateFingerprintVisitor {})
}
}

pub fn calculate_fingerprint(certificate: &[u8]) -> anyhow::Result<Vec<u8>> {
let parsed_certificate = parse(certificate).with_context(|| "Can not parse certificate")?;
let fingerprint = Sha256::digest(parsed_certificate.contents)
Expand Down
16 changes: 9 additions & 7 deletions command/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ use anyhow::{bail, Context};
use toml;

use crate::{
certificate::split_certificate_chain,
order::Order,
worker::{
ActivateListener, AddCertificate, Backend, CertificateAndKey, Cluster, HttpFrontend,
HttpListenerConfig, HttpsListenerConfig, InnerOrder, ListenerType, LoadBalancingAlgorithms,
LoadBalancingParams, LoadMetric, PathRule, Route, RulePosition, TcpFrontend,
TcpListenerConfig, TlsVersion,
certificate::TlsVersion,
order::{ActivateListener, Cluster, InnerOrder, ListenerType, LoadBalancingParams},
response::{Backend, HttpListenerConfig, TcpFrontend},
};
use crate::{
certificate::{split_certificate_chain, CertificateAndKey},
order::{AddCertificate, LoadBalancingAlgorithms, LoadMetric, Order},
response::{
HttpFrontend, HttpsListenerConfig, PathRule, Route, RulePosition, TcpListenerConfig,
},
};

Expand Down
1 change: 1 addition & 0 deletions command/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub mod config;
pub mod order;
pub mod parser;
pub mod ready;
pub mod response;
pub mod scm_socket;
pub mod state;
pub mod worker;
Expand Down

0 comments on commit 4bd9c6f

Please sign in to comment.