mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Nemanja Lukic
19.53.2012 d109b49627501575f3c8a9da429f72097601615f
Implementaion of OPENDJ-441 - Operational attribute for password expiration time

4 files added
3 files modified
601 ■■■■■ changed files
opends/resource/config/config.ldif 10 ●●●●● patch | view | raw | blame | history
opends/resource/schema/02-config.ldif 15 ●●●●● patch | view | raw | blame | history
opends/src/admin/defn/org/opends/server/admin/std/PasswordExpirationTimeVirtualAttributeConfiguration.xml 69 ●●●●● patch | view | raw | blame | history
opends/src/admin/messages/PasswordExpirationTimeVirtualAttributeCfgDefn.properties 24 ●●●●● patch | view | raw | blame | history
opends/src/messages/messages/extension.properties 2 ●●●●● patch | view | raw | blame | history
opends/src/server/org/opends/server/extensions/PasswordExpirationTimeVirtualAttributeProvider.java 233 ●●●●● patch | view | raw | blame | history
opends/tests/unit-tests-testng/src/server/org/opends/server/extensions/PasswordExpirationTimeVirtualAttributeProviderTestCase.java 248 ●●●●● patch | view | raw | blame | history
opends/resource/config/config.ldif
@@ -2500,6 +2500,16 @@
ds-cfg-checksum-algorithm: adler-32
ds-cfg-excluded-attribute: ds-sync-hist
dn: cn=Password Expiration Time,cn=Virtual Attributes,cn=config
objectClass: top
objectClass: ds-cfg-virtual-attribute
objectClass: ds-cfg-password-expiration-time-virtual-attribute
cn: Password Expiration Time
ds-cfg-java-class: org.opends.server.extensions.PasswordExpirationTimeVirtualAttributeProvider
ds-cfg-enabled: true
ds-cfg-attribute-type: ds-pwp-password-expiration-time
ds-cfg-conflict-behavior: virtual-overrides-real
dn: cn=Work Queue,cn=config
objectClass: top
objectClass: ds-cfg-work-queue
opends/resource/schema/02-config.ldif
@@ -3316,6 +3316,16 @@
  EQUALITY caseIgnoreMatch
  SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
  X-ORIGIN 'OpenDJ Directory Server' )
attributeTypes: ( 1.3.6.1.4.1.36733.2.1.1.60
  NAME ( 'ds-pwp-password-expiration-time'
  'pwdExpirationTime' )
  EQUALITY generalizedTimeMatch
  ORDERING generalizedTimeOrderingMatch
  SYNTAX 1.3.6.1.4.1.1466.115.121.1.24
  SINGLE-VALUE
  NO-USER-MODIFICATION
  USAGE directoryOperation
  X-ORIGIN 'OpenDJ Directory Server' )
objectClasses: ( 1.3.6.1.4.1.26027.1.2.1
  NAME 'ds-cfg-access-control-handler'
  SUP top
@@ -5120,3 +5130,8 @@
  MAY ( ds-cfg-checksum-algorithm $
        ds-cfg-excluded-attribute )
  X-ORIGIN 'OpenDJ Directory Server' )
objectClasses: ( 1.3.6.1.4.1.36733.2.1.2.9
  NAME 'ds-cfg-password-expiration-time-virtual-attribute'
  SUP ds-cfg-virtual-attribute
  STRUCTURAL
  X-ORIGIN 'OpenDJ Directory Server' )
