pgroles-cli 0.5.0-alpha.2

CLI for pgroles — validate, diff, apply, inspect, and generate role policies
Documentation
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! Testable CLI logic for pgroles.
//!
//! All pure functions that don't require a live database connection live here.
//! The binary (`main.rs`) delegates to these, making validation, plan formatting,
//! and output rendering fully unit-testable.

use std::path::Path;

use anyhow::{Context, Result};

use pgroles_core::diff::{self, Change};
use pgroles_core::manifest::{self, ExpandedManifest, PolicyManifest, RoleRetirement};
use pgroles_core::model::RoleGraph;
use pgroles_core::sql;

// ---------------------------------------------------------------------------
// File loading
// ---------------------------------------------------------------------------

/// Read a manifest file from disk and return the raw YAML string.
pub fn read_manifest_file(path: &Path) -> Result<String> {
    std::fs::read_to_string(path)
        .with_context(|| format!("failed to read manifest file: {}", path.display()))
}

// ---------------------------------------------------------------------------
// Validation pipeline (pure — no DB)
// ---------------------------------------------------------------------------

/// Parse and validate a YAML string into a `PolicyManifest`.
pub fn parse(yaml: &str) -> Result<PolicyManifest> {
    manifest::parse_manifest(yaml).map_err(|err| anyhow::anyhow!("{err}"))
}

/// Parse, validate, and expand a manifest YAML string into an `ExpandedManifest`.
pub fn parse_and_expand(yaml: &str) -> Result<ExpandedManifest> {
    let policy_manifest = parse(yaml)?;
    manifest::expand_manifest(&policy_manifest).map_err(|err| anyhow::anyhow!("{err}"))
}

/// Full validation: parse, expand, and build a RoleGraph from a manifest string.
/// Returns the expanded manifest and the desired RoleGraph.
pub fn validate_manifest(yaml: &str) -> Result<ValidatedManifest> {
    let policy_manifest = parse(yaml)?;

    if policy_manifest.roles.is_empty()
        && policy_manifest.schemas.is_empty()
        && policy_manifest.grants.is_empty()
        && policy_manifest.memberships.is_empty()
    {
        tracing::warn!(
            "manifest defines no roles, schemas, grants, or memberships — is the file correct?"
        );
    }

    let expanded =
        manifest::expand_manifest(&policy_manifest).map_err(|err| anyhow::anyhow!("{err}"))?;

    let default_owner = policy_manifest.default_owner.as_deref();
    let desired = RoleGraph::from_expanded(&expanded, default_owner)
        .map_err(|err| anyhow::anyhow!("{err}"))?;

    Ok(ValidatedManifest {
        manifest: policy_manifest,
        expanded,
        desired,
    })
}

/// The result of successfully validating a manifest.
pub struct ValidatedManifest {
    pub manifest: PolicyManifest,
    pub expanded: ExpandedManifest,
    pub desired: RoleGraph,
}

// ---------------------------------------------------------------------------
// Plan computation (pure — given both role graphs)
// ---------------------------------------------------------------------------

/// Compute the list of changes needed to bring `current` state to `desired` state.
pub fn compute_plan(current: &RoleGraph, desired: &RoleGraph) -> Vec<Change> {
    diff::diff(current, desired)
}

/// Collect the role names that the current plan intends to drop.
pub fn planned_role_drops(changes: &[Change]) -> Vec<String> {
    changes
        .iter()
        .filter_map(|change| match change {
            Change::DropRole { name } => Some(name.clone()),
            _ => None,
        })
        .collect()
}

/// Insert explicit retirement actions before any matching role drops.
pub fn apply_role_retirements(changes: Vec<Change>, retirements: &[RoleRetirement]) -> Vec<Change> {
    diff::apply_role_retirements(changes, retirements)
}

/// Resolve password sources from environment variables for roles that declare them.
pub fn resolve_passwords(
    expanded: &ExpandedManifest,
) -> Result<std::collections::BTreeMap<String, String>> {
    diff::resolve_passwords(&expanded.roles).map_err(|err| anyhow::anyhow!("{err}"))
}

/// Inject `SetPassword` changes into a plan for roles with resolved passwords.
pub fn inject_password_changes(
    changes: Vec<Change>,
    resolved_passwords: &std::collections::BTreeMap<String, String>,
) -> Vec<Change> {
    diff::inject_password_changes(changes, resolved_passwords)
}

