Skip to content
Merged
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ pub fn commands() -> Vec<C> {
Ok(proj) => proj,
Err(error) => {
super::connections::restore_active(s);
return Err(error.replace("RustGIS project", "RustGIS template"));
return Err(error.replace("RustGIS project", "RustGIS template").replace("this project ", "this template "));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quality (nit, confidence: high). Chained .replace on the error text is fragile: it also rewrites any user-supplied capability name that happens to contain "this project ". Passing kind through check_format / read_json would avoid the string surgery. Can be left for the release quality pass.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed it's string surgery; passing the kind through read_json would touch every reader, so I'll leave it to the release quality pass.

}
};
proj.name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Untitled").chars().take(200).collect();
Expand Down
260 changes: 254 additions & 6 deletions crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,32 @@ pub fn open_command(path: &str) -> &'static str {
"layer.addData"
}
}
/// Saved-document compatibility version, independent of the RustGIS release version.
/// Advance it when an older reader would lose meaningful saved information on resaving.
/// The format this RustGIS writes: the saved-document compatibility version, independent of the
/// RustGIS release version. Advance it when an older reader would lose meaningful saved
/// information on resaving; within format 2, such an addition is named in `requires` instead
/// (see [`READ_FORMAT`] and [`CAPABILITIES`]).
pub const FORMAT: u32 = 1;
/// The newest format this RustGIS reads. Format 2 is read a release before anything writes it
/// (#1853): a document of format 2 opens when this RustGIS knows every capability it `requires`,
/// so what a later RustGIS adds to format 2, and an older one would lose, is listed there and
/// refused by name instead.
pub const READ_FORMAT: u32 = 2;
/// The capabilities a saved document may require that this RustGIS reads. None yet: format 2 is
/// format 1's content, and each later addition an older reader would lose comes with its name.
pub const CAPABILITIES: &[&str] = &[];
/// The most entries a document's `requires` may list: past it the document is refused without
/// the rest being read.
const MAX_REQUIRES: usize = 256;
/// The longest capability name kept whole, in bytes: a longer one can't be a known capability
/// (none is longer, held below), so only its start is kept, marked `…`, for the refusal to show.
const MAX_CAPABILITY_BYTES: usize = 128;
const _: () = {
let mut i = 0;
while i < CAPABILITIES.len() {
assert!(CAPABILITIES[i].len() <= MAX_CAPABILITY_BYTES, "a known capability's name is at most MAX_CAPABILITY_BYTES");
i += 1;
}
};
/// Largest project file read or saved in the browser, or on a computer whose memory isn't known
/// (512 MiB): the floor of [`max_bytes`].
pub const BYTES_FLOOR: u64 = 512 << 20;
Expand Down Expand Up @@ -683,11 +706,200 @@ fn plain_web_address(path: &str) -> bool {
struct FileFormat {
#[serde(default)]
format: u64,
#[serde(default)]
requires: Requires,
}

/// What a document's `requires` holds, read without keeping anything else: the names it lists
/// (at most [`MAX_REQUIRES`]), or that it lists more, or something that isn't a list of names.
#[derive(Default)]
enum Requires {
#[default]
Nothing,
Names(Vec<String>),
TooMany,
NotNames,
}

impl<'de> Deserialize<'de> for Requires {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
d.deserialize_any(RequiresVisitor)
}
}

/// One entry of `requires`: a name, or anything else, skipped without being kept.
enum RequiredName {
Name(String),
Other,
}

impl<'de> Deserialize<'de> for RequiredName {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
d.deserialize_any(RequiredNameVisitor)
}
}

/// Skips the rest of a list without keeping any of it.
fn skip_seq<'de, A: serde::de::SeqAccess<'de>>(mut seq: A) -> Result<(), A::Error> {
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {}
Ok(())
}

/// Skips the rest of an object without keeping any of it.
fn skip_map<'de, A: serde::de::MapAccess<'de>>(mut map: A) -> Result<(), A::Error> {
while map.next_entry::<serde::de::IgnoredAny, serde::de::IgnoredAny>()?.is_some() {}
Ok(())
}

