This is an automated email from the ASF dual-hosted git repository.

smengcl pushed a commit to branch ozone-2.1
in repository https://gitbox.apache.org/repos/asf/ozone.git

commit ce009990a1ffd9d88f1a1f3bd2d9e629751a9cca
Author: Siyao Meng <[email protected]>
AuthorDate: Fri Oct 16 21:18:49 2026 -0700

    Improve certificate request handling in SCMSecurityProtocolServer and 
DefaultCAServer.
    
    (cherry picked from commit 7f9b6237deb2b06d73d1ac2b78cccaa60780c3ef)
    
    Conflicts:
            
hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/authority/DefaultCAServer.java
            
hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/TestHddsServerUtil.java
            
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/TestSecureOzoneCluster.java
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../org/apache/hadoop/hdds/recon/ReconConfig.java  |  3 +-
 .../common/src/main/resources/ozone-default.xml    |  6 ++-
 .../certificate/authority/DefaultCAServer.java     | 15 +++++-
 .../authority/profile/DefaultCAProfile.java        | 14 ++++--
 .../authority/profile/DefaultProfile.java          |  2 +-
 .../certificate/authority/TestDefaultCAServer.java |  3 +-
 .../certificate/authority/TestDefaultProfile.java  | 15 ++++++
 .../hdds/scm/server/SCMSecurityProtocolServer.java | 34 +++++++++++++
 .../apache/hadoop/hdds/scm/TestHddsServerUtil.java | 17 +++++++
 .../hadoop/ozone/TestSecureOzoneCluster.java       | 55 ++++++++++++++++++++++
 10 files changed, 153 insertions(+), 11 deletions(-)

diff --git 
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/recon/ReconConfig.java
 
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/recon/ReconConfig.java
index 61cfb3172e3..0f18a62b1ce 100644
--- 
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/recon/ReconConfig.java
+++ 
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/recon/ReconConfig.java
@@ -32,7 +32,8 @@ public class ReconConfig {
       type = ConfigType.STRING,
       defaultValue = "",
       tags = { ConfigTag.SECURITY, ConfigTag.RECON, ConfigTag.OZONE },
-      description = "This Kerberos principal is used by the Recon service."
+      description = "This Kerberos principal is used by the Recon service. SCM 
issues a Recon certificate only to this"
+          + " service user, so the property must be set in the configuration 
of SCM as well."
   )
   private String principal;
 
diff --git a/hadoop-hdds/common/src/main/resources/ozone-default.xml 
b/hadoop-hdds/common/src/main/resources/ozone-default.xml
index 496df01e926..cae8d2cdd0b 100644
--- a/hadoop-hdds/common/src/main/resources/ozone-default.xml
+++ b/hadoop-hdds/common/src/main/resources/ozone-default.xml
@@ -2371,8 +2371,8 @@
     <value>OM/_HOST@REALM</value>
     <tag>OZONE, SECURITY, KERBEROS</tag>
     <description>The OzoneManager service principal. Ex om/[email protected]
-      SCM allocates and deletes blocks only for this service user or an SCM 
admin, so the property must be set in the
-      configuration of SCM as well.
+      SCM issues an OM certificate only to this service user, and allocates 
and deletes blocks only for this service
+      user or an SCM admin, so the property must be set in the configuration 
of SCM as well.
     </description>
   </property>
   <property>
@@ -4789,6 +4789,8 @@
       dn/[email protected]. Each Datanode will substitute _HOST with its
       own fully qualified hostname at startup. The _HOST placeholder
       allows using the same configuration setting on all Datanodes.
+      SCM issues a Datanode certificate only to this service user, so the
+      property must be set in the configuration of SCM as well.
     </description>
   </property>
   <property>
diff --git 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/authority/DefaultCAServer.java
 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/authority/DefaultCAServer.java
index 75d19dedd2b..ca11cfa2681 100644
--- 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/authority/DefaultCAServer.java
+++ 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/authority/DefaultCAServer.java
@@ -48,6 +48,7 @@
 import org.apache.hadoop.hdds.scm.metadata.SCMMetadataStore;
 import org.apache.hadoop.hdds.security.SecurityConfig;
 import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import 
