public void testMakeObjectConnectsAndOtherwiseInitializesConnections()
      throws LDAPException, UnsupportedEncodingException {

    setConnectionManagerConfigExpectations();
    factory.setConnectionManager(connMgr);
    mockConn.expects(once()).method("setConnectionManager").with(same(connMgr));
    mockConn.expects(once()).method("setConstraints").with(NOT_NULL); // TODO make more specific
    mockConn
        .expects(once())
        .method("connect")
        .with(eq(connMgrConfig.getLdapHost()), eq(connMgrConfig.getLdapPort()))
        .after("setConstraints");
    mockConn.expects(once()).method("startTLS").after("connect");
    mockConn
        .expects(once())
        .method("bind")
        .with(
            eq(LDAPConnection.LDAP_V3),
            eq(connMgrConfig.getLdapUser()),
            eq(connMgrConfig.getLdapPassword().getBytes("UTF-8")))
        .after("connect");
    mockConn.expects(once()).method("setBindAttempted").with(eq(false)).after("bind");

    // the actual code exercise
    assertSame(conn, factory.makeObject());

    // TODO how to test socket factory assignment (static call)
  }
Пример #2
0
  /** {@inheritDoc} */
  public LDAPConnection getConnection() throws LDAPException {

    if (M_log.isDebugEnabled()) {
      M_log.debug("getConnection()");
    }
    LDAPConnection conn = newConnection();

    if (config.isAutoBind()) {
      if (M_log.isDebugEnabled()) {
        M_log.debug("getConnection(): auto-binding");
      }
      try {
        bind(conn, config.getLdapUser(), config.getLdapPassword());
      } catch (LDAPException ldape) {
        if (ldape.getResultCode() == LDAPException.INVALID_CREDENTIALS) {
          M_log.warn(
              "Failed to bind against: "
                  + conn.getHost()
                  + " with user: "******" password: "******".", "*"));
        }
        throw ldape;
      }
    }

    return conn;
  }
Пример #3
0
 /**
  * Applies <code>LDAPConstraints</code> to the specified <code>LDAPConnection</code>. Implemented
  * to assign <code>timeLimit</code> and <code>referralFollowing</code> constraint values retrieved
  * from the currently assigned {@link LdapConnectionManagerConfig}.
  *
  * @param conn
  */
 protected void applyConstraints(LDAPConnection conn) {
   int timeout = config.getOperationTimeout();
   boolean followReferrals = config.isFollowReferrals();
   if (M_log.isDebugEnabled()) {
     M_log.debug(
         "applyConstraints(): values [timeout = "
             + timeout
             + "][follow referrals = "
             + followReferrals
             + "]");
   }
   LDAPConstraints constraints = new LDAPConstraints();
   constraints.setTimeLimit(timeout);
   constraints.setReferralFollowing(followReferrals);
   conn.setConstraints(constraints);
 }
Пример #4
0
 /**
  * Caches a keystore location as a system property. No-op if the {@link
  * #KEYSTORE_LOCATION_SYS_PROP_KEY} system property has a non-<code>null</code> value. Otherwise
  * caches the keystore location from the currently assigned {@link LdapConnectionManagerConfig}.
  *
  * @param config
  * @throws NullPointerException if a non-null keystore location cannot be resolved
  */
 protected void initKeystoreLocation() {
   if (M_log.isDebugEnabled()) {
     M_log.debug("initKeystoreLocation()");
   }
   String sysKeystoreLocation = System.getProperty(KEYSTORE_LOCATION_SYS_PROP_KEY);
   if (sysKeystoreLocation == null) {
     String configuredKeystoreLocation = config.getKeystoreLocation();
     if (configuredKeystoreLocation != null) {
       if (M_log.isDebugEnabled()) {
         M_log.debug(
             "initKeystoreLocation(): setting system property [location = "
                 + configuredKeystoreLocation
                 + "]");
       }
       System.setProperty(KEYSTORE_LOCATION_SYS_PROP_KEY, configuredKeystoreLocation);
     }
   } else {
     if (M_log.isDebugEnabled()) {
       M_log.debug(
           "initKeystoreLocation(): retained existing system property [location = "
               + sysKeystoreLocation
               + "]");
     }
   }
 }
