mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-25 08:50:58 +01:00
Retain bounded authentication and add exact token request coverage
This commit is contained in:
commit
1982beb6a8
2 files changed
+25
-2
No files matched your search
@@ -16,6 +16,14 @@ use materialcraft_automation::security::{
|
||||
use materialcraft_ui_egui::ControlRequest;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "control_server.test.rs"]
|
||||
mod auth_tests;
|
||||
|
||||
fn auth_ok(token: &str, method: &str, params: &Value) -> bool {
|
||||
method == "auth" && params.get("token").and_then(Value::as_str).is_some_and(|t| token_matches(token, t))
|
||||
}
|
||||
|
||||
/// How long an authenticated connection may stay idle.
|
||||
const IDLE_TIMEOUT: Duration = Duration::from_secs(600);
|
||||
|
||||
@@ -123,8 +131,7 @@ fn serve(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, ctx: &egui
|
||||
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let params = msg.get("params").cloned().unwrap_or(json!({}));
|
||||
if deadline.is_some() {
|
||||
let supplied = params.get("token").and_then(Value::as_str).unwrap_or_default();
|
||||
if method != "auth" || !token_matches(token, supplied) {
|
||||
if !auth_ok(token, &method, ¶ms) {
|
||||
// One attempt per connection, as on `materialcraft-cli serve`.
|
||||
reply(&mut out, id, json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"}));
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
#[cfg(test)]
|
||||
mod auth_tests {
|
||||
use crate::control_server::auth_ok;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn only_the_exact_token_on_an_auth_request_passes() {
|
||||
let token = "0123456789abcdef0123456789abcdef";
|
||||
assert!(auth_ok(token, "auth", &json!({"token": token})));
|
||||
assert!(!auth_ok(token, "auth", &json!({"token": "0123456789abcdef0123456789abcdee"})));
|
||||
assert!(!auth_ok(token, "auth", &json!({"token": "short"})));
|
||||
assert!(!auth_ok(token, "auth", &json!({})));
|
||||
assert!(!auth_ok(token, "auth", &json!({"token": 5})));
|
||||
assert!(!auth_ok(token, "command.run", &json!({"token": token})));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user