opends/src/admin/defn/org/opends/server/admin/std/PasswordExpirationTimeVirtualAttributeConfiguration.xml
New file
@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ! CDDL HEADER START
  !
  ! The contents of this file are subject to the terms of the
  ! Common Development and Distribution License, Version 1.0 only
  ! (the "License").  You may not use this file except in compliance
  ! with the License.
  !
  ! You can obtain a copy of the license at
  ! trunk/opends/resource/legal-notices/CDDLv1_0.txt
  ! or http://forgerock.org/license/CDDLv1.0.html.
  ! See the License for the specific language governing permissions
  ! and limitations under the License.
  !
  ! When distributing Covered Code, include this CDDL HEADER in each
  ! file and include the License file at
  ! trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
  ! add the following below this CDDL HEADER, with the fields enclosed
  ! by brackets "[]" replaced with your own identifying information:
  !      Portions Copyright [yyyy] [name of copyright owner]
  !
  ! CDDL HEADER END
  !
  !
  !      Copyright 2012 profiq s.r.o.
  ! -->
<adm:managed-object name="password-expiration-time-virtual-attribute"
  plural-name="password-expiration-time-virtual-attribute"
  package="org.opends.server.admin.std" extends="virtual-attribute"
  xmlns:adm="http://www.opends.org/admin"
  xmlns:ldap="http://www.opends.org/admin-ldap">
  <adm:synopsis>
    The
    <adm:user-friendly-name />
    generates a virtual attribute which shows the password expiration date.
  </adm:synopsis>
  <adm:profile name="ldap">
    <ldap:object-class>
      <ldap:name>
        ds-cfg-password-expiration-time-virtual-attribute
      </ldap:name>
      <ldap:superior>ds-cfg-virtual-attribute</ldap:superior>
    </ldap:object-class>
  </adm:profile>
  <adm:property-override name="java-class" advanced="true">
    <adm:default-behavior>
      <adm:defined>
        <adm:value>
          org.opends.server.extensions.PasswordExpirationTimeVirtualAttributeProvider
        </adm:value>
      </adm:defined>
    </adm:default-behavior>
  </adm:property-override>
  <adm:property-override name="conflict-behavior" advanced="true">
    <adm:default-behavior>
      <adm:defined>
        <adm:value>virtual-overrides-real</adm:value>
      </adm:defined>
    </adm:default-behavior>
  </adm:property-override>
  <adm:property-override name="attribute-type">
    <adm:default-behavior>
      <adm:defined>
        <adm:value>ds-pwp-password-expiration-time</adm:value>
      </adm:defined>
    </adm:default-behavior>
  </adm:property-override>
</adm:managed-object>
opends/src/admin/messages/PasswordExpirationTimeVirtualAttributeCfgDefn.properties
New file
@@ -0,0 +1,24 @@
user-friendly-name=Password Expiration Time Virtual Attribute
user-friendly-plural-name=Password Expiration Time Virtual Attribute
synopsis=The Password Expiration Time Virtual Attribute generates a virtual attribute which shows the password expiration date.
property.attribute-type.synopsis=Specifies the attribute type for the attribute whose values are to be dynamically assigned by the virtual attribute.
property.base-dn.synopsis=Specifies the base DNs for the branches containing entries that are eligible to use this virtual attribute.
property.base-dn.description=If no values are given, then the server generates virtual attributes anywhere in the server.
property.base-dn.default-behavior.alias.synopsis=The location of the entry in the server is not taken into account when determining whether an entry is eligible to use this virtual attribute.
property.conflict-behavior.synopsis=Specifies the behavior that the server is to exhibit for entries that already contain one or more real values for the associated attribute.
property.conflict-behavior.syntax.enumeration.value.merge-real-and-virtual.synopsis=Indicates that the virtual attribute provider is to preserve any real values contained in the entry and merge them with the set of generated virtual values so that both the real and virtual values are used.
property.conflict-behavior.syntax.enumeration.value.real-overrides-virtual.synopsis=Indicates that any real values contained in the entry are preserved and used, and virtual values are not generated.
property.conflict-behavior.syntax.enumeration.value.virtual-overrides-real.synopsis=Indicates that the virtual attribute provider suppresses any real values contained in the entry and generates virtual values and uses them.
property.enabled.synopsis=Indicates whether the Password Expiration Time Virtual Attribute is enabled for use.
property.filter.synopsis=Specifies the search filters to be applied against entries to determine if the virtual attribute is to be generated for those entries.
property.filter.description=If no values are given, then any entry is eligible to have the value generated. If one or more filters are specified, then only entries that match at least one of those filters are allowed to have the virtual attribute.
property.filter.syntax.string.pattern.synopsis=Any valid search filter string.
property.group-dn.synopsis=Specifies the DNs of the groups whose members can be eligible to use this virtual attribute.
property.group-dn.description=If no values are given, then group membership is not taken into account when generating the virtual attribute. If one or more group DNs are specified, then only members of those groups are allowed to have the virtual attribute.
property.group-dn.default-behavior.alias.synopsis=Group membership is not taken into account when determining whether an entry is eligible to use this virtual attribute.
property.java-class.synopsis=Specifies the fully-qualified name of the virtual attribute provider class that generates the attribute values.
property.scope.synopsis=Specifies the LDAP scope associated with base DNs for entries that are eligible to use this virtual attribute.
property.scope.syntax.enumeration.value.base-object.synopsis=Search the base object only.
property.scope.syntax.enumeration.value.single-level.synopsis=Search the immediate children of the base object but do not include any of their descendants or the base object itself.
property.scope.syntax.enumeration.value.subordinate-subtree.synopsis=Search the entire subtree below the base object but do not include the base object itself.
property.scope.syntax.enumeration.value.whole-subtree.synopsis=Search the base object and the entire subtree below the base object.
opends/src/messages/messages/extension.properties
@@ -1518,3 +1518,5 @@
 search bind password
