Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion docs/self-host/email.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ If CoderHelm's mail service can't be reached, the email fails and shows in **Del

- Your install sends a template id and its parameters, signed with its registration secret, never a subject or HTML. CoderHelm writes the email from its own templates.
- Mail comes from `notifications@notify.coderhelm.com` with your install's address as the name (`acme.coderhelm.com via CoderHelm`), and no Reply-To. The footer names your install and its admin.
- Every link in the email goes to your install's own verified address (its CloudFront address or its CoderHelm name). An install on its own custom domain should use its own SES for now.
- Every link in the email goes to your install's own verified address: its CloudFront address, its CoderHelm name, or its own domain once CoderHelm has reached your install over HTTPS on that name (DNS and certificate working). Your install asks for that by itself the first time it needs it, and the proof counts for a week at a time.
- It only sends to your install's people and pending invites, listed by an install admin, at most 50 new addresses a day, 30 emails a minute and 500 a day.
- An address that bounces or marks an email as spam gets nothing more. Too many bounces or complaints pause email for your install, and your install admins are told.

Expand Down
2 changes: 1 addition & 1 deletion docs/self-host/hybrid.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ What CoderHelm's mail service refuses, and how. Each line has a test (`services/
|---|---|
| Another install, or someone without the install's secret, sends as your install | Every request is signed with the install's own secret (derived per install on CoderHelm's side), checked within 5 minutes, with a request id that is refused the second time. Only a registered, verified, not revoked install can send; revoking stops it at the next request. |
| An email made to look like it comes from CoderHelm support or security | No subject, HTML, sender or Reply-To can be sent: only a template id and parameters. Subjects are fixed. Parameters are plain text, escaped, length-limited, and refused when they read as CoderHelm itself ("CoderHelm support", "CoderHelm security"). The sender name is built only from the install's verified address, and a name that reads as CoderHelm staff (`support`, `billing`, `c0derhe1m` and other look-alikes) falls back to the CloudFront address. Every email's footer names the install. |
| A phishing link | Link parameters must be `https://` links to the install's own verified address. Links, addresses and look-alike domains in text parameters are removed before the email is written. |
| A phishing link | Link parameters must be `https://` links to the install's own verified address (its CloudFront address, its CoderHelm name, or its own domain while CoderHelm's HTTPS proof on it is under a week old). Links, addresses and look-alike domains in text parameters are removed before the email is written. |
| Mail to people outside the install | Only listed addresses: the install's admins, people and pending invites. Only an install admin can list an invite, at most 50 new addresses a day. CoderHelm's own addresses are never a recipient. |
| Spam or a burst | 30 emails a minute and 500 a day per install. Bounced and complaining addresses get nothing more; too many bounces or complaints pause the install's email and its admins are told. |
| Spoofing CoderHelm's sending domain | Mail comes from its own subdomain, `notify.coderhelm.com`, with Easy DKIM, SPF for a custom MAIL FROM and DMARC `p=reject`, so it can't harm the main domain's reputation and can't be forged from it. |
Expand Down
3 changes: 2 additions & 1 deletion services/common/src/deliveries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,8 @@ const REASONS: &[Reason] = &[
Reason { code: "email_quota_reached", message: "The install reached today's email quota through CoderHelm.", fix: "Wait until tomorrow (UTC), or send through the install's own Amazon SES." },
Reason { code: "email_paused", message: "CoderHelm paused email for this install after too many bounces or complaints.", fix: "Check recent bounces in Deliveries, fix the addresses, then ask CoderHelm support to resume, or switch to Amazon SES." },
Reason { code: "install_not_verified", message: "CoderHelm sends an install's email only after it proves its address.", fix: "Finish verifying the install in Settings, System, Hybrid." },
Reason { code: "link_not_own_host", message: "A link in the email didn't point at this install's own address, so CoderHelm's relay refused it.", fix: "Use the install's CloudFront address or its CoderHelm name. A custom domain isn't known to the relay yet." },
Reason { code: "link_not_own_host", message: "A link in the email didn't point at this install's own address, so CoderHelm's relay refused it.", fix: "Links may go to the install's CloudFront address, its CoderHelm name, or its own domain once CoderHelm has reached the install over HTTPS on it (the install asks for that by itself; check the domain's DNS and certificate in Settings, System, Domain)." },
Reason { code: "domain_not_proved", message: "CoderHelm couldn't reach this install over HTTPS on its own domain, so emails through CoderHelm can't link there yet.", fix: "Check the domain's DNS records and certificate in Settings, System, Domain; the next email asks again." },
Reason { code: "param_reserved", message: "Part of the email read as CoderHelm itself (support, security, staff), so the relay refused it.", fix: "Rename what was quoted (a team, a ticket subject) so it reads as your install." },
Reason { code: "email_bounced", message: "The address doesn't exist or refuses mail.", fix: "Fix the address on the team page; CoderHelm's relay won't send to it again." },
Reason { code: "email_complained", message: "The recipient marked the email as spam.", fix: "Nothing more is sent to them through CoderHelm." },
Expand Down
18 changes: 18 additions & 0 deletions services/common/src/mail/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,24 @@ async fn send_relay(
.map(|_| ())
.map_err(|e| err(&e.code, e.message))
}
// A link to the install's own domain the relay hasn't proved yet:
// ask it to (it reaches the install over HTTPS on that name), then
// try once more.
Err(e) if e.code == "link_not_own_host" => {
let host =
crate::public_urls::host_of(crate::public_urls::app_url_from_env()).to_string();
if !relay::custom_domain_ok(&host) {
return Err(err(&e.code, e.message));
}
let body = serde_json::json!({ "hostname": host });
crate::hybrid::client::call(http, creds, "POST", relay::PATH_DOMAIN, Some(&body))
.await
.map_err(|e| err(&e.code, e.message))?;
call(req(relay::new_request_id()))
.await
.map(|_| ())
.map_err(|e| err(&e.code, e.message))
}
Err(e) => Err(err(&e.code, e.message)),
}
}
Expand Down
155 changes: 155 additions & 0 deletions services/common/src/mail/relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,61 @@ pub fn from_header(display: &str, address: &str) -> String {
format!("\"{d}\" <{address}>")
}

