Skip to content

Commit 1ed1f3d

Browse files
committed
fix(stack-encrypt): address the review of the operator-typed query
- A match configuration whose `MatchCase` disagrees with its options is refused when the query is awaited, with the new `PlanError::MatchCase`, instead of answering in a case its index does not fold. `Supports` gains `check`. - `Supports::query` takes an `op::QueryToken` only this crate can make, so no caller can turn a stored term into a query term by hand. - `MatchTerms::matches(&MatchQuery)` tests a stored filter against a query; `MatchQuery::filter` is crate-only. - Docs say what is a compile error and what is refused when awaited: on a field of a fields plan, which is data, an undeclared index, other match options and a mislabelled case are runtime refusals. A typed field of a fields plan answers through the operator's default index, not its type's `Answers`; the ADR, `DefaultIndex` and the CHANGELOG say so. - `QueryTerm`'s doc no longer calls every term that refines nothing exact before `Probabilistic` exists. A broken ADR sentence is fixed. - `Operator::NAME` is gone (nothing read it); `Matches` is `Hash`. - Tests: the case mismatch, a refused query loading no named keyset (kills the `QueryOp::check` mutant), a query under a named keyset, and `MatchQuery`'s `Debug`. The three `via` mutants and `Matches::clone`'s are equivalent (unit structs) and are excluded in .cargo/mutants.toml. Claude-Session: https://claude.ai/code/session_01VYKAWbd361xDLmqBdLoUcB
1 parent fb99f8d commit 1ed1f3d

10 files changed

Lines changed: 280 additions & 67 deletions

File tree

