From 082dfdd62906f2e838f20ab4acd1bb5481d229b9 Mon Sep 17 00:00:00 2001 From: Andrew Kenworthy Date: Tue, 24 Nov 2026 17:49:24 +0100 Subject: [PATCH 1/4] add necessary core-site entries when kerberos enabled --- .../src/controller/build/container.rs | 3 + .../src/controller/build/kerberos.rs | 134 ++++++++++++++++++ .../src/controller/build/mod.rs | 71 +++++++++- .../controller/build/properties/core_site.rs | 17 ++- .../controller/build/resource/config_map.rs | 2 + 5 files changed, 225 insertions(+), 2 deletions(-) diff --git a/rust/operator-binary/src/controller/build/container.rs b/rust/operator-binary/src/controller/build/container.rs index 8777ec72..3120523c 100644 --- a/rust/operator-binary/src/controller/build/container.rs +++ b/rust/operator-binary/src/controller/build/container.rs @@ -297,6 +297,9 @@ impl ContainerConfig { SecretClassVolumeProvisionParts::PublicPrivate, ) .with_service_scope(cluster.name_any()) + // Hadoop's HTTP clients request a ticket for `HTTP/`, 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() diff --git a/rust/operator-binary/src/controller/build/kerberos.rs b/rust/operator-binary/src/controller/build/kerberos.rs index 6719d3d5..0e9f9d50 100644 --- a/rust/operator-binary/src/controller/build/kerberos.rs +++ b/rust/operator-binary/src/controller/build/kerberos.rs @@ -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( @@ -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 { @@ -193,3 +238,92 @@ 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; + + /// 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} + {value}"} + } + + /// Hadoop's HTTP clients request a ticket for `HTTP/`, 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 ` `. + #[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/ DEFAULT", + ); + assert!(xml.contains(&expected), "{xml}"); + } + + #[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_prefix}")), "{xml}"); + } +} diff --git a/rust/operator-binary/src/controller/build/mod.rs b/rust/operator-binary/src/controller/build/mod.rs index 3b9e7e3e..a7c589df 100644 --- a/rust/operator-binary/src/controller/build/mod.rs +++ b/rust/operator-binary/src/controller/build/mod.rs @@ -493,14 +493,47 @@ pub(crate) fn role_group_selector( #[cfg(test)] mod tests { + use indoc::indoc; use stackable_operator::{k8s_openapi::api::core::v1::ConfigMap, kube::Resource}; use super::build; use crate::{ controller::build::properties::test_support::{cluster_info, validated_cluster}, - test_support::namenode_listener, + test_support::{deserialize_and_validate_cluster, namenode_listener}, }; + /// The minimal three-role cluster with Kerberos authentication enabled. + const KERBEROS_HDFS_YAML: &str = indoc! {r#" + --- + apiVersion: hdfs.stackable.tech/v1alpha1 + kind: HdfsCluster + metadata: + name: hdfs + namespace: default + uid: c2c8c5c0-0b5a-4b1e-9f3e-1a2b3c4d5e6f + spec: + image: + productVersion: 3.4.0 + clusterConfig: + zookeeperConfigMapName: hdfs-zk + authentication: + tlsSecretClass: tls + kerberos: + secretClass: kerberos + nameNodes: + roleGroups: + default: + replicas: 1 + journalNodes: + roleGroups: + default: + replicas: 1 + dataNodes: + roleGroups: + default: + replicas: 1 + "#}; + /// The sorted `metadata.name`s of a resource collection. fn sorted_names(resources: &[impl Resource]) -> Vec { let mut names: Vec = resources @@ -781,4 +814,40 @@ mod tests { ); } } + + /// Hadoop's HTTP clients request a ticket for `HTTP/`, and daemons address each + /// other by pod FQDN, `...svc.`. 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 cluster = deserialize_and_validate_cluster(KERBEROS_HDFS_YAML); + let resources = build(&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 = resources + .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")) + .expect("every role group's ConfigMap should contain core-site.xml"); + + let expected = format!( + "HTTP/${{env.POD_NAME}}.{service_name}.default.svc.cluster.local@${{env.KERBEROS_REALM}}" + ); + assert!(core_site.contains(&expected), "{name}: {core_site}"); + } + } } diff --git a/rust/operator-binary/src/controller/build/properties/core_site.rs b/rust/operator-binary/src/controller/build/properties/core_site.rs index 40ec1635..682c1028 100644 --- a/rust/operator-binary/src/controller/build/properties/core_site.rs +++ b/rust/operator-binary/src/controller/build/properties/core_site.rs @@ -22,6 +22,7 @@ pub fn build( role: HdfsNodeRole, cluster_info: &KubernetesClusterInfo, overrides: KeyValueConfigOverrides, + role_group_service_name: &str, ) -> String { let cluster_config = &cluster.cluster_config; let kerberos = KerberosConfig { @@ -36,7 +37,7 @@ pub fn build( core_site .fs_default_fs() .ha_zookeeper_quorum() - .security_config(&kerberos, cluster_info) + .security_config(&kerberos, cluster_info, role_group_service_name) .enable_prometheus_endpoint() // The default (4096) hasn't changed since 2009. // Increase to 128k to allow for faster transfers. @@ -115,11 +116,18 @@ mod tests { #[test] fn renders_operator_defaults() { + let role_group_service_name = &validated_cluster() + .governing_service_name( + &HdfsNodeRole::Name, + &"default".parse().expect("valid role group name"), + ) + .to_string(); let xml = build( &validated_cluster(), HdfsNodeRole::Name, &cluster_info(), KeyValueConfigOverrides::default(), + role_group_service_name, ); assert!( xml.contains(indoc! {" @@ -143,11 +151,18 @@ mod tests { #[test] fn user_overrides_win_over_defaults() { + let role_group_service_name = &validated_cluster() + .governing_service_name( + &HdfsNodeRole::Name, + &"default".parse().expect("valid role group name"), + ) + .to_string(); let xml = build( &validated_cluster(), HdfsNodeRole::Name, &cluster_info(), [("io.file.buffer.size", "65536")].into(), + role_group_service_name, ); assert!( xml.contains(indoc! {" diff --git a/rust/operator-binary/src/controller/build/resource/config_map.rs b/rust/operator-binary/src/controller/build/resource/config_map.rs index dd3bf6de..507638bc 100644 --- a/rust/operator-binary/src/controller/build/resource/config_map.rs +++ b/rust/operator-binary/src/controller/build/resource/config_map.rs @@ -48,6 +48,7 @@ pub(crate) fn common_config_map_data(inputs: &RoleGroupInputs) -> Result Result Date: Tue, 24 Nov 2026 19:26:04 +0100 Subject: [PATCH 2/4] add kuttl steps to test kerberized endpoints --- tests/templates/kuttl/kerberos/33-assert.yaml | 11 +++ .../kuttl/kerberos/33-check-http-auth.txt.j2 | 90 +++++++++++++++++++ .../kuttl/kerberos/33-check-http-auth.yaml.j2 | 6 ++ 3 files changed, 107 insertions(+) create mode 100644 tests/templates/kuttl/kerberos/33-assert.yaml create mode 100644 tests/templates/kuttl/kerberos/33-check-http-auth.txt.j2 create mode 100644 tests/templates/kuttl/kerberos/33-check-http-auth.yaml.j2 diff --git a/tests/templates/kuttl/kerberos/33-assert.yaml b/tests/templates/kuttl/kerberos/33-assert.yaml new file mode 100644 index 00000000..50b248e6 --- /dev/null +++ b/tests/templates/kuttl/kerberos/33-assert.yaml @@ -0,0 +1,11 @@ +--- +apiVersion: kuttl.dev/v1beta1 +kind: TestAssert +timeout: 600 +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: check-http-auth +status: + succeeded: 1 diff --git a/tests/templates/kuttl/kerberos/33-check-http-auth.txt.j2 b/tests/templates/kuttl/kerberos/33-check-http-auth.txt.j2 new file mode 100644 index 00000000..a267e076 --- /dev/null +++ b/tests/templates/kuttl/kerberos/33-check-http-auth.txt.j2 @@ -0,0 +1,90 @@ +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: check-http-auth +spec: + template: + spec: + serviceAccountName: test-sa + containers: + - name: check-http-auth +{% if test_scenario['values']['hadoop'].find(",") > 0 %} + image: "{{ test_scenario['values']['hadoop'].split(',')[1] }}" +{% else %} + image: oci.stackable.tech/sdp/hadoop:{{ test_scenario['values']['hadoop'] }}-stackable0.0.0-dev +{% endif %} + env: + - name: KRB5_CONFIG + value: /stackable/kerberos/krb5.conf + command: + - /bin/bash + - -c + - | + set -u + + NAMENODE_0=https://hdfs-namenode-default-0.hdfs-namenode-default.$NAMESPACE.svc.cluster.local:9871 + NAMENODE_1=https://hdfs-namenode-default-1.hdfs-namenode-default.$NAMESPACE.svc.cluster.local:9871 + JOURNALNODE=https://hdfs-journalnode-default-0.hdfs-journalnode-default.$NAMESPACE.svc.cluster.local:8481 + DATANODE=https://hdfs-datanode-default-0.hdfs-datanode-default.$NAMESPACE.svc.cluster.local:9865 + + failures=0 + + # `-q` must be the first argument, otherwise curl reads the image's `~/.curlrc`, + # whose `fail` option hides the status code. + expect_status () { + expected=$1 + shift + actual=$(curl -q --silent --insecure --output /dev/null --write-out '%{http_code}' "$@") + if [ "$actual" = "$expected" ]; then + echo "OK $actual $*" + else + echo "FAIL $actual (expected $expected) $*" + failures=$((failures + 1)) + fi + } + + echo "Without credentials, every endpoint except the metrics requires authentication" + for server in $NAMENODE_0 $NAMENODE_1; do + expect_status 401 "$server/webhdfs/v1/?op=GETFILESTATUS&user.name=nn" + done + for server in $NAMENODE_0 $NAMENODE_1 $JOURNALNODE $DATANODE; do + expect_status 401 "$server/jmx" + expect_status 401 "$server/conf" + expect_status 200 "$server/prom" + done + + echo "With credentials, SPNEGO authentication succeeds" + kinit -kt /stackable/kerberos/keytab admin/check-http-auth.$NAMESPACE.svc.cluster.local + for server in $NAMENODE_0 $NAMENODE_1 $JOURNALNODE $DATANODE; do + expect_status 200 --negotiate --user : "$server/jmx" + done + kdestroy + + if [ "$failures" -ne 0 ]; then + echo "$failures check(s) failed" + exit 1 + fi + echo "Test passed" + volumeMounts: + - name: kerberos + mountPath: /stackable/kerberos + volumes: + - name: kerberos + ephemeral: + volumeClaimTemplate: + metadata: + annotations: + secrets.stackable.tech/class: kerberos-$NAMESPACE + secrets.stackable.tech/scope: service=check-http-auth + secrets.stackable.tech/kerberos.service.names: admin + spec: + storageClassName: secrets.stackable.tech + accessModes: + - ReadWriteOnce + resources: + requests: + storage: "1" + securityContext: + fsGroup: 1000 + restartPolicy: OnFailure diff --git a/tests/templates/kuttl/kerberos/33-check-http-auth.yaml.j2 b/tests/templates/kuttl/kerberos/33-check-http-auth.yaml.j2 new file mode 100644 index 00000000..51a08dc6 --- /dev/null +++ b/tests/templates/kuttl/kerberos/33-check-http-auth.yaml.j2 @@ -0,0 +1,6 @@ +--- +apiVersion: kuttl.dev/v1beta1 +kind: TestStep +commands: + # We need to replace $NAMESPACE (by KUTTL) + - script: envsubst '$NAMESPACE' < 33-check-http-auth.txt | kubectl apply -n $NAMESPACE -f - From b362977e84243952f7db343b3e8c9d5a5e1ce546 Mon Sep 17 00:00:00 2001 From: Andrew Kenworthy Date: Tue, 24 Nov 2026 19:26:33 +0100 Subject: [PATCH 3/4] add unit tests --- .../src/controller/build/kerberos.rs | 25 ++- .../src/controller/build/mod.rs | 210 ++++++++++++++---- .../src/controller/build/properties/mod.rs | 43 ++++ .../controller/build/resource/discovery.rs | 40 +++- 4 files changed, 272 insertions(+), 46 deletions(-) diff --git a/rust/operator-binary/src/controller/build/kerberos.rs b/rust/operator-binary/src/controller/build/kerberos.rs index 0e9f9d50..e3dc3c4d 100644 --- a/rust/operator-binary/src/controller/build/kerberos.rs +++ b/rust/operator-binary/src/controller/build/kerberos.rs @@ -245,7 +245,7 @@ mod tests { use rstest::rstest; use super::*; - use crate::controller::build::properties::test_support::cluster_info; + 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`. @@ -317,6 +317,29 @@ mod tests { 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")] diff --git a/rust/operator-binary/src/controller/build/mod.rs b/rust/operator-binary/src/controller/build/mod.rs index a7c589df..fb2f6ca9 100644 --- a/rust/operator-binary/src/controller/build/mod.rs +++ b/rust/operator-binary/src/controller/build/mod.rs @@ -493,47 +493,19 @@ pub(crate) fn role_group_selector( #[cfg(test)] mod tests { - use indoc::indoc; use stackable_operator::{k8s_openapi::api::core::v1::ConfigMap, kube::Resource}; use super::build; use crate::{ - controller::build::properties::test_support::{cluster_info, validated_cluster}, - test_support::{deserialize_and_validate_cluster, namenode_listener}, + controller::build::{ + container::KERBEROS_VOLUME_NAME, + properties::test_support::{ + cluster_info, hadoop_property_value, kerberos_validated_cluster, validated_cluster, + }, + }, + test_support::namenode_listener, }; - /// The minimal three-role cluster with Kerberos authentication enabled. - const KERBEROS_HDFS_YAML: &str = indoc! {r#" - --- - apiVersion: hdfs.stackable.tech/v1alpha1 - kind: HdfsCluster - metadata: - name: hdfs - namespace: default - uid: c2c8c5c0-0b5a-4b1e-9f3e-1a2b3c4d5e6f - spec: - image: - productVersion: 3.4.0 - clusterConfig: - zookeeperConfigMapName: hdfs-zk - authentication: - tlsSecretClass: tls - kerberos: - secretClass: kerberos - nameNodes: - roleGroups: - default: - replicas: 1 - journalNodes: - roleGroups: - default: - replicas: 1 - dataNodes: - roleGroups: - default: - replicas: 1 - "#}; - /// The sorted `metadata.name`s of a resource collection. fn sorted_names(resources: &[impl Resource]) -> Vec { let mut names: Vec = resources @@ -821,8 +793,8 @@ mod tests { /// SPNEGO between daemons fails. #[test] fn kerberos_http_principal_names_the_statefulset_service() { - let cluster = deserialize_and_validate_cluster(KERBEROS_HDFS_YAML); - let resources = build(&cluster, &cluster_info()).expect("build should succeed"); + 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 { @@ -836,13 +808,7 @@ mod tests { .as_ref() .and_then(|spec| spec.service_name.as_deref()) .expect("every StatefulSet should set serviceName"); - let core_site = resources - .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")) - .expect("every role group's ConfigMap should contain core-site.xml"); + let core_site = role_group_core_site(&resources.config_maps, name); let expected = format!( "HTTP/${{env.POD_NAME}}.{service_name}.default.svc.cluster.local@${{env.KERBEROS_REALM}}" @@ -850,4 +816,160 @@ mod tests { 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/.…` 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); + } + } + } } diff --git a/rust/operator-binary/src/controller/build/properties/mod.rs b/rust/operator-binary/src/controller/build/properties/mod.rs index de184ff3..b764cfaf 100644 --- a/rust/operator-binary/src/controller/build/properties/mod.rs +++ b/rust/operator-binary/src/controller/build/properties/mod.rs @@ -122,4 +122,47 @@ spec: pub fn validated_cluster() -> ValidatedCluster { deserialize_and_validate_cluster(MINIMAL_HDFS_YAML) } + + /// The minimal three-role HdfsCluster with Kerberos authentication enabled. + pub const KERBEROS_HDFS_YAML: &str = indoc! {r#" + --- + apiVersion: hdfs.stackable.tech/v1alpha1 + kind: HdfsCluster + metadata: + name: hdfs + namespace: default + uid: c2c8c5c0-0b5a-4b1e-9f3e-1a2b3c4d5e6f + spec: + image: + productVersion: 3.4.0 + clusterConfig: + zookeeperConfigMapName: hdfs-zk + authentication: + tlsSecretClass: tls + kerberos: + secretClass: kerberos + nameNodes: + roleGroups: + default: + replicas: 1 + journalNodes: + roleGroups: + default: + replicas: 1 + dataNodes: + roleGroups: + default: + replicas: 1 + "#}; + + pub fn kerberos_validated_cluster() -> ValidatedCluster { + deserialize_and_validate_cluster(KERBEROS_HDFS_YAML) + } + + /// The value of the property `name` in rendered Hadoop XML, as written (XML-escaped). + pub fn hadoop_property_value<'a>(xml: &'a str, name: &str) -> Option<&'a str> { + let after_name = xml.split_once(&format!("{name}"))?.1; + let after_value_tag = after_name.split_once("")?.1; + Some(after_value_tag.split_once("")?.0) + } } diff --git a/rust/operator-binary/src/controller/build/resource/discovery.rs b/rust/operator-binary/src/controller/build/resource/discovery.rs index 337b9027..9334ca0f 100644 --- a/rust/operator-binary/src/controller/build/resource/discovery.rs +++ b/rust/operator-binary/src/controller/build/resource/discovery.rs @@ -173,11 +173,14 @@ fn build_discovery_core_site_xml( mod tests { use std::collections::BTreeMap; + use rstest::rstest; use stackable_operator::kube::api::ObjectMeta; use super::*; use crate::{ - controller::build::properties::test_support::{cluster_info, validated_cluster}, + controller::build::properties::test_support::{ + cluster_info, hadoop_property_value, kerberos_validated_cluster, validated_cluster, + }, test_support::namenode_listener, }; @@ -276,4 +279,39 @@ mod tests { assert!(config_map.is_none()); } + + /// Clients load the discovery `core-site.xml`, and some of them run their own Hadoop HTTP + /// servers. The settings that secure the HDFS daemons' HTTP endpoints name HDFS pods and + /// principals, so they must stay out of the client configuration. + #[rstest] + #[case::http_authentication("hadoop.http.authentication.")] + #[case::http_filter("hadoop.http.filter.initializers")] + #[case::principal_mapping("hadoop.security.auth_to_local")] + fn kerberos_discovery_core_site_omits_server_http_settings(#[case] name_prefix: &str) { + let mut cluster = kerberos_validated_cluster(); + cluster.namenode_listeners = vec![namenode_listener( + "listener-hdfs-namenode-default-0", + "namenode-0.example.org", + 31000, + )]; + + let config_map = build_discovery_config_map(&cluster, &cluster_info()) + .expect("the build should not fail") + .expect("a fresh ConfigMap should be built"); + let core_site = config_map + .data + .as_ref() + .and_then(|data| data.get("core-site.xml")) + .expect("core-site.xml should be rendered"); + + assert_eq!( + hadoop_property_value(core_site, "hadoop.security.authentication"), + Some("kerberos"), + "the discovery config should be the Kerberos one: {core_site}" + ); + assert!( + !core_site.contains(&format!("{name_prefix}")), + "{core_site}" + ); + } } From c5654bc09b8277b2658b3c57d0a6b64c8d3ac778 Mon Sep 17 00:00:00 2001 From: Andrew Kenworthy Date: Wed, 25 Nov 2026 16:21:31 +0100 Subject: [PATCH 4/4] use indoc consistently --- .../src/controller/build/properties/mod.rs | 52 +++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/rust/operator-binary/src/controller/build/properties/mod.rs b/rust/operator-binary/src/controller/build/properties/mod.rs index b764cfaf..7ed4d796 100644 --- a/rust/operator-binary/src/controller/build/properties/mod.rs +++ b/rust/operator-binary/src/controller/build/properties/mod.rs @@ -86,32 +86,32 @@ pub(crate) mod test_support { "#}; /// A minimal three-role HdfsCluster used to drive the per-file builder tests. - pub const MINIMAL_HDFS_YAML: &str = r#" ---- -apiVersion: hdfs.stackable.tech/v1alpha1 -kind: HdfsCluster -metadata: - name: hdfs - namespace: default - uid: c2c8c5c0-0b5a-4b1e-9f3e-1a2b3c4d5e6f -spec: - image: - productVersion: 3.4.0 - clusterConfig: - zookeeperConfigMapName: hdfs-zk - nameNodes: - roleGroups: - default: - replicas: 1 - journalNodes: - roleGroups: - default: - replicas: 1 - dataNodes: - roleGroups: - default: - replicas: 1 -"#; + pub const MINIMAL_HDFS_YAML: &str = indoc! {r#" + --- + apiVersion: hdfs.stackable.tech/v1alpha1 + kind: HdfsCluster + metadata: + name: hdfs + namespace: default + uid: c2c8c5c0-0b5a-4b1e-9f3e-1a2b3c4d5e6f + spec: + image: + productVersion: 3.4.0 + clusterConfig: + zookeeperConfigMapName: hdfs-zk + nameNodes: + roleGroups: + default: + replicas: 1 + journalNodes: + roleGroups: + default: + replicas: 1 + dataNodes: + roleGroups: + default: + replicas: 1 + "#}; pub fn cluster_info() -> KubernetesClusterInfo { KubernetesClusterInfo {