Skip to content

Commit 7867fcb

Browse files
fastrevmd-labclaude
andcommitted
fix(changeset): keep a pending-confirm refusal typed through apply staging
The coordinator stringifies stage errors and apply_change_set_with_cancel rebuilt only PlaneManagedConfig, so the change-set path's new CommitConfirmedActive surfaced as Validation and was audited as invalid_input. The plane_refusal side channel becomes stage_refusal and carries both refusals; the e2e tests now pin the audit error_kind for commit_check_config and apply_junos_change_set. (#632) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7d30973 commit 7867fcb

3 files changed

Lines changed: 123 additions & 43 deletions

File tree

‎rust-junosmcp-core/src/junos_transaction.rs‎

Lines changed: 65 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -264,10 +264,23 @@ pub struct JunosTransaction {
264264
allow_plane_owned_writes: bool,
265265
/// Plane-guard warning recorded by `stage()` when the flag let a write through.
266266
plane_warning: std::sync::Mutex<Option<String>>,
267-
/// Plane-guard refusal from `stage()` as `(tool, device, authority, detail)`,
268-
/// kept because the coordinator stringifies stage errors and the caller
269-
/// needs the typed `PlaneManagedConfig` back for its audit kind and code.
270-
plane_refusal: std::sync::Mutex<Option<(&'static str, String, String, String)>>,
267+
/// Typed refusal from `stage()`, kept because the coordinator stringifies
268+
/// stage errors and the caller needs the typed error back for its audit
269+
/// kind and code.
270+
stage_refusal: std::sync::Mutex<Option<StageRefusal>>,
271+
}
272+
273+
/// A `stage()` refusal that must survive the coordinator's stringification.
274+
enum StageRefusal {
275+
/// Plane-guard refusal, the fields of `JmcpError::PlaneManagedConfig`.
276+
Plane {
277+
tool: &'static str,
278+
device: String,
279+
authority: String,
280+
detail: String,
281+
},
282+
/// A commit confirmed is pending on the device (#632).
283+
CommitConfirmedActive { router: String },
271284
}
272285

273286
impl JunosTransaction {
@@ -279,7 +292,7 @@ impl JunosTransaction {
279292
locked_session: tokio::sync::Mutex::new(None),
280293
allow_plane_owned_writes: false,
281294
plane_warning: std::sync::Mutex::new(None),
282-
plane_refusal: std::sync::Mutex::new(None),
295+
stage_refusal: std::sync::Mutex::new(None),
283296
}
284297
}
285298

@@ -306,38 +319,56 @@ impl JunosTransaction {
306319
.unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(warning);
307320
}
308321

309-
/// The plane-guard refusal `stage()` returned, rebuilt as the typed error.
310-
pub fn take_plane_refusal(&self) -> Option<JmcpError> {
311-
let (tool, device, authority, detail) = self
312-
.plane_refusal
322+
/// The refusal `stage()` returned, rebuilt as the typed error.
323+
pub fn take_stage_refusal(&self) -> Option<JmcpError> {
324+
let refusal = self
325+
.stage_refusal
313326
.lock()
314327
.unwrap_or_else(|poisoned| poisoned.into_inner())
315328
.take()?;
316-
Some(JmcpError::PlaneManagedConfig {
317-
tool,
318-
device,
319-
authority,
320-
detail,
329+
Some(match refusal {
330+
StageRefusal::Plane {
331+
tool,
332+
device,
333+
authority,
334+
detail,
335+
} => JmcpError::PlaneManagedConfig {
336+
tool,
337+
device,
338+
authority,
339+
detail,
340+
},
341+
StageRefusal::CommitConfirmedActive { router } => {
342+
JmcpError::CommitConfirmedActive { router }
343+
}
321344
})
322345
}
323346

324-
/// Remember `error` if it is a plane refusal. A `CandidateCleanupFailed`
325-
/// wrapping one is not recorded: the cleanup failure must stay visible.
326-
fn record_plane_refusal(&self, error: &JmcpError) {
327-
let JmcpError::PlaneManagedConfig {
328-
tool,
329-
device,
330-
authority,
331-
detail,
332-
} = error
333-
else {
334-
return;
347+
/// Remember `error` if it is a plane or pending-commit refusal. A
348+
/// `CandidateCleanupFailed` wrapping one is not recorded: the cleanup
349+
/// failure must stay visible.
350+
fn record_stage_refusal(&self, error: &JmcpError) {
351+
let refusal = match error {
352+
JmcpError::PlaneManagedConfig {
353+
tool,
354+
device,
355+
authority,
356+
detail,
357+
} => StageRefusal::Plane {
358+
tool,
359+
device: device.clone(),
360+
authority: authority.clone(),
361+
detail: detail.clone(),
362+
},
363+
JmcpError::CommitConfirmedActive { router } => StageRefusal::CommitConfirmedActive {
364+
router: router.clone(),
365+
},
366+
_ => return,
335367
};
336368
*self
337-
.plane_refusal
369+
.stage_refusal
338370
.lock()
339-
.unwrap_or_else(|poisoned| poisoned.into_inner()) =
340-
Some((tool, device.clone(), authority.clone(), detail.clone()));
371+
.unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(refusal);
341372
}
342373

343374
/// Revert anything loaded into the candidate and release the lock, then
@@ -653,7 +684,7 @@ impl DeviceTransaction for JunosTransaction {
653684
let error = self
654685
.revert_and_release(&mut dev, 0, refusal, "plane-owned refusal")
655686
.await;
656-
self.record_plane_refusal(&error);
687+
self.record_stage_refusal(&error);
657688
return Err(error);
658689
}
659690
}
@@ -671,9 +702,11 @@ impl DeviceTransaction for JunosTransaction {
671702
Ok(_) => None,
672703
};
673704
if let Some(error) = pending_error {
674-
return Err(self
705+
let error = self
675706
.revert_and_release(&mut dev, 0, error, "pending commit confirmed")
676-
.await);
707+
.await;
708+
self.record_stage_refusal(&error);
709+
return Err(error);
677710
}
678711

679712
let mut cfg = dev.config()?;
@@ -833,7 +866,7 @@ impl DeviceTransaction for JunosTransaction {
833866
let error = self
834867
.revert_and_release(&mut dev, actions.len(), refusal, "plane-owned refusal")
835868
.await;
836-
self.record_plane_refusal(&error);
869+
self.record_stage_refusal(&error);
837870
return Err(error);
838871
}
839872
}

‎rust-junosmcp-core/src/tools/changeset.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1215,12 +1215,12 @@ pub async fn apply_change_set_with_cancel(
12151215
&ct,
12161216
)
12171217
.await
1218-
// The coordinator stringifies stage errors; a plane refusal goes back typed
1219-
// so it is audited as `blocked` with the `unauthorized` code. Only the
1220-
// stage wrapper carries it: a bookkeeping failure must stay visible.
1218+
// The coordinator stringifies stage errors; a plane refusal or a pending
1219+
// commit confirmed goes back typed so it keeps its audit kind and code.
1220+
// Only the stage wrapper carries it: a bookkeeping failure must stay visible.
12211221
.map_err(|e| {
12221222
is_stage_failure(&e)
1223-
.then(|| transaction.take_plane_refusal())
1223+
.then(|| transaction.take_stage_refusal())
12241224
.flatten()
12251225
.unwrap_or_else(|| JmcpError::Validation(e.to_string()))
12261226
})?;

‎rust-junosmcp/tests/plane_guard_e2e.rs‎

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -889,45 +889,92 @@ fn pending_script(script: Script) -> Script {
889889
entries
890890
}
891891

892+
/// The audit record `tool` wrote to `audit_log` that carries an error kind,
893+
/// once it appears (a change-set apply also writes an `ok` preflight record).
894+
fn audit_fields(audit_log: &std::path::Path, tool: &str) -> Value {
895+
let deadline = Instant::now() + Duration::from_secs(5);
896+
loop {
897+
let contents = std::fs::read_to_string(audit_log).unwrap_or_default();
898+
let record = contents
899+
.lines()
900+
.map(|line| serde_json::from_str::<Value>(line).unwrap())
901+
.find(|record| {
902+
record["fields"]["tool"] == tool && record["fields"]["error_kind"] != ""
903+
});
904+
if let Some(record) = record {
905+
return record["fields"].clone();
906+
}
907+
assert!(Instant::now() < deadline, "no audit record: {contents}");
908+
std::thread::sleep(Duration::from_millis(20));
909+
}
910+
}
911+
912+
/// Tool error `code` for a `commit_confirmed_active` refusal (the server maps
913+
/// it with the other precondition errors).
914+
const COMMIT_CONFIRMED_ACTIVE_CODE: &str = "invalid_argument";
915+
916+
/// The structured error code of a tool response.
917+
fn error_code(resp: &Value) -> &str {
918+
resp["structuredContent"]["code"].as_str().unwrap_or("")
919+
}
920+
892921
#[test]
893922
fn commit_check_is_refused_while_a_commit_confirmed_is_pending() {
923+
let audit_dir = tempfile::tempdir().unwrap();
924+
let audit_log = audit_dir.path().join("audit.jsonl");
894925
let (fake, mut server, _dir) = start(
895926
pending_script(script(NO_STANZA, INTERFACE_DIFF)),
896927
Some("local"),
897-
&[],
928+
&[
929+
"--audit-log-file",
930+
audit_log.to_str().unwrap(),
931+
"--audit-format",
932+
"json",
933+
],
898934
);
899935
let resp = call_tool(
900936
&mut server,
901937
"commit_check_config",
902938
json!({ "device": "fake", "config_text": "set system host-name x", "config_format": "set" }),
903939
);
904940
assert_eq!(resp.get("isError"), Some(&json!(true)), "{resp}");
905-
assert!(
906-
resp.to_string().contains("commit_confirmed_active"),
907-
"{resp}"
908-
);
941+
assert_eq!(error_code(&resp), COMMIT_CONFIRMED_ACTIVE_CODE, "{resp}");
909942
assert!(fake.saw("show system commit"), "{:?}", fake.requests());
910943
assert!(!fake.saw("<nc:validate"), "{:?}", fake.requests());
911944
assert!(!fake.saw("<nc:commit"), "{:?}", fake.requests());
912945
assert!(!fake.saw("<commit-configuration"), "{:?}", fake.requests());
946+
let fields = audit_fields(&audit_log, "commit_check_config");
947+
assert_eq!(fields["error_kind"], "commit_confirmed_active", "{fields}");
913948
}
914949

915950
#[test]
916951
fn changeset_apply_is_refused_while_a_commit_confirmed_is_pending() {
952+
let audit_dir = tempfile::tempdir().unwrap();
953+
let audit_log = audit_dir.path().join("audit.jsonl");
917954
let rig = start_changeset(
918955
pending_script(changeset_script(NO_STANZA, INTERFACE_DIFF)),
919956
Some("local"),
920-
&[],
957+
&[
958+
"--audit-log-file",
959+
audit_log.to_str().unwrap(),
960+
"--audit-format",
961+
"json",
962+
],
921963
);
922964
let (created, (apply_error, apply_text)) = rig.create_and_apply();
923965
assert!(!created.0, "{created:?}");
924966
assert!(apply_error, "{apply_text}");
967+
// Typed, not stringified into a validation error by the coordinator. The
968+
// HTTP response carries no structured `code` on this path, so the typed
969+
// error's own text is the signal; the audit kind below is the other.
925970
assert!(
926-
apply_text.contains("commit_confirmed_active"),
971+
apply_text.starts_with("active commit-confirmed window [code=commit_confirmed_active]"),
927972
"{apply_text}"
928973
);
929974
let requests = rig.fake.requests();
930975
assert!(!rig.fake.saw("<nc:validate"), "{requests:?}");
931976
assert!(!rig.fake.saw("<nc:commit"), "{requests:?}");
932977
assert!(!rig.fake.saw("<commit-configuration"), "{requests:?}");
978+
let fields = audit_fields(&audit_log, "apply_junos_change_set");
979+
assert_eq!(fields["error_kind"], "commit_confirmed_active", "{fields}");
933980
}

0 commit comments

Comments
 (0)