Skip to content

Commit 5374938

Browse files
committed
feat(go): bind a jsonpath predicate on a JsonSearch field as one parameter
An application that compiles a filter language into SQL targets jsonb_path_match(col, $1, $2): the predicate and its variables, two parameters. On an encrypted column the same filter was one Go call per leaf and a hand-assembled WHERE, one cast per parameter. The engine's match operator (#1441) compiles the predicate into one operand; this is the Go call on top (#1443). Fields.<Field>.Match(ctx, cipher, predicate, vars, opts) is generated on every JsonSearch field and returns eql.JSONSearchPredicateQuery, which binds as col @@ $1::eql_v4.query_json_predicate or eql_v4.json_tree_match(col, $1::...). The predicate crosses as text and vars as JSON text written by gensupport.JSONText, so Go adds no grammar: nil, or a value that writes null, sends no vars, and a Go string is refused as a Contains needle is. opts.WildcardBound bounds the filters that compile to the element match, as Elements.<Array>.Match takes it. The guest now names eql_v4.query_json_predicate, so the engine lists match (input predicate) on every JsonSearch field; the checker and stashgen read it, and stashgen refuses a document field the engine answers no match on. The guest maps Error::Predicate to STATUS_ENCODING: a refused predicate is the caller's input, not an internal failure. Diagnostic gains Construct and At, which read the construct and the byte offset the refusal carries. testusers.Entity grows the RC2 model's members (score, weight, address, country, preferred languages; $.weight ordered). The PostgreSQL test runs the seven filters of the customer's request and checks @@, json_tree_match, the per-operator query and jsonb_path_match over the plaintexts return the same rows; it joins go:test:postgres. Claude-Session: https://claude.ai/code/session_01MrxG73fnX1p7oiizh3GRG5
1 parent e0f14b1 commit 5374938

25 files changed

Lines changed: 1361 additions & 54 deletions

File tree

