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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
use super::output_request::*;
use super::processor::*;
use super::request::*;
use crate::non::NONObjectInfo;
use crate::{base::*, SharedObjectStackDecID};
use cyfs_base::*;

use http_types::{Method, Request, Response, Url};
use std::sync::Arc;

#[derive(Clone)]
pub struct CryptoRequestor {
    dec_id: Option<SharedObjectStackDecID>,
    requestor: HttpRequestorRef,
    service_url: Url,
}

impl CryptoRequestor {
    pub fn new_default_tcp(dec_id: Option<SharedObjectStackDecID>) -> Self {
        let service_addr = format!("127.0.0.1:{}", cyfs_base::NON_STACK_HTTP_PORT);
        Self::new_tcp(dec_id, &service_addr)
    }

    pub fn new_tcp(dec_id: Option<SharedObjectStackDecID>, service_addr: &str) -> Self {
        let tcp_requestor = TcpHttpRequestor::new(service_addr);
        Self::new(dec_id, Arc::new(Box::new(tcp_requestor)))
    }

    pub fn new(dec_id: Option<SharedObjectStackDecID>, requestor: HttpRequestorRef) -> Self {
        let addr = requestor.remote_addr();

        let url = format!("http://{}/crypto/", addr);
        let url = Url::parse(&url).unwrap();

        Self {
            dec_id,
            requestor,
            service_url: url,
        }
    }

    pub fn into_processor(self) -> CryptoOutputProcessorRef {
        Arc::new(Box::new(self))
    }

    pub fn clone_processor(&self) -> CryptoOutputProcessorRef {
        self.clone().into_processor()
    }

    fn encode_common_headers(&self, com_req: &CryptoOutputRequestCommon, http_req: &mut Request) {
        if let Some(dec_id) = &com_req.dec_id {
            http_req.insert_header(cyfs_base::CYFS_DEC_ID, dec_id.to_string());
        } else if let Some(dec_id) = &self.dec_id {
            if let Some(dec_id) = dec_id.get() {
                http_req.insert_header(cyfs_base::CYFS_DEC_ID, dec_id.to_string());
            }
        }

        RequestorHelper::encode_opt_header_with_encoding(
            http_req,
            cyfs_base::CYFS_REQ_PATH,
            com_req.req_path.as_deref(),
        );

        if let Some(target) = &com_req.target {
            http_req.insert_header(cyfs_base::CYFS_TARGET, target.to_string());
        }

        http_req.insert_header(cyfs_base::CYFS_FLAGS, com_req.flags.to_string());
    }

    fn encode_verify_object_request(&self, req: &CryptoVerifyObjectOutputRequest) -> Request {
        let url = self.service_url.join("verify").unwrap();

        let mut http_req = Request::new(Method::Post, url);
        self.encode_common_headers(&req.common, &mut http_req);

        http_req.insert_header(cyfs_base::CYFS_OBJECT_ID, req.object.object_id.to_string());
        http_req.insert_header(cyfs_base::CYFS_SIGN_TYPE, req.sign_type.to_string());

        let verify_type = req.sign_object.as_str();
        match &req.sign_object {
            VerifyObjectType::Owner | VerifyObjectType::Own => {}
            VerifyObjectType::Object(sign_object) => {
                http_req.insert_header(
                    cyfs_base::CYFS_SIGN_OBJ_ID,
                    sign_object.object_id.to_string(),
                );
                if let Some(obj) = &sign_object.object_raw {
                    http_req.insert_header(cyfs_base::CYFS_SIGN_OBJ, hex::encode(obj));
                }
            }
            VerifyObjectType::Sign(signs) => {
                http_req.insert_header(cyfs_base::CYFS_VERIFY_SIGNS, signs.encode_string());
            }
        }

        http_req.insert_header(cyfs_base::CYFS_VERIFY_TYPE, verify_type);

        http_req
    }

    async fn decode_verify_object_response(
        object_id: &ObjectId,
        mut resp: Response,
    ) -> BuckyResult<CryptoVerifyObjectOutputResponse> {
        let body = resp.body_string().await.map_err(|e| {
            let msg = format!(
                "read verify object response from crypto failed, read body string error! obj={}, {}",
                object_id, e
            );
            error!("{}", msg);

            BuckyError::new(BuckyErrorCode::IoError, msg)
        })?;

        info!("verify resp body: {}", body);

        let resp = CryptoVerifyObjectResponse::decode_string(&body)?;

        info!("verify object response: obj={}, resp={:?}", object_id, resp);

        Ok(resp)
    }

