cert.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. use crate::schema;
  2. use microrm::prelude::*;
  3. use ring::signature::Ed25519KeyPair;
  4. use sha2::Digest;
  5. use std::collections::HashMap;
  6. pub struct CertStore<'a> {
  7. db: &'a microrm::DB,
  8. qi: microrm::QueryInterface<'a>,
  9. keys: HashMap<String, Ed25519KeyPair>,
  10. }
  11. impl<'a> CertStore<'a> {
  12. pub fn new(db: &'a microrm::DB) -> Self {
  13. Self {
  14. db,
  15. qi: db.query_interface(),
  16. keys: HashMap::new(),
  17. }
  18. }
  19. fn realm_id(&self, realm_name: &str) -> Option<schema::RealmID> {
  20. self.qi
  21. .get()
  22. .by(schema::Realm::Shortname, realm_name)
  23. .one()
  24. .expect("couldn't query db")
  25. .map(|x| x.id())
  26. }
  27. pub fn generate_in(&self, realm_name: &str) -> Result<String, &'static str> {
  28. let mut rng = ring::rand::SystemRandom::new();
  29. let sign_generated = Ed25519KeyPair::generate_pkcs8(&mut rng);
  30. let realm_id = self.realm_id(realm_name).ok_or("Failed to find realm")?;
  31. if let Err(_) = sign_generated {
  32. return Err("Failed to generate key");
  33. }
  34. let sign_generated = sign_generated.unwrap();
  35. let keydata = sign_generated.as_ref().to_owned();
  36. let mut key_hasher = sha2::Sha256::new();
  37. key_hasher.update(&keydata);
  38. let mut key_id = base64::encode(key_hasher.finalize());
  39. key_id.truncate(16);
  40. self.qi
  41. .add(&schema::Key {
  42. realm: realm_id,
  43. key_id: key_id.clone(),
  44. keydata,
  45. })
  46. .expect("Couldn't add key");
  47. Ok(key_id)
  48. }
  49. }
  50. pub fn inspect(db: &microrm::DB, realm_name: &str) {
  51. let qi = db.query_interface();
  52. let cs = CertStore::new(db);
  53. println!("Certstore loaded.");
  54. let realm = qi
  55. .get()
  56. .by(schema::Realm::Shortname, realm_name)
  57. .one()
  58. .expect("couldn't query db");
  59. if realm.is_none() {
  60. println!("No such realm {}", realm_name);
  61. return;
  62. }
  63. let realm = realm.unwrap();
  64. println!("Retrieving keys for {} realm...", realm_name);
  65. let keys = qi
  66. .get()
  67. .by(schema::Key::Realm, &realm.id())
  68. .all()
  69. .expect("Can get keys");
  70. for key in keys {
  71. println!("- [{:20}]", key.key_id);
  72. }
  73. }
  74. pub fn generate(db: &microrm::DB, realm_name: &str) {
  75. let qi = db.query_interface();
  76. let cs = CertStore::new(db);
  77. if let Err(e) = cs.generate_in(realm_name) {
  78. println!("Failed to generate key: {}", e);
  79. }
  80. }