// ---------------------------------------------------------------------------
// Output formatting
// ---------------------------------------------------------------------------

/// Format a plan as SQL statements.
pub fn format_plan_sql(changes: &[Change]) -> String {
    sql::render_all(changes)
}

/// Format a plan as SQL statements using an explicit SQL context.
pub fn format_plan_sql_with_context(changes: &[Change], ctx: &sql::SqlContext) -> String {
    sql::render_all_with_context(&redacted_changes(changes), ctx)
}

/// Format a plan as JSON for machine consumption.
pub fn format_plan_json(changes: &[Change]) -> Result<String> {
    serde_json::to_string_pretty(&redacted_changes(changes)).map_err(|err| anyhow::anyhow!("{err}"))
}

fn redacted_changes(changes: &[Change]) -> Vec<Change> {
    changes
        .iter()
        .map(|change| match change {
            Change::SetPassword { name, .. } => Change::SetPassword {
                name: name.clone(),
                password: "[REDACTED]".to_string(),
            },
            other => other.clone(),
        })
        .collect()
}

/// Summary statistics for a plan.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct PlanSummary {
    pub roles_created: usize,
    pub roles_altered: usize,
    pub roles_dropped: usize,
    pub comments_changed: usize,
    pub sessions_terminated: usize,
    pub ownerships_reassigned: usize,
    pub owned_objects_dropped: usize,
    pub grants: usize,
    pub revokes: usize,
    pub default_privileges_set: usize,
    pub default_privileges_revoked: usize,
    pub members_added: usize,
    pub members_removed: usize,
    pub passwords_set: usize,
}

impl PlanSummary {
    /// Compute summary statistics from a list of changes.
    pub fn from_changes(changes: &[Change]) -> Self {
        let mut summary = Self::default();
        for change in changes {
            match change {
                Change::CreateRole { .. } => summary.roles_created += 1,
                Change::AlterRole { .. } => summary.roles_altered += 1,
                Change::DropRole { .. } => summary.roles_dropped += 1,
                Change::SetComment { .. } => summary.comments_changed += 1,
                Change::TerminateSessions { .. } => summary.sessions_terminated += 1,
                Change::ReassignOwned { .. } => summary.ownerships_reassigned += 1,
                Change::DropOwned { .. } => summary.owned_objects_dropped += 1,
                Change::Grant { .. } => summary.grants += 1,
                Change::Revoke { .. } => summary.revokes += 1,
                Change::SetDefaultPrivilege { .. } => summary.default_privileges_set += 1,
                Change::RevokeDefaultPrivilege { .. } => summary.default_privileges_revoked += 1,
                Change::AddMember { .. } => summary.members_added += 1,
                Change::RemoveMember { .. } => summary.members_removed += 1,
                Change::SetPassword { .. } => summary.passwords_set += 1,
            }
        }
        summary
    }

    /// Total number of changes in the plan.
    pub fn total(&self) -> usize {
        self.roles_created
            + self.roles_altered
            + self.roles_dropped
            + self.comments_changed
            + self.sessions_terminated
            + self.ownerships_reassigned
            + self.owned_objects_dropped
            + self.grants
            + self.revokes
            + self.default_privileges_set
            + self.default_privileges_revoked
            + self.members_added
            + self.members_removed
            + self.passwords_set
    }

    /// True if the plan has no changes.
    pub fn is_empty(&self) -> bool {
        self.total() == 0
    }

    /// True if the plan has structural drift (excluding password-only changes).
    ///
    /// Password changes always appear in plans because passwords cannot be read
    /// back from PostgreSQL for comparison. This method allows CI gates
    /// (`--exit-code`) to distinguish real drift from password-only changes.
    pub fn has_structural_changes(&self) -> bool {
        self.total() - self.passwords_set > 0
    }

    pub fn format_plan(&self) -> String {
        self.format_with_header("Plan")
    }

    pub fn format_applied(&self) -> String {
        self.format_with_header("Applied")
    }

