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
use crate::client::auth::{Auth, PrivAuth};
use crate::client::LightningStorageClient;
use crate::proto::{self, GetRequest, InfoRequest, PingRequest, PutRequest};
use crate::util::{compute_shared_hmac, prepare_value_for_put, process_value_from_get};
use crate::Value;
use log::{debug, error};
use secp256k1::rand::rngs::OsRng;
use secp256k1::rand::RngCore;
use secp256k1::PublicKey;
use thiserror::Error;
use tonic::{transport, Request};

#[derive(Debug, Error)]
pub enum ClientError {
    #[error("transport error")]
    Connect(#[from] transport::Error),
    #[error("API error")]
    Tonic(#[from] tonic::Status),
    #[error("invalid response from server")]
    InvalidResponse,
    /// client HMAC integrity error, with string
    #[error("invalid HMAC for key {0} version {1}")]
    InvalidHmac(String, i64),
    /// server HMAC integrity error, with string
    #[error("invalid server HMAC")]
    InvalidServerHmac(),
    #[error("Put had conflicts")]
    PutConflict(Vec<(String, Value)>),
}

pub struct Client {
    client: LightningStorageClient<transport::Channel>,
    auth: Auth,
}

impl Client {
    /// Get the server info
    pub async fn get_info(uri: &str) -> Result<(PublicKey, String), ClientError> {
        debug!("info");
        let mut client = connect(uri).await?;
        let info_request = Request::new(InfoRequest {});

        let response = client.info(info_request).await?.into_inner();
        debug!("info result {:?}", response);
        let pubkey = PublicKey::from_slice(&response.server_id).map_err(|_| ClientError::InvalidResponse)?;
        let version = response.version;
        Ok((pubkey, version))
    }

    pub async fn new(uri: &str, auth: Auth) -> Result<Self, ClientError> {
        let client = connect(uri).await?;
        Ok(Self { client, auth })
    }

    pub async fn ping(uri: &str, message: &str) -> Result<String, ClientError> {
        debug!("ping");
        let mut client = connect(uri).await?;
        let ping_request = Request::new(PingRequest { message: message.into() });

        let response = client.ping(ping_request).await?.into_inner();
        debug!("ping result {:?}", response);
        Ok(response.message)
    }

    pub async fn get(
        &mut self,
        key_prefix: String,
        nonce: &[u8],
    ) -> Result<(Vec<(String, Value)>, Vec<u8>), ClientError> {
        let get_request = Request::new(GetRequest {
            auth: self.make_auth_proto(),
            key_prefix,
            nonce: nonce.to_vec(),
        });

        let response = self.client.get(get_request).await?.into_inner();
        let kvs = kvs_from_proto(response.kvs);

        Ok((kvs, response.hmac))
    }

    pub async fn put(&mut self, kvs: Vec<(String, Value)>, client_hmac: &[u8]) -> Result<Vec<u8>, ClientError> {
        let kvs_proto = kvs
            .into_iter()
            .map(|(k, v)| proto::KeyValue {
                key: k.clone(),
                value: v.value.clone(),
                version: v.version,
            })
            .collect();

        let put_request = Request::new(PutRequest {
            auth: self.make_auth_proto(),
            kvs: kvs_proto,
            hmac: client_hmac.to_vec(),
        });

        let response = self.client.put(put_request).await?.into_inner();
        debug!("put result {:?}", response);

        if response.success {
            Ok(response.hmac)
        } else {
            let conflicts = kvs_from_proto(response.conflicts);
            Err(ClientError::PutConflict(conflicts))
        }
    }

    fn make_auth_proto(&self) -> Option<proto::Auth> {
        Some(proto::Auth {
            client_id: self.auth.client_id.serialize().to_vec(),
            token: self.auth.auth_token(),
        })
    }
}

pub struct PrivClient {
    client: Client,
    auth: PrivAuth,
}

impl PrivClient {
    /// Get the server info
    pub async fn get_info(uri: &str) -> Result<(PublicKey, String), ClientError> {
        Client::get_info(uri).await
    }

    pub async fn new(uri: &str, auth: PrivAuth) -> Result<Self, ClientError> {
        let client = Client::new(uri, auth.auth()).await?;
        Ok(Self { client, auth })
    }

    pub async fn ping(uri: &str, message: &str) -> Result<String, ClientError> {
        Client::ping(uri, message).await
    }

    pub async fn get(
        &mut self,
        hmac_secret: &[u8],
        key_prefix: String,
    ) -> Result<Vec<(String, Value)>, ClientError> {
        let mut nonce = Vec::with_capacity(32);
        nonce.resize(32, 0);
        let mut rng = OsRng;
        rng.fill_bytes(&mut nonce);

        debug!("get request '{}'", key_prefix);

        let (mut kvs, received_hmac) = self.client.get(key_prefix, &nonce).await?;
        let hmac = compute_shared_hmac(&self.auth.shared_secret, &nonce, &kvs);
        if received_hmac != hmac {
            error!("get hmac mismatch");
            return Err(ClientError::InvalidServerHmac());
        }

        remove_and_check_hmacs(&hmac_secret, &mut kvs)?;
        debug!("get result {:?}", kvs);
        Ok(kvs)
    }

    /// values do not include HMAC
    pub async fn put(
        &mut self,
        hmac_secret: &[u8],
        mut kvs: Vec<(String, Value)>,
    ) -> Result<(), ClientError> {
        debug!("put request {:?}", kvs);
        kvs.sort_by_key(|(k, _)| k.clone());
        for (key, value) in kvs.iter_mut() {
            prepare_value_for_put(hmac_secret, key, value);
        }

        let client_hmac = compute_shared_hmac(&self.auth.shared_secret, &[0x01], &kvs);

        let server_hmac = compute_shared_hmac(&self.auth.shared_secret, &[0x02], &kvs);

        match self.client.put(kvs, &client_hmac).await {
            Ok(received_server_hmac) => {
                if received_server_hmac == server_hmac {
                    return Ok(())
                } else {
                    error!("put hmac mismatch");
                    return Err(ClientError::InvalidServerHmac())
                }
            },
            Err(ClientError::PutConflict(mut conflicts)) => {
                remove_and_check_hmacs(&hmac_secret, &mut conflicts)?;
                error!("put conflicts {:?}", conflicts);
                Err(ClientError::PutConflict(conflicts))
            }
            Err(e) => Err(e),
        }
    }
}

async fn connect(uri: &str) -> Result<LightningStorageClient<transport::Channel>, ClientError> {
    debug!("connect to {}", uri.to_string());
    let uri_clone = String::from(uri);
    Ok(LightningStorageClient::connect(uri_clone).await?)
}

fn kvs_from_proto(conflicts_proto: Vec<proto::KeyValue>) -> Vec<(String, Value)> {
    conflicts_proto
        .into_iter()
        .map(|kv| (kv.key, Value { version: kv.version, value: kv.value }))
        .collect()
}

fn remove_and_check_hmacs(
    hmac_secret: &[u8],
    kvs: &mut Vec<(String, Value)>,
) -> Result<(), ClientError> {
    for (key, value) in kvs.iter_mut() {
        process_value_from_get(hmac_secret, key, value)
            .map_err(|()| ClientError::InvalidHmac(key.clone(), value.version))?;
    }
    Ok(())
}