top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Protecting Sensitive Data in REST Assured

When using REST Assured for API testing, it's crucial to ensure that sensitive data is not exposed in your logs. This includes:


Authentication Credentials: Usernames, passwords, API keys, or tokens.

Personal Identifiable Information (PII): Names, email addresses, phone numbers, social security numbers.

Sensitive Request Payload: Data such as credit card numbers, addresses, or health information.

Sensitive Response Payload: Similar to request payloads, containing important data that should be kept private.


Keeping this information out of logs helps protect the security and privacy of the systems and users interacting with your application.


Methods to Protect Sensitive Data


1. Disabling logging of sensitive information

2. Masking sensitive data

3. Log Only If Validation Fails

4. Blacklist Sensitive Headers


1. Disabling logging of sensitive information


Disabling the logging of request and response details in REST Assured is a simple and effective way to ensure that sensitive information is not exposed. This includes details like usernames, passwords, API keys, and personal data.


What is the use of  Disable Logging?


Security: Prevents sensitive data from being exposed if logs are accessed.

Privacy: Protects user information.

Compliance: Meets regulatory requirements for data protection.


How to do Disable Logging:


1.Create Maven project, add this to your pom.xml:


<dependency>

    <groupId>io.rest-assured</groupId>

    <artifactId>rest-assured</artifactId>

    <version>4.4.0</version>

    <scope>test</scope>

</dependency>


Set Up REST Assured to Disable Logging:


import io.restassured.RestAssured;

import io.restassured.config.LogConfig;


public class ApiTest {

    public static void main(String[] args) {

        RestAssured.config = RestAssured.config()

            .logConfig(LogConfig.logConfig().disableLoggingOfRequestAndResponseIfValidationFails());


        RestAssured.given()

            .header("Authorization", "Bearer token-here")

            .when()

            .get("https://api.example.com/yourEndpoint")

            .then()

            .statusCode(200);

    }

}


In this setup, RestAssured.config is used to configure REST Assured to disable logging of request and response details when validation fails.

 LogConfig.logConfig().disableLoggingOfRequestAndResponseIfValidationFails() method specifically handles this, ensuring sensitive information such as authorization tokens is not logged. 

The RestAssured.given() method builds the request, adding an authorization header, and

 the when().get("https://api.example.com/yourEndpoint") specifies the GET request to the API endpoint. 

The .then().statusCode(200) validates that the response status code is 200, indicating a successful request.


2.Mask Sensitive Data


Masking sensitive data means hiding confidential information in your logs. This approach allows you to log necessary information without exposing sensitive details such as authentication tokens, passwords, or personal identifiable information (PII).


What is the use of Mask Sensitive Data?


Security: Prevents data breaches.

Compliance: Ensures adherence to regulations.

Auditability: Maintains useful logs without exposing confidential data.

How to Mask Sensitive Data:

Consider a scenario where you need to send a POST request with a JSON body containing a password field. To mask this sensitive data, you can create a custom filter that replaces the actual password with asterisks (*) before sending the request.

import io.restassured.filter.Filter;

import io.restassured.filter.FilterContext;

import io.restassured.response.Response;

import io.restassured.specification.FilterableRequestSpecification;

import io.restassured.specification.FilterableResponseSpecification;


public class MaskSensitiveDataFilter implements Filter {

    

    public Response filter(FilterableRequestSpecification reqSpec, FilterableResponseSpecification resSpec, FilterContext ctx) {

        // Replace sensitive data in the request body with placeholders

        if (reqSpec.getBody() != null) {

            String body = reqSpec.getBody().asString();

            body = body.replaceAll("\"password\":\"[^\"]*\"", "\"password\":\"*****\"");

            reqSpec.body(body);

        }

        return ctx.next(reqSpec, resSpec);

    }

}



In this code,

The class MaskSensitiveDataFilter implements the Filter interface, which requires implementing the filter method.

Inside the filter method:

It takes three parameters: reqSpec (FilterableRequestSpecification), resSpec (FilterableResponseSpecification), and ctx (FilterContext).

