Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/eql-bindings-context-label-redacted.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@cipherstash/eql': patch
---

**Two eql-bindings errors no longer show a field's label, and one no longer quotes stored bytes** (`stack-encrypt` feature, #1999). A label is an encryption context. `TargetError::Context` and `QueryLabelError::NotAColumn` no longer show it. On the data path, `stack-encrypt`'s `TargetError::Column` still shows the label until #1983 lands.

- `encryption::targets::TargetError::Context` was `"app/users/email" is not an EQL column identifier: expected two segments, table and column`. It is now `the field's label is not an EQL column identifier: expected two segments, table and column`.
- `encryption::query::QueryLabelError::NotAColumn` now starts `the query's label is not an EQL column identifier`. A typed query returns it inside `stack_encrypt::Error::Other`.
- `Debug` shows the label of both errors as `<redacted>`. Both types now write `Debug` by hand.
- Both variants keep their `label` field, so code that builds or matches them still compiles. Code that needs the label takes it from the plan or the query.
- `encryption::targets::TargetError::Stored` now shows only the kind, line, and column of the JSON parser's error, in its message and in `Debug`. The parser's own message could quote the stored ciphertext it refused. For example: `stored value is not a TextEq: unexpected data at line 1 column 19`. Its `source` field and `source()` still return the parser's error.
- `TargetError` prints every other variant in `Debug` as the derived `Debug` did.
15 changes: 15 additions & 0 deletions packages/eql/crates/eql-bindings/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- **Two column refusals no longer show the field's label** (#1999). A
label is an encryption context. The message of
`encryption::targets::TargetError::Context` now starts
`the field's label`, and the message of
`encryption::query::QueryLabelError::NotAColumn` now starts
`the query's label`. `Debug` shows the label of both as
`<redacted>`. Both variants keep their `label` field, so code that
builds or matches them still compiles. On the data path,
`stack-encrypt`'s `TargetError::Column` still shows the label until
#1983 lands.
- **`TargetError::Stored` no longer quotes the stored bytes** (#1999). Its
message and `Debug` now show only the kind, line, and column of the
JSON parser's error. The parser's own message could quote the stored
ciphertext it refused. The `source` field and `source()` still return
the parser's error.
- **The by-name target entry points borrow the plaintext as a `Frame`, and
open into an `OwnedFrame`** (#1955). `encryption::targets::encrypt`,
`encrypt_with` and `query`, and the `v4::targets` table, take the
Expand Down
63 changes: 58 additions & 5 deletions packages/eql/crates/eql-bindings/src/encryption/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,29 +396,46 @@ fn check_column(label: &Label) -> Result<(), Error> {
/// The label of a derived record's field reference is the record's scope and
/// the field's name, two segments, so a query from such a field reference is never
/// refused this way.
#[derive(Clone, Debug, PartialEq, Eq)]
///
/// The message and `Debug` leave out the label: a label is an encryption
/// context, and an error never shows a context's value.
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum QueryLabelError {
/// The label names no column: an EQL query value stores the
/// [`Identifier`] it queries, a two-segment label, table then column.
/// The data path refuses the same label as `TargetError::Context`.
NotAColumn {
/// The label, rendered.
/// The label, rendered. Never shown: not in the message or `Debug`.
/// Kept so that code which builds or matches this variant still
/// compiles.
label: String,
},
}

impl fmt::Display for QueryLabelError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotAColumn { label } => write!(
f,
"{label:?} is not an EQL column identifier: expected two segments, table and column"
Self::NotAColumn { .. } => f.write_str(
"the query's label is not an EQL column identifier: expected two segments, table \
and column",
),
}
}
}

/// The derived form, except that the label is shown as `<redacted>`.
impl fmt::Debug for QueryLabelError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotAColumn { .. } => f
.debug_struct("NotAColumn")
.field("label", &format_args!("<redacted>"))
.finish(),
}
}
}

impl std::error::Error for QueryLabelError {}

/// The column a query's label names. A field query calls `query` only
Expand Down Expand Up @@ -648,3 +665,39 @@ impl<Q: Serialize> Serialize for MatchTwin<Q> {
self.twin.serialize(serializer)
}
}

