Add opt-in physical USB device enrollment and remembered choices in 0.2.7

This commit is contained in:
tongtong committed 2026-11-14 04:06:01 +08:00
1 parent dc29a20a41
commit 208d37b7d8
20 files changed
+515 -18

No files matched your search

+1
View File
@@ -13,6 +13,7 @@ tracing.workspace = true
ads-management = { path = "../crates/ads-management" }
serde.workspace = true
serde_json.workspace = true
sha2 = "0.10"
tracing-subscriber.workspace = true
[target.'cfg(windows)'.dependencies]
+1
View File
@@ -2,6 +2,7 @@ mod adb_monitor;
mod gateway;
mod managed;
mod supervisor;
mod usb_discovery;
use ads_core::{valid_device_id, validate_token, NetworkArgs};
use ads_management::{credential, AgentConfig};
use anyhow::{bail, Context, Result};
+97 -2
View File
@@ -89,6 +89,7 @@ struct Runtime {
restart: watch::Sender<bool>,
supervised: bool,
instance: String,
ready: std::sync::atomic::AtomicBool,
}
impl Runtime {
fn reconcile(&self, state: &mut State) {
@@ -105,6 +106,7 @@ impl Runtime {
.clone()
.unwrap_or_else(|| adb_server.clone())
})
.chain(state.config.auto_register_usb.then(|| adb_server.clone()))
.collect();
state.monitors.retain(|server, _| servers.contains(server));
for server in servers {
@@ -242,6 +244,9 @@ impl Runtime {
if config.devices.iter().any(|d| d.id == device.id) {
bail!("device ID already exists")
};
if let Some(serial) = &device.adb_serial {
config.ignored_usb_serials.retain(|s| s != serial);
}
config.devices.push(device);
}
Request::DeviceRemove { id } => {
@@ -259,7 +264,16 @@ impl Runtime {
.context("device not found")?
.enabled = enabled;
}
Request::ConfigSet { config: new } => {
Request::ConfigSet {
config: new,
expected_config,
} => {
if expected_config
.as_ref()
.is_some_and(|expected| expected != &state.config)
{
bail!("Agent 配置已变化,请刷新后重试,避免覆盖自动发现或其他管理操作")
}
if new.id != config.id {
bail!("agent ID is immutable; initialize a separate agent to change identity")
};
@@ -267,6 +281,16 @@ impl Runtime {
}
_ => bail!("unsupported operation"),
}
// Deleting an ADB entry means "do not add it again" even after a restart.
for old in &state.config.devices {
if !config.devices.iter().any(|d| d.id == old.id) {
if let Some(serial) = &old.adb_serial {
if !config.ignored_usb_serials.contains(serial) {
config.ignored_usb_serials.push(serial.clone());
}
}
}
}
config.validate()?;
let changed_network = config.server != state.config.server
|| config.connect_address != state.config.connect_address
@@ -286,6 +310,63 @@ impl Runtime {
}
}
}
async fn discover_usb(&self) -> Result<()> {
if !self.ready.load(std::sync::atomic::Ordering::Acquire) {
return Ok(());
}
{
let state = self.state.lock().await;
if !state.config.auto_register_usb
|| !crate::usb_discovery::local_server(&state.config.adb_server)
{
return Ok(());
}
// Native PnP enumeration is only needed for new eligible ADB serials.
// Previewing candidates does not authorize or persist any device.
let online = match state
.monitors
.get(&state.config.adb_server)
.map(|m| m.receiver.borrow().clone())
{
Some(crate::adb_monitor::Snapshot::Devices(devices)) => devices
.into_iter()
.filter(|(_, s)| s == "device")
.map(|(serial, _)| serial)
.collect(),
_ => return Ok(()),
};
let mut preview = state.config.clone();
if crate::usb_discovery::add_online(&mut preview, &online, &online) == 0 {
return Ok(());
}
}
let physical = crate::usb_discovery::physical_serials().await?;
let mut state = self.state.lock().await;
let online = match state
.monitors
.get(&state.config.adb_server)
.map(|m| m.receiver.borrow().clone())
{
Some(crate::adb_monitor::Snapshot::Devices(devices)) => devices
.into_iter()
.filter(|(_, s)| s == "device")
.map(|(s, _)| s)
.collect(),
_ => return Ok(()),
};
let mut config = state.config.clone();
let count = crate::usb_discovery::add_online(&mut config, &online, &physical);
if count == 0 {
return Ok(());
}
config.validate()?;
ads_management::save_private(&self.path, &serde_json::to_vec_pretty(&config)?)?;
state.config = config;
state.revision += 1;
self.reconcile(&mut state);
tracing::info!(count, "physical USB devices automatically added");
Ok(())
}
async fn handle(&self, request: Request) -> Response {
match self.execute(request).await {
Ok(value) => value,
@@ -375,6 +456,7 @@ pub async fn run(path: PathBuf, config: AgentConfig, token: String) -> Result<bo
restart,
supervised: std::env::var("ADS_SUPERVISED").as_deref() == Ok("1"),
instance,
ready: std::sync::atomic::AtomicBool::new(false),
});
let handler: ads_management::ipc::Handler = {
let runtime = runtime.clone();
@@ -394,6 +476,9 @@ pub async fn run(path: PathBuf, config: AgentConfig, token: String) -> Result<bo
{
let mut state = runtime.state.lock().await;
runtime.reconcile(&mut state);
runtime
.ready
.store(true, std::sync::atomic::Ordering::Release);
}
let mut delay = 1;
loop {
@@ -405,7 +490,17 @@ pub async fn run(path: PathBuf, config: AgentConfig, token: String) -> Result<bo
}
};
tokio::pin!(networking);
let restart = tokio::select! {result=&mut ipc=>{result?;false},_=&mut networking=>false,result=restarting.changed()=>{result?;sleep(Duration::from_millis(400)).await;true},result=crate::supervisor::shutdown()=>{result?;false}};
let discovery = async {
let mut ticks = interval(Duration::from_secs(5));
loop {
ticks.tick().await;
if let Err(error) = runtime.discover_usb().await {
tracing::warn!(%error,"USB auto-registration scan failed");
}
}
};
tokio::pin!(discovery);
let restart = tokio::select! {_=&mut discovery=>false,result=&mut ipc=>{result?;false},_=&mut networking=>false,result=restarting.changed()=>{result?;sleep(Duration::from_millis(400)).await;true},result=crate::supervisor::shutdown()=>{result?;false}};
let mut state = runtime.state.lock().await;
state.workers.clear();
state.monitors.clear();
+194
View File
@@ -0,0 +1,194 @@
//! Fail closed: only native USB devices on a physical host controller are eligible.
use ads_management::{AgentConfig, DeviceConfig};
use sha2::{Digest, Sha256};
use std::collections::BTreeSet;
pub fn local_server(server: &str) -> bool {
server
.rsplit_once(':')
.is_some_and(|(host, _)| matches!(host, "127.0.0.1" | "localhost" | "[::1]"))
}
fn allowed_serial(serial: &str) -> bool {
!serial.is_empty()
&& serial.len() <= 256
&& !serial.chars().any(char::is_control)
&& !serial.to_ascii_lowercase().starts_with("ads-")
&& !serial.starts_with("emulator-")
&& !serial.contains(':')
}
pub fn add_online(
config: &mut AgentConfig,
online: &BTreeSet<String>,
physical: &BTreeSet<String>,
) -> usize {
if !config.auto_register_usb || !local_server(&config.adb_server) {
return 0;
}
let mut added = 0;
for serial in online.intersection(physical) {
if !allowed_serial(serial)
|| config.ignored_usb_serials.contains(serial)
|| config
.devices
.iter()
.any(|d| d.adb_serial.as_ref() == Some(serial))
|| config.devices.len() >= 128
{
continue;
}
let id = config
.usb_device_ids
.get(serial)
.cloned()
.unwrap_or_else(|| {
let hash = Sha256::digest(format!("{}:{serial}", config.id).as_bytes());
format!("usb-{:x}", hash)[..36].to_owned()
});
if config.devices.iter().any(|d| d.id == id)
|| (!config.usb_device_ids.contains_key(serial) && config.usb_device_ids.len() >= 512)
{
continue;
}
config.usb_device_ids.insert(serial.clone(), id.clone());
config.devices.push(DeviceConfig {
id,
target: None,
adb_serial: Some(serial.clone()),
adb_server: None,
device_port: 5555,
enabled: true,
});
added += 1;
}
added
}
#[cfg(target_os = "linux")]
pub async fn physical_serials() -> anyhow::Result<BTreeSet<String>> {
tokio::task::spawn_blocking(|| {
let mut serials = BTreeSet::new();
for entry in std::fs::read_dir("/sys/bus/usb/devices")? {
let Ok(path) = std::fs::canonicalize(entry?.path()) else {
continue;
};
let name = path.to_string_lossy().to_ascii_lowercase();
if name.contains("vhci") || !name.contains("/pci") {
continue;
}
let product = std::fs::read_to_string(path.join("product")).unwrap_or_default();
if product.to_ascii_lowercase().contains("ads virtual") {
continue;
}
if let Ok(serial) = std::fs::read_to_string(path.join("serial")) {
let serial = serial.trim();
if allowed_serial(serial) {
serials.insert(serial.to_owned());
}
}
}
Ok(serials)
})
.await?
}
#[cfg(windows)]
pub async fn physical_serials() -> anyhow::Result<BTreeSet<String>> {
// No interpolated serials or credentials; bounded child is killed on timeout/cancellation.
let script = r#"
$ErrorActionPreference='Stop'
[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)
$devices=Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -like 'USB\VID_*' -and $_.InstanceId -notlike '*&MI_*' }
foreach($d in $devices) {
if($d.FriendlyName -like '*ADS Virtual*') {continue}
$serial=($d.InstanceId -split '\\')[-1]
if($serial.Contains('&')) {continue}
$parent=$d.InstanceId;$physical=$false
for($i=0;$i -lt 16;$i++) {
if($parent -match '(?i)USBIP|VHCI|UDE|^ROOT\\') {break}
if($parent.StartsWith('PCI\',[StringComparison]::OrdinalIgnoreCase)) {$physical=$true;break}
$parent=(Get-PnpDeviceProperty -InstanceId $parent -KeyName 'DEVPKEY_Device_Parent' -ErrorAction SilentlyContinue).Data
if(!$parent) {break}
}
if($physical) {[Console]::WriteLine($serial)}
}
"#;
let exe = std::env::var_os("SystemRoot")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| r"C:\Windows".into())
.join("System32/WindowsPowerShell/v1.0/powershell.exe");
let mut command = tokio::process::Command::new(exe);
command
.args(["-NoProfile", "-NonInteractive", "-Command", script])
.kill_on_drop(true);
command.creation_flags(0x08000000);
let output =
tokio::time::timeout(std::time::Duration::from_secs(15), command.output()).await??;
anyhow::ensure!(output.status.success(), "native USB inventory failed");
Ok(String::from_utf8(output.stdout)?
.lines()
.map(str::trim)
.filter(|s| allowed_serial(s))
.map(str::to_owned)
.collect())
}
#[cfg(not(any(windows, target_os = "linux")))]
pub async fn physical_serials() -> anyhow::Result<BTreeSet<String>> {
anyhow::bail!("USB auto-registration requires Windows or Linux physical USB inventory")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registration_is_opt_in_and_preserves_user_choices() {
let mut c: AgentConfig = serde_json::from_value(
serde_json::json!({"id":"pc","name":"pc","server":"wss://example.com","devices":[]}),
)
.unwrap();
let online = [
"real",
"ignored",
"ADS-test",
"emulator-5554",
"192.168.1.2:5555",
"unauthorized",
]
.map(str::to_owned)
.into_iter()
.collect();
let physical = [
"real",
"ignored",
"ADS-test",
"emulator-5554",
"192.168.1.2:5555",
]
.map(str::to_owned)
.into_iter()
.collect();
assert_eq!(add_online(&mut c, &online, &physical), 0);
c.auto_register_usb = true;
c.ignored_usb_serials.push("ignored".into());
assert_eq!(add_online(&mut c, &online, &physical), 1);
let id = c.devices[0].id.clone();
c = serde_json::from_slice(&serde_json::to_vec(&c).unwrap()).unwrap();
c.devices[0].enabled = false;
c.devices[0].adb_server = Some("localhost:5037".into());
assert_eq!(add_online(&mut c, &online, &physical), 0);
assert!(!c.devices[0].enabled);
c.devices.clear();
assert_eq!(add_online(&mut c, &online, &physical), 1);
assert_eq!(c.devices[0].id, id);
c.adb_server = "192.168.1.5:5037".into();
c.devices.clear();
assert_eq!(add_online(&mut c, &online, &physical), 0);
}
}
#[cfg(all(test, windows))]
mod native_tests {
#[tokio::test]
async fn native_inventory_runs_without_a_visible_console() {
super::physical_serials()
.await
.expect("Windows PnP inventory");
}
}