Skip to content

Commit 9e8e538

Browse files
philipgreatPhilip Z
andauthored
Validate dynamic search input while retaining schema-drift warnings (#93)
* feat: normalize generated wire field metadata * feat: accept generated wire metadata registries * test: verify serialized checker wire contract * fix: validate dynamic search controls and preserve drift warnings (#92) * fix: validate dynamic search syntax before applying clauses (#92) * feat: add shared typed local search normalization (#92) * feat: compose local search with scoped native Java requests (#92) * ci: connect NVD secret and pin the OWASP scanner (#94) * test: exercise generated School dynamic search and related scope (#92) * test: keep School authorization independent of optional search (#92) --------- Co-authored-by: Philip Z <hello@teaql.io>
1 parent b48a379 commit 9e8e538

22 files changed

Lines changed: 952 additions & 11 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,8 @@ jobs:
2929
# intentionally do not inherit the runtime's SpotBugs build plugin.
3030
run: mvn spotbugs:check -pl '!examples/conformance/lib,!examples/conformance'
3131
- name: OWASP Dependency Check
32-
run: mvn org.owasp:dependency-check-maven:check
32+
env:
33+
NVD_API_KEY: ${{ secrets.NVD_API_KEY }}
34+
# Pass only the environment variable NAME on the command line, never
35+
# the secret value. Pin the scanner for non-inheriting example modules too.
36+
run: mvn -B org.owasp:dependency-check-maven:13.0.0:check -DnvdApiKeyEnvironmentVariable=NVD_API_KEY

‎examples/school-management/pom.xml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,11 @@
4343
</dependencyManagement>
4444

4545
<dependencies>
46+
<dependency>
47+
<groupId>io.teaql</groupId>
48+
<artifactId>teaql-query-json</artifactId>
49+
<version>${teaql.version}</version>
50+
</dependency>
4651
<dependency>
4752
<groupId>io.teaql</groupId>
4853
<artifactId>teaql-provider-spring-jdbc</artifactId>

‎examples/school-management/src/main/java/com/example/schoolmanagementservice/App.java‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ public CommandLineRunner teaQLConsoleStartup(
129129
school.auditAs("Create the School Query conformance fixture").save(context);
130130
}
131131

132+
verifyDynamicSearch(context);
132133
assertQuery(context, "string equality", Q.schools().withNameIs("Riverside Primary School"), 1);
133134
assertQuery(context, "string inequality", Q.schools().withNameIsNot("Another School"), 1);
134135
assertQuery(context, "string membership", Q.schools().withNameIn("Riverside Primary School", "Another School"), 1);
@@ -226,4 +227,48 @@ private static void assertQuery(
226227
private static void require(boolean condition, String message) {
227228
if (!condition) throw new IllegalStateException(message);
228229
}
230+
231+
private static void verifyDynamicSearch(UserContext context) {
232+
var models = java.util.Map.of(
233+
"School", new io.teaql.query.json.LocalDynamicSearch.Model(
234+
java.util.Map.of("name", "string"), java.util.Map.of("platform", "Platform")),
235+
"Platform", new io.teaql.query.json.LocalDynamicSearch.Model(
236+
java.util.Map.of("name", "string"), java.util.Map.of()));
237+
String input = """
238+
{"filter":{"name":"Riverside Primary School","platform.name":"Campus Learning Platform",
239+
"removed":"SECRET_VALUE","platform.removed":"SECRET_VALUE"},
240+
"orderBy":[{"field":"removed","direction":"asc"}]}
241+
""";
242+
// Authorization input is server-owned, never accepted from the JSON form.
243+
for (long authorizedPlatform : new long[] {1L, 2L}) {
244+
for (String searchInput : new String[] {input, "{}"}) {
245+
SchoolRequest<School> request = Q.schools().withNameIs("Riverside Primary School")
246+
.withPlatformMatching(Q.platforms().withIdIs(authorizedPlatform));
247+
request.setSize(2);
248+
request.orderByIdDescending();
249+
int hardLimit = request.hardLimit();
250+
var warnings = new java.util.ArrayList<io.teaql.query.json.LocalDynamicSearch.Warning>();
251+
io.teaql.query.json.LocalDynamicSearch.merge(request, searchInput, models, filter -> {
252+
if (!"$eq".equals(filter.operator())) {
253+
throw new IllegalArgumentException("This demo binding supports equality only");
254+
}
255+
return switch (filter.fieldPath()) {
256+
case "name" -> Q.schools().withNameIs(filter.value().textValue()).getSearchCriteria();
257+
case "platform.name" -> Q.schools().withPlatformMatching(
258+
Q.platforms().withIdIs(authorizedPlatform).withNameIs(filter.value().textValue()))
259+
.getSearchCriteria();
260+
default -> throw new IllegalArgumentException("Missing trusted demo binding");
261+
};
262+
}, order -> { throw new IllegalArgumentException("No demo order binding required"); }, warnings::add);
263+
SmartList<School> rows = request.comment("what: generated School dynamic search")
264+
.purpose("why: verify stale fields cannot bypass related authorization").executeForList(context);
265+
require(rows.size() == (authorizedPlatform == 1L ? 1 : 0),
266+
"Dynamic search lost its related authorization filter");
267+
require(warnings.size() == (searchInput.equals("{}") ? 0 : 3)
268+
&& request.hardLimit() == hardLimit && request.getSize() == 2,
269+
"Dynamic search warning or limit contract failed");
270+
}
271+
}
272+
System.out.println("PASS Java generated School dynamic search: related scope, drift warnings, typed bindings");
273+
}
229274
}

‎pom.xml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,7 @@
314314
<plugin>
315315
<groupId>org.owasp</groupId>
316316
<artifactId>dependency-check-maven</artifactId>
317-
<version>10.0.4</version>
317+
<version>13.0.0</version>
318318
<configuration>
319319
<ossindexAnalyzerEnabled>false</ossindexAnalyzerEnabled>
320320
</configuration>

‎teaql-core/src/main/java/io/teaql/core/checker/CheckResult.java‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package io.teaql.core.checker;
22

33
import java.time.LocalDateTime;
4+
import java.util.Locale;
45

56
public class CheckResult {
67
private RuleId ruleId;
@@ -12,6 +13,7 @@ public class CheckResult {
1213
private Object systemValue;
1314

1415
private String naturalLanguageStatement;
16+
private String sourceInstancePath;
1517

1618
public static CheckResult required(ObjectLocation location) {
1719
CheckResult checkResult = new CheckResult();
@@ -144,6 +146,27 @@ public void setNaturalLanguageStatement(String pNaturalLanguageStatement) {
144146
naturalLanguageStatement = pNaturalLanguageStatement;
145147
}
146148

149+
/** Exact RFC 6901 pointer submitted through an accepted input alias. */
150+
public String getSourceInstancePath() {
151+
return sourceInstancePath;
152+
}
153+
154+
public void setSourceInstancePath(String pSourceInstancePath) {
155+
sourceInstancePath = pSourceInstancePath;
156+
}
157+
158+
public WireCheckResult toWire(JsonFieldNamingProfile profile) {
159+
return new WireCheckResult(
160+
ruleId == null ? null : ruleId.name().toLowerCase(Locale.ROOT),
161+
rootType,
162+
location == null ? null : location.segments(),
163+
location == null ? null : location.instancePath(profile),
164+
sourceInstancePath,
165+
inputValue,
166+
systemValue,
167+
naturalLanguageStatement);
168+
}
169+
147170
public enum RuleId {
148171
MIN,
149172
MAX,
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package io.teaql.core.checker;
2+
3+
/** Model-selected naming policy for JSON fields and RFC 6901 instance paths. */
4+
public enum JsonFieldNamingProfile {
5+
CAMEL_CASE("camelCase"),
6+
SNAKE_CASE("snake_case"),
7+
PASCAL_CASE("PascalCase");
8+
9+
private final String modelValue;
10+
11+
JsonFieldNamingProfile(String pModelValue) {
12+
modelValue = pModelValue;
13+
}
14+
15+
public String modelValue() {
16+
return modelValue;
17+
}
18+
19+
public String render(String canonicalName) {
20+
if (this == SNAKE_CASE) {
21+
return canonicalName;
22+
}
23+
String[] parts = canonicalName.split("_", -1);
24+
StringBuilder result = new StringBuilder();
25+
for (int i = 0; i < parts.length; i++) {
26+
if (parts[i].isEmpty()) continue;
27+
if (i == 0 && this == CAMEL_CASE) {
28+
result.append(parts[i]);
29+
} else {
30+
result.append(Character.toUpperCase(parts[i].charAt(0)))
31+
.append(parts[i].substring(1));
32+
}
33+
}
34+
return result.toString();
35+
}
36+
37+
public static JsonFieldNamingProfile fromModelValue(String value) {
38+
if (value == null || value.isBlank() || "camelCase".equals(value)) {
39+
return CAMEL_CASE;
40+
}
41+
for (JsonFieldNamingProfile profile : values()) {
42+
if (profile.modelValue.equals(value)) return profile;
43+
}
44+
throw new IllegalArgumentException("Unsupported json_field_naming: " + value);
45+
}
46+
}

‎teaql-core/src/main/java/io/teaql/core/checker/ObjectLocation.java‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,18 +61,39 @@ public String nativePath() {
6161

6262
/** RFC 6901 JSON pointer using TeaQL's default lower-camel wire policy. */
6363
public String instancePath() {
64-
return render(true, true);
64+
return instancePath(JsonFieldNamingProfile.CAMEL_CASE);
65+
}
66+
67+
/** RFC 6901 JSON pointer rendered with the model-selected wire profile. */
68+
public String instancePath(JsonFieldNamingProfile profile) {
69+
return render(profile, true);
70+
}
71+
72+
public List<WireLocationSegment> segments() {
73+
List<WireLocationSegment> result = new ArrayList<>();
74+
for (ObjectLocation current = this; current != null; current = current.getParent()) {
75+
if (current instanceof HashLocation hash) {
76+
result.add(0, WireLocationSegment.property(hash.getMember()));
77+
} else if (current instanceof ArrayLocation array) {
78+
result.add(0, WireLocationSegment.index(array.getIndex()));
79+
}
80+
}
81+
return List.copyOf(result);
6582
}
6683

6784
private String render(boolean lowerCamel, boolean pointer) {
85+
return render(lowerCamel ? JsonFieldNamingProfile.CAMEL_CASE : null, pointer);
86+
}
87+
88+
private String render(JsonFieldNamingProfile profile, boolean pointer) {
6889
List<ObjectLocation> locations = new ArrayList<>();
6990
for (ObjectLocation current = this; current != null; current = current.getParent()) {
7091
locations.add(0, current);
7192
}
7293
StringBuilder result = new StringBuilder();
7394
for (ObjectLocation location : locations) {
7495
if (location instanceof HashLocation hash) {
75-
String member = lowerCamel ? lowerCamel(hash.getMember()) : hash.getMember();
96+
String member = profile == null ? hash.getMember() : profile.render(hash.getMember());
7697
if (pointer) {
7798
result.append('/').append(escapePointer(member));
7899
} else {
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package io.teaql.core.checker;
2+
3+
import java.util.List;
4+
5+
/** Stable external projection of a Checker violation. */
6+
public record WireCheckResult(
7+
String ruleId,
8+
String entityType,
9+
List<WireLocationSegment> location,
10+
String instancePath,
11+
String sourceInstancePath,
12+
Object inputValue,
13+
Object systemValue,
14+
String message) {}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package io.teaql.core.checker;
2+
3+
/** Canonical KSML property or array-index segment used by wire violations. */
4+
public record WireLocationSegment(String kind, String name, Integer index) {
5+
public static WireLocationSegment property(String name) {
6+
return new WireLocationSegment("property", name, null);
7+
}
8+
9+
public static WireLocationSegment index(int index) {
10+
return new WireLocationSegment("index", null, index);
11+
}
12+
}

‎teaql-core/src/test/java/io/teaql/core/checker/ObjectLocationTest.java‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package io.teaql.core.checker;
22

3+
import java.util.List;
34
import org.junit.Test;
45
import static org.junit.Assert.*;
56

@@ -14,9 +15,25 @@ public void rendersCanonicalNativeAndExternalPaths() {
1415
assertEquals("order_items[2].user_url", location.modelPath());
1516
assertEquals("orderItems[2].userUrl", location.nativePath());
1617
assertEquals("/orderItems/2/userUrl", location.instancePath());
18+
assertEquals("/order_items/2/user_url", location.instancePath(JsonFieldNamingProfile.SNAKE_CASE));
19+
assertEquals("/OrderItems/2/UserUrl", location.instancePath(JsonFieldNamingProfile.PASCAL_CASE));
1720
assertEquals("order_items[2].user_url", location.toString());
1821
}
1922

23+
@Test
24+
public void projectsCheckerResultWithProfileAndSubmittedAlias() {
25+
CheckResult result = CheckResult.required(ObjectLocation.hashRoot("user_url"));
26+
result.setRootType("customer_account");
27+
result.setSourceInstancePath("/user_url");
28+
29+
WireCheckResult wire = result.toWire(JsonFieldNamingProfile.CAMEL_CASE);
30+
assertEquals("required", wire.ruleId());
31+
assertEquals("customer_account", wire.entityType());
32+
assertEquals(List.of(WireLocationSegment.property("user_url")), wire.location());
33+
assertEquals("/userUrl", wire.instancePath());
34+
assertEquals("/user_url", wire.sourceInstancePath());
35+
}
36+
2037
@Test
2138
public void escapesJsonPointerMembers() {
2239
assertEquals("/a~0~1b", ObjectLocation.hashRoot("a~/b").instancePath());

0 commit comments

Comments
 (0)