Integrating authendication

moved IPInfo to global
configured secret key path
authendicated register app node
This commit is contained in:
Noor 2025-02-10 20:08:13 +05:30
parent 28618f38d0
commit 354741a0a2
Signed by: noormohammedb
GPG Key ID: D83EFB8B3B967146
7 changed files with 396 additions and 33 deletions

288
Cargo.lock generated

@ -26,6 +26,21 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "android-tzdata"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0"
[[package]]
name = "android_system_properties"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "anstream" name = "anstream"
version = "0.6.18" version = "0.6.18"
@ -195,12 +210,36 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64ct"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "2.8.0" version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "bs58"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"
dependencies = [
"tinyvec",
]
[[package]] [[package]]
name = "bumpalo" name = "bumpalo"
version = "3.16.0" version = "3.16.0"
@ -234,12 +273,32 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chrono"
version = "0.4.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e36cc9d416881d2e24f9a963be5fb1cd90966419ac844274161d10488b3e825"
dependencies = [
"android-tzdata",
"iana-time-zone",
"js-sys",
"num-traits",
"wasm-bindgen",
"windows-targets",
]
[[package]] [[package]]
name = "colorchoice" name = "colorchoice"
version = "1.0.3" version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990"
[[package]]
name = "const-oid"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
[[package]] [[package]]
name = "core-foundation" name = "core-foundation"
version = "0.9.4" version = "0.9.4"
@ -256,6 +315,15 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "crc32fast" name = "crc32fast"
version = "1.4.2" version = "1.4.2"
@ -265,12 +333,62 @@ dependencies = [
"cfg-if", "cfg-if",
] ]
[[package]]
name = "crypto-common"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "curve25519-dalek"
version = "4.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
dependencies = [
"cfg-if",
"cpufeatures",
"curve25519-dalek-derive",
"digest",
"fiat-crypto",
"rustc_version",
"subtle",
"zeroize",
]
[[package]]
name = "curve25519-dalek-derive"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "der"
version = "0.7.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f55bf8e7b65898637379c1b74eb1551107c8294ed26d855ceb9fd1a09cfc9bc0"
dependencies = [
"const-oid",
"zeroize",
]
[[package]] [[package]]
name = "detee-sgx-daemon" name = "detee-sgx-daemon"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bs58",
"chrono",
"detee-shared", "detee-shared",
"ed25519-dalek",
"env_logger", "env_logger",
"flate2", "flate2",
"home", "home",
@ -292,7 +410,7 @@ dependencies = [
[[package]] [[package]]
name = "detee-shared" name = "detee-shared"
version = "0.1.0" version = "0.1.0"
source = "git+ssh://git@gitea.detee.cloud/noormohammedb/detee-shared?branch=stable_01#fce57884937a4ec02acbf2f5b370ab879b1af657" source = "git+ssh://git@gitea.detee.cloud/noormohammedb/detee-shared?branch=stable_01#65bfa113a44251dd13e5d895014f4a773e367d2e"
dependencies = [ dependencies = [
"base64", "base64",
"prost", "prost",
@ -302,6 +420,16 @@ dependencies = [
"tonic-build", "tonic-build",
] ]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]] [[package]]
name = "displaydoc" name = "displaydoc"
version = "0.2.5" version = "0.2.5"
@ -313,6 +441,31 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "ed25519"
version = "2.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
dependencies = [
"pkcs8",
"signature",
]
[[package]]
name = "ed25519-dalek"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a3daa8e81a3963a60642bcc1f90a670680bd4a77535faa384e9d1c79d620871"
dependencies = [
"curve25519-dalek",
"ed25519",
"rand_core",
"serde",
"sha2",
"subtle",
"zeroize",
]
[[package]] [[package]]
name = "either" name = "either"
version = "1.13.0" version = "1.13.0"
@ -373,6 +526,12 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "fiat-crypto"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]] [[package]]
name = "filetime" name = "filetime"
version = "0.2.25" version = "0.2.25"
@ -481,6 +640,16 @@ dependencies = [
"slab", "slab",
] ]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.2.15" version = "0.2.15"
@ -682,6 +851,29 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "iana-time-zone"
version = "0.1.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"wasm-bindgen",
"windows-core",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
]
[[package]] [[package]]
name = "icu_collections" name = "icu_collections"
version = "1.5.0" version = "1.5.0"
@ -984,6 +1176,15 @@ dependencies = [
"tempfile", "tempfile",
] ]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]] [[package]]
name = "object" name = "object"
version = "0.36.7" version = "0.36.7"
@ -1091,6 +1292,16 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "pkcs8"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
dependencies = [
"der",
"spki",
]
[[package]] [[package]]
name = "pkg-config" name = "pkg-config"
version = "0.3.31" version = "0.3.31"
@ -1320,6 +1531,15 @@ version = "0.1.24"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f"
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "0.38.44" version = "0.38.44"
@ -1416,6 +1636,12 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "semver"
version = "1.0.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f79dfe2d285b0488816f30e700a7438c5a73d816b5b7d3ac72fbc48b0d185e03"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.217" version = "1.0.217"
@ -1475,12 +1701,32 @@ dependencies = [
"version_check", "version_check",
] ]
[[package]]
name = "sha2"
version = "0.10.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]] [[package]]
name = "shlex" name = "shlex"
version = "1.3.0" version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "signature"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"rand_core",
]
[[package]] [[package]]
name = "slab" name = "slab"
version = "0.4.9" version = "0.4.9"
@ -1512,6 +1758,16 @@ version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
[[package]]
name = "spki"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
dependencies = [
"base64ct",
"der",
]
[[package]] [[package]]
name = "stable_deref_trait" name = "stable_deref_trait"
version = "1.2.0" version = "1.2.0"
@ -1611,6 +1867,21 @@ dependencies = [
"zerovec", "zerovec",
] ]
[[package]]
name = "tinyvec"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "022db8904dfa342efe721985167e9fcd16c29b226db4397ed752a761cfce81e8"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.43.0" version = "1.43.0"
@ -1810,6 +2081,12 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "typenum"
version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.15" version = "1.0.15"
@ -1959,6 +2236,15 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "windows-core"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
dependencies = [
"windows-targets",
]
[[package]] [[package]]
name = "windows-registry" name = "windows-registry"
version = "0.2.0" version = "0.2.0"