    fn format_with_header(&self, header: &str) -> String {
        if self.is_empty() {
            return "No changes needed. Database is in sync with manifest.".to_string();
        }

        let mut output = String::new();
        output.push_str(&format!("{header}: {} change(s)\n", self.total()));

        let items: Vec<(&str, usize)> = vec![
            ("role(s) to create", self.roles_created),
            ("role(s) to alter", self.roles_altered),
            ("role(s) to drop", self.roles_dropped),
            ("comment(s) to change", self.comments_changed),
            ("session termination step(s)", self.sessions_terminated),
            ("ownership reassignment(s)", self.ownerships_reassigned),
            ("DROP OWNED cleanup step(s)", self.owned_objects_dropped),
            ("grant(s) to add", self.grants),
            ("grant(s) to revoke", self.revokes),
            ("default privilege(s) to set", self.default_privileges_set),
            (
                "default privilege(s) to revoke",
                self.default_privileges_revoked,
            ),
            ("membership(s) to add", self.members_added),
            ("membership(s) to remove", self.members_removed),
            ("password(s) to set", self.passwords_set),
        ];

        for (label, count) in items {
            if count > 0 {
                output.push_str(&format!("  {count} {label}\n"));
            }
        }

        output
    }
}

impl std::fmt::Display for PlanSummary {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.format_plan())
    }
}

/// Format validation results for human-readable output.
pub fn format_validation_result(validated: &ValidatedManifest) -> String {
    let mut output = String::new();
    output.push_str("Manifest is valid.\n");
    output.push_str(&format!(
        "  {} role(s) defined\n",
        validated.expanded.roles.len()
    ));
    output.push_str(&format!(
        "  {} grant(s) defined\n",
        validated.expanded.grants.len()
    ));
    output.push_str(&format!(
        "  {} default privilege(s) defined\n",
        validated.expanded.default_privileges.len()
    ));
    output.push_str(&format!(
        "  {} membership(s) defined\n",
        validated.expanded.memberships.len()
    ));
    output
}

// ---------------------------------------------------------------------------
// Inspect output formatting
// ---------------------------------------------------------------------------

