mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 13:57:06 +00:00
Merge pull request #233 from dylanmtaylor/security/ai-core-bounds
security: bound ai-core redaction and template rendering; consent for params-only requests (CodeRabbit)
This commit is contained in:
@@ -202,8 +202,9 @@ impl Connection {
|
||||
return Err(ConnectionError::KeyHeader("a header name needs a connection that uses a key"));
|
||||
}
|
||||
}
|
||||
for (i, m) in self.models.iter().enumerate() {
|
||||
if self.models.iter().skip(i + 1).any(|o| o.id == m.id) {
|
||||
let mut seen = std::collections::HashSet::with_capacity(self.models.len());
|
||||
for m in &self.models {
|
||||
if !seen.insert(&m.id) {
|
||||
return Err(ConnectionError::DuplicateModel(m.id.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,9 +67,13 @@ impl Disclosure {
|
||||
}
|
||||
}
|
||||
|
||||
/// The distinct kinds of data this request sends.
|
||||
/// The distinct kinds of data this request sends. Parameters carry values the app chose,
|
||||
/// free text among them, so a request with any counts as sending text even with no inputs.
|
||||
pub fn kinds(&self) -> Vec<PayloadKind> {
|
||||
let mut kinds: Vec<PayloadKind> = self.items.iter().map(|i| i.kind).collect();
|
||||
if !self.param_names.is_empty() {
|
||||
kinds.push(PayloadKind::Text);
|
||||
}
|
||||
kinds.sort();
|
||||
kinds.dedup();
|
||||
kinds
|
||||
@@ -242,6 +246,17 @@ mod tests {
|
||||
assert!(ledger.needs_consent(&d, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parameters_alone_still_need_consent() {
|
||||
let only_params = Request::new(CapabilityId::parse("image.inpaint").unwrap()).with_param("negative", "a private note".into());
|
||||
let d = disclosure_for(&only_params);
|
||||
assert_eq!(d.kinds(), vec![PayloadKind::Text]);
|
||||
let mut ledger = ConsentLedger::default();
|
||||
assert!(ledger.needs_consent(&d, 0));
|
||||
ledger.grant(&d);
|
||||
assert!(!ledger.needs_consent(&d, 0));
|
||||
}
|
||||
|
||||
fn upscale_req() -> Request {
|
||||
Request::new(CapabilityId::parse("image.upscale").unwrap()).with_input(InputRole::Source, Payload::inline("image/png", vec![0; 10]).unwrap())
|
||||
}
|
||||
|
||||
@@ -40,13 +40,32 @@ impl fmt::Display for SecretString {
|
||||
}
|
||||
|
||||
/// Replaces every occurrence of each non-empty secret in `text` with `[redacted]`.
|
||||
///
|
||||
/// Matches are found in `text` itself, never in the markers already written, so the output is at
|
||||
/// most a fixed multiple of the input whatever the secrets are. Overlapping matches of different
|
||||
/// secrets become one marker.
|
||||
pub fn redact(text: &str, secrets: &[&SecretString]) -> String {
|
||||
let mut out = text.to_owned();
|
||||
for secret in secrets {
|
||||
if !secret.is_empty() {
|
||||
out = out.replace(secret.expose(), "[redacted]");
|
||||
const MARKER: &str = "[redacted]";
|
||||
let mut values: Vec<&str> = secrets.iter().map(|s| s.expose()).filter(|v| !v.is_empty()).collect();
|
||||
values.sort_unstable();
|
||||
values.dedup();
|
||||
let mut spans: Vec<(usize, usize)> = values.iter().flat_map(|v| text.match_indices(v).map(|(at, m)| (at, at + m.len()))).collect();
|
||||
spans.sort_unstable();
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut done = 0;
|
||||
let mut i = 0;
|
||||
while i < spans.len() {
|
||||
let (start, mut end) = spans[i];
|
||||
i += 1;
|
||||
while i < spans.len() && spans[i].0 < end {
|
||||
end = end.max(spans[i].1);
|
||||
i += 1;
|
||||
}
|
||||
out.push_str(&text[done..start]);
|
||||
out.push_str(MARKER);
|
||||
done = end;
|
||||
}
|
||||
out.push_str(&text[done..]);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -69,6 +88,24 @@ mod tests {
|
||||
assert_eq!(out, "bad key [redacted] ([redacted])");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redact_never_searches_its_own_markers() {
|
||||
// Each secret matches the marker the one before it wrote; replacing in turn doubled the
|
||||
// text for every secret.
|
||||
let r = SecretString::new("r");
|
||||
let marker = SecretString::new("[redacted]");
|
||||
let secrets: Vec<&SecretString> = std::iter::once(&r).chain(std::iter::repeat_n(&marker, 64)).collect();
|
||||
assert_eq!(redact("rrrr", &secrets), "[redacted][redacted][redacted][redacted]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redact_merges_overlapping_secrets() {
|
||||
let a = SecretString::new("abc");
|
||||
let b = SecretString::new("bcd");
|
||||
assert_eq!(redact("xabcdx", &[&a, &b]), "x[redacted]x");
|
||||
assert_eq!(redact("abcabc", &[&a]), "[redacted][redacted]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redact_ignores_empty_secret() {
|
||||
let s = SecretString::new("");
|
||||
|
||||
@@ -37,8 +37,11 @@ pub const SPEC_VERSION: u32 = 1;
|
||||
pub const MAX_SPEC_BYTES: usize = 32 * 1024;
|
||||
/// Most models one spec may offer.
|
||||
pub const MAX_MODELS: usize = 16;
|
||||
/// Largest rendered or stored template (a body, serialized).
|
||||
/// Largest stored template (a body, serialized).
|
||||
pub const MAX_TEMPLATE_BYTES: usize = 4 * 1024;
|
||||
/// Most text one rendered template may hold, summed over its strings with every substitution made.
|
||||
/// A slot may repeat, so this, not [`MAX_TEMPLATE_BYTES`], bounds what a prompt can grow to.
|
||||
pub const MAX_RENDERED_BYTES: usize = 4 * 1024 * 1024;
|
||||
/// Deepest JSON pointer.
|
||||
pub const MAX_POINTER_DEPTH: usize = 8;
|
||||
/// Most entries in a status table.
|
||||
|
||||
@@ -114,23 +114,40 @@ pub fn value_slots(template: &Value) -> Result<Vec<Slot>, String> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Renders one string. Fails past [`MAX_RENDERED_BYTES`](crate::spec::MAX_RENDERED_BYTES).
|
||||
pub fn render_text(text: &str, values: &Values<'_>) -> Result<String, String> {
|
||||
let mut left = crate::spec::MAX_RENDERED_BYTES;
|
||||
render_text_within(text, values, &mut left)
|
||||
}
|
||||
|
||||
/// Renders `text`, taking its length from `left`; a template that repeats a slot cannot outgrow it.
|
||||
fn render_text_within(text: &str, values: &Values<'_>, left: &mut usize) -> Result<String, String> {
|
||||
let mut out = String::new();
|
||||
for piece in pieces(text)? {
|
||||
match piece {
|
||||
Piece::Text(t) => out.push_str(&t),
|
||||
Piece::Slot(slot, name) => out.push_str(values.get(slot).ok_or_else(|| format!("{{{name}}} is not available in this call"))?),
|
||||
}
|
||||
let add = match &piece {
|
||||
Piece::Text(t) => t.as_str(),
|
||||
Piece::Slot(slot, name) => values.get(*slot).ok_or_else(|| format!("{{{name}}} is not available in this call"))?,
|
||||
};
|
||||
*left = left.checked_sub(add.len()).ok_or_else(|| format!("a rendered template is at most {} bytes", crate::spec::MAX_RENDERED_BYTES))?;
|
||||
out.push_str(add);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Renders every string value of `template`. Keys are never substituted.
|
||||
/// Renders every string value of `template`. Keys are never substituted. All strings together
|
||||
/// share one [`MAX_RENDERED_BYTES`](crate::spec::MAX_RENDERED_BYTES) budget.
|
||||
pub fn render_value(template: &Value, values: &Values<'_>) -> Result<Value, String> {
|
||||
let mut left = crate::spec::MAX_RENDERED_BYTES;
|
||||
render_value_within(template, values, &mut left)
|
||||
}
|
||||
|
||||
fn render_value_within(template: &Value, values: &Values<'_>, left: &mut usize) -> Result<Value, String> {
|
||||
Ok(match template {
|
||||
Value::String(s) => Value::String(render_text(s, values)?),
|
||||
Value::Array(items) => Value::Array(items.iter().map(|i| render_value(i, values)).collect::<Result<_, _>>()?),
|
||||
Value::Object(map) => Value::Object(map.iter().map(|(k, v)| Ok((k.clone(), render_value(v, values)?))).collect::<Result<_, String>>()?),
|
||||
Value::String(s) => Value::String(render_text_within(s, values, left)?),
|
||||
Value::Array(items) => Value::Array(items.iter().map(|i| render_value_within(i, values, left)).collect::<Result<_, _>>()?),
|
||||
Value::Object(map) => {
|
||||
Value::Object(map.iter().map(|(k, v)| Ok((k.clone(), render_value_within(v, values, left)?))).collect::<Result<_, String>>()?)
|
||||
}
|
||||
other => other.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -65,3 +65,15 @@ fn a_slot_with_no_value_is_an_error_not_an_empty_string() {
|
||||
let why = render_text("/jobs/{job_id}", &v).unwrap_err();
|
||||
assert!(why.contains("{job_id} is not available"), "{why}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_slots_share_one_rendered_budget() {
|
||||
let prompt = "x".repeat(64 * 1024);
|
||||
let v = Values { prompt: Some(&prompt), ..values() };
|
||||
let slots = vec![json!("{prompt}"); 16];
|
||||
assert!(render_value(&json!({ "a": slots }), &v).is_ok());
|
||||
let slots = vec![json!("{prompt}{prompt}{prompt}{prompt}"); 32];
|
||||
let why = render_value(&json!({ "a": slots }), &v).unwrap_err();
|
||||
assert!(why.contains("at most"), "{why}");
|
||||
assert!(render_text(&"{prompt}".repeat(128), &v).is_err());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user