volume(rs): refuse short JWT keys and skip Content-MD5 under fips.mode strict (#13206)

* volume(rs): refuse short JWT keys and skip Content-MD5 under fips.mode strict

Under fips.mode = strict the Rust volume server now does what the Go
volume server does under GODEBUG=fips140=only:

- At startup it exits when a JWT key in security.toml (any of the eleven
  jwt.signing* and jwt.filer_signing* settings Go checks) is shorter than
  the 14 characters FIPS 140 needs for HMAC keys, naming each one. Outside
  strict mode it warns about each such key but the previous ones.
- On SIGHUP, short current keys keep the keys in effect, and a short
  previous key is dropped, as in Go's Guard.UpdateSigningKeys.
- An upload's Content-MD5 is kept as the client sent it, unchecked, since
  strict mode computes no MD5.

The key rule and its messages live in seaweed-common's jwt_keys, so the
worker can use the same one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: run the fips140only cells in fips.mode strict, check strict refusals

The fips140only cells of the S3 digest matrix set WEED_FIPS_MODE=strict
beside GODEBUG=fips140=only, so the Rust volume server runs in the same
mode as the Go processes. A new job, test/s3/digest_matrix/negative_config.sh,
checks that master, filer and both volume servers refuse a 10-byte JWT key
at startup, that both volume servers keep a mismatched Content-MD5
unchecked, and that S3 answers a request signed with an 8-character secret
with an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: check the strict-mode Content-MD5 rule against both volume servers

TestWriteMD5MismatchKeptUncheckedUnderStrictFIPS starts the volume cluster
under GODEBUG=fips140=only and WEED_FIPS_MODE=strict and checks that an
upload with a mismatched Content-MD5 is stored with the client's value. It
sits in test/volume_server/http, so it runs against the Go volume server and,
with VOLUME_SERVER_IMPL=rust, against the Rust one. The same check leaves
negative_config.sh, which keeps the startup refusals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): say which keys the strict-mode checks cover and what they do

The doc comments of the startup check, the reload rule and the jwt_keys
helpers now say which keys they check and what happens in each mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): an empty WEED_ variable leaves the security.toml value in place

env_string returned an empty variable as a value, so WEED_JWT_SIGNING_KEY=
replaced the key from security.toml with an empty one: the volume server
then checked no JWTs, and under fips.mode strict a short file key was not
refused, while Go's volume server exits with the same files. Go's viper
ignores empty variables; env_string now does the same for every WEED_
override.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): read security.toml with the TOML parser

The line reader missed quoted key names, multiline strings, dotted keys,
inline tables and spaced or quoted table headers, all of which Go's viper
reads, so a short JWT key written that way escaped the strict-mode check
and was not used at all. Settings are now looked up in the parsed table,
case-insensitively as viper does. A file that is not valid TOML is still
read line by line, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): prefer the longest literal security.toml key, as viper does

Viper looks a dotted setting up longest name first, so a quoted
"jwt.filer_signing.key" key, at the top or under [jwt], wins over the
nested [jwt.filer_signing] key. The volume server read only the nested
one, so a short literal key passed the strict-mode check here while the
Go servers refused it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): resolve security.toml key case collisions as viper does

Viper lowercases every key of a config file, and when two spellings
collide (key and KEY, or [jwt] and [JWT]) the one that is not lowercase
wins. The volume server matched names case-insensitively but took the
exact spelling first, so a short KEY next to a compliant key passed the
strict-mode check here while the Go servers refused it. The parsed table
is now lowercased the same way before any lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): read an array or table security.toml setting as unset

Viper's GetString reads an array or a table as "", so the Go servers
skip a jwt key written as key = ["x"]. The volume server read its TOML
text instead, used it as the key and refused strict-mode startup over
it. fips.mode is still read as text: Go refuses a mode that is not a
string, and so does this server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): keep each lenient security.toml line under its full name

A security.toml that is not valid TOML is read line by line, and those
lines went into nested tables, so a later scalar such as signing = "x"
under [jwt] replaced the [jwt.signing] table and erased its key. The
line reader ignored such lines before, and a SIGHUP reload of that file
would have installed an empty write key. Each line now goes in under its
full dotted name, which the longest-name lookup finds first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): take the FIPS mode from the read that gives the JWT keys

Startup read security.toml once for the JWT keys and again for
fips.mode, so a file replaced between the two reads could pair the keys
of one version with the mode of the other and refuse to start over keys
that version never ran in strict mode with. The mode now comes from the
same parse as the keys; a file that exists but was not read is still an
error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): read a float security.toml setting as Go's GetString does

GetString formats a float with the shortest digits and no exponent, so
key = 1234567890123.0 is a 13-byte key to the Go servers. The volume
server kept the TOML spelling with its .0 and measured 15 bytes, which
passed the strict-mode check the Go servers refuse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): skip array-of-tables sections in a lenient security.toml

A file that is not valid TOML is read line by line, and lines under a
[[jwt.signing]] header went in under the same names as [jwt.signing],
so an empty key there replaced the real one, and a SIGHUP reload would
install it. The line reader now skips such sections up to the next
ordinary header, as the earlier reader did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-12-01 15:33:31 -08:00
1 parent 04bbf1ae0f
commit 0d3f81b771
12 files changed
+974 -165

No files matched your search