/// Implements the visitor methods for the JSON values that are neither a list nor a name: each
/// gives `$other`.
macro_rules! other_values {
($other:expr) => {
fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<Self::Value, E> {
Ok($other)
}
fn visit_i64<E: serde::de::Error>(self, _: i64) -> Result<Self::Value, E> {
Ok($other)
}
fn visit_u64<E: serde::de::Error>(self, _: u64) -> Result<Self::Value, E> {
Ok($other)
}
fn visit_f64<E: serde::de::Error>(self, _: f64) -> Result<Self::Value, E> {
Ok($other)
}
fn visit_map<A: serde::de::MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
skip_map(map)?;
Ok($other)
}
};
}

struct RequiredNameVisitor;

impl<'de> serde::de::Visitor<'de> for RequiredNameVisitor {
type Value = RequiredName;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a capability name")
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
// A long name keeps its first bytes (on a character's boundary) and `…` for the refusal;
// longer than any known name (held by the assertion above), it can't be taken for one.
if v.len() > MAX_CAPABILITY_BYTES {
let mut end = MAX_CAPABILITY_BYTES;
while !v.is_char_boundary(end) {
end -= 1;
}
Ok(RequiredName::Name(format!("{}…", v.get(..end).unwrap_or_default())))
} else {
Ok(RequiredName::Name(v.to_string()))
}
}
fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
Ok(RequiredName::Other)
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, seq: A) -> Result<Self::Value, A::Error> {
skip_seq(seq)?;
Ok(RequiredName::Other)
}
other_values!(RequiredName::Other);
}

struct RequiresVisitor;

impl<'de> serde::de::Visitor<'de> for RequiresVisitor {
type Value = Requires;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a list of capability names")
}
fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
Ok(Requires::Nothing)
}
fn visit_str<E: serde::de::Error>(self, _: &str) -> Result<Self::Value, E> {
Ok(Requires::NotNames)
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let mut names = Vec::new();
loop {
if names.len() >= MAX_REQUIRES {
// One more entry is one too many; the rest is skipped unread.
if seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
skip_seq(seq)?;
return Ok(Requires::TooMany);
}
return Ok(Requires::Names(names));
}
match seq.next_element::<RequiredName>()? {
None => return Ok(Requires::Names(names)),
Some(RequiredName::Name(n)) => names.push(n),
// Not a list of names, whatever else it holds: the rest is skipped unread.
Some(RequiredName::Other) => {
skip_seq(seq)?;
return Ok(Requires::NotNames);
}
}
}
}
other_values!(Requires::NotNames);
}

/// The capabilities a document requires that this RustGIS doesn't know, each once, or why its
/// `requires` can't be read.
fn unknown_capabilities(requires: &Requires, kind: &str) -> Result<Vec<String>, String> {
let names = match requires {
Requires::Nothing => return Ok(Vec::new()),
Requires::Names(names) => names,
Requires::TooMany => {
return Err(format!(
"this {kind} lists more than {MAX_REQUIRES} things it needs (`requires`), more than this RustGIS reads. It may be damaged, or from a newer RustGIS: update RustGIS to open it."
));
}
Requires::NotNames => {
return Err(format!(
"this {kind} lists what it needs (`requires`) as something other than names, so this RustGIS can't tell whether it reads it. It may be damaged, or from a newer RustGIS: update RustGIS to open it."
));
}
};
let mut unknown: Vec<String> = Vec::new();
for name in names {
if !CAPABILITIES.contains(&name.as_str()) && !unknown.contains(name) {
unknown.push(name.clone());
}
}
Ok(unknown)
}

/// A capability name as a refusal says it: line breaks, other control characters and the
/// characters that reorder text as spaces, and `(unnamed)` for one with nothing else.
fn capability_said(name: &str) -> String {
let shown: String = name.chars().map(rustgis_data::io::dbf_notice_char).collect();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quality (nit, confidence: high). capability_said borrows rustgis_data::io::dbf_notice_char, a helper named for DBF field names. A general name (for example, a flattening helper for notice text) would read better. Can be left for the release quality pass.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is the repo's one helper for flattening controls and reordering characters in notice text; a general name for it belongs in a rename of its own, at the release quality pass.

let shown = shown.trim();
if shown.is_empty() { "(unnamed)".to_string() } else { shown.to_string() }
}