‎.cargo/mutants.toml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,10 @@ exclude_re = [
7272
'stack-encrypt/src/cipher\.rs:\d+:\d+: replace client_key_provider -> EnvKeyProvider with Default::default\(\)$',
7373
'stack-encrypt/src/target/pending\.rs:443:9: replace <impl IntoFuture for Pending<.*>>::into_future -> Self::IntoFuture with Default::default\(\)$',
7474
# stack-encrypt — equivalent.
75+
# An operator and an operator's index are unit structs, whose `Default`
76+
# is the value `clone` and `via` already return.
77+
'stack-encrypt/src/op(/mod)?\.rs:\d+:\d+: replace <impl Clone for Matches<C>>::clone -> Self with Default::default\(\)$',
78+
'stack-encrypt/src/op(/mod)?\.rs:\d+:\d+: replace <impl (Answers<Eq, S> for EqualityTerm|DefaultIndex<S> for Eq|DefaultIndex<S> for Matches<<DefaultMatch as MatchCase>::Case>)>::via -> (Equality|Match) with Default::default\(\)$',
7579
'stack-encrypt/src/cipher\.rs:\d+:\d+: replace StackCipher<FromEnv>::builder -> StackCipherBuilder with Default::default\(\)$',
7680
'stack-encrypt/src/sem/mod\.rs:\d+:\d+: replace <impl MatchConfig for DefaultMatch>::options -> MatchOptions with Default::default\(\)$',
7781
# Both unit-context conversions explicitly return Self::default().

‎packages/stack-encrypt/CHANGELOG.md‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1515
operators it answers (`op::Supports`), a target type names the index that
1616
answers each one for it (`op::Answers`), and a plan that declares indexes
1717
uses the operator's default index (`op::DefaultIndex`). `.op_via(op, index)`
18-
names another index, such as a match index with its own configuration. An
19-
operator the plan cannot answer is a compile error; a case-sensitive
20-
`Matches` against a case-folding index is one too.
18+
names another index, such as a match index with its own configuration. What
19+
the plan's type shows is checked at compile time: a match query on an
20+
integer, an operator a target does not answer, and on a one-value plan an
21+
index it does not hold or a case-sensitive `Matches` against a
22+
case-folding index. On a field of a fields plan those are refused when the
23+
query is awaited, before any key is requested, as is a match configuration
24+
whose `op::MatchCase` disagrees with its options (`PlanError::MatchCase`).
2125
- **A match query has its own type, `sem::MatchQuery`.** It is the filter over
22-
the needle that the server tests a stored `MatchTerms` for, and it comes
23-
only from a query.
26+
the needle; test a stored filter against it with
27+
`MatchTerms::matches(&query)`. It comes only from a query chain:
28+
`op::Supports::query` takes an `op::QueryToken` that only this crate can
29+
make.
2430

2531
- **Errors now expose stable codes, help text, and structured details.**
2632
All error types implement `miette::Diagnostic` with codes such as

‎packages/stack-encrypt/CONTEXT.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -234,14 +234,16 @@ package's method name, not the concept)
234234
What a query asks of the server — equality, text match — as a unit type
235235
(`op::Eq`, `op::Matches`). An index declares the operators it answers and the
236236
query term it sends for each; a target type names the index that answers each
237-
operator for it. An operator nothing answers is a compile error (ADR-0009).
237+
operator for it. An operator nothing answers is refused before any key is
238+
requested: at compile time where the plan's type shows it, when the query is
239+
awaited where the plan is data (ADR-0009).
238240
_Avoid_: query type, index (that is what answers the operator)
239241

240242
**Query term**:
241243
The value a query sends to the server. It is not the stored term: equality
242244
sends the same HMAC it stores, but a match query is a filter over the needle,
243245
where the stored term is a filter over the whole value. A query term is never
244-
stored, and a stored term is never sent as a query.
246+
stored, and a query chain never sends a stored term as a query.
245247
_Avoid_: probe, stored term (that is what a write keeps)
246248

247249
**Open**:

‎packages/stack-encrypt/src/codes.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,10 @@ mod tests {
149149
..MatchOptions::default()
150150
}),
151151
},
152+
PlanError::MatchCase { .. } => PlanError::MatchCase {
153+
declared: "Insensitive",
154+
folds: false,
155+
},
152156
PlanError::TwoContextSources { .. } => PlanError::TwoContextSources {
153157
first: "the plan",
154158
second: "the call",

‎packages/stack-encrypt/src/dynamic/record.rs‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -556,9 +556,11 @@ fn refusal(error: crate::Error) -> (Option<String>, Reason) {
556556
P::IndexNotDeclared { field, .. } | P::IndexOptions { field, .. } => {
557557
(Some(field), Reason::Refused)
558558
}
559-
P::IdentityWithoutField | P::MixedCiphers | P::TwoContextSources { .. } | P::NoContext => {
560-
(None, Reason::Refused)
561-
}
559+
P::IdentityWithoutField
560+
| P::MixedCiphers
561+
| P::MatchCase { .. }
562+
| P::TwoContextSources { .. }
563+
| P::NoContext => (None, Reason::Refused),
562564
}
563565
}
564566

@@ -6795,6 +6797,15 @@ mod tests {
67956797
Refused,
67966798
),
67976799
(P::NoContext.into(), None, Refused),
6800+
(
6801+
P::MatchCase {
6802+
declared: "Sensitive",
6803+
folds: true,
6804+
}
6805+
.into(),
6806+
None,
6807+
Refused,
6808+
),
67986809
];
67996810
for (error, field, reason) in cases {
68006811
let shown = format!("{error:?}");

‎packages/stack-encrypt/src/op.rs‎

Lines changed: 65 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,15 @@
3535
//! - [`DefaultIndex<S>`] is on an operator, and names the index a plan that
3636
//! declares its indexes, rather than a target type, answers it with.
3737
//!
38-
//! An operator a plan cannot answer is a compile error: a match query on an
39-
//! integer, a case-sensitive match against a case-folding index, or an
40-
//! operator a target type does not answer. An index the plan does not
41-
//! declare is refused when the query is awaited, as with
38+
//! What the types can see is checked at compile time: a match query on an
39+
//! integer, an operator a target type does not answer, and, on a one-value
40+
//! plan, an index the plan does not hold or a case-sensitive match against
41+
//! a case-folding index. A field of a fields plan is data, so there an
42+
//! index the field does not declare, or declares with other options, is
43+
//! refused when the query is awaited, as with
4244
//! [`index`](crate::plan::QueryUsing::index), before any key is requested.
45+
//! So is a match configuration whose [`MatchCase`] disagrees with its
46+
//! options.
4347
//!
4448
//! The module is meant to be used by path (`op::Eq`): an imported `Eq`
4549
//! would shadow the prelude's `Eq` trait.
@@ -51,23 +55,19 @@ use std::marker::PhantomData;
5155

5256
use crate::sem::{DefaultMatch, EqualityTerm, MatchConfig, MatchQuery, MatchTerms};
5357
use crate::target::{Equality, Index, Match};
58+
use crate::PlanError;
5459

5560
/// A query operator: a unit type naming what a query asks of the server.
5661
///
5762
/// The trait is open, as [`Index`] is: an operator defined in another crate
5863
/// is answered by the indexes that implement [`Supports`] for it.
59-
pub trait Operator: Copy + 'static {
60-
/// The operator's name, as a binding or an error message spells it.
61-
const NAME: &'static str;
62-
}
64+
pub trait Operator: Copy + 'static {}
6365