/// Format a RoleGraph as a human-readable summary.
pub fn format_role_graph_summary(graph: &RoleGraph) -> String {
    let mut output = String::new();
    output.push_str(&format!("Roles: {}\n", graph.roles.len()));
    for (name, state) in &graph.roles {
        let login_marker = if state.login { "LOGIN" } else { "NOLOGIN" };
        output.push_str(&format!("  {name} ({login_marker})\n"));
    }
    output.push_str(&format!("Grants: {}\n", graph.grants.len()));
    output.push_str(&format!(
        "Default privileges: {}\n",
        graph.default_privileges.len()
    ));
    output.push_str(&format!("Memberships: {}\n", graph.memberships.len()));
    for edge in &graph.memberships {
        output.push_str(&format!("  {} -> {}\n", edge.member, edge.role));
    }
    output
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    const MINIMAL_MANIFEST: &str = r#"
default_owner: app_owner

roles:
  - name: analytics
    login: true
    comment: "Analytics read-only role"

grants:
  - role: analytics
    privileges: [CONNECT]
    object: { type: database, name: mydb }
"#;

    const PROFILE_MANIFEST: &str = r#"
default_owner: app_owner

profiles:
  editor:
    grants:
      - privileges: [USAGE]
        object: { type: schema }
      - privileges: [SELECT, INSERT, UPDATE, DELETE]
        object: { type: table, name: "*" }
    default_privileges:
      - privileges: [SELECT, INSERT, UPDATE, DELETE]
        on_type: table
  viewer:
    grants:
      - privileges: [USAGE]
        object: { type: schema }
      - privileges: [SELECT]
        object: { type: table, name: "*" }
    default_privileges:
      - privileges: [SELECT]
        on_type: table

schemas:
  - name: inventory
    profiles: [editor, viewer]
  - name: catalog
    profiles: [viewer]

roles:
  - name: app-service
    login: true

grants:
  - role: app-service
    privileges: [CONNECT]
    object: { type: database, name: mydb }

memberships:
  - role: inventory-editor
    members:
      - name: app-service
"#;

    const INVALID_YAML: &str = r#"
this is: [not: valid yaml: [[
"#;

    const UNDEFINED_PROFILE: &str = r#"
profiles:
  editor:
    grants: []

schemas:
  - name: myschema
    profiles: [nonexistent]
"#;

    // -----------------------------------------------------------------------
    // parse
    // -----------------------------------------------------------------------

    #[test]
    fn parse_valid_manifest() {
        let result = parse(MINIMAL_MANIFEST);
        assert!(result.is_ok());
        let manifest = result.unwrap();
        assert_eq!(manifest.default_owner, Some("app_owner".to_string()));
        assert_eq!(manifest.roles.len(), 1);
        assert_eq!(manifest.roles[0].name, "analytics");
    }

    #[test]
    fn parse_invalid_yaml() {
        let result = parse(INVALID_YAML);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("YAML parse error"), "got: {err_msg}");
    }

    // -----------------------------------------------------------------------
    // parse_and_expand
    // -----------------------------------------------------------------------

    #[test]
    fn expand_profile_manifest() {
        let expanded = parse_and_expand(PROFILE_MANIFEST).unwrap();

        // inventory-editor, inventory-viewer, catalog-viewer, app-service
        assert_eq!(expanded.roles.len(), 4);

        let role_names: Vec<&str> = expanded.roles.iter().map(|r| r.name.as_str()).collect();
        assert!(role_names.contains(&"inventory-editor"));
        assert!(role_names.contains(&"inventory-viewer"));
        assert!(role_names.contains(&"catalog-viewer"));
        assert!(role_names.contains(&"app-service"));
    }

    #[test]
    fn expand_undefined_profile_fails() {
        let result = parse_and_expand(UNDEFINED_PROFILE);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("nonexistent"),
            "expected error about 'nonexistent' profile, got: {err_msg}"
        );
    }

    // -----------------------------------------------------------------------
    // validate_manifest
    // -----------------------------------------------------------------------

    #[test]
    fn validate_builds_role_graph() {
        let validated = validate_manifest(PROFILE_MANIFEST).unwrap();

        // Check the desired graph has the expected roles
        assert_eq!(validated.desired.roles.len(), 4);
        assert!(validated.desired.roles.contains_key("inventory-editor"));
        assert!(validated.desired.roles.contains_key("app-service"));

        // Check grants were expanded
        assert!(!validated.desired.grants.is_empty());

        // Check memberships
        assert!(!validated.desired.memberships.is_empty());
    }

    // -----------------------------------------------------------------------
    // compute_plan + format
    // -----------------------------------------------------------------------

    #[test]
    fn plan_from_empty_creates_roles() {
        let validated = validate_manifest(PROFILE_MANIFEST).unwrap();
        let current = RoleGraph::default(); // empty database

        let changes = compute_plan(&current, &validated.desired);
        assert!(!changes.is_empty());

        let summary = PlanSummary::from_changes(&changes);
        assert_eq!(summary.roles_created, 4); // inventory-editor, inventory-viewer, catalog-viewer, app-service
        assert!(summary.grants > 0);
        assert!(!summary.is_empty());
    }

    #[test]
    fn plan_no_changes_when_in_sync() {
        let validated = validate_manifest(MINIMAL_MANIFEST).unwrap();
        // Simulate a DB that already has the desired state
        let current = validated.desired.clone();

        let changes = compute_plan(&current, &validated.desired);
        let summary = PlanSummary::from_changes(&changes);
        assert!(summary.is_empty());
        assert_eq!(summary.total(), 0);
    }

    #[test]
    fn format_plan_sql_produces_sql() {
        let validated = validate_manifest(MINIMAL_MANIFEST).unwrap();
        let current = RoleGraph::default();
        let changes = compute_plan(&current, &validated.desired);

        let sql_output = format_plan_sql(&changes);
        assert!(
            sql_output.contains("CREATE ROLE"),
            "expected CREATE ROLE in: {sql_output}"
        );
        assert!(
            sql_output.contains("\"analytics\""),
            "expected quoted role name in: {sql_output}"
        );
    }

    #[test]
    fn planned_role_drops_only_returns_drop_changes() {
        let changes = vec![
            Change::CreateRole {
                name: "new-role".to_string(),
                state: pgroles_core::model::RoleState::default(),
            },
            Change::DropRole {
                name: "old-role".to_string(),
            },
            Change::DropRole {
                name: "stale-role".to_string(),
            },
        ];

        assert_eq!(
            planned_role_drops(&changes),
            vec!["old-role".to_string(), "stale-role".to_string()]
        );
    }

    #[test]
    fn apply_role_retirements_updates_plan_summary() {
        let changes = apply_role_retirements(
            vec![Change::DropRole {
                name: "legacy-app".to_string(),
            }],
            &[pgroles_core::manifest::RoleRetirement {
                role: "legacy-app".to_string(),
                reassign_owned_to: Some("app-owner".to_string()),
                drop_owned: true,
                terminate_sessions: true,
            }],
        );

        let summary = PlanSummary::from_changes(&changes);
        assert_eq!(summary.roles_dropped, 1);
        assert_eq!(summary.sessions_terminated, 1);
        assert_eq!(summary.ownerships_reassigned, 1);
        assert_eq!(summary.owned_objects_dropped, 1);
        assert_eq!(summary.total(), 4);
    }

    // -----------------------------------------------------------------------
    // PlanSummary display
    // -----------------------------------------------------------------------

    #[test]
    fn plan_summary_display_empty() {
        let summary = PlanSummary::default();
        let display = summary.to_string();
        assert!(display.contains("No changes needed"));
    }

    #[test]
    fn plan_summary_display_with_changes() {
        let summary = PlanSummary {
            roles_created: 2,
            grants: 5,
            members_added: 1,
            ..Default::default()
        };
        let display = summary.to_string();
        assert!(display.contains("8 change(s)"), "got: {display}");
        assert!(display.contains("2 role(s) to create"), "got: {display}");
        assert!(display.contains("5 grant(s) to add"), "got: {display}");
        assert!(display.contains("1 membership(s) to add"), "got: {display}");
        // Should not mention zero-count items
        assert!(!display.contains("to drop"), "got: {display}");
        assert!(!display.contains("to revoke"), "got: {display}");
    }

    // -----------------------------------------------------------------------
    // format_validation_result
    // -----------------------------------------------------------------------

    #[test]
    fn validation_result_shows_counts() {
        let validated = validate_manifest(PROFILE_MANIFEST).unwrap();
        let output = format_validation_result(&validated);
        assert!(output.contains("Manifest is valid"), "got: {output}");
        assert!(output.contains("4 role(s)"), "got: {output}");
    }

    // -----------------------------------------------------------------------
    // read_manifest_file
    // -----------------------------------------------------------------------

    #[test]
    fn read_nonexistent_file_fails() {
        let result = read_manifest_file(Path::new("/tmp/nonexistent-pgroles-test.yaml"));
        assert!(result.is_err());
        let err_msg = format!("{:#}", result.unwrap_err());
        assert!(
            err_msg.contains("failed to read manifest file"),
            "got: {err_msg}"
        );
    }

    // -----------------------------------------------------------------------
    // format_role_graph_summary
    // -----------------------------------------------------------------------

    #[test]
    fn role_graph_summary_format() {
        let validated = validate_manifest(MINIMAL_MANIFEST).unwrap();
        let summary = format_role_graph_summary(&validated.desired);
        assert!(summary.contains("Roles: 1"), "got: {summary}");
        assert!(summary.contains("analytics (LOGIN)"), "got: {summary}");
    }

    // -----------------------------------------------------------------------
    // has_structural_changes — password-only drift detection
    // -----------------------------------------------------------------------

    #[test]
    fn has_structural_changes_true_for_non_password_changes() {
        let summary = PlanSummary {
            roles_created: 1,
            grants: 2,
            ..Default::default()
        };
        assert!(summary.has_structural_changes());
    }

    #[test]
    fn has_structural_changes_false_for_password_only() {
        let summary = PlanSummary {
            passwords_set: 3,
            ..Default::default()
        };
        assert!(
            !summary.has_structural_changes(),
            "password-only plan should NOT be considered structural drift"
        );
    }

    #[test]
    fn has_structural_changes_true_for_mixed() {
        let summary = PlanSummary {
            roles_created: 1,
            passwords_set: 2,
            ..Default::default()
        };
        assert!(
            summary.has_structural_changes(),
            "mixed plan with structural + password changes IS structural drift"
        );
    }

    #[test]
    fn has_structural_changes_false_for_empty() {
        let summary = PlanSummary::default();
        assert!(!summary.has_structural_changes());
    }

    #[test]
    fn plan_summary_displays_password_count() {
        let summary = PlanSummary {
            passwords_set: 2,
            roles_created: 1,
            ..Default::default()
        };
        let display = summary.to_string();
        assert!(display.contains("2 password(s) to set"), "got: {display}");
        assert!(display.contains("3 change(s)"), "got: {display}");
    }

    // -----------------------------------------------------------------------
    // ReconciliationMode integration through compute_plan + filter
    // -----------------------------------------------------------------------

    #[test]
    fn additive_mode_filters_revokes_from_plan() {
        use pgroles_core::diff::{ReconciliationMode, filter_changes};
        use pgroles_core::model::RoleState;

        let validated = validate_manifest(PROFILE_MANIFEST).unwrap();

        let mut current = validated.desired.clone();
        current
            .roles
            .insert("stale-role".to_string(), RoleState::default());

        let changes = compute_plan(&current, &validated.desired);
        assert!(changes.iter().any(|c| matches!(
            c,
            pgroles_core::diff::Change::DropRole { name } if name == "stale-role"
        )));

        let filtered = filter_changes(changes, ReconciliationMode::Additive);
        assert!(
            !filtered
                .iter()
                .any(|c| matches!(c, pgroles_core::diff::Change::DropRole { .. })),
            "additive mode should filter out DropRole"
        );
    }

    #[test]
    fn adopt_mode_filters_drops_but_keeps_revokes() {
        use pgroles_core::diff::{ReconciliationMode, filter_changes};
        use pgroles_core::manifest::{ObjectType, Privilege};
        use pgroles_core::model::{GrantKey, GrantState, RoleState};
        use std::collections::BTreeSet;

        let validated = validate_manifest(MINIMAL_MANIFEST).unwrap();

        let mut current = validated.desired.clone();
        current
            .roles
            .insert("stale-role".to_string(), RoleState::default());
        current.grants.insert(
            GrantKey {
                role: "analytics".to_string(),
                object_type: ObjectType::Table,
                schema: Some("public".to_string()),
                name: Some("*".to_string()),
            },
            GrantState {
                privileges: BTreeSet::from([Privilege::Select]),
            },
        );

        let changes = compute_plan(&current, &validated.desired);

        let filtered = filter_changes(changes, ReconciliationMode::Adopt);
        assert!(
            !filtered
                .iter()
                .any(|c| matches!(c, pgroles_core::diff::Change::DropRole { .. })),
            "adopt mode should filter out DropRole"
        );
        assert!(
            filtered
                .iter()
                .any(|c| matches!(c, pgroles_core::diff::Change::Revoke { .. })),
            "adopt mode should keep Revoke changes"
        );
    }
    // -----------------------------------------------------------------------
    // format_plan_json
    // -----------------------------------------------------------------------

    #[test]
    fn plan_json_produces_valid_json() {
        let validated = validate_manifest(MINIMAL_MANIFEST).unwrap();
        let current = RoleGraph::default();
        let changes = compute_plan(&current, &validated.desired);

        let json_output = format_plan_json(&changes).unwrap();
        // Should be parseable JSON
        let parsed: serde_json::Value = serde_json::from_str(&json_output).unwrap();
        assert!(parsed.is_array());
        // Should contain CreateRole
        let text = json_output.to_string();
        assert!(text.contains("CreateRole"), "got: {text}");
        assert!(text.contains("analytics"), "got: {text}");
    }

    #[test]
    fn format_plan_json_redacts_passwords() {
        let changes = vec![Change::SetPassword {
            name: "app-svc".to_string(),
            password: "super-secret".to_string(),
        }];

        let json = format_plan_json(&changes).expect("json formatting should succeed");
        assert!(json.contains("[REDACTED]"), "got: {json}");
        assert!(!json.contains("super-secret"), "got: {json}");
    }

    #[test]
    fn format_plan_sql_redacts_passwords() {
        let changes = vec![Change::SetPassword {
            name: "app-svc".to_string(),
            password: "super-secret".to_string(),
        }];

        let sql = format_plan_sql_with_context(&changes, &sql::SqlContext::default());
        assert!(sql.contains("[REDACTED]"), "got: {sql}");
        assert!(!sql.contains("super-secret"), "got: {sql}");
    }

    #[test]
    fn format_applied_uses_applied_header() {
        let summary = PlanSummary {
            roles_created: 1,
            grants: 2,
            ..Default::default()
        };

        let display = summary.format_applied();
        assert!(
            display.starts_with("Applied: 3 change(s)\n"),
            "got: {display}"
        );
        assert!(display.contains("1 role(s) to create"), "got: {display}");
        assert!(display.contains("2 grant(s) to add"), "got: {display}");
        assert!(!display.contains("Plan:"), "got: {display}");
    }
}