pub const PATH_DOMAIN: &str = "/hybrid/email/domain";
pub const DOMAIN_SK: &str = "EMAILDOMAIN";
/// How long a custom domain's proof counts. The install asks again (it does
/// whenever the relay refuses one of its links, and on its setup checks), so
/// a domain that stops answering stops counting within this.
pub const DOMAIN_PROOF_SECS: i64 = 7 * 86_400;

/// A custom domain an install asked the relay to link to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CustomDomain {
pub hostname: String,
/// When the relay last reached the install over HTTPS on it (epoch
/// seconds); `None` until it has.
pub verified_at: Option<i64>,
}

/// A hostname an install may ask the relay to link to: lowercase labels, a
/// real top-level domain, not an AWS address, not CoderHelm's own zone, not
/// an IP address.
pub fn custom_domain_ok(host: &str) -> bool {
let h = host.trim().trim_end_matches('.').to_ascii_lowercase();
if h.len() < 4 || h.len() > 253 || !h.contains('.') {
return false;
}
let labels_ok = h.split('.').all(|l| {
!l.is_empty()
&& l.len() <= 63
&& !l.starts_with('-')
&& !l.ends_with('-')
&& l.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
});
let tld = h.rsplit('.').next().unwrap_or("");
let tld_ok = tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_lowercase());
let not_ours = !(h == "coderhelm.com" || h.ends_with(".coderhelm.com"));
let not_aws = !(h.ends_with(".cloudfront.net") || h.ends_with(".amazonaws.com"));
labels_ok && tld_ok && not_ours && not_aws
}

/// The hosts a relayed email's links may point at: the install's verified
/// CloudFront address and CoderHelm name, plus its own domain only while
/// the relay's last HTTPS proof on it is recent.
pub fn link_hosts(base: &[String], domain: Option<&CustomDomain>, now: i64) -> Vec<String> {
let mut out = base.to_vec();
if let Some(d) = domain {
let fresh = d
.verified_at
.is_some_and(|at| at <= now && now - at <= DOMAIN_PROOF_SECS);
if fresh && custom_domain_ok(&d.hostname) {
out.push(d.hostname.trim_end_matches('.').to_ascii_lowercase());
}
}
out
}

