Pass NATS credentials explicitly: async-nats ignores userinfo in the URL

async_nats::connect() silently drops user:pass embedded in NATS_URL,
so the server rejected every connection with an authorization violation.
Parse the URL and feed credentials through ConnectOptions instead.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-18 22:33:20 +02:00
parent b4dfe0c5ea
commit 46bdad1629
3 changed files with 14 additions and 1 deletions
Generated
+1
View File
@@ -368,6 +368,7 @@ dependencies = [
"tower-sessions",
"tracing",
"tracing-subscriber",
"url",
"uuid",
"wasm-bindgen",
"web-sys",
+2
View File
@@ -21,6 +21,7 @@ tower = { version = "0.5", optional = true }
tower-http = { version = "0.6", features = ["fs", "trace"], optional = true }
tower-sessions = { version = "0.14", optional = true }
async-nats = { version = "0.38", optional = true }
url = { version = "2", optional = true }
sqlx = { version = "0.8", default-features = false, features = [
"runtime-tokio",
"tls-rustls",
@@ -65,6 +66,7 @@ ssr = [
"dep:tower-http",
"dep:tower-sessions",
"dep:async-nats",
"dep:url",
"dep:sqlx",
"dep:openidconnect",
"dep:futures",
+11 -1
View File
@@ -32,7 +32,17 @@ async fn main() -> anyhow::Result<()> {
let nats_url =
std::env::var("NATS_URL").unwrap_or_else(|_| "nats://127.0.0.1:4222".to_string());
tracing::info!(%nats_url, "connecting to NATS");
let nats = async_nats::connect(&nats_url).await?;
// async-nats does not honor userinfo embedded in the URL, so pass any
// credentials explicitly via ConnectOptions.
let parsed = url::Url::parse(&nats_url)?;
let mut nats_opts = async_nats::ConnectOptions::new();
if !parsed.username().is_empty() {
nats_opts = nats_opts.user_and_password(
parsed.username().to_string(),
parsed.password().unwrap_or_default().to_string(),
);
}
let nats = nats_opts.connect(&nats_url).await?;
let database_url = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://cnats:cnats@127.0.0.1:5432/cnats".to_string());