Send crash reports to Slack automatically

This commit is contained in:
Conrad Irwin
2024-01-17 19:51:33 -07:00
parent cf5dc099fb
commit 680929081d
11 changed files with 324 additions and 74 deletions
+124 -3
View File
@@ -18,19 +18,28 @@ use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tower::ServiceBuilder;
use tracing::instrument;
use util::{async_maybe, http::AsyncBody, ResultExt};
pub fn routes(rpc_server: Arc<rpc::Server>, state: Arc<AppState>) -> Router<Body> {
Router::new()
let called_from_website = Router::new()
.route("/user", get(get_authenticated_user))
.route("/users/:id/access_tokens", post(create_access_token))
.route("/panic", post(trace_panic))
.route("/rpc_server_snapshot", get(get_rpc_server_snapshot))
.layer(
ServiceBuilder::new()
.layer(Extension(state))
.layer(Extension(state.clone()))
.layer(Extension(rpc_server))
.layer(middleware::from_fn(validate_api_token)),
)
);
let called_from_client = Router::new().route("/crash", post(trace_crash)).layer(
ServiceBuilder::new()
.layer(Extension(state))
.layer(middleware::from_fn(validate_client_secret)),
);
called_from_website.merge(called_from_client)
}
pub async fn validate_api_token<B>(req: Request<B>, next: Next<B>) -> impl IntoResponse {
@@ -64,6 +73,37 @@ pub async fn validate_api_token<B>(req: Request<B>, next: Next<B>) -> impl IntoR
Ok::<_, Error>(next.run(req).await)
}
pub async fn validate_client_secret<B>(req: Request<B>, next: Next<B>) -> impl IntoResponse {
let token = req
.headers()
.get(http::header::AUTHORIZATION)
.and_then(|header| header.to_str().ok())
.ok_or_else(|| {
Error::Http(
StatusCode::BAD_REQUEST,
"missing authorization header".to_string(),
)
})?
.strip_prefix("token ")
.ok_or_else(|| {
Error::Http(
StatusCode::BAD_REQUEST,
"invalid authorization header".to_string(),
)
})?;
let state = req.extensions().get::<Arc<AppState>>().unwrap();
if token != state.config.client_token {
Err(Error::Http(
StatusCode::UNAUTHORIZED,
"invalid client secret".to_string(),
))?
}
Ok::<_, Error>(next.run(req).await)
}
#[derive(Debug, Deserialize)]
struct AuthenticatedUserParams {
github_user_id: Option<i32>,
@@ -127,6 +167,87 @@ async fn trace_panic(panic: Json<Panic>) -> Result<()> {
Ok(())
}
/// IPSHeader is the first line of an .ips file (in JSON format)
/// https://developer.apple.com/documentation/xcode/interpreting-the-json-format-of-a-crash-report
#[derive(Debug, Serialize, Deserialize)]
struct IPSHeader {
timestamp: Option<String>,
name: Option<String>,
app_name: Option<String>,
app_version: Option<String>,
slice_uuid: Option<String>,
build_version: Option<String>,
platform: Option<i32>,
#[serde(rename = "bundleID")]
bundle_id: Option<String>,
share_with_app_devs: Option<i32>,
is_first_party: Option<i32>,
bug_type: Option<String>,
os_version: Option<String>,
roots_installed: Option<i32>,
incident_id: Option<String>,
}
#[instrument(skip(content, app))]
async fn trace_crash(content: String, Extension(app): Extension<Arc<AppState>>) -> Result<()> {
let Some(header) = content.split("\n").next() else {
return Err(Error::Http(
StatusCode::BAD_REQUEST,
"invalid .ips file".to_string(),
));
};
let header: IPSHeader = serde_json::from_slice(&header.as_bytes())?;
let text = content.as_str();
tracing::error!(app_version = %header.app_version.clone().unwrap_or_default(),
build_version = %header.build_version.unwrap_or_default(),
os_version = %header.os_version.unwrap_or_default(),
bundle_id = %header.bundle_id.clone().unwrap_or_default(),
text = %text,
"crash report");
async_maybe!({
let api_key = app.config.slack_api_key.clone()?;
let channel = app.config.slack_panic_channel.clone()?;
let mut body = form_data_builder::FormData::new(Vec::new());
body.write_field("content", text).log_err()?;
body.write_field("channels", channel.as_str()).log_err()?;
body.write_field(
"filename",
format!("zed-crash-{}.ips", header.incident_id.unwrap_or_default()).as_str(),
)
.log_err()?;
body.write_field(
"initial_comment",
format!(
"New crash in {} ({})",
header.bundle_id.unwrap_or_default(),
header.app_version.unwrap_or_default()
)
.as_str(),
)
.log_err()?;
let content_type = body.content_type_header();
let body = AsyncBody::from(body.finish().log_err()?);
let request = Request::post("https://slack.com/api/files.upload")
.header("Content-Type", content_type)
.header("Authorization", format!("Bearer {}", api_key))
.body(body)
.log_err()?;
let response = util::http::client().send(request).await.log_err()?;
if !response.status().is_success() {
tracing::error!(response = ?response, "failed to send crash report to slack");
}
Some(())
})
.await;
Ok(())
}
async fn get_rpc_server_snapshot(
Extension(rpc_server): Extension<Arc<rpc::Server>>,
) -> Result<ErasedJson> {
+3
View File
@@ -101,6 +101,9 @@ pub struct Config {
pub rust_log: Option<String>,
pub log_json: Option<bool>,
pub zed_environment: Arc<str>,
pub slack_api_key: Option<String>,
pub slack_panic_channel: Option<String>,
pub client_token: String,
}
impl Config {
+3
View File
@@ -465,6 +465,7 @@ impl TestServer {
database_url: "".into(),
database_max_connections: 0,
api_token: "".into(),
client_token: "".into(),
invite_link_prefix: "".into(),
live_kit_server: None,
live_kit_key: None,
@@ -472,6 +473,8 @@ impl TestServer {
rust_log: None,
log_json: None,
zed_environment: "test".into(),
slack_api_key: None,
slack_panic_channel: None,
},
})
}