Skip to content

Commit

Permalink
feat(rust): added TLS inlet support
Browse files Browse the repository at this point in the history
  • Loading branch information
davide-baldo committed Sep 9, 2024
1 parent 63f2251 commit b1a3b78
Show file tree
Hide file tree
Showing 27 changed files with 686 additions and 20 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ pub const OCKAM_ROLE_ATTRIBUTE_KEY: &str = "ockam-role";
/// the corresponding key is [`OCKAM_ROLE_ATTRIBUTE_KEY`]
pub const OCKAM_ROLE_ATTRIBUTE_ENROLLER_VALUE: &str = "enroller";

/// Identity attribute key that indicates the privileges to access the project TLS certificate
pub const OCKAM_TLS_ATTRIBUTE_KEY: &str = "ockam-tls-certificate";

pub struct DirectAuthenticatorError(pub String);

pub type DirectAuthenticatorResult<T> = Either<T, DirectAuthenticatorError>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ impl KafkaInletController {
None,
false,
false,
None,
)
.await?;

Expand Down
12 changes: 10 additions & 2 deletions implementations/rust/ockam/ockam_api/src/nodes/models/portal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,12 @@ pub struct CreateInlet {
/// If not set, the node's identifier will be used.
#[n(10)] pub(crate) secure_channel_identifier: Option<Identifier>,
/// Enable UDP NAT puncture.
#[n(11)] pub enable_udp_puncture: bool,
#[n(11)] pub(crate) enable_udp_puncture: bool,
/// Disable fallback to TCP.
/// TCP won't be used to transfer data between the Inlet and the Outlet.
#[n(12)] pub disable_tcp_fallback: bool,
#[n(12)] pub(crate) disable_tcp_fallback: bool,
/// TLS certificate provider route.
#[n(13)] pub(crate) tls_certificate_provider: Option<MultiAddr>,
}

impl CreateInlet {
Expand Down Expand Up @@ -85,6 +87,7 @@ impl CreateInlet {
secure_channel_identifier: None,
enable_udp_puncture,
disable_tcp_fallback,
tls_certificate_provider: None,
}
}

Expand Down Expand Up @@ -113,9 +116,14 @@ impl CreateInlet {
secure_channel_identifier: None,
enable_udp_puncture,
disable_tcp_fallback,
tls_certificate_provider: None,
}
}

pub fn set_tls_certificate_provider(&mut self, provider: MultiAddr) {
self.tls_certificate_provider = Some(provider);
}

pub fn set_wait_ms(&mut self, ms: u64) {
self.wait_for_outlet_duration = Some(Duration::from_millis(ms))
}
Expand Down
1 change: 1 addition & 0 deletions implementations/rust/ockam/ockam_api/src/nodes/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub mod tcp_outlets;
mod transport;
pub mod workers;

mod certificate_provider;
mod http;
mod manager;
mod trust;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
use crate::nodes::NodeManager;
use minicbor::{Decode, Decoder, Encode};
use ockam_core::errcode::{Kind, Origin};
use ockam_core::{Any, NeutralMessage, Routed};
use ockam_multiaddr::MultiAddr;
use ockam_node::{Context, MessageSendReceiveOptions};
use ockam_transport_tcp::{TlsCertificate, TlsCertificateProvider};
use std::fmt::{Debug, Display, Formatter};
use std::sync::Weak;
use std::time::Duration;
use tonic::async_trait;

#[derive(Clone)]
pub(crate) struct ProjectCertificateProvider {
node_manager: Weak<NodeManager>,
to: MultiAddr,
}

impl Debug for ProjectCertificateProvider {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "ProjectCertificateProvider {{ to: {:?} }}", self.to)
}
}

impl ProjectCertificateProvider {
pub fn new(node_manager: Weak<NodeManager>, to: MultiAddr) -> Self {
Self { node_manager, to }
}
}

impl Display for ProjectCertificateProvider {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "certificate retrieval from: {}", self.to)
}
}

#[derive(Encode, Decode)]
struct CertificateRequest {}

