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
use std::{collections::HashMap, convert::TryInto};

use crate::{
    configuration::Endpoint,
    groups_v2::model::{Group, GroupChanges},
    groups_v2::operations::{GroupDecodingError, GroupOperations},
    prelude::{PushService, ServiceError},
    proto::GroupContextV2,
    push_service::{HttpAuth, HttpAuthOverride, ServiceIds},
    utils::BASE64_RELAXED,
};

use base64::prelude::*;
use bytes::Bytes;
use chrono::{Days, NaiveDate, NaiveTime, Utc};
use futures::AsyncReadExt;
use rand::RngCore;
use serde::Deserialize;
use zkgroup::{
    auth::AuthCredentialWithPniResponse,
    groups::{GroupMasterKey, GroupSecretParams},
    ServerPublicParams,
};

#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TemporalCredential {
    credential: String,
    redemption_time: u64,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CredentialResponse {
    credentials: Vec<TemporalCredential>,
}

impl CredentialResponse {
    pub fn parse(
        self,
    ) -> Result<HashMap<u64, AuthCredentialWithPniResponse>, ServiceError> {
        self.credentials
            .into_iter()
            .map(|c| {
                let bytes = BASE64_RELAXED.decode(c.credential)?;
                let data = AuthCredentialWithPniResponse::new(&bytes)?;
                Ok((c.redemption_time, data))
            })
            .collect::<Result<_, ServiceError>>()
    }
}

#[derive(Debug, thiserror::Error)]
pub enum CredentialsCacheError {
    #[error("failed to read values from cache: {0}")]
    ReadError(String),
    #[error("failed to write values from cache: {0}")]
    WriteError(String),
}

/// Global cache for groups v2 credentials, as demonstrated in the libsignal-service
/// java library of Signal-Android.
///
/// A basic in-memory implementation is provided with `InMemoryCredentialsCache`.
pub trait CredentialsCache {
    fn clear(&mut self) -> Result<(), CredentialsCacheError>;

    /// Get an entry of the cache, key usually represents the day number since EPOCH.
    fn get(
        &self,
        key: &u64,
    ) -> Result<Option<&AuthCredentialWithPniResponse>, CredentialsCacheError>;

    /// Overwrite the entire contents of the cache with new data.
    fn write(
        &mut self,
        map: HashMap<u64, AuthCredentialWithPniResponse>,
    ) -> Result<(), CredentialsCacheError>;
}

#[derive(Default)]
pub struct InMemoryCredentialsCache {
    map: HashMap<u64, AuthCredentialWithPniResponse>,
}

impl CredentialsCache for InMemoryCredentialsCache {
    fn clear(&mut self) -> Result<(), CredentialsCacheError> {
        self.map.clear();
        Ok(())
    }

    fn get(
        &self,
        key: &u64,
    ) -> Result<Option<&AuthCredentialWithPniResponse>, CredentialsCacheError>
    {
        Ok(self.map.get(key))
    }

    fn write(
        &mut self,
        map: HashMap<u64, AuthCredentialWithPniResponse>,
    ) -> Result<(), CredentialsCacheError> {
        self.map = map;
        Ok(())
    }
}

impl<T: CredentialsCache> CredentialsCache for &mut T {
    fn clear(&mut self) -> Result<(), CredentialsCacheError> {
        (**self).clear()
    }

    fn get(
        &self,
        key: &u64,
    ) -> Result<Option<&AuthCredentialWithPniResponse>, CredentialsCacheError>
    {
        (**self).get(key)
    }

    fn write(
        &mut self,
        map: HashMap<u64, AuthCredentialWithPniResponse>,
    ) -> Result<(), CredentialsCacheError> {
        (**self).write(map)
    }
}

pub struct GroupsManager<S: PushService, C: CredentialsCache> {
    service_ids: ServiceIds,
    push_service: S,
    credentials_cache: C,
    server_public_params: ServerPublicParams,
}

impl<S: PushService, C: CredentialsCache> GroupsManager<S, C> {
    pub fn new(
        service_ids: ServiceIds,
        push_service: S,
        credentials_cache: C,
        server_public_params: ServerPublicParams,
    ) -> Self {
        Self {
            service_ids,
            push_service,
            credentials_cache,
            server_public_params,
        }
    }

    pub async fn get_authorization_for_today(
        &mut self,
        group_secret_params: GroupSecretParams,
    ) -> Result<HttpAuth, ServiceError> {
        let (today, today_plus_7_days) = current_days_seconds();

        let auth_credential_response = if let Some(auth_credential_response) =
            self.credentials_cache.get(&today)?
        {
            auth_credential_response
        } else {
            let path =
            format!("/v1/certificate/auth/group?redemptionStartSeconds={}&redemptionEndSeconds={}&pniAsServiceId=true", today, today_plus_7_days);

            let credentials_response: CredentialResponse = self
                .push_service
                .get_json(
                    Endpoint::Service,
                    &path,
                    &[],
                    HttpAuthOverride::NoOverride,
                )
                .await?;
            self.credentials_cache
                .write(credentials_response.parse()?)?;
            self.credentials_cache.get(&today)?.ok_or_else(|| {
                ServiceError::ResponseError {
                    reason:
                        "credentials received did not contain requested day"
                            .into(),
                }
            })?
        };

        self.get_authorization_string(
            group_secret_params,
            auth_credential_response.clone(),
            today,
        )
    }

