Passing a literal (direct or coerced via .as_bytes() / .as_ref() / .as_str()) to EncodingKey::from_secret(), EncodingKey::from_base64_secret(), or their DecodingKey counterparts from the jsonwebtoken crate hardcodes the JWT signing key in source code. For HMAC algorithms the same secret signs and verifies, so a hardcoded DecodingKey lets attackers forge tokens. Every deployment shares the same key, rotation requires a code change, and the secret is visible to anyone who can read the repository (or its history) which includes past contributors and anyone who clones a leaked archive. Load the key from an environment variable, configuration file, or a secret store at runtime instead.
usejsonwebtoken::EncodingKey;fnvalid()-> Result<(),Box<dynstd::error::Error>>{// Loaded from the environment at runtime
letsecret=std::env::var("JWT_SECRET")?;let_=EncodingKey::from_secret(secret.as_bytes());// From a function call
fnget_secret()-> Vec<u8>{vec![]}let_=EncodingKey::from_secret(&get_secret());// Variable holding the bytes
letkey_bytes: &[u8]=&[1,2,3];let_=EncodingKey::from_secret(key_bytes);// .as_bytes() on a variable — not a literal so must not flag
letname=String::from("runtime");let_=EncodingKey::from_secret(name.as_bytes());Ok(())}
Seamless integrations. Try Datadog Code Security
Datadog Code Security
Try this rule and analyze your code with Datadog Code Security
How to use this rule
1
2
rulesets:- rust-security # Rules to enforce Rust security.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Security scans to your CI pipelines