/// Whether a saved document's text, read for its format, is one to keep as written rather than
/// rewrite through RustGIS's types. For a kind whose reader looks at `requires` and reads format 2
/// (`reads_format_2`: projects and maps): of a format past [`READ_FORMAT`], or requiring anything,
/// as the typed copy wouldn't keep the list, even of capabilities it knows. For the others (tasks,
/// presentations, notebooks, models), whose typed copies drop what they don't know: of a format
/// past [`FORMAT`]. A list (a legacy style file), or text whose `format` isn't a number, isn't one.
pub(crate) fn kept_as_written(text: &str, reads_format_2: bool) -> bool {
if text.trim_start().starts_with('[') {
return false;
}
serde_json::from_str::<FileFormat>(text).is_ok_and(|h| {
let requires_nothing = match &h.requires {
Requires::Nothing => true,
Requires::Names(names) => names.is_empty(),
Requires::TooMany | Requires::NotNames => false,
};
if reads_format_2 { h.format > u64::from(READ_FORMAT) || !requires_nothing } else { h.format > u64::from(FORMAT) }
})
}

/// Refuse future document formats before typed deserialization or normalization. Missing
/// metadata is legacy content; arrays include legacy style files. Writers remain unchanged
/// until a change needs a newer format, at which point it must declare that format.
/// metadata is legacy content; arrays include legacy style files. Up to [`READ_FORMAT`] is read,
/// unless the document requires a capability this RustGIS doesn't know: that refusal names them.
/// A change an older reader would lose names a capability in `requires` (see [`CAPABILITIES`]).
pub(crate) fn check_format(text: &str, kind: &str) -> Result<(), String> {
let max = max_bytes();
if text.len() as u64 > max {
Expand All @@ -697,9 +909,19 @@ pub(crate) fn check_format(text: &str, kind: &str) -> Result<(), String> {
return Ok(());
}
let header: FileFormat = serde_json::from_str(text).map_err(|e| format!("not a RustGIS {kind}: {e}"))?;
if header.format > u64::from(FORMAT) {
if header.format > u64::from(READ_FORMAT) {
return Err(format!("this {kind} was saved by a newer RustGIS (format {}). Update RustGIS to open it.", header.format));
}
let unknown = unknown_capabilities(&header.requires, kind)?;
if !unknown.is_empty() {
let mut said: Vec<String> = Vec::new();
for name in unknown.iter().map(|n| capability_said(n)) {
if !said.contains(&name) {
said.push(name);
}
}
return Err(format!("this {kind} needs what this RustGIS can't read: {}. Update RustGIS to open it.", crate::names_said(&said)));
}
Ok(())
}

Expand Down Expand Up @@ -1311,7 +1533,8 @@ impl Project {
}
})?;
p.ensure_imports_complete().map_err(|_| "a project file cannot contain runtime GeoLibre download reservations".to_string())?;
if p.format > FORMAT {
// (A backstop: `check_format` has refused it already.)
if p.format > READ_FORMAT {
return Err(format!("this project was saved by a newer RustGIS (format {}). Update RustGIS to open it.", p.format));
}
if restore {
Expand Down Expand Up @@ -2068,6 +2291,31 @@ fn project_text(p: &Project) -> Result<String, String> {
json_within(p, max)?.ok_or_else(|| format!("the project is too large to save (maximum {})", limit_said(max)))
}

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

fn requires(names: serde_json::Value) -> Requires {
serde_json::from_value::<FileFormat>(serde_json::json!({"format": 2, "requires": names})).map(|h| h.requires).unwrap_or_default()
}

/// At most [`MAX_REQUIRES`] entries are read, and a long name keeps only its start.
#[test]
fn requires_is_read_within_its_bounds() {
let names = |n: usize| serde_json::Value::from((0..n).map(|i| format!("c{i}")).collect::<Vec<_>>());
assert!(matches!(requires(names(MAX_REQUIRES)), Requires::Names(n) if n.len() == MAX_REQUIRES));
assert!(matches!(requires(names(MAX_REQUIRES + 1)), Requires::TooMany));
// A name of a million characters is kept as its first 128 bytes and `…`; a long name of
// characters of three bytes is cut on a boundary, and a short one kept whole.
let Requires::Names(n) = requires(serde_json::json!(["y".repeat(1_000_000), "名".repeat(50), "名".repeat(42)])) else { panic!() };
assert_eq!(n[0], format!("{}…", "y".repeat(MAX_CAPABILITY_BYTES)));
assert_eq!(n[1], format!("{}…", "名".repeat(42)));
assert_eq!(n[2], "名".repeat(42));
// The first entry that isn't a name ends the reading.
assert!(matches!(requires(serde_json::json!(["a", 1, "b"])), Requires::NotNames));
}
}

#[cfg(test)]
mod limit_tests {
use super::*;
Expand Down
11 changes: 4 additions & 7 deletions crates/engine/src/roles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,6 @@ pub(crate) enum Document {
Model,
}

/// Compatibility metadata is read before any embedded document uses this version's types.
#[derive(serde::Deserialize)]
struct DocumentFormat {
format: u64,
}

const WITHHELD: &str = "[parameters withheld]";
const NESTED: &str = "[withheld: nested too deep]";
const DATA: &[&str] = &[
Expand Down Expand Up @@ -377,7 +371,10 @@ impl Durable for VecSteps {
/// access. Unchanged documents keep their exact text; only changed typed copies are serialized.
fn document(kind: Document, v: &Value, depth: usize, report: &mut Report) -> Option<Value> {
let Some(text) = v.as_str().filter(|s| s.len() as u64 <= crate::project::max_bytes()) else { return invalid(v, report) };
if serde_json::from_str::<DocumentFormat>(text).is_ok_and(|f| f.format > u64::from(crate::project::FORMAT)) {
// One this RustGIS wouldn't read, or would rewrite without what it doesn't know, stays as
// written. Only project and map readers read format 2 and refuse a document for what it
// requires; the others keep format 1's bound and don't look at `requires`.
if crate::project::kept_as_written(text, matches!(kind, Document::Project | Document::Map)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug (security/regression, confidence: medium-high). A project or map embedded in a task step that lists requires is now returned verbatim and counted as "unchecked", so any credential in it stays in the saved step. Before this PR, the old check only kept format > FORMAT, so a format-1 document with requires went through the typed path and its secrets were withheld. The new honours_requires branch reverses that default for every requires-bearing document. The notice ("may hold credentials and were kept unchecked") makes it visible, but the secret is still saved.

Since CAPABILITIES is empty, every requires-bearing document is refused on open anyway, so keeping its text buys very little here. Suggested direction: keep credential withholding on the typed path for format ≤ READ_FORMAT, and preserve the requires list separately, or only keep verbatim when the document is of a newer format.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept as is, on purpose. A project or map that lists requires is, for this release, a document it can't fully read: rewriting it through Project would drop the requires list and whatever fields the capabilities name, so the step would later open, without them, in a RustGIS that can read it. That is the same reason documents of a newer format were already kept as written, with the existing "kept unchecked" notice; a requires list is the finer-grained form of a newer format. A format 2 document that requires nothing is now checked and its secrets withheld ((READ_FORMAT, None, 0) in the test). The format 2 task case from the summary is fixed in d51e03a, see the CodeRabbit thread.

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low confidence (about 30%), never-silent. A format 2 project or map in a task step with no requires now goes through the typed path. If it holds a credential, the typed copy (text_document, which is saved when changed is true) replaces the text. That copy drops any field this version doesn't know, and the report only counts withheld values, so the loss is not mentioned. This is the same pattern as the earlier task-document thread, now reached by format 2 projects and maps.

This only happens if format 2 files carry fields that aren't listed in requires. That is the convention in docs/maintaining.md, and format 1 behaves the same way today, so I'm not treating it as a blocker. If it's intended, a short note in the doc comment on kept_as_written would make the trade-off visible.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept as is: it is the rule this PR sets rather than a gap in it. A format 2 project or map that lists nothing in requires holds format 1's content, so this release reads, checks and rewrites it exactly as it does a format 1 one today; a field a later RustGIS adds that an older reader would lose must be named in requires (docs/maintaining.md, docs/contributing.md), and then the document is kept as written here. Unknown fields outside that rule are dropped by every typed rewrite of format 1 already, which is what #1405 item 1 asks future writers to prevent by declaring them.

report.unchecked = report.unchecked.saturating_add(1);
return None;
}
Expand Down
Loading
Loading