Merge pull request #8948 from dotCooCoo/fix/script-grants-read-failure

Scripts: script.grants reports an error when the grants file cannot be read
This commit is contained in:
BFlat authored and GitHub committed 2026-11-25 11:27:15 +07:00
commit 53199e5dbc
5 files changed
+75 -14

No files matched your search

+3 -2
View File
@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Script File Permissions",
[],
None,
"{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}",
"{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}; a missing grants file lists none, and one that is there but cannot be read, is too large, is not a grants file of this version or holds no list of grants, or whose lock cannot be taken, is an error (a grant in it that is not well formed is left out)",
always,
grants
),
@@ -369,7 +369,8 @@ fn grants(s: &mut Session, _: &Value) -> Result<Value> {
let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) };
let file = dir.with_file_name(script::files::GRANTS_FILE);
// A script or a granted path outside the automation read roots is named by its file name alone.
let mut grants = script::files::stored_grants(dir);
let mut grants =
script::files::stored_grants(dir).map_err(|e| EngineError::Other(format!("the script file permissions could not be read: {e}")))?;
for g in &mut grants {
for key in ["script", "path"] {
if let Some(name) = g[key].as_str().and_then(hidden_name) {
+16 -8
View File
@@ -923,8 +923,15 @@ fn read_head(real: &Path, max: usize) -> std::io::Result<Vec<u8>> {
/// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read
/// between two changes, and none are read when the lock cannot be taken.
fn read_store(store: &Path) -> Vec<serde_json::Value> {
let Ok(_lock) = lock_store(store) else { return Vec::new() };
load_store(store, false).unwrap_or_default()
list_store(store).unwrap_or_default()
}
/// The grants [`read_store`] reads; none when the grants file is missing, and `Err` when the lock
/// cannot be taken or the file is there but cannot be read, is too large, is not a grants file of
/// this version or holds no list of grants.
fn list_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
let _lock = lock_store(store)?;
load_store(store, false)
}
/// The grants the grants file at `store` holds, to change and write back; none when it is missing,
@@ -940,7 +947,8 @@ fn try_read_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Value>> {
let bytes = match read_head(store, MAX_STORE_BYTES) {
Ok(bytes) => bytes,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
// A link whose target is missing is there but cannot be read.
Err(e) if e.kind() == std::io::ErrorKind::NotFound && std::fs::symlink_metadata(store).is_err() => return Ok(Vec::new()),
Err(e) => return Err(e),
};
if bytes.len() > MAX_STORE_BYTES {
@@ -958,14 +966,14 @@ fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Val
&& g["write"].is_boolean()
&& g["folder"].is_boolean()
};
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
if strict {
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
if grants.len() > MAX_STORED_GRANTS || !grants.iter().all(valid) {
return Err(std::io::Error::other("the grants file holds a grant that cannot be read"));
}
return Ok(grants.clone());
}
Ok(v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default())
Ok(grants.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect())
}
/// The number in the name of the next file [`write_store`] writes before it takes the grants file's
@@ -1065,9 +1073,9 @@ fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
}
/// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of
/// its text, the path and whether it may be written (`script.grants`).
pub(crate) fn stored_grants(data_dir: &Path) -> Vec<serde_json::Value> {
read_store(&data_dir.with_file_name(GRANTS_FILE))
/// its text, the path and whether it may be written (`script.grants`); as [`list_store`] reads them.
pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result<Vec<serde_json::Value>> {
list_store(&data_dir.with_file_name(GRANTS_FILE))
}
/// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path
+52 -2
View File
@@ -653,7 +653,7 @@ fn a_grants_change_without_its_lock_changes_nothing() {
}
/// Reading and changing the grants file wait for a lock another handle holds only for a bounded
/// number of tries: then a read gives no grants and a change fails with the file unchanged. A lock
/// number of tries: then a listing and a change fail, with the file unchanged. A lock
/// released while it waits is taken.
#[test]
fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() {
@@ -668,7 +668,8 @@ fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() {
let waits = std::rc::Rc::new(std::cell::Cell::new(0));
let counted = waits.clone();
WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1))));
assert_eq!(stored_grants(&data), Vec::<Value>::new(), "grants are not read without the lock");
let listed = stored_grants(&data);
assert_eq!(listed.map_err(|e| e.kind()), Err(std::io::ErrorKind::TimedOut), "grants are not listed without the lock");
assert_eq!(waits.get(), LOCK_TRIES - 1);
waits.set(0);
let refused = revoke_grants(&data, None, None);
@@ -1319,6 +1320,55 @@ fn script_file_grants_file_that_cannot_be_read_is_left_as_it_is() {
}
}
/// `script.grants` fails on a grants file that is there but cannot be read (another version, not
/// JSON, no list of grants, over the size limit, not a file, or on Unix a link to a missing file),
/// lists none when it is missing, and
/// lists the well-formed grants of one that holds a grant that is not.
#[test]
fn script_grants_fails_on_a_grants_file_that_cannot_be_read() {
let mut big = b"{\"version\": 1, \"grants\": []}".to_vec();
big.resize((4 << 20) + 1, b' ');
let cases = [
("list-newer", br#"{"version": 2, "grants": []}"#.to_vec()),
("list-broken", b"{ not json".to_vec()),
("list-nolist", br#"{"version": 1, "grants": {}}"#.to_vec()),
("list-big", big),
];
for (name, held) in cases {
let base = folder(name);
write(&base.join("settings/Script Grants.json"), &held);
let mut s = with_data(&base);
let e = s.execute("script.grants", &json!({})).unwrap_err().to_string();
assert!(e.contains("the script file permissions could not be read"), "{name}: {e}");
let _ = std::fs::remove_dir_all(base);
}
let base = folder("list-folder");
std::fs::create_dir_all(base.join("settings/Script Grants.json")).unwrap();
let mut s = with_data(&base);
assert!(s.execute("script.grants", &json!({})).is_err(), "a folder in the grants file's place");
let _ = std::fs::remove_dir_all(base);
#[cfg(unix)]
{
let base = folder("list-dangling");
std::fs::create_dir_all(base.join("settings")).unwrap();
std::os::unix::fs::symlink(base.join("gone.json"), base.join("settings/Script Grants.json")).unwrap();
let mut s = with_data(&base);
assert!(s.execute("script.grants", &json!({})).is_err(), "a link to a missing file in the grants file's place");
let _ = std::fs::remove_dir_all(base);
}
let base = folder("list-missing");
let mut s = with_data(&base);
assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([]), "a missing grants file lists none");
let _ = std::fs::remove_dir_all(base);
let base = folder("list-mixed");
let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false});
let text = json!({"version": 1, "grants": [grant, {"script": "x"}]}).to_string();
write(&base.join("settings/Script Grants.json"), text.as_bytes());
let mut s = with_data(&base);
assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1);
let _ = std::fs::remove_dir_all(base);
}
/// `copy` of a file over 8 MiB is refused, as opening one is.
#[test]
fn script_file_copy_is_held_to_the_file_limit() {
+3 -1
View File
@@ -3117,7 +3117,9 @@ is given as its file name alone. `script.grants.revoke {script?, path?, all?}` r
a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is
matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script
runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but
cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. A script
cannot be read, a link to a missing file included, is left as it is: `script.grants` and `script.grants.revoke` fail, and a grant picked with Always is
not kept. A missing grants file lists no grants, and `script.grants` leaves out a grant in the file that is not well
formed. A script
cannot run either command.
```json
+1 -1
View File
@@ -1049,7 +1049,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`.
- Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` starts with a line holding the run's name in square brackets, such as `[main.jsx]`, then writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.
- Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `localizedName`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: `localizedName` gives the same decoded name as `displayName`, without looking up a name the system shows in another language; a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`.
- Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`.
- Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants (it fails when the grants file is there but cannot be read) and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`.
- Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files as the links led at the run's first `vc.run` and as the person last opened or saved each document; a link does not let them write the file it names, and they write a linked file only where the previous line lets them write (the script's own write places and the open documents' own files); a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read unless it lies in one of the script's own places inside that folder, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`.
- Scripts: the `hidden` setter and `createAlias(target)` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/)), with setting `hidden`, `rename` and `remove` acting on an alias itself ([Using File and Folder objects](https://extendscript.docsforadobe.dev/file-system-access/using-file-and-folder-objects/)). VectorCraft's own rules: on Unix a name that starts with a dot is hidden, so setting `hidden` renames the file with one dot added or its leading dots taken off, and both names must be places the script may write; `createAlias` makes a symbolic link to the real path of a file the script may read, in a place it may write where nothing is, a link that leads nowhere included; a link is checked again each time it is used; on Windows both set `error` and change nothing. `crates/engine/src/tests/script_io.rs`.
- Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`).