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

use libsignal_core::{Aci, Pni};
use partial_default::PartialDefault;
use serde::{Deserialize, Serialize};
use zkcredential::credentials::{CredentialKeyPair, CredentialPublicKey};

use crate::api::auth::auth_credential_with_pni::AuthCredentialWithPniVersion;
use crate::common::constants::PRESENTATION_VERSION_4;
use crate::common::serialization::VersionByte;
use crate::common::simple_types::{RandomnessBytes, Timestamp};
use crate::crypto::uid_encryption;
use crate::crypto::uid_struct::UidStruct;
use crate::groups::{GroupPublicParams, GroupSecretParams, UuidCiphertext};
use crate::{ServerPublicParams, ServerSecretParams, ZkGroupVerificationFailure};

const CREDENTIAL_LABEL: &[u8] = b"20240222_Signal_AuthCredentialZkc";

/// Authentication credential implemented using [`zkcredential`].
///
/// The same credential as [`crate::api::auth::AuthCredentialWithPni`] but
/// implemented using the types and mechanism from the `zkcredential` crate.
#[derive(Clone, Serialize, Deserialize, PartialDefault)]
pub struct AuthCredentialWithPniZkc {
    version: VersionByte<{ AuthCredentialWithPniVersion::Zkc as u8 }>,
    credential: zkcredential::credentials::Credential,
    aci: UidStruct,
    pni: UidStruct,
    redemption_time: Timestamp,
}

#[derive(Clone, Serialize, Deserialize, PartialDefault)]
pub struct AuthCredentialWithPniZkcResponse {
    version: VersionByte<{ AuthCredentialWithPniVersion::Zkc as u8 }>,
    proof: zkcredential::issuance::IssuanceProof,
}

#[derive(Serialize, Deserialize, PartialDefault)]
pub struct AuthCredentialWithPniZkcPresentation {
    version: VersionByte<PRESENTATION_VERSION_4>,
    proof: zkcredential::presentation::PresentationProof,
    aci_ciphertext: uid_encryption::Ciphertext,
    pni_ciphertext: uid_encryption::Ciphertext,
    redemption_time: Timestamp,
}

impl AuthCredentialWithPniZkcResponse {
    pub fn issue_credential(
        aci: Aci,
        pni: Pni,
        redemption_time: Timestamp,
        params: &ServerSecretParams,
        randomness: RandomnessBytes,
    ) -> Self {
        Self::issue_credential_for_key(
            aci,
            pni,
            redemption_time,
            &params.generic_credential_key_pair,
            randomness,
        )
    }

    pub fn receive(
        self,
        aci: Aci,
        pni: Pni,
        redemption_time: Timestamp,
        public_params: &ServerPublicParams,
    ) -> Result<AuthCredentialWithPniZkc, ZkGroupVerificationFailure> {
        self.receive_for_key(
            aci,
            pni,
            redemption_time,
            &public_params.generic_credential_public_key,
        )
    }

    pub(crate) fn issue_credential_for_key(
        aci: Aci,
        pni: Pni,
        redemption_time: Timestamp,
        credential_key: &CredentialKeyPair,
        randomness: RandomnessBytes,
    ) -> Self {
        let proof = zkcredential::issuance::IssuanceProofBuilder::new(CREDENTIAL_LABEL)
            .add_attribute(&UidStruct::from_service_id(aci.into()))
            .add_attribute(&UidStruct::from_service_id(pni.into()))
            .add_public_attribute(&redemption_time)
            .issue(credential_key, randomness);

        Self {
            version: VersionByte,
            proof,
        }
    }

    pub(crate) fn receive_for_key(
        self,
        aci: Aci,
        pni: Pni,
        redemption_time: Timestamp,
        public_key: &CredentialPublicKey,
    ) -> Result<AuthCredentialWithPniZkc, ZkGroupVerificationFailure> {
        if !redemption_time.is_day_aligned() {
            return Err(ZkGroupVerificationFailure);
        }

        let aci = UidStruct::from_service_id(aci.into());
        let pni = UidStruct::from_service_id(pni.into());

        let raw_credential = zkcredential::issuance::IssuanceProofBuilder::new(CREDENTIAL_LABEL)
            .add_attribute(&aci)
            .add_attribute(&pni)
            .add_public_attribute(&redemption_time)
            .verify(public_key, self.proof)?;

        Ok(AuthCredentialWithPniZkc {
            credential: raw_credential,
            version: VersionByte,
            aci,
            pni,
            redemption_time,
        })
    }
}