#[derive(Debug, Encode, Decode)]
#[rustfmt::skip]
#[cbor(map)]
struct CertificateResponse {
#[n(1)] kind: ReplyKind,
#[n(2)] certificate: Option<TlsCertificate>,
}

#[derive(Debug, Encode, Decode, PartialEq)]
#[rustfmt::skip]
#[cbor(index_only)]
enum ReplyKind {
#[n(0)] Ready,
#[n(1)] NotReady,
#[n(2)] Unsupported,
}

#[async_trait]
impl TlsCertificateProvider for ProjectCertificateProvider {
async fn get_certificate(&self, context: &Context) -> ockam_core::Result<TlsCertificate> {
debug!("requesting TLS certificate from: {}", self.to);
let node_manager = self.node_manager.upgrade().ok_or_else(|| {
ockam_core::Error::new(Origin::Transport, Kind::Invalid, "NodeManager shut down")
})?;
let connection = {
node_manager
.make_connection(
context,
&self.to,
node_manager.node_identifier.clone(),
None,
None,
)
.await?
};

let options = MessageSendReceiveOptions::new().with_timeout(Duration::from_secs(30));

let payload = {
let mut buffer = Vec::new();
minicbor::Encoder::new(&mut buffer).encode(&CertificateRequest {})?;
buffer
};

let reply: Routed<Any> = context
.send_and_receive_extended(connection.route()?, NeutralMessage::from(payload), options)
.await?;

let payload = reply.into_payload();
let reply: CertificateResponse = Decoder::new(&payload).decode()?;

match reply.kind {
ReplyKind::Ready => {
if let Some(certificate) = reply.certificate {
Ok(certificate)
} else {
Err(ockam_core::Error::new(
Origin::Transport,
Kind::Invalid,
"invalid reply from certificate provider",
))
}
}
ReplyKind::Unsupported => Err(ockam_core::Error::new(
Origin::Transport,
Kind::NotReady,
"certificate",
)),
ReplyKind::NotReady => Err(ockam_core::Error::new(
Origin::Transport,
Kind::NotReady,
"certificate",
)),
}
}
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn check_orchestrator_encoding_not_ready() {
let payload = hex::decode("A10101").unwrap();
let reply: CertificateResponse = Decoder::new(&payload).decode().unwrap();
assert_eq!(reply.kind, ReplyKind::NotReady);
assert!(reply.certificate.is_none());
}

#[test]
fn check_orchestrator_encoding_ready() {
let payload =
hex::decode("a2010002a2014a66756c6c5f636861696e024b707269766174655f6b6579").unwrap();
let reply: CertificateResponse = Decoder::new(&payload).decode().unwrap();
assert_eq!(reply.kind, ReplyKind::Ready);
assert_eq!(
reply.certificate,
Some(TlsCertificate {
full_chain_pem: "full_chain".as_bytes().to_vec(),
private_key_pem: "private_key".as_bytes().to_vec()
})
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ impl InMemoryNode {
None,
false,
false,
None,
)
.await?;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ impl Inlets for BackgroundNodeClient {
secure_channel_identifier: &Option<Identifier>,
enable_udp_puncture: bool,
disable_tcp_fallback: bool,
tls_certificate_provider: &Option<MultiAddr>,
) -> miette::Result<Reply<InletStatus>> {
let request = {
let via_project = outlet_addr.matches(0, &[ProjectProto::CODE.into()]);
Expand Down Expand Up @@ -60,6 +61,9 @@ impl Inlets for BackgroundNodeClient {
if let Some(identifier) = secure_channel_identifier {
payload.set_secure_channel_identifier(identifier.clone())
}
if let Some(tls_provider) = tls_certificate_provider {
payload.set_tls_certificate_provider(tls_provider.clone())
}
payload.set_wait_ms(wait_for_outlet_timeout.as_millis() as u64);
Request::post("/node/inlet").body(payload)
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ impl InMemoryNode {
secure_channel_identifier: Option<Identifier>,
enable_udp_puncture: bool,
disable_tcp_fallback: bool,
tls_certificate_provider: Option<MultiAddr>,
) -> Result<InletStatus> {
self.node_manager
.create_inlet(
Expand All @@ -44,6 +45,7 @@ impl InMemoryNode {
secure_channel_identifier,
enable_udp_puncture,
disable_tcp_fallback,
tls_certificate_provider,
)
.await
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub trait Inlets {
secure_channel_identifier: &Option<Identifier>,
enable_udp_puncture: bool,
disable_tcp_fallback: bool,
tls_certificate_provider: &Option<MultiAddr>,
) -> miette::Result<Reply<InletStatus>>;

async fn show_inlet(&self, ctx: &Context, alias: &str) -> miette::Result<Reply<InletStatus>>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ impl NodeManager {
enable_udp_puncture: bool,
// TODO: Introduce mode enum
disable_tcp_fallback: bool,
tls_certificate_provider: Option<MultiAddr>,
) -> Result<InletStatus> {
info!("Handling request to create inlet portal");
debug! {
Expand Down Expand Up @@ -118,6 +119,7 @@ impl NodeManager {
policy_expression,
secure_channel_identifier,
disable_tcp_fallback,
tls_certificate_provider,
inlet: None,
connection: None,
main_route: None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ impl NodeManagerWorker {
secure_channel_identifier,
enable_udp_puncture,
disable_tcp_fallback,
tls_certificate_provider,
} = create_inlet;
match self
.node_manager
Expand All @@ -47,6 +48,7 @@ impl NodeManagerWorker {
secure_channel_identifier,
enable_udp_puncture,
disable_tcp_fallback,
tls_certificate_provider,
)
.await
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use crate::nodes::service::certificate_provider::ProjectCertificateProvider;
use ockam_transport_tcp::new_certificate_provider_cache;
use std::sync::{Arc, Weak};
use std::time::Duration;

Expand Down Expand Up @@ -39,6 +41,7 @@ pub(super) struct InletSessionReplacer {
pub(super) policy_expression: Option<PolicyExpression>,
pub(super) secure_channel_identifier: Option<Identifier>,
pub(super) disable_tcp_fallback: bool,
pub(super) tls_certificate_provider: Option<MultiAddr>,

// current status
pub(super) inlet: Option<Arc<TcpInlet>>,
Expand Down Expand Up @@ -111,6 +114,14 @@ impl InletSessionReplacer {
options
};

let options = if let Some(tls_provider) = &self.tls_certificate_provider {
options.with_tls_certificate_provider(new_certificate_provider_cache(Arc::new(
ProjectCertificateProvider::new(self.node_manager.clone(), tls_provider.clone()),
)))
} else {
options
};

Ok(options)
}

Expand Down
1 change: 1 addition & 0 deletions implementations/rust/ockam/ockam_api/tests/latency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ pub fn measure_buffer_latency_two_nodes_portal() {
None,
false,
false,
None,
)
.await?;

Expand Down
5 changes: 5 additions & 0 deletions implementations/rust/ockam/ockam_api/tests/portals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ async fn inlet_outlet_local_successful(context: &mut Context) -> ockam::Result<(
None,
false,
false,
None,
)
.await?;

Expand Down Expand Up @@ -132,6 +133,7 @@ fn portal_node_goes_down_reconnect() {
None,
false,
false,
None,
)
.await?;

Expand Down Expand Up @@ -286,6 +288,7 @@ fn portal_low_bandwidth_connection_keep_working_for_60s() {
None,
false,
false,
None,
)
.await?;

Expand Down Expand Up @@ -397,6 +400,7 @@ fn portal_heavy_load_exchanged() {
None,
false,
false,
None,
)
.await?;

Expand Down Expand Up @@ -547,6 +551,7 @@ fn test_portal_payload_transfer(outgoing_disruption: Disruption, incoming_disrup
None,
false,
false,
None,
)
.await?;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ impl AppState {
&None,
false,
false,
&None,
)
.await
.map_err(|err| {
Expand Down
Loading

0 comments on commit b1a3b78

Please sign in to comment.