blob: 4cd0cb74ae694e033039f63c7ddc6622e12a6033 [file] [log] [blame]
David Drysdale6c09af22023-11-06 09:57:10 +00001/*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//! Common functionality for non-secure/testing instance of AuthGraph.
18
19use authgraph_boringssl as boring;
20use authgraph_core::{
21 key::MillisecondsSinceEpoch,
22 ta::{AuthGraphTa, Role},
23 traits,
24};
25use authgraph_hal::channel::SerializedChannel;
26use std::sync::{Arc, Mutex};
27use std::time::Instant;
28
29/// Monotonic clock with an epoch that starts at the point of construction.
30/// (This makes it unsuitable for use outside of testing, because the epoch
31/// will not match that of any other component.)
32pub struct StdClock(Instant);
33
34impl Default for StdClock {
35 fn default() -> Self {
36 Self(Instant::now())
37 }
38}
39
40impl traits::MonotonicClock for StdClock {
41 fn now(&self) -> MillisecondsSinceEpoch {
42 let millis: i64 = self
43 .0
44 .elapsed()
45 .as_millis()
46 .try_into()
47 .expect("failed to fit timestamp in i64");
48 MillisecondsSinceEpoch(millis)
49 }
50}
51
52/// Implementation of the AuthGraph TA that runs locally in-process (and which is therefore
53/// insecure).
54pub struct LocalTa {
55 ta: Arc<Mutex<AuthGraphTa>>,
56}
57
58impl LocalTa {
59 /// Create a new instance.
60 pub fn new() -> Self {
61 Self {
62 ta: Arc::new(Mutex::new(AuthGraphTa::new(
63 boring::trait_impls(
64 Box::<boring::test_device::AgDevice>::default(),
65 Some(Box::new(StdClock::default())),
66 ),
67 Role::Both,
68 ))),
69 }
70 }
71}
72
73/// Pretend to be a serialized channel to the TA, but actually just directly invoke the TA with
74/// incoming requests.
75impl SerializedChannel for LocalTa {
76 const MAX_SIZE: usize = usize::MAX;
77
78 fn execute(&mut self, req_data: &[u8]) -> binder::Result<Vec<u8>> {
79 Ok(self.ta.lock().unwrap().process(req_data))
80 }
81}