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
use std::borrow::Cow;
use std::marker::PhantomData;

use generic_array::{ArrayLength, GenericArray};
use hmac::digest::{BlockInput, FixedOutput, Input, Reset};
use typenum::Unsigned;

use crate::algorithm::{self, Signature, Signer as AlgorithmSigner};
use crate::base64::{self, Base64Sized, Base64SizedEncoder, URLSafeBase64Encode};
use crate::key_derivation;
use crate::timed::TimestampSignerImpl;
use crate::traits::GetSigner;
use crate::{AsSigner, BadSignature, IntoTimestampSigner, Separator, Signer};

static DEFAULT_SALT: Cow<'static, str> = Cow::Borrowed("itsdangerous.Signer");

pub struct SignerBuilder<Digest, Algorithm, KeyDerivation> {
    secret_key: Cow<'static, str>,
    salt: Cow<'static, str>,
    separator: Separator,
    _phantom: PhantomData<(Digest, Algorithm, KeyDerivation)>,
}

/// Constructs a default signer builder, using the [`sha1`] digest, [`hmac`],
/// and the [`django concat`] key derivation.
///
/// [`django concat`]: crate::key_derivation::DjangoConcat
pub fn default_builder<S: Into<Cow<'static, str>>>(
    secret_key: S,
) -> SignerBuilder<sha1::Sha1, algorithm::HMACAlgorithm<sha1::Sha1>, key_derivation::DjangoConcat> {
    SignerBuilder::new(secret_key)
}

impl<Digest, Algorithm, KeyDerivation> SignerBuilder<Digest, Algorithm, KeyDerivation>
where
    Digest: Input + BlockInput + FixedOutput + Reset + Default + Clone,
    Digest::BlockSize: ArrayLength<u8> + Clone,
    Digest::OutputSize: ArrayLength<u8>,
    Algorithm: algorithm::SigningAlgorithm,
    Algorithm::OutputSize: ArrayLength<u8>,
    KeyDerivation: key_derivation::DeriveKey,
{
    /// Constructs a new signer builder with a given secret key.
    pub fn new<S: Into<Cow<'static, str>>>(secret_key: S) -> Self {
        Self {
            secret_key: secret_key.into(),
            salt: DEFAULT_SALT.clone(),
            separator: Default::default(),
            _phantom: PhantomData,
        }
    }

    /// Uses a specific salt with the signer. If no salt is defined, will
    /// default to `DEFAULT_SALT`.
    pub fn with_salt<S: Into<Cow<'static, str>>>(mut self, salt: S) -> Self {
        self.salt = salt.into();
        self
    }

    /// Uses a specific separator with the signer. If no separator is
    /// defined, will default to '.'
    pub fn with_separator(mut self, separator: Separator) -> Self {
        self.separator = separator;
        self
    }

    /// Builds a Signer using the configuration specified in this builder.
    pub fn build(
        self,
    ) -> SignerImpl<Algorithm, Digest::OutputSize, Base64SizedEncoder<Algorithm::OutputSize>> {
        let derived_key = KeyDerivation::derive_key::<Digest>(&self.secret_key, &self.salt);

        SignerImpl {
            derived_key,
            separator: self.separator,
            _phantom: PhantomData,
        }
    }
}

pub struct SignerImpl<Algorithm, DerivedKeySize, SignatureEncoder>
where
    DerivedKeySize: ArrayLength<u8>,
{
    derived_key: GenericArray<u8, DerivedKeySize>,
    pub(crate) separator: Separator,
    _phantom: PhantomData<(Algorithm, SignatureEncoder)>,
}

impl<Algorithm, DerivedKeySize, SignatureEncoder>
    SignerImpl<Algorithm, DerivedKeySize, SignatureEncoder>
where
    Algorithm: algorithm::SigningAlgorithm,
    DerivedKeySize: ArrayLength<u8>,
    SignatureEncoder: Base64Sized,
{
    /// Given a base64-encoded signature, attempt to decode it and convert it
    /// to a Signature.
    ///
    /// A signature is considered base64 encoded if it was encoded using
    /// `URLSafeBase64Encode::base64_encode`.
    #[inline(always)]
    fn decode_signature(
        &self,
        encoded_signature: &[u8],
    ) -> Result<Signature<Algorithm::OutputSize>, base64::DecodeError> {
        Ok(base64::decode(encoded_signature)?
            .into_exact_inner()?
            .into())
    }

    /// Given a signature, attempt to verify whether or not it is valid
    /// for the given `value`.
    #[inline(always)]
    fn verify_signature(
        &self,
        value: &[u8],
        expected_signature: Signature<Algorithm::OutputSize>,
    ) -> bool {
        let computed_signature = self.get_signature(value);
        expected_signature == computed_signature
    }
}

impl<Algorithm, DerivedKeySize, SignatureEncoder> Signer
    for SignerImpl<Algorithm, DerivedKeySize, SignatureEncoder>
