trustflow_attestation_rs/
lib.rs

1// Copyright 2024 Ant Group Co., Ltd.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//   http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use sdc_apis::secretflowapis::v2::sdc::UnifiedAttestationAttributes;
16use std::ffi::CString;
17
18const BUFFER_SIZE_IN_BYTES: u32 = 8192;
19
20pub type Error = Box<dyn std::error::Error + Send + Sync>;
21
22pub fn parse_attributes_from_report(
23    report_json_str: &str,
24) -> Result<UnifiedAttestationAttributes, Error> {
25    let c_report_json_str = CString::new(report_json_str.as_bytes())
26        .map_err(|_| Error::from("attestation_report_verify: report_json_str ffi failure"))?;
27
28    let mut attrs_len = get_attributes_max_size()?;
29    let mut attrs_buf = vec![0; attrs_len as usize];
30
31    let mut msg_buf = vec![0; BUFFER_SIZE_IN_BYTES as usize];
32    let mut msg_len: u32 = BUFFER_SIZE_IN_BYTES;
33    let mut details_len: u32 = 0;
34
35    // c lib interface
36    let code = unsafe {
37        trustflow_attestation_sys::ParseAttributesFromReport(
38            c_report_json_str.as_ptr(),
39            report_json_str.len() as u32,
40            attrs_buf.as_mut_ptr() as *mut i8,
41            &mut attrs_len,
42            msg_buf.as_mut_ptr() as *mut i8,
43            &mut msg_len,
44            std::ptr::null_mut(),
45            &mut details_len,
46        )
47    };
48    if code != 0 {
49        match std::str::from_utf8(&msg_buf[..(msg_len as usize)]) {
50            Ok(v) => return Err(v.into()),
51            Err(e) => return Err(format!("parse error msg failed, {}", e).into()),
52        };
53    }
54
55    Ok(serde_json::from_slice(&attrs_buf[..(attrs_len as usize)])?)
56}
57
58pub fn get_attributes_max_size() -> Result<u32, Error> {
59    return Ok(unsafe { trustflow_attestation_sys::GetAttributesMaxSize() });
60}
61
62/// Verifies the given attestation report against the given policy.
63///
64/// # Arguments
65///
66/// * `report_json_str` - The JSON string representation of the attestation report.
67/// * `policy_json_str` - The JSON string representation of the policy.
68///
69/// # Returns
70///
71/// A result containing either an empty tuple indicating success or an error message.
72pub fn attestation_report_verify(
73    report_json_str: &str,
74    policy_json_str: &str,
75) -> Result<(), Error> {
76    let c_report_json_str = CString::new(report_json_str.as_bytes())
77        .map_err(|_| Error::from("attestation_report_verify: report_json_str ffi failure"))?;
78
79    let c_policy_json_str = CString::new(policy_json_str.as_bytes())
80        .map_err(|_| Error::from("attestation_report_verify: policy_json_str ffi failure"))?;
81
82    let mut msg_buf = vec![0; BUFFER_SIZE_IN_BYTES as usize];
83    let mut msg_len: u32 = BUFFER_SIZE_IN_BYTES;
84    let mut details_len: u32 = 0;
85
86    // c lib interface
87    let code = unsafe {
88        trustflow_attestation_sys::AttestationReportVerify(
89            c_report_json_str.as_ptr(),
90            report_json_str.len() as u32,
91            c_policy_json_str.as_ptr(),
92            policy_json_str.len() as u32,
93            msg_buf.as_mut_ptr() as *mut i8,
94            &mut msg_len,
95            std::ptr::null_mut(),
96            &mut details_len,
97        )
98    };
99    if code != 0 {
100        match std::str::from_utf8(&msg_buf[..(msg_len as usize)]) {
101            Ok(v) => return Err(v.into()),
102            Err(e) => return Err(format!("parse error msg failed, {}", e).into()),
103        };
104    }
105
106    Ok(())
107}
108
109/// Gets the size of the attestation report that would be generated using the given parameters.
110///
111/// # Arguments
112///
113/// * `params_json_str` - The JSON string representation of the parameters.
114///
115/// # Returns
116///
117/// A result containing either the size of the attestation report or an error message.
118pub fn get_attestation_report_size(params_json_str: &str) -> Result<u32, Error> {
119    let c_params_json_str = CString::new(params_json_str.as_bytes())
120        .map_err(|_| Error::from("attestation_report_verify: params_json_str ffi failure"))?;
121    let mut report_len: u32 = 0;
122    let code = unsafe {
123        trustflow_attestation_sys::GetAttestationReportSize(
124            c_params_json_str.as_ptr(),
125            params_json_str.len() as u32,
126            &mut report_len,
127        )
128    };
129    if code != 0 {
130        return Err(format!("get_attestation_report_size failed").into());
131    }
132    return Ok(report_len);
133}
134
135/// Generates an attestation report using the given parameters.
136///
137/// # Arguments
138///
139/// * `params_json_str` - The JSON string representation of the parameters.
140///
141/// # Returns
142///
143/// A result containing either the generated attestation report or an error message.
144pub fn generate_attestation_report(params_json_str: &str) -> Result<std::string::String, Error> {
145    let mut report_len = get_attestation_report_size(params_json_str)?;
146    let mut report_buf = vec![0; report_len as usize];
147
148    let mut msg_buf = vec![0; BUFFER_SIZE_IN_BYTES as usize];
149    let mut msg_len: u32 = BUFFER_SIZE_IN_BYTES;
150    let mut details_len: u32 = 0;
151
152    let c_params_json_str = CString::new(params_json_str.as_bytes())
153        .map_err(|_| Error::from("attestation_report_verify: params_json_str ffi failure"))?;
154
155    let code = unsafe {
156        trustflow_attestation_sys::GenerateAttestationReport(
157            c_params_json_str.as_ptr(),
158            params_json_str.len() as u32,
159            report_buf.as_mut_ptr() as *mut i8,
160            &mut report_len,
161            msg_buf.as_mut_ptr() as *mut i8,
162            &mut msg_len,
163            std::ptr::null_mut(),
164            &mut details_len,
165        )
166    };
167
168    if code != 0 {
169        match std::str::from_utf8(&msg_buf[..(msg_len as usize)]) {
170            Ok(v) => return Err(v.into()),
171            Err(e) => return Err(format!("parse error msg failed, {}", e).into()),
172        };
173    }
174
175    return Ok(std::str::from_utf8(&report_buf[..(report_len as usize)])?.to_string());
176}
177
178