/// A bounce or complaint, read from the SES event the topic delivers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MailEvent {
Expand Down Expand Up @@ -803,4 +858,104 @@ mod tests {
assert!(parse_event(&untagged).is_none());
assert!(!is_ses_event(&json!({"type": "ticket", "mail": {}})));
}

#[test]
fn a_custom_domain_counts_only_while_its_proof_is_recent() {
let base = vec!["d1.cloudfront.net".to_string()];
let now = 1_800_000_000;
let unverified = CustomDomain {
hostname: "helm.example.org".into(),
verified_at: None,
};
assert_eq!(link_hosts(&base, Some(&unverified), now), base);
let fresh = CustomDomain {
hostname: "Helm.Example.org.".into(),
verified_at: Some(now - 60),
};
assert_eq!(
link_hosts(&base, Some(&fresh), now),
vec!["d1.cloudfront.net", "helm.example.org"]
);
let stale = CustomDomain {
hostname: "helm.example.org".into(),
verified_at: Some(now - DOMAIN_PROOF_SECS - 1),
};
assert_eq!(link_hosts(&base, Some(&stale), now), base);
let future = CustomDomain {
hostname: "helm.example.org".into(),
verified_at: Some(now + 3600),
};
assert_eq!(link_hosts(&base, Some(&future), now), base);
assert_eq!(link_hosts(&base, None, now), base);
}

#[test]
fn only_a_real_domain_outside_aws_and_coderhelm_can_be_asked_for() {
assert!(custom_domain_ok("helm.example.org"));
assert!(custom_domain_ok("ci-2.helm.example.co.uk"));
for bad in [
"coderhelm.com",
"app.coderhelm.com",
"acme.coderhelm.com",
"d1.cloudfront.net",
"x.s3.amazonaws.com",
"10.0.0.1",
"localhost",
"-bad.example.org",
"a_b.example.org",
"helm.example.org/path",
"helm.example.org:8443",
"",
] {
assert!(!custom_domain_ok(bad), "{bad}");
}
}

