Repository navigation
Expand file tree
/
Copy pathload_commit.rs
More file actions
468 lines (448 loc) · 17 KB
/
Copy pathload_commit.rs
File metadata and controls
468 lines (448 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! `load_and_commit_config` — lock candidate, load, diff, commit (with comment),
//! unlock. Rollback on commit failure. Returns `{success, diff, error?}`.
use crate::device_manager::DeviceManager;
use crate::error::JmcpError;
use crate::helpers::{
ConfirmDecision, build_config_payload, confirm_timeout_to_secs, excerpt, parse_load_mode,
refuse_override_outside_changeset, resolve_confirm_timeout, resolve_load_action,
rollback_deadline_unix, validate_input_length,
};
use crate::policy::{BlocklistDomain, Decision, Policy};
use crate::tools::LoadCommitArgs;
use crate::tools::candidate_transaction::{self, CandidateMode, CandidateRequest, CandidateResult};
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
use tokio_util::sync::CancellationToken;
/// Load configuration and commit it to the device.
///
/// Locks the candidate, loads the provided config (validating format and checking
/// policy), diffs, and commits with the provided comment. Supports confirmed-commit
/// with auto-rollback. Rolls back the candidate on commit failure. Returns
/// `{success, diff, error?, confirmed?, rollback_in_minutes?}`.
pub async fn handle(
args: LoadCommitArgs,
dm: Arc<DeviceManager>,
policy: Arc<Policy>,
allow_plane_owned_writes: bool,
) -> Result<Value, JmcpError> {
handle_with_cancel(
args,
dm,
policy,
allow_plane_owned_writes,
CancellationToken::new(),
)
.await
}
/// Cancellable variant of `handle` for use in transport shutdown paths.
pub async fn handle_with_cancel(
args: LoadCommitArgs,
dm: Arc<DeviceManager>,
policy: Arc<Policy>,
allow_plane_owned_writes: bool,
ct: CancellationToken,
) -> Result<Value, JmcpError> {
validate_input_length("config_text", &args.config_text)?;
// Confirm the router exists before consulting the policy. Plane
// ownership is checked inside the candidate transaction.
let _ = dm.inventory().get(&args.device)?;
// The format gate is part of the policy check; downstream
// build_config_payload still validates the value separately.
match policy.check_config(&args.device, &args.config_format, &args.config_text)? {
Decision::Allow => {}
Decision::Deny {
rule,
source,
line_number,
} => {
let pattern = rule.pattern.clone();
let source_str = source.as_str();
let denied_excerpt = excerpt(&args.config_text);
tracing::warn!(
tool = "load_and_commit_config",
router = %args.device,
matched_rule = %pattern,
rule_source = %source_str,
line_number = ?line_number,
input_excerpt = %denied_excerpt,
"blocklist denied request",
);
return Err(JmcpError::Denied {
tool: "load_and_commit_config",
router: args.device.clone(),
pattern,
rule_source: source,
domain: BlocklistDomain::Config,
input_excerpt: denied_excerpt.into(),
line_number,
});
}
Decision::DenyAllowlist { .. } => {
return Err(JmcpError::ConfigDomainAllowlistInvariant {
tool: "load_and_commit_config",
router: args.device.clone(),
});
}
}
// `mode` is validated and gated before any payload is built or RPC is
// sent: `override` is the highest blast-radius operation this server
// exposes, and this tool commits directly with no second-principal
// review, so it is refused outright rather than forwarded to the device.
let load_mode = parse_load_mode(Some(&args.mode))?;
refuse_override_outside_changeset("load_and_commit_config", load_mode)?;
let load_action = resolve_load_action(&args.config_format, load_mode)?;
let payload = build_config_payload(args.config_text, Some(&args.config_format))?;
let timeout_dur = Duration::from_secs(args.timeout);
// Commit-confirmed by default (MEC-45): a bad load that cuts management
// access reverts itself unless the caller explicitly opts out with
// `confirm_timeout_mins: 0`.
let (mode, confirmed) = match resolve_confirm_timeout(args.confirm_timeout_mins) {
ConfirmDecision::Confirmed(mins) => {
let secs = confirm_timeout_to_secs(mins)?;
(CandidateMode::CommitConfirmed(secs), Some(mins))
}
ConfirmDecision::OptedOut => (
CandidateMode::CommitWithComment(args.commit_comment.clone()),
None,
),
};
let (result, authority_warning) = candidate_transaction::run(
&dm,
&args.device,
CandidateRequest {
payload: Some(payload),
rollback_source: None,
mode,
load_action,
tool: "load_and_commit_config",
allow_plane_owned_writes,
},
timeout_dur,
&ct,
)
.await?;
match result {
CandidateResult::Committed { diff } => {
let mut obj = json!({ "success": true, "diff": diff });
if let Some(mins) = confirmed {
obj["confirmed"] = json!(true);
obj["rollback_in_minutes"] = json!(mins);
obj["rollback_deadline_unix"] = json!(rollback_deadline_unix(mins));
obj["message"] = json!(format!(
"Commit confirmed: auto-rollback in {} minutes unless confirmed. \
Send another commit to confirm with confirm_commit.",
mins
));
if !args.commit_comment.is_empty() {
obj["note"] = json!(
"commit_comment is not applied during confirmed commits \
(rustez API limitation)"
);
}
}
if let Some(warning) = authority_warning {
obj["warning"] = json!(warning);
}
Ok(obj)
}
CandidateResult::CommitFailed { diff, error } => {
let mut obj = json!({ "success": false, "diff": diff, "error": error });
if let Some(warning) = authority_warning {
obj["warning"] = json!(warning);
}
Ok(obj)
}
_ => unreachable!("load/commit transaction returned the wrong result kind"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::inventory::Inventory;
use crate::policy::Policy;
use std::io::Write;
fn inv_with(json: &str) -> Arc<Inventory> {
let mut f = tempfile::NamedTempFile::new().unwrap();
f.write_all(json.as_bytes()).unwrap();
Arc::new(Inventory::load(f.path()).unwrap())
}
#[tokio::test]
async fn unknown_router_propagates_error() {
let inv = inv_with(
r#"{"r1":{"ip":"127.0.0.1","username":"u","auth":{"type":"password","password":"x"}}}"#,
);
let dm = Arc::new(DeviceManager::new(inv.clone()));
let pol = Arc::new(Policy::build(&inv).unwrap());
let r = handle(
LoadCommitArgs {
device: "nope".into(),
config_text: "set system foo".into(),
config_format: "set".into(),
mode: "merge".into(),
commit_comment: "test".into(),
confirm_timeout_mins: None,
timeout: 5,
},
dm,
pol,
false,
)
.await;
assert!(matches!(r, Err(JmcpError::UnknownRouter(_))));
}
#[tokio::test]
async fn invalid_format_rejected_before_connect() {
let inv = inv_with(
r#"{"r1":{"ip":"127.0.0.1","username":"u","auth":{"type":"password","password":"x"}}}"#,
);
let dm = Arc::new(DeviceManager::new(inv.clone()));
let pol = Arc::new(Policy::build(&inv).unwrap());
let r = handle(
LoadCommitArgs {
device: "r1".into(),
config_text: "x".into(),
config_format: "yaml".into(),
mode: "merge".into(),
commit_comment: "test".into(),
confirm_timeout_mins: None,
timeout: 5,
},
dm,
pol,
false,
)
.await;
assert!(matches!(r, Err(JmcpError::BadFormat(ref s)) if s == "yaml"));
}
#[tokio::test]
async fn non_set_format_with_rules_present_returns_format_error() {
let inv = inv_with(
r#"{
"_blocklist_defaults":{"config":[{"action":"deny","pattern":"delete *"}]},
"r1":{"ip":"203.0.113.1","port":1,"username":"u","auth":{"type":"password","password":"x"}}
}"#,
);
let dm = Arc::new(DeviceManager::new(inv.clone()));
let pol = Arc::new(Policy::build(&inv).unwrap());
let r = handle(
LoadCommitArgs {
device: "r1".into(),
config_text: "<x/>".into(),
config_format: "xml".into(),
mode: "merge".into(),
commit_comment: "test".into(),
confirm_timeout_mins: None,
timeout: 5,
},
dm,
pol,
false,
)
.await;
match r {
Err(JmcpError::ConfigFormatNotAllowedWithRules { format }) => {
assert_eq!(format, "xml");
}
other => panic!("expected ConfigFormatNotAllowedWithRules, got {other:?}"),
}
}
#[tokio::test]
async fn denied_payload_short_circuits_before_connect() {
let inv = inv_with(
r#"{
"_blocklist_defaults":{"config":[{"action":"deny","pattern":"delete *"}]},
"r1":{"ip":"203.0.113.1","port":1,"username":"u","auth":{"type":"password","password":"x"}}
}"#,
);
let dm = Arc::new(DeviceManager::new(inv.clone()));
let pol = Arc::new(Policy::build(&inv).unwrap());
let r = handle(
LoadCommitArgs {
device: "r1".into(),
config_text: "set foo\ndelete protocols bgp".into(),
config_format: "set".into(),
mode: "merge".into(),
commit_comment: "test".into(),
confirm_timeout_mins: None,
timeout: 5,
},
dm,
pol,
false,
)
.await;
match r {
Err(JmcpError::Denied {
tool,
line_number,
pattern,
..
}) => {
assert_eq!(tool, "load_and_commit_config");
assert_eq!(line_number, Some(2));
assert_eq!(pattern, "delete *");
}
other => panic!("expected Denied, got {other:?}"),
}
}
/// `override` is the highest blast-radius operation this server exposes.
/// `load_and_commit_config` commits in the same call with no
/// second-principal review, so it must refuse `override` outright —
/// before any device connection, exactly like the format/blocklist
/// gates above.
#[tokio::test]
async fn override_mode_is_refused_without_a_change_set() {
let inv = inv_with(
r#"{"r1":{"ip":"127.0.0.1","username":"u","auth":{"type":"password","password":"x"}}}"#,
);
let dm = Arc::new(DeviceManager::new(inv.clone()));
let pol = Arc::new(Policy::build(&inv).unwrap());
let r = handle(
LoadCommitArgs {
device: "r1".into(),
config_text: "system { host-name test; }".into(),
config_format: "text".into(),
mode: "override".into(),
commit_comment: "test".into(),
confirm_timeout_mins: None,
timeout: 5,
},
dm,
pol,
false,
)
.await;
match r {
Err(JmcpError::OverrideRequiresChangeSet { tool }) => {
assert_eq!(tool, "load_and_commit_config");
}
other => panic!("expected OverrideRequiresChangeSet, got {other:?}"),
}
}
#[tokio::test]
async fn replace_mode_is_accepted_unlike_override() {
// `replace` is not gated the way `override` is: it does not reach
// OverrideRequiresChangeSet. It fails later trying to reach the
// device (a non-routable address on a closed port), proving the
// gate did not fire for `replace`.
let inv = inv_with(
r#"{"r1":{"ip":"203.0.113.1","port":1,"username":"u","auth":{"type":"password","password":"x"}}}"#,
);
let dm = Arc::new(DeviceManager::new(inv.clone()));
let pol = Arc::new(Policy::build(&inv).unwrap());
let r = handle(
LoadCommitArgs {
device: "r1".into(),
config_text: "system { host-name test; }".into(),
config_format: "text".into(),
mode: "replace".into(),
commit_comment: "test".into(),
confirm_timeout_mins: None,
timeout: 1,
},
dm,
pol,
false,
)
.await;
assert!(!matches!(
r,
Err(JmcpError::OverrideRequiresChangeSet { .. })
));
}
#[tokio::test]
async fn unknown_mode_is_rejected_before_connect() {
let inv = inv_with(
r#"{"r1":{"ip":"127.0.0.1","username":"u","auth":{"type":"password","password":"x"}}}"#,
);
let dm = Arc::new(DeviceManager::new(inv.clone()));
let pol = Arc::new(Policy::build(&inv).unwrap());
let r = handle(
LoadCommitArgs {
device: "r1".into(),
config_text: "set system foo".into(),
config_format: "set".into(),
mode: "wipe".into(),
commit_comment: "test".into(),
confirm_timeout_mins: None,
timeout: 5,
},
dm,
pol,
false,
)
.await;
assert!(matches!(r, Err(JmcpError::BadLoadMode(ref s)) if s == "wipe"));
}
/// Junos has no wire-level `override` action for a `configuration-set`
/// payload. This combination must be rejected before any RPC is sent —
/// and it also happens to be moot, since `override` alone is already
/// refused by `refuse_override_outside_changeset` for this tool; this
/// test pins that the format/mode incompatibility check exists
/// independently (exercised directly for `set`+`override` via
/// `helpers::resolve_load_action` unit tests) and does not silently fall
/// back to `merge`.
#[tokio::test]
async fn set_format_with_override_mode_is_refused() {
let inv = inv_with(
r#"{"r1":{"ip":"127.0.0.1","username":"u","auth":{"type":"password","password":"x"}}}"#,
);
let dm = Arc::new(DeviceManager::new(inv.clone()));
let pol = Arc::new(Policy::build(&inv).unwrap());
let r = handle(
LoadCommitArgs {
device: "r1".into(),
config_text: "set system foo".into(),
config_format: "set".into(),
mode: "override".into(),
commit_comment: "test".into(),
confirm_timeout_mins: None,
timeout: 5,
},
dm,
pol,
false,
)
.await;
// OverrideRequiresChangeSet fires first (tool-level gate), before the
// format/mode compatibility check ever runs.
match r {
Err(JmcpError::OverrideRequiresChangeSet { tool }) => {
assert_eq!(tool, "load_and_commit_config");
}
other => panic!("expected OverrideRequiresChangeSet, got {other:?}"),
}
}
/// Mist devices are read-only: refused before any connection attempt
/// (203.0.113.1:1 would otherwise surface a connect error).
#[tokio::test]
async fn mist_device_is_refused_before_connect() {
let inv = inv_with(
r#"{"r1":{"ip":"203.0.113.1","port":1,"username":"u","auth":{"type":"password","password":"x"},"config_authority":"mist"}}"#,
);
let dm = Arc::new(DeviceManager::new(inv.clone()));
let pol = Arc::new(Policy::build(&inv).unwrap());
let r = handle(
LoadCommitArgs {
device: "r1".into(),
config_text: "set system host-name x".into(),
config_format: "set".into(),
mode: "merge".into(),
commit_comment: "test".into(),
confirm_timeout_mins: None,
timeout: 5,
},
dm,
pol,
false,
)
.await;
match r {
Err(e @ JmcpError::PlaneManagedConfig { .. }) => {
assert_eq!(e.audit_kind(), "blocked");
}
other => panic!("expected PlaneManagedConfig, got {other:?}"),
}
}
}