Skip to content

Commit 67d0f94

Browse files
author
Philip Z
committed
fix: classify BETWEEN and phonetic operands before root SQL logs
1 parent 698b8c1 commit 67d0f94

4 files changed

Lines changed: 252 additions & 13 deletions

File tree

‎scripts/verify-examples.sh‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ fi
1313

1414
cd "$repo"
1515
mvn -q -DskipTests install
16-
mvn -q -pl teaql-sqlite -Dtest=DerivedQueryTraceSqliteTest test
16+
mvn -q -pl teaql-sqlite \
17+
-Dtest=DerivedQueryTraceSqliteTest,LikeIntentPrivacySqliteTest,TypedIntentPrivacySqliteTest test
1718
mvn -q -pl examples/business-id-runtime \
1819
-Dtest=BusinessIdRuntimeExampleTest test
1920
mvn -q -pl examples/security-foundations \

‎teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/SqlLikeIntent.java‎

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -52,18 +52,44 @@ private void expression(Expression expression, PortableSQLRepository<?> reposito
5252
} else if (expression instanceof SubQuerySearchCriteria subquery) {
5353
child(subquery.getDependsOn(), repository);
5454
} else if (expression instanceof FunctionApply function) {
55-
if (function instanceof TwoOperatorCriteria && function.getExpressions().size() == 2
56-
&& function.getOperator() instanceof Operator operator
57-
&& function.second() instanceof Parameter parameter
58-
&& ExpressionHelper.hasBuiltinParser(parameter, repository)
59-
&& parameter.getOperator() == operator) {
60-
var policy = ExpressionHelper.parameterPolicy(context, function, repository);
61-
if (io.teaql.core.utils.SensitiveLogNames.credential(parameter.getName()))
62-
policy = SqlParameterLogPolicy.CREDENTIAL;
63-
output.capture(List.of(policy), new Object[]{parameter.getValue()});
55+
if (function instanceof Between && function.getOperator() == Operator.BETWEEN
56+
&& function.getExpressions().size() == 3
57+
&& ExpressionHelper.hasBuiltinParser(function.first(), repository)) {
58+
// Each bound may have been rewritten independently; trust only matching typed operands.
59+
capture(function, function.second(), Operator.BETWEEN, repository);
60+
capture(function, function.third(), Operator.BETWEEN, repository);
61+
} else if (function instanceof TwoOperatorCriteria && function.getExpressions().size() == 2
62+
&& function.getOperator() instanceof Operator operator) {
63+
capture(function, function.second(), operator, repository);
64+
if (operator == Operator.EQUAL
65+
&& phonetic(function.first(), repository) instanceof PropertyReference
66+
&& phonetic(function.second(), repository) instanceof Parameter parameter) {
67+
// BaseRequest emits EQ(SOUNDEX(property), SOUNDEX(parameter)). Inherit
68+
// the enclosing field's policy, not the parameter's caller-supplied name.
69+
capture(function, parameter, Operator.SOUNDS_LIKE, repository);
70+
}
6471
}
6572
for (var child : function.getExpressions()) expression(child, repository);
6673
}
6774
}
6875

76+
private Expression phonetic(Expression expression, PortableSQLRepository<?> repository) {
77+
if (expression instanceof FunctionApply function
78+
&& ExpressionHelper.hasBuiltinParser(function, repository)
79+
&& function.getOperator() == Operator.SOUNDS_LIKE && function.getExpressions().size() == 1
80+
&& ExpressionHelper.hasBuiltinParser(function.first(), repository)) return function.first();
81+
return null;
82+
}
83+
84+
private void capture(Expression scope, Expression operand, Operator operator,
85+
PortableSQLRepository<?> repository) {
86+
if (!(operand instanceof Parameter parameter)
87+
|| !ExpressionHelper.hasBuiltinParser(parameter, repository)
88+
|| parameter.getOperator() != operator) return;
89+
var policy = ExpressionHelper.parameterPolicy(context, scope, repository);
90+
if (io.teaql.core.utils.SensitiveLogNames.credential(parameter.getName()))
91+
policy = SqlParameterLogPolicy.CREDENTIAL;
92+
output.capture(List.of(policy), new Object[]{parameter.getValue()});
93+
}
94+
6995
}

