Skip to main content

storekit/
verification_result.rs

1use serde::Deserialize;
2
3use crate::error::{StoreKitError, VerificationErrorPayload, VerificationFailure};
4use crate::private::decode_base64;
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7/// Carries metadata returned alongside `StoreKit.VerificationResult`.
8pub struct VerificationMetadata {
9    /// `StoreKit`-provided `jws_representation` value.
10    pub jws_representation: String,
11    /// Decoded JWS header bytes returned by `StoreKit`.
12    pub header_data: Vec<u8>,
13    /// Decoded JWS payload bytes returned by `StoreKit`.
14    pub payload_data: Vec<u8>,
15    /// Decoded JWS signature bytes returned by `StoreKit`.
16    pub signature_data: Vec<u8>,
17    /// Decoded signed-data bytes returned by `StoreKit`.
18    pub signed_data: Vec<u8>,
19    /// Signature timestamp reported by `StoreKit`.
20    pub signed_date: String,
21    /// Decoded device-verification bytes returned by `StoreKit`.
22    pub device_verification: Vec<u8>,
23    /// Device verification nonce reported by `StoreKit`.
24    pub device_verification_nonce: String,
25}
26
27impl VerificationMetadata {
28    /// Returns the compact JWS representation returned by `StoreKit`.
29    pub fn jws_representation(&self) -> &str {
30        &self.jws_representation
31    }
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35/// Wraps `StoreKit.VerificationResult`.
36pub enum VerificationResult<T> {
37    /// `StoreKit` verified the payload signature.
38    Verified {
39        /// Decoded payload returned by `StoreKit`.
40        payload: T,
41        /// Verification metadata returned by `StoreKit`.
42        metadata: VerificationMetadata,
43    },
44    /// `StoreKit` returned the payload but verification failed.
45    Unverified {
46        /// Decoded payload returned by `StoreKit`.
47        payload: T,
48        /// Verification metadata returned by `StoreKit`.
49        metadata: VerificationMetadata,
50        /// Verification failure returned by `StoreKit`.
51        failure: VerificationFailure,
52    },
53}
54
55impl<T> VerificationResult<T> {
56    /// Returns `true` when `StoreKit` verified the payload.
57    pub const fn is_verified(&self) -> bool {
58        matches!(self, Self::Verified { .. })
59    }
60
61    pub fn payload_value(&self) -> Result<&T, StoreKitError> {
62        match self {
63            Self::Verified { payload, .. } => Ok(payload),
64            Self::Unverified { failure, .. } => Err(StoreKitError::Verification(failure.clone())),
65        }
66    }
67
68    pub fn into_payload_value(self) -> Result<T, StoreKitError> {
69        match self {
70            Self::Verified { payload, .. } => Ok(payload),
71            Self::Unverified { failure, .. } => Err(StoreKitError::Verification(failure)),
72        }
73    }
74
75    /// Returns the decoded payload returned by `StoreKit`.
76    pub const fn unverified_payload(&self) -> &T {
77        match self {
78            Self::Verified { payload, .. } | Self::Unverified { payload, .. } => payload,
79        }
80    }
81
82    /// Consumes the wrapper and returns the decoded `StoreKit` payload.
83    pub fn into_unverified_payload(self) -> T {
84        match self {
85            Self::Verified { payload, .. } | Self::Unverified { payload, .. } => payload,
86        }
87    }
88
89    /// Returns the verification metadata returned by `StoreKit`.
90    pub const fn metadata(&self) -> &VerificationMetadata {
91        match self {
92            Self::Verified { metadata, .. } | Self::Unverified { metadata, .. } => metadata,
93        }
94    }
95
96    /// Returns the verification failure reported by `StoreKit`, if any.
97    pub const fn verification_failure(&self) -> Option<&VerificationFailure> {
98        match self {
99            Self::Verified { .. } => None,
100            Self::Unverified { failure, .. } => Some(failure),
101        }
102    }
103
104    /// Consumes the wrapper and returns the payload, metadata, and optional verification failure.
105    pub fn into_parts(self) -> (T, VerificationMetadata, Option<VerificationFailure>) {
106        match self {
107            Self::Verified { payload, metadata } => (payload, metadata, None),
108            Self::Unverified {
109                payload,
110                metadata,
111                failure,
112            } => (payload, metadata, Some(failure)),
113        }
114    }
115
116    /// Returns the compact JWS representation returned by `StoreKit`.
117    pub fn jws_representation(&self) -> &str {
118        self.metadata().jws_representation()
119    }
120}
121
122#[derive(Debug, Deserialize)]
123pub(crate) struct VerificationMetadataPayload {
124    #[serde(rename = "jwsRepresentation")]
125    jws_representation: String,
126    #[serde(rename = "headerDataBase64")]
127    header_data_base64: String,
128    #[serde(rename = "payloadDataBase64")]
129    payload_data_base64: String,
130    #[serde(rename = "signatureDataBase64")]
131    signature_data_base64: String,
132    #[serde(rename = "signedDataBase64")]
133    signed_data_base64: String,
134    #[serde(rename = "signedDate")]
135    signed_date: String,
136    #[serde(rename = "deviceVerificationBase64")]
137    device_verification_base64: String,
138    #[serde(rename = "deviceVerificationNonce")]
139    device_verification_nonce: String,
140}
141
142impl VerificationMetadataPayload {
143    fn into_metadata(self) -> Result<VerificationMetadata, StoreKitError> {
144        Ok(VerificationMetadata {
145            jws_representation: self.jws_representation,
146            header_data: decode_base64(&self.header_data_base64, "verification header data")?,
147            payload_data: decode_base64(&self.payload_data_base64, "verification payload data")?,
148            signature_data: decode_base64(
149                &self.signature_data_base64,
150                "verification signature data",
151            )?,
152            signed_data: decode_base64(&self.signed_data_base64, "verification signed data")?,
153            signed_date: self.signed_date,
154            device_verification: decode_base64(
155                &self.device_verification_base64,
156                "verification device data",
157            )?,
158            device_verification_nonce: self.device_verification_nonce,
159        })
160    }
161}
162
163#[derive(Debug, Deserialize)]
164pub(crate) struct VerificationResultPayload<T> {
165    kind: String,
166    payload: T,
167    metadata: VerificationMetadataPayload,
168    #[serde(rename = "verificationError")]
169    verification_error: Option<VerificationErrorPayload>,
170}
171
172impl<T> VerificationResultPayload<T> {
173    pub(crate) fn into_result<U, F>(
174        self,
175        map_payload: F,
176    ) -> Result<VerificationResult<U>, StoreKitError>
177    where
178        F: FnOnce(T) -> Result<U, StoreKitError>,
179    {
180        let payload = map_payload(self.payload)?;
181        let metadata = self.metadata.into_metadata()?;
182        match self.kind.as_str() {
183            "verified" => Ok(VerificationResult::Verified { payload, metadata }),
184            "unverified" => {
185                let failure = self
186                    .verification_error
187                    .map(VerificationFailure::from_payload)
188                    .ok_or_else(|| {
189                        StoreKitError::Unknown(
190                            "StoreKit returned an unverified result without a verification error"
191                                .to_owned(),
192                        )
193                    })?;
194                Ok(VerificationResult::Unverified {
195                    payload,
196                    metadata,
197                    failure,
198                })
199            }
200            other => Err(StoreKitError::Unknown(format!(
201                "StoreKit returned an unknown verification result kind '{other}'"
202            ))),
203        }
204    }
205}