Skip to content
Draft
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
3 changes: 3 additions & 0 deletions rust/operator-binary/src/controller/build/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,9 @@ impl ContainerConfig {
SecretClassVolumeProvisionParts::PublicPrivate,
)
.with_service_scope(cluster.name_any())
// Hadoop's HTTP clients request a ticket for `HTTP/<host in URL>`, and the
// URLs between daemons (`/imagetransfer`, `/getJournal`) use pod FQDNs.
.with_pod_scope()
.with_kerberos_service_name(role.kerberos_service_name())
.with_kerberos_service_name("HTTP")
.build()
Expand Down
157 changes: 157 additions & 0 deletions rust/operator-binary/src/controller/build/kerberos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ impl CoreSiteConfigBuilder {
&mut self,
kerberos: &KerberosConfig,
cluster_info: &KubernetesClusterInfo,
role_group_service_name: &str,
) -> &mut Self {
if kerberos.authentication_enabled {
let principal_host_part = principal_host_part(
Expand Down Expand Up @@ -118,6 +119,50 @@ impl CoreSiteConfigBuilder {
.add(
"dfs.namenode.kerberos.principal.pattern",
format!("nn/{principal_host_part}"),
)
// The following are required to secure WebHDFS
.add("hadoop.http.authentication.type", "kerberos")
.add(
"hadoop.http.authentication.simple.anonymous.allowed",
"false",
)
// SPNEGO principal for this pod's own FQDN. A single named principal is read
// through the JDK; `*` would make Hadoop parse the keytab with Kerby, which
// fails on the hole secret-operator leaves where it removes its dummy entry.
.add(
"hadoop.http.authentication.kerberos.principal",
format!(
"HTTP/${{env.POD_NAME}}.{role_group_service_name}.{namespace}.svc.{cluster_domain}@${{env.KERBEROS_REALM}}",
namespace = kerberos.cluster_namespace,
cluster_domain = cluster_info.cluster_domain,
),
)
.add(
"hadoop.http.authentication.kerberos.keytab",
format!("{KERBEROS_CONTAINER_PATH}/keytab"),
)
// DataNodes build their HTTP server without `DFSUtil.getHttpServerTemplate`, so they
// only get an authentication filter if one is listed here. NameNodes and JournalNodes
// drop `AuthenticationFilterInitializer` from this list and install `AuthFilterInitializer`.
.add(
"hadoop.http.filter.initializers",
"org.apache.hadoop.http.lib.StaticUserWebFilter,org.apache.hadoop.security.AuthenticationFilterInitializer",
)
// Prometheus cannot do SPNEGO, so the metrics endpoint skips authentication.
.add("hadoop.http.authentication.kerberos.endpoint.whitelist", "/prom")
// NameNodes fetch edits from JournalNodes over SPNEGO, which yields the caller's short
// name. `GetJournalEditServlet.isValidRequestor` only accepts a short name equal to the
// JournalNode's own, so the JournalNode principal maps to the NameNode's short name.
.add(
"hadoop.security.auth_to_local",
format!(
"RULE:[2:$1/$2@$0](jn/{host}@${{env.KERBEROS_REALM}})s/.*/nn/\nDEFAULT",
host = format!("{cluster}.{namespace}.svc.{cluster_domain}",
cluster = kerberos.cluster_name,
namespace = kerberos.cluster_namespace,
cluster_domain = cluster_info.cluster_domain,
).replace('.', "\\."),
),
);

if !kerberos.authorization_enabled {
Expand Down Expand Up @@ -193,3 +238,115 @@ fn principal_host_part(
let cluster_domain = &cluster_info.cluster_domain;
format!("{cluster_name}.{cluster_namespace}.svc.{cluster_domain}@${{env.KERBEROS_REALM}}")
}

#[cfg(test)]
mod tests {
use indoc::formatdoc;
use rstest::rstest;

use super::*;
use crate::controller::build::properties::test_support::{cluster_info, hadoop_property_value};

/// Renders the core-site security config of the `hdfs` cluster in the `default` namespace
/// for a pod of the role group Service `hdfs-namenode-default`.
fn render(authentication_enabled: bool) -> String {
let kerberos = KerberosConfig {
cluster_name: "hdfs",
cluster_namespace: "default",
authentication_enabled,
kerberos_enabled: authentication_enabled,
authorization_enabled: false,
};
CoreSiteConfigBuilder::new("hdfs".to_owned())
.security_config(&kerberos, &cluster_info(), "hdfs-namenode-default")
.build_as_xml()
}

fn property(name: &str, value: &str) -> String {
formatdoc! {"
<name>{name}</name>
<value>{value}</value>"}
}

/// Hadoop's HTTP clients request a ticket for `HTTP/<host in URL>`, and daemons address
/// each other by pod FQDN, so each pod must accept its own FQDN principal.
#[test]
fn http_principal_is_the_pods_fqdn() {
let xml = render(true);

let expected = property(
"hadoop.http.authentication.kerberos.principal",
"HTTP/${env.POD_NAME}.hdfs-namenode-default.default.svc.cluster.local@${env.KERBEROS_REALM}",
);
assert!(xml.contains(&expected), "{xml}");
}

#[rstest]
#[case::kerberos_type("hadoop.http.authentication.type", "kerberos")]
#[case::no_anonymous_access("hadoop.http.authentication.simple.anonymous.allowed", "false")]
#[case::keytab(
"hadoop.http.authentication.kerberos.keytab",
"/stackable/kerberos/keytab"
)]
#[case::datanode_filter(
"hadoop.http.filter.initializers",
"org.apache.hadoop.http.lib.StaticUserWebFilter,org.apache.hadoop.security.AuthenticationFilterInitializer"
)]
#[case::unauthenticated_metrics(
"hadoop.http.authentication.kerberos.endpoint.whitelist",
"/prom"
)]
fn http_endpoints_require_authentication(#[case] name: &str, #[case] value: &str) {
let xml = render(true);

assert!(xml.contains(&property(name, value)), "{xml}");
}

/// `GetJournalEditServlet` only accepts a requester whose short name equals the
/// JournalNode's own, so the JournalNode service principal must map to `nn`, while
/// `DEFAULT` keeps every other principal's mapping. The XML writer encodes the newline
/// between the two rules as `&#xA;`.
#[test]
fn journalnode_principal_maps_to_namenode_user() {
let xml = render(true);

let expected = property(
"hadoop.security.auth_to_local",
r"RULE:[2:$1/$2@$0](jn/hdfs\.default\.svc\.cluster\.local@${env.KERBEROS_REALM})s/.*/nn/&#xA;DEFAULT",
);
assert!(xml.contains(&expected), "{xml}");
}

/// The JournalNode logs in as `dfs.journalnode.kerberos.principal`, so the `auth_to_local`
/// rule must match exactly that principal, with every dot of the host escaped so that the
/// regular expression matches nothing else.
#[test]
fn auth_to_local_rule_matches_the_journalnode_principal() {
let xml = render(true);
let journalnode_principal =
hadoop_property_value(&xml, "dfs.journalnode.kerberos.principal")
.expect("the JournalNode principal should be set");
let rule_pattern = hadoop_property_value(&xml, "hadoop.security.auth_to_local")
.and_then(|rules| rules.strip_prefix("RULE:[2:$1/$2@$0]("))
.and_then(|rule| rule.split_once(")s/"))
.map(|(pattern, _)| pattern)
.expect("the first auth_to_local rule should map a two-component principal");

assert_eq!(rule_pattern.replace(r"\.", "."), journalnode_principal);
let host_pattern = rule_pattern.replace("${env.KERBEROS_REALM}", "");
assert!(
!host_pattern.replace(r"\.", "").contains('.'),
"unescaped dot in {rule_pattern:?}"
);
}

#[rstest]
#[case::http_authentication("hadoop.http.authentication.")]
#[case::http_filter("hadoop.http.filter.initializers")]
#[case::principal_mapping("hadoop.security.auth_to_local")]
fn no_security_settings_without_authentication(#[case] name_prefix: &str) {
let xml = render(false);

assert!(!xml.contains(&format!("<name>{name_prefix}")), "{xml}");
}
}
193 changes: 192 additions & 1 deletion rust/operator-binary/src/controller/build/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,12 @@ mod tests {

use super::build;
use crate::{
controller::build::properties::test_support::{cluster_info, validated_cluster},
controller::build::{
container::KERBEROS_VOLUME_NAME,
properties::test_support::{
cluster_info, hadoop_property_value, kerberos_validated_cluster, validated_cluster,
},
},
test_support::namenode_listener,
};

Expand Down Expand Up @@ -781,4 +786,190 @@ mod tests {
);
}
}