MILD_ERR_ETAG_VATTR_NOT_SEARCHABLE_614=The %s attribute is not \
 searchable and should not be included in otherwise unindexed search filters
MILD_ERR_PWDEXPTIME_VATTR_NOT_SEARCHABLE_615=The %s attribute is not \
 searchable and should not be included in otherwise unindexed search filters
opends/src/server/org/opends/server/extensions/PasswordExpirationTimeVirtualAttributeProvider.java
New file
@@ -0,0 +1,233 @@
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at
 * trunk/opends/resource/legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2012 profiq s.r.o.
 */
package org.opends.server.extensions;
import java.util.Collections;
import org.opends.server.core.PasswordPolicyState;
import java.util.Set;
import org.opends.messages.Message;
import
  org.opends.server.admin.std.server.PasswordExpirationTimeVirtualAttributeCfg;
import org.opends.server.api.AuthenticationPolicy;
import org.opends.server.api.VirtualAttributeProvider;
import org.opends.server.core.SearchOperation;
import org.opends.server.config.ConfigException;
import org.opends.server.loggers.ErrorLogger;
import org.opends.server.loggers.debug.DebugTracer;
import org.opends.server.schema.GeneralizedTimeSyntax;
import org.opends.server.types.*;
import static org.opends.messages.ExtensionMessages.*;
import static org.opends.server.loggers.debug.DebugLogger.*;
import static org.opends.server.util.StaticUtils.*;
/**
 * Provider for the password expiration time virtual attribute.
 */