It checks if the request body (reqSpec.getBody()) is not null.

If the request body is not null, it converts it to a string (reqSpec.getBody().asString()) and replaces any occurrences of the password field with asterisks ("*****"). This is done using a regular expression ("\"password\":\"[^\"]*\"").

The modified request body is then set back to the request specification (reqSpec.body(body)).

Finally, the method returns the result of calling ctx.next(reqSpec, resSpec), which passes control to the next filter in the chain.

Overall, this filter intercepts requests, checks if they contain sensitive data (e.g., passwords), and masks that data before allowing the request to proceed.








Let's apply this filter when making a POST request:


import io.restassured.RestAssured;


public class ApiTest {

    public static void main(String[] args) {

        // Apply the custom filter

        RestAssured.filters(new MaskSensitiveDataFilter());


        // Send a POST request with sensitive data

        RestAssured.given()

            .baseUri("https://api.example.com")

            .header("Content-Type", "application/json")

            .body("{\"username\": \"john.doe\", \"password\": \"secretpassword\"}")

            .when()

            .post("/login")

            .then()

            .statusCode(200);

    }

}


In this code snippet, we apply the MaskSensitiveDataFilter to mask sensitive data before sending the POST request. When executed, the password field in the request body will be replaced with asterisks (*) to ensure that sensitive information is not exposed in logs or during transmission. This approach enhances the security of your API requests by preventing unauthorized access to sensitive data.



3.Log Only If Validation Fails


Logging only if validation fails means that you'll keep detailed logs of your API requests and responses only when something goes wrong.


What is the use of Log Only If Validation Fails?


Less Risk: Reduces exposure of sensitive data when everything is working correctly.

Saves Time: Makes it easier to find and fix issues by logging only problematic cases.



import io.restassured.RestAssured;


public class ApiTest {

    public static void main(String[] args) {

        RestAssured.given()

            .header("Authorization", "Bearer token here")

            .log().ifValidationFails()

            .when()

            .get("https://api.example.com/yourEndpoint")

            .then()

            .statusCode(200);

    }

}

In this setup, the .log().ifValidationFails() method configures REST Assured to log request and response details only if the validation fails. 

This ensures that only problematic cases are logged, reducing the risk of exposing sensitive information. 

The .statusCode(200) validates that the response status code is 200, indicating a successful request.


4.Blacklist Sensitive Headers


Blacklisting specific headers prevents them from being logged.


What is the use of  Blacklist Sensitive Headers?


Keeps Information Safe: Ensures private data like passwords or tokens are not shown in logs.

How to Blacklist Headers:



import io.restassured.RestAssured;

import io.restassured.config.LogConfig;


public class ApiTest {

    public static void main(String[] args) {

        RestAssured.config = RestAssured.config().logConfig(

            LogConfig.logConfig().blacklistHeader("Authorization", "Sensitive-Header")

        );


        RestAssured.given()

            .header("Authorization", "Bearer token here")

            .header("Sensitive-Header", "sensitive-value")

            .log().all()

            .when()

            .get("https://api.example.com/yourEndpoint")

            .then()

            .statusCode(200);

    }

}

In this configuration, LogConfig.logConfig().blacklistHeader("Authorization", "Sensitive-Header") is used to specify which headers should not be logged.

 This ensures that headers containing sensitive information, such as "Authorization" and "Sensitive-Header", are excluded from the logs. 

The .header("Authorization", "Bearer your-token-here") adds an authorization header to the request, and .header("Sensitive-Header", "sensitive-value") adds another sensitive header. 

The .log().all() method logs all request and response details except for the blacklisted headers.


Conclusion

By using these methods,disabling logging, masking data, logging only on validation failure, and blacklisting headers,We can protect sensitive information and can enhance the security and reliability of API testing processes.

“Thank you for reading! Happy testing!"


45 views1 comment

1 Comment

Rated 0 out of 5 stars.
No ratings yet

Add a rating
Guest
May 22
Rated 5 out of 5 stars.

That’s a good one

Like
bottom of page