‎languages/golang/cmd/stashgen/main_test.go‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,18 @@ func TestRunGeneratesJSONSearchFields(t *testing.T) {
458458
if strings.Contains(written, "PrefsFieldElements") {
459459
t.Error("Prefs orders no member, and got Elements")
460460
}
461+
// Every document field has Match, ordered paths or none: what a
462+
// predicate may use is the engine's to decide when it compiles it.
463+
for _, field := range []string{"ProfileField", "PrefsField"} {
464+
for _, want := range []string{
465+
"func (f " + field + ") Match(ctx context.Context, c *encrypt.Cipher, predicate string, vars any, opts encrypt.JSONReadOptions) (eql.JSONSearchPredicateQuery, error)",
466+
"gensupport.JSONMatch[eql.JSONSearchPredicateQuery](ctx, f.field, c, predicate, vars, opts)",
467+
} {
468+
if !strings.Contains(written, want) {
469+
t.Errorf("the generated file lacks %q", want)
470+
}
471+
}
472+
}
461473
// The members of one array, named as At names their paths; an ordered
462474
// path that ends at its wildcard, or has none, is no array's member.
463475
written, stderr, code = generate("\tProfile json.RawMessage `stash:\"profile,encrypt_into=JsonSearch(ordered=$.extra.emergency_contacts[*].relationship;$.extra.emergency_contacts[*].previous_call_count;$.tags[*];$.age)\"`")
@@ -570,6 +582,19 @@ func TestRunGeneratesJSONSearchFields(t *testing.T) {
570582
if _, err := os.Stat(filepath.Join(dir, "customer_stash.go")); !os.IsNotExist(err) {
571583
t.Fatal("a file was written after the refusal")
572584
}
585+
// The same for any document field, ordered or not, and an engine that
586+
// answers no match.
587+
dir = writeModule(t, map[string]string{"model.go": source("\tProfile json.RawMessage `stash:\"profile,encrypt_into=JsonSearch\"`")})
588+
stderrBuf.Reset()
589+
if code := run([]string{"-type", "Customer"}, dir, &bytes.Buffer{}, &stderrBuf, withoutOperator("match")); code != 1 {
590+
t.Fatalf("exit %d, want 1\n%s", code, stderrBuf.String())
591+
}
592+
if got := stderrBuf.String(); !strings.Contains(got, "Customer.Profile") || !strings.Contains(got, "the engine answers no match on JsonSearch") {
593+
t.Fatalf("stderr = %q", got)
594+
}
595+
if _, err := os.Stat(filepath.Join(dir, "customer_stash.go")); !os.IsNotExist(err) {
596+
t.Fatal("a file was written after the refusal")
597+
}
573598
for _, c := range []struct{ name, fields, want string }{
574599
{"a sealed null", "\tPrefs *json.RawMessage `stash:\"prefs,encrypt_into=JsonSearch,null=sealed\"`", "Customer.Prefs: a nil has an equality term and no other, so another index's column would show which values are absent; write null=sql"},
575600
{"a nil document that does not say null=sql", "\tPrefs *json.RawMessage `stash:\"prefs,encrypt_into=JsonSearch\"`", "null=sql"},

‎languages/golang/encrypt/checker.go‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ func parseOperators(value any) ([]record.Operator, error) {
258258
op.Index, err = parseOperatorIndex(s)
259259
case "input":
260260
switch s {
261-
case "value", "pair", "json", "path_json", "path_pair", "path", "path_bound", "path_predicates":
261+
case "value", "pair", "json", "path_json", "path_pair", "path", "path_bound", "path_predicates", "predicate":
262262
op.Input = s
263263
default:
264264
return nil, fmt.Errorf("operator %d: unknown input %q", i, s)
@@ -282,14 +282,14 @@ func parseOperators(value any) ([]record.Operator, error) {
282282
// of the names the engine's OpSpec::parse accepts, the scalar operators
283283
// (eq, lt, lte, gt, gte, between, matches) and a document's (contains,
284284
// contained_by, eq_at, the orderings at a path, between_at, selector,
285-
// subtree, children, child_count, element_match). The catalog (se_targets) and se_query_term are
286-
// read through this, parseFidelity and parseOperatorIndex, so the two
287-
// readers refuse the same values.
285+
// subtree, children, child_count, element_match, match). The catalog
286+
// (se_targets) and se_query_term are read through this, parseFidelity and
287+
// parseOperatorIndex, so the two readers refuse the same values.
288288
func parseOperatorName(s string) (string, error) {
289289
switch s {
290290
case "eq", "lt", "lte", "gt", "gte", "between", "matches",
291291
"contains", "contained_by", "eq_at", "lt_at", "lte_at", "gt_at", "gte_at", "between_at",
292-
"selector", "subtree", "children", "child_count", "element_match":
292+
"selector", "subtree", "children", "child_count", "element_match", "match":
293293
return s, nil
294294
}
295295
return "", fmt.Errorf("unknown operator %q", s)

‎languages/golang/encrypt/errors.go‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -90,13 +90,15 @@ var ErrStorageVersion = vcffi.ErrUnsupportedVersion
9090
// returns after the sentinel's text), Help, URL, Severity, Fields (the
9191
// structured fields, by name) and Causes (the errors behind it, outermost
9292
// first). Accessors read the fields a caller branches on: ExpectedKeyset
93-
// and FoundKeyset on an [ErrForeignKeyset] (each a [KeysetID]'s bytes), and
94-
// Field and Reason on a refused plan, record or value.
93+
// and FoundKeyset on an [ErrForeignKeyset] (each a [KeysetID]'s bytes);
94+
// Field and Reason on a refused plan, record or value; and Construct and At
95+
// on a refused Match predicate, the construct in the grammar's words and
96+
// the byte offset in the predicate where it starts.
9597
//
9698
// What one may carry is fixed: keyset ids and names, field names, counts,
97-
// index kinds, ZeroKMS request kinds and HTTP statuses. Never plaintext,
98-
// key material, tokens, ciphertext or term bytes, or the values of an
99-
// encryption context.
99+
// index kinds, ZeroKMS request kinds and HTTP statuses, and a refused
100+
// predicate's construct and offset. Never plaintext, key material,
101+
// tokens, ciphertext or term bytes, or the values of an encryption context.
100102
//
101103
// Errors the client raises itself carry none: a closed client ([ErrState]),
102104
// a guest that did not return, [ErrMemoryLock], and an argument refused

‎languages/golang/encrypt/example/json/customer_stash.go‎

Lines changed: 40 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎languages/golang/encrypt/gensupport/json.go‎

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,16 @@ func JSONText(v any) ([]byte, error) {
7070
return nil, fmt.Errorf("%w: a %T does not write as JSON", encrypt.ErrEncoding, v)
7171
}
7272

73+
// isGoString reports whether v is a Go string, a type defined over one, or
74+
// a pointer to either, that encoding/json writes as one JSON string: one
75+
// with no MarshalJSON or MarshalText of its own. A containment needle and
76+
// Match's vars refuse it, since JSON text in a Go string is the likely
77+
// mistake.
78+
func isGoString(v any) bool {
79+
t := throughPointer(v)
80+
return t != nil && t.Kind() == reflect.String && writesItself(v) == ""
81+
}
82+
7383
// writesItself names the encoding/json interface v implements to write
7484
// itself, or "" for none.
7585
func writesItself(v any) string {
@@ -82,6 +92,13 @@ func writesItself(v any) string {
8292
return ""
8393
}
8494

95+
// isNilPointer reports whether v is a nil pointer of any type, which
96+
// carries no value whatever type it points to.
97+
func isNilPointer(v any) bool {
98+
rv := reflect.ValueOf(v)
99+
return rv.Kind() == reflect.Pointer && rv.IsNil()
100+
}
101+
85102
// throughPointer is v's dynamic type, or what it points to when it is a
86103
// pointer, or nil for nil: the one place the JSON operands look at a type
87104
// by kind, since a type switch cannot name every type defined over []byte
@@ -181,7 +198,7 @@ func (f Field[T]) jsonOperand(v any) ([]byte, error) {
181198
func JSONQuery[Q ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.Cipher, operator string, needle any) (Q, error) {
182199
// A Go string is one JSON string, and a document of members never
183200
// contains one: it is almost always JSON text meant as the needle.
184-
if t := throughPointer(needle); t != nil && t.Kind() == reflect.String && writesItself(needle) == "" {
201+
if isGoString(needle) {
185202
return nil, fmt.Errorf("%w: gensupport: %s: a %T needle is one JSON string, not JSON text; pass JSON text as json.RawMessage, or a map or struct", encrypt.ErrEncoding, f.name, needle)
186203
}
187204
if needle == nil {
@@ -306,6 +323,60 @@ func JSONElementMatch[Q ~[]byte, T any](ctx context.Context, f Field[T], c *encr
306323
return Q(term.Terms[0]), nil
307324
}
308325

326+
// JSONMatch derives match on a JSON field: the one operand
327+
// eql_v4.json_tree_match and `@@` take, a jsonpath predicate compiled into
328+
// a boolean tree of the other operators' operands. The predicate crosses
329+
// as it is: the engine parses and compiles it, and nothing here reads it.
330+
//
331+
// vars are the predicate's variables ($name), the jsonb that
332+
// jsonb_path_match takes third: any value [JSONText] writes as a JSON
333+
// object, such as a map, a struct or a json.RawMessage of one. nil, a nil
334+
// pointer of any type, a nil map, or a json.RawMessage of the literal null
335+
// sends none. Any other json.RawMessage crosses as it is, so an empty or
336+
// whitespace-only one is refused by the engine as not JSON, as "{" is. A Go
337+
// string or a non-nil pointer to one is refused, as [JSONQuery] refuses a
338+
// needle: it writes one JSON string, and JSON text in a Go string is the
339+
// likely mistake.
340+
//
341+
// What the engine refuses (text it does not read, a construct the index
342+
// cannot answer, a variable vars do not hold, vars that are not an
343+
// object, an ordering at a path the field does not order) is its
344+
// [encrypt.Diagnostic]. opts.WildcardBound 0 sends no bound, and the
345+
// engine's default, 64, applies.
346+
func JSONMatch[Q ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.Cipher, predicate string, vars any, opts encrypt.JSONReadOptions) (Q, error) {
347+
if f.err != nil {
348+
return nil, f.err
349+
}
350+
input := vcvalue.Object{{Key: "predicate", Value: predicate}}
351+
if vars != nil && !isNilPointer(vars) {
352+
if isGoString(vars) {
353+
return nil, fmt.Errorf("%w: gensupport: %s: Match takes vars as a JSON object, and a %T is one JSON string; pass JSON text as json.RawMessage, or a map or struct", encrypt.ErrEncoding, f.name, vars)
354+
}
355+
text, err := f.jsonOperand(vars)
356+
if err != nil {
357+
return nil, err
358+
}
359+
// The literal null, which encoding/json writes for a nil map, slice
360+
// or pointer: no variables. Anything else, empty text included, is
361+
// the engine's to read.
362+
if !bytes.Equal(bytes.TrimSpace(text), []byte("null")) {
363+
if text == nil {
364+
// A nil json.RawMessage is empty text, not an absent field.
365+
text = []byte{}
366+
}
367+
input = append(input, vcvalue.Field{Key: "vars", Value: text})
368+
}
369+
}
370+
if opts.WildcardBound != 0 {
371+
input = append(input, vcvalue.Field{Key: "wildcard_bound", Value: opts.WildcardBound})
372+
}
373+
term, err := f.jsonTerm(ctx, c, "match", "eql", 1, input)
374+
if err != nil {
375+
return nil, err
376+
}
377+
return Q(term.Terms[0]), nil
378+
}
379+
309380
// orderedMembers says which members of an array's elements the field
310381
// orders.
311382
func orderedMembers(members []string) string {

‎languages/golang/encrypt/guest/src/ops.rs‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -985,4 +985,61 @@ mod tests {
985985
Err(STATUS_ENCODING)
986986
);
987987
}
988+
989+
/// `match` on a JsonSearch field through the query exports: a
990+
/// predicate compiles to the predicate operand, and one the grammar
991+
/// refuses is the caller's input (`STATUS_ENCODING`), never the
992+
/// guest's own failure.
993+
#[cfg(feature = "eql")]
994+
#[test]
995+
fn a_compiled_predicate_derives_and_a_refused_one_is_the_callers_input() {
996+
use futures::executor::block_on;
997+
use stack_encrypt::StackCipher;
998+
use stack_kms::FakeDataKeySource;
999+
1000+
let cipher = block_on(StackCipher::builder().kms(FakeDataKeySource::new()).init())
1001+
.expect("a cipher");
1002+
let keyset = cipher.default_keyset();
1003+
let plan = encoded(object(vec![(
1004+
"profile",
1005+
object(vec![
1006+
("context", Tree::Array(vec![text("users"), text("profile")])),
1007+
("type", text("json")),
1008+
("null", text("sql")),
1009+
("target", text("JsonSearch")),
1010+
]),
1011+
)]));
1012+
let input = |predicate: &str| {
1013+
encoded(object(vec![
1014+
("predicate", text(predicate)),
1015+
("vars", text(r#"{"v": "nz"}"#)),
1016+
]))
1017+
};
1018+
1019+
let accepted = input("$.country == $v && exists($.tags[*])");
1020+
validate::query_term(&accepted, &plan, b"profile", b"match")
1021+
.expect("a field answers match");
1022+
let term =
1023+
block_on(query_term(&keyset, &accepted, &plan, b"profile", b"match")).expect("derives");
1024+
let Tree::Object(term) = Tree::from_frame(&term).expect("a value") else {
1025+
panic!("a query term is an object")
1026+
};
1027+
let text = |key: &str| match term.iter().find(|(k, _)| k == key) {
1028+
Some((_, Tree::String(s))) => s.as_bytes().to_vec(),
1029+
other => panic!("{key}: {other:?}"),
1030+
};
1031+
assert_eq!(text("operator"), b"match");
1032+
assert_eq!(text("domain"), b"eql_v4.query_json_predicate");
1033+
assert_eq!(text("encoding"), b"eql");
1034+
1035+
let refused = input(r#"$.country like_regex "n""#);
1036+
assert_eq!(
1037+
validate::query_term(&refused, &plan, b"profile", b"match"),
1038+
Err(STATUS_ENCODING)
1039+
);
1040+
assert_eq!(
1041+
block_on(query_term(&keyset, &refused, &plan, b"profile", b"match")),
1042+
Err(STATUS_ENCODING)
1043+
);
1044+
}
9881045
}

‎languages/golang/encrypt/guest/src/status.rs‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,8 +162,9 @@ pub fn status_for_error(error: &stack_encrypt::Error) -> u32 {
162162
/// A dynamic-path error as a status code.
163163
///
164164
/// The split the library draws is the one the ABI needs: `Context`, `Term`,
165-
/// `Plan`, `UntypedIndex`, `Source` and `Record` are each a statement about
166-
/// the caller's input, decided before any key is minted or retrieved, so they are
165+
/// `Plan`, `UntypedIndex`, `Source`, `Record` and `Predicate` are each a
166+
/// statement about the caller's input, decided before any key is minted or
167+
/// retrieved, so they are
167168
/// [`STATUS_ENCODING`] — named one by one, because that verdict is the
168169
/// host's to act on and must be given deliberately. `Cipher` defers to
169170
/// [`status_for_error`]; `Internal` is the library's own invariant failing
@@ -184,7 +185,11 @@ pub fn status_for_dynamic(error: &stack_encrypt::dynamic::Error) -> u32 {
184185
| Error::Plan { .. }
185186
| Error::UntypedIndex { .. }
186187
| Error::Source { .. }
187-
| Error::Record { .. } => STATUS_ENCODING,
188+
| Error::Record { .. }
189+
// A `match` predicate refused at an offset in its text: a construct
190+
// the grammar does not read or the index cannot answer, a variable
191+
// its vars do not hold, a value its comparison cannot take.
192+
| Error::Predicate { .. } => STATUS_ENCODING,
188193
Error::Cipher(e) => status_for_error(e),
189194
// A target refusal is a statement about the plan, the label or the
190195
// value (an unknown or unproducible type, an extended plan, a value
@@ -563,6 +568,15 @@ mod tests {
563568
reason: Reason::NoCiphertextNode,
564569
},
565570
),
571+
(
572+
"a refused predicate",
573+
Error::Predicate {
574+
field: age(),
575+
reason: Reason::JsonPredicateUnsupported,
576+
construct: "`like_regex`",
577+
at: 4,
578+
},
579+
),
566580
] {
567581
assert_eq!(
568582
status_for_dynamic(&err),

0 commit comments

Comments
 (0)