Пример #5
0
  /**
   * Return a new LDAPConnection with the appropriate socket factory set for the connection type.
   */
  private LDAPConnection createConnectionWithSocketFactory() {
    LDAPSocketFactory factory;

    if (config.isSecureConnection()) {
      factory = config.getSecureSocketFactory();

      if (factory == null) {
        throw new RuntimeException(
            "You must set a 'secureSocketFactory' (in jldap-beans.xml) when using LDAPS");
      }
    } else {
      factory = config.getSocketFactory();
    }

    if (factory == null) {
      return new LDAPConnection();
    } else {
      return new LDAPConnection(factory);
    }
  }
  /**
   * Verifies that a failed rebind during connection validation marks the connection as "inactive".
   * This ensures that the connection is not returned to the pool by {@link
   * PooledLDAPConnection#finalize()}. Technically, a failed rebind does not mean the connection is
   * stale but failing to bind as the system user should indicate that something is very much wrong,
   * so reallocating a connection is not a bad idea. Certainly better than finding oneself caught in
   * an endless loop of validating stale connections.
   */
  public void testValidateObjectLowersActiveFlagIfRebindFails()
      throws UnsupportedEncodingException {

    setConnectionManagerConfigExpectations();
    factory.setConnectionManager(connMgr);
    LDAPException bindFailure = new LDAPException();

    mockConn.expects(once()).method("isBindAttempted").will(returnValue(true));
    mockConn
        .expects(once())
        .method("bind")
        .with(
            eq(LDAPConnection.LDAP_V3),
            eq(connMgrConfig.getLdapUser()),
            eq(connMgrConfig.getLdapPassword().getBytes("UTF-8")))
        .after("isBindAttempted")
        .will(throwException(bindFailure));
    mockConn.expects(once()).method("setActive").with(eq(false)).after("bind");

    assertFalse(factory.validateObject(conn));
  }
  /**
   * Verifies that the {@link PooledLdapConnection} to be validated is re-bound as the system user
   * prior to testing the connection for liveness. This is only relevant if the client has bound the
   * connection as another user and the autoBind behavior has been enabled.
   */
  public void testValidateObjectRebindsAsAutoBindUserIfNecessaryPriorToTestingConnectionLiveness()
      throws UnsupportedEncodingException {

    setConnectionManagerConfigExpectations();
    factory.setConnectionManager(connMgr);

    mockConn.expects(once()).method("isBindAttempted").will(returnValue(true));
    mockConn
        .expects(once())
        .method("bind")
        .with(
            eq(LDAPConnection.LDAP_V3),
            eq(connMgrConfig.getLdapUser()),
            eq(connMgrConfig.getLdapPassword().getBytes("UTF-8")))
        .after("isBindAttempted");
    mockConn.expects(once()).method("setBindAttempted").with(eq(false)).after("bind");

    mockLivenessValidator.expects(once()).method("isConnectionAlive").will(returnValue(true));
    factory.setConnectionLivenessValidator(livenessValidator);
    assertTrue(factory.validateObject(conn));
  }
Пример #8
0
  protected void postConnect(LDAPConnection conn) throws LDAPException {

    if (M_log.isDebugEnabled()) {
      M_log.debug("postConnect()");
    }

    if (config.isSecureConnection() && isTlsSocketFactory()) {
      if (M_log.isDebugEnabled()) {
        M_log.debug("postConnect(): starting TLS");
      }
      conn.startTLS();
    }
  }
Пример #9
0
  /** {@inheritDoc} */
  public void init() {

    if (M_log.isDebugEnabled()) {
      M_log.debug("init()");
    }

    if (config.isSecureConnection()) {
      if (M_log.isDebugEnabled()) {
        M_log.debug("init(): initializing keystore");
      }
      initKeystoreLocation();
      initKeystorePassword();
    }
  }
Пример #10
0
 /**
  * Caches a keystore password as a system property. No-op if the {@link
  * #KEYSTORE_PASSWORD_SYS_PROP_KEY} system property has a non-<code>null</code> value. Otherwise
  * caches the keystore password from the currently assigned {@link LdapConnectionManagerConfig}.
  *
  * @param config
  * @throws NullPointerException if a non-null keystore password cannot be resolved
  */
 protected void initKeystorePassword() {
   if (M_log.isDebugEnabled()) {
     M_log.debug("initKeystorePassword()");
   }
   String sysKeystorePassword = System.getProperty(KEYSTORE_PASSWORD_SYS_PROP_KEY);
   if (sysKeystorePassword == null) {
     String configuredKeystorePassword = config.getKeystorePassword();
     if (configuredKeystorePassword != null) {
       if (M_log.isDebugEnabled()) {
         M_log.debug("initKeystorePassword(): setting system property");
       }
       System.setProperty(KEYSTORE_PASSWORD_SYS_PROP_KEY, configuredKeystorePassword);
     }
   } else {
     if (M_log.isDebugEnabled()) {
       M_log.debug("initKeystorePassword(): retained existing system property");
     }
   }
 }
Пример #11
0
  /**
   * Connects the specified <code>LDAPConnection</code> to the currently configured host and port.
   *
   * @param conn an <code>LDAPConnection</code>
   * @throws LDAPConnection if the connect attempt fails
   */
  protected void connect(LDAPConnection conn) throws LDAPException {
    if (M_log.isDebugEnabled()) {
      M_log.debug("connect()");
    }

    conn.connect(config.getLdapHost(), config.getLdapPort());

    try {
      postConnect(conn);
    } catch (LDAPException e) {
      M_log.error(
          "Failed to completely initialize a connection [host = "
              + config.getLdapHost()
              + "][port = "
              + config.getLdapPort()
              + "]",
          e);
      try {
        conn.disconnect();
      } catch (LDAPException ee) {
      }

      throw e;
    } catch (Throwable e) {
      M_log.error(
          "Failed to completely initialize a connection [host = "
              + config.getLdapHost()
              + "][port = "
              + config.getLdapPort()
              + "]",
          e);
      try {
        conn.disconnect();
      } catch (LDAPException ee) {
      }

      if (e instanceof Error) {
        throw (Error) e;
      }
      if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
      }

      throw new RuntimeException("LDAPConnection allocation failure", e);
    }
  }
Пример #12
0
 protected boolean isTlsSocketFactory() {
   return config.getSecureSocketFactory() instanceof LDAPTLSSocketFactory;
 }