public class PasswordExpirationTimeVirtualAttributeProvider
  extends VirtualAttributeProvider<PasswordExpirationTimeVirtualAttributeCfg>
{
  /**
   * Debug tracer to log debugging information.
   */
  private static final DebugTracer TRACER = getTracer();
  /**
   * Default constructor.
   */
  public PasswordExpirationTimeVirtualAttributeProvider()
  {
    super();
  }
  /**
   * {@inheritDoc}
   */
  @Override
  public void
    initializeVirtualAttributeProvider(
      PasswordExpirationTimeVirtualAttributeCfg configuration)
    throws ConfigException, InitializationException
  {
    // No initialization needed
  }
  /**
   * {@inheritDoc}
   */
  @Override
  public boolean isMultiValued()
  {
    return false;
  }
  /**
   * {@inheritDoc}
   */
  @Override
  public Set<AttributeValue> getValues(Entry entry,
                                       VirtualAttributeRule rule)
  {
    // Do not process LDAP operational entries.
    if (!entry.isSubentry() && !entry.isLDAPSubentry())
    {
      long expirationTime = getPasswordExpirationTime(entry);
      if (expirationTime == -1)
      {
        // It does not expire.
        return Collections.emptySet();
      }
      AttributeValue value =
        GeneralizedTimeSyntax.createGeneralizedTimeValue(expirationTime);
      return Collections.singleton(value);
    }
    return Collections.emptySet();
  }
  /**
   * {@inheritDoc}
   */
  @Override
  public boolean isSearchable(VirtualAttributeRule rule,
                              SearchOperation searchOperation)
  {
    return false;
  }
  /**
   * {@inheritDoc}
   */
  @Override
  public void processSearch(VirtualAttributeRule rule,
                            SearchOperation searchOperation)
  {
    searchOperation.setResultCode(ResultCode.UNWILLING_TO_PERFORM);
    Message message =
            ERR_PWDEXPTIME_VATTR_NOT_SEARCHABLE.get(
            rule.getAttributeType().getNameOrOID());
    searchOperation.appendErrorMessage(message);
  }
  /**
   * {@inheritDoc}
   */
  @Override
  public boolean hasValue(Entry entry, VirtualAttributeRule rule)
  {
    if (getPasswordExpirationTime(entry) == -1)
    {
      return false;
    }
    return true;
  }
  /**
   * Utility method to wrap the PasswordPolicyState.getExpirationTime().
   *
   * @param entry LDAP entry
   * @return  Expiration time in milliseconds since the epoch.
   */
  private long getPasswordExpirationTime(Entry entry)
  {
    // Do not process LDAP operational entries.
    AuthenticationPolicy policy = null;
    try
    {
      policy = AuthenticationPolicy.forUser(entry, false);
    }
    catch (DirectoryException de)
    {
      ErrorLogger.logError(de.getMessageObject());
      if (debugEnabled())
      {
        TRACER.debugError("Failed to retrieve password " +
              "policy for user %s: %s",
              entry.getDN().toString(),
              stackTraceToSingleLineString(de));
      }
    }
    if (policy == null)
    {
      // No authentication policy: debug log this as an error since all
      // entries should have at least the default password policy.
      if (debugEnabled())
      {
        TRACER.debugError("No applicable password policy for user %s", entry
            .getDN().toString());
      }
    }
    else if (policy.isPasswordPolicy())
    {
      PasswordPolicyState pwpState = null;
      try
      {
        pwpState =
          (PasswordPolicyState) policy.createAuthenticationPolicyState(entry);
      }
      catch (DirectoryException de)
      {
        ErrorLogger.logError(de.getMessageObject());
        if (debugEnabled())
        {
          TRACER.debugError("Failed to retrieve password " +
                "policy state for user %s: %s",
                entry.getDN().toString(),
                stackTraceToSingleLineString(de));
        }
      }
      return pwpState.getPasswordExpirationTime();
    }
    else
    {
      // Not a password policy, could be PTA, etc.
      if (debugEnabled())
      {
        TRACER.debugVerbose("Authentication policy %s found for user %s is "
            + "not a password policy", policy.getDN().toString(), entry
            .getDN().toString());
      }
    }
    return -1L;
  }
}
opends/tests/unit-tests-testng/src/server/org/opends/server/extensions/PasswordExpirationTimeVirtualAttributeProviderTestCase.java
New file
@@ -0,0 +1,248 @@
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at
 * trunk/opends/resource/legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2012 profiq, s.r.o.
 */