6466
/// Equality: rows whose value equals the query's.
6567
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
6668
pub struct Eq;
6769

68-
impl Operator for Eq {
69-
const NAME: &'static str = "eq";
70-
}
70+
impl Operator for Eq {}
7171

7272
/// Text search: rows whose text contains the needle's tokens, under the
7373
/// match index's tokenizer. Not containment: a Bloom match is order- and
@@ -105,15 +105,16 @@ impl<C> PartialEq for Matches<C> {
105105
}
106106
}
107107
impl<C> std::cmp::Eq for Matches<C> {}
108+
impl<C> std::hash::Hash for Matches<C> {
109+
fn hash<H: std::hash::Hasher>(&self, _: &mut H) {}
110+
}
108111
impl<C: Case> fmt::Debug for Matches<C> {
109112
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110113
write!(f, "Matches<{}>", C::NAME)
111114
}
112115
}
113116

114-
impl<C: Case> Operator for Matches<C> {
115-
const NAME: &'static str = "matches";
116-
}
117+
impl<C: Case> Operator for Matches<C> {}
117118

118119
mod sealed {
119120
pub trait Sealed {}
@@ -151,9 +152,12 @@ impl Case for Sensitive {
151152
/// index answers are known at compile time.
152153
///
153154
/// `Case::FOLDS` must equal the configuration's
154-
/// [`MatchOptions::downcase`](crate::sem::MatchOptions::downcase). A
155-
/// configuration that does not implement this can still store and query
156-
/// match terms; it cannot be queried by [`Matches`].
155+
/// [`MatchOptions::downcase`](crate::sem::MatchOptions::downcase): the type
156+
/// cannot see the options, so a query through a configuration whose two
157+
/// disagree is refused when it is awaited, with
158+
/// [`PlanError::MatchCase`]. A configuration
159+
/// that does not implement this can still store match terms and query them
160+
/// by index; it cannot be queried by [`Matches`].
157161
pub trait MatchCase: MatchConfig {
158162
/// The case the configuration's index answers.
159163
type Case: Case;
@@ -165,8 +169,10 @@ impl MatchCase for DefaultMatch {
165169

166170
/// A value a query sends to the server to compare against stored terms.
167171
///
168-
/// A term that implements this and nothing more is *exact*: the server's
169-
/// answer is the answer.
172+
/// This trait says only that a value is a query term. How far the server's
173+
/// answer can be trusted is said by the traits that refine it: a term that
174+
/// can return false positives says how a row is checked (ADR-0009,
175+
/// decision 4), and one that refines nothing is exact.
170176
pub trait QueryTerm {}
171177

172178
impl QueryTerm for EqualityTerm {}
@@ -187,14 +193,34 @@ impl<O> QueryTerm for MatchQuery<O> {}
187193
pub trait Supports<Op: Operator, S>: Index<S> {
188194
/// What this index sends for `Op`.
189195
type Query: QueryTerm;
196+
/// Why this index cannot answer `Op` as configured, if it cannot: a
197+
/// match index whose [`MatchCase`] disagrees with its options.
198+
fn check(&self) -> Result<(), PlanError>;
190199
/// The query term, from the term the index derived for the query's
191-
/// value.
192-
fn query(term: Self::Term) -> Self::Query;
200+
/// value. Only a query chain calls this: `QueryToken` cannot be made
201+
/// outside this crate, so a stored term cannot be passed off as a
202+
/// query.
203+
fn query(term: Self::Term, token: QueryToken) -> Self::Query;
204+
}
205+
206+
/// Proof that [`Supports::query`] is called by a query chain. Only this
207+
/// crate can make one, so an index in another crate can implement
208+
/// [`Supports`] but no caller can turn a term into a query term by hand.
209+
#[derive(Debug)]
210+
pub struct QueryToken(());
211+
212+
impl QueryToken {
213+
pub(crate) fn new() -> Self {
214+
Self(())
215+
}
193216
}
194217

195218
impl<S: vitaminc_prf::PrfValue> Supports<Eq, S> for Equality {
196219
type Query = EqualityTerm;
197-
fn query(term: EqualityTerm) -> EqualityTerm {
220+
fn check(&self) -> Result<(), PlanError> {
221+
Ok(())
222+
}
223+
fn query(term: EqualityTerm, _: QueryToken) -> EqualityTerm {
198224
term
199225
}
200226
}
@@ -205,7 +231,18 @@ where
205231
O: MatchCase,
206232
{
207233
type Query = MatchQuery<O>;
208-
fn query(term: MatchTerms<O>) -> MatchQuery<O> {
234+
fn check(&self) -> Result<(), PlanError> {
235+
let folds = O::options().downcase;
236+
if folds == O::Case::FOLDS {
237+
Ok(())
238+
} else {
239+
Err(PlanError::MatchCase {
240+
declared: O::Case::NAME,
241+
folds,
242+
})
243+
}
244+
}
245+
fn query(term: MatchTerms<O>, _: QueryToken) -> MatchQuery<O> {
209246
MatchQuery::from_terms(term)
210247
}
211248
}
@@ -272,7 +309,10 @@ impl<Op: Operator, S, T: Answers<Op, S>> Answers<Op, S> for crate::target::Encry
272309
///
273310
/// A plan that declares a different index for the operator, such as a
274311
/// match index with its own configuration, names it with
275-
/// `.op_via(op, index)`.
312+
/// `.op_via(op, index)`. So does a typed field of a fields plan
313+
/// (`encrypt_into::<T, _>(name)`): the field's type is not known where the
314+
/// query is written, so its [`Answers`] impl is not consulted, and a field
315+
/// whose type answers through another index needs `op_via`.
276316
#[diagnostic::on_unimplemented(
277317
message = "`{Self}` has no default index over `{S}`",
278318
label = "no default index answers this operator here",
@@ -313,7 +353,7 @@ mod tests {
313353

314354
#[test]
315355
fn an_operator_is_equal_to_itself() {
316-
assert_eq!(Matches::<Insensitive>::new(), Matches::default());
356+
assert_eq!(Matches::<Insensitive>::new(), Matches::new());
317357
assert_eq!(Eq, Eq);
318358
}
319359

‎packages/stack-encrypt/src/plan/chain.rs‎

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use super::build::{FieldPlan, FieldsBuilder, IntoLabel, Opens, PlanContext, Runs
1111
use super::field_ref::FieldRef;
1212
use super::value::{Indexed, Typed, ValuePlan, ValueShape};
1313
use super::PlanError;
14-
use crate::op::{Answers, DefaultIndex, Operator, Supports};
14+
use crate::op::{Answers, DefaultIndex, Operator, QueryToken, Supports};
1515
use crate::target::{
1616
ciphertext, Borrowed, CallerContext, DeclaredContext, DecryptField, Decryptable, EncryptFrom,
1717
Index, Indexes, Owned, Pending, PendingFuture, Select,
@@ -643,10 +643,7 @@ impl<'a, F: 'static, K: 'static> QueryUsing<'a, F, FieldPlan, K> {
643643
Op: Operator,
644644
I: Supports<Op, F>,
645645
{
646-
QueryOp {
647-
inner: self.index(index),
648-
op: PhantomData,
649-
}
646+
QueryOp::new(self.index(index))
650647
}
651648

652649
/// The term of `index`. The field must have declared it, and the query's
@@ -690,10 +687,7 @@ impl<'a, F: 'static, X: Indexes<F>, K: 'static> QueryUsing<'a, F, ValuePlan<F, I
690687
I: Supports<Op, F> + Clone,
691688
X: Select<I, At>,
692689
{
693-
QueryOp {
694-
inner: self.index::<I, At>(),
695-
op: PhantomData,
696-
}
690+
QueryOp::new(self.index::<I, At>())
697691
}
698692

699693
/// The term of the plan's index of type `I`, selected by type
@@ -741,10 +735,7 @@ where
741735
Op: Operator,
742736
I: Supports<Op, F>,
743737
{
744-
QueryOp {
745-
inner: self.index(index),
746-
op: PhantomData,
747-
}
738+
QueryOp::new(self.index(index))
748739
}
749740

750741
/// The term of `index`. The target must declare it
@@ -814,6 +805,20 @@ pub struct QueryOp<'a, F, Op, I, K> {
814805
op: PhantomData<fn() -> Op>,
815806
}
816807

808+
impl<'a, F, Op: Operator, I: Supports<Op, F>, K: 'static> QueryOp<'a, F, Op, I, K> {
809+
/// The chain for `inner`'s index, refused when awaited if the index
810+
/// cannot answer `Op` as it is configured.
811+
fn new(mut inner: QueryIndex<'a, F, I, K>) -> Self {
812+
if let Err(error) = inner.index.check() {
813+
inner.label = Err(error);
814+
}
815+
Self {
816+
inner,
817+
op: PhantomData,
818+
}
819+
}
820+
}
821+
817822
impl<'a, F, Op, I, K: 'static> QueryOp<'a, F, Op, I, K> {
818823
/// Run under this keyset, as [`QueryBuilder::keyset`].
819824
pub fn keyset(mut self, keyset: impl Into<KeysetChoice<'a, K>>) -> Self {
@@ -857,7 +862,7 @@ where
857862
{
858863
self.inner
859864
.prepare(keyset, scoped)
860-
.map(<I as Supports<Op, F>>::query)
865+
.map(|term| I::query(term, QueryToken::new()))
861866
}
862867
}
863868

‎packages/stack-encrypt/src/plan/error.rs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,23 @@ pub enum PlanError {
183183
/// The index as the query asked for it.
184184
asked: IndexSpec,
185185
},
186+
/// A match configuration's [`MatchCase`](crate::op::MatchCase) names one
187+
/// case and its options fold the other, so a `Matches` query would be
188+
/// asked in a case its index does not answer.
189+
#[error(
190+
"a match configuration declares the case {declared} but its options {}",
191+
if *folds { "fold case" } else { "keep case" }
192+
)]
193+
#[diagnostic(
194+
code(stack_encrypt::plan_match_case),
195+
help("Make `MatchCase::Case` agree with `MatchConfig::options().downcase`: `Insensitive` when it is true, `Sensitive` when it is false.")
196+
)]
197+
MatchCase {
198+
/// The case `MatchCase::Case` names: `Insensitive` or `Sensitive`.
199+
declared: &'static str,
200+
/// Whether the configuration's options fold case.
201+
folds: bool,
202+
},
186203
/// The plan's context was given twice. A plan takes its context from
187204
/// exactly one place: the plan, the call that runs it, or a context
188205
/// field.
@@ -263,6 +280,9 @@ impl crate::ErrorPayload for PlanError {
263280
("declared", index_value(declared)),
264281
("asked", index_value(asked)),
265282
]),
283+
Self::MatchCase { declared, folds } => {
284+
payload([("declared", (*declared).into()), ("folds", (*folds).into())])
285+
}
266286
Self::TwoContextSources { first, second } => {
267287
payload([("first", (*first).into()), ("second", (*second).into())])
268288
}

0 commit comments

Comments
 (0)