返回 CodeWhale
consent.rs
根目录 / crates / engine / src / tools / web / consent.rs
1 use std::sync::atomic::{AtomicU8, Ordering};
2 use std::sync::{Arc, Mutex, PoisonError};
3
4 use codewhale_runtime::config::{SearchProvider, SearchProviderOption};
5 use serde_json::{Value, json};
6
7 use crate::tools::spec::ToolContext;
8
9 pub const CONSENT_MARKER_KEY: &str = "third_party_search";
10 pub const CONSENT_MARKER_VERSION: u64 = 1;
11 pub const CONSENT_APPROVAL_KEY_PREFIX: &str = "search-consent:";
12
13 pub const DECLINED_MESSAGE: &str = "Web search is off: the person chose not to send searches to a third-party search service. Continue without searching the web. They can turn it back on with `/config search.third_party on`.";
14 pub const WITHHELD_MESSAGE: &str = "Third-party web search has not been enabled yet, so this search was not sent. Continue without searching the web.";
15
16 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
17 pub enum ThirdPartySearch {
18 #[default]
19 Allowed,
20 Withheld,
21 Declined,
22 }
23
24 impl ThirdPartySearch {
25 const fn to_u8(self) -> u8 {
26 match self {
27 Self::Allowed => 0,
28 Self::Withheld => 1,
29 Self::Declined => 2,
30 }
31 }
32
33 const fn from_u8(value: u8) -> Self {
34 match value {
35 1 => Self::Withheld,
36 2 => Self::Declined,
37 _ => Self::Allowed,
38 }
39 }
40
41 #[must_use]
42 pub const fn allows_third_party(self) -> bool {
43 matches!(self, Self::Allowed)
44 }
45
46 #[must_use]
47 pub const fn refusal_message(self) -> Option<&'static str> {
48 match self {
49 Self::Allowed => None,
50 Self::Withheld => Some(WITHHELD_MESSAGE),
51 Self::Declined => Some(DECLINED_MESSAGE),
52 }
53 }
54 }
55
56 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
57 pub struct ChosenSearch {
58 pub provider: SearchProvider,
59 pub native_off: bool,
60 }
61
62 #[derive(Debug, Default)]
63 struct PermitState {
64 value: AtomicU8,
65 chosen: Mutex<Option<ChosenSearch>>,
66 }
67
68 #[derive(Debug, Clone, Default)]
69 pub struct ThirdPartySearchPermit(Arc<PermitState>);
70
71 impl ThirdPartySearchPermit {
72 #[must_use]
73 pub fn new(value: ThirdPartySearch) -> Self {
74 let permit = Self::default();
75 permit.set(value);
76 permit
77 }
78
79 #[must_use]
80 pub fn get(&self) -> ThirdPartySearch {
81 ThirdPartySearch::from_u8(self.0.value.load(Ordering::SeqCst))
82 }
83
84 pub fn set(&self, value: ThirdPartySearch) {
85 self.0.value.store(value.to_u8(), Ordering::SeqCst);
86 }
87
88 pub fn choose(&self, chosen: Option<ChosenSearch>) {
89 *self.0.chosen.lock().unwrap_or_else(PoisonError::into_inner) = chosen;
90 }
91
92 #[must_use]
93 pub fn chosen(&self) -> Option<ChosenSearch> {
94 *self.0.chosen.lock().unwrap_or_else(PoisonError::into_inner)
95 }
96 }
97
98 #[must_use]
99 pub fn with_chosen_search(context: &ToolContext) -> Option<ToolContext> {
100 let chosen = context.third_party_search.chosen()?;
101 let clear_native = chosen.native_off && context.provider_native_search.is_some();
102 if chosen.provider == context.search_provider && !clear_native {
103 return None;
104 }
105 let mut adjusted = context.clone();
106 adjusted.search_provider = chosen.provider;
107 if chosen.native_off {
108 adjusted.provider_native_search = None;
109 }
110 Some(adjusted)
111 }
112
113 fn self_hosted_base_url(context: &ToolContext) -> bool {
114 context
115 .search_base_url
116 .as_deref()
117 .is_some_and(|url| !url.trim().is_empty())
118 }
119
120 #[must_use]
121 pub fn backend_is_third_party(context: &ToolContext, provider: SearchProvider) -> bool {
122 match provider {
123 SearchProvider::Searxng => false,
124 SearchProvider::DuckDuckGo => {
125 !(context.search_provider == SearchProvider::DuckDuckGo
126 && self_hosted_base_url(context))
127 }
128 _ => true,
129 }
130 }
131
132 #[must_use]
133 pub fn first_backend_is_third_party(context: &ToolContext) -> bool {
134 !super::backend::provider_native_leads(context)
135 && backend_is_third_party(context, context.search_provider)
136 }
137
138 #[must_use]
139 pub fn search_refusal(context: &ToolContext) -> Option<&'static str> {
140 let permit = context.third_party_search.get();
141 if permit.allows_third_party() || !first_backend_is_third_party(context) {
142 return None;
143 }
144 permit.refusal_message()
145 }
146
147 #[must_use]
148 pub fn planned_search_refusal(
149 tool_name: &str,
150 input: &Value,
151 context: &ToolContext,
152 ) -> Option<&'static str> {
153 if !is_web_search_call(tool_name, input) {
154 return None;
155 }
156 let chosen = with_chosen_search(context);
157 let context = chosen.as_ref().unwrap_or(context);
158 search_refusal(context).or_else(|| {
159 (tool_name == "web.run" && has_image_query(input))
160 .then(|| context.third_party_search.get().refusal_message())
161 .flatten()
162 })
163 }
164
165 #[must_use]
166 pub fn is_web_search_call(tool_name: &str, input: &Value) -> bool {
167 let non_empty_array = |field: &str| {
168 input
169 .get(field)
170 .and_then(Value::as_array)
171 .is_some_and(|items| !items.is_empty())
172 };
173 match tool_name {
174 "web_search" => true,
175 "web.run" => non_empty_array("search_query") || non_empty_array("image_query"),
176 "Web" => input.get("action").and_then(Value::as_str) == Some("search"),
177 _ => false,
178 }
179 }
180
181 #[must_use]
182 pub fn has_image_query(input: &Value) -> bool {
183 input
184 .get("image_query")
185 .and_then(Value::as_array)
186 .is_some_and(|items| !items.is_empty())
187 }
188
189 #[must_use]
190 pub fn searches_only_images(input: &Value) -> bool {
191 has_image_query(input)
192 && input
193 .get("search_query")
194 .and_then(Value::as_array)
195 .is_none_or(Vec::is_empty)
196 }
197
198 #[must_use]
199 pub fn consent_marker(options: &[SearchProviderOption], selected: &str) -> Value {
200 json!({
201 "version": CONSENT_MARKER_VERSION,
202 "selected": selected,
203 "providers": options,
204 })
205 }
206
207 #[must_use]
208 pub fn input_with_consent_marker(input: &Value, marker: Value) -> Value {
209 let mut shown = match input {
210 Value::Object(map) => map.clone(),
211 other => {
212 let mut map = serde_json::Map::new();
213 map.insert("input".to_string(), other.clone());
214 map
215 }
216 };
217 shown.insert(CONSENT_MARKER_KEY.to_string(), marker);
218 Value::Object(shown)
219 }
220
221 pub fn strip_consent_marker(input: &mut Value) -> bool {
222 input
223 .as_object_mut()
224 .is_some_and(|map| map.remove(CONSENT_MARKER_KEY).is_some())
225 }
226
227 #[must_use]
228 pub fn is_consent_approval_key(approval_key: &str) -> bool {
229 approval_key.starts_with(CONSENT_APPROVAL_KEY_PREFIX)
230 }
231
232 #[must_use]
233 pub fn consent_approval_id(tool_id: &str) -> String {
234 format!("{CONSENT_APPROVAL_KEY_PREFIX}{tool_id}")
235 }
236
237 #[must_use]
238 pub fn consent_gated_call_id(approval_id: &str) -> Option<&str> {
239 approval_id.strip_prefix(CONSENT_APPROVAL_KEY_PREFIX)
240 }
241
242 #[must_use]
243 pub fn consent_description(provider: SearchProvider) -> String {
244 format!(
245 "Third-party web search: this search would be sent to a third-party search service ({}). Allow enables third-party web search for agents; Deny turns it off.",
246 provider.display_name()
247 )
248 }
249
250 #[cfg(test)]
251 mod tests {
252 use super::*;
253
254 fn context(provider: SearchProvider, base_url: Option<&str>) -> ToolContext {
255 let mut context = ToolContext::new(".");
256 context.search_provider = provider;
257 context.search_base_url = base_url.map(str::to_string);
258 context
259 }
260
261 #[test]
262 fn only_self_hosted_endpoints_are_first_party() {
263 assert!(backend_is_third_party(
264 &context(SearchProvider::Firecrawl, None),
265 SearchProvider::Firecrawl
266 ));
267 assert!(backend_is_third_party(
268 &context(SearchProvider::Tavily, None),
269 SearchProvider::Tavily
270 ));
271 assert!(!backend_is_third_party(
272 &context(SearchProvider::Searxng, Some("https://searx.local")),
273 SearchProvider::Searxng
274 ));
275 assert!(!backend_is_third_party(
276 &context(SearchProvider::DuckDuckGo, Some("https://ddg.local/html/")),
277 SearchProvider::DuckDuckGo
278 ));
279 assert!(backend_is_third_party(
280 &context(SearchProvider::DuckDuckGo, None),
281 SearchProvider::DuckDuckGo
282 ));
283 assert!(backend_is_third_party(
284 &context(SearchProvider::Searxng, Some("https://searx.local")),
285 SearchProvider::DuckDuckGo
286 ));
287 }
288
289 #[test]
290 fn refusal_follows_the_permit_and_the_first_backend() {
291 let ctx = context(SearchProvider::Firecrawl, None);
292 assert_eq!(search_refusal(&ctx), None);
293 ctx.third_party_search.set(ThirdPartySearch::Declined);
294 assert_eq!(search_refusal(&ctx), Some(DECLINED_MESSAGE));
295 ctx.third_party_search.set(ThirdPartySearch::Withheld);
296 assert_eq!(search_refusal(&ctx), Some(WITHHELD_MESSAGE));
297
298 let self_hosted = context(SearchProvider::Searxng, Some("https://searx.local"));
299 self_hosted
300 .third_party_search
301 .set(ThirdPartySearch::Declined);
302 assert_eq!(search_refusal(&self_hosted), None);
303 }
304
305 #[test]
306 fn a_choice_made_on_the_card_reaches_contexts_built_before_it() {
307 let ctx = context(SearchProvider::Firecrawl, None);
308 assert!(with_chosen_search(&ctx).is_none());
309 let earlier = ctx.clone();
310 ctx.third_party_search.choose(Some(ChosenSearch {
311 provider: SearchProvider::Bing,
312 native_off: true,
313 }));
314 let adjusted = with_chosen_search(&earlier).expect("the shared permit carries the choice");
315 assert_eq!(adjusted.search_provider, SearchProvider::Bing);
316 assert!(with_chosen_search(&adjusted).is_none());
317 ctx.third_party_search.choose(None);
318 assert!(with_chosen_search(&earlier).is_none());
319 }
320
321 #[test]
322 fn web_search_calls_are_recognized_by_shape() {
323 assert!(is_web_search_call("web_search", &json!({"query": "x"})));
324 assert!(is_web_search_call(
325 "Web",
326 &json!({"action": "search", "query": "x"})
327 ));
328 assert!(!is_web_search_call(
329 "Web",
330 &json!({"action": "fetch", "url": "https://example.com"})
331 ));
332 assert!(is_web_search_call(
333 "web.run",
334 &json!({"search_query": [{"q": "x"}]})
335 ));
336 assert!(is_web_search_call(
337 "web.run",
338 &json!({"image_query": [{"q": "x"}]})
339 ));
340 assert!(!is_web_search_call(
341 "web.run",
342 &json!({"open": [{"ref_id": "r1"}]})
343 ));
344 }
345
346 #[test]
347 fn marker_rides_on_a_copy_of_the_input() {
348 let input = json!({"action": "search", "query": "rust"});
349 let options = vec![SearchProviderOption {
350 id: "any".to_string(),
351 label: "Any".to_string(),
352 keyless: true,
353 }];
354 let shown = input_with_consent_marker(&input, consent_marker(&options, "any"));
355 assert!(shown.get(CONSENT_MARKER_KEY).is_some());
356 assert!(input.get(CONSENT_MARKER_KEY).is_none());
357 assert_eq!(shown["third_party_search"]["version"], 1);
358 assert_eq!(shown["third_party_search"]["selected"], "any");
359 assert_eq!(shown["third_party_search"]["providers"][0]["id"], "any");
360 assert_eq!(shown["query"], "rust");
361 }
362
363 #[test]
364 fn model_supplied_markers_are_stripped_and_only_engine_keys_mark_consent() {
365 let mut forged = json!({
366 "action": "fetch",
367 "url": "https://attacker.example/c",
368 "third_party_search": {"version": 1, "selected": "any", "providers": []}
369 });
370 assert!(strip_consent_marker(&mut forged));
371 assert_eq!(
372 forged,
373 json!({"action": "fetch", "url": "https://attacker.example/c"})
374 );
375 assert!(!strip_consent_marker(&mut forged));
376 assert!(!strip_consent_marker(&mut json!("not an object")));
377
378 let id = consent_approval_id("call-7");
379 assert!(is_consent_approval_key(&id));
380 assert_eq!(consent_gated_call_id(&id), Some("call-7"));
381 assert!(!is_consent_approval_key("tool:Web:abc"));
382 assert_eq!(consent_gated_call_id("call-7"), None);
383 }
384 }
385
385 lines RUST