where
    Algorithm: algorithm::SigningAlgorithm,
    DerivedKeySize: ArrayLength<u8>,
    SignatureEncoder: Base64Sized,
{
    fn signature_output_size(&self) -> usize {
        SignatureEncoder::OutputSize::USIZE
    }

    #[inline(always)]
    fn verify_encoded_signature(&self, value: &[u8], encoded_signature: &[u8]) -> bool {
        match self.decode_signature(encoded_signature) {
            Ok(sig) => self.verify_signature(value, sig),
            Err(_) => false,
        }
    }

    #[inline(always)]
    fn separator(&self) -> Separator {
        self.separator
    }

    #[inline(always)]
    fn sign<S: AsRef<str>>(&self, value: S) -> String {
        let value = value.as_ref();
        // Pre-allocate a string with the correct size (for maximum speeds.)
        // This (albeit a bit artisnal approach) is much faster than using `format!(...)`.
        let mut output =
            String::with_capacity(value.len() + 1 + SignatureEncoder::OutputSize::USIZE);

        output.push_str(value);
        output.push(self.separator.0);
        self.get_signature(value.as_bytes())
            .base64_encode_str(&mut output);

        output
    }

    #[inline(always)]
    fn unsign<'a>(&'a self, value: &'a str) -> Result<&'a str, BadSignature<'a>> {
        let (value, signature) = self.separator.split(&value)?;
        if self.verify_encoded_signature(value.as_bytes(), signature.as_bytes()) {
            Ok(value)
        } else {
            Err(BadSignature::SignatureMismatch { signature, value })
        }
    }
}

impl<Algorithm, DerivedKeySize, SignatureEncoder> GetSigner
    for SignerImpl<Algorithm, DerivedKeySize, SignatureEncoder>
where
    Algorithm: algorithm::SigningAlgorithm,
    DerivedKeySize: ArrayLength<u8>,
{
    type OutputSize = Algorithm::OutputSize;
    type Signer = Algorithm::Signer;

    /// Gets the signature for a given value.
    #[inline(always)]
    fn get_signer(&self) -> Self::Signer {
        Self::Signer::new(self.derived_key.as_slice())
    }
}

impl<Algorithm, DerivedKeySize, SignatureEncoder> IntoTimestampSigner
    for SignerImpl<Algorithm, DerivedKeySize, SignatureEncoder>
where
    Algorithm: algorithm::SigningAlgorithm,
    DerivedKeySize: ArrayLength<u8>,
    SignatureEncoder: Base64Sized,
{
    type TimestampSigner = TimestampSignerImpl<Self>;

    fn into_timestamp_signer(self) -> Self::TimestampSigner {
        TimestampSignerImpl::with_signer(self)
    }
}

impl<Algorithm, DerivedKeySize, SignatureEncoder> AsSigner
    for SignerImpl<Algorithm, DerivedKeySize, SignatureEncoder>
where
    Algorithm: algorithm::SigningAlgorithm,
    DerivedKeySize: ArrayLength<u8>,
    SignatureEncoder: Base64Sized,
{
    type Signer = Self;

    fn as_signer(&self) -> &Self::Signer {
        &self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Signer;

    #[test]
    fn test_signature_basic() {
        let signer = default_builder("hello").build();
        let signature = signer.sign("this is a test");
        // This is a compatibility test against python.
        assert_eq!(signature, "this is a test.hgGT0Zoara4L13FX3_xm-xmfa_0");
        assert_eq!(
            signer
                .unsign("this is a test.hgGT0Zoara4L13FX3_xm-xmfa_0")
                .unwrap(),
            "this is a test"
        );
    }

    #[test]
    fn test_non_default_separator() {
        let signer = default_builder("hello")
            .with_separator(Separator::new('!').unwrap())
            .build();
        let signature = signer.sign("this is a test");
        assert_eq!(signature, "this is a test!hgGT0Zoara4L13FX3_xm-xmfa_0");
    }

    #[test]
    fn test_default_separator() {
        assert!(!base64::in_alphabet(Separator::default().0));
    }

    #[test]
    fn test_separator_rejects_invalid_char() {
        assert!(Separator::new('a').is_err());
    }

    #[test]
    fn test_unsign_edge_cases() {
        let signer = default_builder("hello").build();

        assert!(signer.unsign("").is_err());
        assert!(signer.unsign("fish").is_err());
        assert!(signer.unsign(".").is_err());
        assert!(signer.unsign("w.").is_err());
        assert!(signer.unsign(".w").is_err());
    }
}

#[cfg(all(test, feature = "nightly"))]
mod bench {
    use super::*;
    use crate::Signer;

    extern crate test;
    use test::Bencher;

    #[bench]
    fn bench_unsign(bench: &mut Bencher) {
        let signer = default_builder("hello").build();
        bench.iter(|| signer.unsign("this is a test.hgGT0Zoara4L13FX3_xm-xmfa_0"))
    }

    #[bench]
    fn bench_sign(bench: &mut Bencher) {
        let signer = default_builder("hello").build();
        bench.iter(|| signer.sign("this is a test"))
    }
}