Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ jobs:
if grep -q 'data-cargo-profile=' apps/rustgis-web/index.html; then echo "::error::apps/rustgis-web/index.html still names a Cargo profile" >&2; exit 1; fi
(cd apps/rustgis-web && "$RUNNER_TEMP/bin/trunk" build --locked --cargo-profile dev)
cargo xtask web-pwa dist/web
node apps/rustgis-web/smoke/run.mjs --dist dist/web --chrome "$(command -v google-chrome)"
node apps/rustgis-web/smoke/run.mjs --dist dist/web --chrome google-chrome

# The iOS app (apps/rustgis-mobile, #1902): linted for devices and built for the Simulator,
# where macOS is tested (pushes to main, a manual run on every platform, a pull request labelled
Expand Down
6 changes: 3 additions & 3 deletions apps/rustgis-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1426,18 +1426,18 @@ mod tests {
}

#[test]
fn every_option_read_with_opt_is_checked_by_check_values() {
fn every_option_read_with_opt_num_or_side_is_checked_by_check_values() {
let source = include_str!("main.rs");
let mut missing = Vec::new();
for call in ["opt(&args, \"", "opt(args, \""] {
for call in ["opt(&args, \"", "opt(args, \"", "num(&args, \"", "num(args, \"", "side(&mut s, &args, \""] {
for part in source.split(call).skip(1) {
let flag = format!("--{}", part.trim_start_matches('-').split('"').next().unwrap_or(""));
if !VALUE_FLAGS.contains(&flag.as_str()) {
missing.push(flag);
}
}
}
assert!(missing.is_empty(), "read with opt but not in VALUE_FLAGS: {missing:?}");
assert!(missing.is_empty(), "read with opt, num or side but not in VALUE_FLAGS: {missing:?}");
}

/// An environment with no keys.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -705,7 +705,8 @@ public void copyText(final String text) {
}
} catch (RuntimeException e) {
// Too large for Android to pass on, say: the Rust side's own clipboard still has it.
add("copy-failed\t" + oneField(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()));
String why = e.getMessage();
add("copy-failed\t" + oneField(why == null || why.isEmpty() ? e.getClass().getSimpleName() : why));
} finally {
answered();
}
Expand Down
8 changes: 7 additions & 1 deletion apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,13 @@ static synchronized String delete(android.content.Context context, String accoun
if (version(before) > VERSION) {
return NEWER;
}
return before == null || file.delete() || !file.exists() ? "ok" : UNWRITTEN;
// A save cut short between writing the part and renaming it leaves the part, which
// holds the secret too: it goes with the entry.
java.io.File folder = file.getParentFile();
java.io.File part = folder == null ? null : new java.io.File(folder, file.getName() + ".part");
boolean partGone = part == null || part.delete() || !part.exists();
boolean entryGone = before == null || file.delete() || !file.exists();
return partGone && entryGone ? "ok" : UNWRITTEN;
} catch (java.io.IOException | RuntimeException e) {
return "failed\terror\t" + reason(e);
}
Expand Down
48 changes: 48 additions & 0 deletions apps/rustgis-mobile/src/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1133,6 +1133,54 @@ mod tests {
assert_eq!(window.poll, Some(5000));
}

/// The window around `app`, reading its events from `phone`.
fn window_on(app: RustGisApp, phone: Rc<FakePhone>) -> App<FakePhone> {
App {
app,
pushed: Vec::new(),
poll: None,
locating: false,
keeping: false,
keyboard: None,
typing: None,
back: false,
bars_light: None,
phone: Some(phone),
inbox: Inbox::default(),
refusals: Refusals::default(),
asked: Asked::default(),
kept: Rc::default(),
refused_picker: Rc::default(),
waiting: Vec::new(),
problems: Problems::default(),
reading: Arc::default(),
}
}

