Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions src/bin/cratesfyi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,16 @@ fn main() {
.from_env_lossy(),
);

let _sentry_guard = if let Ok(sentry_dsn) = env::var("SENTRY_DSN") {
let ctx = BinContext::new();
let config = match ctx.config().context("could not load config") {
Ok(config) => config,
Err(err) => {
eprintln!("{:?}", err);
std::process::exit(1);
}
};

let _sentry_guard = if let Some(ref sentry_dsn) = config.sentry_dsn {
tracing::subscriber::set_global_default(tracing_registry.with(
sentry_tracing::layer().event_filter(|md| {
if md.fields().field("reported_to_sentry").is_some() {
Expand All @@ -58,10 +67,7 @@ fn main() {
sentry::ClientOptions {
release: Some(docs_rs::BUILD_VERSION.into()),
attach_stacktrace: true,
traces_sample_rate: env::var("SENTRY_TRACES_SAMPLE_RATE")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0.0),
traces_sample_rate: config.sentry_traces_sample_rate.unwrap_or(0.0),
..Default::default()
}
.add_integration(sentry_panic::PanicIntegration::default()),
Expand All @@ -71,7 +77,7 @@ fn main() {
None
};

if let Err(err) = CommandLine::parse().handle_args() {
if let Err(err) = CommandLine::parse().handle_args(ctx) {
let mut msg = format!("Error: {err}");
for cause in err.chain() {
write!(msg, "\n\nCaused by:\n {cause}").unwrap();
Expand Down Expand Up @@ -156,9 +162,7 @@ enum CommandLine {
}

impl CommandLine {
fn handle_args(self) -> Result<()> {
let ctx = BinContext::new();

fn handle_args(self, ctx: BinContext) -> Result<()> {
match self {
Self::Build { subcommand } => subcommand.handle_args(ctx)?,
Self::StartRegistryWatcher {
Expand Down
29 changes: 28 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::{cdn::CdnKind, storage::StorageKind};
use anyhow::{anyhow, bail, Context, Result};
use std::{env::VarError, error::Error, path::PathBuf, str::FromStr, time::Duration};
use serde::ser::{Serialize, SerializeStruct, Serializer};
use std::{env::VarError, error::Error, path::PathBuf, str::FromStr, sync::Arc, time::Duration};
use tracing::trace;
use url::Url;

Expand All @@ -11,6 +12,10 @@ pub struct Config {
pub registry_url: Option<String>,
pub registry_api_host: Url,

// sentry config
pub sentry_dsn: Option<sentry::types::Dsn>,
pub sentry_traces_sample_rate: Option<f32>,

// Database connection params
pub(crate) database_url: String,
pub(crate) max_legacy_pool_size: u32,
Expand Down Expand Up @@ -148,6 +153,9 @@ impl Config {
)?,
prefix: prefix.clone(),

sentry_dsn: maybe_env("SENTRY_DSN")?,
sentry_traces_sample_rate: maybe_env("SENTRY_TRACES_SAMPLE_RATE")?,

database_url: require_env("DOCSRS_DATABASE_URL")?,
max_legacy_pool_size: env("DOCSRS_MAX_LEGACY_POOL_SIZE", 45)?,
max_pool_size: env("DOCSRS_MAX_POOL_SIZE", 45)?,
Expand Down Expand Up @@ -224,6 +232,25 @@ impl Config {
}
}

/// A more public version of the config that will be automaticaly exposed to the
/// Tera context.
pub(crate) struct PublicConfig(pub Arc<Config>);

impl Serialize for PublicConfig {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("PublicConfig", 2)?;
state.serialize_field("sentry_dsn", &self.0.sentry_dsn)?;
state.serialize_field(
"sentry_traces_sample_rate",
&self.0.sentry_traces_sample_rate,
)?;
state.end()
}
}

fn env<T>(var: &str, default: T) -> Result<T>
where
T: FromStr,
Expand Down
12 changes: 9 additions & 3 deletions src/web/csp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl Csp {
result.push_str("; font-src 'self'");

// Allow XHR.
result.push_str("; connect-src 'self'");
result.push_str("; connect-src 'self' *.sentry.io");

// Only allow scripts with the random nonce attached to them.
//
Expand All @@ -83,6 +83,7 @@ impl Csp {
//
// This `.unwrap` is safe since the `Write` impl on str can never fail.
write!(result, "; script-src 'nonce-{}'", self.nonce).unwrap();
result.push_str(" https://browser.sentry-cdn.com https://js.sentry-cdn.com");
}

fn render_svg(&self, result: &mut String) {
Expand Down Expand Up @@ -192,8 +193,13 @@ mod tests {
let csp = Csp::new();
assert_eq!(
Some(format!(
"default-src 'none'; base-uri 'none'; img-src 'self' https:; \
style-src 'self'; font-src 'self'; connect-src 'self'; script-src 'nonce-{}'",
"default-src 'none'; \
base-uri 'none'; \
img-src 'self' https:; \
style-src 'self'; \
font-src 'self'; \
connect-src 'self' *.sentry.io; \
script-src 'nonce-{}' https://browser.sentry-cdn.com https://js.sentry-cdn.com",
csp.nonce()
)),
csp.render(ContentType::Html)
Expand Down
33 changes: 18 additions & 15 deletions src/web/page/web_page.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
use super::TemplateData;
use crate::web::{csp::Csp, error::AxumNope};
use crate::{
config::PublicConfig,
web::{csp::Csp, error::AxumNope},
Config,
};
use anyhow::Error;
use axum::{
body::Body,
extract::Request as AxumRequest,
middleware::Next,
response::{IntoResponse, Response as AxumResponse},
Extension,
};
use futures_util::future::{BoxFuture, FutureExt};
use http::header::CONTENT_LENGTH;
Expand Down Expand Up @@ -123,6 +128,7 @@ pub(crate) struct DelayedTemplateRender {
fn render_response(
mut response: AxumResponse,
templates: Arc<TemplateData>,
config: Arc<Config>,
csp_nonce: String,
) -> BoxFuture<'static, AxumResponse> {
async move {
Expand All @@ -133,6 +139,7 @@ fn render_response(
cpu_intensive_rendering,
} = render;
context.insert("csp_nonce", &csp_nonce);
context.insert("config", &PublicConfig(config.clone()));

let rendered = if cpu_intensive_rendering {
templates
Expand Down Expand Up @@ -160,6 +167,7 @@ fn render_response(
return render_response(
AxumNope::InternalError(err).into_response(),
templates,
config,
csp_nonce,
)
.await;
Expand All @@ -179,21 +187,16 @@ fn render_response(
.boxed()
}

pub(crate) async fn render_templates_middleware(req: AxumRequest, next: Next) -> AxumResponse {
let templates: Arc<TemplateData> = req
.extensions()
.get::<Arc<TemplateData>>()
.expect("template data request extension not found")
.clone();

let csp_nonce = req
.extensions()
.get::<Arc<Csp>>()
.expect("csp request extension not found")
.nonce()
.to_owned();
pub(crate) async fn render_templates_middleware(
Extension(config): Extension<Arc<Config>>,
Extension(templates): Extension<Arc<TemplateData>>,
Extension(csp): Extension<Arc<Csp>>,
req: AxumRequest,
next: Next,
) -> AxumResponse {
let csp_nonce = csp.nonce().to_owned();

let response = next.run(req).await;

render_response(response, templates, csp_nonce).await
render_response(response, templates, config, csp_nonce).await
}
23 changes: 22 additions & 1 deletion templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,27 @@

<title>{%- block title -%} Docs.rs {%- endblock title -%}</title>

{% if config.sentry_dsn %}
<script
src="https://browser.sentry-cdn.com/7.105.0/bundle.tracing.min.js"
integrity="sha384-XFfw9fN0ZxeLnveKcWT/zLOcibWw9ewRfNiUu/teAuMfP4G3Oy7lLh7rN3rX2T7M"
crossorigin="anonymous"
></script>

<script nonce="{{ csp_nonce }}">
Sentry.init({
dsn: "{{ config.sentry_dsn | safe }}",
release: "{{ docsrs_version() }}",
integrations: [
// potentially override transaction name later
// https://docs.sentry.io/platforms/javascript/performance/troubleshooting/
Sentry.browserTracingIntegration()
],
tracesSampleRate: {{ config.sentry_traces_sample_rate }},
});
</script>
{% endif %}

<script nonce="{{ csp_nonce }}">{%- include "theme.js" -%}</script>
{%- block css -%}{%- endblock css -%}

Expand All @@ -26,7 +47,7 @@

<body class="{% block body_classes %}{% endblock body_classes %}">
{%- block topbar -%}
{%- include "header/topbar.html" -%}
{%- include "header/topbar.html" -%}
{%- endblock topbar -%}

{%- block header %}{% endblock header -%}
Expand Down