[ 
https://issues.apache.org/jira/browse/KNOX-3574?focusedWorklogId=1055731&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-1055731
 ]

ASF GitHub Bot logged work on KNOX-3574:
----------------------------------------

                Author: ASF GitHub Bot
            Created on: 18/Nov/26 15:43
            Start Date: 18/Nov/26 15:43
    Worklog Time Spent: 10m 
      Work Description: smolnar82 commented on code in PR #1523:
URL: https://github.com/apache/knox/pull/1523#discussion_r4616136266


##########
gateway-server/src/main/java/org/apache/knox/gateway/services/ldap/backend/LdapProxyBackend.java:
##########
@@ -586,8 +769,8 @@ public List<Entry> search(String searchBase, SearchScope 
searchScope, String fil
         try {
             connection = getConnection();
             List<Entry> results = new ArrayList<>();
-            boolean memberOfRequested = isAttributeRequested(attributes, 
proxyEntryGroupMembershipAttributeType, schemaManager);
-            String[] remoteAttributes = memberOfRequested && useMemberOf ? 
ALL_ATTRIBUTES_AND_MEMBEROF : ALL_ATTRIBUTES;
+            boolean memberOfRequested = isAttributeRequested(attributes, 
MEMBER_OF, schemaManager);
+            String[] remoteAttributes = memberOfRequested && useMemberOf ? 
addMemberOfAttribute(attributes) : attributes;

Review Comment:
   With this change, the remote search only asks for the attributes the client 
requested. But `RemoteSchemaConverter.convertRemoteEntryToProxyEntry` needs two 
attributes the client normally doesn't request:
   
   - `objectClass`: `LdapUtils.isUserEntry(entry)` relies on it to decide 
whether to map the identifier to `uid`, and the user/group objectClass rewrite 
needs it too.
   - `remoteUserIdentifierAttribute` (`sAMAccountName` on AD): this is the 
source of `uid`.
   
   Take a request for `uid` against AD. The remote search asks for `uid`, AD 
has no such attribute, and the proxy entry comes back without `uid`. 
`LDAPRolesLookupInterceptor` augments the request with `uid`/`objectClass` 
precisely so it can resolve roles. With no `uid` it falls back to `cn`, the 
display name, so roles are looked up for the wrong id. A plain `ldapsearch ... 
uid` against an AD backend also stops returning `uid`, which works on master 
today because we send `*`.
   
   Suggestion: unless `*` is already in the list, always add the attributes the 
converter depends on. Something like:
   
   ```java
   private String[] toRemoteAttributes(String[] attributes, boolean 
addMemberOf) {
       final Set<String> remote = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
       remote.addAll(Arrays.asList(attributes));
       if (!remote.contains("*")) {
           remote.add("objectClass");
           remote.add(remoteUserIdentifierAttribute);
       }
       if (addMemberOf) {
           remote.add(MEMBER_OF);
       }
       return remote.toArray(new String[0]);
   }
   ```
   
   This could also replace `addMemberOfAttribute`.
   
   Please also add a test with `userIdentifierAttribute=sAMAccountName` that 
requests only `uid` and asserts `uid` is populated. It should also assert that 
the extra attributes don't leak into the response when the client didn't ask 
for them.
   



##########
gateway-server/src/main/java/org/apache/knox/gateway/services/ldap/SchemaManagerFactory.java:
##########
@@ -110,5 +111,35 @@ private static void 
getActiveDirectoryAttributeTypes(List<AttributeType> userAtt
         userAccountControlAttrType.setOrderingOid("2.5.13.15"); // 
integerorderingmatch
         userAccountControlAttrType.setSingleValued(true);
         userAttributes.add(userAccountControlAttrType);
+
+        // whenChanged and objectGUID exist on every Active Directory object 
(users and groups) and
+        // are read-only. whenChanged is operational (returned only when 
explicitly requested), which
+        // is the main reason KNOX-3574 passes requested attributes through to 
the backend.
+        AttributeType whenChangedAttrType = new 
AttributeType("1.2.840.113556.1.2.3");
+        whenChangedAttrType.setNames("whenChanged");
+        whenChangedAttrType.setSchemaName("other");
+        whenChangedAttrType.setSyntaxOid("1.3.6.1.4.1.1466.115.121.1.24"); // 
generalized time
+        whenChangedAttrType.setEqualityOid("2.5.13.27"); // 
generalizedtimematch
+        whenChangedAttrType.setOrderingOid("2.5.13.28"); // 
generalizedtimeorderingmatch
+        whenChangedAttrType.setDescription("Microsoft Active Directory 
whenChanged modification timestamp (operational)");
+        whenChangedAttrType.setSingleValued(true);
+        whenChangedAttrType.setUserModifiable(false);
+        whenChangedAttrType.setUsage(UsageEnum.DIRECTORY_OPERATION);
+        userAttributes.add(whenChangedAttrType);
+        groupAttributes.add(whenChangedAttrType);
+
+        AttributeType objectGuidAttrType = new 
AttributeType("1.2.840.113556.1.4.2");

Review Comment:
   This PR makes `objectGUID` a built-in attribute, which means it will now 
actually be returned to clients, but its values come back corrupted.
   
   `RemoteSchemaConverter.copyAttribute` copies each value via 
`value.toString()`. For a binary value that is the hex dump string, not the raw 
bytes. The sample output in the PR description shows it: `objectGUID:: 
MHgxOSAweEIx...` base64-decodes to the text `0x19 0xB1 ...` instead of the 
16-byte GUID. Clients that key on `objectGUID` (sync tools, IdM connectors) 
would get a different, invalid value. The same applies to any `extraAttributes` 
entry that falls back to the octet-string syntax in `resolvedSyntaxOid`.
   
   `copyAttribute` isn't touched by this diff, but this PR is what exposes it. 
Suggested fix in `RemoteSchemaConverter.copyAttribute`:
   
   ```java
   for (Value value : attribute) {
       try {
           if (!value.isHumanReadable()) {
               if (!target.contains(attributeName, value.getBytes())) {
                   target.add(attributeName, value.getBytes());
               }
               continue;
           }
           String valueString = convertDn ? 
convertRemoteDnToProxyDn(value.getString()) : value.getString();
           if (!target.contains(attributeName, valueString)) {
               target.add(attributeName, valueString);
           }
       } catch (LdapException e) {
           LOG.ldapAttributeCopyError(e);
       }
   }
   ```
   
   Alternatively, leave `objectGUID` out of the built-ins until the copy is 
fixed in a follow-up. Either way, a test that round-trips a 16-byte 
`objectGUID` and asserts byte equality would cover it.
   



##########
gateway-server/src/main/java/org/apache/knox/gateway/services/ldap/KnoxLDAPServerManager.java:
##########
@@ -316,6 +316,10 @@ public void start() throws Exception {
 
         // Create SchemaManager
         SchemaManager schemaManager = 
SchemaManagerFactory.createSchemaManager();
+        // Enrich the schema with attribute types defined on the remote 
backends (e.g. operational
+        // attributes) so the proxy can recognise and request them. Done 
before the schema partition
+        // is built so the merged attribute types are in place for the 
lifetime of the service.
+        loadRemoteBackendSchemas(schemaManager);

Review Comment:
   **Follow-up (non-blocking):** `loadRemoteBackendSchemas` runs synchronously 
during LDAP service start. For each backend with `extraAttributes` set, it 
opens a connection to the remote server and reads its full schema 
(`loadAllEnabledRelaxed()`), one backend after another.
   
   If a backend is unreachable or slow at boot, startup blocks for the 
connect/response timeout of each such backend. When `connectionTimeout` isn't 
set, that's the LDAP API default (30s). This degrades correctly, since the 
failure is caught and logged. It's just slow, and it only affects backends that 
set `extraAttributes`.
   
   Could be addressed in a follow-up:
   - Document in `service_ldap_server.md` that `extraAttributes` causes a 
schema read at startup, and recommend setting `connectionTimeout`.
   - Or load the remote schemas in parallel, or bound the whole step with an 
overall timeout.
   



##########
gateway-server/src/main/java/org/apache/knox/gateway/services/ldap/backend/LdapProxyBackend.java:
##########
@@ -462,6 +474,170 @@ private void releaseConnection(LdapConnection connection) 
{
         }
     }
 
+    /**
+     * Imports the operator-declared {@code extraAttributes} from the remote 
LDAP server's schema
+     * into the shared schema manager, so the proxy can recognise and request 
them (e.g. operational
+     * attributes like whenChanged). Only the configured attributes are 
imported — the remote schema
+     * is never trusted wholesale — and each imported definition comes from 
the remote server, so its
+     * syntax and usage are authoritative. Attribute types already registered 
(by OID) are left
+     * untouched, so the hardcoded definitions in {@code SchemaManagerFactory} 
always win. A configured
+     * attribute that the remote server does not publish is logged as an error 
and skipped.
+     * <p>
+     * Any failure (the remote server being unreachable, not publishing a 
schema, or a single
+     * attribute type that cannot be resolved against the bundled 
syntaxes/matching rules) is
+     * logged and skipped rather than propagated, so a backend's schema being 
unavailable never
+     * prevents the embedded LDAP service from starting.
+     */
+    @Override
+    public void loadRemoteSchema(SchemaManager schemaManager) {
+        if (extraAttributes == null || extraAttributes.length == 0) {
+            // Nothing declared to import; do not even contact the remote 
server.
+            return;
+        }
+        LdapConnection connection = null;
+        try {
+            connection = getConnection();
+            // Quirks mode (the second argument) relaxes the schema parser so 
non-RFC-4512 schemas
+            // load instead of failing. Active Directory in particular 
publishes attribute type and
+            // object class descriptions with non-numeric OIDs and missing 
elements that the strict
+            // parser rejects with ERR_13787_OID_EXPECTED.
+            final DefaultSchemaLoader remoteLoader = new 
DefaultSchemaLoader(connection, true);
+            final SchemaManager remoteSchemaManager = new 
DefaultSchemaManager(remoteLoader);
+            // Relaxed loading so an incomplete or non-standard remote schema 
yields what it can
+            // instead of failing wholesale.
+            remoteSchemaManager.loadAllEnabledRelaxed();
+            importConfiguredAttributeTypes(schemaManager, remoteSchemaManager);
+        } catch (Exception e) {
+            LOG.ldapRemoteSchemaLoadFailed(getName(), e);
+        } finally {
+            releaseConnection(connection);
+        }
+    }
+
+    /**
+     * Imports each configured {@code extraAttributes} entry from {@code 
remoteSchemaManager} into
+     * {@code schemaManager}, using the remote server's own definition. 
Attributes the remote server
+     * does not publish are logged and skipped. Separated from the connection 
handling in
+     * {@link #loadRemoteSchema(SchemaManager)} so the import can be exercised 
without a live server.
+     */
+    void importConfiguredAttributeTypes(SchemaManager schemaManager, 
SchemaManager remoteSchemaManager) {
+        if (extraAttributes == null) {
+            return;
+        }
+        int imported = 0;
+        for (String attributeName : extraAttributes) {
+            final AttributeType remoteType = 
remoteSchemaManager.getAttributeType(attributeName);
+            if (remoteType == null || remoteType.getOid() == null) {
+                // Configured but not published by the remote server: almost 
always a typo or an
+                // attribute that does not exist on this directory. Surface it 
rather than ignore it.
+                LOG.ldapConfiguredAttributeNotInRemoteSchema(getName(), 
attributeName);
+                continue;
+            }
+            if (registerRemoteAttributeType(schemaManager, remoteType)) {
+                imported++;
+            }
+        }
+        LOG.ldapRemoteSchemaLoaded(getName(), imported);
+    }
+
+    /**
+     * Registers a single remote attribute type into the target schema 
manager, unless an attribute
+     * type with the same OID is already present. The definition is rebuilt as 
a standalone attribute
+     * type whose syntax and matching rules are expressed by OID so that the 
target manager resolves
+     * them against its own (bundled) registries; its superior chain is 
flattened for the same reason.
+     *
+     * @return true if a new attribute type was added, false if it already 
existed or could not be added
+     */
+    boolean registerRemoteAttributeType(SchemaManager schemaManager, 
AttributeType remoteType) {
+        final String oid = remoteType.getOid();
+        if (oid == null || 
schemaManager.getAttributeTypeRegistry().contains(oid)) {
+            return false;
+        }
+        try {
+            final AttributeType attributeType = 
toStandaloneAttributeType(schemaManager, remoteType);
+            final boolean addedToManager = schemaManager.add(attributeType);
+            if (!addedToManager) {
+                // add() records the reason (e.g. an unresolved syntax) in the 
manager's error list
+                // rather than throwing; surface it and move on so one bad 
definition is skipped.
+                LOG.ldapRemoteAttributeTypeSkipped(getName(), oid, 
String.valueOf(schemaManager.getErrors()));

Review Comment:
   **Follow-up (non-blocking):** these attributes are ones the operator 
explicitly listed in `extraAttributes`, so failing to import one should be 
visible at the default log level. Right now both failure paths log at DEBUG 
only: `ldapRemoteAttributeTypeSkipped` here, and `ldapRemoteAttributeTypeError` 
in the catch below. A typo'd name, by contrast, is logged at ERROR 
(`ldapConfiguredAttributeNotInRemoteSchema`).
   
   One case where this bites: the pre-check above only looks for an existing 
OID. A remote attribute with a different OID but the same name or alias as a 
bundled attribute fails in `schemaManager.add(...)` on the name collision. The 
operator only sees `Imported 0 configured attribute type(s)` at INFO and has no 
idea why.
   
   Suggestion:
   - Log both messages at WARN, and include the attribute name, not just the 
OID.
   - Optionally check the name as well 
(`schemaManager.getAttributeTypeRegistry().contains(remoteType.getName())`) and 
log a specific "name already defined locally with OID X" message.
   





Issue Time Tracking
-------------------

    Worklog Id:     (was: 1055731)
    Time Spent: 40m  (was: 0.5h)

> LDAP proxy backend returns operational attributes
> -------------------------------------------------
>
>                 Key: KNOX-3574
>                 URL: https://issues.apache.org/jira/browse/KNOX-3574
>             Project: Apache Knox
>          Issue Type: Improvement
>          Components: LDAP
>    Affects Versions: 3.0.0
>            Reporter: David Han
>            Assignee: David Han
>            Priority: Major
>             Fix For: 3.1.0
>
>          Time Spent: 40m
>  Remaining Estimate: 0h
>
> The returned attributes from the search should be passed directly to the 
> backend so that operational attributes will be returned when specified.



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to