#[test]
fn an_unverified_custom_domain_link_is_still_refused() {
use super::super::templates::{check, Refusal};
let base = vec!["d1.cloudfront.net".to_string()];
let now = 1_800_000_000;
let params = |link: &str| {
serde_json::json!({ "link": link })
.as_object()
.unwrap()
.clone()
};
let unverified = CustomDomain {
hostname: "helm.example.org".into(),
verified_at: None,
};
let hosts = link_hosts(&base, Some(&unverified), now);
assert_eq!(
check(
"welcome",
&params("https://helm.example.org/"),
&hosts,
true
)
.unwrap_err(),
Refusal::LinkNotOwnHost("link".into())
);
let verified = CustomDomain {
verified_at: Some(now),
..unverified
};
let hosts = link_hosts(&base, Some(&verified), now);
assert!(check(
"welcome",
&params("https://helm.example.org/"),
&hosts,
true
)
.is_ok());
// Another domain is still refused.
assert!(check(
"welcome",
&params("https://other.example.org/"),
&hosts,
true
)
.is_err());
}
}
1 change: 1 addition & 0 deletions services/gateway/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1239,6 +1239,7 @@ async fn main() -> Result<(), Error> {
// (routes::hybrid_email).
.route("/email", post(routes::hybrid_email::send))
.route("/email/recipients", post(routes::hybrid_email::recipients))
.route("/email/domain", post(routes::hybrid_email::domain))
.route("/email/status", get(routes::hybrid_email::status))
.route("/settings", put(routes::hybrid::settings))
.route(
Expand Down
124 changes: 116 additions & 8 deletions services/gateway/src/routes/hybrid_email.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,14 +266,18 @@ pub async fn send(
let req: relay::SendRequest =
serde_json::from_slice(&body).map_err(|_| refuse(relay::Refusal::BadRequest))?;
let fail_with = |code: &str| relay_delivery(&req.template, &req.to, Err(code));
let (template, values) =
match templates::check(&req.template, &req.params, &own_hosts(&install), true) {
Ok(v) => v,
Err(r) => {
record(&state, &install.id, &fail_with(r.code())).await;
return Err(fail(StatusCode::BAD_REQUEST, r.code(), &r.message()));
}
};
let hosts = relay::link_hosts(
&own_hosts(&install),
custom_domain(&state, &install.id).await?.as_ref(),
epoch(),
);
let (template, values) = match templates::check(&req.template, &req.params, &hosts, true) {
Ok(v) => v,
Err(r) => {
record(&state, &install.id, &fail_with(r.code())).await;
return Err(fail(StatusCode::BAD_REQUEST, r.code(), &r.message()));
}
};
first_use(&state, &install.id, &req.request_id).await?;
let hash = relay::recipient_hash(&install.id, &req.to);
let listing = relay::Listing {
Expand Down Expand Up @@ -584,6 +588,110 @@ async fn seal_admin(
Ok(base64::engine::general_purpose::STANDARD.encode(blob))
}

/// The install's own domain, as last asked for and proved.
async fn custom_domain(
state: &AppState,
install: &str,
) -> Result<Option<relay::CustomDomain>, (StatusCode, Json<Value>)> {
Ok(get(state, install, relay::DOMAIN_SK).await?.and_then(|i| {
let hostname = i.get("hostname")?.as_s().ok()?.clone();
let verified_at = i
.get("verified_at")
.and_then(|v| v.as_n().ok())
.and_then(|v| v.parse().ok());
Some(relay::CustomDomain {
hostname,
verified_at,
})
}))
}

/// Whether the install answers its own proof on `host` over HTTPS: the
/// name resolves to it and its certificate is valid. Never a redirect, at
/// most a small answer.
async fn proves_on(master: &str, install: &Install, host: &str) -> bool {
let challenge = common::hybrid::broker::new_handle("ch");
let url = format!("https://{host}/webhooks/relay/proof?challenge={challenge}");
let Ok(r) = hybrid_relay::install_client()
.get(&url)
.timeout(std::time::Duration::from_secs(6))
.send()
.await
else {
return false;
};
if !r.status().is_success() {
return false;
}
let v: Value = serde_json::from_slice(&hybrid_relay::read_capped(r).await).unwrap_or_default();
v["install_id"].as_str() == Some(install.id.as_str())
&& common::hybrid::sign::check_proof(
&common::hybrid::sign::install_secret(master, &install.id),
&challenge,
v["proof"].as_str().unwrap_or(""),
)
}

/// POST /hybrid/email/domain (signed) `{hostname}`: let relayed emails link
/// to the install's own domain. The relay proves it first, over HTTPS on
/// that name, the same proof as the CloudFront address; until then (and
/// once the proof is a week old) links there are refused.
pub async fn domain(
State(state): State<Arc<AppState>>,
method: Method,
uri: Uri,
headers: HeaderMap,
body: Bytes,
) -> Reply {
let (install, _) = verified(&state, &headers, &method, &uri, &body).await?;
let master = master(&state).ok_or_else(not_here)?.to_string();
crate::middleware::rate_limit::allow(&headers, "hybrid-email-domain", 20, 3600)
.map_err(|_| refuse(relay::Refusal::RateLimited))?;
let host = serde_json::from_slice::<Value>(&body).unwrap_or_default()["hostname"]
.as_str()
.unwrap_or("")
.trim()
.trim_end_matches('.')
.to_ascii_lowercase();
if !relay::custom_domain_ok(&host) {
return Err(fail(
StatusCode::BAD_REQUEST,
"bad_domain",
"Send the install's own domain, such as coderhelm.example.com.",
));
}
let ok = proves_on(&master, &install, &host).await;
let mut put = state
.dynamo
.put_item()
.table_name(&state.config.settings_table_name)
.item("pk", s(&hybrid_relay::install_pk(&install.id)))
.item("sk", s(relay::DOMAIN_SK))
.item("hostname", s(&host));
if ok {
put = put.item("verified_at", n(epoch()));
}
put.send().await.map_err(|e| {
warn!(error = %e, "email relay: domain write failed");
unavailable()
})?;
audit(
&state,
&install.id,
"email_domain",
json!({ "hostname": host, "verified": ok }),
)
.await;
if !ok {
return Err(fail(
StatusCode::BAD_REQUEST,
"domain_not_proved",
"CoderHelm couldn't reach this install over HTTPS on that domain. Check its DNS records and certificate in Settings, System, Domain.",
));
}
Ok(Json(json!({ "ok": true, "hostname": host })))
}

/// GET /hybrid/email/status (signed): what the install's Settings, Emails
/// and Setup checks show.
pub async fn status(
Expand Down
Loading