/// Hadoop's HTTP clients request a ticket for `HTTP/<host in URL>`, and daemons address each
/// other by pod FQDN, `<pod>.<StatefulSet serviceName>.<namespace>.svc.<cluster domain>`. Each
/// role group's `core-site.xml` must therefore name the Service its StatefulSet uses, or
/// SPNEGO between daemons fails.
#[test]
fn kerberos_http_principal_names_the_statefulset_service() {
let resources =
build(&kerberos_validated_cluster(), &cluster_info()).expect("build should succeed");
assert_eq!(resources.stateful_sets.len(), 3, "one StatefulSet per role");

for stateful_set in &resources.stateful_sets {
let name = stateful_set
.meta()
.name
.as_deref()
.expect("every StatefulSet should have a name");
let service_name = stateful_set
.spec
.as_ref()
.and_then(|spec| spec.service_name.as_deref())
.expect("every StatefulSet should set serviceName");
let core_site = role_group_core_site(&resources.config_maps, name);

let expected = format!(
"<value>HTTP/${{env.POD_NAME}}.{service_name}.default.svc.cluster.local@${{env.KERBEROS_REALM}}</value>"
);
assert!(core_site.contains(&expected), "{name}: {core_site}");
}
}

/// The `core-site.xml` of the named role group `ConfigMap`.
fn role_group_core_site<'a>(config_maps: &'a [ConfigMap], name: &str) -> &'a str {
config_maps
.iter()
.find(|config_map| config_map.meta().name.as_deref() == Some(name))
.and_then(|config_map| config_map.data.as_ref())
.and_then(|data| data.get("core-site.xml"))
.map(String::as_str)
.expect("every role group's ConfigMap should contain core-site.xml")
}

