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
//
// Copyright 2023 Signal Messenger, LLC.
// SPDX-License-Identifier: AGPL-3.0-only
//

//! Provides CreateCallLinkCredential and related types.
//!
//! CreateCallLinkCredential is a MAC over:
//! - a call link room ID (chosen by the client, blinded at issuance, revealed for verification)
//! - the user's ACI (provided by the chat server at issuance, passed encrypted to the calling server for verification)
//! - a timestamp, truncated to day granularity (chosen by the chat server at issuance, passed publicly to the calling server for verification)

use curve25519_dalek_signal::ristretto::RistrettoPoint;
use partial_default::PartialDefault;
use poksho::ShoApi;
use serde::{Deserialize, Serialize};

use super::{CallLinkPublicParams, CallLinkSecretParams};
use crate::common::serialization::ReservedByte;
use crate::common::sho::Sho;
use crate::common::simple_types::*;
use crate::crypto::uid_encryption;
use crate::crypto::uid_struct::UidStruct;
use crate::generic_server_params::{GenericServerPublicParams, GenericServerSecretParams};
use crate::groups::UuidCiphertext;
use crate::ZkGroupVerificationFailure;

#[derive(Serialize, Deserialize, Clone, Copy)]
struct CallLinkRoomIdPoint(RistrettoPoint);

impl CallLinkRoomIdPoint {
    fn new(room_id: &[u8]) -> Self {
        Self(Sho::new(b"20230413_Signal_CallLinkRoomId", room_id).get_point())
    }
}

impl zkcredential::attributes::RevealedAttribute for CallLinkRoomIdPoint {
    fn as_point(&self) -> RistrettoPoint {
        self.0
    }
}

const CREDENTIAL_LABEL: &[u8] = b"20230413_Signal_CreateCallLinkCredential";

#[derive(Serialize, Deserialize, PartialDefault)]
pub struct CreateCallLinkCredentialRequestContext {
    reserved: ReservedByte,
    blinded_room_id: zkcredential::issuance::blind::BlindedPoint,
    key_pair: zkcredential::issuance::blind::BlindingKeyPair,
}

impl CreateCallLinkCredentialRequestContext {
    pub fn new(room_id: &[u8], randomness: RandomnessBytes) -> Self {
        let mut sho =
            poksho::ShoHmacSha256::new(b"20230413_Signal_CreateCallLinkCredentialRequest");
        sho.absorb_and_ratchet(&randomness);

        let key_pair = zkcredential::issuance::blind::BlindingKeyPair::generate(&mut sho);
        let blinded_room_id = key_pair
            .blind(&CallLinkRoomIdPoint::new(room_id), &mut sho)
            .into();

        Self {
            reserved: Default::default(),
            blinded_room_id,
            key_pair,
        }
    }

    pub fn get_request(&self) -> CreateCallLinkCredentialRequest {
        CreateCallLinkCredentialRequest {
            reserved: Default::default(),
            blinded_room_id: self.blinded_room_id,
            public_key: *self.key_pair.public_key(),
        }
    }
}

#[derive(Serialize, Deserialize, PartialDefault)]
pub struct CreateCallLinkCredentialRequest {
    reserved: ReservedByte,
    blinded_room_id: zkcredential::issuance::blind::BlindedPoint,
    public_key: zkcredential::issuance::blind::BlindingPublicKey,
    // Note that unlike ProfileKeyCredentialRequest, we don't have a proof. This is because our only
    // "blinded" attribute is derived from the room ID, making it effectively random as far as the
    // issuing server is concerned. Whether or not the server is willing to issue a
    // CreateCallLinkCredential doesn't depend on what that room ID is; in the very unlikely case of
    // a collision, the client will get a failure when they use the credential presentation to
    // actually attempt to create the link.
    //
    // (RingRTC will only generate room IDs of a certain form, but we don't need to enforce that
    // using zkproofs; we can do so more directly in RingRTC and on the calling server.)
}

impl CreateCallLinkCredentialRequest {
    pub fn issue(
        &self,
        user_id: libsignal_core::Aci,
        timestamp: Timestamp,
        params: &GenericServerSecretParams,
        randomness: RandomnessBytes,
    ) -> CreateCallLinkCredentialResponse {
        CreateCallLinkCredentialResponse {
            reserved: Default::default(),
            timestamp,
            blinded_credential: zkcredential::issuance::IssuanceProofBuilder::new(CREDENTIAL_LABEL)
                .add_public_attribute(&timestamp)
                .add_attribute(&UidStruct::from_service_id(user_id.into()))
                .add_blinded_revealed_attribute(&self.blinded_room_id)
                .issue(&params.credential_key, &self.public_key, randomness),
        }
    }
}