@ -15,14 +15,17 @@ tar = "0.4.43"
anyhow = "1.0.95" anyhow = "1.0.95"
rand = "0.8.5" rand = "0.8.5"
tokio-stream = "0.1.17" tokio-stream = "0.1.17"
detee-shared = { git = "ssh://git@gitea.detee.cloud/noormohammedb/detee-shared", branch = "stable_01" }
# detee-shared = { path = "../detee-shared" }
log = "0.4.25" log = "0.4.25"
serde = "1.0.217" serde = "1.0.217"
serde_json = "1.0.138" serde_json = "1.0.138"
serde_yml = "0.0.12" serde_yml = "0.0.12"
home = "0.5.11" home = "0.5.11"
ed25519-dalek = { version = "2.1.1", features = ["rand_core"] }
bs58 = "0.5.1"
chrono = "0.4.39"
detee-shared = { git = "ssh://git@gitea.detee.cloud/noormohammedb/detee-shared", branch = "stable_01" }
# detee-shared = { path = "../detee-shared" }
[build-dependencies] [build-dependencies]
tonic-build = "0.12.3" tonic-build = "0.12.3"

@ -15,7 +15,7 @@ use crate::HostConfig;
use crate::global::APP_CONFIG_DIR; use crate::global::APP_CONFIG_DIR;
use crate::global::APP_NAME_PREFIX; use crate::global::APP_NAME_PREFIX;
use crate::global::USED_RESOURCES; use crate::global::USED_RESOURCES_PATH;
#[derive(Debug, Default, Deserialize, Serialize)] #[derive(Debug, Default, Deserialize, Serialize)]
pub struct HostResources { pub struct HostResources {
@ -34,13 +34,13 @@ impl HostResources {
// TODO: implement load and save // TODO: implement load and save
fn save_to_disk(&self) -> Result<()> { fn save_to_disk(&self) -> Result<()> {
let mut file = File::create(&*USED_RESOURCES)?; let mut file = File::create(&*USED_RESOURCES_PATH)?;
file.write_all(serde_yml::to_string(self)?.as_bytes())?; file.write_all(serde_yml::to_string(self)?.as_bytes())?;
Ok(()) Ok(())
} }
pub fn load_from_disk() -> Result<Self> { pub fn load_from_disk() -> Result<Self> {
let content = std::fs::read_to_string(&*USED_RESOURCES)?; let content = std::fs::read_to_string(&*USED_RESOURCES_PATH)?;
let res: Self = serde_yml::from_str(&content)?; let res: Self = serde_yml::from_str(&content)?;
Ok(res) Ok(res)
} }

@ -1,3 +1,8 @@
use anyhow::Result;
use ed25519_dalek::SigningKey;
use log::{info, warn};
use std::fs::File;
use std::io::Write;
use std::sync::LazyLock; use std::sync::LazyLock;
pub const NODE_PUBKEY: &str = "0xd0837609aedd53854651210327db90f5c2626188a00e940bbc9eea2c7e6838b7"; pub const NODE_PUBKEY: &str = "0xd0837609aedd53854651210327db90f5c2626188a00e940bbc9eea2c7e6838b7";
@ -11,15 +16,15 @@ pub const APP_NAME_PREFIX: &str = "dtpm";
const DETEE_DIR_ENV_NAME: &str = "DETEE_DIR"; const DETEE_DIR_ENV_NAME: &str = "DETEE_DIR";
// TODO: try lazy static later pub static IP_INFO: LazyLock<IPInfo> = LazyLock::new(|| get_ip_info().unwrap());
pub static USED_RESOURCES: LazyLock<String> = LazyLock::new(|| { pub static USED_RESOURCES_PATH: LazyLock<String> = LazyLock::new(|| {
let home = home::home_dir().unwrap().to_string_lossy().into_owned(); let home = home::home_dir().unwrap().to_string_lossy().into_owned();
std::env::var(DETEE_DIR_ENV_NAME) std::env::var(DETEE_DIR_ENV_NAME)
.unwrap_or(format!("{home}/.detee/app_daemon/used_resources.yaml")) .unwrap_or(format!("{home}/.detee/app_daemon/USED_RESOURCES_PATH.yaml"))
}); });
pub static DAEMON_CONFIG_DIR: LazyLock<String> = LazyLock::new(|| { pub static DAEMON_CONFIG_PATH: LazyLock<String> = LazyLock::new(|| {
let home = home::home_dir().unwrap().to_string_lossy().into_owned(); let home = home::home_dir().unwrap().to_string_lossy().into_owned();
std::env::var(DETEE_DIR_ENV_NAME).unwrap_or(format!("{home}/.detee/app_daemon/config.yaml")) std::env::var(DETEE_DIR_ENV_NAME).unwrap_or(format!("{home}/.detee/app_daemon/config.yaml"))
}); });
@ -28,3 +33,63 @@ pub static APP_CONFIG_DIR: LazyLock<String> = LazyLock::new(|| {
let home = home::home_dir().unwrap().to_string_lossy().into_owned(); let home = home::home_dir().unwrap().to_string_lossy().into_owned();
std::env::var(DETEE_DIR_ENV_NAME).unwrap_or(format!("{home}/.detee/app_daemon/deployed_apps/")) std::env::var(DETEE_DIR_ENV_NAME).unwrap_or(format!("{home}/.detee/app_daemon/deployed_apps/"))
}); });
pub static SECRET_KEY_PATH: LazyLock<String> = LazyLock::new(|| {
let home = home::home_dir().unwrap().to_string_lossy().into_owned();
std::env::var(DETEE_DIR_ENV_NAME)
.unwrap_or(format!("{home}/.detee/app_daemon/node_secret_key.pem"))
});
pub static PUBLIC_KEY: LazyLock<String> = LazyLock::new(get_public_key);
#[derive(serde::Deserialize, Clone)]
pub struct IPInfo {
pub country: String,
pub region: String,
pub city: String,
pub ip: String,
}
fn get_ip_info() -> anyhow::Result<IPInfo> {
let body = reqwest::blocking::get("https://ipinfo.io/".to_string())?.text()?;
log::info!("Got the following data from ipinfo.io: {body}");
Ok(serde_json::de::from_str(&body)?)
}
fn create_secret_key() -> Result<SigningKey> {
let key_path = SECRET_KEY_PATH.to_string();
info!("Creating new secret key at {}", key_path);
let sk = SigningKey::generate(&mut rand::rngs::OsRng);
let private_key_string = bs58::encode(sk.to_bytes()).into_string();
let mut file = File::create(key_path)?;
file.write_all(private_key_string.as_bytes())?;
Ok(sk)
}
fn load_secret_key() -> Result<ed25519_dalek::SigningKey> {
let secret_key_string = match std::fs::read_to_string(SECRET_KEY_PATH.to_string()) {
Ok(secret_key_pem) => secret_key_pem,
Err(e) => {
warn!("Could not load secret key due to error: {e:?}");
return create_secret_key();
}
};
Ok(SigningKey::from_bytes(
&bs58::decode(secret_key_string)
.into_vec()?
.try_into()
.map_err(|_| bs58::decode::Error::BufferTooSmall)?,
))
}
pub fn sign_message(msg: &str) -> Result<String> {
use ed25519_dalek::Signer;
let key = load_secret_key()?;
Ok(bs58::encode(key.sign(msg.as_bytes()).to_bytes()).into_string())
}
pub fn get_public_key() -> String {
let pubkey = bs58::encode(load_secret_key().unwrap().verifying_key().to_bytes()).into_string();
log::info!("Loaded the following public key: {pubkey}");
pubkey
}

@ -8,16 +8,20 @@ use tokio::sync::mpsc::Sender;
use tokio::task::JoinSet; use tokio::task::JoinSet;
use tokio_stream::wrappers::ReceiverStream; use tokio_stream::wrappers::ReceiverStream;
use tokio_stream::StreamExt; use tokio_stream::StreamExt;
use tonic::metadata::AsciiMetadataValue;
use tonic::transport::Channel; use tonic::transport::Channel;
use tonic::Request;
use crate::global::IP_INFO;
use crate::global::PUBLIC_KEY;
use crate::global::{ADMIN_PUBKEY, NODE_PUBKEY}; use crate::global::{ADMIN_PUBKEY, NODE_PUBKEY};
use crate::utils::IP_INFO;
pub struct ConnectionData { pub struct ConnectionData {
pub brain_url: String, pub brain_url: String,
pub brain_msg_tx: Sender<BrainMessageApp>, pub brain_msg_tx: Sender<BrainMessageApp>,
pub daemon_msg_rx: Receiver<DaemonMessageApp>, pub daemon_msg_rx: Receiver<DaemonMessageApp>,
pub daemon_msg_tx: Sender<DaemonMessageApp>, pub daemon_msg_tx: Sender<DaemonMessageApp>,
pub app_contracts_uuid: Vec<String>,
} }
pub async fn register_node(config: &crate::HostConfig) -> Result<Vec<AppContract>> { pub async fn register_node(config: &crate::HostConfig) -> Result<Vec<AppContract>> {
@ -34,9 +38,20 @@ pub async fn register_node(config: &crate::HostConfig) -> Result<Vec<AppContract
country: IP_INFO.country.clone(), country: IP_INFO.country.clone(),
}; };
let pubkey = PUBLIC_KEY.clone();
let timestamp = chrono::Utc::now().to_rfc3339();
let signature = crate::global::sign_message(&format!("{timestamp}{req:?}"))?;
let timestamp: AsciiMetadataValue = timestamp.parse()?;
let pubkey: AsciiMetadataValue = pubkey.parse()?;
let signature: AsciiMetadataValue = signature.parse()?;
let mut req = Request::new(req);
req.metadata_mut().insert("timestamp", timestamp);
req.metadata_mut().insert("pubkey", pubkey);
req.metadata_mut().insert("request-signature", signature);
let mut container_contracts = vec![]; let mut container_contracts = vec![];
let mut grpc_stream = client.register_node(req).await?.into_inner(); let mut grpc_stream = client.register_app_node(req).await?.into_inner();
while let Some(stream_update) = grpc_stream.next().await { while let Some(stream_update) = grpc_stream.next().await {
match stream_update { match stream_update {
Ok(contract) => { Ok(contract) => {
@ -60,7 +75,11 @@ pub async fn connect_and_run(conn_data: ConnectionData) -> Result<()> {
let mut streaming_tasks = JoinSet::new(); let mut streaming_tasks = JoinSet::new();
streaming_tasks.spawn(receive_messages(client.clone(), conn_data.brain_msg_tx)); streaming_tasks.spawn(receive_messages(
client.clone(),
conn_data.app_contracts_uuid.clone(),
conn_data.brain_msg_tx,
));
streaming_tasks.spawn(send_messages( streaming_tasks.spawn(send_messages(
client.clone(), client.clone(),
conn_data.daemon_msg_rx, conn_data.daemon_msg_rx,
@ -74,6 +93,7 @@ pub async fn connect_and_run(conn_data: ConnectionData) -> Result<()> {
pub async fn receive_messages( pub async fn receive_messages(
mut client: BrainAppDaemonClient<Channel>, mut client: BrainAppDaemonClient<Channel>,
_contracts: Vec<String>,
tx: Sender<BrainMessageApp>, tx: Sender<BrainMessageApp>,
) -> Result<()> { ) -> Result<()> {
let pubkey = NODE_PUBKEY.to_string(); let pubkey = NODE_PUBKEY.to_string();

@ -28,7 +28,7 @@ pub use crate::config::HostConfig;
pub use crate::data::HostResources; pub use crate::data::HostResources;
use global::APP_CONFIG_DIR; use global::APP_CONFIG_DIR;
use global::DAEMON_CONFIG_DIR; use global::DAEMON_CONFIG_PATH;
#[derive(Debug)] #[derive(Debug)]
pub struct AppHandler { pub struct AppHandler {
@ -43,7 +43,7 @@ impl AppHandler {
// TODO: load from config and resources from file, // TODO: load from config and resources from file,
// if not found use default and save host resources to file // if not found use default and save host resources to file
let host_config = match HostConfig::load_from_disk(&DAEMON_CONFIG_DIR) { let host_config = match HostConfig::load_from_disk(&DAEMON_CONFIG_PATH) {
Ok(config) => config, Ok(config) => config,
Err(e) => panic!("Could not load config: {e:?}"), Err(e) => panic!("Could not load config: {e:?}"),
}; };
@ -167,8 +167,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut app_handler = AppHandler::new(brain_msg_rx, daemon_msg_tx.clone()); let mut app_handler = AppHandler::new(brain_msg_rx, daemon_msg_tx.clone());
let brain_url = app_handler.host_config.brain_url.clone(); let brain_url = app_handler.host_config.brain_url.clone();
let mut contracts = vec![];
match grpc::register_node(&app_handler.host_config).await { match grpc::register_node(&app_handler.host_config).await {
Ok(app_contracts) => app_handler.handle_contracts(app_contracts).await, Ok(app_contracts) => {
contracts.append(&mut app_contracts.iter().map(|c| c.uuid.clone()).collect());
app_handler.handle_contracts(app_contracts).await
}
Err(e) => log::error!("Failed to connect to brain: {e}"), Err(e) => log::error!("Failed to connect to brain: {e}"),
} }
@ -183,6 +187,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
brain_msg_tx, brain_msg_tx,
daemon_msg_rx, daemon_msg_rx,
daemon_msg_tx, daemon_msg_tx,
app_contracts_uuid: contracts,
}) })
.await .await
{ {

@ -4,7 +4,6 @@ use rand::Rng;
use reqwest::Client; use reqwest::Client;
use std::io::BufReader; use std::io::BufReader;
use std::path::Path; use std::path::Path;
use std::sync::LazyLock;
use tar::Archive; use tar::Archive;
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener; use tokio::net::TcpListener;
@ -12,8 +11,6 @@ use tokio::{fs, fs::File};
use crate::global::{PACKAGE_ARCHIVE_DIR_PATH, PACKAGE_ARCHIVE_POSTFIX, PACKAGE_DIR_PATH}; use crate::global::{PACKAGE_ARCHIVE_DIR_PATH, PACKAGE_ARCHIVE_POSTFIX, PACKAGE_DIR_PATH};
pub static IP_INFO: LazyLock<IPInfo> = LazyLock::new(|| get_ip_info().unwrap());
pub async fn handle_package( pub async fn handle_package(
package_url: String, package_url: String,
container_uuid: String, container_uuid: String,
@ -90,19 +87,6 @@ async fn is_port_available(port: u16) -> bool {
.await .await
.is_ok() .is_ok()
} }
#[derive(serde::Deserialize, Clone)]
pub struct IPInfo {
pub country: String,
pub region: String,
pub city: String,
pub ip: String,
}
fn get_ip_info() -> anyhow::Result<IPInfo> {
let body = reqwest::blocking::get("https://ipinfo.io/".to_string())?.text()?;
log::info!("Got the following data from ipinfo.io: {body}");
Ok(serde_json::de::from_str(&body)?)
}
pub async fn cleanup_enclave_disk_and_package(container_uuid: String) -> Result<()> { pub async fn cleanup_enclave_disk_and_package(container_uuid: String) -> Result<()> {
let enclave_disk_dir_str = format!("{PACKAGE_DIR_PATH}/{container_uuid}"); let enclave_disk_dir_str = format!("{PACKAGE_DIR_PATH}/{container_uuid}");