Post

Check Session Cookie Security in REST Assured

Check the cookies a server sets, from their values to the security attributes of a session cookie (Secure, HttpOnly, SameSite, Path and Max-Age) with detailedCookie(), and read a Cookie object afterwards.

Check Session Cookie Security in REST Assured

When a user signs in, the API answers with a session cookie. A refactor of the sign-in code drops the HttpOnly attribute, and every functional test still passes: the cookie works exactly as before. It’s also readable by any script on the page, until someone steals it. In this guide, you’ll check the cookies a server sets, from their values to the security attributes that protect a session.

Level: Intermediate · Time: 15 minutes · Part of: Module 3: Validating Responses in Depth, section 6

What You’ll Build

You’ll build a test class called CookiesTest with three tests. One checks cookie values, one checks every security attribute of the session cookie, and one reads the cookie as an object for JUnit assertions.

All three tests send this request and check this response:

1
2
3
4
5
6
7
8
POST /api/v1/sessions HTTP/1.1
Host: localhost:<port>

HTTP/1.1 201 Created
Set-Cookie: SESSION=<uuid>; Path=/api; Max-Age=900; Secure; HttpOnly; SameSite=Strict
Set-Cookie: lang=nl; Path=/

{"status":"signed in"}

When you’re done, Maven reports three passing tests:

1
2
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Check cookie values.
  • Check a cookie’s security attributes.
  • Read a cookie afterwards.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: create CookiesTest in a new section_06 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (CookiesTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: if you haven’t cloned the examples repository yet, follow the steps in Filter JSON Lists With GPath in REST Assured.

Out of scope: this guide doesn’t cover sessions that span several requests, or authentication; they’re taught in Module 7.

Understand Response Cookies

The problem. A session cookie’s value is a random token, so a test can’t know it in advance, and checking that it exists says little. What protects the session are the cookie’s attributes. A cookie without them works perfectly in every functional test, so only a test that checks the attributes notices when one goes missing.

The concept. A server sets a cookie with a Set-Cookie header: a name and value, followed by attributes.

AttributeWhat it does
Path=/apiThe browser sends the cookie only for paths under /api
Max-Age=900The cookie expires after 900 seconds, 15 minutes
SecureThe cookie is sent only over HTTPS
HttpOnlyScripts in the page can’t read the cookie
SameSite=StrictThe cookie isn’t sent with requests that start on another site

After then(), REST Assured checks cookies in two ways: cookie(name) and cookie(name, value) check that a cookie exists and its value; cookie(name, detailedCookie()...) checks the value and every attribute.

When to use each. Check the value of a preference cookie, such as a language. For a session cookie, check its format and every attribute the server must set. Decide per cookie what matters: a preference that isn’t a secret doesn’t need HttpOnly.

For a session cookie, the attributes are the security, so test them.

Meet the API Under Test

This guide uses one endpoint of the Transactions API:

MethodPathPurpose
POST/sessionsSign in, and set the session cookies

It answers 201 Created with the body {"status":"signed in"} and two cookies:

1
2
3
4
5
6
HTTP/1.1 201 Created
Content-type: application/json; charset=utf-8
Set-Cookie: SESSION=28241e47-3850-49ba-9299-a9fdf0313b9b; Path=/api; Max-Age=900; Secure; HttpOnly; SameSite=Strict
Set-Cookie: lang=nl; Path=/

{"status":"signed in"}

Your tests check these cookies:

  • SESSION, whose value is a new UUID on every sign-in, and whose attributes protect it.
  • lang, a language preference with the fixed value nl and no security attributes.

Set Up the Test Class

Goal: create the test class with a UUID pattern and a helper that signs in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.javanibble.module_03.section_06;

import static io.restassured.RestAssured.given;
import static io.restassured.matcher.RestAssuredMatchers.detailedCookie;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.javanibble.transactions.TransactionsApi;

import io.restassured.http.Cookie;
import io.restassured.response.ValidatableResponse;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

class CookiesTest {

    private static final String UUID = "[0-9a-f-]{36}";

    private static TransactionsApi api;

    @BeforeAll
    static void startApi() {
        api = TransactionsApi.start();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    private static ValidatableResponse signIn() {
        return given().baseUri(api.baseUri()).port(api.port()).basePath(TransactionsApi.BASE_PATH)
            .when().post("/sessions")
            .then().statusCode(201);
    }
}

What’s happening:

  • UUID is a pattern for the session id, which the test can’t know in advance.
  • signIn() posts to /sessions, checks for 201 and returns the ValidatableResponse for further checks.
  • detailedCookie comes from RestAssuredMatchers, and Cookie is REST Assured’s cookie object.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

Check Value, Existence and Format

Goal: check the language cookie’s value, and the session cookie’s existence and format.

1
2
3
4
5
6
7
@Test
void cookieValues() {
    signIn()
        .cookie("lang", "nl")
        .cookie("SESSION")
        .cookie("SESSION", matchesPattern(UUID));
}

What’s happening:

  • cookie("lang", "nl") checks an exact value.
  • cookie("SESSION") checks only that the server set the cookie.
  • cookie("SESSION", matchesPattern(UUID)) checks the format of a generated value, with any Hamcrest matcher. Never hard-code a session id: it changes on every sign-in.

Checkpoint: run CookiesTest from your IDE. One test runs and passes.

When a cookie is missing, the failure lists every cookie the server set, attributes included. cookie("SESSIONID") fails with Cookie "SESSIONID" was not defined in the response. Cookies are: followed by SESSION=...;Path=/api;Max-Age=900;Secure;HttpOnly;SameSite=Strict and lang=nl;Path=/.

After then(), cookie(..) checks a cookie the server set; before when(), as in Module 2, it sends one. The method name is the same, so check which side of the chain you’re on.

Check a Cookie’s Security Attributes

Goal: check the session cookie’s value and every attribute in one call.

1
2
3
4
5
6
7
8
9
10
11
@Test
void theSessionCookieIsLockedDown() {
    signIn()
        .cookie("SESSION", detailedCookie()
                .value(matchesPattern(UUID))
                .path("/api")
                .maxAge(900)
                .secured(true)
                .httpOnly(true)
                .sameSite("Strict"));
}

What’s happening:

  • detailedCookie() builds a matcher for a whole cookie. Each call adds one check, and the cookie must pass all of them.
  • value(..) takes a value or a matcher.
  • path(..) and maxAge(..) check where and how long the cookie is valid.
  • secured(true), httpOnly(true) and sameSite(..) check the security attributes.

Checkpoint: run the class again. Two tests pass.

This is a security test. If someone removes Secure, HttpOnly or SameSite from the server code, every functional test still passes, but this one fails. Check Path as well as Max-Age: a session cookie with Path=/ is sent to every page on the site.

Goal: read the session cookie as an object and check it with JUnit.

Sometimes you want the cookie itself, for example to send it with the next request, or to check it with plain assertions:

1
2
3
4
5
6
7
8
@Test
void readingACookieAfterwards() {
    Cookie session = signIn().extract().detailedCookie("SESSION");

    assertTrue(session.isSecured());
    assertTrue(session.isHttpOnly());
    assertEquals("Strict", session.getSameSite());
}

What’s happening:

  • extract().detailedCookie("SESSION") returns an io.restassured.http.Cookie with every attribute.
  • isSecured(), isHttpOnly() and getSameSite() read the attributes for JUnit’s assertions.
  • extract().cookie("SESSION") would return only the value, as a string such as 28241e47-3850-49ba-9299-a9fdf0313b9b.

Checkpoint: run the class again. All three tests pass.

A Cookie object can be passed straight to cookie(..) on the next request, as in Send Headers and Cookies in REST Assured. Module 4 covers extract() in depth.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-03 -Dtest=CookiesTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_03.section_06.CookiesTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.191 s -- in com.javanibble.module_03.section_06.CookiesTest
[INFO]
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In theSessionCookieIsLockedDown, change sameSite("Strict") to sameSite("Lax") and run the command again. You should see a result similar to the following:

1
2
3
[ERROR] Failures:
[ERROR]   CookiesTest.theSessionCookieIsLockedDown:63 1 expectation failed.
Expected cookie "SESSION" was not ((((((not null and hasProperty("value", a string matching the pattern '[0-9a-f-]{36}')) and hasProperty("path", "/api")) and hasProperty("maxAge", <900L>)) and hasProperty("secured", <true>)) and hasProperty("httpOnly", <true>)) and hasProperty("sameSite", "Lax")), hasProperty("sameSite", "Lax")  property 'sameSite' was "Strict".

The message is long, because it describes every check in the detailedCookie() matcher. Read it from the end: the part after the last comma names the one check that failed, hasProperty("sameSite", "Lax"), and the actual value, "Strict".

Change sameSite("Lax") back to sameSite("Strict") and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
Cookie "SESSIONID" was not defined in the response. Cookies are: ...The cookie name is wrong, or the server didn’t set itCompare the name with the list of cookies in the message
Expected cookie "SESSION" was not (...) property 'sameSite' was "Strict"One attribute differs from what the test expectsRead the end of the message for the failing attribute
A session-cookie test fails on every run with a different valueThe test hard-codes the session idCheck the format with matchesPattern(..)

Try It Yourself

Exercise 1: Check the Language Cookie’s Attributes

The lang cookie is a preference, not a secret. Add a test called theLanguageCookieIsNotLockedDown that checks, with detailedCookie(), that its value is "nl", its path is "/", and that it’s neither secured nor HTTP-only.

Hint

Start from theSessionCookieIsLockedDown. secured(..) and httpOnly(..) take false as well as true.

Solution
1
2
3
4
5
6
7
8
9
@Test
void theLanguageCookieIsNotLockedDown() {
    signIn()
        .cookie("lang", detailedCookie()
                .value("nl")
                .path("/")
                .secured(false)
                .httpOnly(false));
}

Exercise 2: Prove Every Session Is New

Add a test called everySignInGetsANewSession that signs in twice and extracts the SESSION cookie both times. Check with JUnit that the first cookie’s value matches the UUID pattern, that its path is "/api" and its max age 900, and that the two values differ.

Hint

Use extract().detailedCookie(..) as in readingACookieAfterwards. A Cookie has getValue(), getPath() and getMaxAge(), and a String has matches(..).

Solution
1
2
3
4
5
6
7
8
9
10
@Test
void everySignInGetsANewSession() {
    Cookie first = signIn().extract().detailedCookie("SESSION");
    Cookie second = signIn().extract().detailedCookie("SESSION");

    assertTrue(first.getValue().matches(UUID));
    assertEquals("/api", first.getPath());
    assertEquals(900, first.getMaxAge());
    assertNotEquals(first.getValue(), second.getValue());
}

Add import static org.junit.jupiter.api.Assertions.assertNotEquals; to the class.

Summary

You built CookiesTest, which checks the values of the cookies a server sets, every security attribute of the session cookie, and the cookie as an object. A refactor that drops HttpOnly now turns a test red.

  • After then(), cookie(name) checks that a cookie exists, and cookie(name, value) checks its value with a string or a matcher.
  • Check a generated session id by its format with matchesPattern(..), never by its value.
  • detailedCookie() checks Secure, HttpOnly, SameSite, Path and Max-Age together; for a session cookie, those attributes are the security.
  • Decide per cookie which attributes the server must set; a preference cookie doesn’t need them.
  • extract().detailedCookie(..) returns the whole cookie, for JUnit assertions or for the next request.

Here are the commands you used in this guide:

1
mvn test -pl module-03 -Dtest=CookiesTest

What’s Next

Next: continue with Check XML and HTML Responses in REST Assured, which checks an XML bank statement and an HTML page with the same body(..) and GPath.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.