    // 校验一个对象是否有指定object的签名
    pub async fn verify_object(
        &self,
        req: CryptoVerifyObjectRequest,
    ) -> BuckyResult<CryptoVerifyObjectResponse> {
        let mut http_req = self.encode_verify_object_request(&req);
        http_req.set_body(req.object.object_raw);

        let mut resp = self.requestor.request(http_req).await?;

        if resp.status().is_success() {
            let resp = Self::decode_verify_object_response(&req.object.object_id, resp).await?;
            Ok(resp)
        } else {
            let e = RequestorHelper::error_from_resp(&mut resp).await;
            Err(e)
        }
    }

    fn encode_sign_object_request(&self, req: &CryptoSignObjectRequest) -> Request {
        let url = self.service_url.join("sign").unwrap();

        let mut http_req = Request::new(Method::Post, url);
        self.encode_common_headers(&req.common, &mut http_req);
        http_req.insert_header(cyfs_base::CYFS_OBJECT_ID, req.object.object_id.to_string());
        http_req.insert_header(cyfs_base::CYFS_CRYPTO_FLAGS, req.flags.to_string());

        http_req
    }

    async fn decode_sign_object_response(
        object_id: &ObjectId,
        mut resp: Response,
    ) -> BuckyResult<CryptoSignObjectOutputResponse> {
        let sign_result: SignObjectResult =
            RequestorHelper::decode_header(&resp, cyfs_base::CYFS_SIGN_RET)?;

        info!(
            "sign object from crypto success: obj={}, ret={}",
            object_id,
            sign_result.to_string()
        );

        let ret = match sign_result {
            SignObjectResult::Signed => {
                let buf = resp.body_bytes().await.map_err(|e| {
                    let msg = format!(
                        "get object from sign object resp failed, read body bytes error! obj={} {}",
                        object_id, e
                    );
                    error!("{}", msg);

                    BuckyError::from(msg)
                })?;

                let object = NONObjectInfo::new_from_object_raw(buf)?;

                CryptoSignObjectResponse {
                    result: sign_result,
                    object: Some(object),
                }
            }
            SignObjectResult::Pending => CryptoSignObjectResponse {
                result: sign_result,
                object: None,
            },
        };

        Ok(ret)
    }

    pub async fn sign_object(
        &self,
        req: CryptoSignObjectRequest,
    ) -> BuckyResult<CryptoSignObjectResponse> {
        let mut http_req = self.encode_sign_object_request(&req);
        http_req.set_body(req.object.object_raw);

        let mut resp = self.requestor.request(http_req).await?;

        if resp.status().is_success() {
            let resp = Self::decode_sign_object_response(&req.object.object_id, resp).await?;
            Ok(resp)
        } else {
            let e = RequestorHelper::error_from_resp(&mut resp).await;
            Err(e)
        }
    }

    // encrypt
    fn encode_encrypt_data_request(&self, req: &CryptoEncryptDataOutputRequest) -> Request {
        let url = self.service_url.join("encrypt").unwrap();

        let mut http_req = Request::new(Method::Post, url);
        self.encode_common_headers(&req.common, &mut http_req);
        http_req.insert_header(cyfs_base::CYFS_ENCRYPT_TYPE, req.encrypt_type.to_string());
        http_req.insert_header(cyfs_base::CYFS_CRYPTO_FLAGS, req.flags.to_string());

        http_req
    }

    async fn decode_encrypt_data_response(
        mut resp: Response,
    ) -> BuckyResult<CryptoEncryptDataOutputResponse> {
        let aes_key: Option<AesKey> =
            RequestorHelper::decode_optional_header(&resp, cyfs_base::CYFS_AES_KEY)?;

        let result = resp.body_bytes().await.map_err(|e| {
            let msg = format!(
                "get encrypt data from resp failed, read body bytes error! {}",
                e
            );
            error!("{}", msg);

            BuckyError::from(msg)
        })?;

        let resp = CryptoEncryptDataOutputResponse { aes_key, result };

        Ok(resp)
    }