+37 -2
View File
@@ -4,8 +4,11 @@ name: "S3 digest and FIPS matrix"
# signing on, so the sha256 digest and GODEBUG=fips140=only stay working:
# md5 GODEBUG=fips140=off, the default digest
# sha256 GODEBUG=fips140=on with the filer's -digest=sha256
# fips140only GODEBUG=fips140=only, built with GOFIPS140=v1.0.0
# test/s3/digest_matrix/start_cluster.sh starts each cell's cluster.
# fips140only GODEBUG=fips140=only and WEED_FIPS_MODE=strict, built with
# GOFIPS140=v1.0.0
# test/s3/digest_matrix/start_cluster.sh starts each cell's cluster. The
# negative-config job checks what strict mode refuses at startup
# (test/s3/digest_matrix/negative_config.sh).
on:
push:
@@ -115,6 +118,38 @@ jobs:
retention-days: 1
path: digest-matrix-binaries.tar
negative-config:
name: Strict FIPS mode refusals
needs: build
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
with:
name: digest-matrix-binaries
- name: Restore binaries
run: |
tar xf digest-matrix-binaries.tar
chmod +x weed/weed seaweed-volume/target/release/weed-volume
- name: Short keys refused
env:
WEED: ${{ github.workspace }}/weed/weed
WEED_VOLUME: ${{ github.workspace }}/seaweed-volume/target/release/weed-volume
WORK_DIR: /tmp/negative-config
run: bash test/s3/digest_matrix/negative_config.sh
- name: Upload logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: negative-config-logs
path: /tmp/negative-config/**/*.log
retention-days: 3
suites:
name: S3 suites (${{ matrix.digest }}, ${{ matrix.volume }} volume server)
needs: build
+169
View File
@@ -0,0 +1,169 @@
//! JWT signing keys under [`FipsMode::Strict`].
//!
//! FIPS 140 needs HMAC keys of at least 112 bits, and Go's `crypto/hmac`
//! panics on a shorter one under `GODEBUG=fips140=only`, so every Go process
//! refuses to start when a JWT key in security.toml is shorter
//! (`weed/util/fips140_keys.go`). The Rust binaries take `fips.mode = strict`
//! to mean the same and apply the same rule with the same wording, so one
//! security.toml gets the same answer from a Go and a Rust server.
use crate::fips::FipsMode;
/// The shortest HMAC key FIPS 140 allows: 112 bits.
pub const MIN_HMAC_KEY_BYTES: usize = 14;
/// The wiki section on switching JWT signing keys without downtime.
pub const JWT_SIGNING_KEYS_WIKI: &str =
"https://github.com/seaweedfs/seaweedfs/wiki/Cryptography-and-FIPS-Compliance#jwt-signing-keys";
/// Every security.toml setting that keys an HS256 JWT, in the order Go checks
/// them. Go refuses a short one at startup in any process that reads the file.
pub const JWT_KEY_SETTINGS: [&str; 11] = [
"jwt.signing.key",
"jwt.signing.previous_key",
"jwt.signing.read.key",
"jwt.signing.read.previous_key",
"jwt.filer_signing.key",
"jwt.filer_signing.previous_key",
"jwt.filer_signing.read.key",
"jwt.filer_signing.read.previous_key",
"jwt.filer_signing.grpc_key",
"jwt.filer_signing.grpc_previous_key",
"jwt.filer_signing.subscribe.key",
];
/// Whether `key` is shorter than the FIPS mode allows (14 characters when
/// strict).
pub fn is_short(mode: FipsMode, key: &[u8]) -> bool {
mode == FipsMode::Strict && !key.is_empty() && key.len() < MIN_HMAC_KEY_BYTES
}
/// Go's `CheckFips140HmacKeys`: under strict mode, one message naming each
/// setting in `keys` whose key is too short, with its length; otherwise `None`.
pub fn short_keys(mode: FipsMode, keys: &[(&str, &[u8])]) -> Option<String> {
let short: Vec<String> = keys
.iter()
.filter(|(_, key)| is_short(mode, key))
.map(|(setting, key)| format!("{} ({} characters)", setting, key.len()))
.collect();
match short.as_slice() {
[] => None,
[one] => Some(format!(
"{} is shorter than the {} characters FIPS 140 needs for HMAC keys",
one, MIN_HMAC_KEY_BYTES
)),
[rest @ .., last] => Some(format!(
"{} and {} are shorter than the {} characters FIPS 140 needs for HMAC keys",
rest.join(", "),
last,
MIN_HMAC_KEY_BYTES
)),
}
}
/// The error a server logs before it exits at startup over the short keys in
/// `file`; `short` is the message from [`short_keys`].
pub fn startup_refusal(file: &str, short: &str) -> String {
format!(
"{}: this process runs with fips.mode strict, and stops because {}; replace them on every server that uses them, with or without downtime, see {}",
file, short, JWT_SIGNING_KEYS_WIKI
)
}
/// Go's `shortJwtKeyWarning`: a warning that the key (other than a previous
/// key) of `setting` in `file` is too short for strict mode, asking for a
/// longer one while the short one still works.
pub fn short_key_warning(mode: FipsMode, file: &str, setting: &str, key: &[u8]) -> Option<String> {
if mode == FipsMode::Strict
|| key.is_empty()
|| key.len() >= MIN_HMAC_KEY_BYTES
|| setting.ends_with("previous_key")
{
return None;
}
Some(format!(
"{}: this process does not run with fips.mode strict, so {} works, but under fips.mode strict this server would not start: the key is shorter than the {} characters FIPS 140 needs for HMAC keys (it has {}); to replace it on every server that uses it without downtime, see {}",
file,
setting,
MIN_HMAC_KEY_BYTES,
key.len(),
JWT_SIGNING_KEYS_WIKI
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_keys_only_under_strict() {
let keys: [(&str, &[u8]); 1] = [("jwt.signing.key", b"0123456789")];
assert_eq!(short_keys(FipsMode::On, &keys), None);
assert_eq!(short_keys(FipsMode::Off, &keys), None);
assert_eq!(
short_keys(FipsMode::Strict, &keys).as_deref(),
Some(
"jwt.signing.key (10 characters) is shorter than the 14 characters FIPS 140 needs for HMAC keys"
)
);
}
#[test]
fn short_keys_names_every_short_key_and_skips_unset_and_long_ones() {
let keys: [(&str, &[u8]); 4] = [
("jwt.signing.key", b"0123456789"),
("jwt.signing.read.key", b""),
("jwt.filer_signing.key", b"01234567890123"),
("jwt.filer_signing.subscribe.key", b"01234567"),
];
assert_eq!(
short_keys(FipsMode::Strict, &keys).as_deref(),
Some(
"jwt.signing.key (10 characters) and jwt.filer_signing.subscribe.key (8 characters) are shorter than the 14 characters FIPS 140 needs for HMAC keys"
)
);
let three: [(&str, &[u8]); 3] = [("a", b"1"), ("b", b"12"), ("c", b"123")];
assert_eq!(
short_keys(FipsMode::Strict, &three).as_deref(),
Some(
"a (1 characters), b (2 characters) and c (3 characters) are shorter than the 14 characters FIPS 140 needs for HMAC keys"
)
);
}
#[test]
fn warning_outside_strict_except_for_previous_keys() {
assert!(short_key_warning(FipsMode::Off, "s.toml", "jwt.signing.key", b"0123456789")
.unwrap()
.starts_with("s.toml: this process does not run with fips.mode strict, so jwt.signing.key works"));
assert!(
short_key_warning(FipsMode::On, "s.toml", "jwt.signing.key", b"0123456789").is_some()
);
assert_eq!(
short_key_warning(FipsMode::Strict, "s.toml", "jwt.signing.key", b"0123456789"),
None
);
assert_eq!(
short_key_warning(
FipsMode::Off,
"s.toml",
"jwt.signing.previous_key",
b"0123456789"
),
None
);
assert_eq!(
short_key_warning(
FipsMode::Off,
"s.toml",
"jwt.signing.key",
b"01234567890123"
),
None
);
assert_eq!(
short_key_warning(FipsMode::Off, "s.toml", "jwt.signing.key", b""),
None
);
}
}
+3 -1
View File
@@ -8,9 +8,11 @@
//! rustls provider, which only works if every binary installs the same one.
//! The security.toml search path joined them for the same reason: an operator
//! mounts the file once and every binary has to look where `weed` looks.
//! The FIPS mode joined them because it decides that provider.
//! The FIPS mode joined them because it decides that provider, and the JWT key
//! rule for strict mode because every binary that reads the keys applies it.
pub mod address;
pub mod fips;
pub mod jwt_keys;
pub mod security_config;
pub mod tls;
+459 -150
View File
@@ -31,8 +31,12 @@ fn parse_common_names(value: &str) -> Vec<String> {
.collect()
}
/// The value of the WEED_ variable `key`, or `None` when it is unset or empty:
/// Go's viper ignores an empty variable, so the setting keeps its file value.
fn env_string(env: EnvLookup<'_>, key: &str) -> Option<String> {
env(key).and_then(|value| value.into_string().ok())
env(key)
.and_then(|value| value.into_string().ok())
.filter(|value| !value.is_empty())
}
/// SeaweedFS Volume Server (Rust implementation)
@@ -337,6 +341,13 @@ pub struct VolumeServerConfig {
pub tls_policy: TlsPolicy,
/// Path to security.toml — stored for SIGHUP reload.
pub security_file: String,
/// The security.toml the settings came from, for messages that name it.
pub security_file_name: String,
/// Every JWT key setting, from `SecurityConfig::jwt_keys`, for the strict
/// mode check at startup.
pub jwt_keys: Vec<(&'static str, Vec<u8>)>,
/// The FIPS mode, from the same read of security.toml as `jwt_keys`.
pub fips_setting: Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError>,
/// If true, FetchAndWriteNeedle skips remote S3 endpoint validation
/// (allows loopback / link-local / metadata hosts).
pub allow_untrusted_remote_endpoints: bool,
@@ -974,6 +985,7 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
// Parse security config from TOML file
let sec = parse_security_config_with_env(&cli.security_file, env);
let fips_setting = resolve_fips_setting_with_env(&cli.security_file, &sec, env);
// Parse whitelist: merge CLI --whiteList with guard.white_list from security.toml
let mut white_list: Vec<String> = cli
@@ -1030,6 +1042,9 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
debug: cli.debug,
debug_port: cli.debug_port,
ui_enabled: sec.jwt_signing_key.is_empty() || sec.access_ui,
security_file_name: sec.file_name(),
jwt_keys: sec.jwt_keys(),
fips_setting,
jwt_signing_key: sec.jwt_signing_key,
jwt_signing_expires_seconds: sec.jwt_signing_expires,
jwt_previous_signing_key: sec.jwt_previous_signing_key,
@@ -1061,6 +1076,12 @@ fn default_volume_dir() -> String {
std::env::temp_dir().to_string_lossy().into_owned()
}
/// The WEED_ variable that overrides `setting`, as Go's viper names it:
/// `jwt.filer_signing.key` is `WEED_JWT_FILER_SIGNING_KEY`.
fn env_name(setting: &str) -> String {
format!("WEED_{}", setting.to_uppercase().replace('.', "_"))
}
/// Parsed security configuration from security.toml.
#[derive(Debug, Default)]
pub struct SecurityConfig {
@@ -1089,6 +1110,12 @@ pub struct SecurityConfig {
pub access_ui: bool,
/// The file was read; otherwise only defaults and WEED_ overrides are set.
pub file_read: bool,
/// The file the settings came from, for messages that name it.
pub file_used: Option<PathBuf>,
/// The `jwt.filer_signing*` keys, by setting. The volume server does not
/// use them; they are read so strict mode refuses a short one, as every Go
/// process that reads the same security.toml does.
pub filer_jwt_keys: Vec<(&'static str, Vec<u8>)>,
/// IPs from [guard] white_list in security.toml
pub guard_white_list: Vec<String>,
/// `[fips] mode` as the file sets it, read like every other key here;
@@ -1096,6 +1123,48 @@ pub struct SecurityConfig {
pub fips_mode: Option<String>,
}
impl SecurityConfig {
/// Sets the `jwt.filer_signing*` key `setting` to `value`, replacing an
/// earlier value as a later line or a WEED_ variable does in Go.
fn set_filer_jwt_key(&mut self, setting: &'static str, value: &str) {
self.filer_jwt_keys.retain(|(s, _)| *s != setting);
self.filer_jwt_keys
.push((setting, value.as_bytes().to_vec()));
}
/// Every JWT key setting the file and the WEED_ variables set, in the
/// order of `seaweed_common::jwt_keys::JWT_KEY_SETTINGS`; an unset key is
/// empty.
pub fn jwt_keys(&self) -> Vec<(&'static str, Vec<u8>)> {
seaweed_common::jwt_keys::JWT_KEY_SETTINGS
.iter()
.map(|&setting| {
let key = match setting {
"jwt.signing.key" => self.jwt_signing_key.clone(),
"jwt.signing.previous_key" => self.jwt_previous_signing_key.clone(),
"jwt.signing.read.key" => self.jwt_read_signing_key.clone(),
"jwt.signing.read.previous_key" => self.jwt_previous_read_signing_key.clone(),
_ => self
.filer_jwt_keys
.iter()
.find(|(s, _)| *s == setting)
.map(|(_, key)| key.clone())
.unwrap_or_default(),
};
(setting, key)
})
.collect()
}
/// The name messages give the file: its path, or "security.toml" when no
/// file was read, as Go does.
pub fn file_name(&self) -> String {
self.file_used
.as_ref()
.map_or_else(|| "security.toml".to_string(), |p| p.display().to_string())
}
}
/// Parse a security.toml file to extract JWT signing keys and TLS configuration.
/// Format:
/// ```toml
@@ -1154,129 +1223,62 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
}
};
let mut cfg = SecurityConfig::default();
let table = lowercase_keys(
content
.parse::<toml::Table>()
.unwrap_or_else(|_| lenient_toml_table(&content)),
);
let setting = |name: &str| toml_setting(&table, name);
let text = |name: &str| setting(name).unwrap_or_default();
let flag = |name: &str| text(name).parse().unwrap_or(false);
let expires =
|name: &str, default: i64| setting(name).map_or(0, |v| v.parse().unwrap_or(default));
#[derive(PartialEq)]
enum Section {
None,
JwtSigning,
JwtSigningRead,
HttpsClient,
Grpc,
HttpsVolume,
GrpcVolume,
Tls,
Guard,
Access,
Fips,
}
let mut section = Section::None;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('#') || trimmed.is_empty() {
continue;
}
if let Some(header) = section_header(trimmed) {
section = match header {
"[jwt.signing.read]" => Section::JwtSigningRead,
"[jwt.signing]" => Section::JwtSigning,
"[https.client]" => Section::HttpsClient,
"[grpc]" => Section::Grpc,
"[https.volume]" => Section::HttpsVolume,
"[grpc.volume]" => Section::GrpcVolume,
"[tls]" => Section::Tls,
"[guard]" => Section::Guard,
"[access]" => Section::Access,
"[fips]" => Section::Fips,
_ => Section::None,
};
continue;
}
if let Some((key, value)) = trimmed.split_once('=') {
let key = key.trim();
let value: &str = &toml_value_text(value);
match section {
Section::JwtSigningRead => match key {
"key" => cfg.jwt_read_signing_key = value.as_bytes().to_vec(),
"previous_key" => cfg.jwt_previous_read_signing_key = value.as_bytes().to_vec(),
"expires_after_seconds" => {
cfg.jwt_read_signing_expires = value.parse().unwrap_or(60)
}
_ => {}
},
Section::JwtSigning => match key {
"key" => cfg.jwt_signing_key = value.as_bytes().to_vec(),
"previous_key" => cfg.jwt_previous_signing_key = value.as_bytes().to_vec(),
"expires_after_seconds" => {
cfg.jwt_signing_expires = value.parse().unwrap_or(10)
}
_ => {}
},
Section::HttpsClient => match key {
"enabled" => cfg.https_client_enabled = value.parse().unwrap_or(false),
"cert" => cfg.https_client_cert_file = value.to_string(),
"key" => cfg.https_client_key_file = value.to_string(),
"ca" => cfg.https_client_ca_file = value.to_string(),
_ => {}
},
Section::Grpc => match key {
"ca" => cfg.grpc_ca_file = value.to_string(),
"allowed_wildcard_domain" => {
cfg.grpc_allowed_wildcard_domain = value.to_string()
}
"health_check_commonNames" => {
cfg.grpc_health_check_common_names = parse_common_names(value)
}
_ => {}
},
Section::HttpsVolume => match key {
"cert" => cfg.https_cert_file = value.to_string(),
"key" => cfg.https_key_file = value.to_string(),
"ca" => cfg.https_ca_file = value.to_string(),
_ => {}
},
Section::GrpcVolume => match key {
"cert" => cfg.grpc_cert_file = value.to_string(),
"key" => cfg.grpc_key_file = value.to_string(),
"client_cert" => cfg.grpc_client_cert_file = value.to_string(),
"client_key" => cfg.grpc_client_key_file = value.to_string(),
// Go only reads CA from [grpc], not [grpc.volume]
"allowed_commonNames" => {
cfg.grpc_volume_allowed_common_names =
value.split(',').map(|name| name.to_string()).collect();
}
_ => {}
},
Section::Tls => match key {
"min_version" => cfg.tls_policy.min_version = value.to_string(),
"max_version" => cfg.tls_policy.max_version = value.to_string(),
"cipher_suites" => cfg.tls_policy.cipher_suites = value.to_string(),
_ => {}
},
Section::Guard => {
if key == "white_list" {
cfg.guard_white_list = value
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
}
}
Section::Access => {
if key == "ui" {
cfg.access_ui = value.parse().unwrap_or(false)
}
}
Section::Fips => {
if key == "mode" {
cfg.fips_mode = Some(value.to_string())
}
}
Section::None => {}
}
let mut cfg = SecurityConfig {
jwt_signing_key: text("jwt.signing.key").into_bytes(),
jwt_previous_signing_key: text("jwt.signing.previous_key").into_bytes(),
jwt_signing_expires: expires("jwt.signing.expires_after_seconds", 10),
jwt_read_signing_key: text("jwt.signing.read.key").into_bytes(),
jwt_previous_read_signing_key: text("jwt.signing.read.previous_key").into_bytes(),
jwt_read_signing_expires: expires("jwt.signing.read.expires_after_seconds", 60),
https_client_enabled: flag("https.client.enabled"),
https_client_cert_file: text("https.client.cert"),
https_client_key_file: text("https.client.key"),
https_client_ca_file: text("https.client.ca"),
grpc_ca_file: text("grpc.ca"),
grpc_allowed_wildcard_domain: text("grpc.allowed_wildcard_domain"),
grpc_health_check_common_names: parse_common_names(&text("grpc.health_check_commonNames")),
https_cert_file: text("https.volume.cert"),
https_key_file: text("https.volume.key"),
https_ca_file: text("https.volume.ca"),
grpc_cert_file: text("grpc.volume.cert"),
grpc_key_file: text("grpc.volume.key"),
grpc_client_cert_file: text("grpc.volume.client_cert"),
grpc_client_key_file: text("grpc.volume.client_key"),
// Go only reads CA from [grpc], not [grpc.volume]
grpc_volume_allowed_common_names: setting("grpc.volume.allowed_commonNames")
.map(|names| names.split(',').map(String::from).collect())
.unwrap_or_default(),
tls_policy: TlsPolicy {
min_version: text("tls.min_version"),
max_version: text("tls.max_version"),
cipher_suites: text("tls.cipher_suites"),
},
guard_white_list: text("guard.white_list")
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect(),
access_ui: flag("access.ui"),
fips_mode: toml_entry(&table, &["fips", "mode"]).map(toml_text),
..SecurityConfig::default()
};
for name in seaweed_common::jwt_keys::JWT_KEY_SETTINGS
.iter()
.filter(|name| name.starts_with("jwt.filer_signing"))
{
if let Some(key) = setting(name) {
cfg.set_filer_jwt_key(name, &key);
}
}
@@ -1294,6 +1296,7 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
// e.g. WEED_JWT_SIGNING_KEY overrides [jwt.signing] key
apply_env_overrides(&mut cfg, env);
cfg.file_read = true;
cfg.file_used = Some(config_path);
cfg
}
@@ -1312,6 +1315,95 @@ fn section_header(trimmed: &str) -> Option<&str> {
Some(header.trim_end())
}
/// The value of the dotted `setting` in `table`, a table from
/// `lowercase_keys`, as Go's viper GetString reads it: a value that is not a
/// string reads as its TOML text, and an array or a table as unset.
fn toml_setting(table: &toml::Table, setting: &str) -> Option<String> {
let setting = setting.to_lowercase();
let path: Vec<&str> = setting.split('.').collect();
match toml_entry(table, &path)? {
toml::Value::Array(_) | toml::Value::Table(_) => None,
value => Some(toml_text(value)),
}
}
fn toml_text(value: &toml::Value) -> String {
match value {
toml::Value::String(text) => text.clone(),
toml::Value::Float(number) => number.to_string(),
other => other.to_string(),
}
}
/// The value at `path` in `table`. As in viper, the longest run of leading
/// parts that is itself a key wins (`"jwt.signing.key" = ...` over
/// `[jwt.signing] key`), and a shorter run is tried when the rest of the path
/// is not under it.
fn toml_entry<'a>(table: &'a toml::Table, path: &[&str]) -> Option<&'a toml::Value> {
(1..=path.len()).rev().find_map(|n| {
let value = table.get(&path[..n].join("."))?;
match (&path[n..], value) {
([], value) => Some(value),
(rest, toml::Value::Table(next)) => toml_entry(next, rest),
_ => None,
}
})
}
/// `table` with every key lowercased, as viper holds a config file. When two
/// spellings of a key collide, the one that is not lowercase wins, as it does
/// in viper.
fn lowercase_keys(table: toml::Table) -> toml::Table {
let mut lowered = toml::Table::new();
for (key, value) in table {
let value = match value {
toml::Value::Table(nested) => toml::Value::Table(lowercase_keys(nested)),
other => other,
};
let lower = key.to_lowercase();
if key != lower || !lowered.contains_key(&lower) {
lowered.insert(lower, value);
}
}
lowered
}
/// The `key = value` lines of a file that is not valid TOML, each under its
/// full dotted name (`jwt.signing.key`), so no line can replace the table
/// another line's value is in. Go's viper skips such a file; this server keeps
/// reading what it can from it, one line at a time.
fn lenient_toml_table(content: &str) -> toml::Table {
let mut table = toml::Table::new();
let mut section = String::new();
let mut in_array_of_tables = false;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('#') || trimmed.is_empty() {
continue;
}
if let Some(header) = section_header(trimmed) {
in_array_of_tables = header.starts_with("[[");
section = header
.trim_start_matches('[')
.trim_end_matches(']')
.split('.')
.map(|part| format!("{}.", part.trim()))
.collect();
continue;
}
if in_array_of_tables {
continue;
}
if let Some((key, value)) = trimmed.split_once('=') {
table.insert(
format!("{section}{}", key.trim()),
toml::Value::String(toml_value_text(value)),
);
}
}
table
}
/// Reads the right-hand side of `key = value` the way TOML (and so Go) does:
/// escapes decoded, literal strings kept as written, a trailing comment
/// dropped. Text TOML rejects keeps the plain quote trimming.
@@ -1327,31 +1419,22 @@ fn toml_value_text(raw: &str) -> String {
}
/// The FIPS mode this volume server runs in: `WEED_FIPS_MODE`, else
/// `fips.mode` in the security.toml `--securityFile` names or the search
/// finds, read by the same loader as the JWT keys, else off. A file that
/// exists but cannot be read is an error, since it may set the mode.
pub fn resolve_fips_setting(
security_file: &str,
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
resolve_fips_setting_with_env(security_file, &process_env)
}
/// `fips.mode` in `parsed`, the security.toml `--securityFile` names or the
/// search finds, else off. A file that exists but was not read is an error,
/// since it may set the mode.
fn resolve_fips_setting_with_env(
security_file: &str,
parsed: &SecurityConfig,
env: EnvLookup<'_>,
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
let path = resolve_security_config_path(security_file, env).filter(|p| p.exists());
let path = parsed
.file_used
.clone()
.or_else(|| resolve_security_config_path(security_file, env).filter(|p| p.exists()));
let Some(path) = path else {
return seaweed_common::fips::resolve(None, None, env);
};
if let Err(e) = std::fs::read_to_string(&path) {
return Err(seaweed_common::fips::FipsModeError::File {
path,
reason: e.to_string(),
});
}
let parsed = parse_security_config_with_env(&path.to_string_lossy(), env);
fips_setting_from_parsed(path, &parsed, env)
fips_setting_from_parsed(path, parsed, env)
}
/// The FIPS mode `parsed`, the security.toml at `path`, sets with `env`
@@ -1386,6 +1469,13 @@ fn resolve_security_config_path(path: &str, env: EnvLookup<'_>) -> Option<PathBu
/// Apply WEED_ environment variable overrides to a SecurityConfig.
/// Matches Go's Viper convention: WEED_ prefix, uppercase, dots replaced with underscores.
fn apply_env_overrides(cfg: &mut SecurityConfig, env: EnvLookup<'_>) {
for setting in seaweed_common::jwt_keys::JWT_KEY_SETTINGS {
if setting.starts_with("jwt.filer_signing") {
if let Some(v) = env_string(env, &env_name(setting)) {
cfg.set_filer_jwt_key(setting, &v);
}
}
}
if let Some(v) = env_string(env, "WEED_JWT_SIGNING_KEY") {
cfg.jwt_signing_key = v.into_bytes();
}
@@ -2004,6 +2094,58 @@ mod tests {
}
}
#[test]
fn test_jwt_keys_include_the_filer_keys_and_their_env_overrides() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(
tmp.path(),
r#"
[jwt.signing]
key = "volume-write"
previous_key = "volume-write-old"
[jwt.signing.read]
key = "volume-read"
[jwt.filer_signing]
key = "filer-write"
grpc_key = "filer-grpc"
[jwt.filer_signing.read]
previous_key = "filer-read-old"
[jwt.filer_signing.subscribe]
key = "filer-subscribe"
"#,
)
.unwrap();
let path = tmp.path().to_str().unwrap();
let env = fake_env(&[("WEED_JWT_FILER_SIGNING_KEY", "filer-write-env")]);
let cfg = parse_security_config_with_env(path, &env);
let keys: Vec<(&str, String)> = cfg
.jwt_keys()
.into_iter()
.map(|(setting, key)| (setting, String::from_utf8(key).unwrap()))
.collect();
let want = [
("jwt.signing.key", "volume-write"),
("jwt.signing.previous_key", "volume-write-old"),
("jwt.signing.read.key", "volume-read"),
("jwt.signing.read.previous_key", ""),
("jwt.filer_signing.key", "filer-write-env"),
("jwt.filer_signing.previous_key", ""),
("jwt.filer_signing.read.key", ""),
("jwt.filer_signing.read.previous_key", "filer-read-old"),
("jwt.filer_signing.grpc_key", "filer-grpc"),
("jwt.filer_signing.grpc_previous_key", ""),
("jwt.filer_signing.subscribe.key", "filer-subscribe"),
];
let want: Vec<(&str, String)> = want.iter().map(|(s, k)| (*s, k.to_string())).collect();
assert_eq!(keys, want);
assert_eq!(cfg.file_name(), path);
assert_eq!(SecurityConfig::default().file_name(), "security.toml");
}
#[test]
fn test_parse_security_config_access_ui() {
let tmp = tempfile::NamedTempFile::new().unwrap();
@@ -2323,6 +2465,39 @@ cipher_suites = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
assert_eq!(cfg.jwt_signing_key, b"env-secret");
}
#[test]
fn test_empty_env_override_keeps_the_file_value() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(
tmp.path(),
r#"
[jwt.signing]
key = "file-write"
[jwt.filer_signing]
key = "file-filer"
[grpc]
ca = "/file/ca.pem"
"#,
)
.unwrap();
let env = fake_env(&[
("WEED_JWT_SIGNING_KEY", ""),
("WEED_JWT_FILER_SIGNING_KEY", ""),
("WEED_GRPC_CA", ""),
]);
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &env);
assert_eq!(cfg.jwt_signing_key, b"file-write");
assert_eq!(cfg.grpc_ca_file, "/file/ca.pem");
let filer_key = cfg
.jwt_keys()
.into_iter()
.find(|(setting, _)| *setting == "jwt.filer_signing.key")
.map(|(_, key)| key);
assert_eq!(filer_key.as_deref(), Some(&b"file-filer"[..]));
}
#[test]
fn test_previous_signing_keys_from_file_and_env() {
let tmp = tempfile::NamedTempFile::new().unwrap();
@@ -2374,16 +2549,16 @@ previous_key = "read-old"
std::fs::write(tmp.path(), "[fips]\nmode = \"on\"\n").unwrap();
let path = tmp.path().to_str().unwrap();
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::On);
let env = fake_env(&[("WEED_FIPS_MODE", "strict")]);
let setting = resolve_fips_setting_with_env(path, &env).unwrap();
let setting = fips_setting_of(path, &env).unwrap();
assert_eq!(setting.mode, FipsMode::Strict);
let env = fake_env(&[("WEED_FIPS_MODE", "only")]);
assert!(resolve_fips_setting_with_env(path, &env).is_err());
assert!(fips_setting_of(path, &env).is_err());
std::fs::write(tmp.path(), "[jwt.signing]\nkey = \"secret\"\n").unwrap();
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::Off);
}
@@ -2397,11 +2572,34 @@ previous_key = "read-old"
assert!(text.parse::<toml::Table>().is_err(), "not TOML");
let cfg = parse_security_config_with_env(path, &fake_env(&[]));
assert_eq!(cfg.jwt_signing_key, b"unquoted-secret");
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::On);
std::fs::write(tmp.path(), "[fips]\nmode = [\"strict\"]\n").unwrap();
assert!(resolve_fips_setting_with_env(path, &fake_env(&[])).is_err());
assert!(fips_setting_of(path, &fake_env(&[])).is_err());
}
#[test]
fn test_lenient_file_keeps_a_key_a_later_line_would_shadow() {
let tmp = tempfile::NamedTempFile::new().unwrap();
let text = "[jwt.signing]\nkey = \"0123456789abcdef\"\n[jwt]\nsigning = \"x\"\n\
[jwt.signing.key]\nx = unquoted\n";
std::fs::write(tmp.path(), text).unwrap();
assert!(text.parse::<toml::Table>().is_err(), "not TOML");
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
assert_eq!(cfg.jwt_signing_key, b"0123456789abcdef");
}
#[test]
fn test_lenient_file_skips_array_of_tables_sections() {
let tmp = tempfile::NamedTempFile::new().unwrap();
let text = "[jwt.signing]\nkey = \"0123456789abcdef\"\n[[jwt.signing]]\nkey = \"\"\n\
[fips]\nmode = \"on\"\n";
std::fs::write(tmp.path(), text).unwrap();
assert!(text.parse::<toml::Table>().is_err(), "not TOML");
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
assert_eq!(cfg.jwt_signing_key, b"0123456789abcdef");
assert_eq!(cfg.fips_mode.as_deref(), Some("on"));
}
#[test]
@@ -2418,23 +2616,134 @@ previous_key = "read-old"
let cfg = parse_security_config_with_env(path, &fake_env(&[]));
assert_eq!(cfg.fips_mode.as_deref(), Some("on"));
assert_eq!(cfg.jwt_signing_key, b"secret");
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::On);
}
#[test]
fn test_security_config_reads_the_toml_forms_go_reads() {
for text in [
"[jwt.signing]\n\"key\" = \"0123456789\"\n\
[jwt.filer_signing]\n'key' = \"0123456789\"\n[fips]\n\"mode\" = \"on\"\n",
"[jwt.signing]\nkey = \"\"\"\n0123456789\"\"\"\n\
[jwt.filer_signing]\nkey = '''\n0123456789'''\n[fips]\nmode = \"on\"\n",
"jwt.signing.key = \"0123456789\"\njwt.filer_signing.key = \"0123456789\"\n\
fips.mode = \"on\"\n",
"[jwt]\nsigning = { key = \"0123456789\" }\nfiler_signing = { key = \"0123456789\" }\n\
[fips]\nmode = \"on\"\n",
"[ \"jwt\" . signing ]\nKey = \"0123456789\"\n[jwt.\"filer_signing\"]\nKEY = \"0123456789\"\n\
[FIPS]\nMode = \"on\"\n",
] {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), text).unwrap();
assert!(
text.parse::<toml::Table>().is_ok(),
"TOML, as Go reads it: {text}"
);
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
let keys = cfg.jwt_keys();
for setting in ["jwt.signing.key", "jwt.filer_signing.key"] {
let key = keys
.iter()
.find(|(s, _)| *s == setting)
.map(|(_, k)| k.as_slice());
assert_eq!(key, Some(&b"0123456789"[..]), "{setting} in {text}");
}
assert_eq!(cfg.fips_mode.as_deref(), Some("on"), "{text}");
}
}
fn fips_setting_of(
path: &str,
env: EnvLookup<'_>,
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
resolve_fips_setting_with_env(path, &parse_security_config_with_env(path, env), env)
}
#[test]
fn test_fips_mode_comes_from_the_read_the_jwt_keys_come_from() {
use seaweed_common::fips::FipsMode;
let tmp = tempfile::NamedTempFile::new().unwrap();
let path = tmp.path().to_str().unwrap();
std::fs::write(tmp.path(), "[fips]\nmode = \"strict\"\n").unwrap();
let parsed = parse_security_config_with_env(path, &fake_env(&[]));
std::fs::write(tmp.path(), "[fips]\nmode = \"off\"\n").unwrap();
let setting = resolve_fips_setting_with_env(path, &parsed, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::Strict);
}
/// The value Go's viper GetString reads for `jwt.filer_signing.key` from
/// security.toml `text`, as this server reads it.
fn filer_jwt_key(text: &str) -> Vec<u8> {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), text).unwrap();
assert!(text.parse::<toml::Table>().is_ok(), "TOML: {text}");
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
cfg.jwt_keys()
.into_iter()
.find(|(s, _)| *s == "jwt.filer_signing.key")
.map(|(_, k)| k)
.unwrap()
}
#[test]
fn test_security_config_prefers_the_longest_literal_key_as_go_does() {
let nested = "[jwt.filer_signing]\nkey = \"0123456789abcdef\"\n";
for literal in [
"\"jwt.filer_signing.key\" = \"short\"\n",
"[jwt]\n\"filer_signing.key\" = \"short\"\n",
] {
assert_eq!(filer_jwt_key(&format!("{literal}{nested}")), b"short");
}
assert_eq!(
filer_jwt_key(&format!("\"jwt.filer_signing\" = \"x\"\n{nested}")),
b"0123456789abcdef"
);
}
#[test]
fn test_security_config_resolves_key_case_collisions_as_go_does() {
for text in [
"[jwt.filer_signing]\nkey = \"0123456789abcdef\"\nKEY = \"short\"\n",
"[jwt.filer_signing]\nKEY = \"short\"\nkey = \"0123456789abcdef\"\n",
"[jwt.filer_signing]\nkey = \"0123456789abcdef\"\n[JWT.filer_signing]\nkey = \"short\"\n",
] {
assert_eq!(filer_jwt_key(text), b"short", "{text}");
}
assert_eq!(
filer_jwt_key("[JWT.Filer_Signing]\nKey = \"0123456789abcdef\"\n"),
b"0123456789abcdef"
);
}
#[test]
fn test_security_config_reads_a_non_string_jwt_key_as_go_does() {
assert_eq!(filer_jwt_key("[jwt.filer_signing]\nkey = [\"x\"]\n"), b"");
assert_eq!(filer_jwt_key("[jwt.filer_signing.key]\nx = \"y\"\n"), b"");
assert_eq!(filer_jwt_key("[jwt.filer_signing]\nkey = 1234\n"), b"1234");
}
#[test]
fn test_security_config_reads_a_float_jwt_key_as_go_does() {
let key = filer_jwt_key("[jwt.filer_signing]\nkey = 1234567890123.0\n");
assert_eq!(key, b"1234567890123");
let key = filer_jwt_key("[jwt.filer_signing]\nkey = \"1234567890123.0\"\n");
assert_eq!(key, b"1234567890123.0");
}
#[test]
fn test_fips_mode_refuses_a_security_file_it_cannot_read() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), b"[fips]\nmode = \"on\"\n\xff\xfe\n").unwrap();
let path = tmp.path().to_str().unwrap();
let err = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap_err();
let err = fips_setting_of(path, &fake_env(&[])).unwrap_err();
assert!(
err.to_string()
.contains("cannot tell whether it sets fips.mode"),
"{err}"
);
let missing = format!("{path}.missing");
let setting = resolve_fips_setting_with_env(&missing, &fake_env(&[])).unwrap();
let setting = fips_setting_of(&missing, &fake_env(&[])).unwrap();
assert_eq!(setting.mode, seaweed_common::fips::FipsMode::Off);
}
+32 -3
View File
@@ -57,7 +57,8 @@ fn main() {
.init();
let config = config::parse_cli();
install_crypto_provider_for_fips_mode(&config.security_file);
install_crypto_provider_for_fips_mode(&config);
check_jwt_keys_for_fips_mode(&config);
seaweed_volume::server::server_stats::init_process_start();
#[cfg(unix)]
let cpu_profile = match CpuProfileSession::start(&config) {
@@ -105,8 +106,10 @@ fn main() {
/// Resolves the FIPS mode from `fips.mode` or `WEED_FIPS_MODE`, logs it and
/// installs the matching rustls provider before anything builds TLS; exits
/// when the value is unknown.
fn install_crypto_provider_for_fips_mode(security_file: &str) {
let installed = config::resolve_fips_setting(security_file)
fn install_crypto_provider_for_fips_mode(config: &config::VolumeServerConfig) {
let installed = config
.fips_setting
.clone()
.map_err(|e| e.to_string())
.and_then(|setting| {
seaweed_common::tls::install_process_provider(setting.mode)
@@ -126,6 +129,32 @@ fn install_crypto_provider_for_fips_mode(security_file: &str) {
}
}
/// Checks the JWT HMAC signing keys from security.toml and their WEED_
/// variables for a length of at least 14 characters, as FIPS 140 requires.
/// Under `fips.mode = strict`, if any of them is shorter, it logs an error
/// naming each such setting and its length and exits the server with status 1.
/// In any other mode the server starts, and each such key except a
/// `previous_key` gets a warning that strict mode would refuse it.
fn check_jwt_keys_for_fips_mode(config: &config::VolumeServerConfig) {
use seaweed_common::jwt_keys;
let mode = seaweed_common::fips::process_mode();
let file = &config.security_file_name;
for (setting, key) in &config.jwt_keys {
if let Some(warning) = jwt_keys::short_key_warning(mode, file, setting, key) {
warn!("{}", warning);
}
}
let keys: Vec<(&str, &[u8])> = config
.jwt_keys
.iter()
.map(|(setting, key)| (*setting, key.as_slice()))
.collect();
if let Some(short) = jwt_keys::short_keys(mode, &keys) {
error!("{}", jwt_keys::startup_refusal(file, &short));
std::process::exit(1);
}
}
/// Mirrors Go's rejectHttpsDowngrade: a redirect must not downgrade a request
/// carrying data and auth headers from https to plaintext.
fn redirect_is_https_downgrade(previous: &[reqwest::Url], next: &reqwest::Url) -> bool {
+116 -2
View File
@@ -12,6 +12,8 @@ use std::net::IpAddr;
use std::time::{SystemTime, UNIX_EPOCH};
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
use seaweed_common::fips::FipsMode;
use seaweed_common::jwt_keys;
use serde::{Deserialize, Serialize};
// ============================================================================
@@ -184,6 +186,21 @@ pub struct Guard {
is_write_active: bool,
}
/// Go's `usablePreviousKey`: under strict mode, a previous key shorter than 14
/// characters is dropped with an error naming it (`name`), and the reload goes
/// ahead without it.
fn usable_previous_key(mode: FipsMode, name: &str, key: SigningKey) -> SigningKey {
if jwt_keys::is_short(mode, &key.0) {
tracing::error!(
"JWT reload: ignoring the {}, which is shorter than the {} characters FIPS 140 needs for HMAC keys; the new keys are in effect",
name,
jwt_keys::MIN_HMAC_KEY_BYTES
);
return SigningKey(vec![]);
}
key
}
impl Guard {
pub fn new(
whitelist: &[String],
@@ -238,7 +255,10 @@ impl Guard {
/// Refresh the JWT signing keys and their expirations in place so operators
/// can rotate keys via SIGHUP without restarting the process. Mirrors Go's
/// `Guard::UpdateSigningKeys`: it swaps the fields and recomputes
/// `is_write_active`.
/// `is_write_active`. Under `fips.mode = strict`, a new write or read key
/// shorter than 14 characters keeps the keys as they were, logs an error and
/// returns false; a short previous key is dropped with an error and the
/// other keys take effect.
pub fn update_signing_keys(
&mut self,
signing_key: SigningKey,
@@ -247,7 +267,42 @@ impl Guard {
read_expires_after_sec: i64,
previous_signing_key: SigningKey,
previous_read_signing_key: SigningKey,
) {
) -> bool {
self.update_signing_keys_in_mode(
seaweed_common::fips::process_mode(),
signing_key,
expires_after_sec,
read_signing_key,
read_expires_after_sec,
previous_signing_key,
previous_read_signing_key,
)
}
/// [`Guard::update_signing_keys`] for the FIPS mode `mode`.
#[allow(clippy::too_many_arguments)]
fn update_signing_keys_in_mode(
&mut self,
mode: FipsMode,
signing_key: SigningKey,
expires_after_sec: i64,
read_signing_key: SigningKey,
read_expires_after_sec: i64,
previous_signing_key: SigningKey,
previous_read_signing_key: SigningKey,
) -> bool {
let current: [(&str, &[u8]); 2] = [
("signing key", &signing_key.0),
("read signing key", &read_signing_key.0),
];
if let Some(short) = jwt_keys::short_keys(mode, &current) {
tracing::error!("JWT reload: keeping the keys in effect, because {}", short);
return false;
}
let previous_signing_key =
usable_previous_key(mode, "previous signing key", previous_signing_key);
let previous_read_signing_key =
usable_previous_key(mode, "previous read signing key", previous_read_signing_key);
self.signing_key = signing_key;
self.expires_after_sec = expires_after_sec;
self.read_signing_key = read_signing_key;
@@ -257,6 +312,7 @@ impl Guard {
let is_empty_whitelist = self.whitelist_ips.is_empty() && self.whitelist_cidrs.is_empty();
self.is_write_active = !is_empty_whitelist || !self.signing_key.is_empty();
true
}
/// Whether any write-side control is configured: a non-empty whitelist or a
@@ -688,6 +744,64 @@ mod tests {
assert!(!accepts(&guard, "read-old", false));
}
#[test]
fn test_strict_reload_keeps_keys_when_a_current_key_is_short() {
let mut guard = Guard::new(
&[],
SigningKey::from_string("write-key-long-enough"),
10,
SigningKey::from_string("read-key-long-enough"),
60,
);
for (write, read) in [
("0123456789", "read-key-replaced-ok"),
("write-key-replaced-ok", "short"),
] {
assert!(!guard.update_signing_keys_in_mode(
FipsMode::Strict,
SigningKey::from_string(write),
11,
SigningKey::from_string(read),
61,
SigningKey(vec![]),
SigningKey(vec![]),
));
assert_eq!(guard.signing_key.0, b"write-key-long-enough");
assert_eq!(guard.read_signing_key.0, b"read-key-long-enough");
assert_eq!(guard.expires_after_sec, 10);
}
assert!(guard.update_signing_keys_in_mode(
FipsMode::On,
SigningKey::from_string("0123456789"),
11,
SigningKey(vec![]),
61,
SigningKey(vec![]),
SigningKey(vec![]),
));
assert_eq!(guard.signing_key.0, b"0123456789");
}
#[test]
fn test_strict_reload_drops_a_short_previous_key() {
let mut guard = Guard::new(&[], SigningKey(vec![]), 0, SigningKey(vec![]), 0);
assert!(guard.update_signing_keys_in_mode(
FipsMode::Strict,
SigningKey::from_string("write-key-long-enough"),
10,
SigningKey::from_string("read-key-long-enough"),
60,
SigningKey::from_string("old-short"),
SigningKey::from_string("old-read-key-long-enough"),
));
assert_eq!(guard.signing_key.0, b"write-key-long-enough");
assert!(guard.previous_signing_key.is_empty());
assert_eq!(
guard.previous_read_signing_key.0,
b"old-read-key-long-enough"
);
}
#[test]
fn test_update_signing_keys_toggles_write_active() {
let mut guard = Guard::new(&[], SigningKey(vec![]), 0, SigningKey(vec![]), 0);
+6
View File
@@ -457,6 +457,12 @@ mod tests {
grpc_health_check_common_names: vec![],
tls_policy: TlsPolicy::default(),
security_file: String::new(),
security_file_name: String::new(),
jwt_keys: Vec::new(),
fips_setting: Ok(seaweed_common::fips::Setting {
mode: Default::default(),
source: None,
}),
}
}
+13 -5
View File
@@ -3317,12 +3317,14 @@ pub async fn post_handler(
let original_data_size = uncompressed_data.len() as u32;
// Only compute and validate Content-MD5 when the client provided one
// (Go only computes MD5 when Content-MD5 header/field is present)
// (Go only computes MD5 when Content-MD5 header/field is present).
// Under fips.mode strict no MD5 is computed: the client's value is kept
// unchecked, as Go does under GODEBUG=fips140=only.
let content_md5 = content_md5.or(parsed_content_md5);
let original_content_md5 = if content_md5.is_some() {
Some(compute_md5_base64(&uncompressed_data))
} else {
None
let original_content_md5 = match &content_md5 {
Some(expected) if strict_fips_mode() => Some(expected.clone()),
Some(_) => Some(compute_md5_base64(&uncompressed_data)),
None => None,
};
if let (Some(expected_md5), Some(actual_md5)) = (&content_md5, &original_content_md5)
&& expected_md5 != actual_md5
@@ -5377,6 +5379,12 @@ fn check_content_crc32c(expected: &str, data: &[u8]) -> Result<(), String> {
Ok(())
}
/// Whether this process runs under `fips.mode = strict`, where it computes no
/// MD5.
fn strict_fips_mode() -> bool {
seaweed_common::fips::process_mode() == seaweed_common::fips::FipsMode::Strict
}
fn compute_md5_base64(data: &[u8]) -> String {
use base64::Engine;
use md5::{Digest, Md5};
+6
View File
@@ -177,6 +177,12 @@ mod tests {
grpc_health_check_common_names: vec![],
tls_policy: TlsPolicy::default(),
security_file: String::new(),
security_file_name: String::new(),
jwt_keys: Vec::new(),
fips_setting: Ok(seaweed_common::fips::Setting {
mode: Default::default(),
source: None,
}),
}
}
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env bash
# Checks what strict FIPS mode refuses, in the Go components
# (GODEBUG=fips140=only) and the Rust volume server (WEED_FIPS_MODE=strict).
# Go's crypto/hmac refuses keys shorter than 112 bits (14 bytes) in that mode,
# so a component must refuse such a key at startup instead of failing (or
# panicking) on the first request that needs it.
#
# master, filer, volume (Go), volume (Rust): started alone with a 10-byte
# jwt.signing.key; each must exit non-zero within 20 s naming the mode.
# s3: a fips140=only cluster with valid JWT keys and an identity whose
# 8-character secret makes a SigV4 signing key under 14 bytes; a request
# signed with it must get an S3 error answer, not a dropped connection.
#
# Prints one line per component and exits non-zero if any check fails.
# WEED, WEED_VOLUME, WORK_DIR binaries and scratch dir
set -uo pipefail
WEED=${WEED:-weed}
WEED_VOLUME=${WEED_VOLUME:-weed-volume}
WORK_DIR=${WORK_DIR:-/tmp/seaweedfs-negative-config}
export GODEBUG=fips140=only WEED_FIPS_MODE=strict
rm -rf "$WORK_DIR"
mkdir -p "$WORK_DIR/short" "$WORK_DIR/valid"
printf '[jwt.signing]\nkey = "0123456789"\n' > "$WORK_DIR/short/security.toml"
printf '[jwt.signing]\nkey = "%s"\n' "$(head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n')" \
> "$WORK_DIR/valid/security.toml"
failures=0
# expect_refusal starts a component with the short key and reports whether it
# exited non-zero within 20 s naming the mode in its log: fips140=only for Go,
# fips.mode strict for Rust.
expect_refusal() {
local name=$1; shift
local log="$WORK_DIR/$name.log"
(cd "$WORK_DIR/short" && exec "$@") > "$log" 2>&1 &
local pid=$! status=
for _ in $(seq 1 20); do
if ! kill -0 "$pid" 2>/dev/null; then wait "$pid"; status=$?; break; fi
sleep 1
done
if [ -z "$status" ]; then
kill -KILL "$pid" 2>/dev/null; wait "$pid" 2>/dev/null
echo "FAIL $name: still running after 20 s with a 10-byte jwt.signing.key"
failures=$((failures + 1))
elif [ "$status" -ne 0 ] && grep -q -E 'fips140=only|fips\.mode strict' "$log"; then
echo "ok $name: refused at startup (exit $status)"
else
echo "FAIL $name: exited $status without naming the FIPS mode; log tail:"
tail -5 "$log" | sed 's/^/ /'
failures=$((failures + 1))
fi
}
mkdir -p "$WORK_DIR/m" "$WORK_DIR/f" "$WORK_DIR/vg" "$WORK_DIR/vr"
expect_refusal master "$WEED" master -port=19333 -mdir="$WORK_DIR/m" -peers=none
expect_refusal filer "$WEED" filer -master=127.0.0.1:19333 -port=18888 -defaultStoreDir="$WORK_DIR/f"
expect_refusal volume-go "$WEED" volume -master=127.0.0.1:19333 -port=18080 -dir="$WORK_DIR/vg"
expect_refusal volume-rust "$WEED_VOLUME" --master 127.0.0.1:19333 --port 18081 --port.grpc 28081 \
--dir "$WORK_DIR/vr" --securityFile "$WORK_DIR/short/security.toml"
cat > "$WORK_DIR/valid/s3.json" <<'EOF'
{"identities":[{"name":"short","credentials":[{"accessKey":"shortsecretkey01","secretKey":"abcd1234"}],"actions":["Admin"]}]}
EOF
mkdir -p "$WORK_DIR/s"
(cd "$WORK_DIR/valid" && exec "$WEED" server -filer -s3 -ip=127.0.0.1 -dir="$WORK_DIR/s" \
-master.port=29333 -volume.port=28080 -filer.port=28888 -s3.port=28000 -master.peers=none \
-s3.config="$WORK_DIR/valid/s3.json") > "$WORK_DIR/s3.log" 2>&1 &
server_pid=$!
for _ in $(seq 1 60); do curl -s -o /dev/null http://127.0.0.1:28000/ && break; sleep 1; done
code=$(curl -s -o "$WORK_DIR/s3.body" -w '%{http_code}' --aws-sigv4 "aws:amz:us-east-1:s3" \
--user shortsecretkey01:abcd1234 http://127.0.0.1:28000/)
curl_status=$?
if [ "$curl_status" -eq 0 ] && [ "${code:0:1}" = 4 ]; then
echo "ok s3: an 8-character secret gets HTTP $code ($(grep -o '<Code>[^<]*' "$WORK_DIR/s3.body" | cut -c7-))"
else
echo "FAIL s3: an 8-character secret got curl exit $curl_status, HTTP $code (a dropped connection is a panic in the request)"
failures=$((failures + 1))
fi
kill -TERM "$server_pid" 2>/dev/null; wait "$server_pid" 2>/dev/null
exit $((failures > 0))
+4 -2
View File
@@ -4,7 +4,9 @@
# $WORK_DIR/pids, so `xargs kill < "$WORK_DIR/pids"` stops the cell.
#
# DIGEST_MODE md5 (GODEBUG=fips140=off), sha256 (fips140=on with the
# filer's -digest=sha256) or fips140only (GODEBUG=fips140=only)
# filer's -digest=sha256) or fips140only (GODEBUG=fips140=only
# and WEED_FIPS_MODE=strict, which the Rust volume server
# takes its mode from and the Go processes check)
# VOLUME_SERVER go (weed server's own volume server) or rust (weed-volume)
# WEED, WEED_VOLUME, WORK_DIR, S3_CONFIG binaries, scratch dir, identities
#
@@ -22,7 +24,7 @@ WORK_DIR=${WORK_DIR:-/tmp/seaweedfs-digest-matrix}
case "$DIGEST_MODE" in
md5) export GODEBUG=fips140=off; digest_flag=() ;;
sha256) export GODEBUG=fips140=on; digest_flag=(-filer.digest=sha256) ;;
fips140only) export GODEBUG=fips140=only; digest_flag=() ;;
fips140only) export GODEBUG=fips140=only WEED_FIPS_MODE=strict; digest_flag=() ;;
*) echo "unknown DIGEST_MODE $DIGEST_MODE" >&2; exit 2 ;;
esac
case "$VOLUME_SERVER" in
@@ -79,6 +79,53 @@ func TestWriteMalformedMultipartAndMD5Mismatch(t *testing.T) {
}
}
// TestWriteMD5MismatchKeptUncheckedUnderStrictFIPS checks that in strict FIPS
// mode (GODEBUG=fips140=only for Go, fips.mode strict for Rust), where no MD5
// may be computed, an upload whose Content-MD5 does not match its body is
// stored with the client's value instead of refused. The master and volume
// server inherit the environment set here; this test process keeps the mode it
// started with.
func TestWriteMD5MismatchKeptUncheckedUnderStrictFIPS(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
t.Setenv("GODEBUG", "fips140=only")
t.Setenv("WEED_FIPS_MODE", "strict")
clusterHarness := framework.StartVolumeCluster(t, matrix.P1())
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
defer conn.Close()
const volumeID = uint32(97)
framework.AllocateVolume(t, grpcClient, volumeID, "")
client := framework.NewHTTPClient()
url := clusterHarness.VolumeAdminURL() + "/" + framework.NewFileID(volumeID, 772101, 0x1A2B3C4D)
payload := []byte("content-md5-unchecked-body")
const wrongMD5 = "AAAAAAAAAAAAAAAAAAAAAA=="
uploadReq := newUploadRequest(t, url, payload)
uploadReq.Header.Set("Content-MD5", wrongMD5)
uploadResp := framework.DoRequest(t, client, uploadReq)
uploadBody := framework.ReadAllAndClose(t, uploadResp)
if uploadResp.StatusCode != http.StatusCreated {
t.Fatalf("content-md5 mismatch write under strict FIPS mode expected 201, got %d: %s", uploadResp.StatusCode, uploadBody)
}
if !strings.Contains(string(uploadBody), `"contentMd5":"`+wrongMD5+`"`) {
t.Fatalf("upload result should carry the client's Content-MD5 %s, got %s", wrongMD5, uploadBody)
}
readReq, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
t.Fatalf("create read request: %v", err)
}
readResp := framework.DoRequest(t, client, readReq)
readBody := framework.ReadAllAndClose(t, readResp)
if readResp.StatusCode != http.StatusOK || !bytes.Equal(readBody, payload) {
t.Fatalf("read back expected 200 with the payload, got %d: %q", readResp.StatusCode, readBody)
}
}
func TestWriteReadOnlyReportsConflictAndSafeRefusal(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")