|
| 1 | +use std::time::SystemTime; |
| 2 | + |
| 3 | +use aws_config::SdkConfig; |
| 4 | + |
| 5 | +use axum::{Extension, Json}; |
| 6 | +use base64::{Engine, engine::general_purpose::STANDARD as Base64}; |
| 7 | +use chrono::{DateTime, Utc}; |
| 8 | +use josekit::jwt::JwtPayload; |
| 9 | +use openssl::{ |
| 10 | + bn::BigNum, |
| 11 | + ec::{EcGroup, EcKey}, |
| 12 | + nid::Nid, |
| 13 | + pkey::PKey, |
| 14 | + sha::sha256, |
| 15 | +}; |
| 16 | +use redis::aio::ConnectionManager; |
| 17 | +use schemars::JsonSchema; |
| 18 | + |
| 19 | +use crate::{ |
| 20 | + apple, keys, kms_jws, |
| 21 | + nonces::NonceDb, |
| 22 | + utils::{BundleIdentifier, ErrorCode, GlobalConfig, Platform, RequestError}, |
| 23 | +}; |
| 24 | + |
| 25 | +#[derive(Debug, serde::Deserialize, serde::Serialize, JsonSchema)] |
| 26 | +pub struct Request { |
| 27 | + pub nonce: String, |
| 28 | + pub app_version: String, |
| 29 | + pub bundle_identifier: BundleIdentifier, |
| 30 | + pub apple_attestation: Option<String>, |
| 31 | + pub android_attestation: Option<Vec<String>>, |
| 32 | +} |
| 33 | + |
| 34 | +#[derive(Debug, serde::Deserialize, serde::Serialize, JsonSchema)] |
| 35 | +pub struct Response { |
| 36 | + pub integrity_token: String, |
| 37 | +} |
| 38 | + |
| 39 | +#[derive(Debug)] |
| 40 | +pub struct IntegrityTokenPayload { |
| 41 | + pub v: String, |
| 42 | + pub platform: Platform, |
| 43 | + pub app_version: String, |
| 44 | + pub aud: String, |
| 45 | + pub cnf: Vec<u8>, |
| 46 | + pub pass: bool, |
| 47 | + pub exp: DateTime<Utc>, |
| 48 | +} |
| 49 | + |
| 50 | +impl IntegrityTokenPayload { |
| 51 | + pub fn generate(&self) -> eyre::Result<JwtPayload> { |
| 52 | + if self.cnf.len() != 65 { |
| 53 | + return Err(eyre::eyre!("Invalid device public key")); |
| 54 | + } |
| 55 | + |
| 56 | + let cnf_ec_key = EcKey::from_public_key_affine_coordinates( |
| 57 | + &EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(), |
| 58 | + &BigNum::from_slice(&self.cnf[1..33]).unwrap(), |
| 59 | + &BigNum::from_slice(&self.cnf[33..65]).unwrap(), |
| 60 | + ) |
| 61 | + .map_err(|_| RequestError { |
| 62 | + code: ErrorCode::BadRequest, |
| 63 | + details: Some("Invalid device public key".to_string()), |
| 64 | + })?; |
| 65 | + |
| 66 | + let cnf_pkey = PKey::from_ec_key(cnf_ec_key).map_err(|_| RequestError { |
| 67 | + code: ErrorCode::BadRequest, |
| 68 | + details: Some("Invalid device public key".to_string()), |
| 69 | + })?; |
| 70 | + |
| 71 | + let cnf_key_id = Base64.encode(sha256(&self.cnf)); |
| 72 | + let cnf_jwk = keys::public_key_to_jwk(&cnf_pkey, Some(cnf_key_id))?; |
| 73 | + |
| 74 | + let mut cfn = josekit::Map::new(); |
| 75 | + cfn.insert("jwk".to_string(), josekit::Value::Object(cnf_jwk.into())); |
| 76 | + |
| 77 | + let mut payload = JwtPayload::new(); |
| 78 | + payload.set_issued_at(&SystemTime::now()); |
| 79 | + payload.set_issuer("attestation.worldcoin.org"); // TODO: what about attestation.worldcoin.dev? |
| 80 | + payload.set_expires_at(&self.exp.into()); |
| 81 | + payload.set_claim("v", Some(josekit::Value::String(self.v.clone())))?; |
| 82 | + payload.set_claim( |
| 83 | + "app_version", |
| 84 | + Some(josekit::Value::String(self.app_version.clone())), |
| 85 | + )?; |
| 86 | + payload.set_claim( |
| 87 | + "platform", |
| 88 | + Some(josekit::Value::String(self.platform.to_string())), |
| 89 | + )?; |
| 90 | + payload.set_claim("aud", Some(josekit::Value::String(self.aud.clone())))?; |
| 91 | + payload.set_claim("cnf", Some(josekit::Value::Object(cfn)))?; |
| 92 | + payload.set_claim("pass", Some(josekit::Value::Bool(self.pass)))?; |
| 93 | + |
| 94 | + Ok(payload) |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +pub async fn handler( |
| 99 | + Extension(global_config): Extension<GlobalConfig>, |
| 100 | + Extension(mut redis): Extension<ConnectionManager>, |
| 101 | + Extension(mut nonce_db): Extension<NonceDb>, |
| 102 | + Extension(aws_config): Extension<SdkConfig>, |
| 103 | + Json(request): Json<Request>, |
| 104 | +) -> Result<Json<Response>, RequestError> { |
| 105 | + let tracing_span = tracing::span!(tracing::Level::DEBUG, "a", endpoint = "/a"); |
| 106 | + let _enter = tracing_span.enter(); |
| 107 | + |
| 108 | + if !global_config |
| 109 | + .enabled_bundle_identifiers |
| 110 | + .contains(&request.bundle_identifier) |
| 111 | + { |
| 112 | + return Err(RequestError { |
| 113 | + code: ErrorCode::BadRequest, |
| 114 | + details: Some("This bundle identifier is currently unavailable.".to_string()), |
| 115 | + }); |
| 116 | + } |
| 117 | + |
| 118 | + let challenge = format!("n={},av={}", request.nonce, request.app_version); |
| 119 | + let platform = request.bundle_identifier.platform(); |
| 120 | + |
| 121 | + let device_public_key = match platform { |
| 122 | + Platform::AppleIOS => { |
| 123 | + let apple_attestation = request.apple_attestation.ok_or_else(|| RequestError { |
| 124 | + code: ErrorCode::BadRequest, |
| 125 | + details: Some("Apple attestation is required".to_string()), |
| 126 | + })?; |
| 127 | + |
| 128 | + validate_apple_attestation_and_get_device_public_key( |
| 129 | + &global_config.apple_root_ca_pem, |
| 130 | + &challenge, |
| 131 | + &request.bundle_identifier, |
| 132 | + apple_attestation, |
| 133 | + )? |
| 134 | + } |
| 135 | + Platform::Android => { |
| 136 | + return Err(RequestError { |
| 137 | + code: ErrorCode::BadRequest, |
| 138 | + details: Some("Android attestation is not supported on this endpoint.".to_string()), |
| 139 | + }); |
| 140 | + } |
| 141 | + }; |
| 142 | + |
| 143 | + let token_details = nonce_db.consume_nonce(&request.nonce).await.map_err(|e| { |
| 144 | + tracing::error!(error = ?e, "Error consuming token nonce"); |
| 145 | + RequestError { |
| 146 | + code: ErrorCode::InternalServerError, |
| 147 | + details: None, |
| 148 | + } |
| 149 | + })?; |
| 150 | + |
| 151 | + let integrity_token = generate_integrity_token( |
| 152 | + &mut redis, |
| 153 | + &aws_config, |
| 154 | + IntegrityTokenPayload { |
| 155 | + v: "1".to_string(), |
| 156 | + platform, |
| 157 | + app_version: request.app_version, |
| 158 | + aud: token_details.aud, |
| 159 | + cnf: device_public_key, |
| 160 | + pass: true, |
| 161 | + exp: token_details.exp, |
| 162 | + }, |
| 163 | + ) |
| 164 | + .await?; |
| 165 | + |
| 166 | + Ok(Json(Response { integrity_token })) |
| 167 | +} |
| 168 | + |
| 169 | +fn validate_apple_attestation_and_get_device_public_key( |
| 170 | + apple_root_ca_pem: &[u8], |
| 171 | + challenge: &str, |
| 172 | + bundle_identifier: &BundleIdentifier, |
| 173 | + apple_attestation: String, |
| 174 | +) -> Result<Vec<u8>, RequestError> { |
| 175 | + let app_id = bundle_identifier.apple_app_id().ok_or(RequestError { |
| 176 | + code: ErrorCode::BadRequest, |
| 177 | + details: Some("Invalid bundle identifier".to_string()), |
| 178 | + })?; |
| 179 | + |
| 180 | + let allowed_aaguid_vec = apple::AAGUID::allowed_for_bundle_identifier(bundle_identifier) |
| 181 | + .map_err(|_| RequestError { |
| 182 | + code: ErrorCode::BadRequest, |
| 183 | + details: Some("Invalid bundle identifier".to_string()), |
| 184 | + })?; |
| 185 | + |
| 186 | + let initial_attestation = apple::decode_and_validate_initial_attestation( |
| 187 | + apple_attestation, |
| 188 | + challenge, |
| 189 | + app_id, |
| 190 | + allowed_aaguid_vec.as_slice(), |
| 191 | + apple_root_ca_pem, |
| 192 | + ) |
| 193 | + .map_err(|e| RequestError { |
| 194 | + code: ErrorCode::BadRequest, |
| 195 | + details: Some(e.to_string()), |
| 196 | + })?; |
| 197 | + |
| 198 | + Ok(initial_attestation.key_public_key) |
| 199 | +} |
| 200 | + |
| 201 | +async fn generate_integrity_token( |
| 202 | + redis: &mut ConnectionManager, |
| 203 | + aws_config: &SdkConfig, |
| 204 | + integrity_token_payload: IntegrityTokenPayload, |
| 205 | +) -> Result<String, RequestError> { |
| 206 | + let integrity_token_payload = integrity_token_payload.generate().map_err(|e| { |
| 207 | + tracing::error!(error = ?e, "Error generating integrity token payload"); |
| 208 | + RequestError { |
| 209 | + code: ErrorCode::InternalServerError, |
| 210 | + details: None, |
| 211 | + } |
| 212 | + })?; |
| 213 | + |
| 214 | + let kms_key = keys::fetch_active_key(redis, aws_config) |
| 215 | + .await |
| 216 | + .map_err(|e| { |
| 217 | + tracing::error!(error = ?e, "Error fetching active key"); |
| 218 | + RequestError { |
| 219 | + code: ErrorCode::InternalServerError, |
| 220 | + details: None, |
| 221 | + } |
| 222 | + })?; |
| 223 | + |
| 224 | + let integrity_token = kms_jws::generate_output_token( |
| 225 | + aws_config, |
| 226 | + kms_key.key_definition.arn, |
| 227 | + integrity_token_payload, |
| 228 | + ) |
| 229 | + .await |
| 230 | + .map_err(|e| { |
| 231 | + tracing::error!(error = ?e, "Error generating output token"); |
| 232 | + RequestError { |
| 233 | + code: ErrorCode::InternalServerError, |
| 234 | + details: None, |
| 235 | + } |
| 236 | + })?; |
| 237 | + |
| 238 | + Ok(integrity_token) |
| 239 | +} |
0 commit comments