impl AuthCredentialWithPniZkc {
    pub fn present(
        &self,
        public_params: &ServerPublicParams,
        group_secret_params: &GroupSecretParams,
        randomness: RandomnessBytes,
    ) -> AuthCredentialWithPniZkcPresentation {
        self.present_for_key(
            &public_params.generic_credential_public_key,
            group_secret_params,
            randomness,
        )
    }

    pub(crate) fn present_for_key(
        &self,
        public_key: &CredentialPublicKey,
        group_secret_params: &GroupSecretParams,
        randomness: RandomnessBytes,
    ) -> AuthCredentialWithPniZkcPresentation {
        let Self {
            aci,
            credential,
            pni,
            redemption_time,
            version: _,
        } = self;

        let proof = zkcredential::presentation::PresentationProofBuilder::new(CREDENTIAL_LABEL)
            .add_attribute(aci, &group_secret_params.uid_enc_key_pair)
            .add_attribute(pni, &group_secret_params.uid_enc_key_pair)
            .present(public_key, credential, randomness);

        AuthCredentialWithPniZkcPresentation {
            aci_ciphertext: group_secret_params.uid_enc_key_pair.encrypt(&self.aci),
            pni_ciphertext: group_secret_params.uid_enc_key_pair.encrypt(&self.pni),
            proof,
            redemption_time: *redemption_time,
            version: VersionByte,
        }
    }
}

impl AuthCredentialWithPniZkcPresentation {
    pub fn verify(
        &self,
        params: &ServerSecretParams,
        group_public_params: &GroupPublicParams,
        redemption_time: Timestamp,
    ) -> Result<(), ZkGroupVerificationFailure> {
        self.verify_for_key(
            &params.generic_credential_key_pair,
            group_public_params,
            redemption_time,
        )
    }

    pub(crate) fn verify_for_key(
        &self,
        credential_key: &CredentialKeyPair,
        group_public_params: &GroupPublicParams,
        redemption_time: Timestamp,
    ) -> Result<(), ZkGroupVerificationFailure> {
        zkcredential::presentation::PresentationProofVerifier::new(CREDENTIAL_LABEL)
            .add_attribute(
                &self.aci_ciphertext,
                &group_public_params.uid_enc_public_key,
            )
            .add_attribute(
                &self.pni_ciphertext,
                &group_public_params.uid_enc_public_key,
            )
            .add_public_attribute(&redemption_time)
            .verify(credential_key, &self.proof)
            .map_err(|_| ZkGroupVerificationFailure)
    }

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

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

    pub fn redemption_time(&self) -> Timestamp {
        self.redemption_time
    }
}

#[cfg(test)]
mod test {
    use zkcredential::RANDOMNESS_LEN;

    use super::*;
    use crate::SECONDS_PER_DAY;

    #[test]
    fn issue_receive_present() {
        const ACI: Aci = Aci::from_uuid_bytes([b'a'; 16]);
        const PNI: Pni = Pni::from_uuid_bytes([b'p'; 16]);
        const REDEMPTION_TIME: Timestamp = Timestamp::from_epoch_seconds(12345 * SECONDS_PER_DAY);

        let credential_key = CredentialKeyPair::generate([1; RANDOMNESS_LEN]);
        let public_key = credential_key.public_key();
        let group_secret_params = GroupSecretParams::generate([2; RANDOMNESS_LEN]);

        let response = AuthCredentialWithPniZkcResponse::issue_credential_for_key(
            ACI,
            PNI,
            REDEMPTION_TIME,
            &credential_key,
            [3; RANDOMNESS_LEN],
        );

        let credential = response
            .receive_for_key(ACI, PNI, REDEMPTION_TIME, public_key)
            .expect("is valid");

        let presentation =
            credential.present_for_key(public_key, &group_secret_params, [4; RANDOMNESS_LEN]);

        presentation
            .verify_for_key(
                &credential_key,
                &group_secret_params.get_public_params(),
                REDEMPTION_TIME,
            )
            .expect("can verify")
    }
}