Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugfix/sdknew 2781 closing resources #290

Closed
wants to merge 13 commits into from
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
# Change Log
## [vX.X.X](...)
- Updating readme with `customIsSensitve`, `customParametersExtraction`
- Added an option to configure logger without slf4j using `PXConfiguration.setPxLoggerSeverity(<loggerSeverity>)`
- Added an option to close PerimeterX [SDKNEW-2781](https://perimeterx.atlassian.net/browse/SDKNEW-2781)

## [v6.5.0](https://github.com/PerimeterX/perimeterx-java-sdk/compare/v6.5.0...HEAD) (2023-03-04)
- Adding custom is sensitive configuration option
Expand Down
63 changes: 49 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
- [Advanced Usage Examples](#advanced-usage)
- [Data Enrichment](#data-enrichment)
- [Custom Parameters](#custom-parameters)
- [Custom Sensitive Request](#custom-sensitive-request)
- [Multiple Application Support](#multi-app-support)
- [Configuration](CONFIGURATIONS.md)
- [Logging and Troubleshooting](#loggin-troubleshoot)
Expand Down Expand Up @@ -190,31 +191,51 @@ enforcer.setVerificationHandler(new MyVerificationHandler(config));
...
```

#### <a name="custom-parameters"></a> Custom Parameters
#### <a name="custom-sensitive-request"></a> Custom Sensitive Request
With the `customIsSensitive` predicate you can force the request to be sensitive.
The input of the function is the same request that sent to the method `pxVerify`.
If the function throws exception, it is equivalent to returning `false`.
Implementing this configuration does NOT override other `sensitive` configurations, like `sensitive_routes`.

With the `customParametersProvider` function you can add up to 10 custom parameters to be sent back to PerimeterX servers. When set, the function is called before setting the payload on every request to PerimetrX servers.
> **Note**
> The request body can only be read once by default. If your function requires reading the body
> consider using RequestWrapper which caches the body. Send the wrapped request to
> `pxVerify` instead of the native one.

MyCustomParametersProvider.java:
In your filter:
```java
...
public class MyCustomParametersProvider implements CustomParametersProvider {
public CustomParameters buildCustomParameters(PXConfiguration pxConfiguration, PXContext pxContext) {
CustomParameters customParameters = new CustomParameters();
customParameters.setCustomParam1("my_custom_param_1");
customParameters.setCustomParam2("my_custom_param_2");
PXConfiguration pxConfiguration = new PXConfiguration.Builder()
...
customParameters.setCustomParam10("my_custom_param_10");
return customParameters;
}
}
.customIsSensitiveRequest((req) -> req.getHeader("example-header") == "example-value")
.build();

```

Then, in your filter:
#### <a name="custom-parameters"></a> Custom Parameters

With the `customParametersExtraction` function you can add up to 10 custom parameters to be sent back to PerimeterX servers.
When set, the function is called before setting the payload on every request to PerimetrX servers.
The input of the function is the same request that sent to the method `pxVerify`.
If the function throws exception, it is equivalent to returning empty custom params.
Implementing this configuration overrides the deprecated configuration `customParameterProvider`.

> **Note**
> The request body can only be read once by default. If your function requires reading the body
> consider using RequestWrapper which caches the body. Send the wrapped request to
> `pxVerify` instead of the native one.

In your filter:
```java
...
PXConfiguration pxConfiguration = new PXConfiguration.Builder()
...
.customParametersProvider(new MyCustomParametersProvider())
.customParametersExtraction((req) -> {
CustomParameters customParameters = new CustomParameters();
customParameters.setCustomParam1("example-value");
customParameters.setCustomParam2(req.getHeader("example-header"));
return customParameters;
})
.build();
...
```
Expand Down Expand Up @@ -251,6 +272,20 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se

For further information please visit [SLF4J](https://www.slf4j.org/manual.html) and [Logback](https://logback.qos.ch).

If you wish to use a basic logger which uses `System.out` and `System.err` to print debug and error accordingly,
Change the value of the static variable to your desired level.
```java
import com.perimeterx.models.configuration.PXConfiguration;
import com.perimeterx.utils.LoggerSeverity;

PXConfiguration.setPxLoggerSeverity(LoggerSeverity.DEBUG);
```
> **Note**
> This method can be executed once, no need to execute it every request.


---

The following steps are welcome when contributing to our project.

#### Fork/Clone
Expand Down
14 changes: 10 additions & 4 deletions src/main/java/com/perimeterx/api/PerimeterX.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,12 @@

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.Closeable;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Optional;

import static com.perimeterx.utils.Constants.*;
import static java.util.Objects.isNull;
Expand All @@ -78,7 +77,7 @@
* Created by shikloshi on 03/07/2016.
*/

public class PerimeterX {
public class PerimeterX implements Closeable {

private static final PXLogger logger = PXLogger.getLogger(PerimeterX.class);

Expand All @@ -90,14 +89,15 @@ public class PerimeterX {
private HostnameProvider hostnameProvider;
private VerificationHandler verificationHandler;
private ReverseProxy reverseProxy;
private PXHttpClient pxClient = null;

private void init(PXConfiguration configuration) throws PXException {
logger.debug(PXLogger.LogReason.DEBUG_INITIALIZING_MODULE);
configuration.mergeConfigurations();
this.configuration = configuration;
hostnameProvider = new DefaultHostnameProvider();
ipProvider = new CombinedIPProvider(configuration);
PXHttpClient pxClient = new PXHttpClient(configuration);
this.pxClient = new PXHttpClient(configuration);
this.activityHandler = new BufferedActivityHandler(pxClient, this.configuration);

if (configuration.isRemoteConfigurationEnabled()) {
Expand Down Expand Up @@ -337,4 +337,10 @@ public void setVerificationHandler(VerificationHandler verificationHandler) {
this.verificationHandler = verificationHandler;
}

@Override
public void close() throws IOException {
if(this.pxClient != null) {
this.pxClient.close();
}
}
}
20 changes: 17 additions & 3 deletions src/main/java/com/perimeterx/http/PXHttpClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.util.EntityUtils;

import java.io.Closeable;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
Expand All @@ -50,7 +51,7 @@
* <p>
* Created by shikloshi on 04/07/2016.
*/
public class PXHttpClient implements PXClient {
public class PXHttpClient implements PXClient, Closeable {
private static final int INACTIVITY_PERIOD_TIME_MS = 1000;
private static final long MAX_IDLE_TIME_SEC = 30L;

Expand All @@ -61,7 +62,7 @@ public class PXHttpClient implements PXClient {
private CloseableHttpClient httpClient;
private CloseableHttpAsyncClient asyncHttpClient;
private PoolingNHttpClientConnectionManager nHttpConnectionManager;

private final TimerValidateRequestsQueue timerConfigUpdater;
private PXConfiguration pxConfiguration;

public PXHttpClient(PXConfiguration pxConfiguration) throws PXException {
Expand All @@ -73,7 +74,7 @@ public PXHttpClient(PXConfiguration pxConfiguration) throws PXException {
throw new PXException(e);
}

TimerValidateRequestsQueue timerConfigUpdater = new TimerValidateRequestsQueue(nHttpConnectionManager, pxConfiguration);
this.timerConfigUpdater = new TimerValidateRequestsQueue(nHttpConnectionManager, pxConfiguration);
timerConfigUpdater.schedule();
}

Expand Down Expand Up @@ -316,4 +317,17 @@ public void sendEnforcerTelemetry(EnforcerTelemetry enforcerTelemetry) throws IO
}
}
}

@Override
public void close() throws IOException {
this.timerConfigUpdater.close();

if (this.asyncHttpClient != null) {
this.asyncHttpClient.close();
}

if (this.httpClient != null) {
this.httpClient.close();
}
}
}
15 changes: 13 additions & 2 deletions src/main/java/com/perimeterx/http/TimerValidateRequestsQueue.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
import com.perimeterx.utils.PXLogger;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;

import java.io.Closeable;
import java.util.Timer;
import java.util.TimerTask;

public class TimerValidateRequestsQueue extends TimerTask {
public class TimerValidateRequestsQueue extends TimerTask implements Closeable {

private static final PXLogger logger = PXLogger.getLogger(TimerValidateRequestsQueue.class);

private Timer timer = null;
private PoolingNHttpClientConnectionManager nHttpConnectionManager;
private PXConfiguration pxConfiguration;

Expand All @@ -29,7 +31,16 @@ public void run() {
* Sets a new timer object and runs its execution method
*/
public void schedule() {
Timer timer = new Timer();
this.close();
timer = new Timer();
timer.schedule(this, 0, pxConfiguration.getValidateRequestQueueInterval());
}

@Override
public void close() {
if(timer != null) {
timer.cancel();
timer = null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import com.perimeterx.models.risk.CustomParameters;
import com.perimeterx.utils.Constants;
import com.perimeterx.utils.FilesUtils;
import com.perimeterx.utils.LoggerSeverity;
import com.perimeterx.utils.PXLogger;
import lombok.AllArgsConstructor;
import lombok.Builder;
Expand Down Expand Up @@ -46,6 +47,15 @@
@Getter
public class PXConfiguration {
private static final PXLogger logger = PXLogger.getLogger(PXConfiguration.class);
private static LoggerSeverity loggerSeverity = null;

public static LoggerSeverity getPxLoggerSeverity() {
return loggerSeverity;
}

public static void setPxLoggerSeverity(LoggerSeverity severity) {
loggerSeverity = severity;
}

@JsonProperty("px_app_id")
private String appId;
Expand Down
47 changes: 47 additions & 0 deletions src/main/java/com/perimeterx/utils/ConsoleLogger.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.perimeterx.utils;

import java.io.PrintStream;
public class ConsoleLogger implements PXLogger {
private final LoggerSeverity severity;

public ConsoleLogger(LoggerSeverity severity) {
this.severity = severity;
}

private void log(PrintStream out, String prefix, Object msg, Object... additional) {
StringBuilder builder = new StringBuilder();
builder.append(prefix);
builder.append(msg);
for (Object arg : additional) {
builder.append(" ").append(arg.toString());
}
out.println(builder);
}
@Override
public void debug(LogReason reason, Object... args) {
if(severity.level >= LoggerSeverity.DEBUG.level) {
log(System.out, PXLogger.DEBUG_PREFIX, reason, args);
}
}

@Override
public void debug(String msg, Object... args) {
if(severity.level >= LoggerSeverity.DEBUG.level) {
log(System.out, PXLogger.DEBUG_PREFIX, msg, args);
}
}

@Override
public void error(LogReason reason, Object... args) {
if(severity.level >= LoggerSeverity.ERROR.level) {
log(System.err, PXLogger.ERROR_PREFIX, reason, args);
}
}

@Override
public void error(String msg, Object... args) {
if(severity.level >= LoggerSeverity.ERROR.level) {
log(System.err, msg, args);
}
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/perimeterx/utils/HMACUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public static boolean isHMACValid(String encodedString, String hmac,
byte[] bCookieHmac = StringUtils.hexStringToByteArray(hmac);
isValid = Arrays.equals(bHMAC, bCookieHmac);
} catch (Exception e) {
logger.error(PXLogger.LogReason.DEBUG_COOKIE_HMAC_VALIDATION_FAILED, e.getMessage());
logger.debug(PXLogger.LogReason.DEBUG_COOKIE_HMAC_VALIDATION_FAILED, e.getMessage());
isValid = false;
}

Expand Down
21 changes: 21 additions & 0 deletions src/main/java/com/perimeterx/utils/LoggerSeverity.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.perimeterx.utils;

import com.fasterxml.jackson.annotation.JsonValue;

public enum LoggerSeverity {
NONE(0),
ERROR(10),
DEBUG(100);


public final int level;

LoggerSeverity(int level) {
this.level = level;
}

@JsonValue
public String jsonName() {
return this.name().toLowerCase();
}
}
Loading