ockam_entity/worker/
trust_policy_worker.rs1use crate::{SecureChannelTrustInfo, TrustPolicy};
2use ockam_core::compat::boxed::Box;
3use ockam_core::{
4 async_trait::async_trait, Address, AsyncTryClone, Message, Result, Routed, Worker,
5};
6use ockam_node::{Context, Handle};
7use serde::{Deserialize, Serialize};
8#[derive(AsyncTryClone)]
9pub struct TrustPolicyImpl {
10 handle: Handle,
11}
12
13impl TrustPolicyImpl {
14 pub fn new(handle: Handle) -> Self {
15 TrustPolicyImpl { handle }
16 }
17}
18
19impl TrustPolicyImpl {
20 pub async fn create_using_worker(ctx: &Context, address: &Address) -> Result<Self> {
21 let handle = Handle::new(ctx.new_context(Address::random(0)).await?, address.clone());
22
23 Ok(Self::new(handle))
24 }
25
26 pub async fn create_using_impl(ctx: &Context, trust_policy: impl TrustPolicy) -> Result<Self> {
27 let address = Self::create_worker(ctx, trust_policy).await?;
28 Self::create_using_worker(ctx, &address).await
29 }
30
31 pub async fn create_worker(ctx: &Context, trust_policy: impl TrustPolicy) -> Result<Address> {
32 let address = Address::random(0);
33
34 ctx.start_worker(address.clone(), TrustPolicyWorker::new(trust_policy))
35 .await?;
36
37 Ok(address)
38 }
39}
40
41#[async_trait]
42impl TrustPolicy for TrustPolicyImpl {
43 async fn check(&mut self, trust_info: &SecureChannelTrustInfo) -> Result<bool> {
44 let response: TrustPolicyResponse = self
45 .handle
46 .call(TrustPolicyRequest {
47 info: trust_info.clone(),
48 })
49 .await?;
50
51 Ok(response.res)
52 }
53}
54
55pub struct TrustPolicyWorker<T: TrustPolicy> {
56 trust_policy: T,
57}
58
59impl<T: TrustPolicy> TrustPolicyWorker<T> {
60 pub fn new(trust_policy: T) -> Self {
61 TrustPolicyWorker { trust_policy }
62 }
63}
64
65#[derive(Serialize, Deserialize, Message)]
66pub struct TrustPolicyRequest {
67 pub info: SecureChannelTrustInfo,
68}
69
70#[derive(Serialize, Deserialize, Message)]
71pub struct TrustPolicyResponse {
72 pub res: bool,
73}
74
75#[async_trait]
76impl<T: TrustPolicy> Worker for TrustPolicyWorker<T> {
77 type Message = TrustPolicyRequest;
78 type Context = Context;
79
80 async fn handle_message(
81 &mut self,
82 ctx: &mut Self::Context,
83 msg: Routed<Self::Message>,
84 ) -> Result<()> {
85 let route = msg.return_route();
86 let msg = msg.body();
87
88 let res = self.trust_policy.check(&msg.info).await?;
89 ctx.send(route, TrustPolicyResponse { res }).await?;
90
91 Ok(())
92 }
93}