/// A text box the system couldn't open is said once, with its reason; one that closed after
/// opening says nothing.
#[test]
fn a_text_box_that_could_not_open_is_said() {
use rustgis_engine::platform::Typed;
let _held = settings_notices_held();
let typed = |failed: Option<&str>| Event::Typed(Typed::Closed { id: "note".into(), failed: failed.map(str::to_string) });
for (failed, expected) in [(Some("no keyboard service"), 1), (None, 0)] {
let app = RustGisApp::with_sample();
let mark = app.session.notice_mark();
let phone = Rc::new(FakePhone::default());
phone.1.borrow_mut().push(typed(failed));
let mut window = window_on(app, phone);
window.take_phone_events(&egui::Context::default(), &mut egui::RawInput::default());
let said: Vec<_> =
window.app.session.notices_since(mark).iter().filter(|n| n.text.contains("text box")).map(|n| n.text.clone()).collect();
assert_eq!(said.len(), expected, "{failed:?}: {said:?}");
if let Some(why) = failed {
assert!(said[0].contains(why), "{said:?}");
}
assert_eq!(window.app.typed.len(), 1, "the form still gets the close");
}
}

/// A copy the phone couldn't be asked to take is said once; one it took says nothing.
#[test]
fn a_copy_that_cannot_reach_the_clipboard_is_said() {
Expand Down
3 changes: 2 additions & 1 deletion apps/rustgis-python/python/rustgis/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ class DataLossWarning(UserWarning):

Raised through :mod:`warnings` for each notice that carries a loss code, so
``warnings.filterwarnings("error", category=rustgis.DataLossWarning)`` turns a loss into
an exception. The notice also stays in :meth:`Session.notices`.
an exception. The notice also stays in :meth:`Session.notices`. Losses whose notices the
session no longer keeps (past its last 200) are warned once per code, with their count.

Attributes:
code: The loss code, such as ``"dropped.ring"``: never translated, renamed or reused.
Expand Down
21 changes: 8 additions & 13 deletions apps/rustgis-python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,23 +121,18 @@ struct Losses {
}

impl Losses {
/// Sets aside the losses `session` gave since the last call, for the calling thread, while
/// their notices are still in its queue (after every call, so before `take_notices` drains
/// it). One the queue no longer keeps (past its last 200) is set aside as one entry per code
/// that says how many.
/// Sets aside the losses `session` gave since the last call, for the calling thread. It runs
/// after each native call; the notice mark and the counts taken then keep the tally right
/// whatever has drained the queue since. One the queue no longer keeps (past its last 200) is
/// set aside as one entry per code that says how many ([`Session::losses_not_kept`]).
fn collect(&mut self, session: &Session) {
let thread = std::thread::current().id();
let kept: Vec<(LossCode, String)> =
session.notices_since(self.mark).iter().filter_map(|n| n.loss().map(|code| (code, n.text.clone()))).collect();
for &(code, given) in session.losses_given() {
let was = self.given.iter().find(|(c, _)| *c == code).map_or(0, |(_, n)| *n);
let held = kept.iter().filter(|(c, _)| *c == code).count() as u64;
let lost = given.saturating_sub(was).saturating_sub(held);
if lost > 0 {
let spec = code.spec();
let text = format!("{lost} further {} notice(s) were not kept", spec.id);
self.pending.push((thread, (spec.kind.id().into(), spec.id.into(), text)));
}
for (code, lost) in session.losses_not_kept(self.mark, &self.given) {
let spec = code.spec();
let text = format!("{lost} further {} notice(s) were not kept", spec.id);
self.pending.push((thread, (spec.kind.id().into(), spec.id.into(), text)));
}
self.pending.extend(kept.into_iter().map(|(code, text)| (thread, (code.spec().kind.id().into(), code.spec().id.into(), text))));
self.mark = session.notice_mark();
Expand Down
3 changes: 3 additions & 0 deletions apps/rustgis-web/smoke/run.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,9 @@ const search = async (name) => {
// Gives `files` to the file picker that `trigger` opens. The app's picker opens the browser's
// chooser while the key that asked counts as the user's action; past that (a loaded machine can
// take seconds to handle the key) it shows its own panel to choose them in, as a user then does.
// The ids and class come from the `rfd` crate's wasm backend (0.18.0, `src/backend/wasm.rs`): its
// panel is `#rfd-overlay`, with the file input `#rfd-input`, and it carries the `hidden` class when
// the chooser could open at once. Check them again when `rfd` is bumped.
const PANEL = "#rfd-overlay:not(.hidden) #rfd-input";
const pick = async (what, trigger, files) => {
// Watched only while picking: no wait is left behind when the panel takes the files.
Expand Down
70 changes: 66 additions & 4 deletions crates/assistant/src/audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,16 +261,47 @@ fn redact_script(script: &str) -> String {
if omitted > 0 { format!("# [{omitted} further script line(s) not recorded]\n{output}") } else { output }
}

/// The least room past [`MAX_ARGS`] that a long text is cut to before it is scrubbed, enough for
/// a capability wrapper's head; [`scrub_margin`] widens it to the longest active login.
const SCRUB_MARGIN: usize = 4_096;

/// Room past [`MAX_ARGS`] that a long text is cut to before it is scrubbed: at least as long as
/// every active login, so one crossing the bound is still whole when it is taken out.
fn scrub_margin() -> usize {
SCRUB_MARGIN.max(rustgis_engine::render::rustgis_tiles::logins::longest_redaction())
Comment thread
giswqs marked this conversation as resolved.
Resolved
}

/// `v` without what would give someone else the user's access: values under keys that name a
/// secret, the passwords, keys and tokens in addresses ([`rustgis_engine::sources::redact`]),
/// and the same inside a script's lines.
fn redact(v: Value, depth: usize) -> Value {
let redact_bounded = |s: &str| {
if s.len() > MAX_ARGS {
// Scrub wrappers and active logins before clipping so a secret crossing MAX_ARGS
// cannot leave a recognizable prefix behind.
let scrubbed = rustgis_engine::render::rustgis_tiles::logins::scrub(&rustgis_engine::sources::scrub_s3_wrappers(s));
redact_string_inner(&crate::tools::clip(&scrubbed, MAX_ARGS))
// Only the first MAX_ARGS characters are kept, so only what starts there is scrubbed
// and kept ([`logins::scrub_until`]): a secret that starts there is taken out whole,
// as the head scrubbed runs [`scrub_margin`] past it, and nothing after it (a secret
// cut at the head's end) can reach what is kept, whatever the redactions before it
// do to the length. A login activated in between by another session, longer than
// the margin read first, widens it and the head is scrubbed again. Capability
// wrappers come out after, from what is kept: one cut at its end can't be read and
// is redacted whole. A multi-megabyte argument costs little.
use rustgis_engine::render::rustgis_tiles::logins;
let mut margin = scrub_margin();
let scrubbed = loop {
let head: String = s.chars().take(MAX_ARGS.saturating_add(margin)).collect();
let stop = head.char_indices().nth(MAX_ARGS).map_or(head.len(), |(i, _)| i);
let (scrubbed, longest) = logins::scrub_until(&head, stop);
if longest <= margin {
break rustgis_engine::sources::scrub_s3_wrappers(&scrubbed);
}
margin = longest;
};
let kept = if s.chars().nth(MAX_ARGS).is_some() || scrubbed.chars().nth(MAX_ARGS).is_some() {
format!("{}… (cut: {} characters in all)", scrubbed.chars().take(MAX_ARGS).collect::<String>(), s.chars().count())
} else {
scrubbed
};
redact_string_inner(&kept)
} else {
redact_string(s)
}
Expand Down Expand Up @@ -590,5 +621,36 @@ mod tests {
assert!(!redacted.contains(&active_secret[..8]), "redacted leaked active login prefix: {redacted}");
assert!(!redacted.contains("rustgis-s3:"), "redacted leaked s3 wrapper in key: {redacted}");
assert!(!redacted.contains("RGSYNTH_s3_tok_9921"), "redacted leaked wrapped token in key: {redacted}");

// A string of a few megabytes is scrubbed only up to the clip plus a margin, and a secret
// starting just inside MAX_ARGS still leaves no prefix of itself behind.
let huge = format!("{}{active_secret}{}", "y".repeat(MAX_ARGS - 4), "z".repeat(3_000_000));
let redacted = redact(json!({"long": huge}), 0).to_string();
assert!(!redacted.contains(&active_secret[..4]), "redacted leaked active login prefix: {redacted:.200}");
assert!(
redacted.contains(&format!("(cut: {} characters in all)", huge.chars().count())),
"{:.200}",
&redacted[redacted.len().saturating_sub(200)..]
);

// Many whole copies before the clip shrink as they are redacted: the copy cut at the end of
// the scrubbed head isn't pulled into what is kept.
// (Back to back, a copy is cut wherever the head ends.)
let shrinking = format!("{}tail", active_secret.repeat(1_000));
let redacted = redact(json!({"long": shrinking}), 0).to_string();
assert!(!redacted.contains(&active_secret[..4]), "redacted leaked active login prefix: {redacted:.200}");
assert!(redacted.contains("(cut: "), "{redacted:.200}");

// A capability wrapper straddling the clip, or cut at the end of the scrubbed head, leaves
// no part of its binding behind.
for at in [MAX_ARGS - 20, MAX_ARGS - 2, MAX_ARGS + scrub_margin() - 30] {
let long = format!("{}{wrapped}/{}", "x".repeat(at), "p".repeat(5_000));
let redacted = redact(json!({"long": long}), 0).to_string();
assert!(
!redacted.contains("0123456789abcdef") && !redacted.contains("rustgis-s3:"),
"{at}: {:.300}",
&redacted[redacted.len().saturating_sub(300)..]
);
}
}
}
44 changes: 36 additions & 8 deletions crates/assistant/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,7 @@ impl Note {
/// Every [`Note`] template RustGIS writes (the interface's catalogs translate each).
pub const NOTE_TEMPLATES: &[&str] = &[
"The reply contains {count} content parts of type {kind} that aren't displayed.",
"The reply contains {count} content parts of {types} further type(s) that aren't displayed.",
"OpenRouter found no endpoint matching your data policy. Check Private routing in the Assistant settings or your OpenRouter privacy settings.",
"The reply reached its length limit.",
"The provider's content filter stopped the reply.",
Expand Down Expand Up @@ -975,7 +976,9 @@ fn openai_assembled(events: &[Value]) -> Value {
}
}
}
if content.as_str() == Some("") {
// Empty-text deltas are never stored, but an all-empty array (`"content": []`) is: it is no
// content, and replayed as `[]` it would ride along in every later request.
if content.as_str() == Some("") || content.as_array().is_some_and(Vec::is_empty) {
content = Value::Null;
}
let mut message = json!({"role": "assistant", "content": content});
Expand Down Expand Up @@ -1331,25 +1334,50 @@ fn openai_content_text(content: Option<&Value>) -> String {
/// Counts unsupported display parts once per type. Thinking is native replay metadata;
/// other non-text parts remain native too, but their omission from the answer must be visible.
fn openai_content_notes(content: Option<&Value>) -> Vec<Note> {
let mut counts = std::collections::BTreeMap::<&str, usize>::new();
let mut counts = std::collections::BTreeMap::<String, usize>::new();
for part in content.and_then(Value::as_array).into_iter().flatten() {
let kind = part.get("type").and_then(Value::as_str).unwrap_or("unknown");
if kind == "thinking" || (kind == "text" && part.get("text").is_some_and(Value::is_string)) {
continue;
}
*counts.entry(kind).or_default() += 1;
}
counts
.into_iter()
*counts.entry(kind.to_string()).or_default() += 1;
}
// The server names the type: shown with control characters as spaces, and cut when long, so
// a note stays a line. Types are counted as sent, so two that look alike stay two.
let shown = |kind: &str| {
let kind: String = kind.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
Comment thread
giswqs marked this conversation as resolved.
Resolved
if kind.chars().nth(MAX_KIND_CHARS).is_some() {
format!("{}…", kind.chars().take(MAX_KIND_CHARS).collect::<String>())
} else {
kind
}
};
let mut notes: Vec<Note> = counts
.iter()
.take(MAX_KIND_NOTES)
.map(|(kind, count)| {
Note::with(
"The reply contains {count} content parts of type {kind} that aren't displayed.",
[("count", count.to_string()), ("kind", kind.to_string())],
[("count", count.to_string()), ("kind", shown(kind))],
)
})
.collect()
.collect();
// Past a few types, the rest share one note, so a server can't fill the transcript.
let others: Vec<usize> = counts.values().skip(MAX_KIND_NOTES).copied().collect();
if !others.is_empty() {
notes.push(Note::with(
"The reply contains {count} content parts of {types} further type(s) that aren't displayed.",
[("count", others.iter().sum::<usize>().to_string()), ("types", others.len().to_string())],
));
}
notes
}

/// The most characters of a server's content-part type a note names.
const MAX_KIND_CHARS: usize = 40;
/// The most content-part types named in a note each; the rest share one note.
const MAX_KIND_NOTES: usize = 5;

/// Reads Chat Completions, retaining native typed content for the next request.
fn openai_reply(v: &Value) -> Result<Reply, String> {
let choice = v.get("choices").and_then(|c| c.get(0)).ok_or("the reply has no choices")?;
Expand Down
Loading
Loading