1 //
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 #pragma once
17 
18 #include <any>
19 #include <string>
20 
21 #include "common/libs/utils/result.h"
22 
23 namespace cuttlefish {
24 namespace secure_env {
25 
26 struct StorageData {
27   uint32_t size;
28   uint8_t payload[0];
29 
asUint8StorageData30   Result<uint8_t> asUint8() {
31     CF_EXPECT(size == sizeof(uint8_t), "Size of payload is not matched with uint8 size");
32     return *reinterpret_cast<uint8_t*>(payload);
33   }
34 };
35 
36 /**
37  * A destroyer for StorageData instances created with
38  * CreateStorageData. Wipes memory from the StorageData instances.
39  */
40 class StorageDataDestroyer {
41  public:
42   void operator()(StorageData* ptr);
43 };
44 
45 /** An owning pointer for a StorageData instance. */
46 using ManagedStorageData = std::unique_ptr<StorageData, StorageDataDestroyer>;
47 
48 /**
49  * Allocates memory for a StorageData carrying a message of size
50  * `size`.
51  */
52 Result<ManagedStorageData> CreateStorageData(size_t size);
53 Result<ManagedStorageData> CreateStorageData(const void* data, size_t size);
54 
55 /**
56  * Storage abstraction to store binary blobs associated with string key
57 */
58 class Storage {
59  public:
60   virtual Result<bool> HasKey(const std::string& key) const = 0;
61   virtual Result<ManagedStorageData> Read(const std::string& key) const = 0;
62   virtual Result<void> Write(const std::string& key, const StorageData& data) = 0;
63   virtual bool Exists() const = 0;
64 
65   virtual ~Storage() = default;
66 };
67 
68 } // namespace secure_env
69 } // namespace cuttlefish
70