package org.opends.server.extensions;
import org.testng.annotations.BeforeMethod;
import org.opends.server.schema.GeneralizedTimeSyntax;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import org.opends.messages.Message;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.opends.server.TestCaseUtils;
import org.opends.server.protocols.internal.InternalClientConnection;
import org.opends.server.protocols.internal.InternalSearchOperation;
import org.opends.server.types.*;
import static org.testng.Assert.*;
public class PasswordExpirationTimeVirtualAttributeProviderTestCase
  extends ExtensionsTestCase
{
  private Entry notExpired;
  private Entry expired;
  @BeforeClass()
  public void startServer()
         throws Exception
  {
    TestCaseUtils.startServer();
    notExpired = TestCaseUtils.makeEntry("dn: uid=tuser," + TestCaseUtils.TEST_ROOT_DN_STRING,
                                         "objectClass: top",
                                         "objectClass: person",
                                         "objectClass: organizationalPerson",
                                         "objectClass: inetOrgPerson",
                                         "uid: tuser",
                                         "cn: Test User",
                                         "sn: User",
                                         "userPassword: password",
                                         "createTimestamp: 20120315163235Z");
    expired = TestCaseUtils.makeEntry("dn: uid=tuser," + TestCaseUtils.TEST_ROOT_DN_STRING,
                                       "objectClass: top",
                                       "objectClass: person",
                                       "objectClass: organizationalPerson",
                                       "objectClass: inetOrgPerson",
                                       "uid: tuser",
                                       "cn: Test User",
                                       "sn: User",
                                       "userPassword: password",
                                       "createTimestamp: 20110315163235Z");
  }
  @Test
  public void test30dPwPolicy() throws Exception
  {
    TestCaseUtils.addEntry(notExpired);
    TestCaseUtils.addEntry("dn: cn=Subentry Password Policy,"  + TestCaseUtils.TEST_ROOT_DN_STRING,
                           "objectClass: top",
                           "objectClass: subentry",
                           "objectClass: pwdPolicy",
                           "cn: Subentry Password Policy",
                           "pwdAttribute: userPassword",
                           "pwdLockout: TRUE",
                           "pwdMaxFailure: 3",
                           "pwdFailureCountInterval: 300",
                           "pwdLockoutDuration: 300",
                           "pwdAllowUserChange: TRUE",
                           "pwdSafeModify: TRUE",
                           "pwdMaxAge: 2592000", // 30 days
                           "subtreeSpecification: {minimum 1, specificationFilter \"(objectclass=*)\"}");
    long expirationTime = getTimeValueFromAttribute("ds-pwp-password-expiration-time");
    long createTime = getTimeValueFromAttribute("pwdchangedtime");
    assertEquals(expirationTime, createTime + 2592000000L);
  }
  @BeforeMethod()
  public void environmentSetup() throws Exception
  {
    TestCaseUtils.initializeMemoryBackend(TestCaseUtils.TEST_BACKEND_ID,
                                          TestCaseUtils.TEST_ROOT_DN_STRING,
                                          true);
  }
  @AfterMethod()
  public void environmentCleanup() throws Exception
  {
    TestCaseUtils.clearMemoryBackend(TestCaseUtils.TEST_BACKEND_ID);
  }
  @Test(expectedExceptions = AssertionError.class)
  public void testNoExpiration() throws Exception
  {
    TestCaseUtils.addEntry(notExpired);
    TestCaseUtils.addEntry("dn: cn=Subentry Password Policy,"  + TestCaseUtils.TEST_ROOT_DN_STRING,
                           "objectClass: top",
                           "objectClass: subentry",
                           "objectClass: pwdPolicy",
                           "cn: Subentry Password Policy",
                           "pwdAttribute: userPassword",
                           "pwdLockout: TRUE",
                           "pwdMaxFailure: 3",
                           "pwdFailureCountInterval: 300",
                           "pwdLockoutDuration: 300",
                           "pwdAllowUserChange: TRUE",
                           "pwdSafeModify: TRUE",
                           "subtreeSpecification: {minimum 1, specificationFilter \"(objectclass=*)\"}");
    getTimeValueFromAttribute("ds-pwp-password-expiration-time");
  }
  @Test
  public void testPwPolicyExpiring() throws Exception
  {
    TestCaseUtils.addEntry(notExpired);
    TestCaseUtils.addEntry("dn: cn=Subentry Password Policy,"  + TestCaseUtils.TEST_ROOT_DN_STRING,
                           "objectClass: top",
                           "objectClass: subentry",
                           "objectClass: pwdPolicy",
                           "cn: Subentry Password Policy",
                           "pwdAttribute: userPassword",
                           "pwdLockout: TRUE",
                           "pwdMaxFailure: 3",
                           "pwdFailureCountInterval: 300",
                           "pwdLockoutDuration: 300",
                           "pwdAllowUserChange: TRUE",
                           "pwdSafeModify: TRUE",
                           "pwdMaxAge: 2592000", // 30 days
                           "subtreeSpecification: {minimum 1, specificationFilter \"(objectclass=*)\"}");
    long expirationTime = getTimeValueFromAttribute("ds-pwp-password-expiration-time");
    long createTime = getTimeValueFromAttribute("pwdchangedtime");
    assertEquals(expirationTime, createTime + 2592000000L);
  }
  @Test
  public void testPwPolicyExpired() throws Exception
  {
    TestCaseUtils.addEntry(expired);
    TestCaseUtils.addEntry("dn: cn=Subentry Password Policy,"  + TestCaseUtils.TEST_ROOT_DN_STRING,
                           "objectClass: top",
                           "objectClass: subentry",
                           "objectClass: pwdPolicy",
                           "cn: Subentry Password Policy",
                           "pwdAttribute: userPassword",
                           "pwdLockout: TRUE",
                           "pwdMaxFailure: 3",
                           "pwdFailureCountInterval: 300",
                           "pwdLockoutDuration: 300",
                           "pwdAllowUserChange: TRUE",
                           "pwdSafeModify: TRUE",
                           "pwdMaxAge: 648000", // 7.5 days
                           "subtreeSpecification: {minimum 1, specificationFilter \"(objectclass=*)\"}");
    long expirationTime = getTimeValueFromAttribute("ds-pwp-password-expiration-time");
    long createTime = getTimeValueFromAttribute("pwdchangedtime");
    assertEquals(expirationTime, createTime + 648000000L);
  }
  private long getTimeValueFromAttribute(String attributeName)
    throws Exception
  {
    // Establish the internal connection as root
    InternalClientConnection conn =
      InternalClientConnection.getRootConnection();
    assertNotNull(conn);
    // Define the attribute to be returned
    LinkedHashSet<String> retAttr = new  LinkedHashSet<String>();
    retAttr.add(attributeName);
    retAttr.add("pwdpolicysubentry");
    // Process the search request
    InternalSearchOperation search =
      conn.processSearch(notExpired.getDN().toString(),
                         SearchScope.BASE_OBJECT,
                         DereferencePolicy.DEREF_ALWAYS,
                         0,
                         0,
                         false,
                         "(objectclass=*)",
                         retAttr);
    assertEquals(search.getResultCode(), ResultCode.SUCCESS);
    LinkedList<SearchResultEntry> entries = search.getSearchEntries();
    assertNotNull(entries);
    assertEquals(entries.size(), 1);
    SearchResultEntry entry = entries.get(0);
    assertNotNull(entry);
    List<Attribute> attrs = entry.getAttribute(attributeName);
    assertNotNull(attrs);
    assertEquals(attrs.size(), 1);
    Attribute attr = attrs.get(0);
    assertNotNull(attr);
    Iterator<AttributeValue> it = attr.iterator();
    assertTrue(it.hasNext());
    AttributeValue val = it.next();
    conn.disconnect(DisconnectReason.UNBIND, true, Message.EMPTY);
    return
      GeneralizedTimeSyntax.decodeGeneralizedTimeValue(val.getValue());
  }
}