/// The pod FQDN principal `HTTP/<pod>.<service>…` only exists if the secret-operator creates
/// it, which takes the pod scope plus the `HTTP` service name on the keytab volume. Without
/// it, SPNEGO between daemons fails, e.g. a new standby namenode cannot bootstrap.
#[test]
fn kerberos_keytab_contains_the_pods_http_principal() {
let resources =
build(&kerberos_validated_cluster(), &cluster_info()).expect("build should succeed");
assert_eq!(resources.stateful_sets.len(), 3, "one StatefulSet per role");

for stateful_set in &resources.stateful_sets {
let name = stateful_set
.meta()
.name
.as_deref()
.expect("every StatefulSet should have a name");
let annotations = stateful_set
.spec
.as_ref()
.and_then(|spec| spec.template.spec.as_ref())
.and_then(|pod_spec| pod_spec.volumes.as_ref())
.and_then(|volumes| {
volumes
.iter()
.find(|volume| volume.name == KERBEROS_VOLUME_NAME.to_string())
})
.and_then(|volume| volume.ephemeral.as_ref())
.and_then(|ephemeral| ephemeral.volume_claim_template.as_ref())
.and_then(|template| template.metadata.as_ref())
.and_then(|metadata| metadata.annotations.as_ref())
.expect("every StatefulSet should have an annotated kerberos volume");
let list = |key: &str| -> Vec<&str> {
annotations
.get(key)
.map(|value| value.split(',').collect())
.unwrap_or_default()
};

assert!(
list("secrets.stackable.tech/scope").contains(&"pod"),
"{name}: {annotations:?}"
);
assert!(
list("secrets.stackable.tech/kerberos.service.names").contains(&"HTTP"),
"{name}: {annotations:?}"
);
}
}

/// Prometheus cannot do SPNEGO, so the path every metrics Service tells it to scrape must be
/// whitelisted from Kerberos authentication, or scraping silently fails with 401.
#[test]
fn kerberos_metrics_scrape_path_skips_authentication() {
let resources =
build(&kerberos_validated_cluster(), &cluster_info()).expect("build should succeed");

let mut metrics_services = 0;
for service in &resources.services {
let name = service
.meta()
.name
.as_deref()
.expect("every Service should have a name");
let Some(role_group) = name.strip_suffix("-metrics") else {
continue;
};
metrics_services += 1;
let path = service
.meta()
.annotations
.as_ref()
.and_then(|annotations| annotations.get("prometheus.io/path"))
.expect("every metrics Service should set the scrape path");
let whitelist = hadoop_property_value(
role_group_core_site(&resources.config_maps, role_group),
"hadoop.http.authentication.kerberos.endpoint.whitelist",
)
.expect("every role group should whitelist endpoints from Kerberos authentication");

assert!(
whitelist.split(',').any(|endpoint| endpoint == path),
"{name} scrapes {path:?}, whitelist is {whitelist:?}"
);
}
assert_eq!(metrics_services, 3, "one metrics Service per role");
}

/// The HTTP principal in `core-site.xml` contains `${env.POD_NAME}` and
/// `${env.KERBEROS_REALM}`. Hadoop leaves an unset variable as literal text, so every
/// container that uses the keytab must provide both, or SPNEGO fails at runtime.
#[test]
fn kerberos_containers_provide_the_principal_variables() {
let resources =
build(&kerberos_validated_cluster(), &cluster_info()).expect("build should succeed");
let kerberos_volume_name = KERBEROS_VOLUME_NAME.to_string();

for stateful_set in &resources.stateful_sets {
let name = stateful_set
.meta()
.name
.as_deref()
.expect("every StatefulSet should have a name");
let pod_spec = stateful_set
.spec
.as_ref()
.and_then(|spec| spec.template.spec.as_ref())
.expect("every StatefulSet should have a pod spec");

let kerberos_containers: Vec<_> = pod_spec
.containers
.iter()
.chain(pod_spec.init_containers.iter().flatten())
.filter(|container| {
container
.volume_mounts
.iter()
.flatten()
.any(|volume_mount| volume_mount.name == kerberos_volume_name)
})
.collect();
assert!(
!kerberos_containers.is_empty(),
"{name} should have containers using the keytab"
);

for container in kerberos_containers {
let sets_pod_name = container.env.iter().flatten().any(|env_var| {
env_var.name == "POD_NAME"
&& env_var
.value_from
.as_ref()
.and_then(|source| source.field_ref.as_ref())
.is_some_and(|field_ref| field_ref.field_path == "metadata.name")
});
let exports_realm = container
.args
.iter()
.flatten()
.any(|arg| arg.contains("export KERBEROS_REALM="));

assert!(sets_pod_name, "{name}/{}: POD_NAME", container.name);
assert!(exports_realm, "{name}/{}: KERBEROS_REALM", container.name);
}
}
}
}
Loading
Loading