|
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::{BTreeMap, BTreeSet, HashMap}; |
21 | 24 | use std::str::FromStr;
|
22 | 25 | use std::sync::LazyLock;
|
23 | 26 | use std::time::Duration;
|
@@ -138,19 +141,31 @@ 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 | + // Delete the token and return crate_ids for notifications |
| 145 | + let crate_ids = diesel::delete(trustpub_tokens::table) |
143 | 146 | .filter(trustpub_tokens::hashed_token.eq(hashed_token.as_slice()))
|
144 |
| - .execute(conn) |
145 |
| - .await?; |
| 147 | + .returning(trustpub_tokens::crate_ids) |
| 148 | + .get_result::<Vec<Option<i32>>>(conn) |
| 149 | + .await |
| 150 | + .optional()?; |
146 | 151 |
|
147 |
| - if deleted_count > 0 { |
148 |
| - warn!("Active Trusted Publishing token received and revoked (true positive)"); |
149 |
| - return Ok(GitHubSecretAlertFeedbackLabel::TruePositive); |
150 |
| - } else { |
| 152 | + let Some(crate_ids) = crate_ids else { |
151 | 153 | debug!("Unknown Trusted Publishing token received (false positive)");
|
152 | 154 | return Ok(GitHubSecretAlertFeedbackLabel::FalsePositive);
|
| 155 | + }; |
| 156 | + |
| 157 | + warn!("Active Trusted Publishing token received and revoked (true positive)"); |
| 158 | + |
| 159 | + // Send notification emails to all affected crate owners |
| 160 | + let actual_crate_ids: Vec<i32> = crate_ids.into_iter().flatten().collect(); |
| 161 | + let result = send_trustpub_notification_emails(&actual_crate_ids, alert, state, conn).await; |
| 162 | + if let Err(error) = result { |
| 163 | + warn!( |
| 164 | + "Failed to send trusted publishing token exposure notifications for crates {actual_crate_ids:?}: {error}", |
| 165 | + ); |
153 | 166 | }
|
| 167 | + |
| 168 | + return Ok(GitHubSecretAlertFeedbackLabel::TruePositive); |
154 | 169 | }
|
155 | 170 |
|
156 | 171 | // If not a Trusted Publishing token or not found, try as a regular API token
|
@@ -224,6 +239,71 @@ async fn send_notification_email(
|
224 | 239 | Ok(())
|
225 | 240 | }
|
226 | 241 |
|
| 242 | +async fn send_trustpub_notification_emails( |
| 243 | + crate_ids: &[i32], |
| 244 | + alert: &GitHubSecretAlert, |
| 245 | + state: &AppState, |
| 246 | + conn: &mut AsyncPgConnection, |
| 247 | +) -> anyhow::Result<()> { |
| 248 | + // Build a mapping from crate_id to crate_name directly from the query |
| 249 | + let crate_id_to_name: HashMap<i32, String> = crates::table |
| 250 | + .select((crates::id, crates::name)) |
| 251 | + .filter(crates::id.eq_any(crate_ids)) |
| 252 | + .load_stream::<(i32, String)>(conn) |
| 253 | + .await? |
| 254 | + .try_fold(HashMap::new(), |mut map, (id, name)| { |
| 255 | + map.insert(id, name); |
| 256 | + std::future::ready(Ok(map)) |
| 257 | + }) |
| 258 | + .await |
| 259 | + .context("Failed to query crate names")?; |
| 260 | + |
| 261 | + // Then, get all verified owner emails for these crates |
| 262 | + let owner_emails = crate_owners::table |
| 263 | + .filter(crate_owners::crate_id.eq_any(crate_ids)) |
| 264 | + .filter(crate_owners::owner_kind.eq(OwnerKind::User)) // OwnerKind::User |
| 265 | + .filter(crate_owners::deleted.eq(false)) |
| 266 | + .inner_join(emails::table.on(crate_owners::owner_id.eq(emails::user_id))) |
| 267 | + .filter(emails::verified.eq(true)) |
| 268 | + .select((crate_owners::crate_id, emails::email)) |
| 269 | + .order((emails::email, crate_owners::crate_id)) |
| 270 | + .load::<(i32, String)>(conn) |
| 271 | + .await |
| 272 | + .context("Failed to query crate owners")?; |
| 273 | + |
| 274 | + // Group by email address to send one notification per user |
| 275 | + let mut notifications: BTreeMap<String, BTreeSet<String>> = BTreeMap::new(); |
| 276 | + |
| 277 | + for (crate_id, email) in owner_emails { |
| 278 | + if let Some(crate_name) = crate_id_to_name.get(&crate_id) { |
| 279 | + notifications |
| 280 | + .entry(email) |
| 281 | + .or_default() |
| 282 | + .insert(crate_name.clone()); |
| 283 | + } |
| 284 | + } |
| 285 | + |
| 286 | + // Send notifications in sorted order by email for consistent testing |
| 287 | + for (email, crate_names) in notifications { |
| 288 | + let email_template = TrustedPublishingTokenExposedEmail { |
| 289 | + domain: &state.config.domain_name, |
| 290 | + reporter: "GitHub", |
| 291 | + source: &alert.source, |
| 292 | + crate_names: &crate_names.iter().cloned().collect::<Vec<_>>(), |
| 293 | + url: &alert.url, |
| 294 | + }; |
| 295 | + |
| 296 | + if let Err(error) = state.emails.send(&email, email_template).await { |
| 297 | + warn!( |
| 298 | + %email, ?crate_names, ?error, |
| 299 | + "Failed to send trusted publishing token exposure notification" |
| 300 | + ); |
| 301 | + } |
| 302 | + } |
| 303 | + |
| 304 | + Ok(()) |
| 305 | +} |
| 306 | + |
227 | 307 | struct TokenExposedEmail<'a> {
|
228 | 308 | domain: &'a str,
|
229 | 309 | reporter: &'a str,
|
@@ -264,6 +344,64 @@ Source type: {source}",
|
264 | 344 | }
|
265 | 345 | }
|
266 | 346 |
|
| 347 | +struct TrustedPublishingTokenExposedEmail<'a> { |
| 348 | + domain: &'a str, |
| 349 | + reporter: &'a str, |
| 350 | + source: &'a str, |
| 351 | + crate_names: &'a [String], |
| 352 | + url: &'a str, |
| 353 | +} |
| 354 | + |
| 355 | +impl Email for TrustedPublishingTokenExposedEmail<'_> { |
| 356 | + fn subject(&self) -> String { |
| 357 | + "crates.io: Your Trusted Publishing token has been revoked".to_string() |
| 358 | + } |
| 359 | + |
| 360 | + fn body(&self) -> String { |
| 361 | + let authorization = if self.crate_names.len() == 1 { |
| 362 | + format!( |
| 363 | + "This token was only authorized to publish the \"{}\" crate.", |
| 364 | + self.crate_names[0] |
| 365 | + ) |
| 366 | + } else { |
| 367 | + format!( |
| 368 | + "This token was authorized to publish the following crates: \"{}\".", |
| 369 | + self.crate_names.join("\", \"") |
| 370 | + ) |
| 371 | + }; |
| 372 | + |
| 373 | + let mut body = format!( |
| 374 | + "{reporter} has notified us that one of your crates.io Trusted Publishing tokens \ |
| 375 | +has been exposed publicly. We have revoked this token as a precaution. |
| 376 | +
|
| 377 | +{authorization} |
| 378 | +
|
| 379 | +Please review your account at https://{domain} and your GitHub repository \ |
| 380 | +settings to confirm that no unexpected changes have been made to your crates \ |
| 381 | +or trusted publishing configurations. |
| 382 | +
|
| 383 | +Source type: {source}", |
| 384 | + domain = self.domain, |
| 385 | + reporter = self.reporter, |
| 386 | + source = self.source, |
| 387 | + ); |
| 388 | + |
| 389 | + if self.url.is_empty() { |
| 390 | + body.push_str("\n\nWe were not informed of the URL where the token was found."); |
| 391 | + } else { |
| 392 | + body.push_str(&format!("\n\nURL where the token was found: {}", self.url)); |
| 393 | + } |
| 394 | + |
| 395 | + body.push_str( |
| 396 | + "\n\nTrusted Publishing tokens are temporary and used for automated \ |
| 397 | +publishing from GitHub Actions. If this exposure was unexpected, please review \ |
| 398 | +your repository's workflow files and secrets.", |
| 399 | + ); |
| 400 | + |
| 401 | + body |
| 402 | + } |
| 403 | +} |
| 404 | + |
267 | 405 | #[derive(Deserialize, Serialize)]
|
268 | 406 | pub struct GitHubSecretAlertFeedback {
|
269 | 407 | pub token_raw: String,
|
|
0 commit comments