org.apache.hadoop.hdds.security.x509.certificate.authority.profile.DefaultProfile;
 import 
org.apache.hadoop.hdds.security.x509.certificate.authority.profile.PKIProfile;
 import org.apache.hadoop.hdds.security.x509.certificate.utils.CertificateCodec;
 import 
org.apache.hadoop.hdds.security.x509.certificate.utils.SelfSignedCertificate;
@@ -119,6 +120,7 @@ public class DefaultCAServer implements CertificateServer {
    */
   private PKIProfile profile;
   private CertificateApprover approver;
+  private CertificateApprover leafApprover;
   private CertificateStore store;
   private Lock lock;
   private BigInteger rootCertificateId;
@@ -156,6 +158,7 @@ public void init(SecurityConfig securityConfig, CAType type)
     caRootX509Path = securityConfig.getCertificateLocation(componentName);
     this.config = securityConfig;
     this.approver = new DefaultApprover(profile, this.config);
+    this.leafApprover = new DefaultApprover(new DefaultProfile(), this.config);
 
     /* In future we will split this code to have different kind of CAs.
      * Right now, we have only self-signed CertificateServer.
@@ -210,7 +213,7 @@ public Future<CertPath> requestCertificate(
     LocalDateTime beginDate = LocalDateTime.now();
     LocalDateTime endDate = expiryFor(beginDate, role);
 
-    CompletableFuture<Void> csrInspection = approver.inspectCSR(csr);
+    CompletableFuture<Void> csrInspection = getApprover(role).inspectCSR(csr);
     CompletableFuture<CertPath> certPathPromise = new CompletableFuture<>();
     // An inspection that has not completed is not an approval.
     if (!csrInspection.isDone()) {
@@ -254,6 +257,14 @@ public Future<CertPath> requestCertificate(
     return certPathPromise;
   }
 
+  /**
+   * Only an SCM can be issued a CA certificate, by this CA whether it is the 
root CA or the intermediate CA of another
+   * SCM (HDDS-8286). The other roles get a leaf certificate whatever the 
profile of this CA.
+   */
+  private CertificateApprover getApprover(NodeType role) {
+    return role == NodeType.SCM ? approver : leafApprover;
+  }
+
   private LocalDateTime expiryFor(LocalDateTime beginDate, NodeType role) {
     // When issuing certificates for sub-ca use the max certificate duration 
similar to self-signed root certificate.
     if (role == NodeType.SCM) {
@@ -270,7 +281,7 @@ private X509Certificate signAndStoreCertificate(
     X509Certificate xcert;
     try {
       Preconditions.checkState(!Strings.isNullOrEmpty(certSerialId));
-      xcert = approver.sign(config,
+      xcert = getApprover(role).sign(config,
           getPrivateKey(),
           getCACertificate(),
           Date.from(beginDate.atZone(ZoneId.systemDefault()).toInstant()),
diff --git 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/authority/profile/DefaultCAProfile.java
 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/authority/profile/DefaultCAProfile.java
index 5aa87d5aea1..1a38e9c341d 100644
--- 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/authority/profile/DefaultCAProfile.java
+++ 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/authority/profile/DefaultCAProfile.java
@@ -17,6 +17,7 @@
 
 package org.apache.hadoop.hdds.security.x509.certificate.authority.profile;
 
+import java.util.HashMap;
 import java.util.Map;
 import java.util.function.BiPredicate;
 import org.bouncycastle.asn1.ASN1ObjectIdentifier;
@@ -33,6 +34,14 @@ public class DefaultCAProfile extends DefaultProfile {
   private static final BiPredicate<Extension, PKIProfile>
       VALIDATE_BASIC_CONSTRAINTS = DefaultCAProfile::validateBasicExtensions;
 
+  // Basic constraints are accepted by the CA profile only.
+  private static final Map<ASN1ObjectIdentifier, BiPredicate<Extension, 
PKIProfile>> CA_EXTENSIONS_MAP =
+      new HashMap<>(EXTENSIONS_MAP);
+
+  static {
+    CA_EXTENSIONS_MAP.put(Extension.basicConstraints, 
VALIDATE_BASIC_CONSTRAINTS);
+  }
+
   private static boolean validateBasicExtensions(Extension ext,
       PKIProfile pkiProfile) {
     BasicConstraints constraints =
@@ -48,10 +57,7 @@ public boolean isCA() {
   @Override
   public Map<ASN1ObjectIdentifier,
       BiPredicate<Extension, PKIProfile>> getExtensionsMap() {
-    // Add basic constraint.
-    EXTENSIONS_MAP.putIfAbsent(Extension.basicConstraints,
-        VALIDATE_BASIC_CONSTRAINTS);
-    return EXTENSIONS_MAP;
+    return CA_EXTENSIONS_MAP;
   }
 
   @Override
diff --git 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/authority/profile/DefaultProfile.java
 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/authority/profile/DefaultProfile.java
index 6d5c2d21b1e..b52a8a5b7f3 100644
--- 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/authority/profile/DefaultProfile.java
+++ 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/authority/profile/DefaultProfile.java
@@ -269,7 +269,7 @@ public boolean validateExtension(Extension extension) {
       return false;
     }
 
-    return EXTENSIONS_MAP.getOrDefault(extension.getExtnId(), (x, y) -> false)
+    return getExtensionsMap().getOrDefault(extension.getExtnId(), (x, y) -> 
false)
         .test(extension, this);
   }
 
diff --git 
a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultCAServer.java
 
b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultCAServer.java
index be717dab749..31f77628fbe 100644
--- 
a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultCAServer.java
+++ 
b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultCAServer.java
@@ -264,7 +264,8 @@ public void testBasicConstraintsAllowedForScmRoleOnly() 
throws Exception {
     ExecutionException execution = assertThrows(ExecutionException.class,
         () -> testCA.requestCertificate(caCsr, 
CertificateApprover.ApprovalType.TESTING_AUTOMATIC, OM,
             String.valueOf(System.nanoTime())).get());
-    assertThat(execution.getCause().getMessage()).contains("allowed for the 
SCM role only, not for OM");
+    // The leaf profile used for other roles rejects the CA constraint before 
the role check.
+    assertThat(execution.getCause().getMessage()).contains("Failed to verify 
the CSR");
     assertThat(caStore.getStoredCertificates()).isEmpty();
 
     X509Certificate scmCert = 
CertificateCodec.firstCertificateFrom(testCA.requestCertificate(caCsr,
diff --git 
a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultProfile.java
 
b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultProfile.java
index 06ca02857e9..c0ec1d8a88c 100644
--- 
a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultProfile.java
+++ 
b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultProfile.java
@@ -34,13 +34,16 @@
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.hdds.security.SecurityConfig;
 import org.apache.hadoop.hdds.security.exception.SCMSecurityException;
+import 
org.apache.hadoop.hdds.security.x509.certificate.authority.profile.DefaultCAProfile;
 import 
org.apache.hadoop.hdds.security.x509.certificate.authority.profile.DefaultProfile;
 import 
org.apache.hadoop.hdds.security.x509.certificate.utils.CertificateSignRequest;
 import org.apache.hadoop.hdds.security.x509.keys.HDDSKeyGenerator;
+import org.bouncycastle.asn1.DEROctetString;
 import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
 import org.bouncycastle.asn1.x500.X500Name;
 import org.bouncycastle.asn1.x500.X500NameBuilder;
 import org.bouncycastle.asn1.x500.style.BCStyle;
+import org.bouncycastle.asn1.x509.BasicConstraints;
 import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
 import org.bouncycastle.asn1.x509.Extension;
 import org.bouncycastle.asn1.x509.Extensions;
@@ -352,6 +355,18 @@ private PKCS10CertificationRequest getInvalidCSR(KeyPair 
kPair,
     return p10Builder.build(signer);
   }
 
+  /**
+   * Basic constraints, which make a certificate a CA, are accepted by the CA 
profile only.
+   */
+  @Test
+  void testBasicConstraintsOnlyInCAProfile() throws IOException {
+    Extension ca = new Extension(Extension.basicConstraints, true, new 
DEROctetString(new BasicConstraints(true)));
+
+    assertThat(new DefaultCAProfile().validateExtension(ca)).isTrue();
+    
assertThat(defaultProfile.getSupportedExtensions()).doesNotContain(Extension.basicConstraints);
+    assertThat(defaultProfile.validateExtension(ca)).isFalse();
+  }
+
   /**
    * Generate an Extension with rfc822Name.
    * @param extensionCode - Extension Code.
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMSecurityProtocolServer.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMSecurityProtocolServer.java
index dca9d0bcc38..586eb076b5e 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMSecurityProtocolServer.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMSecurityProtocolServer.java
@@ -17,6 +17,9 @@
 
 package org.apache.hadoop.hdds.scm.server;
 
+import static 
org.apache.hadoop.hdds.HddsConfigKeys.HDDS_DATANODE_KERBEROS_PRINCIPAL_KEY;
+import static 
org.apache.hadoop.hdds.recon.ReconConfig.ConfigStrings.OZONE_RECON_KERBEROS_PRINCIPAL_KEY;
+import static 
org.apache.hadoop.hdds.scm.ScmConfig.ConfigStrings.HDDS_SCM_KERBEROS_PRINCIPAL_KEY;
 import static 
org.apache.hadoop.hdds.scm.ScmUtils.checkIfCertSignRequestAllowed;
 import static org.apache.hadoop.hdds.scm.ha.SequenceIdGenerator.CERTIFICATE_ID;
 import static 
org.apache.hadoop.hdds.security.exception.SCMSecretKeyException.ErrorCode.SECRET_KEY_NOT_ENABLED;
@@ -24,6 +27,7 @@
 import static 
org.apache.hadoop.hdds.security.exception.SCMSecurityException.ErrorCode.CERTIFICATE_NOT_FOUND;
 import static 
org.apache.hadoop.hdds.security.exception.SCMSecurityException.ErrorCode.GET_CA_CERT_FAILED;
 import static 
org.apache.hadoop.hdds.security.exception.SCMSecurityException.ErrorCode.GET_CERTIFICATE_FAILED;
+import static 
org.apache.hadoop.hdds.security.exception.SCMSecurityException.ErrorCode.UNABLE_TO_ISSUE_CERTIFICATE;
 import static 
org.apache.hadoop.hdds.security.x509.certificate.authority.CertificateApprover.ApprovalType.KERBEROS_TRUSTED;
 import static 
org.apache.hadoop.hdds.security.x509.certificate.utils.CertificateCodec.getPEMEncodedString;
 import static 
org.apache.hadoop.hdds.security.x509.certificate.utils.CertificateSignRequest.getCertificationRequest;
@@ -342,6 +346,7 @@ private synchronized String getEncodedCertToString(String 
certSignReq,
       // SCM role certificates are CA certificates and are issued to SCM 
admins only, the check addSCM applies.
       storageContainerManager.checkAdminAccess(getRpcRemoteUser(), false);
     }
+    checkRequesterIsService(nodeType);
     Future<CertPath> future;
     PKCS10CertificationRequest csr = getCertificationRequest(certSignReq);
     if (nodeType == NodeType.SCM && rootCertificateServer != null) {
@@ -369,6 +374,35 @@ private synchronized String getEncodedCertToString(String 
certSignReq,
     }
   }
 
+  /**
+   * A certificate for a role is only issued to the service user of that role.
+   */
+  private void checkRequesterIsService(NodeType role) throws IOException {
+    final String principalKey = getKerberosPrincipalKey(role);
+    final UserGroupInformation user = HddsServerUtil.getRemoteUser();
+    if (principalKey == null || !HddsServerUtil.isServiceUser(user, 
config.get(principalKey, ""))) {
+      throw new SCMSecurityException("User " + user.getUserName() + " is not 
allowed to request a " + role
+          + " certificate, it does not match the principal configured as " + 
principalKey + " on SCM.",
+          UNABLE_TO_ISSUE_CERTIFICATE);
+    }
+  }
+
+  private static String getKerberosPrincipalKey(NodeType role) {
+    switch (role) {
+    case DATANODE:
+      return HDDS_DATANODE_KERBEROS_PRINCIPAL_KEY;
+    case OM:
+      // TODO: move OMConfigKeys.OZONE_OM_KERBEROS_PRINCIPAL_KEY to 
hdds-common.
+      return "ozone.om.kerberos.principal";
+    case SCM:
+      return HDDS_SCM_KERBEROS_PRINCIPAL_KEY;
+    case RECON:
+      return OZONE_RECON_KERBEROS_PRINCIPAL_KEY;
+    default:
+      return null;
+    }
+  }
+
   private SCMSecurityException generateException(Exception ex, NodeType role) {
     SCMSecurityException.ErrorCode errorCode;
     if (role == NodeType.SCM) {
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/TestHddsServerUtil.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/TestHddsServerUtil.java
index 6feba1a48f3..84fb7dc8d4b 100644
--- 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/TestHddsServerUtil.java
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/TestHddsServerUtil.java
@@ -17,6 +17,10 @@
 
 package org.apache.hadoop.hdds.scm;
 
+import static org.apache.hadoop.hdds.utils.HddsServerUtil.isServiceUser;
+import static org.apache.hadoop.security.UserGroupInformation.createProxyUser;
+import static org.apache.hadoop.security.UserGroupInformation.createRemoteUser;
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 
 import java.net.InetSocketAddress;
@@ -24,6 +28,7 @@
 import org.apache.hadoop.hdds.scm.ha.SCMNodeInfo;
 import org.apache.hadoop.hdds.utils.HddsServerUtil;
 import org.apache.hadoop.net.NetUtils;
+import org.apache.hadoop.security.UserGroupInformation;
 import org.junit.jupiter.api.Test;
 
 /**
@@ -169,4 +174,16 @@ public void testScmDataNodeBindHostDefault() {
     assertEquals(200, addr.getPort());
   }
 
+  @Test
+  void testIsServiceUser() {
+    UserGroupInformation.setConfiguration(new OzoneConfiguration());
+    String principal = "om/[email protected]";
+    assertThat(isServiceUser(createRemoteUser("om/[email protected]"), 
principal)).isTrue();
+    for (String user : new String[] {"[email protected]", "om/[email protected]", 
"om/host1", "alice/[email protected]"}) {
+      assertThat(isServiceUser(createRemoteUser(user), 
principal)).as(user).isFalse();
+    }
+    assertThat(isServiceUser(createProxyUser("om/[email protected]", 
createRemoteUser("alice")), principal)).isFalse();
+    // No user matches a principal that is not configured.
+    assertThat(isServiceUser(createRemoteUser("om/[email protected]"), 
"")).isFalse();
+  }
 }
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/TestSecureOzoneCluster.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/TestSecureOzoneCluster.java
index cef7ed43178..f69757bdfd0 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/TestSecureOzoneCluster.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/TestSecureOzoneCluster.java
@@ -56,6 +56,7 @@
 import static 
org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod.KERBEROS;
 import static org.apache.ozone.test.GenericTestUtils.PortAllocator.getFreePort;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -98,6 +99,7 @@
 import org.apache.commons.validator.routines.DomainValidator;
 import org.apache.hadoop.hdds.HddsConfigKeys;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.MockDatanodeDetails;
 import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
 import org.apache.hadoop.hdds.protocol.proto.SCMSecurityProtocolProtos;
 import 
org.apache.hadoop.hdds.protocol.proto.SCMSecurityProtocolProtos.SCMGetCertResponseProto;
@@ -398,6 +400,8 @@ void testSCMSecurityProtocol() throws Exception {
             () -> securityClient.getCertificate("1"));
         assertThat(ioException).hasMessageContaining(cannotAuthMessage);
       }
+
+      assertScmIssuesCertificateOnlyToServiceUserOfRole();
     } finally {
       if (scm != null) {
         scm.stop();
@@ -405,6 +409,57 @@ void testSCMSecurityProtocol() throws Exception {
     }
   }
 
+  /** SCM security protocol - a certificate is only issued to the service user 
of the requested role. */
+  private void assertScmIssuesCertificateOnlyToServiceUserOfRole() throws 
Exception {
+    String csr = newCsr(false);
+    HddsProtos.ScmNodeDetailsProto scmInfo = 
HddsProtos.ScmNodeDetailsProto.newBuilder()
+        
.setClusterId(clusterId).setHostName("localhost").setScmNodeId(scmId).build();
+
+    UserGroupInformation testUser = 
UserGroupInformation.loginUserFromKeytabAndReturnUGI(
+        testUserPrincipal, testUserKeytab.getCanonicalPath());
+    try (SCMSecurityProtocolClientSideTranslatorPB securityClient = 
getScmSecurityClient(conf, testUser)) {
+      assertThatThrownBy(() -> securityClient.getOMCertificate(omInfo, csr))
+          .hasMessageContaining("is not allowed to request a OM certificate");
+      assertThatThrownBy(() -> securityClient.getDataNodeCertificate(
+          MockDatanodeDetails.randomDatanodeDetails().getProtoBufMessage(), 
csr))
+          .hasMessageContaining("is not allowed to request a DATANODE 
certificate");
+      // SCM role certificates are refused to non admins before the service 
user check.
+      assertThatThrownBy(() -> securityClient.getSCMCertificate(scmInfo, 
csr)).hasMessageContaining("Access denied");
+      assertThatThrownBy(() -> 
securityClient.getCertificate(HddsProtos.NodeDetailsProto.newBuilder()
+          
.setUuid(omId).setClusterId(clusterId).setHostName("localhost").setNodeType(HddsProtos.NodeType.RECON)
+          .build(), csr))
+          .hasMessageContaining("is not allowed to request a RECON 
certificate");
+    }
+
+    UserGroupInformation omUser = 
UserGroupInformation.loginUserFromKeytabAndReturnUGI(
+        conf.get(OZONE_OM_KERBEROS_PRINCIPAL_KEY), 
conf.get(OZONE_OM_KERBEROS_KEYTAB_FILE_KEY));
+    try (SCMSecurityProtocolClientSideTranslatorPB securityClient = 
getScmSecurityClient(conf, omUser)) {
+      // OM gets a certificate for itself, but not one that can sign other 
certificates.
+      String caCsr = newCsr(true);
+      assertThatThrownBy(() -> securityClient.getOMCertificate(omInfo, caCsr))
+          .hasMessageContaining("Failed to verify the CSR");
+      assertThat(securityClient.getOMCertificate(omInfo, csr)).isNotEmpty();
+      // The service user of one role does not get a certificate of another 
role.
+      assertThatThrownBy(() -> securityClient.getDataNodeCertificate(
+          MockDatanodeDetails.randomDatanodeDetails().getProtoBufMessage(), 
csr))
+          .hasMessageContaining("is not allowed to request a DATANODE 
certificate");
+    }
+  }
+
+  private String newCsr(boolean ca) throws Exception {
+    CertificateSignRequest.Builder csrBuilder = new 
CertificateSignRequest.Builder()
+        .setKey(keyPair)
+        .setConfiguration(new SecurityConfig(conf))
+        .setScmID(scmId)
+        .setClusterID(clusterId)
+        .setSubject("test")
+        .setCA(ca)
+        .setDigitalSignature(true)
+        .setDigitalEncryption(true);
+    addIpAndDnsDataToBuilder(csrBuilder);
+    return csrBuilder.build().toEncodedFormat();
+  }
+
   @Test
   void testAdminAccessControlException() throws Exception {
     initSCM();


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to