Repository navigation
Expand file tree
/
Copy pathapi.rs
More file actions
1968 lines (1843 loc) · 65.1 KB
/
Copy pathapi.rs
File metadata and controls
1968 lines (1843 loc) · 65.1 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
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Stable, supported Rust API for safe-migrate.
//!
//! The public API deliberately owns its configuration, baseline, and report
//! types. The analyzer implementation and its mutable schema model remain
//! crate-private implementation details.
//!
//! ```no_run
//! # fn main() -> Result<(), safe_migrate::api::Error> {
//! use safe_migrate::api::{self, Baseline, Config};
//! use std::path::Path;
//!
//! let config = Config::load_from_file(Path::new("safe-migrate.toml"))?;
//! let baseline = Baseline::load_optional(Path::new(".safe-migrate.cache"), &config)?;
//! let outcome = api::analyze(&config, "001.sql", "CREATE TABLE users (id bigint);", &baseline)?;
//! if outcome.should_halt() {
//! eprintln!("{}", outcome.markdown());
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ```compile_fail
//! // Internal state-machine types are intentionally not a downstream API.
//! use safe_migrate::_internal::analysis::state::AnalysisState;
//! ```
//!
//! Analysis outcomes preserve their internal reporting invariants:
//!
//! ```compile_fail
//! # use safe_migrate::api::{self, Baseline, Config};
//! # fn example() -> Result<(), api::Error> {
//! let config = Config::default();
//! let baseline = Baseline::unavailable();
//! let mut outcome = api::analyze(&config, "001.sql", "", &baseline)?;
//! outcome.findings.clear();
//! # Ok(())
//! # }
//! ```
pub(crate) mod config;
pub use config::{Config, RuleConfig};
/// Current schema version emitted by [`AnalysisOutcome::json`].
pub const REPORT_SCHEMA_VERSION: u32 = InternalReporter::JSON_SCHEMA_VERSION;
use crate::_internal::analysis::evidence as internal_evidence;
use crate::_internal::analysis::outcome::AnalysisOutcome as InternalOutcome;
use crate::_internal::analysis::state::{
AnalysisState as InternalAnalysisState, Confidence as InternalConfidence,
};
use crate::_internal::db::cache::{
CACHE_FORMAT_VERSION, CACHE_MAGIC, DbCache as InternalDbCache, DbCacheVersioned,
};
use crate::_internal::db::cache_file::{
MAX_CACHE_DECODE_BYTES, decode_hex_key, is_encrypted_cache_bytes, read_cache_bytes,
unprotect_cache_bytes, unprotect_cache_bytes_with_key,
};
use crate::_internal::engine::engine::SafeMigrateEngine;
use crate::_internal::model::function::RoutineKind;
use crate::_internal::model::relation::RelationKind;
use crate::_internal::report::reporter::{
Reporter as InternalReporter, Verdict as InternalVerdict,
};
use crate::_internal::report::violations::{
ObjectKind as InternalObjectKind, ReportFinding as InternalFinding,
Violation as InternalViolation, ViolationTier as InternalTier,
};
use crate::_internal::rules::registry::{
self, RuleConfigurationField as InternalRuleConfigurationField,
};
use serde::Serialize;
use std::fmt;
use std::io::Read;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
use zeroize::{Zeroize, Zeroizing};
/// Broad category of a supported API failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
/// Configuration could not be read, parsed, or validated.
Configuration,
/// A baseline could not be read, authenticated, decoded, or validated.
Cache,
/// A requested primary rule ID does not exist.
UnknownRule,
/// One or more SQL sources could not be analyzed.
Analysis,
/// A report could not be rendered or presented.
Report,
/// PostgreSQL metadata synchronization failed.
Sync,
}
/// Error returned by the supported API.
///
/// The stable [`ErrorKind`] supports programmatic handling while [`Self::message`]
/// and [`std::error::Error::source`] retain diagnostic detail.
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
message: String,
source: Option<Box<dyn std::error::Error + Send + Sync>>,
}
impl Error {
fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
source: None,
}
}
fn with_source(
kind: ErrorKind,
message: impl Into<String>,
source: impl std::error::Error + Send + Sync + 'static,
) -> Self {
Self {
kind,
message: message.into(),
source: Some(Box::new(source)),
}
}
fn with_anyhow_source(
kind: ErrorKind,
message: impl Into<String>,
source: anyhow::Error,
) -> Self {
Self {
kind,
message: message.into(),
source: Some(source.into_boxed_dyn_error()),
}
}
fn configuration(message: impl Into<String>) -> Self {
Self::new(ErrorKind::Configuration, message)
}
fn cache(message: impl Into<String>) -> Self {
Self::new(ErrorKind::Cache, message)
}
fn analysis(errors: Vec<String>) -> Self {
Self::new(ErrorKind::Analysis, errors.join("; "))
}
/// Return the stable category of this failure.
pub fn kind(&self) -> ErrorKind {
self.kind
}
/// Return the operation context without its category prefix.
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self {
kind: ErrorKind::Configuration,
message,
..
} => write!(formatter, "invalid configuration: {message}"),
Self {
kind: ErrorKind::Cache,
message,
..
} => write!(formatter, "invalid baseline cache: {message}"),
Self {
kind: ErrorKind::UnknownRule,
message,
..
} => write!(formatter, "unknown primary rule: {message}"),
Self {
kind: ErrorKind::Analysis,
message,
..
} => write!(formatter, "analysis failed: {message}"),
Self {
kind: ErrorKind::Report,
message,
..
} => write!(formatter, "report failed: {message}"),
Self {
kind: ErrorKind::Sync,
message,
..
} => write!(formatter, "baseline sync failed: {message}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source
.as_deref()
.map(|source| source as &(dyn std::error::Error + 'static))
}
}
/// Validated PostgreSQL connection input for embedded synchronization.
///
/// Its debug representation is always redacted. Connections must target
/// localhost or a Unix socket, matching the CLI security boundary.
pub struct DatabaseUrl(String);
impl DatabaseUrl {
/// Validate and retain a PostgreSQL connection string without connecting.
///
/// # Errors
///
/// Returns [`ErrorKind::Configuration`] for empty, malformed, or remote
/// connection strings.
pub fn new(value: impl Into<String>) -> Result<Self, Error> {
let mut value = value.into();
if let Err(error) = crate::_internal::sync::validate_database_url(&value) {
value.zeroize();
let message = error.to_string();
return Err(Error::with_anyhow_source(
ErrorKind::Configuration,
message,
error,
));
}
Ok(Self(value))
}
fn expose(&self) -> &str {
&self.0
}
}
impl fmt::Debug for DatabaseUrl {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("DatabaseUrl([REDACTED])")
}
}
impl Drop for DatabaseUrl {
fn drop(&mut self) {
self.0.zeroize();
}
}
/// Validated 256-bit key for encrypted baseline caches.
///
/// Key material is never exposed through formatting or serialization.
pub struct CacheKey([u8; 32]);
impl CacheKey {
/// Retain an already decoded 256-bit cache key.
pub fn from_bytes(value: [u8; 32]) -> Self {
Self(value)
}
/// Decode a 64-character hexadecimal cache key.
///
/// # Errors
///
/// Returns [`ErrorKind::Configuration`] when the value is not exactly 32
/// bytes of hexadecimal key material.
pub fn from_hex(value: &str) -> Result<Self, Error> {
decode_hex_key(value.trim())
.map(Self)
.map_err(|error| Error::configuration(error.to_string()))
}
fn expose(&self) -> &[u8; 32] {
&self.0
}
}
impl fmt::Debug for CacheKey {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("CacheKey([REDACTED])")
}
}
impl Drop for CacheKey {
fn drop(&mut self) {
self.0.zeroize();
}
}
impl From<[u8; 32]> for CacheKey {
fn from(value: [u8; 32]) -> Self {
Self::from_bytes(value)
}
}
/// Confidence in the final migration result.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub enum Confidence {
/// The result is fully supported by the available modeled evidence.
Exact,
/// At least one relevant fact was unavailable or could not be modeled exactly.
Tainted,
}
/// How well-supported a single finding is by the evidence behind it.
///
/// Separate from [`Confidence`], which describes the run as a whole. Reduced
/// certainty never reduces severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[non_exhaustive]
pub enum Certainty {
/// Proven from observed evidence.
Exact,
/// Decided under an asserted input rather than an observed one. Reported
/// rather than suppressed, because a false negative cannot be
/// self-remediated by the reader.
Assumed,
/// Partially supported: a relevant fact was unavailable or unmodeled.
Tainted,
}
impl std::fmt::Display for Certainty {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Certainty::Exact => write!(f, "exact"),
Certainty::Assumed => write!(f, "assumed"),
Certainty::Tainted => write!(f, "tainted"),
}
}
}
impl Certainty {
/// Whether the evidence is certain.
pub fn is_exact(&self) -> bool {
matches!(self, Self::Exact)
}
}
/// Stable severity assigned to a finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[non_exhaustive]
pub enum Tier {
/// Blocking safety problem.
Tier1,
/// Risk requiring explicit review.
Tier2,
/// Informational or operability guidance.
Tier3,
}
/// Stable category of the SQL operation that produced a finding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub enum OperationKind {
/// Drops a table column.
DropColumn,
/// Drops a table.
DropTable,
/// Drops an index.
DropIndex,
/// Drops a view.
DropView,
/// Drops a materialized view.
DropMaterializedView,
/// Drops a function.
DropFunction,
/// Drops a procedure.
DropProcedure,
/// Drops a schema.
DropSchema,
/// Drops a database.
DropDatabase,
/// Drops a sequence.
DropSequence,
/// Drops a domain.
DropDomain,
/// Drops a type.
DropType,
/// Drops a publication.
DropPublication,
/// Drops a trigger.
DropTrigger,
/// Drops a row-level security policy.
DropPolicy,
/// Adds a table column.
AddColumn,
/// Changes a column's data type.
AlterColumnType,
/// Adds a table constraint.
AddConstraint,
/// Creates an index.
CreateIndex,
/// Creates a table.
CreateTable,
/// Creates a view.
CreateView,
/// Creates a function.
CreateFunction,
/// Creates a procedure.
CreateProcedure,
/// Changes a function.
AlterFunction,
/// Changes a procedure.
AlterProcedure,
/// Refreshes a materialized view.
RefreshMaterializedView,
/// Reindexes a table, index, database, schema, or system.
Reindex,
/// Attaches a partition.
AttachPartition,
/// Detaches a partition.
DetachPartition,
/// Runs `VACUUM FULL`.
VacuumFull,
/// Acquires an explicit table lock.
LockTable,
/// Removes all rows from one or more tables.
TruncateTable,
/// Grants privileges.
Grant,
/// Revokes privileges.
RevokeGrant,
/// Changes a type definition.
AlterType,
/// Creates a trigger.
CreateTrigger,
/// Creates a row-level security policy.
CreatePolicy,
/// Disables a trigger.
DisableTrigger,
/// Enables a trigger.
EnableTrigger,
/// Renames a table.
RenameTable,
/// Renames a table column.
RenameColumn,
/// Renames an object with no more specific category.
Rename,
/// SQL whose effects cannot be modeled precisely.
OpaqueSql,
/// Creates a schema.
CreateSchema,
/// Sets or drops a column default.
SetDefault,
/// Creates a sequence.
CreateSequence,
/// Creates a domain.
CreateDomain,
/// Changes a schema.
AlterSchema,
/// Represents a conflict detected before execution.
Conflict,
/// Represents an irreversible operation.
Irreversible,
/// Represents a reference that could not be resolved safely.
UnresolvedReference,
/// A named operation outside the stable categories above.
Other(String),
}
/// Stable category of the database object associated with a finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
pub enum ObjectKind {
/// A table.
Table,
/// An index.
Index,
/// A view.
View,
/// A materialized view.
MaterializedView,
/// A function.
Function,
/// A procedure.
Procedure,
/// A trigger.
Trigger,
/// A sequence.
Sequence,
/// A schema.
Schema,
/// A database role.
Role,
/// A logical replication publication.
Publication,
/// A logical replication subscription.
Subscription,
/// A database.
Database,
/// A domain.
Domain,
/// A row-level security policy.
Policy,
/// A PostgreSQL type.
Type,
/// Object whose identity is opaque to the analyzer.
Opaque,
/// Unknown object category.
Unknown,
}
/// Overall deployment verdict derived from all findings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
pub enum Verdict {
/// At least one Tier 1 finding blocks deployment.
#[serde(rename = "HALT")]
Halt,
/// At least one Tier 2 finding requires review and no Tier 1 finding exists.
#[serde(rename = "CAUTIOUS")]
Cautious,
/// Only non-blocking findings exist, including an irreversible operation.
#[serde(rename = "SAFE WITH RISK")]
SafeWithRisk,
/// No modeled blocking or irreversible finding exists.
#[serde(rename = "SAFE")]
Safe,
}
impl Verdict {
/// Return the stable human and JSON report label.
pub fn as_str(self) -> &'static str {
match self {
Self::Halt => "HALT",
Self::Cautious => "CAUTIOUS",
Self::SafeWithRisk => "SAFE WITH RISK",
Self::Safe => "SAFE",
}
}
}
/// Counts of findings by severity tier.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
pub struct FindingSummary {
/// Total number of findings.
pub total: usize,
/// Number of blocking Tier 1 findings.
pub tier1: usize,
/// Number of review-required Tier 2 findings.
pub tier2: usize,
/// Number of informational Tier 3 findings.
pub tier3: usize,
}
/// Stable reason why analysis had to be conservative.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EvidenceCode {
/// No synchronized database baseline was supplied.
BaselineUnavailable,
/// The supplied baseline exceeded the configured maximum age.
BaselineStale,
/// A required catalog family was absent from the baseline.
CatalogCoverageIncomplete,
/// The parser accepted a statement for which no typed extractor exists.
UnsupportedStatement,
/// The statement was recognized but some behavior could not be modeled.
UnsupportedSemantics,
/// An object reference could not be resolved exactly.
UnresolvedReference,
/// The relevant object state could not be proven.
UnknownObjectState,
/// Transaction state became uncertain.
TransactionStateUnknown,
/// A state transition was deliberately treated as opaque.
UnmodeledState,
}
/// Whether evidence affects one statement or the entire migration chain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EvidenceScope {
/// Evidence applies to one statement.
Statement,
/// Evidence applies to the complete ordered migration chain.
Chain,
}
/// Location of conservative-analysis evidence.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[non_exhaustive]
pub struct EvidenceLocation {
/// Source filename supplied by the caller.
pub file: String,
/// One-based statement position within the source file.
pub statement_index: usize,
}
/// Stable explanation for a conservative analysis decision.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[non_exhaustive]
pub struct Evidence {
/// Machine-readable reason code.
pub code: EvidenceCode,
/// Portion of the analysis affected by this evidence.
pub scope: EvidenceScope,
/// Human-readable explanation without SQL or credentials.
pub summary: String,
/// Source location when the evidence belongs to one statement.
#[serde(skip_serializing_if = "Option::is_none")]
pub location: Option<EvidenceLocation>,
}
/// One-based source position of a finding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct SourceLocation {
/// Source filename supplied by the caller.
pub file: String,
/// One-based source line.
pub line: usize,
/// One-based source column.
pub column: usize,
}
/// A source-aware, machine-readable migration finding.
///
/// Per-occurrence fields only. Rule metadata (title, summary) is not repeated
/// here; look the `rule_id` up in the report's `rules` catalogue.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct Finding {
/// Stable primary rule identifier.
pub rule_id: String,
/// Stable database-object category.
pub object_kind: ObjectKind,
/// Qualified object name when known.
pub object_name: String,
/// A property of the operation alone; see [`Finding::certainty`].
pub tier: Tier,
/// Explanation of the detected risk.
pub reason: String,
/// Recommended remediation.
pub recipe: String,
/// SQL statement associated with the finding, when available.
#[serde(skip_serializing_if = "Option::is_none")]
pub sql: Option<String>,
/// Source line and column, when available.
#[serde(skip_serializing_if = "Option::is_none")]
pub location: Option<SourceLocation>,
/// One-based statement position within the source file.
#[serde(skip_serializing_if = "Option::is_none")]
pub statement_index: Option<usize>,
/// How well-supported this finding is by the evidence behind it. Reduced
/// certainty never reduces severity. Reported only when it is not exact.
#[serde(skip_serializing_if = "Certainty::is_exact")]
pub certainty: Certainty,
}
/// One named SQL migration in its intended analysis order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Migration {
filename: String,
sql: String,
}
impl Migration {
/// Create one named SQL migration for [`analyze_chain`].
pub fn new(filename: impl Into<String>, sql: impl Into<String>) -> Self {
Self {
filename: filename.into(),
sql: sql.into(),
}
}
/// Return the migration's source name, used in finding locations.
pub fn filename(&self) -> &str {
&self.filename
}
/// Return the SQL source submitted for analysis.
pub fn sql(&self) -> &str {
&self.sql
}
}
/// A rule that could not state a finding for want of evidence. Nothing is
/// wrong with the migration; these are the checks that did not run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct NotEvaluated {
/// Rule that could not be evaluated.
pub rule_id: String,
/// Tier this rule would have produced had it been evaluable.
pub tier: Tier,
/// Why the evidence was unavailable.
pub cause: String,
/// SQL statement the rule could not judge.
#[serde(skip_serializing_if = "Option::is_none")]
pub sql: Option<String>,
/// What would make this rule evaluable.
pub recipe: String,
/// Out-of-scope schemas the boundary query observed for this rule.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub missing_schemas: Vec<String>,
}
impl From<&crate::_internal::report::violations::NotEvaluated> for NotEvaluated {
fn from(value: &crate::_internal::report::violations::NotEvaluated) -> Self {
Self {
rule_id: value.rule_id.to_owned(),
tier: value.tier.clone().into(),
cause: value.cause.as_str().to_owned(),
sql: value.sql.clone(),
recipe: value.recipe.clone(),
missing_schemas: value.missing_schemas.clone(),
}
}
}
/// Verdict, findings, evidence, and the checks that did not run.
#[derive(Clone)]
pub struct AnalysisOutcome {
findings: Vec<Finding>,
confidence: Confidence,
evidence: Vec<Evidence>,
baseline: BaselineReport,
/// Rules that could not state a finding for want of evidence.
not_evaluated: Vec<crate::_internal::report::violations::NotEvaluated>,
inner: InternalOutcome<InternalFinding>,
}
impl fmt::Debug for AnalysisOutcome {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("AnalysisOutcome")
.field("findings", &self.findings)
.field("confidence", &self.confidence)
.field("evidence", &self.evidence)
.field("baseline", &self.baseline)
.finish()
}
}
impl AnalysisOutcome {
/// Return findings in deterministic report order.
pub fn findings(&self) -> &[Finding] {
&self.findings
}
/// Return the confidence of the complete analysis.
pub fn confidence(&self) -> Confidence {
self.confidence
}
/// Return the evidence explaining conservative analysis decisions.
pub fn evidence(&self) -> &[Evidence] {
&self.evidence
}
/// Rules that could not state a finding because the evidence they need was
/// unavailable, each with the cause and what would resolve it.
pub fn not_evaluated(&self) -> Vec<NotEvaluated> {
self.not_evaluated.iter().map(NotEvaluated::from).collect()
}
/// Return the baseline provenance attached to every report format.
pub fn baseline(&self) -> &BaselineReport {
&self.baseline
}
/// Return whether any finding is a blocking Tier 1 result.
pub fn should_halt(&self) -> bool {
self.verdict() == Verdict::Halt
}
/// Return the overall deployment verdict.
pub fn verdict(&self) -> Verdict {
crate::_internal::report::reporter::compute_verdict_with(
&self.violations(),
&self.not_evaluated,
)
.into()
}
/// Return the canonical deployment recommendation for this result.
pub fn recommendation(&self) -> &'static str {
crate::_internal::report::reporter::compute_verdict_with(
&self.violations(),
&self.not_evaluated,
)
.recommendation(&self.inner.confidence)
}
/// Return finding counts by severity tier.
pub fn summary(&self) -> FindingSummary {
self.findings.iter().fold(
FindingSummary {
total: self.findings.len(),
..FindingSummary::default()
},
|mut summary, finding| {
match finding.tier {
Tier::Tier1 => summary.tier1 += 1,
Tier::Tier2 => summary.tier2 += 1,
Tier::Tier3 => summary.tier3 += 1,
}
summary
},
)
}
/// Render the stable JSON report consumed by automation.
pub fn json(&self) -> serde_json::Value {
let mut report =
InternalReporter::json_outcome_with_locations(&self.inner, &self.not_evaluated);
report["baseline"] = serde_json::to_value(&self.baseline)
.expect("API-owned baseline report is always serializable");
report["not_evaluated"] = serde_json::to_value(self.not_evaluated())
.expect("not-evaluated records are always serializable");
report
}
/// Render the Markdown report used in pull-request summaries.
pub fn markdown(&self) -> String {
let mut report = InternalReporter::markdown_outcome(&self.inner, &self.not_evaluated);
report.push_str("\n## Baseline\n\n");
report.push_str(&format!(
"- **Status:** `{}`\n- **Automatic sync:** `{}`\n",
self.baseline.status.label(),
self.baseline.auto_sync.label()
));
if let Some(source_database) = &self.baseline.source_database {
report.push_str(&format!(
"- **Source database:** `{}`\n",
markdown_inline_code(source_database)
));
}
if let Some(schemas) = &self.baseline.schemas {
report.push_str(&format!(
"- **Schemas:** `{}`\n",
markdown_inline_code(&schemas.join(", "))
));
}
report.push_str(&format!(
"- **Observed lock timeout:** `{}`\n- **Observed statement timeout:** `{}`\n",
format_timeout(self.baseline.observed_settings.lock_timeout_ms),
format_timeout(self.baseline.observed_settings.statement_timeout_ms)
));
report
}
/// Print the human report and return whether it contains a halt result.
pub fn print_human(&self) -> bool {
InternalReporter::print_outcome(&self.inner, &self.not_evaluated, false)
}
/// As [`print_human`](Self::print_human), without ANSI styling.
pub fn print_human_without_color(&self) -> bool {
InternalReporter::print_outcome(&self.inner, &self.not_evaluated, true)
}
/// Run the terminal report viewer.
pub fn run_interactive(&self) -> Result<(), Error> {
crate::_internal::report::interactive::run_interactive(
&self.inner.findings,
&self.inner.confidence,
&self.not_evaluated,
)
.map_err(|error| {
let message = error.to_string();
Error::with_anyhow_source(ErrorKind::Report, message, error)
})
}
/// Add explicit conservative evidence before rendering an outcome.
///
/// This is useful for callers that know a prerequisite was unavailable
/// outside safe-migrate's SQL analysis.
pub fn with_evidence(mut self, code: EvidenceCode, scope: EvidenceScope) -> Self {
self.inner = self
.inner
.with_evidence(internal_evidence::EvidenceRecord::new(
code.into(),
scope.into(),
));
self.evidence = self.inner.evidence.iter().map(Evidence::from).collect();
self.confidence = self.inner.confidence.clone().into();
self
}
/// Attach the result of a caller-managed automatic baseline refresh.
pub fn with_auto_sync_status(mut self, status: AutoSyncStatus) -> Self {
self.baseline.auto_sync = status;
self
}
fn violations(&self) -> Vec<InternalViolation> {
self.inner
.findings
.iter()
.map(|finding| finding.violation.clone())
.collect()
}
}
impl AnalysisOutcome {
fn from_internal(inner: InternalOutcome<InternalFinding>, baseline: BaselineReport) -> Self {
Self {
findings: inner.findings.iter().map(Finding::from).collect(),
confidence: inner.confidence.clone().into(),
evidence: inner.evidence.iter().map(Evidence::from).collect(),
baseline,
not_evaluated: Vec::new(),
inner,
}
}
}
/// Opaque, validated database baseline used for analysis.
#[derive(Clone)]
pub struct Baseline {
inner: InternalDbCache,
available: bool,
encrypted: bool,
format_version: Option<u32>,
path: Option<std::path::PathBuf>,
}
impl fmt::Debug for Baseline {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Baseline")
.field("inspection", &self.inspect())
.finish()
}
}
impl Default for Baseline {
fn default() -> Self {
Self::unavailable()
}
}
impl Baseline {
/// Use default worst-case assumptions when no synchronized baseline exists.
pub fn unavailable() -> Self {
Self {
inner: InternalDbCache::new(),
available: false,
encrypted: false,
format_version: None,
path: None,
}
}
/// Load a synchronized cache, validate its structure, and keep its internal
/// representation opaque to callers.
///
/// # Errors
///
/// Returns [`ErrorKind::Cache`] when the file cannot be read, its encryption
/// configuration or key is wrong, or its encoded contents fail validation.
pub fn load(path: &Path, config: &Config) -> Result<Self, Error> {
let (inner, format_version, encrypted) = decode_cache(path, config.cache_encryption())?;
Ok(Self {
inner,
available: true,
encrypted,
format_version: Some(format_version),
path: Some(path.to_path_buf()),
})
}
/// Load an encrypted baseline with key material supplied by the caller.
///
/// This entry point avoids process-global environment mutation in embedded
/// and concurrent applications.
///
/// # Errors
///
/// Returns [`ErrorKind::Configuration`] when cache encryption is disabled,
/// or [`ErrorKind::Cache`] when the cache cannot be authenticated or decoded.
pub fn load_with_key(path: &Path, config: &Config, key: &CacheKey) -> Result<Self, Error> {
require_cache_encryption(config)?;
let (inner, format_version, encrypted) = decode_cache_with_key(path, key)?;
Ok(Self {
inner,
available: true,
encrypted,
format_version: Some(format_version),
path: Some(path.to_path_buf()),
})
}
/// Load a baseline when it exists, while preserving every other loading
/// or validation failure.
///
/// A missing path produces [`Baseline::unavailable`]. Every other error is
/// returned, so callers cannot silently downgrade a damaged baseline.
///
/// # Errors