diff --git a/crates/resonance-collections/src/cache.rs b/crates/resonance-collections/src/cache.rs index 5c1a3456..eacbe285 100644 --- a/crates/resonance-collections/src/cache.rs +++ b/crates/resonance-collections/src/cache.rs @@ -156,7 +156,9 @@ impl CollectionCache { /// than cold. pub fn refresh(&self, dir: &Path, collection: &LoadedCollection) { if let Ok(fingerprint) = fingerprint(dir) { - self.put(dir, fingerprint, collection.clone()); + let mut collection = collection.clone(); + crate::read::sort_folder(&mut collection.root); + self.put(dir, fingerprint, collection); } } diff --git a/crates/resonance-collections/src/capture.rs b/crates/resonance-collections/src/capture.rs index 8a3feb38..fbb17fcb 100644 --- a/crates/resonance-collections/src/capture.rs +++ b/crates/resonance-collections/src/capture.rs @@ -236,7 +236,8 @@ pub fn capture_runner_entry(entry: &CaptureEntry<'_>, target: &CaptureTarget) -> .filter(|row| row_enabled(row) && row_key(row).is_some()) .map(parameter) .collect(); - if query_rows.is_empty() + if overrides.query_params.is_none() + && query_source.is_empty() && let Some(examples) = query_examples { query_rows = examples diff --git a/crates/resonance-collections/src/ipc.rs b/crates/resonance-collections/src/ipc.rs index dfd1994a..d9a2dc7b 100644 --- a/crates/resonance-collections/src/ipc.rs +++ b/crates/resonance-collections/src/ipc.rs @@ -696,7 +696,41 @@ fn renumber_if_reordered(requests: &mut [RequestEntry], existing: Option<&Folder .collect(); if previous_surviving == incoming_known { - return; + // Allocate inserted/moved requests between their destination siblings. + // A moved request's old seq belongs to its source folder. + let mut candidate: Vec = requests.iter().map(|entry| entry.doc.seq).collect(); + let mut last = 0_i64; + let mut fits = true; + for index in 0..requests.len() { + if previous.contains(&requests[index].doc.id.as_str()) { + if candidate[index] <= last { + fits = false; + break; + } + } else { + let next = requests[index + 1..] + .iter() + .find(|entry| previous.contains(&entry.doc.id.as_str())) + .map(|entry| entry.doc.seq); + let step = if next.is_some() { 1 } else { 10 }; + let Some(seq) = last.checked_add(step) else { + fits = false; + break; + }; + if next.is_some_and(|next| seq >= next) { + fits = false; + break; + } + candidate[index] = seq; + } + last = candidate[index]; + } + if fits { + for (entry, seq) in requests.iter_mut().zip(candidate) { + entry.doc.seq = seq; + } + return; + } } for (index, entry) in requests.iter_mut().enumerate() { @@ -1587,6 +1621,105 @@ mod save_path { mod reordering { use super::*; + #[test] + fn moved_requests_keep_the_requested_order_in_cache_and_on_disk() { + use crate::cache::{CollectionCache, read_collection_dir_cached}; + use crate::read::read_collection_dir; + use crate::write::write_collection_dir; + + for (source, destination) in [ + ("root", "destination"), + ("source", "root"), + ("source", "destination"), + ] { + for position in 0..=2 { + let temp = tempfile::TempDir::new().unwrap(); + let mut existing = existing_three(); + let entries = |ids: &[&str]| -> Vec { + ids.iter() + .enumerate() + .map(|(index, id)| { + let mut doc = RequestDoc::new((*id).into(), id.to_uppercase()); + doc.seq = (index as i64 + 1) * 10; + RequestEntry::new(doc) + }) + .collect() + }; + existing.root.requests = entries(if source == "root" { + &["z"] + } else if destination == "root" { + &["a", "c"] + } else { + &["untouched"] + }); + existing.root.folders.clear(); + for (id, ids) in [(source, vec!["z"]), (destination, vec!["a", "c"])] { + if id == "root" { + continue; + } + existing.root.folders.push(FolderNode { + meta: Some(crate::model::FolderDoc { + format: FORMAT_VERSION, + id: id.into(), + name: id.into(), + seq: 10, + auth: None, + extra: Map::new(), + }), + requests: entries(&ids), + ..Default::default() + }); + } + write_collection_dir(temp.path(), &mut existing).unwrap(); + let existing = read_collection_dir(temp.path()).unwrap(); + let mut desired = vec!["a", "c"]; + desired.insert(position, "z"); + let mut folders = Vec::new(); + if source != "root" { + folders.push(json!({"id": source, "name": source, "endpoints": []})); + } + if destination != "root" { + folders.push(json!({"id": destination, "name": destination, + "endpoints": desired.iter().map(|id| endpoint(id)).collect::>() })); + } + let mut flat = desired.iter().map(|id| endpoint(id)).collect::>(); + if source != "root" && destination != "root" { + flat.push(endpoint("untouched")); + } + let incoming = ipc_collection(flat, folders); + let mut updated = existing.clone(); + updated.root = tree_from_ipc(&incoming, Some(&existing)); + write_collection_dir(temp.path(), &mut updated).unwrap(); + let cache = CollectionCache::default(); + cache.refresh(temp.path(), &updated); + for collection in [ + read_collection_dir_cached(&cache, temp.path()).unwrap(), + read_collection_dir(temp.path()).unwrap(), + ] { + let node = if destination == "root" { + &collection.root + } else { + collection + .root + .folders + .iter() + .find(|folder| folder.meta.as_ref().unwrap().id == destination) + .unwrap() + }; + let actual: Vec<_> = node + .requests + .iter() + .map(|entry| entry.doc.id.as_str()) + .collect(); + assert_eq!( + actual, desired, + "move {source} -> {destination}, insertion {position}" + ); + } + } + } + } + fn existing_three() -> LoadedCollection { let mut c = existing_with_state(); c.root.requests.clear(); diff --git a/crates/resonance-collections/src/read.rs b/crates/resonance-collections/src/read.rs index 54da356d..9c455651 100644 --- a/crates/resonance-collections/src/read.rs +++ b/crates/resonance-collections/src/read.rs @@ -279,15 +279,7 @@ fn read_folder(dir: &Path, at_root: bool) -> Result { } } - node.requests - .sort_by_key(|entry| sort_key(entry.doc.seq, &entry.doc.name, &entry.doc.id)); - node.folders.sort_by_key(|folder| { - let meta = folder.meta.as_ref(); - let seq = meta.map(|m| m.seq).unwrap_or(0); - let name = folder_display_name(folder); - let id = meta.map(|m| m.id.clone()).unwrap_or_default(); - sort_key(seq, &name, &id) - }); + sort_folder(&mut node); Ok(node) } @@ -460,6 +452,22 @@ pub fn read_collection_dir(dir: &Path) -> Result { }) } +/// Keep warm cache ordering identical to a fresh directory read. +pub(crate) fn sort_folder(node: &mut FolderNode) { + node.requests + .sort_by_key(|entry| sort_key(entry.doc.seq, &entry.doc.name, &entry.doc.id)); + node.folders.sort_by_key(|folder| { + let meta = folder.meta.as_ref(); + let seq = meta.map(|m| m.seq).unwrap_or(0); + let name = folder_display_name(folder); + let id = meta.map(|m| m.id.clone()).unwrap_or_default(); + sort_key(seq, &name, &id) + }); + for folder in &mut node.folders { + sort_folder(folder); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/resonance-collections/src/write.rs b/crates/resonance-collections/src/write.rs index df9ac189..bbfc2111 100644 --- a/crates/resonance-collections/src/write.rs +++ b/crates/resonance-collections/src/write.rs @@ -21,7 +21,13 @@ use super::layout::{ find_available_path, is_reserved_dir, request_stem, slugify, }; use super::read::{FolderNode, LoadedCollection, RequestEntry, folder_display_name}; -use crate::fs_secure::{restrict_dir, restrict_file}; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WritePolicy { + /// App-owned storage: owner-only files and directories. + Private, + /// User-owned checkout: preserve existing modes; normal defaults for new entries. + Linked, +} /// Gap left between consecutive `seq` values, so a request can be inserted /// between two others without renumbering either. @@ -42,6 +48,14 @@ pub fn to_yaml(value: &T) -> Result { /// @param contents - Bytes to write /// @returns Ok once the file is durably in place pub fn write_atomic(path: &Path, contents: &str) -> Result<(), String> { + write_atomic_with_policy(path, contents, WritePolicy::Private) +} + +pub fn write_atomic_with_policy( + path: &Path, + contents: &str, + policy: WritePolicy, +) -> Result<(), String> { let parent = path .parent() .ok_or_else(|| format!("{} has no parent directory", path.display()))?; @@ -58,16 +72,40 @@ pub fn write_atomic(path: &Path, contents: &str) -> Result<(), String> { )); let result = (|| -> Result<(), String> { - let mut file = fs::File::create(&temp) + let existing_permissions = if policy == WritePolicy::Linked { + match fs::metadata(path) { + Ok(meta) => Some(meta.permissions()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return Err(format!("Failed to read permissions: {e}")), + } + } else { + None + }; + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + if policy == WritePolicy::Private { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + #[cfg(unix)] + if let Some(permissions) = &existing_permissions { + use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + options.mode(permissions.mode() & 0o777); + } + let mut file = options + .open(&temp) .map_err(|e| format!("Failed to create {}: {}", temp.display(), e))?; + if let Some(permissions) = existing_permissions { + file.set_permissions(permissions) + .map_err(|e| format!("Failed to preserve permissions: {e}"))?; + } file.write_all(contents.as_bytes()) .map_err(|e| format!("Failed to write {}: {}", temp.display(), e))?; file.sync_all() .map_err(|e| format!("Failed to flush {}: {}", temp.display(), e))?; drop(file); - restrict_file(&temp); - fs::rename(&temp, path).map_err(|e| format!("Failed to place {}: {}", path.display(), e)) })(); @@ -83,22 +121,47 @@ pub fn write_atomic(path: &Path, contents: &str) -> Result<(), String> { /// @param contents - Bytes the file should hold /// @returns True when the file was written pub fn write_if_changed(path: &Path, contents: &str) -> Result { + write_if_changed_with_policy(path, contents, WritePolicy::Private) +} + +pub fn write_if_changed_with_policy( + path: &Path, + contents: &str, + policy: WritePolicy, +) -> Result { if let Ok(existing) = fs::read_to_string(path) && existing == contents { return Ok(false); } - write_atomic(path, contents)?; + write_atomic_with_policy(path, contents, policy)?; Ok(true) } /// Creates a directory if missing and tightens its permissions either way. pub fn ensure_dir(dir: &Path) -> Result<(), String> { + ensure_dir_with_policy(dir, WritePolicy::Private) +} + +pub fn ensure_dir_with_policy(dir: &Path, policy: WritePolicy) -> Result<(), String> { if !dir.exists() { - fs::create_dir_all(dir) + let mut builder = fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + if policy == WritePolicy::Private { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder + .create(dir) .map_err(|e| format!("Failed to create {}: {}", dir.display(), e))?; } - restrict_dir(dir); + #[cfg(unix)] + if policy == WritePolicy::Private { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(dir, fs::Permissions::from_mode(0o700)) + .map_err(|e| format!("Failed to restrict {}: {e}", dir.display()))?; + } Ok(()) } @@ -179,14 +242,19 @@ fn rebase_sources(node: &mut FolderNode, from: &Path, to: &Path) { /// the directory belong to the tree. At the collection root a subfolder whose /// slug is a reserved directory name is suffixed, so it can never claim the /// directory the layout owns. -fn write_folder(dir: &Path, node: &mut FolderNode, at_root: bool) -> Result, String> { - ensure_dir(dir)?; +fn write_folder( + dir: &Path, + node: &mut FolderNode, + at_root: bool, + policy: WritePolicy, +) -> Result, String> { + ensure_dir_with_policy(dir, policy)?; let mut claimed: Vec = Vec::new(); if let Some(meta) = &node.meta { let path = dir.join(FOLDER_YAML); - write_if_changed(&path, &to_yaml(meta)?)?; + write_if_changed_with_policy(&path, &to_yaml(meta)?, policy)?; claimed.push(path); } @@ -200,7 +268,7 @@ fn write_folder(dir: &Path, node: &mut FolderNode, at_root: bool) -> Result Result Result Result<(), String> { - ensure_dir(dir)?; + write_collection_dir_with_policy(dir, collection, WritePolicy::Private) +} + +pub fn write_collection_dir_with_policy( + dir: &Path, + collection: &mut LoadedCollection, + policy: WritePolicy, +) -> Result<(), String> { + ensure_dir_with_policy(dir, policy)?; assign_missing_seq(&mut collection.root); - write_folder(dir, &mut collection.root, true)?; + write_folder(dir, &mut collection.root, true, policy)?; if !collection.variables.is_empty() { - write_if_changed(&dir.join(VARIABLES_YAML), &to_yaml(&collection.variables)?)?; + write_if_changed_with_policy( + &dir.join(VARIABLES_YAML), + &to_yaml(&collection.variables)?, + policy, + )?; } if let Some(spec) = &collection.open_api_spec { - write_if_changed(&dir.join(OPENAPI_YAML), &to_yaml(spec)?)?; + write_if_changed_with_policy(&dir.join(OPENAPI_YAML), &to_yaml(spec)?, policy)?; collection.meta.open_api_spec = Some(OPENAPI_YAML.to_string()); } - write_if_changed(&dir.join(COLLECTION_YAML), &to_yaml(&collection.meta)?)?; + write_if_changed_with_policy( + &dir.join(COLLECTION_YAML), + &to_yaml(&collection.meta)?, + policy, + )?; Ok(()) } @@ -272,13 +356,20 @@ pub fn write_collection_dir(dir: &Path, collection: &mut LoadedCollection) -> Re /// @returns False when the request has no file or no `seq` yet, in which case /// the caller must fall back to a whole-tree write that assigns both pub fn write_request_in_place(entry: &RequestEntry) -> Result { + write_request_in_place_with_policy(entry, WritePolicy::Private) +} + +pub fn write_request_in_place_with_policy( + entry: &RequestEntry, + policy: WritePolicy, +) -> Result { let Some(path) = entry.source.as_deref() else { return Ok(false); }; if entry.doc.seq == 0 || !path.exists() { return Ok(false); } - write_if_changed(path, &to_yaml(&entry.doc)?)?; + write_if_changed_with_policy(path, &to_yaml(&entry.doc)?, policy)?; Ok(true) } @@ -304,6 +395,74 @@ mod tests { } } + #[cfg(unix)] + #[test] + fn linked_collection_saves_preserve_shared_directory_and_file_modes() { + use std::os::unix::fs::PermissionsExt; + let temp = TempDir::new().unwrap(); + let mut c = collection(vec![request("r1", "Health")]); + write_collection_dir_with_policy(temp.path(), &mut c, WritePolicy::Linked).unwrap(); + fs::set_permissions(temp.path(), fs::Permissions::from_mode(0o2770)).unwrap(); + for name in [COLLECTION_YAML, "health.yaml"] { + fs::set_permissions(temp.path().join(name), fs::Permissions::from_mode(0o660)).unwrap(); + } + c.meta.name = "Updated collection".into(); + c.root.requests[0].doc.description = Some("Changed request".into()); + write_collection_dir_with_policy(temp.path(), &mut c, WritePolicy::Linked).unwrap(); + + assert_eq!( + fs::metadata(temp.path()).unwrap().permissions().mode() & 0o7777, + 0o2770 + ); + for name in [COLLECTION_YAML, "health.yaml"] { + assert_eq!( + fs::metadata(temp.path().join(name)) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o660, + "{name}" + ); + } + } + + #[cfg(unix)] + #[test] + fn linked_targeted_saves_and_renames_preserve_existing_file_modes() { + use std::os::unix::fs::PermissionsExt; + let temp = TempDir::new().unwrap(); + let mut c = collection(vec![request("r1", "Health")]); + write_collection_dir_with_policy(temp.path(), &mut c, WritePolicy::Linked).unwrap(); + fs::set_permissions( + temp.path().join("health.yaml"), + fs::Permissions::from_mode(0o640), + ) + .unwrap(); + c.root.requests[0].doc.description = Some("Updated in place".into()); + assert!( + write_request_in_place_with_policy(&c.root.requests[0], WritePolicy::Linked).unwrap() + ); + assert_eq!( + fs::metadata(temp.path().join("health.yaml")) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o640 + ); + c.root.requests[0].doc.name = "Renamed".into(); + write_collection_dir_with_policy(temp.path(), &mut c, WritePolicy::Linked).unwrap(); + assert_eq!( + fs::metadata(temp.path().join("renamed.yaml")) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o640 + ); + } + fn folder_meta(id: &str, name: &str) -> FolderDoc { FolderDoc { format: FORMAT_VERSION, @@ -315,6 +474,30 @@ mod tests { } } + #[cfg(unix)] + #[test] + fn linked_new_entries_use_the_same_modes_as_normal_filesystem_creation() { + use std::os::unix::fs::PermissionsExt; + let temp = TempDir::new().unwrap(); + let baseline_file = temp.path().join("baseline-file"); + let baseline_dir = temp.path().join("baseline-dir"); + fs::write(&baseline_file, "baseline").unwrap(); + fs::create_dir(&baseline_dir).unwrap(); + let mut c = collection(vec![request("r1", "Health")]); + c.root + .folders + .push(folder("f1", "Pets", vec![request("r2", "List")])); + write_collection_dir_with_policy(temp.path(), &mut c, WritePolicy::Linked).unwrap(); + + let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&temp.path().join("health.yaml")), mode(&baseline_file)); + assert_eq!(mode(&temp.path().join("pets")), mode(&baseline_dir)); + assert_eq!( + mode(&temp.path().join("pets/list.yaml")), + mode(&baseline_file) + ); + } + fn request(id: &str, name: &str) -> RequestEntry { RequestEntry::new(RequestDoc::new(id.into(), name.into())) } diff --git a/crates/resonance-collections/tests/capture_parity.rs b/crates/resonance-collections/tests/capture_parity.rs index ce4e5cef..376e6a7e 100644 --- a/crates/resonance-collections/tests/capture_parity.rs +++ b/crates/resonance-collections/tests/capture_parity.rs @@ -13,7 +13,7 @@ fn template_capture_fixtures_match_the_js_port() { "../../../tests/fixtures/execution/template-capture.json" )) .unwrap(); - assert_eq!(fixtures.len(), 20); + assert_eq!(fixtures.len(), 21); for fixture in fixtures { let name = fixture["name"].as_str().unwrap(); diff --git a/crates/resonance-core/src/api_request.rs b/crates/resonance-core/src/api_request.rs index 38b71a27..312e874b 100644 --- a/crates/resonance-core/src/api_request.rs +++ b/crates/resonance-core/src/api_request.rs @@ -22,48 +22,132 @@ struct DigestChallenge { opaque: Option, } -impl DigestChallenge { - /// Parse WWW-Authenticate header to extract digest challenge parameters - fn parse(www_authenticate: &str) -> Option { - if !www_authenticate.contains("Digest") { - return None; +/// Split challenges/parameters at commas outside quoted strings. +fn auth_segments(header: &str) -> Option> { + let mut quoted = false; + let mut escaped = false; + let mut start = 0; + let mut parts = Vec::new(); + for (index, ch) in header.char_indices() { + if escaped { + escaped = false; + continue; + } + if quoted && ch == '\\' { + escaped = true; + continue; } + if ch == '"' { + quoted = !quoted; + } + if ch == ',' && !quoted { + parts.push(header[start..index].trim()); + start = index + 1; + } + } + if quoted || escaped { + return None; + } + parts.push(header[start..].trim()); + Some(parts) +} + +fn auth_value(value: &str) -> Option { + let value = value.trim(); + if !value.starts_with('"') { + return Some(value.to_string()); + } + let inner = value.strip_prefix('"')?.strip_suffix('"')?; + let mut result = String::new(); + let mut chars = inner.chars(); + while let Some(ch) = chars.next() { + result.push(if ch == '\\' { chars.next()? } else { ch }); + } + Some(result) +} - let mut realm = String::new(); - let mut nonce = String::new(); - let mut qop = None; - let mut algorithm = "MD5".to_string(); - let mut opaque = None; - - // Parse key=value pairs from the header - let re = regex::Regex::new(r#"(\w+)=["']?([^"',]+)["']?"#).ok()?; - for cap in re.captures_iter(www_authenticate) { - let key = cap.get(1)?.as_str(); - let value = cap.get(2)?.as_str(); - match key { - "realm" => realm = value.to_string(), - "nonce" => nonce = value.to_string(), - "qop" => qop = Some(value.to_string()), - "algorithm" => algorithm = value.to_uppercase(), - "opaque" => opaque = Some(value.to_string()), +impl DigestChallenge { + fn parse_all(header: &str) -> Vec { + let Some(parts) = auth_segments(header) else { + return Vec::new(); + }; + let mut challenges = Vec::new(); + let mut current: Option = None; + for part in parts { + let token_end = part + .find(|ch: char| ch.is_whitespace() || ch == '=') + .unwrap_or(part.len()); + let token = &part[..token_end]; + let rest = part[token_end..].trim_start(); + let parameter = if !rest.starts_with('=') { + if let Some(challenge) = current.take().filter(|c| !c.nonce.is_empty()) { + challenges.push(challenge); + } + if token.eq_ignore_ascii_case("digest") { + current = Some(Self { + realm: String::new(), + nonce: String::new(), + qop: None, + algorithm: "MD5".into(), + opaque: None, + }); + } + rest + } else { + part + }; + let Some(challenge) = current.as_mut() else { + continue; + }; + let Some((key, value)) = parameter.split_once('=') else { + continue; + }; + let Some(value) = auth_value(value) else { + current = None; + continue; + }; + match key.trim().to_ascii_lowercase().as_str() { + "realm" => challenge.realm = value, + "nonce" => challenge.nonce = value, + "qop" => challenge.qop = Some(value), + "algorithm" => challenge.algorithm = value.to_ascii_uppercase(), + "opaque" => challenge.opaque = Some(value), _ => {} } } - - if nonce.is_empty() { - return None; + if let Some(challenge) = current.filter(|c| !c.nonce.is_empty()) { + challenges.push(challenge); } + challenges + } + + #[cfg(test)] + fn parse(header: &str) -> Option { + Self::parse_all(header).into_iter().next() + } - Some(DigestChallenge { - realm, - nonce, - qop, - algorithm, - opaque, - }) + fn supported(&self) -> bool { + matches!(self.algorithm.as_str(), "MD5" | "MD5-SESS") + && self + .qop + .as_ref() + .is_none_or(|qop| qop.split(',').any(|value| value.trim() == "auth")) } } +fn extract_digest_challenge(headers: &reqwest::header::HeaderMap) -> Option { + headers + .get_all("www-authenticate") + .iter() + .filter_map(|value| value.to_str().ok()) + .flat_map(DigestChallenge::parse_all) + .find(DigestChallenge::supported) +} + +fn quote_auth(value: &str) -> String { + value.replace('\\', "\\\\").replace('"', "\\\"") +} + /// Compute MD5 hash of a string fn md5_hash(data: &str) -> String { use md5::Digest; @@ -130,13 +214,17 @@ fn build_digest_auth_header( // Build the header let mut header = format!( r#"Digest username="{}", realm="{}", nonce="{}", uri="{}", response="{}""#, - username, challenge.realm, challenge.nonce, uri, response + quote_auth(username), + quote_auth(&challenge.realm), + quote_auth(&challenge.nonce), + quote_auth(uri), + response ); header.push_str(&format!(", algorithm={}", challenge.algorithm)); if let Some(opaque) = &challenge.opaque { - header.push_str(&format!(r#", opaque="{}""#, opaque)); + header.push_str(&format!(r#", opaque="{}""#, quote_auth(opaque))); } if challenge.qop.is_some() { @@ -305,6 +393,33 @@ fn aws_uri_encode(input: &str, encode_slash: bool) -> String { encoded } +/// The URL path is already serialized. Preserve valid escapes for S3; +/// other services encode them again in the canonical request. +fn aws_canonical_uri(path: &str, service: &str) -> String { + let path = if path.is_empty() { "/" } else { path }; + if service != "s3" { + return aws_uri_encode(path, false); + } + let mut result = String::new(); + let mut remaining = path; + while !remaining.is_empty() { + let bytes = remaining.as_bytes(); + if bytes.len() >= 3 + && bytes[0] == b'%' + && bytes[1].is_ascii_hexdigit() + && bytes[2].is_ascii_hexdigit() + { + result.push_str(&remaining[..3].to_ascii_uppercase()); + remaining = &remaining[3..]; + } else { + let ch = remaining.chars().next().unwrap(); + result.push_str(&aws_uri_encode(&ch.to_string(), false)); + remaining = &remaining[ch.len_utf8()..]; + } + } + result +} + /// Derive the AWS Signature V4 signing key. fn aws_derive_signing_key(secret: &str, date: &str, region: &str, service: &str) -> Vec { let k_date = hmac_sha256(format!("AWS4{}", secret).as_bytes(), date.as_bytes()); @@ -324,11 +439,28 @@ fn build_aws_v4_headers( url_str: &str, existing_headers: &HashMap, body_bytes: &[u8], +) -> Result, String> { + build_aws_v4_headers_at( + aws, + method, + url_str, + existing_headers, + body_bytes, + chrono::Utc::now(), + ) +} + +fn build_aws_v4_headers_at( + aws: &AwsAuthConfig, + method: &str, + url_str: &str, + existing_headers: &HashMap, + body_bytes: &[u8], + now: chrono::DateTime, ) -> Result, String> { let parsed = url::Url::parse(url_str).map_err(|e| format!("Invalid URL for AWS signing: {}", e))?; - let now = chrono::Utc::now(); let date_stamp = now.format("%Y%m%d").to_string(); let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string(); @@ -367,11 +499,7 @@ fn build_aws_v4_headers( } // -- Step 1: Canonical Request -------------------------------------------- - let canonical_uri = if parsed.path().is_empty() { - "/".to_string() - } else { - parsed.path().to_string() - }; + let canonical_uri = aws_canonical_uri(parsed.path(), &aws.service); // Canonical query string: sorted by key then value let mut query_pairs: Vec<(String, String)> = parsed @@ -1143,9 +1271,7 @@ pub async fn send_api_request( } if let Some(auth_config) = &request_options.auth - && let Some(www_auth) = response.headers().get("www-authenticate") - && let Ok(www_auth_str) = www_auth.to_str() - && let Some(challenge) = DigestChallenge::parse(www_auth_str) + && let Some(challenge) = extract_digest_challenge(response.headers()) { let uri = extract_uri(&request_options.url); @@ -1898,3 +2024,149 @@ mod tests { assert!(wire_body_bytes("json", None, None).unwrap().is_empty()); } } + +#[cfg(test)] +mod correctness_auth_regressions { + use super::*; + + #[test] + fn digest_preserves_quoted_commas_and_escaped_characters() { + let challenge = DigestChallenge::parse( + r#"Digest realm="team, \"blue\"\\ops", nonce="abc", qop="auth,auth-int", opaque="x,y""#, + ) + .unwrap(); + assert_eq!(challenge.realm, "team, \"blue\"\\ops"); + assert_eq!(challenge.qop.as_deref(), Some("auth,auth-int")); + assert_eq!(challenge.opaque.as_deref(), Some("x,y")); + } + + #[test] + fn digest_parameters_are_case_insensitive_and_do_not_cross_challenges() { + let challenge = DigestChallenge::parse( + r#"Basic realm="wrong", dIgEsT REALM = "right", NONCE = "abc", ALGORITHM = MD5, Basic realm="also wrong""#, + ).unwrap(); + assert_eq!(challenge.realm, "right"); + assert_eq!(challenge.nonce, "abc"); + assert_eq!(challenge.algorithm, "MD5"); + } + + #[test] + fn digest_rejects_an_unterminated_quoted_parameter() { + assert!(DigestChallenge::parse(r#"Digest realm="ok", nonce="unterminated"#).is_none()); + } + + #[test] + fn digest_authorization_escapes_quoted_values() { + let challenge = DigestChallenge { + realm: "team\"blue\\ops".into(), + nonce: "nonce\"value".into(), + qop: None, + algorithm: "MD5".into(), + opaque: Some("opaque\\value".into()), + }; + let header = + build_digest_auth_header("user\"name", "pass", "GET", "/", &challenge).unwrap(); + assert!(header.contains(r#"username="user\"name""#), "{header}"); + assert!(header.contains(r#"realm="team\"blue\\ops""#), "{header}"); + assert!(header.contains(r#"nonce="nonce\"value""#), "{header}"); + assert!(header.contains(r#"opaque="opaque\\value""#), "{header}"); + } + + #[tokio::test] + async fn digest_handshake_finds_a_later_header_and_hashes_the_entire_realm() { + use axum::{ + Router, + http::{HeaderMap, StatusCode}, + routing::get, + }; + async fn handler(headers: HeaderMap) -> (StatusCode, HeaderMap, &'static str) { + let expected = md5_hash(&format!( + "{}:abc:{}", + md5_hash("user:team,blue:pass"), + md5_hash("GET:/api") + )); + if headers + .get("authorization") + .and_then(|h| h.to_str().ok()) + .is_some_and(|h| { + h.starts_with("Digest ") && h.contains(&format!("response=\"{expected}\"")) + }) + { + return (StatusCode::OK, HeaderMap::new(), "authenticated"); + } + let mut headers = HeaderMap::new(); + headers.append("www-authenticate", "Basic realm=\"basic\"".parse().unwrap()); + headers.append( + "www-authenticate", + "Digest realm=\"team,blue\", nonce=\"abc\", algorithm=MD5" + .parse() + .unwrap(), + ); + (StatusCode::UNAUTHORIZED, headers, "challenge") + } + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + axum::serve(listener, Router::new().route("/api", get(handler))) + .await + .unwrap(); + }); + let options: RequestOptions = serde_json::from_value(serde_json::json!({ + "method": "GET", "url": format!("http://{addr}/api"), + "auth": {"username": "user", "password": "pass"}, "timeout": 3000 + })) + .unwrap(); + let result = + send_api_request(&RequestState::default(), &ProxySettings::default(), options).await; + server.abort(); + assert_eq!(result.unwrap().status, Some(200)); + } + + #[test] + fn aws_canonical_path_is_encoded_for_the_service() { + // Independently assemble the canonical request using expected URI literals; + // the timestamp comes from the generated header to avoid clock flakiness. + for (service, path, expected_path) in [ + ("execute-api", "/a+b", "/a%2Bb"), + ("execute-api", "/a%20b", "/a%2520b"), + ("execute-api", "/a%2Fb", "/a%252Fb"), + ("execute-api", "/%C3%A9", "/%25C3%25A9"), + ("s3", "/a+b", "/a%2Bb"), + ("s3", "/a%20b", "/a%20b"), + ("s3", "/a%2Fb", "/a%2Fb"), + ("s3", "/a//b", "/a//b"), + ] { + let config = AwsAuthConfig { + access_key_id: "AKIDEXAMPLE".into(), + secret_access_key: "test-secret".into(), + region: "us-east-1".into(), + service: service.into(), + session_token: None, + }; + let headers = build_aws_v4_headers( + &config, + "GET", + &format!("https://example.com{path}"), + &HashMap::new(), + b"", + ) + .unwrap(); + let date = &headers["x-amz-date"]; + let payload_hash = sha256_hex(b""); + let canonical = format!( + "GET\n{expected_path}\n\nhost:example.com\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{date}\n\nhost;x-amz-content-sha256;x-amz-date\n{payload_hash}" + ); + let scope = format!("{}/us-east-1/{service}/aws4_request", &date[..8]); + let to_sign = format!( + "AWS4-HMAC-SHA256\n{date}\n{scope}\n{}", + sha256_hex(canonical.as_bytes()) + ); + let key = aws_derive_signing_key("test-secret", &date[..8], "us-east-1", service); + let signature = hex::encode(hmac_sha256(&key, to_sign.as_bytes())); + assert!( + headers["Authorization"].ends_with(&signature), + "wrong canonical URI for {service}: {path}" + ); + } + } +} diff --git a/src-tauri/src/commands/collections/mod.rs b/src-tauri/src/commands/collections/mod.rs index 4d1c0e2b..3310801c 100644 --- a/src-tauri/src/commands/collections/mod.rs +++ b/src-tauri/src/commands/collections/mod.rs @@ -226,17 +226,28 @@ fn find_request_entry_mut<'a>( /// @param request_id - Request to update /// @param data - The data the frontend sent /// @returns Ok once the change is on disk +#[cfg(test)] fn save_endpoint_data_v2( dir: &Path, loaded: &mut read::LoadedCollection, request_id: &str, data: &EndpointData, +) -> Result<(), String> { + save_endpoint_data_v2_with_policy(dir, loaded, request_id, data, write::WritePolicy::Private) +} + +fn save_endpoint_data_v2_with_policy( + dir: &Path, + loaded: &mut read::LoadedCollection, + request_id: &str, + data: &EndpointData, + policy: write::WritePolicy, ) -> Result<(), String> { let entry = find_request_entry_mut(&mut loaded.root, request_id) .ok_or_else(|| format!("Endpoint {} not found in collection", request_id))?; ipc::apply_endpoint_data(&mut entry.doc, data); - if !write::write_request_in_place(entry)? { - write::write_collection_dir(dir, loaded)?; + if !write::write_request_in_place_with_policy(entry, policy)? { + write::write_collection_dir_with_policy(dir, loaded, policy)?; } Ok(()) } @@ -299,17 +310,34 @@ fn validate_examples(examples: &[ExampleDoc]) -> Result<(), String> { /// @param request_id - Request to update /// @param examples - The full new list /// @returns Ok once the change is on disk +#[cfg(test)] fn save_examples_v2( dir: &Path, loaded: &mut read::LoadedCollection, request_id: &str, examples: Vec, +) -> Result<(), String> { + save_examples_v2_with_policy( + dir, + loaded, + request_id, + examples, + write::WritePolicy::Private, + ) +} + +fn save_examples_v2_with_policy( + dir: &Path, + loaded: &mut read::LoadedCollection, + request_id: &str, + examples: Vec, + policy: write::WritePolicy, ) -> Result<(), String> { let entry = find_request_entry_mut(&mut loaded.root, request_id) .ok_or_else(|| format!("Endpoint {} not found in collection", request_id))?; entry.doc.examples = examples; - if !write::write_request_in_place(entry)? { - write::write_collection_dir(dir, loaded)?; + if !write::write_request_in_place_with_policy(entry, policy)? { + write::write_collection_dir_with_policy(dir, loaded, policy)?; } Ok(()) } @@ -459,7 +487,15 @@ fn write_v2_collection_seeded( .unwrap_or_default(), }; - write::write_collection_dir(dir, &mut loaded)?; + write::write_collection_dir_with_policy( + dir, + &mut loaded, + if incoming.linked { + write::WritePolicy::Linked + } else { + write::WritePolicy::Private + }, + )?; collection_cache().refresh(dir, &loaded); Ok(skipped) } @@ -617,6 +653,14 @@ fn save_linked_collections( } /// Reports whether a collection was opened in place. +fn write_policy(app: &AppHandle, id: &str) -> Result { + Ok(if is_linked_collection(app, id)? { + write::WritePolicy::Linked + } else { + write::WritePolicy::Private + }) +} + fn is_linked_collection(app: &AppHandle, collection_id: &str) -> Result { Ok(link::is_linked( collection_id, @@ -1227,7 +1271,13 @@ pub async fn collection_save_endpoint_data( let paths = CollectionPaths::resolve(&app, &collection_id)?; let mut loaded = read_collection_dir_cached(collection_cache(), &paths.dir)?; - save_endpoint_data_v2(&paths.dir, &mut loaded, &endpoint_id, &data)?; + save_endpoint_data_v2_with_policy( + &paths.dir, + &mut loaded, + &endpoint_id, + &data, + write_policy(&app, &collection_id)?, + )?; collection_cache().refresh(&paths.dir, &loaded); Ok(()) } @@ -1257,7 +1307,13 @@ pub async fn collection_save_examples( validate_examples(&examples)?; let paths = CollectionPaths::resolve(&app, &collection_id)?; let mut loaded = read_collection_dir_cached(collection_cache(), &paths.dir)?; - save_examples_v2(&paths.dir, &mut loaded, &endpoint_id, examples)?; + save_examples_v2_with_policy( + &paths.dir, + &mut loaded, + &endpoint_id, + examples, + write_policy(&app, &collection_id)?, + )?; collection_cache().refresh(&paths.dir, &loaded); Ok(()) } @@ -1278,7 +1334,11 @@ pub async fn collection_delete_endpoint_data( .and_then(|entry| entry.source.clone()); if remove_request_from_tree(&mut loaded.root, &endpoint_id) { - write::write_collection_dir(&paths.dir, &mut loaded)?; + write::write_collection_dir_with_policy( + &paths.dir, + &mut loaded, + write_policy(&app, &collection_id)?, + )?; if let Some(file) = request_file { let _ = fs::remove_file(file); } @@ -1301,7 +1361,11 @@ pub async fn collection_delete_folder( let folder = take_folder_from_tree(&mut loaded.root, &folder_id) .ok_or_else(|| format!("Folder {} not found in collection", folder_id))?; - write::write_collection_dir(&paths.dir, &mut loaded)?; + write::write_collection_dir_with_policy( + &paths.dir, + &mut loaded, + write_policy(&app, &collection_id)?, + )?; remove_folder_files(&folder); collection_cache().refresh(&paths.dir, &loaded); @@ -1338,16 +1402,25 @@ pub async fn collection_save_variables( } } - save_variables_in(&paths.dir, variables) + save_variables_in_with_policy(&paths.dir, variables, write_policy(&app, &collection_id)?) } /// Replaces a collection's variables on disk. The directory writer skips an /// empty list, so clearing the last variable removes the file here; otherwise /// the old values would come back on the next uncached read. +#[cfg(test)] fn save_variables_in(dir: &Path, variables: Vec) -> Result<(), String> { + save_variables_in_with_policy(dir, variables, write::WritePolicy::Private) +} + +fn save_variables_in_with_policy( + dir: &Path, + variables: Vec, + policy: write::WritePolicy, +) -> Result<(), String> { let mut loaded = read_collection_dir_cached(collection_cache(), dir)?; loaded.variables = variables; - write::write_collection_dir(dir, &mut loaded)?; + write::write_collection_dir_with_policy(dir, &mut loaded, policy)?; if loaded.variables.is_empty() { let file = dir.join(layout::VARIABLES_YAML); if file.exists() { diff --git a/src-tauri/src/commands/import_export/postman.rs b/src-tauri/src/commands/import_export/postman.rs index 9a5816b0..eac5e74f 100644 --- a/src-tauri/src/commands/import_export/postman.rs +++ b/src-tauri/src/commands/import_export/postman.rs @@ -471,7 +471,7 @@ fn extract_postman_oauth2(params: Option<&Vec>) -> Value { /// Extract request body from Postman body format /// Raw bodies become { example: "..." }. -/// Form bodies become { type: "formdata"|"urlencoded", fields: { key: value } }. +/// Form bodies become { type: "formdata"|"urlencoded", fields: [{ key, value, enabled, ... }] }. /// GraphQL bodies become a `graphql_data` payload { mode, query, variables }. fn extract_postman_body(body: Option<&Value>) -> ParsedBody { let Some(body_obj) = body.and_then(|b| b.as_object()) else { @@ -491,48 +491,20 @@ fn extract_postman_body(body: Option<&Value>) -> ParsedBody { "example": raw_content })) } - "formdata" => { - if let Some(formdata) = body_obj.get("formdata").and_then(|f| f.as_array()) { - let mut fields = serde_json::Map::new(); - for item in formdata { - if item.get("type").and_then(|t| t.as_str()) == Some("file") { - continue; - } - if let (Some(key), Some(value)) = ( - item.get("key").and_then(|k| k.as_str()), - item.get("value").and_then(|v| v.as_str()), - ) { - fields.insert(key.to_string(), Value::String(value.to_string())); - } - } - if !fields.is_empty() { - return ParsedBody::RequestBody(serde_json::json!({ - "type": "formdata", - "fields": Value::Object(fields) - })); - } - } - ParsedBody::Empty - } - "urlencoded" => { - if let Some(urlencoded) = body_obj.get("urlencoded").and_then(|u| u.as_array()) { - let mut fields = serde_json::Map::new(); - for item in urlencoded { - if let (Some(key), Some(value)) = ( - item.get("key").and_then(|k| k.as_str()), - item.get("value").and_then(|v| v.as_str()), - ) { - fields.insert(key.to_string(), Value::String(value.to_string())); - } - } - if !fields.is_empty() { - return ParsedBody::RequestBody(serde_json::json!({ - "type": "urlencoded", - "fields": Value::Object(fields) - })); - } - } - ParsedBody::Empty + "formdata" | "urlencoded" => { + let fields: Vec = body_obj.get(mode).and_then(Value::as_array) + .into_iter().flatten() + .filter(|item| item.get("type").and_then(Value::as_str) != Some("file")) + .filter_map(|item| { + let key = item.get("key")?.as_str()?; + let value = item.get("value").and_then(Value::as_str).unwrap_or(""); + Some(serde_json::json!({ + "key": key, "value": value, "type": "text", "filePath": "", + "contentType": item.get("contentType").and_then(Value::as_str).unwrap_or(""), + "enabled": item.get("disabled").and_then(Value::as_bool) != Some(true) + })) + }).collect(); + ParsedBody::RequestBody(serde_json::json!({"type": mode, "fields": fields})) } "graphql" => { let graphql = body_obj.get("graphql").and_then(|g| g.as_object()); @@ -1049,3 +1021,24 @@ mod tests { } } } + +#[cfg(test)] +mod disabled_form_regressions { + use super::*; + #[test] + fn imported_form_rows_preserve_disabled_duplicates_and_empty_values() { + for mode in ["formdata", "urlencoded"] { + let body = serde_json::json!({"mode":mode, mode: [ + {"key":"a", "value":"", "disabled":true}, + {"key":"a", "value":"second", "contentType":"text/plain"} + ]}); + let ParsedBody::RequestBody(parsed) = extract_postman_body(Some(&body)) else { + panic!("form missing"); + }; + assert_eq!(parsed["fields"][0]["enabled"], false); + assert_eq!(parsed["fields"][0]["value"], ""); + assert_eq!(parsed["fields"][1]["key"], "a"); + assert_eq!(parsed["fields"][1]["enabled"], true); + } + } +} diff --git a/src-tauri/src/commands/import_export/storage.rs b/src-tauri/src/commands/import_export/storage.rs index f581fbac..df86165c 100644 --- a/src-tauri/src/commands/import_export/storage.rs +++ b/src-tauri/src/commands/import_export/storage.rs @@ -4,6 +4,7 @@ use super::{Collection, VariableEntry}; use crate::commands::collections as storage_collections; +use serde_json::Value; use std::path::PathBuf; use tauri::AppHandle; use tauri_plugin_dialog::{DialogExt, FilePath}; @@ -89,11 +90,14 @@ pub(crate) fn save_collection_to_files( let mut endpoint_data = std::collections::HashMap::new(); for endpoint in &collection.endpoints { - if endpoint.scripts.is_none() && endpoint.graphql_data.is_none() { + let form_body_data = imported_form_body(endpoint.request_body.as_ref()); + if endpoint.scripts.is_none() && endpoint.graphql_data.is_none() && form_body_data.is_none() + { continue; } endpoint_data.entry(endpoint.id.clone()).or_insert_with(|| { storage_collections::EndpointData { + form_body_data, scripts: endpoint.scripts.clone(), graphql_data: endpoint.graphql_data.clone(), ..Default::default() @@ -165,3 +169,42 @@ pub(crate) async fn pick_import_file_with_kind( save_last_import_directory(app, file_path); Ok(Some(file_path.to_path_buf())) } + +/// Seed editable form state so the editor and runner see the same imported rows. +fn imported_form_body(body: Option<&Value>) -> Option { + let body = body?; + let mode = body.get("type")?.as_str()?; + if !matches!(mode, "formdata" | "urlencoded") { + return None; + } + Some( + serde_json::json!({"mode": mode, "fields": body.get("fields").cloned().unwrap_or(serde_json::json!([]))}), + ) +} + +#[cfg(test)] +mod form_seed_tests { + use super::*; + #[test] + fn form_seed_survives_the_collection_body_round_trip() { + let rows = serde_json::json!([ + {"key":"a", "value":"", "enabled":false}, + {"key":"a", "value":"second", "enabled":true} + ]); + for mode in ["formdata", "urlencoded"] { + let body = serde_json::json!({"type":mode, "fields":rows}); + let data = storage_collections::EndpointData { + form_body_data: imported_form_body(Some(&body)), + ..Default::default() + }; + let mut doc: resonance_collections::model::RequestDoc = + serde_json::from_value(serde_json::json!({"id":"r", "name":"Form"})).unwrap(); + resonance_collections::ipc::apply_endpoint_data(&mut doc, &data); + let yaml = resonance_collections::write::to_yaml(&doc).unwrap(); + let reread: resonance_collections::model::RequestDoc = + serde_yaml_ng::from_str(&yaml).unwrap(); + let read = resonance_collections::ipc::request_to_endpoint_data(&reread); + assert_eq!(read.form_body_data.unwrap()["fields"], rows); + } + } +} diff --git a/src-tauri/src/commands/mock_server.rs b/src-tauri/src/commands/mock_server.rs index 6f3211db..67e6d244 100644 --- a/src-tauri/src/commands/mock_server.rs +++ b/src-tauri/src/commands/mock_server.rs @@ -183,13 +183,15 @@ pub async fn mock_server_status() -> Result { Ok(serde_json::json!({ "running": true, "port": server.port, - "requestCount": log_count + "requestCount": log_count, + "loadedCollectionIds": server.state.endpoints.read().unwrap().iter().map(|endpoint| endpoint.collection_id.clone()).collect::>() })) } else { Ok(serde_json::json!({ "running": false, "port": null, - "requestCount": 0 + "requestCount": 0, + "loadedCollectionIds": [] })) } } @@ -221,11 +223,19 @@ pub async fn mock_server_clear_logs() -> Result { } #[tauri::command] -pub async fn mock_server_reload_settings(settings: MockServerSettings) -> Result { +pub async fn mock_server_reload_settings( + settings: MockServerSettings, + collections: Option>, +) -> Result { let handle = get_server_handle().read().unwrap(); if let Some(server) = handle.as_ref() { - apply_settings(&server.state, settings, server.port); + if let Some(collections) = collections { + let endpoints = build_routing_table(&collections); + apply_routes(&server.state, settings, endpoints, server.port); + } else { + apply_settings(&server.state, settings, server.port); + } Ok(serde_json::json!({ "success": true, "message": "Settings reloaded successfully" @@ -235,6 +245,20 @@ pub async fn mock_server_reload_settings(settings: MockServerSettings) -> Result } } +/// Replace routes and settings while excluding request readers from both. +fn apply_routes( + state: &MockServerState, + settings: MockServerSettings, + endpoints: Vec, + port: u16, +) { + // Match the handler's endpoints -> settings lock order. + let mut routes = state.endpoints.write().unwrap(); + let mut current = state.settings.write().unwrap(); + *routes = endpoints; + *current = MockServerSettings { port, ..settings }; +} + /// Swaps in new per-endpoint settings; the bound port can't change while running. fn apply_settings(state: &MockServerState, settings: MockServerSettings, port: u16) { *state.settings.write().unwrap() = MockServerSettings { port, ..settings }; @@ -1128,6 +1152,23 @@ mod tests { serde_json::json!({ "id": id, "name": id, "method": method, "path": path }) } + #[tokio::test] + async fn route_reload_replaces_routes_and_can_disable_the_last_collection() { + let state = state_with(vec![endpoint("old", "GET", "/old")]); + let settings = state.settings.read().unwrap().clone(); + apply_routes( + &state, + settings.clone(), + build_routing_table(&[collection(vec![endpoint("new", "GET", "/new")])]), + 3000, + ); + assert_eq!(call(&state, "GET", "/old").await.0, StatusCode::NOT_FOUND); + assert_eq!(call(&state, "GET", "/new").await.0, StatusCode::OK); + apply_routes(&state, settings, Vec::new(), 3000); + assert_eq!(call(&state, "GET", "/new").await.0, StatusCode::NOT_FOUND); + assert_eq!(state.settings.read().unwrap().port, 3000); + } + fn state_with(endpoints: Vec) -> MockServerState { let state = empty_state(); *state.endpoints.write().unwrap() = build_routing_table(&[collection(endpoints)]); diff --git a/src/modules/WorkspaceTabStateManager.js b/src/modules/WorkspaceTabStateManager.js index 5e0fa09f..802a82b8 100644 --- a/src/modules/WorkspaceTabStateManager.js +++ b/src/modules/WorkspaceTabStateManager.js @@ -699,6 +699,7 @@ export class WorkspaceTabStateManager { _clearResponse(tabId) { clearResponseDisplayForTab(tabId); + setResponseMeta(tabId, { isBinary: false, base64: null, suggestedName: 'response' }); updateStatusDisplay('Ready', null); diff --git a/src/modules/apiHandler.js b/src/modules/apiHandler.js index 2450e14e..a011010b 100644 --- a/src/modules/apiHandler.js +++ b/src/modules/apiHandler.js @@ -449,7 +449,8 @@ async function sendHttpRequest() { previous?.cancel().catch(() => {}); const execution = core.createExecution(); manualExecutions.set(requestTabId, execution); - const isCurrent = () => manualExecutions.get(requestTabId) === execution && !execution.cancelled; + const isCurrent = () => manualExecutions.get(requestTabId) === execution && !execution.cancelled && + inFlightRequestFor(requestTabId) === execution.executionId; const untrack = trackInFlight(requestTabId, execution.executionId); setRequestInProgress(true); const { schemaController } = app; @@ -575,6 +576,7 @@ async function handleReceivedResponse(result, { requestConfig, requestTabId, url } const cookies = responseCookies(result); + if (!isCurrentResponse()) { return; } if (app.workspaceTabController && requestTabId) { app.workspaceTabController.service.updateTab(requestTabId, { diff --git a/src/modules/controllers/CollectionController.js b/src/modules/controllers/CollectionController.js index 18dd6cb9..4ab5b776 100644 --- a/src/modules/controllers/CollectionController.js +++ b/src/modules/controllers/CollectionController.js @@ -1064,6 +1064,11 @@ export class CollectionController { try { await app.runnerBookkeeping?.forgetCollection(collection.id); await this.service.deleteCollection(collection.id); + await app.workspaceTabController?.service.detachCollection(collection.id); + if (getCurrentEndpoint()?.collectionId === collection.id) { + setCurrentEndpoint(null); + this.highlightEndpoint(null); + } await this.variableService.cleanupCollectionVariables(collection.id); await this.loadCollections(); toast.success(`Collection "${collection.name}" deleted`); diff --git a/src/modules/grpcHandler.js b/src/modules/grpcHandler.js index abb4b846..cd33bd3a 100644 --- a/src/modules/grpcHandler.js +++ b/src/modules/grpcHandler.js @@ -633,6 +633,7 @@ async function invokeGrpcUnary({ target, fullMethod, requestJson, metadata, prot ? await window.backendAPI.grpc.protoInvokeUnary(protoPath, unaryRequest) : await window.backendAPI.grpc.invokeUnary(unaryRequest); + if (inFlightRequestFor(requestTabId) !== requestId) {return;} if (result.cancelled) { displayResponseWithLineNumbersForTab('Request was cancelled', null, requestTabId); await showStatus('Request cancelled'); @@ -656,8 +657,10 @@ async function invokeGrpcUnary({ target, fullMethod, requestJson, metadata, prot await showStatus(result.success ? 'gRPC OK' : `gRPC error: ${result.statusMessage || 'unknown'}`); + if (inFlightRequestFor(requestTabId) !== requestId) {return;} await persistGrpcResult(requestTabId, result, grpcPanes, Date.now() - startedAt, historyContext, containerElements); } catch (error) { + if (inFlightRequestFor(requestTabId) !== requestId) {return;} const msg = error.message || String(error); toast.error(`gRPC send error: ${msg}`); await showStatus(`gRPC send error: ${msg}`); diff --git a/src/modules/ipcBridge.js b/src/modules/ipcBridge.js index 9a637ca0..0068de2c 100644 --- a/src/modules/ipcBridge.js +++ b/src/modules/ipcBridge.js @@ -147,7 +147,7 @@ if (isTauri) { status: () => invoke('mock_server_status'), logs: (limit) => invoke('mock_server_logs', { limit }), clearLogs: () => invoke('mock_server_clear_logs'), - reloadSettings: (settings) => invoke('mock_server_reload_settings', { settings }) + reloadSettings: (settings, collections = null) => invoke('mock_server_reload_settings', { settings, collections }) }, schema: { check: (schema) => invoke('schema_check', { schema }), diff --git a/src/modules/mockServer.feature.js b/src/modules/mockServer.feature.js index 46d5cc27..887e81de 100644 --- a/src/modules/mockServer.feature.js +++ b/src/modules/mockServer.feature.js @@ -13,7 +13,7 @@ export const mockServerFeature = { name: 'mockServer', create(ctx) { const repository = new MockServerRepository(ctx.backendAPI); - const service = new MockServerService(repository, ctx.statusDisplay); + const service = new MockServerService(repository, ctx.statusDisplay, () => ctx.get('collectionRepository').getAll()); const controller = new MockServerController(service, ctx.get('collectionRepository')); const dialog = new MockServerDialog(controller); return { repository, service, controller, dialog }; diff --git a/src/modules/services/CoreExecutionService.js b/src/modules/services/CoreExecutionService.js index adf27675..bae8d0b7 100644 --- a/src/modules/services/CoreExecutionService.js +++ b/src/modules/services/CoreExecutionService.js @@ -400,14 +400,13 @@ export function captureRunnerEntry(entry, { collection, endpoint, persisted, inh headers[row.key] = row.value ?? ''; } } - let queryRows = ( - (Array.isArray(overrides.queryParams) ? overrides.queryParams : persisted.queryParams) || [] - ).filter((row) => row.enabled !== false && row.key); - if (!queryRows.length) { - queryRows = Object.entries(endpoint.parameters?.query || {}) + const hasQueryOverride = Array.isArray(overrides.queryParams); + const configuredQueryRows = hasQueryOverride ? overrides.queryParams : persisted.queryParams || []; + const queryRows = hasQueryOverride || configuredQueryRows.length + ? configuredQueryRows.filter(row => row.enabled !== false && row.key) + : Object.entries(endpoint.parameters?.query || {}) .filter(([, param]) => param.example) .map(([key, param]) => ({ key, value: String(param.example) })); - } const form = persisted.formBodyData || {}; const hasOverride = typeof overrides.body === 'string'; const nonemptyOverride = hasOverride && overrides.body.trim() !== ''; diff --git a/src/modules/services/MockServerService.js b/src/modules/services/MockServerService.js index cf67805a..c26210d6 100644 --- a/src/modules/services/MockServerService.js +++ b/src/modules/services/MockServerService.js @@ -10,8 +10,10 @@ export class MockServerService { * @param {MockServerRepository} repository * @param {IStatusDisplay} statusDisplay */ - constructor(repository, statusDisplay) { + constructor(repository, statusDisplay, getCollections = async () => []) { this.repository = repository; + this.getCollections = getCollections; + this._mutationChain = Promise.resolve(); this.statusDisplay = statusDisplay; this._events = new ChangeEmitter(); } @@ -38,11 +40,19 @@ export class MockServerService { } } - /** - * @param {Array} collections - * @returns {Promise} - */ - async startServer(collections) { + /** Serialize lifecycle and settings changes against the live server. */ + _serialize(work) { + const mutation = this._mutationChain.catch(() => {}).then(work); + this._mutationChain = mutation; + return mutation; + } + + /** @param {Array} collections */ + startServer(collections) { + return this._serialize(() => this._startServer(collections)); + } + + async _startServer(collections) { try { const settings = await this.repository.getSettings(); @@ -74,7 +84,11 @@ export class MockServerService { } /** @returns {Promise} */ - async stopServer() { + stopServer() { + return this._serialize(() => this._stopServer()); + } + + async _stopServer() { try { const result = await window.backendAPI.mockServer.stop(); @@ -112,16 +126,13 @@ export class MockServerService { */ async shouldUseMockServer(collectionId) { try { - const [status, settings] = await Promise.all([ - this.getStatus(), - this.getSettings() - ]); + const status = await this.getStatus(); if (!status.running) { return { shouldUseMock: false, mockBaseUrl: null }; } - if (!settings.enabledCollections.includes(collectionId)) { + if (!status.loadedCollectionIds?.includes(collectionId)) { return { shouldUseMock: false, mockBaseUrl: null }; } @@ -160,7 +171,11 @@ export class MockServerService { * @param {Object} updates * @returns {Promise} */ - async updateSettings(updates) { + updateSettings(updates) { + return this._serialize(() => this._updateSettings(updates)); + } + + async _updateSettings(updates) { return this._reporting('Error updating mock server settings', async () => { const status = await this.getStatus(); const requiresRestart = status.running && updates.port !== undefined; @@ -183,7 +198,11 @@ export class MockServerService { * @param {number} delayMs * @returns {Promise} */ - async setEndpointDelay(collectionId, endpointId, delayMs) { + setEndpointDelay(collectionId, endpointId, delayMs) { + return this._serialize(() => this._setEndpointDelay(collectionId, endpointId, delayMs)); + } + + async _setEndpointDelay(collectionId, endpointId, delayMs) { return this._reporting('Error setting endpoint delay', async () => { const errors = this.validateDelay(delayMs); if (errors.length > 0) { @@ -204,7 +223,11 @@ export class MockServerService { * @param {Object|null} response * @returns {Promise} */ - async setCustomResponse(collectionId, endpointId, response) { + setCustomResponse(collectionId, endpointId, response) { + return this._serialize(() => this._setCustomResponse(collectionId, endpointId, response)); + } + + async _setCustomResponse(collectionId, endpointId, response) { return this._reporting('Error setting custom response', async () => { const result = await this.repository.setCustomResponse(collectionId, endpointId, response); @@ -233,7 +256,11 @@ export class MockServerService { * @param {number|null} statusCode * @returns {Promise} */ - async setCustomStatusCode(collectionId, endpointId, statusCode) { + setCustomStatusCode(collectionId, endpointId, statusCode) { + return this._serialize(() => this._setCustomStatusCode(collectionId, endpointId, statusCode)); + } + + async _setCustomStatusCode(collectionId, endpointId, statusCode) { return this._reporting('Error setting custom status code', async () => { const result = await this.repository.setCustomStatusCode(collectionId, endpointId, statusCode); @@ -260,11 +287,28 @@ export class MockServerService { * @param {string} collectionId * @returns {Promise} */ - async toggleCollectionEnabled(collectionId) { - return this._reporting('Error toggling collection', async () => { + toggleCollectionEnabled(collectionId) { + return this._serialize(() => this._reporting('Error toggling collection', async () => { + const previous = await this.repository.getSettings(); + const status = await window.backendAPI.mockServer.status(); + const collections = status.running ? await this.getCollections() : []; const settings = await this.repository.toggleCollectionEnabled(collectionId); + if (status.running) { + try { + const enabled = collections.filter(collection => settings.enabledCollections.includes(collection.id)); + const availableIds = new Set(enabled.map(collection => collection.id)); + if (settings.enabledCollections.some(id => !availableIds.has(id))) { + throw new Error('An enabled collection is no longer available'); + } + const result = await window.backendAPI.mockServer.reloadSettings(settings, enabled); + if (!result.success) { throw new Error(result.message || 'Could not reload mock routes'); } + } catch (error) { + await this.repository.saveSettings(previous); + throw error; + } + } return settings.enabledCollections.includes(collectionId); - }); + })); } /** diff --git a/src/modules/services/WorkspaceTabEndpointLoaderService.js b/src/modules/services/WorkspaceTabEndpointLoaderService.js index f19ec063..9a7e0251 100644 --- a/src/modules/services/WorkspaceTabEndpointLoaderService.js +++ b/src/modules/services/WorkspaceTabEndpointLoaderService.js @@ -3,6 +3,7 @@ * @module services/WorkspaceTabEndpointLoaderService */ +import { invalidateInFlight } from '../state/inFlightRequests.js'; import { app } from '../appContext.js'; import { getProtocol } from '../protocols/protocolRegistry.js'; import { normalizeKeyValueRows } from '../utils/keyValueRows.js'; @@ -59,6 +60,7 @@ export class WorkspaceTabEndpointLoaderService { async loadEndpoint(endpoint, targetTabId) { try { const tabUpdate = { ...this.createTabUpdate(endpoint), historyEntryId: null }; + invalidateInFlight(targetTabId); const tab = await this.service.updateTab(targetTabId, tabUpdate); if (tab) { @@ -78,6 +80,7 @@ export class WorkspaceTabEndpointLoaderService { async loadHistoryEntry(historyEntry, targetTabId) { try { const tabUpdate = this.createHistoryTabUpdate(historyEntry); + invalidateInFlight(targetTabId); const tab = await this.service.updateTab(targetTabId, tabUpdate); if (tab) { @@ -105,6 +108,8 @@ export class WorkspaceTabEndpointLoaderService { return { ...update, type: 'request', + response: null, + responseInspection: null, endpoint: null, historyEntryId: historyEntry.id || null, isModified: false @@ -291,6 +296,8 @@ export class WorkspaceTabEndpointLoaderService { return { name, type: 'request', + response: null, + responseInspection: null, endpoint: { collectionId: endpoint.collectionId, endpointId: endpoint.id, diff --git a/src/modules/services/WorkspaceTabService.js b/src/modules/services/WorkspaceTabService.js index 1342bc89..1b280f10 100644 --- a/src/modules/services/WorkspaceTabService.js +++ b/src/modules/services/WorkspaceTabService.js @@ -158,6 +158,11 @@ export class WorkspaceTabService { }); } + /** Clear bindings to a deleted collection while preserving tab contents. */ + async detachCollection(collectionId) { + return this.repository.detachCollection(collectionId); + } + /** * @param {string} tabId * @param {Object} updates diff --git a/src/modules/state/inFlightRequests.js b/src/modules/state/inFlightRequests.js index 0a5b3542..f977a3a9 100644 --- a/src/modules/state/inFlightRequests.js +++ b/src/modules/state/inFlightRequests.js @@ -42,3 +42,8 @@ export function trackInFlight(tabId, requestId) { export function inFlightRequestFor(tabId) { return byTab.get(tabId ?? NO_TAB) ?? null; } + +/** Detach a replaced request so its late response cannot update the tab. */ +export function invalidateInFlight(tabId) { + byTab.delete(tabId ?? NO_TAB); +} diff --git a/src/modules/storage/WorkspaceTabRepository.js b/src/modules/storage/WorkspaceTabRepository.js index 4e313155..21fe6d37 100644 --- a/src/modules/storage/WorkspaceTabRepository.js +++ b/src/modules/storage/WorkspaceTabRepository.js @@ -307,6 +307,13 @@ export class WorkspaceTabRepository { return newTab; } + /** Clear bindings to a deleted collection while preserving tab contents. */ + async detachCollection(collectionId) { + const tabs = await this.getTabs(); + await this.saveTabs(tabs.map(tab => tab.endpoint?.collectionId === collectionId + ? { ...tab, endpoint: null } : tab)); + } + /** * @param {string} tabId * @param {Object} updates @@ -357,7 +364,7 @@ export class WorkspaceTabRepository { const mergedEndpoint = (updates.endpoint && existingTab.endpoint) ? { ...existingTab.endpoint, ...updates.endpoint } : - (updates.endpoint || existingTab.endpoint); + (updates.endpoint !== undefined ? updates.endpoint : existingTab.endpoint); const { request: _r, response: _res, endpoint: _e, ...restUpdates } = updates; diff --git a/src/modules/ui/EnvironmentManager.js b/src/modules/ui/EnvironmentManager.js index ab9f5632..3d436391 100644 --- a/src/modules/ui/EnvironmentManager.js +++ b/src/modules/ui/EnvironmentManager.js @@ -142,9 +142,10 @@ export class EnvironmentManager extends BaseModal { envs.find(e => e.id === environmentId) ); - if (!environment) {return;} + if (!environment || this.currentEnvironmentId !== environmentId) {return;} const activeEnvId = await this.service.getActiveEnvironmentId(); + if (this.currentEnvironmentId !== environmentId || !this.dialog) {return;} const isActive = environment.id === activeEnvId; const detailsContainer = this.dialog.querySelector('#env-details'); @@ -154,6 +155,7 @@ export class EnvironmentManager extends BaseModal { TEMPLATE_PATH, 'tpl-environment-manager-details' ); + if (this.currentEnvironmentId !== environmentId || !detailsContainer.isConnected) {return;} detailsContainer.appendChild(detailsFragment); const setActiveBtn = detailsContainer.querySelector('#env-set-active-btn'); @@ -377,7 +379,8 @@ export class EnvironmentManager extends BaseModal { : value; return { name, value: resolvedValue, isSecret }; })); - await Promise.all(rows.map(row => this.addVariableRow(row, container))); + if (this.currentEnvironmentId !== environment.id || !container.isConnected) {return;} + await Promise.all(rows.map(row => this.addVariableRow(row, container, environment.id))); this.updateVariablesEmptyState(); } @@ -389,7 +392,7 @@ export class EnvironmentManager extends BaseModal { } /** @returns {Promise} */ - addVariableRow({ name = '', value = '', isSecret = false }, container = null) { + addVariableRow({ name = '', value = '', isSecret = false }, container = null, environmentId = this.currentEnvironmentId) { if (!container) { container = this.dialog.querySelector('#env-variables-container'); } @@ -407,7 +410,7 @@ export class EnvironmentManager extends BaseModal { this.applySecretState(row, isSecret); - this.setupVariableRowListeners(row, name); + this.setupVariableRowListeners(row, name, environmentId); this.updateVariablesEmptyState(); return row; }) @@ -423,7 +426,7 @@ export class EnvironmentManager extends BaseModal { secretBtn?.setAttribute('aria-pressed', String(isSecret)); } - setupVariableRowListeners(row, originalName) { + setupVariableRowListeners(row, originalName, environmentId = this.currentEnvironmentId) { const nameInput = row.querySelector('.var-name-input'); const valueInput = row.querySelector('.var-value-input'); const deleteBtn = row.querySelector('.var-delete-btn'); @@ -433,24 +436,33 @@ export class EnvironmentManager extends BaseModal { const isSecret = () => row.dataset.secret === 'true'; let currentName = originalName; - const saveVariable = async () => { - const name = nameInput.value.trim(); - const value = valueInput.value.trim(); - - if (!name) { - if (currentName) { - await this.deleteVariable(currentName); - currentName = ''; + let pending = Promise.resolve(); + const enqueue = work => { + pending = pending.then(work).catch(error => toast.error(error.message)); + return pending; + }; + const saveVariable = () => { + const nextName = nameInput.value.trim(); + const nextValue = valueInput.value.trim(); + const nextSecret = isSecret(); + return enqueue(async () => { + const name = nextName; + const value = nextValue; + + if (!name) { + if (currentName) { + await this.service.deleteVariable(environmentId, currentName); + currentName = ''; + } + return; } - return; - } - if (currentName && name !== currentName) { - await this.deleteVariable(currentName); - } - - await this.setVariable(name, value, isSecret()); - currentName = name; + await this.service.setVariable(environmentId, name, value, nextSecret); + if (currentName && name !== currentName) { + await this.service.deleteVariable(environmentId, currentName); + } + currentName = name; + }); }; nameInput.addEventListener('blur', saveVariable); @@ -465,12 +477,12 @@ export class EnvironmentManager extends BaseModal { }); if (secretBtn) { - secretBtn.addEventListener('click', async () => { + secretBtn.addEventListener('click', () => { const next = !isSecret(); this.applySecretState(row, next); const name = nameInput.value.trim(); if (name) { - await this.setVariable(name, valueInput.value.trim(), next); + saveVariable(); } }); } @@ -479,13 +491,13 @@ export class EnvironmentManager extends BaseModal { revealBtn.addEventListener('click', () => toggleRevealed(valueInput, revealBtn)); } - deleteBtn.addEventListener('click', async () => { + deleteBtn.addEventListener('click', () => enqueue(async () => { if (currentName) { - await this.deleteVariable(currentName); + await this.service.deleteVariable(environmentId, currentName); } row.remove(); this.updateVariablesEmptyState(); - }); + })); } /** diff --git a/tests/apiHandler/handleSendRequest.httpResponse.test.js b/tests/apiHandler/handleSendRequest.httpResponse.test.js index f3fa3223..c7603fd4 100644 --- a/tests/apiHandler/handleSendRequest.httpResponse.test.js +++ b/tests/apiHandler/handleSendRequest.httpResponse.test.js @@ -68,6 +68,26 @@ afterEach(() => { }); describe('HTTP responses of every status are treated as responses', () => { + test('a response arriving after request replacement cannot overwrite the new tab', async () => { + const { handleSendRequest, updateTab, app } = await loadApiHandler({}); + let resolveResponse; + let signalStarted; + const started = new Promise(resolve => { signalStarted = resolve; }); + window.backendAPI.sendApiRequest.mockImplementation(() => { + signalStarted(); + return new Promise(resolve => { resolveResponse = resolve; }); + }); + const sending = handleSendRequest(); + await started; + const { invalidateInFlight } = await import('../../src/modules/state/inFlightRequests.js'); + invalidateInFlight('tab-1'); + resolveResponse({ status: 200, success: true, data: 'old response', headers: {} }); + await sending; + expect(updateTab).not.toHaveBeenCalled(); + delete app.workspaceTabController; + delete app.cookieController; + }); + test('retains the complete live inspection source across tab restores when storage caps its body', async () => { const data = { value: 'x'.repeat(500100) }; const { handleSendRequest, app, updateTab } = await loadApiHandler({ diff --git a/tests/controllers/CollectionController.tabSync.test.js b/tests/controllers/CollectionController.tabSync.test.js index 200cb9d7..ceccbd14 100644 --- a/tests/controllers/CollectionController.tabSync.test.js +++ b/tests/controllers/CollectionController.tabSync.test.js @@ -65,3 +65,20 @@ describe('CollectionController.handleRenameRequest', () => { expect(controller.service.renameRequest).toHaveBeenCalledWith('c1', 'e1', 'Named'); }); }); + + test.each([false, true])('collection deletion detaches tabs only after success (failure=%s)', async fails => { + const { setCurrentEndpoint, getCurrentEndpoint } = await import('../../src/modules/state/currentEndpoint.js'); + const controller = makeController(); + controller.confirmDialog = { show: jest.fn(async () => true) }; + controller.service.deleteCollection = fails ? jest.fn(async () => { throw new Error('disk failure'); }) : jest.fn(async () => {}); + controller.variableService = { cleanupCollectionVariables: jest.fn(async () => {}) }; + controller.loadCollections = jest.fn(async () => {}); + controller.highlightEndpoint = jest.fn(); + const detachCollection = jest.fn(async () => {}); + app.workspaceTabController = { service: { detachCollection } }; + setCurrentEndpoint({ collectionId: 'c1', endpointId: 'e1' }); + await controller.handleDelete(collection); + expect(detachCollection).toHaveBeenCalledTimes(fails ? 0 : 1); + expect(getCurrentEndpoint()).toEqual(fails ? { collectionId: 'c1', endpointId: 'e1' } : null); + setCurrentEndpoint(null); +}); diff --git a/tests/fixtures/execution/template-capture.json b/tests/fixtures/execution/template-capture.json index ccbfd0a8..0e12b591 100644 --- a/tests/fixtures/execution/template-capture.json +++ b/tests/fixtures/execution/template-capture.json @@ -365,9 +365,9 @@ } }, { - "name": "disabled queries fall back to examples", + "name": "disabled queries stay disabled", "entry": { - "name": "disabled queries fall back to examples" + "name": "disabled queries stay disabled" }, "target": { "collection": { @@ -454,7 +454,7 @@ "expected": { "collectionId": "collection", "endpointId": "request", - "name": "disabled queries fall back to examples", + "name": "disabled queries stay disabled", "path": "/items/{id}", "method": "POST", "protocol": "http", @@ -471,12 +471,7 @@ "zero" ], "headers": {}, - "queryRows": [ - { - "key": "q", - "value": "example" - } - ], + "queryRows": [], "bearerFallback": true, "auth": { "type": "inherit", @@ -1159,12 +1154,7 @@ "zero" ], "headers": {}, - "queryRows": [ - { - "key": "q", - "value": "example" - } - ], + "queryRows": [], "bearerFallback": true, "auth": { "type": "inherit", @@ -1705,12 +1695,7 @@ "zero" ], "headers": {}, - "queryRows": [ - { - "key": "q", - "value": "example" - } - ], + "queryRows": [], "bearerFallback": true, "auth": { "type": "inherit", @@ -2251,12 +2236,7 @@ "zero" ], "headers": {}, - "queryRows": [ - { - "key": "q", - "value": "example" - } - ], + "queryRows": [], "bearerFallback": true, "auth": { "type": "inherit", @@ -2797,12 +2777,7 @@ "zero" ], "headers": {}, - "queryRows": [ - { - "key": "q", - "value": "example" - } - ], + "queryRows": [], "bearerFallback": true, "auth": { "type": "inherit", @@ -3365,5 +3340,163 @@ "details": null } } + }, + { + "name": "explicit empty query override suppresses examples", + "entry": { + "name": "explicit empty query override suppresses examples", + "overrides": { + "queryParams": [] + } + }, + "target": { + "collection": { + "id": "collection", + "baseUrl": "https://api.test", + "defaultHeaders": { + "Accept": "application/json" + } + }, + "endpoint": { + "id": "request", + "path": "/items/{id}", + "method": "POST", + "parameters": { + "path": { + "id": { + "example": 7 + }, + "zero": { + "example": 0 + } + }, + "query": { + "q": { + "example": "example" + }, + "empty": { + "example": "" + } + } + } + }, + "persisted": {}, + "inheritedAuth": [ + { + "source": { + "kind": "folder", + "folderId": "inner" + }, + "authConfig": { + "type": "inherit", + "config": {} + } + }, + { + "source": { + "kind": "folder", + "folderId": "outer" + }, + "authConfig": { + "type": "bearer", + "config": { + "token": "synthetic-token" + } + } + }, + { + "source": { + "kind": "collection" + }, + "authConfig": { + "type": "basic", + "config": { + "username": "synthetic", + "password": "synthetic" + } + } + } + ], + "scripts": { + "preRequestScript": "console.log(\"pre\")", + "testScript": "console.log(\"test\")" + }, + "mockBaseUrl": "http://localhost:3333/mock" + }, + "expected": { + "collectionId": "collection", + "endpointId": "request", + "name": "explicit empty query override suppresses examples", + "path": "/items/{id}", + "method": "POST", + "protocol": "http", + "url": "", + "baseUrl": "https://api.test", + "defaultHeaders": { + "Accept": "application/json" + }, + "pathParams": { + "id": "7" + }, + "pathParameterNames": [ + "id", + "zero" + ], + "headers": {}, + "queryRows": [], + "bearerFallback": true, + "auth": { + "type": "inherit", + "config": {} + }, + "inheritedAuth": [ + { + "source": { + "kind": "folder", + "folderId": "inner" + }, + "authConfig": { + "type": "inherit", + "config": {} + } + }, + { + "source": { + "kind": "folder", + "folderId": "outer" + }, + "authConfig": { + "type": "bearer", + "config": { + "token": "synthetic-token" + } + } + }, + { + "source": { + "kind": "collection" + }, + "authConfig": { + "type": "basic", + "config": { + "username": "synthetic", + "password": "synthetic" + } + } + } + ], + "body": { + "mode": "json", + "content": "", + "fields": [], + "filePath": "", + "contentType": null, + "graphql": null + }, + "preRequestScript": "console.log(\"pre\")", + "testScript": "console.log(\"test\")", + "postResponseScript": "", + "mockBaseUrl": "http://localhost:3333/mock" + } } ] diff --git a/tests/services/CoreExecutionService.test.js b/tests/services/CoreExecutionService.test.js index 057abbf2..3eabf707 100644 --- a/tests/services/CoreExecutionService.test.js +++ b/tests/services/CoreExecutionService.test.js @@ -294,3 +294,17 @@ test('captures proxy settings from the desktop IPC namespace and pins an immutab expect(backend.proxySettings.get).toHaveBeenCalledTimes(1); expect(pipeline.environmentRepository.getVariablesForEnvironment).toHaveBeenCalledWith('original'); }); + + test.each([ + [{ queryParams: [] }, [], []], + [{}, [{ key: 'q', value: 'disabled', enabled: false }], []], + [{}, [], [{ key: 'q', value: 'spec' }]], + [{ queryParams: [{ key: 'q', value: '', enabled: true }] }, [], [{ key: 'q', value: '', enabled: true }]] +])('runner respects explicitly configured query rows: %j', (overrides, queryParams, expected) => { + const captured = captureRunnerEntry({ overrides }, { + ...target, + endpoint: { ...target.endpoint, parameters: { query: { q: { example: 'spec' } } } }, + persisted: { ...target.persisted, queryParams } + }); + expect(captured.queryRows).toEqual(expected); +}); diff --git a/tests/services/MockServerService.test.js b/tests/services/MockServerService.test.js index b4a3553b..1cc96c49 100644 --- a/tests/services/MockServerService.test.js +++ b/tests/services/MockServerService.test.js @@ -90,7 +90,7 @@ describe('MockServerService', () => { test('shouldUseMockServer only when running and enabled', async () => { expect(await service.shouldUseMockServer('c1')).toEqual({ shouldUseMock: false, mockBaseUrl: null }); - mockServerApi.status.mockResolvedValue({ running: true, port: 3005 }); + mockServerApi.status.mockResolvedValue({ running: true, port: 3005, loadedCollectionIds: ['c1'] }); expect(await service.shouldUseMockServer('c1')).toEqual({ shouldUseMock: true, mockBaseUrl: 'http://localhost:3005' }); expect(await service.shouldUseMockServer('c9')).toEqual({ shouldUseMock: false, mockBaseUrl: null }); }); @@ -199,6 +199,156 @@ describe('MockServerService', () => { }); }); + describe('live collection toggles', () => { + let saved; + let loaded; + let collections; + let reload; + + const clone = value => JSON.parse(JSON.stringify(value)); + const tick = () => new Promise(resolve => setTimeout(resolve, 0)); + + beforeEach(() => { + saved = { port: 3000, enabledCollections: ['c1'] }; + loaded = ['c1']; + collections = [ + { id: 'c1', endpoints: [{ id: 'e1', path: '/one' }] }, + { id: 'c2', endpoints: [{ id: 'e2', path: '/two' }] } + ]; + repository.getSettings.mockImplementation(async () => clone(saved)); + repository.saveSettings = jest.fn(async settings => { + saved = clone(settings); + return clone(saved); + }); + repository.toggleCollectionEnabled.mockImplementation(async id => { + const ids = saved.enabledCollections; + saved = { ...saved, enabledCollections: ids.includes(id) ? ids.filter(value => value !== id) : [...ids, id] }; + return clone(saved); + }); + mockServerApi.status.mockImplementation(async () => ({ + running: true, port: 3000, loadedCollectionIds: [...loaded] + })); + reload = async (settings, snapshots) => { + loaded = snapshots.map(collection => collection.id); + return { success: true }; + }; + mockServerApi.reloadSettings.mockImplementation((...args) => reload(...args)); + service = new MockServerService(repository, statusDisplay, async () => collections); + }); + + test('enabling an unloaded collection loads its routes before reporting success', async () => { + expect(await service.toggleCollectionEnabled('c2')).toBe(true); + + expect(loaded).toEqual(['c1', 'c2']); + expect(mockServerApi.reloadSettings).toHaveBeenCalledWith(saved, collections); + expect(await service.shouldUseMockServer('c2')).toEqual({ shouldUseMock: true, mockBaseUrl: 'http://localhost:3000' }); + }); + + test('a toggle waits for an in-progress start before replacing routes', async () => { + let running = false; + mockServerApi.status.mockImplementation(async () => ({ running, port: 3000, loadedCollectionIds: [...loaded] })); + loaded = []; + let releaseStart; + let signalStarted; + const started = new Promise(resolve => { signalStarted = resolve; }); + window.backendAPI.mockServer.start.mockImplementation(async (_settings, snapshots) => { + signalStarted(); + await new Promise(resolve => { releaseStart = resolve; }); + running = true; + loaded = snapshots.map(collection => collection.id); + return { success: true, port: 3000 }; + }); + const start = service.startServer(collections); + await started; + const toggle = service.toggleCollectionEnabled('c2'); + releaseStart(); + await Promise.all([start, toggle]); + expect(loaded).toEqual(['c1', 'c2']); + expect(saved.enabledCollections).toEqual(['c1', 'c2']); + }); + + test('routing follows acknowledged runtime membership during a reload', async () => { + let release; + const gate = new Promise(resolve => { release = resolve; }); + reload = async (_settings, snapshots) => { + await gate; + loaded = snapshots.map(collection => collection.id); + return { success: true }; + }; + const toggle = service.toggleCollectionEnabled('c2'); + await tick(); + const beforeReload = await service.shouldUseMockServer('c2'); + release(); + await toggle; + + expect(beforeReload).toEqual({ shouldUseMock: false, mockBaseUrl: null }); + expect(await service.shouldUseMockServer('c2')).toEqual({ shouldUseMock: true, mockBaseUrl: 'http://localhost:3000' }); + }); + + test('a saved toggle cannot redirect to a collection absent from the runtime', async () => { + saved.enabledCollections.push('c2'); + expect(await service.shouldUseMockServer('c2')).toEqual({ shouldUseMock: false, mockBaseUrl: null }); + + saved.enabledCollections = []; + expect(await service.shouldUseMockServer('c1')).toEqual({ shouldUseMock: true, mockBaseUrl: 'http://localhost:3000' }); + }); + + test('disabling the last collection removes routes without stopping the server', async () => { + expect(await service.toggleCollectionEnabled('c1')).toBe(false); + + expect(saved.enabledCollections).toEqual([]); + expect(loaded).toEqual([]); + expect(mockServerApi.stop).not.toHaveBeenCalled(); + expect(await service.shouldUseMockServer('c1')).toEqual({ shouldUseMock: false, mockBaseUrl: null }); + }); + + test('rapid toggles wait for the preceding reload and preserve the final intent', async () => { + let release; + const gate = new Promise(resolve => { release = resolve; }); + let reloadCount = 0; + reload = async (_settings, snapshots) => { + if (++reloadCount === 1) { await gate; } + loaded = snapshots.map(collection => collection.id); + return { success: true }; + }; + const enable = service.toggleCollectionEnabled('c2'); + await tick(); + const disable = service.toggleCollectionEnabled('c2'); + await tick(); + const pendingSaved = clone(saved); + release(); + await expect(Promise.all([enable, disable])).resolves.toEqual([true, false]); + + expect(pendingSaved.enabledCollections).toEqual(['c1', 'c2']); + expect(saved.enabledCollections).toEqual(['c1']); + expect(loaded).toEqual(['c1']); + expect(reloadCount).toBe(2); + }); + + test.each(['transport', 'rejected', 'stopped'])('a %s reload failure restores saved settings and keeps old routing', async kind => { + reload = async () => { + if (kind === 'transport') { throw new Error('reload failed'); } + return { success: false, message: kind === 'stopped' ? 'Server is not running' : 'reload failed' }; + }; + + await expect(service.toggleCollectionEnabled('c2')).rejects.toThrow(); + + expect(saved.enabledCollections).toEqual(['c1']); + expect(loaded).toEqual(['c1']); + expect(await service.shouldUseMockServer('c2')).toEqual({ shouldUseMock: false, mockBaseUrl: null }); + expect(statusDisplay.update).toHaveBeenCalledWith(expect.stringContaining('Error toggling collection:'), null); + }); + + test('a failed reload does not prevent a subsequent toggle', async () => { + mockServerApi.reloadSettings.mockRejectedValueOnce(new Error('temporary failure')); + await expect(service.toggleCollectionEnabled('c2')).rejects.toThrow('temporary failure'); + + await expect(service.toggleCollectionEnabled('c2')).resolves.toBe(true); + expect(saved.enabledCollections).toEqual(['c1', 'c2']); + expect(loaded).toEqual(['c1', 'c2']); + }); + }); + describe('validators', () => { test('validatePort', () => { expect(service.validatePort('abc')).toEqual(['Port must be a number']); diff --git a/tests/services/WorkspaceTabEndpointLoaderProtocols.test.js b/tests/services/WorkspaceTabEndpointLoaderProtocols.test.js index 95e2525f..d74ca601 100644 --- a/tests/services/WorkspaceTabEndpointLoaderProtocols.test.js +++ b/tests/services/WorkspaceTabEndpointLoaderProtocols.test.js @@ -26,6 +26,13 @@ describe('WorkspaceTabEndpointLoaderService protocol dispatch', () => { }); }); + test('replacing a request clears its response and inspection state', () => { + const update = loader.createTabUpdate({ id: 'new', collectionId: 'c', path: '/new' }); + expect(update.response).toBeNull(); + expect(update.responseInspection).toBeNull(); + expect(loader.createHistoryTabUpdate({ request: { url: 'https://example.test' } }).response).toBeNull(); + }); + describe('SSE', () => { const sseEndpoint = { id: 'e1', diff --git a/tests/storage/WorkspaceTabRepository.test.js b/tests/storage/WorkspaceTabRepository.test.js index 98f3ca38..49b256e6 100644 --- a/tests/storage/WorkspaceTabRepository.test.js +++ b/tests/storage/WorkspaceTabRepository.test.js @@ -15,6 +15,24 @@ describe('WorkspaceTabRepository', () => { repository = new WorkspaceTabRepository(mockBackendAPI); }); + test('explicit null detaches an endpoint while omitted fields preserve it', async () => { + mockBackendAPI.store.get.mockResolvedValue([{ id: 't', endpoint: { collectionId: 'c', endpointId: 'e' } }]); + expect((await repository.updateTab('t', { name: 'renamed' })).endpoint.endpointId).toBe('e'); + expect((await repository.updateTab('t', { endpoint: null })).endpoint).toBeNull(); + }); + + test('detaching a collection preserves request contents and other bindings', async () => { + mockBackendAPI.store.get.mockResolvedValue([ + { id: 'a', request: { url: 'https://a' }, endpoint: { collectionId: 'c', endpointId: 'e' } }, + { id: 'b', endpoint: { collectionId: 'other', endpointId: 'e' } } + ]); + await repository.detachCollection('c'); + const tabs = await repository.getTabs(); + expect(tabs[0].endpoint).toBeNull(); + expect(tabs[0].request.url).toBe('https://a'); + expect(tabs[1].endpoint.collectionId).toBe('other'); + }); + describe('getTabs', () => { test('should return tabs from storage', async () => { const tabs = [ diff --git a/tests/ui/EnvironmentManager.test.js b/tests/ui/EnvironmentManager.test.js index 0b0ab743..e48379a7 100644 --- a/tests/ui/EnvironmentManager.test.js +++ b/tests/ui/EnvironmentManager.test.js @@ -66,6 +66,22 @@ describe('EnvironmentManager', () => { expect(escapeHandlerCount()).toBe(0); }); + test('a rename finishing after selection changes stays in the original environment', async () => { + const { manager } = await openManager(service); + let release; + service.deleteVariable.mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); + const input = document.querySelector('.var-name-input'); + input.value = 'renamed'; + input.dispatchEvent(new window.Event('blur')); + await flush(); + manager.selectEnvironment('prod'); + release(); + await flush(); + manager.close(); + expect(service.setVariable).toHaveBeenCalledWith('dev', 'renamed', 'dev.example', false); + expect(service.setVariable.mock.calls.some(call => call[0] === 'prod')).toBe(false); + }); + test('renders the environment list with the active badge and selects the active one', async () => { const { manager } = await openManager(service); diff --git a/tests/workspaceTabResponseRestore.test.js b/tests/workspaceTabResponseRestore.test.js index c7f77c8a..c9123418 100644 --- a/tests/workspaceTabResponseRestore.test.js +++ b/tests/workspaceTabResponseRestore.test.js @@ -46,6 +46,15 @@ function responseOf(data) { } describe('_restoreResponse', () => { + test('clearing a replaced response drops its binary download metadata', async () => { + const { manager } = await loadHarness(); + const { setResponseMeta, getResponseMeta } = await import('../src/modules/responseSaver.js'); + setResponseMeta('tab-1', { isBinary: true, base64: 'b2xk', suggestedName: 'old.bin' }); + await manager._restoreResponseState({ id: 'tab-1', request: { protocol: 'http' }, response: null }); + expect(getResponseMeta('tab-1').isBinary).toBe(false); + expect(getResponseMeta('tab-1').base64).toBeNull(); + }); + test.each(['websocket', 'sse'])('%s response Clear remains available after restoring a disconnected tab', async protocol => { const { manager, container } = await loadHarness(); container.clearBtn.classList.add('is-hidden');