    pub async fn encrypt_data(
        &self,
        req: CryptoEncryptDataOutputRequest,
    ) -> BuckyResult<CryptoEncryptDataOutputResponse> {
        let mut http_req = self.encode_encrypt_data_request(&req);
        let data_len = match &req.data {
            Some(data) => data.len(),
            None => 0,
        };

        if let Some(data) = req.data {
            http_req.set_body(data);
        }

        let mut resp = self.requestor.request(http_req).await?;

        if resp.status().is_success() {
            let resp = Self::decode_encrypt_data_response(resp).await?;

            info!(
                "encrypt data success: data={}, type={}, ret={}",
                data_len,
                req.encrypt_type.to_string(),
                resp.result.len(),
            );

            Ok(resp)
        } else {
            let e = RequestorHelper::error_from_resp(&mut resp).await;
            error!(
                "encrypt data failed: data={}, type={}, {}",
                data_len,
                req.encrypt_type.to_string(),
                e,
            );
            Err(e)
        }
    }

    // decrypt
    fn encode_decrypt_data_request(&self, req: &CryptoDecryptDataOutputRequest) -> Request {
        let url = self.service_url.join("decrypt").unwrap();

        let mut http_req = Request::new(Method::Post, url);
        self.encode_common_headers(&req.common, &mut http_req);
        http_req.insert_header(cyfs_base::CYFS_DECRYPT_TYPE, req.decrypt_type.to_string());
        http_req.insert_header(cyfs_base::CYFS_CRYPTO_FLAGS, req.flags.to_string());

        http_req
    }

    async fn decode_decrypt_data_response(
        mut resp: Response,
    ) -> BuckyResult<CryptoDecryptDataOutputResponse> {
        let result: DecryptDataResult =
            RequestorHelper::decode_header(&resp, cyfs_base::CYFS_DECRYPT_RET)?;

        let data = resp.body_bytes().await.map_err(|e| {
            let msg = format!(
                "get decrypt data from resp failed, read body bytes error! {}",
                e
            );
            error!("{}", msg);

            BuckyError::from(msg)
        })?;

        let resp = CryptoDecryptDataOutputResponse { result, data };

        Ok(resp)
    }

    pub async fn decrypt_data(
        &self,
        req: CryptoDecryptDataOutputRequest,
    ) -> BuckyResult<CryptoDecryptDataOutputResponse> {
        let mut http_req = self.encode_decrypt_data_request(&req);
        let data_len = req.data.len();
        http_req.set_body(req.data);

        let mut resp = self.requestor.request(http_req).await?;

        if resp.status().is_success() {
            let resp = Self::decode_decrypt_data_response(resp).await?;

            info!(
                "decrypt data crypto success: data={}, type={}, {}",
                data_len,
                req.decrypt_type.to_string(),
                resp,
            );

            Ok(resp)
        } else {
            let e = RequestorHelper::error_from_resp(&mut resp).await;
            error!(
                "decrypt data crypto failed: data={}, type={}, {}",
                data_len,
                req.decrypt_type.to_string(),
                e,
            );

            Err(e)
        }
    }
}

#[async_trait::async_trait]
impl CryptoOutputProcessor for CryptoRequestor {
    async fn verify_object(
        &self,
        req: CryptoVerifyObjectOutputRequest,
    ) -> BuckyResult<CryptoVerifyObjectOutputResponse> {
        Self::verify_object(&self, req).await
    }

    async fn sign_object(
        &self,
        req: CryptoSignObjectOutputRequest,
    ) -> BuckyResult<CryptoSignObjectOutputResponse> {
        Self::sign_object(&self, req).await
    }

    async fn encrypt_data(
        &self,
        req: CryptoEncryptDataOutputRequest,
    ) -> BuckyResult<CryptoEncryptDataOutputResponse> {
        Self::encrypt_data(&self, req).await
    }

    async fn decrypt_data(
        &self,
        req: CryptoDecryptDataOutputRequest,
    ) -> BuckyResult<CryptoDecryptDataOutputResponse> {
        Self::decrypt_data(&self, req).await
    }
}