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
use ssi_claims_core::SignatureError;
use ssi_jwk::{Algorithm, JWK};
use std::borrow::Cow;

use crate::{CompactJWSString, Header};

/// JWS payload type.
///
/// Any type that can be serialized with a give JWS type.
pub trait JWSPayload {
    /// JWS type.
    ///
    /// Value of the `typ` field in the JWS header.
    fn typ(&self) -> Option<&str> {
        None
    }

    /// JWS cty header value.
    fn cty(&self) -> Option<&str> {
        None
    }

    fn payload_bytes(&self) -> Cow<[u8]>;

    /// Signs the payload and returns a compact JWS.
    #[allow(async_fn_in_trait)]
    async fn sign(&self, signer: &impl JWSSigner) -> Result<CompactJWSString, SignatureError> {
        signer.sign(self).await
    }
}

impl JWSPayload for [u8] {
    fn payload_bytes(&self) -> Cow<[u8]> {
        Cow::Borrowed(self)
    }
}

impl JWSPayload for Vec<u8> {
    fn payload_bytes(&self) -> Cow<[u8]> {
        Cow::Borrowed(self)
    }
}

impl JWSPayload for str {
    fn payload_bytes(&self) -> Cow<[u8]> {
        Cow::Borrowed(self.as_bytes())
    }
}

impl JWSPayload for String {
    fn payload_bytes(&self) -> Cow<[u8]> {
        Cow::Borrowed(self.as_bytes())
    }
}

pub struct JWSSignerInfo {
    pub key_id: Option<String>,
    pub algorithm: Algorithm,
}

/// JWS Signer.
///
/// Any type that can fetch a JWK using the `kid` parameter of a JWS JOSE
/// header and sign bytes.
pub trait JWSSigner {
    #[allow(async_fn_in_trait)]
    async fn fetch_info(&self) -> Result<JWSSignerInfo, SignatureError>;

    #[allow(async_fn_in_trait)]
    async fn sign_bytes(&self, signing_bytes: &[u8]) -> Result<Vec<u8>, SignatureError>;

    #[allow(async_fn_in_trait)]
    async fn sign(
        &self,
        payload: &(impl ?Sized + JWSPayload),
    ) -> Result<CompactJWSString, SignatureError> {
        let info = self.fetch_info().await?;
        let payload_bytes = payload.payload_bytes();

        let header = Header {
            algorithm: info.algorithm,
            key_id: info.key_id,
            content_type: payload.cty().map(ToOwned::to_owned),
            type_: payload.typ().map(ToOwned::to_owned),
            ..Default::default()
        };

        let signing_bytes = header.encode_signing_bytes(&payload_bytes);
        let signature = self.sign_bytes(&signing_bytes).await?;

        Ok(
            CompactJWSString::encode_from_signing_bytes_and_signature(signing_bytes, &signature)
                .unwrap(),
        )
    }
}

impl<'a, T: JWSSigner> JWSSigner for &'a T {
    async fn fetch_info(&self) -> Result<JWSSignerInfo, SignatureError> {
        T::fetch_info(*self).await
    }

    async fn sign_bytes(&self, signing_bytes: &[u8]) -> Result<Vec<u8>, SignatureError> {
        T::sign_bytes(*self, signing_bytes).await
    }

    async fn sign(
        &self,
        payload: &(impl ?Sized + JWSPayload),
    ) -> Result<CompactJWSString, SignatureError> {
        T::sign(*self, payload).await
    }
}

impl<'a, T: JWSSigner + Clone> JWSSigner for Cow<'a, T> {
    async fn fetch_info(&self) -> Result<JWSSignerInfo, SignatureError> {
        T::fetch_info(self.as_ref()).await
    }

    async fn sign_bytes(&self, signing_bytes: &[u8]) -> Result<Vec<u8>, SignatureError> {
        T::sign_bytes(self.as_ref(), signing_bytes).await
    }

    async fn sign(
        &self,
        payload: &(impl ?Sized + JWSPayload),
    ) -> Result<CompactJWSString, SignatureError> {
        T::sign(self.as_ref(), payload).await
    }
}

impl JWSSigner for JWK {
    async fn fetch_info(&self) -> Result<JWSSignerInfo, SignatureError> {
        Ok(JWSSignerInfo {
            key_id: self.key_id.clone(),
            algorithm: self
                .get_algorithm()
                .ok_or(SignatureError::MissingAlgorithm)?,
        })
    }

    async fn sign_bytes(&self, signing_bytes: &[u8]) -> Result<Vec<u8>, SignatureError> {
        let algorithm = self
            .get_algorithm()
            .ok_or(SignatureError::MissingAlgorithm)?;
        crate::sign_bytes(algorithm, signing_bytes, self).map_err(Into::into)
    }
}

pub struct JWKWithAlgorithm<'a> {
    pub jwk: &'a JWK,
    pub algorithm: Algorithm,
}

impl<'a> JWKWithAlgorithm<'a> {
    pub fn new(jwk: &'a JWK, algorithm: Algorithm) -> Self {
        Self { jwk, algorithm }
    }
}

impl<'a> JWSSigner for JWKWithAlgorithm<'a> {
    async fn fetch_info(&self) -> Result<JWSSignerInfo, SignatureError> {
        Ok(JWSSignerInfo {
            key_id: self.jwk.key_id.clone(),
            algorithm: self.algorithm,
        })
    }

    async fn sign_bytes(&self, signing_bytes: &[u8]) -> Result<Vec<u8>, SignatureError> {
        crate::sign_bytes(self.algorithm, signing_bytes, self.jwk).map_err(Into::into)
    }
}