    fn get_authorization_string(
        &self,
        group_secret_params: GroupSecretParams,
        credential_response: AuthCredentialWithPniResponse,
        today: u64,
    ) -> Result<HttpAuth, ServiceError> {
        let auth_credential = self
            .server_public_params
            .receive_auth_credential_with_pni_as_service_id(
                self.service_ids.aci(),
                self.service_ids.pni(),
                zkgroup::Timestamp::from_epoch_seconds(today),
                credential_response,
            )
            .map_err(|e| {
                tracing::error!(
                    "failed to receive auth credentials with PNI: {:?}",
                    e
                );
                ServiceError::GroupsV2Error
            })?;

        let mut random_bytes = [0u8; 32];
        rand::thread_rng().fill_bytes(&mut random_bytes);

        let auth_credential_presentation = self
            .server_public_params
            .create_auth_credential_with_pni_presentation(
                random_bytes,
                group_secret_params,
                auth_credential,
            );

        // see simpleapi.rs GroupSecretParams_getPublicParams, everything is bincode encoded
        // across the boundary of Rust/Java
        let username = hex::encode(bincode::serialize(
            &group_secret_params.get_public_params(),
        )?);

        let password =
            hex::encode(bincode::serialize(&auth_credential_presentation)?);

        Ok(HttpAuth { username, password })
    }

    #[deprecated = "please use fetch_encrypted_group and decrypt_group separately, which hide more of the implementation details"]
    pub async fn get_group(
        &mut self,
        group_secret_params: GroupSecretParams,
        credentials: HttpAuth,
    ) -> Result<Group, ServiceError> {
        let encrypted_group = self.push_service.get_group(credentials).await?;
        let decrypted_group = GroupOperations::new(group_secret_params)
            .decrypt_group(encrypted_group)?;

        Ok(decrypted_group)
    }

    pub async fn fetch_encrypted_group(
        &mut self,
        master_key_bytes: &[u8],
    ) -> Result<crate::proto::Group, ServiceError> {
        let group_master_key = GroupMasterKey::new(
            master_key_bytes
                .try_into()
                .map_err(|_| ServiceError::GroupsV2Error)?,
        );
        let group_secret_params =
            GroupSecretParams::derive_from_master_key(group_master_key);
        let authorization = self
            .get_authorization_for_today(group_secret_params)
            .await?;
        self.push_service.get_group(authorization).await
    }

    #[tracing::instrument(
        skip(self, group_secret_params),
        fields(path = %path[..4.min(path.len())]),
    )]
    pub async fn retrieve_avatar(
        &mut self,
        path: &str,
        group_secret_params: GroupSecretParams,
    ) -> Result<Option<Vec<u8>>, ServiceError> {
        let mut encrypted_avatar = self
            .push_service
            .retrieve_groups_v2_profile_avatar(path)
            .await?;
        let mut result = Vec::with_capacity(10 * 1024 * 1024);
        encrypted_avatar
            .read_to_end(&mut result)
            .await
            .map_err(|e| ServiceError::ResponseError {
                reason: format!("reading avatar data: {}", e),
            })?;
        Ok(GroupOperations::new(group_secret_params).decrypt_avatar(&result))
    }

    pub fn decrypt_group_context(
        &self,
        group_context: GroupContextV2,
    ) -> Result<Option<GroupChanges>, GroupDecodingError> {
        match (group_context.master_key, group_context.group_change) {
            (Some(master_key), Some(group_change)) => {
                let master_key_bytes: [u8; 32] = master_key
                    .try_into()
                    .map_err(|_| GroupDecodingError::WrongBlob)?;
                let group_master_key = GroupMasterKey::new(master_key_bytes);
                let group_secret_params =
                    GroupSecretParams::derive_from_master_key(group_master_key);
                let encrypted_group_change =
                    prost::Message::decode(Bytes::from(group_change))?;
                let group_change = GroupOperations::new(group_secret_params)
                    .decrypt_group_change(encrypted_group_change)?;
                Ok(Some(group_change))
            },
            _ => Ok(None),
        }
    }
}

pub fn decrypt_group(
    master_key_bytes: &[u8],
    encrypted_group: crate::proto::Group,
) -> Result<Group, ServiceError> {
    let group_master_key = GroupMasterKey::new(
        master_key_bytes
            .try_into()
            .expect("wrong master key bytes length"),
    );
    let group_secret_params =
        GroupSecretParams::derive_from_master_key(group_master_key);

    Ok(GroupOperations::new(group_secret_params)
        .decrypt_group(encrypted_group)?)
}

fn current_days_seconds() -> (u64, u64) {
    let days_seconds = |date: NaiveDate| {
        date.and_time(NaiveTime::from_hms_opt(0, 0, 0).unwrap())
            .and_utc()
            .timestamp() as u64
    };

    let today = Utc::now().naive_utc().date();
    let today_plus_7_days = today + Days::new(7);

    (days_seconds(today), days_seconds(today_plus_7_days))
}