Skip to main content

HashChainAuditor

Struct HashChainAuditor 

Source
pub struct HashChainAuditor { /* private fields */ }
Expand description

带哈希链的审计器:所有日志通过 SHA-256 链式哈希串联,支持篡改检测。

§防篡改机制

  1. 每条记录的 current_hash = SHA256(prev_hash || sql || user || timestamp)
  2. 下一条记录的 prev_hash 等于上一条的 current_hash
  3. 任何对历史记录的修改会导致 current_hash 变化, 进而与下一条的 prev_hash 不匹配
  4. 删除中间记录会断开链;插入记录会改变后续所有哈希

§示例

use sz_orm_audit::{HashChainAuditor, SqlAuditContext};

let mut auditor = HashChainAuditor::new();
auditor.log(&SqlAuditContext {
    sql: "SELECT * FROM users".to_string(),
    user: "admin".to_string(),
    timestamp: 1000,
});
// 验证链完整性
assert!(auditor.verify().is_ok());

Implementations§

Source§

impl HashChainAuditor

Source

pub fn new() -> Self

创建空的哈希链审计器

Source

pub fn log(&self, ctx: &SqlAuditContext)

追加一条审计日志到哈希链末尾。

  • 若链为空,使用 GENESIS_HASH 作为 prev_hash
  • 否则使用上一条记录的 current_hash 作为 prev_hash

SQL 会先经过 mask_sensitive 脱敏再写入链中, 确保存储的审计日志不含敏感信息。

Source

pub fn get_entries(&self) -> Vec<HashChainEntry>

返回所有日志条目的快照(克隆)

Source

pub fn len(&self) -> usize

返回日志条目数量

Source

pub fn is_empty(&self) -> bool

是否为空

Source

pub fn verify(&self) -> Result<(), String>

验证哈希链完整性。

检查内容:

  1. 首条记录的 prev_hash 等于 GENESIS_HASH
  2. 每条记录的 current_hash 等于 compute_hash(prev_hash, entry)
  3. 相邻记录的 prev_hash 等于前一条的 current_hash
§返回值
  • Ok(()):链完整,未被篡改
  • Err(reason):链被篡改,reason 描述首个异常的位置与类型
Source

pub fn flush(&self, path: &str) -> Result<usize, String>

将哈希链持久化到 JSONL 文件(每行一条 JSON)。

返回写入的条目数。

Trait Implementations§

Source§

impl Default for HashChainAuditor

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.