‎teaql-sqlite/src/test/java/io/teaql/sqlite/LikeIntentPrivacySqliteTest.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ private String pattern(String operand) {
4343
default -> "%" + operand;
4444
};
4545
}
46-
private static final class Request<T extends Entity> extends BaseRequest<T> {
46+
static final class Request<T extends Entity> extends BaseRequest<T> {
4747
private final String type;
4848
Request(Class<T> type, Supplier<T> factory) { super(type, factory); this.type = type.getSimpleName(); }
4949
@Override public String getTypeName() { return type; }
@@ -52,8 +52,8 @@ Request<T> where(String field, Operator op, String value) {
5252
}
5353
Request<T> intent(String text) { internalComment("inspect " + text); internalPurpose("render " + text); return this; }
5454
}
55-
private record Bind(String sql, List<Object> values) {}
56-
private static final class Fixture {
55+
record Bind(String sql, List<Object> values) {}
56+
static final class Fixture {
5757
final List<Bind> binds = new ArrayList<>();
5858
final List<ExecutionMetadata> safe = new ArrayList<>();
5959
final List<QueryIntent> policies = new ArrayList<>();
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
package io.teaql.sqlite;
2+
3+
import io.teaql.core.*;
4+
import io.teaql.core.criteria.*;
5+
import io.teaql.runtime.LogPrivacy;
6+
import java.util.*;
7+
import org.junit.Test;
8+
import org.junit.runner.RunWith;
9+
import org.junit.runners.Parameterized;
10+
import static org.junit.Assert.*;
11+
12+
/** Built-in BETWEEN/phonetic operands must be classified before any future child SQL. */
13+
@RunWith(Parameterized.class)
14+
public class TypedIntentPrivacySqliteTest {
15+
@Parameterized.Parameters(name="{0}, marked={1}, logging={2}")
16+
public static Collection<Object[]> cases() {
17+
var cases = new ArrayList<Object[]>();
18+
for (var op : List.of(Operator.BETWEEN, Operator.SOUNDS_LIKE))
19+
for (boolean marked : List.of(false, true))
20+
for (boolean logging : List.of(false, true)) cases.add(new Object[]{op, marked, logging});
21+
return cases;
22+
}
23+
24+
private final Operator op;
25+
private final boolean marked, logging;
26+
public TypedIntentPrivacySqliteTest(Operator op, boolean marked, boolean logging) {
27+
this.op = op; this.marked = marked; this.logging = logging;
28+
}
29+
private String field() { return marked ? "name" : "state"; }
30+
private List<String> operands(String prefix) {
31+
return op == Operator.BETWEEN ? List.of(prefix + "-SECRET", prefix + "-SECREZ")
32+
: List.of(prefix + "-SECRET");
33+
}
34+
private String intent(List<String> operands) { return String.join(" / ", operands); }
35+
private void predicate(LikeIntentPrivacySqliteTest.Request<?> request, List<String> operands) {
36+
request.appendSearchCriteria(request.createBasicSearchCriteria(field(), op, operands.toArray()));
37+
}
38+
private void assertPath(ExecutionMetadata entry, boolean child) {
39+
var expected = new ArrayList<>(List.of(
40+
new TraceNode(TraceKind.OPERATION, "TraceDocument", null, "query"),
41+
new TraceNode(TraceKind.REQUEST, "TraceDocument", null, "")));
42+
if (child) expected.add(new TraceNode(TraceKind.RELATION, "lines", null, "TraceDocument.lines"));
43+
expected.add(new TraceNode(TraceKind.PROVIDER, "sqlite", null, ""));
44+
expected.add(new TraceNode(TraceKind.SQL, "select", null, ""));
45+
assertEquals(expected, entry.getTraceChain());
46+
}
47+
private void assertProjection(LikeIntentPrivacySqliteTest.Fixture f,
48+
LikeIntentPrivacySqliteTest.Request<?> root, List<String> operands, boolean privateOperand, int count) {
49+
assertEquals(count, f.binds.size());
50+
assertEquals(count, f.last.statements().size());
51+
assertEquals(logging ? count : 0, f.safe.size());
52+
String text = intent(operands);
53+
String projected = privateOperand ? String.join(" / ", Collections.nCopies(operands.size(), "[REDACTED]")) : text;
54+
assertEquals("inspect " + text, root.comment());
55+
assertEquals("render " + text, root.purpose());
56+
assertEquals(root.comment(), f.policies.get(0).comment());
57+
assertEquals(root.purpose(), f.policies.get(0).purpose());
58+
for (int i = 0; i < count; i++) {
59+
var raw = f.last.statements().get(i);
60+
assertPath(raw, i > 0);
61+
assertEquals(root.comment(), raw.getComment());
62+
assertEquals(root.purpose(), raw.getPurpose());
63+
var safe = LogPrivacy.sql(raw, false);
64+
assertEquals("inspect " + projected, safe.getComment());
65+
assertEquals("render " + projected, safe.getPurpose());
66+
assertPath(safe, i > 0);
67+
assertNull(safe.getIntentRedactions());
68+
// Explicit debugging may reveal marked business operands, never by mutating raw intent.
69+
assertEquals(root.comment(), LogPrivacy.sql(raw, true).getComment());
70+
if (logging) {
71+
assertEquals(safe.getComment(), f.safe.get(i).getComment());
72+
assertEquals(safe.getPurpose(), f.safe.get(i).getPurpose());
73+
assertPath(f.safe.get(i), i > 0);
74+
assertNull(f.safe.get(i).getIntentRedactions());
75+
}
76+
}
77+
if (logging && privateOperand)
78+
for (String operand : operands) assertFalse(f.output.toString().contains(operand));
79+
if (!logging) assertEquals("", f.output.toString());
80+
assertTrue(f.context.getTraceChain().isEmpty());
81+
}
82+
private void independent(LikeIntentPrivacySqliteTest.Fixture f, List<String> operands) {
83+
f.clear();
84+
var request = f.documents().intent(intent(operands));
85+
assertEquals(2, f.run(request).size());
86+
assertProjection(f, request, operands, false, 1);
87+
}
88+
private void assertBinds(LikeIntentPrivacySqliteTest.Fixture f, List<String> operands, int index) {
89+
for (String operand : operands) assertTrue(f.binds.get(index).values().contains(operand));
90+
assertTrue(f.binds.get(index).sql().toUpperCase(Locale.ROOT)
91+
.contains(op == Operator.BETWEEN ? " BETWEEN " : "SOUNDEX("));
92+
}
93+
94+
@Test public void typedRootAndCachedRebindingKeepOriginalOperandsPrivate() throws Exception {
95+
var f = new LikeIntentPrivacySqliteTest.Fixture(logging);
96+
for (String prefix : List.of("FIRST", "SECOND")) {
97+
f.clear();
98+
var values = operands(prefix);
99+
var root = f.documents().intent(intent(values)); predicate(root, values);
100+
var rows = f.run(root);
101+
assertEquals(1, rows.size());
102+
assertEquals(prefix.equals("FIRST") ? 1L : 2L, rows.get(0).getId().longValue());
103+
assertBinds(f, values, 0);
104+
assertProjection(f, root, values, marked, 1);
105+
}
106+
independent(f, operands("FIRST"));
107+
}
108+
109+
@Test public void futureChildOperandsArePrivateBeforeFirstRootSql() throws Exception {
110+
var f = new LikeIntentPrivacySqliteTest.Fixture(logging);
111+
var values = operands("FIRST");
112+
var child = f.lines(); predicate(child, values); child.topNProbeParentThreshold(0);
113+
var root = f.documents().intent(intent(values)); root.enhanceRelation("lines", child);
114+
var rows = f.run(root);
115+
assertEquals(2, rows.size());
116+
var members = (SmartList<?>) rows.get(0).getProperty("lines");
117+
assertEquals(1, members.size()); assertEquals(Long.valueOf(11), members.get(0).getId());
118+
assertEquals(Long.valueOf(1), ((Entity) members.get(0).getProperty("document")).getId());
119+
var absent = (SmartList<?>) rows.get(1).getProperty("lines");
120+
assertTrue(absent == null || absent.isEmpty());
121+
for (String value : values) assertFalse(f.binds.get(0).values().contains(value));
122+
assertBinds(f, values, 1);
123+
assertProjection(f, root, values, marked, 2);
124+
independent(f, values);
125+
}
126+
127+
@Test public void futureAggregateOperandsArePrivateBeforeFirstRootSql() throws Exception {
128+
var f = new LikeIntentPrivacySqliteTest.Fixture(logging);
129+
var values = operands("FIRST");
130+
var count = f.lines(); predicate(count, values);
131+
count.setPartitionProperty("document"); count.count("count");
132+
var root = f.documents().intent(intent(values)); root.addSingleAggregateDynamicProperty("selectedLineCount", count);
133+
var rows = f.run(root);
134+
assertEquals(2, rows.size());
135+
assertEquals(1, ((Number) rows.get(0).getDynamicProperty("selectedLineCount")).intValue());
136+
assertEquals(0, ((Number) rows.get(1).getDynamicProperty("selectedLineCount")).intValue());
137+
for (String value : values) assertFalse(f.binds.get(0).values().contains(value));
138+
assertBinds(f, values, 1);
139+
assertTrue(f.binds.get(1).sql().toLowerCase(Locale.ROOT).contains("count("));
140+
assertProjection(f, root, values, marked, 2);
141+
independent(f, values);
142+
}
143+
144+
@Test public void parameterNamesCannotReplaceTheResolvedFieldPolicy() throws Exception {
145+
var f = new LikeIntentPrivacySqliteTest.Fixture(logging);
146+
var values = operands("FIRST");
147+
var child = f.lines();
148+
// Deliberately opposite metadata names: only the property reference determines field policy.
149+
String parameterName = marked ? "state" : "name";
150+
SearchCriteria criterion = op == Operator.BETWEEN
151+
? new Between(new PropertyReference(field()), new Parameter(parameterName, values.get(0), op),
152+
new Parameter(parameterName, values.get(1), op))
153+
: new EQ(new FunctionApply(op, new PropertyReference(field())),
154+
new FunctionApply(op, new Parameter(parameterName, values.get(0), op)));
155+
child.appendSearchCriteria(criterion); child.topNProbeParentThreshold(0);
156+
var root = f.documents().intent(intent(values)); root.enhanceRelation("lines", child);
157+
assertEquals(2, f.run(root).size());
158+
assertBinds(f, values, 1);
159+
assertProjection(f, root, values, marked, 2);
160+
independent(f, values);
161+
}
162+
163+
@Test public void rewrittenParameterOperatorsDoNotInventOriginalOperands() throws Exception {
164+
var f = new LikeIntentPrivacySqliteTest.Fixture(logging);
165+
var values = operands("FIRST");
166+
var child = f.lines();
167+
var rewritten = new Parameter(field(), values.get(0), Operator.CONTAIN);
168+
SearchCriteria criterion = op == Operator.BETWEEN
169+
? new Between(new PropertyReference(field()), rewritten, new Parameter(field(), values.get(1), op))
170+
: new EQ(new FunctionApply(op, new PropertyReference(field())), new FunctionApply(op, rewritten));
171+
child.appendSearchCriteria(criterion); child.topNProbeParentThreshold(0);
172+
var root = f.documents().intent(values.get(0)); root.enhanceRelation("lines", child);
173+
assertEquals(2, f.run(root).size());
174+
assertTrue(f.binds.get(1).values().contains("%" + values.get(0) + "%"));
175+
assertFalse(f.binds.get(1).values().contains(values.get(0)));
176+
assertProjection(f, root, List.of(values.get(0)), false, 2);
177+
assertEquals(values.get(0), rewritten.getValue());
178+
assertEquals(Operator.CONTAIN, rewritten.getOperator());
179+
}
180+
181+
@Test public void credentialOperandsStayPrivateEvenInExplicitDebugProjection() throws Exception {
182+
var f = new LikeIntentPrivacySqliteTest.Fixture(logging);
183+
var values = operands("FIRST");
184+
var child = f.lines();
185+
SearchCriteria criterion = op == Operator.BETWEEN
186+
? new Between(new PropertyReference(field()), new Parameter("apiKey", values.get(0), op),
187+
new Parameter("apiKey", values.get(1), op))
188+
: new EQ(new FunctionApply(op, new PropertyReference(field())),
189+
new FunctionApply(op, new Parameter("apiKey", values.get(0), op)));
190+
child.appendSearchCriteria(criterion); child.topNProbeParentThreshold(0);
191+
var root = f.documents().intent(intent(values)); root.enhanceRelation("lines", child);
192+
assertEquals(2, f.run(root).size());
193+
assertBinds(f, values, 1);
194+
String projected = String.join(" / ", Collections.nCopies(values.size(), "[REDACTED]"));
195+
assertEquals(2, f.last.statements().size());
196+
assertEquals(logging ? 2 : 0, f.safe.size());
197+
for (int i = 0; i < 2; i++) {
198+
var raw = f.last.statements().get(i); assertPath(raw, i > 0);
199+
assertEquals(root.comment(), raw.getComment()); assertEquals(root.purpose(), raw.getPurpose());
200+
for (boolean allowPlaintext : List.of(false, true)) {
201+
var safe = LogPrivacy.sql(raw, allowPlaintext);
202+
assertEquals("inspect " + projected, safe.getComment());
203+
assertEquals("render " + projected, safe.getPurpose());
204+
assertPath(safe, i > 0); assertNull(safe.getIntentRedactions());
205+
}
206+
if (logging) assertEquals("inspect " + projected, f.safe.get(i).getComment());
207+
}
208+
for (String value : values) assertFalse(f.output.toString().contains(value));
209+
assertTrue(f.context.getTraceChain().isEmpty());
210+
independent(f, values);
211+
}
212+
}

0 commit comments

Comments
 (0)