#[derive(Serialize, Deserialize, PartialDefault)]
pub struct CreateCallLinkCredentialResponse {
    reserved: ReservedByte,
    // Does not include the room ID or the user ID, because the client already knows those.
    timestamp: Timestamp,
    blinded_credential: zkcredential::issuance::blind::BlindedIssuanceProof,
}

impl CreateCallLinkCredentialRequestContext {
    pub fn receive(
        self,
        response: CreateCallLinkCredentialResponse,
        user_id: libsignal_core::Aci,
        params: &GenericServerPublicParams,
    ) -> Result<CreateCallLinkCredential, ZkGroupVerificationFailure> {
        if !response.timestamp.is_day_aligned() {
            return Err(ZkGroupVerificationFailure);
        }

        Ok(CreateCallLinkCredential {
            reserved: Default::default(),
            timestamp: response.timestamp,
            credential: zkcredential::issuance::IssuanceProofBuilder::new(CREDENTIAL_LABEL)
                .add_public_attribute(&response.timestamp)
                .add_attribute(&UidStruct::from_service_id(user_id.into()))
                .add_blinded_revealed_attribute(&self.blinded_room_id)
                .verify(
                    &params.credential_key,
                    &self.key_pair,
                    response.blinded_credential,
                )
                .map_err(|_| ZkGroupVerificationFailure)?,
        })
    }
}

#[derive(Serialize, Deserialize, PartialDefault)]
pub struct CreateCallLinkCredential {
    reserved: ReservedByte,
    // We could avoid having to pass in the room ID or user ID again if we saved them here, but
    // that's readily available information in the apps, so we may as well keep the credential
    // small.
    timestamp: Timestamp,
    credential: zkcredential::credentials::Credential,
}

impl CreateCallLinkCredential {
    pub fn present(
        &self,
        room_id: &[u8],
        user_id: libsignal_core::Aci,
        server_params: &GenericServerPublicParams,
        call_link_params: &CallLinkSecretParams,
        randomness: RandomnessBytes,
    ) -> CreateCallLinkCredentialPresentation {
        let user_id = UidStruct::from_service_id(user_id.into());
        let encrypted_user_id = call_link_params.uid_enc_key_pair.encrypt(&user_id);
        CreateCallLinkCredentialPresentation {
            reserved: Default::default(),
            timestamp: self.timestamp,
            user_id: encrypted_user_id,
            proof: zkcredential::presentation::PresentationProofBuilder::new(CREDENTIAL_LABEL)
                .add_attribute(&user_id, &call_link_params.uid_enc_key_pair)
                .add_revealed_attribute(&CallLinkRoomIdPoint::new(room_id))
                .present(&server_params.credential_key, &self.credential, randomness),
        }
    }
}

#[derive(Serialize, Deserialize, PartialDefault)]
pub struct CreateCallLinkCredentialPresentation {
    reserved: ReservedByte,
    // The room ID is provided externally as part of the request.
    user_id: zkcredential::attributes::Ciphertext<uid_encryption::UidEncryptionDomain>,
    timestamp: Timestamp,
    proof: zkcredential::presentation::PresentationProof,
}

impl CreateCallLinkCredentialPresentation {
    pub fn verify(
        &self,
        room_id: &[u8],
        current_time: Timestamp,
        server_params: &GenericServerSecretParams,
        call_link_params: &CallLinkPublicParams,
    ) -> Result<(), ZkGroupVerificationFailure> {
        let expiration = self
            .timestamp
            .checked_add_seconds(30 * 60 * 60) // 30 hours, to account for clock skew
            .ok_or(ZkGroupVerificationFailure)?;

        if !(self.timestamp..expiration).contains(&current_time) {
            return Err(ZkGroupVerificationFailure);
        }

        zkcredential::presentation::PresentationProofVerifier::new(CREDENTIAL_LABEL)
            .add_public_attribute(&self.timestamp)
            .add_attribute(&self.user_id, &call_link_params.uid_enc_public_key)
            .add_revealed_attribute(&CallLinkRoomIdPoint::new(room_id))
            .verify(&server_params.credential_key, &self.proof)
            .map_err(|_| ZkGroupVerificationFailure)
    }

    pub fn get_user_id(&self) -> UuidCiphertext {
        UuidCiphertext {
            reserved: Default::default(),
            ciphertext: self.user_id,
        }
    }
}