#[cfg(test)]
mod tests {
use super::*;

/// A label is an encryption context, and an error never shows a
/// context's value: not in the message, not in `Debug`.
#[test]
fn a_label_refusal_never_shows_the_label() {
let label = Label::new(&["tenant-acme", "users", "email"]).unwrap();
let Err(Error::Other(error)) = check_column(&label) else {
panic!("a three-segment label is not a column");
};
let refusal = error
.downcast_ref::<QueryLabelError>()
.expect("the refusal is a QueryLabelError");
assert!(matches!(
refusal,
QueryLabelError::NotAColumn { label } if label == "tenant-acme/users/email"
));
let shown = [
error.to_string(),
format!("{error:?}"),
format!("{refusal:#?}"),
];
for text in &shown {
assert!(!text.contains("tenant-acme"), "the label leaked: {text}");
}
assert_eq!(
error.to_string(),
"the query's label is not an EQL column identifier: expected two segments, table and \
column"
);
assert_eq!(format!("{refusal:?}"), "NotAColumn { label: <redacted> }");
}
}
163 changes: 158 additions & 5 deletions packages/eql/crates/eql-bindings/src/encryption/targets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,10 @@ pub fn target(name: &str) -> Option<&'static Target> {
/// are statements about the name, the context or the value. The encryption
/// itself failing arrives through the returned [`Pending`] as a
/// [`stack_encrypt::Error`].
#[derive(Debug, thiserror::Error)]
///
/// `Debug` is written by hand so that it leaves out
/// [`Context`](Self::Context)'s label, which is an encryption context.
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum TargetError {
/// No EQL type has this name.
Expand Down Expand Up @@ -281,9 +284,16 @@ pub enum TargetError {
},
/// The field's context is not an EQL column: an [`Identifier`] is a
/// two-segment label, table then column, and this label is not one.
#[error("{label:?} is not an EQL column identifier: expected two segments, table and column")]
///
/// The message and `Debug` leave out the label: a label is an
/// encryption context, and an error never shows a context's value.
#[error(
"the field's label is not an EQL column identifier: expected two segments, table and column"
)]
Context {
/// The label, rendered.
/// The label, rendered. Never shown: not in the message or `Debug`.
/// Kept so that code which builds or matches this variant still
/// compiles.
label: String,
},
/// The value is not of the type's plaintext kind. Nothing is converted:
Expand Down Expand Up @@ -323,16 +333,78 @@ pub enum TargetError {
},
/// The stored bytes do not parse as the type: not JSON, not this
/// domain's shape, or another EQL version.
#[error("stored value is not a {target}: {source}")]
///
/// The message and `Debug` give the parser's error by kind, line and
/// column only. The parser's own message can quote the input it
/// refused, and the input is stored ciphertext.
#[error(
"stored value is not a {target}: {}",
stack_encrypt::diagnostic::describe_json_error(source)
)]
Stored {
/// The type the bytes were read as.
target: &'static str,
/// What the parser refused.
/// What the parser refused. Its own `Display` and `Debug` can quote
/// the stored bytes, so do not print it.
#[source]
source: serde_json::Error,
},
}

/// The derived form, except that [`TargetError::Context`]'s label is shown
/// as `<redacted>`, and [`TargetError::Stored`]'s parser error by kind, line
/// and column only. A `Debug` of an error reaches logs through `unwrap` and
/// `{:?}`, so it keeps the rules the message keeps.
impl fmt::Debug for TargetError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unknown { name } => f.debug_struct("Unknown").field("name", name).finish(),
Self::Unproducible { name, reason } => f
.debug_struct("Unproducible")
.field("name", name)
.field("reason", reason)
.finish(),
Self::NoQuery { name } => f.debug_struct("NoQuery").field("name", name).finish(),
Self::DocumentQuery { name } => {
f.debug_struct("DocumentQuery").field("name", name).finish()
}
Self::NoIndex { name, index } => f
.debug_struct("NoIndex")
.field("name", name)
.field("index", index)
.finish(),
Self::Context { .. } => f
.debug_struct("Context")
.field("label", &format_args!("<redacted>"))
.finish(),
Self::Plaintext {
target,
expected,
found,
} => f
.debug_struct("Plaintext")
.field("target", target)
.field("expected", expected)
.field("found", found)
.finish(),
Self::Json { target, source } => f
.debug_struct("Json")
.field("target", target)
.field("source", source)
.finish(),
Self::Options { name } => f.debug_struct("Options").field("name", name).finish(),
Self::Stored { target, source } => f
.debug_struct("Stored")
.field("target", target)
.field(
"source",
&stack_encrypt::diagnostic::describe_json_error(source),
)
.finish(),
Comment thread
auxesis marked this conversation as resolved.
Resolved
}
}
}

