//! Explicit RID-to-record associations; classification remains attached to the RID identity. use crate::{error::Result, store::Store}; use rusqlite::{Connection, OptionalExtension, params}; use serde::Deserialize; use serde_json::{Value, json}; pub fn init(db: &Connection) -> Result<()> { db.execute_batch("CREATE TABLE IF NOT EXISTS target_record_bindings( target_id TEXT PRIMARY KEY COLLATE BINARY, record_id TEXT NOT NULL REFERENCES records(id) ON DELETE CASCADE ); CREATE INDEX IF NOT EXISTS target_record_binding_record ON target_record_bindings(record_id);")?; Ok(()) } fn validate(target: &str) -> Result<()> { if !rid_shared::target_lists::valid_target_id(target) { return Err("RID 目标标识无效".into()); } Ok(()) } fn bound(db: &Connection, target: &str) -> Result> { Ok(db .query_row( "SELECT record_id FROM target_record_bindings WHERE target_id=?1", [target], |r| r.get(0), ) .optional()?) } pub fn resolve(store: &Store, target: &str) -> Result { validate(target)?; let binding = bound(&store.db, target)?; let automatic: Option = if binding.is_none() && !target.starts_with("MAC-") && !target.starts_with("SRC-") { store .db .query_row( "SELECT id FROM records WHERE serial_no=?1 COLLATE BINARY", [target], |r| r.get(0), ) .optional()? } else { None }; let id = binding.as_ref().or(automatic.as_ref()); let record = id .map(|id| store.get(id).map(crate::archive::public)) .transpose()?; Ok( json!({"targetId":target,"bindingRecordId":binding,"matchSource":if binding.is_some(){"manual"}else if automatic.is_some(){"serial"}else{"none"},"record":record}), ) } #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct Mutation { // Required JSON null or string prevents clients silently omitting concurrency checks. expected_record_id: Value, record_id: Value, } fn nullable_id(value: &Value) -> Result> { match value { Value::Null => Ok(None), Value::String(id) if crate::store::valid_id(id) => Ok(Some(id)), _ => Err("档案标识无效".into()), } } pub fn save(store: &mut Store, target: &str, mutation: Mutation) -> Result { validate(target)?; let expected = nullable_id(&mutation.expected_record_id)?; let record = nullable_id(&mutation.record_id)?; let tx = store .db .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; if bound(&tx, target)?.as_deref() != expected { return Err("关联已被其他页面修改,请刷新关联后重试".into()); } if let Some(id) = record { let exists: bool = tx.query_row( "SELECT EXISTS(SELECT 1 FROM records WHERE id=?1)", [id], |r| r.get(0), )?; if !exists { return Err("登记档案已不存在,请重新搜索".into()); } tx.execute("INSERT INTO target_record_bindings(target_id,record_id) VALUES(?1,?2) ON CONFLICT(target_id) DO UPDATE SET record_id=excluded.record_id",params![target,id])?; } else { tx.execute( "DELETE FROM target_record_bindings WHERE target_id=?1", [target], )?; } tx.commit()?; resolve(store, target) } #[cfg(test)] mod tests { use super::*; fn change(expected: Option<&str>, record: Option<&str>) -> Mutation { serde_json::from_value(json!({"expectedRecordId":expected,"recordId":record})).unwrap() } #[test] fn mac_identity_never_automatically_matches_a_serial_record() { let dir = tempfile::tempdir().unwrap(); let mut store = Store::open(dir.path().into()).unwrap(); let registered = store .register(json!({"serialNo":"MAC-AABBCCDDEEFF"})) .unwrap(); let id = registered["record"]["id"].as_str().unwrap(); assert_eq!( resolve(&store, "MAC-AABBCCDDEEFF").unwrap()["matchSource"], "none" ); assert_eq!( save(&mut store, "MAC-AABBCCDDEEFF", change(None, Some(id))).unwrap()["matchSource"], "manual" ); } #[test] fn association_persists_is_exact_and_preserves_classification() { let dir = tempfile::tempdir().unwrap(); let mut s = Store::open(dir.path().into()).unwrap(); let r = s .register(json!({"serialNo":"SERIAL-001","modelName":"Test","ownerName":"Owner"})) .unwrap(); let id = r["record"]["id"].as_str().unwrap(); assert_eq!(resolve(&s, "SERIAL-001").unwrap()["matchSource"], "serial"); assert!(resolve(&s, "serial-001").unwrap()["record"].is_null()); crate::target_lists::save( &mut s.db, "RID-001", rid_shared::target_lists::Mutation { list_kind: rid_shared::target_lists::ListKind::Black, note: String::new(), expected_revision: 0, }, ) .unwrap(); let result = save(&mut s, "RID-001", change(None, Some(id))).unwrap(); assert_eq!(result["record"]["serialNo"], "SERIAL-001"); assert_eq!(result["matchSource"], "manual"); assert!(save(&mut s, "RID-001", change(None, None)).is_err()); assert!(save(&mut s, "RID-001", change(Some(id), Some(&"f".repeat(36)))).is_err()); drop(s); let mut s = Store::open(dir.path().into()).unwrap(); assert_eq!(resolve(&s, "RID-001").unwrap()["bindingRecordId"], id); save(&mut s, "RID-001", change(Some(id), None)).unwrap(); assert!(resolve(&s, "RID-001").unwrap()["record"].is_null()); assert_eq!(crate::target_lists::load(&s.db).unwrap().entries.len(), 1); save(&mut s, "RID-001", change(None, Some(id))).unwrap(); s.delete(id, None).unwrap(); assert!(resolve(&s, "RID-001").unwrap()["record"].is_null()); assert!(resolve(&s, "bad id").is_err()); } #[tokio::test] async fn http_binding_validation_and_origin_protection() { use axum::{body::Body, http::Request}; use tower::ServiceExt; let dir = tempfile::tempdir().unwrap(); let mut store = Store::open(dir.path().into()).unwrap(); let r = store.register(json!({"serialNo":"HTTP-001"})).unwrap(); let id = r["record"]["id"].as_str().unwrap().to_owned(); let (tx, mut rx) = tokio::sync::mpsc::channel::(8); let worker = std::thread::spawn(move || { while let Some(crate::Job::Execute(job)) = rx.blocking_recv() { job(&mut store); } }); let app = crate::http::router(crate::Worker(tx)); for (method, body, origin, status) in [ ("PUT", json!({"recordId":id}), None, 400), ( "PUT", json!({"expectedRecordId":null,"recordId":id}), Some("https://foreign.example"), 403, ), ( "PUT", json!({"expectedRecordId":null,"recordId":id}), None, 200, ), ("GET", Value::Null, None, 200), ( "PUT", json!({"expectedRecordId":null,"recordId":null}), None, 400, ), ( "PUT", json!({"expectedRecordId":id,"recordId":null}), None, 200, ), ] { let mut request = Request::builder() .method(method) .uri("/api/target-bindings/RID-HTTP"); if let Some(origin) = origin { request = request.header("origin", origin); } let response = app .clone() .oneshot(request.body(Body::from(body.to_string())).unwrap()) .await .unwrap(); assert_eq!(response.status().as_u16(), status, "{method} {body}"); if method == "GET" { let bytes = axum::body::to_bytes(response.into_body(), 65536) .await .unwrap(); let value: Value = serde_json::from_slice(&bytes).unwrap(); assert_eq!(value["record"]["serialNo"], "HTTP-001"); } } drop(app); worker.join().unwrap(); } }