π‘οΈ Contract Enforcement, Open-Content Hazards & Perimeter Defense
By default, the IETF JSON Schema specification operates under an open-content model: unless explicitly instructed otherwise, any property not listed in the properties keyword is quietly accepted as valid. In enterprise automation, this loose default allows backend engineering teams to introduce unvetted fields, expose internal database entities, leak sensitive PII, or rename critical attributes without failing existing test assertions. Strict Schema Lockdown enforces a closed-world contract constraint using additionalProperties: false. In REST Assured, combining additionalProperties: false with patternProperties (regex-constrained dynamic dictionary keys), propertyNames (syntax constraints on JSON keys), and strict required arrays transforms contract testing into an airtight quality gate that instantly halts deployment pipelines upon the slightest unapproved payload drift.
additionalProperties: false across multi-tier object trees.
OPEN SCHEMA HAZARD VS. CLOSED-WORLD STRICT SCHEMA LOCKDOWN:
1. OPEN SCHEMA (Default Behavior: additionalProperties: true) - LEAKAGE RISK:
WIRE JSON RESPONSE: SCHEMA CONTRACT:
{ {
"studentId": "STU-88219", βββββββββββββΊ "properties": {
"fullName": "Nikita Sharma", βββββββββββββΊ "studentId": {"type": "string"},
"internalPassHash": "$2a$12$e8..", βββββββββββββΊ "fullName": {"type": "string"}
"unvettedDebugFlag": true βββββββββββββΊ }
} }
VALIDATION RESULT: [PASSED - SILENT LEAK]
Hazard: Backend leaked internal hash & debug flags; validator ignored them completely!
2. STRICT SCHEMA LOCKDOWN (Enforcing additionalProperties: false) - AIRTIGHT DEFENSE:
WIRE JSON RESPONSE: SCHEMA CONTRACT:
{ {
"studentId": "STU-88219", βββββββββββββΊ "properties": {
"fullName": "Nikita Sharma", βββββββββββββΊ "studentId": {"type": "string"},
"internalPassHash": "$2a$12$e8..", βββββββ "fullName": {"type": "string"}
} β },
β "additionalProperties": false
βΌ }
[REJECTED] VALIDATION RESULT: [FAILED FAST]
Benefit: Throws JsonSchemaValidationException pinpointing "internalPassHash" immediately!
additionalProperties: false at root and nested levels, mandatory field definitions, and explicit data types.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "StrictStudentContract",
"description": "Closed-world schema disallowing any undeclared payload properties",
"type": "object",
"additionalProperties": false,
"required": [
"studentId",
"fullName",
"email",
"academicTrack",
"enrolledCredits",
"contactInfo"
],
"properties": {
"studentId": {
"type": "string",
"pattern": "^STU-[0-9]{5}$"
},
"fullName": {
"type": "string",
"minLength": 3,
"maxLength": 100
},
"email": {
"type": "string",
"format": "email"
},
"academicTrack": {
"type": "string",
"enum": [
"ENTERPRISE_AUTOMATION",
"FULLSTACK_SDET",
"CLOUD_DEVOPS_QA"
]
},
"enrolledCredits": {
"type": "integer",
"minimum": 1,
"maximum": 30
},
"contactInfo": {
"type": "object",
"additionalProperties": false,
"required": ["primaryPhone", "city", "postalCode"],
"properties": {
"primaryPhone": {
"type": "string",
"pattern": "^\\+91-[0-9]{10}$"
},
"city": {
"type": "string"
},
"postalCode": {
"type": "string",
"pattern": "^[0-9]{6}$"
}
}
}
}
}
package com.nikita.restassured.schema;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.Matchers.equalTo;
public class StrictSchemaExecutionTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Verify API response strictly conforms to closed-world Draft-07 schema")
public void testStrictStudentContractValidation() {
given()
.baseUri(BASE_URI)
.accept(ContentType.JSON)
.pathParam("studentId", "STU-88219")
.log().ifValidationFails()
.when()
.get("/students/{studentId}")
.then()
.log().ifValidationFails()
.statusCode(200)
.contentType(ContentType.JSON)
// Evaluates strict closed-world contract:
.body(matchesJsonSchemaInClasspath("schemas/student-strict-v1.json"))
// Layer functional assertions on top of verified contract:
.body("studentId", equalTo("STU-88219"))
.body("fullName", equalTo("Nikita Sharma"));
System.out.println("[β] Strict contract validation passed: zero undeclared fields detected.");
}
}
additionalProperties: false triggers a fast-fail exception.
package com.nikita.restassured.schema;
import org.testng.Assert;
import org.testng.annotations.Test;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchema;
public class ContractDriftDetectionTest {
// Closed-world schema strictly allowing only 'id' and 'track'
private static final String CLOSED_SCHEMA = "{\n" +
" \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"required\": [\"id\", \"track\"],\n" +
" \"properties\": {\n" +
" \"id\": { \"type\": \"string\" },\n" +
" \"track\": { \"type\": \"string\" }\n" +
" }\n" +
"}";
@Test(description = "Verify validator flags unapproved backend property leak with fast-fail assertion")
public void testCatchUndeclaredFieldLeak() {
// Backend payload inadvertently leaking internal database and debug fields:
String driftPayload = "{\n" +
" \"id\": \"STU-88219\",\n" +
" \"track\": \"ENTERPRISE_AUTOMATION\",\n" +
" \"internalDatabaseRowId\": 9948210,\n" +
" \"debugEnvironment\": \"STAGE_CLUSTER_01\"\n" +
"}";
try {
// Attempting validation against closed schema
Assert.assertFalse(matchesJsonSchema(CLOSED_SCHEMA).matches(driftPayload),
"Strict validation must reject payload containing unapproved fields!");
System.out.println("[β] Successfully caught and rejected contract drift payload.");
} catch (AssertionError e) {
System.err.println("[!] Contract drift caught: " + e.getMessage());
throw e;
}
}
}
patternProperties with regex to govern dynamic dictionary keys (e.g. META_.* or custom headers) while setting additionalProperties: false to block non-conforming entries.
// ==============================================================================
// SCHEMA DEFINITION: src/test/resources/schemas/dynamic-metadata-schema.json
// ==============================================================================
// {
// "$schema": "http://json-schema.org/draft-07/schema#",
// "type": "object",
// "additionalProperties": false,
// "required": ["recordId", "customTags"],
// "properties": {
// "recordId": { "type": "string" },
// "customTags": {
// "type": "object",
// "additionalProperties": false,
// "patternProperties": {
// "^TAG_[A-Z0-9_]{3,20}$": {
// "type": "string",
// "maxLength": 50
// }
// }
// }
// }
// }
package com.nikita.restassured.schema;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
public class PatternPropertiesValidationTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Verify dynamic map validates regex pattern keys while disallowing non-matching keys")
public void testDynamicTagsWithStrictPatternProperties() {
// Response payload structure:
// {
// "recordId": "REC-99412",
// "customTags": {
// "TAG_CAMPUS_ZONE": "PUNE_WEST",
// "TAG_COHORT_YEAR": "2026"
// }
// }
given()
.baseUri(BASE_URI)
.pathParam("recordId", "REC-99412")
.when()
.get("/records/{recordId}/tags")
.then()
.statusCode(200)
// Validates that all dynamic map keys strictly match ^TAG_[A-Z0-9_]{3,20}$
// and additional non-matching keys are rejected by additionalProperties: false:
.body(matchesJsonSchemaInClasspath("schemas/dynamic-metadata-schema.json"));
System.out.println("[β] Dynamic map keys conformed to patternProperties regex with closed boundary.");
}
}
propertyNames keyword to require that all dictionary keys adhere to camelCase, snake_case, or uppercase enterprise naming standards.
package com.nikita.restassured.schema;
import org.testng.Assert;
import org.testng.annotations.Test;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchema;
public class PropertyNamesGovernanceTest {
// Schema enforcing strict lowercase snake_case on all object keys via propertyNames
private static final String KEY_GOVERNANCE_SCHEMA = "{\n" +
" \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n" +
" \"type\": \"object\",\n" +
" \"propertyNames\": {\n" +
" \"pattern\": \"^[a-z]+(_[a-z0-9]+)*$\"\n" +
" },\n" +
" \"additionalProperties\": { \"type\": \"string\" }\n" +
"}";
@Test(description = "Verify all dynamic JSON keys strictly follow snake_case syntax")
public void testPropertyNamesSyntaxGovernance() {
// Valid payload: all keys conform to snake_case
String validSnakeCaseJson = "{\n" +
" \"student_id\": \"STU-88219\",\n" +
" \"full_name\": \"Nikita Sharma\",\n" +
" \"campus_region\": \"Pune\"\n" +
"}";
Assert.assertTrue(matchesJsonSchema(KEY_GOVERNANCE_SCHEMA).matches(validSnakeCaseJson));
System.out.println("[β] Valid snake_case keys passed propertyNames rule.");
// Invalid payload: contains camelCase key 'academicTrack' violating the pattern
String invalidCamelCaseJson = "{\n" +
" \"student_id\": \"STU-88219\",\n" +
" \"academicTrack\": \"ENTERPRISE_AUTOMATION\"\n" +
"}";
Assert.assertFalse(matchesJsonSchema(KEY_GOVERNANCE_SCHEMA).matches(invalidCamelCaseJson));
System.out.println("[β] Disallowed camelCase key successfully rejected by propertyNames validator.");
}
}
additionalProperties: false across parent wrappers, child objects, array element definitions, and grandchild nodes.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "StrictNestedHierarchyContract",
"type": "object",
"additionalProperties": false,
"required": ["institutionCode", "department"],
"properties": {
"institutionCode": { "type": "string" },
"department": {
"type": "object",
"additionalProperties": false,
"required": ["deptId", "leadFaculty", "activeCourses"],
"properties": {
"deptId": { "type": "string" },
"leadFaculty": {
"type": "object",
"additionalProperties": false,
"required": ["facultyId", "name"],
"properties": {
"facultyId": { "type": "string" },
"name": { "type": "string" }
}
},
"activeCourses": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": false,
"required": ["code", "credits"],
"properties": {
"code": { "type": "string" },
"credits": { "type": "integer", "minimum": 1 }
}
}
}
}
}
}
}
additionalProperties: false into reusable ResponseSpecBuilder templates to enforce zero-tolerance contract testing globally.
package com.nikita.restassured.schema;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.ResponseSpecification;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThan;
public class StrictResponseSpecTest {
private ResponseSpecification strictContractSpec;
@BeforeClass
public void setupStrictContractSpecification() {
// Compile shared specification enforcing 200 OK + SLA + Strict Closed Schema
strictContractSpec = new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.expectResponseTime(lessThan(1200L))
// Enforces closed-world Draft-07 schema on all matching endpoints:
.expectBody(matchesJsonSchemaInClasspath("schemas/student-strict-v1.json"))
.build();
System.out.println("[*] Compiled Strict Contract ResponseSpecification with additionalProperties: false.");
}
@Test(description = "Verify endpoint inherits strict closed-world schema check from ResponseSpecification")
public void testEndpointWithStrictSpec() {
given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}")
.then()
// Evaluates transport status, SLA, and strict schema in one call:
.spec(strictContractSpec)
// Layer endpoint-specific value assertions:
.body("studentId", equalTo("STU-88219"));
System.out.println("[β] Verified endpoint against strict contract specification.");
}
}
package com.nikita.restassured.schema;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchema;
public class AdditionalPropertiesTriageTest {
// Strict schema allowing only 'id' and 'name'
private static final String RIGID_SCHEMA = "{\n" +
" \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"required\": [\"id\", \"name\"],\n" +
" \"properties\": {\n" +
" \"id\": { \"type\": \"string\" },\n" +
" \"name\": { \"type\": \"string\" }\n" +
" }\n" +
"}";
@Test(description = "Demonstrate diagnostic failure output when an unapproved field breaches the schema")
public void testDiagnoseUnapprovedFieldFailure() {
// Simulating broken backend response returning an unvetted 'legacyHash' property:
String payloadWithLeak = "{\n" +
" \"id\": \"STU-88219\",\n" +
" \"name\": \"Nikita Sharma\",\n" +
" \"legacyHash\": \"e8b2a0914f\"\n" +
"}";
// matchesJsonSchema(RIGID_SCHEMA).matches(payloadWithLeak);
}
// ==========================================================================
// DIAGNOSTIC FAILURE TRACE GENERATED BY VALIDATOR ENGINE:
// ==========================================================================
// java.lang.AssertionError: 1 expectation failed.
// Response body doesn't match expectation.
// Expected: The content to match the given a json schema.
// error: object instance has properties which are not allowed by the schema: ["legacyHash"]
// level: "error"
// schema: {"domain":"syntax","keyword":"additionalProperties"}
// instance: {"pointer":""}
// domain: "validation"
// keyword: "additionalProperties"
// unwanted: ["legacyHash"]
//
// ROOT CAUSE BREAKDOWN:
// 1. Keyword: "additionalProperties" triggered the failure
// 2. Unwanted Property: ["legacyHash"] was received but not declared in "properties"
// 3. Pointer: "" shows the violation occurred at the root object level
}
STRICT SCHEMA LOCKDOWN & ADDITIONALPROPERTIES SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β SCHEMA KEYWORD / METHOD β DSL / SYNTAX SIGNATURE β TARGET VALUE β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β additionalProperties β "additionalProperties": falseβ Boolean (false) β Rejects all undeclared fields β
β Typed additionalProps β "additionalProperties": {...}β Sub-schema β Enforces type on extra fields β
β patternProperties β "^TAG_[A-Z_]+$": {...} β Regex Map β Regex-constrained dynamic keysβ
β propertyNames β "propertyNames": {"pattern"} β String Pattern β Enforces key syntax (snake/..)β
β required β "required": ["k1", "k2", ..] β Array of Strings β Enforces mandatory presence β
β minProperties / maxPropsβ "minProperties": 2, "max..":5β Integer bounds β Restricts total field count β
β Classpath Validator β matchesJsonSchemaInClasspath β String path β Resolves strict schema in CI β
β Inline Validator β matchesJsonSchema(String) β JSON String β Tests dynamic inline schema β
β ResponseSpecification β .expectBody(matchesJson..) β Spec Builder β Centralizes strict contract β
β Checked Validation β with().checkedValidation(tr) β Schema Config β Strict conformance checking β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 STRICT SCHEMA TESTING BEST PRACTICES: β
β 1. Always set additionalProperties: false: Close the open-content loophole to catch data leaks. β
β 2. Apply additionalProperties: false recursively: Lock down root objects and nested child structures. β
β 3. Use patternProperties for dynamic maps: Combine regex key validation with additionalProperties:false β
β 4. Enforce propertyNames for naming standards: Standardize snake_case or camelCase key conventions. β
β 5. Embed strict schemas in ResponseSpecBuilder: Ensure all endpoints run closed-world validation. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