/// Which cipher [`decrypt`] opens through: the client, which opens a value
/// sealed under any of its keysets, or one keyset, which refuses a value
/// sealed under another ([`stack_encrypt::Error::ForeignKeyset`]) before any
Expand Down Expand Up @@ -1021,6 +1093,87 @@ mod tests {
}
}

/// A label is an encryption context, and an error never shows a
/// context's value: not in the message, not in `Debug`.
#[test]
fn a_context_refusal_never_shows_the_label() {
let error = Identifier::from_label(&label(&["tenant-acme", "users", "email"])).unwrap_err();
let shown = [
error.to_string(),
format!("{error:?}"),
format!("{error:#?}"),
];
for text in &shown {
assert!(!text.contains("tenant-acme"), "the label leaked: {text}");
}
assert_eq!(
error.to_string(),
"the field's label is not an EQL column identifier: expected two segments, table and \
column"
);
assert_eq!(format!("{error:?}"), "Context { label: <redacted> }");
}

/// The parser's own message quotes the string it refused, and that
/// string is stored ciphertext: the message and `Debug` give the kind,
/// line and column only.
#[test]
fn a_stored_refusal_quotes_none_of_the_stored_value() {
let source = serde_json::from_str::<u8>(r#""marker-ciphertext""#).unwrap_err();
assert!(source.to_string().contains("marker"), "{source}");
let error = TargetError::Stored {
target: "TextEq",
source,
};
for text in [error.to_string(), format!("{error:?}")] {
assert!(!text.contains("marker"), "the stored value leaked: {text}");
}
assert_eq!(
error.to_string(),
"stored value is not a TextEq: unexpected data at line 1 column 19"
);
assert_eq!(
format!("{error:?}"),
"Stored { target: \"TextEq\", source: \"unexpected data at line 1 column 19\" }"
);
}

/// The hand-written `Debug` keeps the derived form for the variants that
/// carry no context.
#[test]
fn debug_keeps_the_derived_form_for_the_other_variants() {
assert_eq!(
format!(
"{:?}",
TargetError::NoIndex {
name: "TextEq",
index: "ore"
}
),
"NoIndex { name: \"TextEq\", index: \"ore\" }"
);
assert_eq!(
format!(
"{:?}",
TargetError::Plaintext {
target: "TextEq",
expected: ValueKind::String,
found: None,
}
),
"Plaintext { target: \"TextEq\", expected: String, found: None }"
);
assert_eq!(
format!(
"{:?}",
TargetError::Unknown {
name: "Nope".into()
}
),
"Unknown { name: \"Nope\" }"
);
}

#[test]
fn the_table_is_catalog_ordered_and_names_each_type_once() {
let names: Vec<&str> = targets().iter().map(|t| t.name).collect();
Expand Down
22 changes: 14 additions & 8 deletions packages/eql/tests/encryption/tests/targets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -343,17 +343,23 @@ mod given_text_eq {
let as_v3 = serde_json::to_vec(&payload).unwrap();

let error = refused(targets::decrypt("TextEq", &cipher, &email(), &as_v3));
let TargetError::Stored {
target: "TextEq",
source,
} = &error
else {
panic!("{error}");
};
// The parser's error names the version it refused. The message
// gives the parser's error by kind and position only, because the
// parser's own text can quote the stored bytes.
assert!(source.to_string().contains("version 3"), "{source}");
assert!(
matches!(
error,
TargetError::Stored {
target: "TextEq",
..
}
),
error
.to_string()
.starts_with("stored value is not a TextEq: "),
"{error}"
);
assert!(error.to_string().contains("version 3"), "{error}");
}

#[tokio::test]
Expand Down
Loading