|
1 | 1 | use crate::app::AppState;
|
2 | 2 | use crate::email::Email;
|
3 | 3 | use crate::models::{ApiToken, User};
|
4 |
| -use crate::schema::api_tokens; |
| 4 | +use crate::schema::{api_tokens, crate_owners, crates, emails}; |
5 | 5 | use crate::util::errors::{AppResult, BoxedAppError, bad_request};
|
6 | 6 | use crate::util::token::HashedToken;
|
7 | 7 | use anyhow::{Context, anyhow};
|
8 | 8 | use axum::Json;
|
9 | 9 | use axum::body::Bytes;
|
10 | 10 | use base64::{Engine, engine::general_purpose};
|
| 11 | +use crates_io_database::models::OwnerKind; |
11 | 12 | use crates_io_database::schema::trustpub_tokens;
|
12 | 13 | use crates_io_github::GitHubPublicKey;
|
13 | 14 | use crates_io_trustpub::access_token::AccessToken;
|
14 | 15 | use diesel::prelude::*;
|
15 | 16 | use diesel_async::{AsyncPgConnection, RunQueryDsl};
|
| 17 | +use futures_util::TryStreamExt; |
16 | 18 | use http::HeaderMap;
|
17 | 19 | use p256::PublicKey;
|
18 | 20 | use p256::ecdsa::VerifyingKey;
|
19 | 21 | use p256::ecdsa::signature::Verifier;
|
20 | 22 | use serde_json as json;
|
| 23 | +use std::collections::HashMap; |
21 | 24 | use std::str::FromStr;
|
22 | 25 | use std::sync::LazyLock;
|
23 | 26 | use std::time::Duration;
|
@@ -138,19 +141,40 @@ async fn alert_revoke_token(
|
138 | 141 | if let Ok(token) = alert.token.parse::<AccessToken>() {
|
139 | 142 | let hashed_token = token.sha256();
|
140 | 143 |
|
141 |
| - // Check if the token exists in the database |
142 |
| - let deleted_count = diesel::delete(trustpub_tokens::table) |
| 144 | + // Query for token data before deleting to get crate_ids for notifications |
| 145 | + let token_data = trustpub_tokens::table |
| 146 | + .select(trustpub_tokens::crate_ids) |
| 147 | + .filter(trustpub_tokens::hashed_token.eq(hashed_token.as_slice())) |
| 148 | + .get_result::<Vec<Option<i32>>>(conn) |
| 149 | + .await |
| 150 | + .optional()?; |
| 151 | + |
| 152 | + let Some(crate_ids) = token_data else { |
| 153 | + debug!("Unknown Trusted Publishing token received (false positive)"); |
| 154 | + return Ok(GitHubSecretAlertFeedbackLabel::FalsePositive); |
| 155 | + }; |
| 156 | + |
| 157 | + // Delete the token |
| 158 | + diesel::delete(trustpub_tokens::table) |
143 | 159 | .filter(trustpub_tokens::hashed_token.eq(hashed_token.as_slice()))
|
144 | 160 | .execute(conn)
|
145 | 161 | .await?;
|
146 | 162 |
|
147 |
| - if deleted_count > 0 { |
148 | 163 | warn!("Active Trusted Publishing token received and revoked (true positive)");
|
149 |
| - return Ok(GitHubSecretAlertFeedbackLabel::TruePositive); |
150 |
| - } else { |
151 |
| - debug!("Unknown Trusted Publishing token received (false positive)"); |
152 |
| - return Ok(GitHubSecretAlertFeedbackLabel::FalsePositive); |
| 164 | + |
| 165 | + // Send notification emails to all affected crate owners |
| 166 | + let actual_crate_ids: Vec<i32> = crate_ids.into_iter().flatten().collect(); |
| 167 | + if let Err(error) = |
| 168 | + send_trustpub_notification_emails(&actual_crate_ids, alert, state, conn).await |
| 169 | + { |
| 170 | + warn!( |
| 171 | + ?actual_crate_ids, |
| 172 | + ?error, |
| 173 | + "Failed to send trusted publishing token exposure notifications" |
| 174 | + ); |
153 | 175 | }
|
| 176 | + |
| 177 | + return Ok(GitHubSecretAlertFeedbackLabel::TruePositive); |
154 | 178 | }
|
155 | 179 |
|
156 | 180 | // If not a Trusted Publishing token or not found, try as a regular API token
|
@@ -224,6 +248,76 @@ async fn send_notification_email(
|
224 | 248 | Ok(())
|
225 | 249 | }
|
226 | 250 |
|
| 251 | +async fn send_trustpub_notification_emails( |
| 252 | + crate_ids: &[i32], |
| 253 | + alert: &GitHubSecretAlert, |
| 254 | + state: &AppState, |
| 255 | + conn: &mut AsyncPgConnection, |
| 256 | +) -> anyhow::Result<()> { |
| 257 | + // Build a mapping from crate_id to crate_name directly from the query |
| 258 | + let crate_id_to_name: HashMap<i32, String> = crates::table |
| 259 | + .select((crates::id, crates::name)) |
| 260 | + .filter(crates::id.eq_any(crate_ids)) |
| 261 | + .load_stream::<(i32, String)>(conn) |
| 262 | + .await? |
| 263 | + .try_fold(HashMap::new(), |mut map, (id, name)| { |
| 264 | + map.insert(id, name); |
| 265 | + std::future::ready(Ok(map)) |
| 266 | + }) |
| 267 | + .await |
| 268 | + .context("Failed to query crate names")?; |
| 269 | + |
| 270 | + // Then, get all verified owner emails for these crates |
| 271 | + let owner_emails = crate_owners::table |
| 272 | + .filter(crate_owners::crate_id.eq_any(crate_ids)) |
| 273 | + .filter(crate_owners::owner_kind.eq(OwnerKind::User)) // OwnerKind::User |
| 274 | + .filter(crate_owners::deleted.eq(false)) |
| 275 | + .inner_join(emails::table.on(crate_owners::owner_id.eq(emails::user_id))) |
| 276 | + .filter(emails::verified.eq(true)) |
| 277 | + .select((crate_owners::crate_id, emails::email)) |
| 278 | + .order((emails::email, crate_owners::crate_id)) |
| 279 | + .load::<(i32, String)>(conn) |
| 280 | + .await |
| 281 | + .context("Failed to query crate owners")?; |
| 282 | + |
| 283 | + // Group by email address to send one notification per user |
| 284 | + let mut notifications: HashMap<String, Vec<String>> = HashMap::new(); |
| 285 | + |
| 286 | + for (crate_id, email) in owner_emails { |
| 287 | + if let Some(crate_name) = crate_id_to_name.get(&crate_id) { |
| 288 | + notifications |
| 289 | + .entry(email) |
| 290 | + .or_default() |
| 291 | + .push(crate_name.clone()); |
| 292 | + } |
| 293 | + } |
| 294 | + |
| 295 | + // Send notifications in sorted order by email for consistent testing |
| 296 | + let mut sorted_notifications: Vec<(String, Vec<String>)> = notifications.into_iter().collect(); |
| 297 | + sorted_notifications.sort_by(|a, b| a.0.cmp(&b.0)); |
| 298 | + |
| 299 | + for (email, mut crate_names) in sorted_notifications { |
| 300 | + crate_names.sort(); |
| 301 | + |
| 302 | + let email_template = TrustedPublishingTokenExposedEmail { |
| 303 | + domain: &state.config.domain_name, |
| 304 | + reporter: "GitHub", |
| 305 | + source: &alert.source, |
| 306 | + crate_names: &crate_names, |
| 307 | + url: &alert.url, |
| 308 | + }; |
| 309 | + |
| 310 | + if let Err(error) = state.emails.send(&email, email_template).await { |
| 311 | + warn!( |
| 312 | + %email, ?crate_names, ?error, |
| 313 | + "Failed to send trusted publishing token exposure notification" |
| 314 | + ); |
| 315 | + } |
| 316 | + } |
| 317 | + |
| 318 | + Ok(()) |
| 319 | +} |
| 320 | + |
227 | 321 | struct TokenExposedEmail<'a> {
|
228 | 322 | domain: &'a str,
|
229 | 323 | reporter: &'a str,
|
|
0 commit comments