Organize device inventory by customer and restrict token access to its audience
This commit is contained in:
+18
-83
@@ -1,6 +1,6 @@
|
||||
use axum::{
|
||||
Extension, Json,
|
||||
extract::{Path, Query, State},
|
||||
extract::State,
|
||||
http::{HeaderMap, StatusCode},
|
||||
};
|
||||
use chrono::Utc;
|
||||
@@ -41,37 +41,32 @@ pub async fn agent_job_signing_key(
|
||||
}
|
||||
job_signing_key(State(state), h, Extension(peer)).await
|
||||
}
|
||||
pub async fn device(
|
||||
State(state): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path((tenant, asset)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<Json<Value>, StatusCode> {
|
||||
let list = device_list(&state, &headers, tenant, Some(asset), Default::default()).await?;
|
||||
let item = list["items"]
|
||||
.as_array()
|
||||
.and_then(|items| {
|
||||
items
|
||||
.iter()
|
||||
.find(|i| i["asset_id"].as_str() == Some(asset.to_string().as_str()))
|
||||
})
|
||||
.cloned()
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
Ok(Json(item))
|
||||
}
|
||||
pub async fn tenants(
|
||||
State(state): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Value>, StatusCode> {
|
||||
let principal = state.auth.principal(&state, &headers, false).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, principal.tenant)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let can_manage = crate::customers::can_manage(&principal, &mut tx)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let mut items = Vec::new();
|
||||
for tenant in &principal.tenants {
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, *tenant)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
if crate::permissions::require_principal(&mut tx, &principal, "inventory:read")
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
// A bearer can have different effective scopes in each customer.
|
||||
let has_read = (principal.name.starts_with("mcp:")
|
||||
|| principal.permits_scope("inventory:read"))
|
||||
&& crate::permissions::allowed(&mut tx, &principal.name, "inventory:read")
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
if !has_read {
|
||||
continue;
|
||||
}
|
||||
let rows = sqlx::query("SELECT tenant_id,name FROM tenants")
|
||||
@@ -89,66 +84,6 @@ pub async fn tenants(
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
Ok(Json(
|
||||
json!({"items": items, "next_cursor":null,"completeness":"complete","truncated":false,"as_of":Utc::now()}),
|
||||
json!({"items": items, "can_manage_customers":can_manage, "next_cursor":null,"completeness":"complete","truncated":false,"as_of":Utc::now()}),
|
||||
))
|
||||
}
|
||||
pub async fn devices(
|
||||
State(state): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path(tenant): Path<Uuid>,
|
||||
) -> Result<Json<Value>, StatusCode> {
|
||||
Ok(Json(
|
||||
device_list(&state, &headers, tenant, None, Default::default()).await?,
|
||||
))
|
||||
}
|
||||
pub async fn devices_page(
|
||||
State(state): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path(tenant): Path<Uuid>,
|
||||
Query(page): Query<crate::pagination::PageQuery>,
|
||||
) -> Result<Json<Value>, StatusCode> {
|
||||
Ok(Json(device_list(&state, &h, tenant, None, page).await?))
|
||||
}
|
||||
async fn device_list(
|
||||
state: &crate::State,
|
||||
headers: &HeaderMap,
|
||||
tenant: Uuid,
|
||||
asset: Option<Uuid>,
|
||||
query: crate::pagination::PageQuery,
|
||||
) -> Result<Value, StatusCode> {
|
||||
if identity(state, headers).await? != tenant {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let principal = state.auth.principal(state, headers, false).await?;
|
||||
crate::permissions::require_principal(&mut tx, &principal, "inventory:read")
|
||||
.await
|
||||
.map_err(|e| e.0)?;
|
||||
let mut page =
|
||||
crate::pagination::Cursor::parse(state, &principal, "devices:agent_id:asc", query)?;
|
||||
let rows = sqlx::query("SELECT a.agent_id,a.asset_id,a.revoked_at,a.last_contact_at,a.certificate_sha256,a.last_authenticated_certificate_sha256,a.last_authenticated_at,a.reported_agent_version,a.capabilities,a.enrollment_generation,a.assignment_version,o.observed_at,o.received_at,o.data,o.source_id FROM agent_installations a LEFT JOIN LATERAL (SELECT observed_at,received_at,data,source_id FROM observations WHERE tenant_id=a.tenant_id AND agent_id=a.agent_id AND source_id IN ('linux.base','windows.base') AND received_at<=$2 ORDER BY observed_at DESC, received_at DESC LIMIT 1) o ON true WHERE ($1::uuid IS NULL OR a.asset_id=$1) AND a.agent_id>$3 AND a.created_at<=$2 ORDER BY a.agent_id LIMIT $4")
|
||||
.bind(asset)
|
||||
.bind(page.as_of).bind(page.last).bind(i64::from(page.limit)+1)
|
||||
.fetch_all(&mut *tx).await.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let truncated = rows.len() > usize::from(page.limit);
|
||||
let items = rows.iter().take(usize::from(page.limit)).map(|r| {
|
||||
let last: Option<chrono::DateTime<Utc>> = r.get("last_contact_at");
|
||||
let revoked: Option<chrono::DateTime<Utc>> = r.get("revoked_at");
|
||||
let age = last.map(|t| (Utc::now()-t).num_seconds());
|
||||
let presence = if revoked.is_some() { "revoked" } else { match age { None=>"never_seen",Some(n) if n<90=>"online",Some(n) if n<180=>"stale",_=>"unreachable" } };
|
||||
json!({"agent_id":r.get::<Uuid,_>("agent_id"),"asset_id":r.get::<Uuid,_>("asset_id"),"agent_version":r.get::<Option<String>,_>("reported_agent_version"),"certificate_sha256":r.get::<String,_>("certificate_sha256"),"last_authenticated_certificate_sha256":r.get::<Option<String>,_>("last_authenticated_certificate_sha256"),"last_authenticated_at":r.get::<Option<chrono::DateTime<Utc>>,_>("last_authenticated_at"),"capabilities":r.get::<Value,_>("capabilities"),"enrollment_generation":r.get::<i64,_>("enrollment_generation"),"assignment_version":r.get::<i64,_>("assignment_version"),"presence":presence,"last_contact_at":last,"inventory":r.get::<Option<Value>,_>("data"),"observed_at":r.get::<Option<chrono::DateTime<Utc>>,_>("observed_at"),"received_at":r.get::<Option<chrono::DateTime<Utc>>,_>("received_at"),"source_id":r.get::<Option<String>,_>("source_id"),"quality":if r.get::<Option<Value>,_>("data").is_some(){"valid"}else{"unknown"},"completeness":"partial","health":"unknown"})
|
||||
}).collect::<Vec<_>>();
|
||||
let next = if truncated {
|
||||
Some(page.next(state, rows[usize::from(page.limit) - 1].get("agent_id"))?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(
|
||||
json!({"items":items,"next_cursor":next,"completeness":if truncated{"partial"}else{"complete"},"truncated":truncated,"as_of":page.as_of}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -261,13 +261,26 @@ impl Auth {
|
||||
}
|
||||
p
|
||||
};
|
||||
if p.name.starts_with("local:")
|
||||
&& !self
|
||||
if p.name.starts_with("local:") {
|
||||
let home = self
|
||||
.local
|
||||
.as_ref()
|
||||
.is_some_and(|local| local.enabled(&p.name, p.tenant))
|
||||
{
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
.and_then(|local| local.home(&p.name))
|
||||
.ok_or(StatusCode::FORBIDDEN)?;
|
||||
let tenants: Vec<Uuid> = sqlx::query_scalar("SELECT local_customer_tenants($1,$2)")
|
||||
.bind(&p.name)
|
||||
.bind(home)
|
||||
.fetch_one(&state.pool)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
if !tenants.contains(&home) {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
p.tenant = selected.unwrap_or(home);
|
||||
if !tenants.contains(&p.tenant) {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
p.tenants = tenants;
|
||||
}
|
||||
if selected.is_some_and(|t| t != p.tenant) {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Fresh-device bootstrap. Public scripts contain no credentials. Downloads use
|
||||
//! the tenant's one-time enrollment token until the final enrollment consumes it.
|
||||
use super::*;
|
||||
mod starter;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -22,7 +23,7 @@ struct TenantPins { current: Pin, previous: Vec<Previous> }
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct UpdaterQuery { platform: Platform, sha256: Option<String> }
|
||||
|
||||
fn config(platform: Platform, tenant: Uuid, wanted: Option<&str>) -> Result<Config, Error> {
|
||||
async fn config(s: &crate::State, platform: Platform, tenant: Uuid, wanted: Option<&str>) -> Result<Config, Error> {
|
||||
let slot = match platform {
|
||||
Platform::LinuxX64 => "RMM_AGENT_BOOTSTRAP_LINUX_FILE",
|
||||
Platform::WindowsX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_FILE",
|
||||
@@ -42,6 +43,15 @@ fn config(platform: Platform, tenant: Uuid, wanted: Option<&str>) -> Result<Conf
|
||||
};
|
||||
config.updater_sha256 = selected.sha256;
|
||||
config.updater_bytes = selected.bytes;
|
||||
} else {
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
let pin = sqlx::query("SELECT sha256,size_bytes FROM customer_starter_workers WHERE platform=$1")
|
||||
.bind(platform_name(platform)).fetch_optional(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
if let Some(pin) = pin {
|
||||
config.updater_sha256 = pin.get("sha256");
|
||||
config.updater_bytes = pin.get::<i64, _>("size_bytes") as u64;
|
||||
}
|
||||
}
|
||||
if wanted.is_some_and(|digest| digest != config.updater_sha256) { return Err(missing()); }
|
||||
let url = url::Url::parse(&config.gateway_origin).map_err(|_| invalid())?;
|
||||
@@ -98,6 +108,7 @@ pub(super) async fn issue(
|
||||
let mut bytes = [0; 32];
|
||||
openssl::rand::rand_bytes(&mut bytes).map_err(|_| fail("TOKEN_GENERATION_FAILED"))?;
|
||||
let token = hex::encode(bytes);
|
||||
starter::publish_missing(&mut tx, t).await?;
|
||||
let release_platforms: Vec<String> =
|
||||
sqlx::query_scalar("SELECT DISTINCT platform FROM agent_update_releases ORDER BY platform")
|
||||
.fetch_all(&mut *tx)
|
||||
@@ -170,7 +181,7 @@ pub(super) async fn current(
|
||||
Query(q): Query<Current>,
|
||||
) -> Result<Response, Error> {
|
||||
let t = token_tenant(&s, &headers).await?;
|
||||
let c = config(q.platform, t, None)?;
|
||||
let c = config(&s, q.platform, t, None).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
||||
let release: Uuid = sqlx::query_scalar("SELECT release_id FROM agent_update_releases WHERE platform=$1 ORDER BY release_sequence DESC LIMIT 1")
|
||||
.bind(platform_name(q.platform)).fetch_optional(&mut *tx).await?.ok_or_else(missing)?;
|
||||
@@ -217,6 +228,6 @@ pub(super) async fn updater(
|
||||
Query(q): Query<UpdaterQuery>,
|
||||
) -> Result<Response, Error> {
|
||||
let tenant = token_tenant(&s, &headers).await?;
|
||||
let c = config(q.platform, tenant, q.sha256.as_deref())?;
|
||||
let c = config(&s, q.platform, tenant, q.sha256.as_deref()).await?;
|
||||
verified_binary(tenant, c.updater_sha256, c.updater_bytes).await
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Seed empty platform catalogs from the operator's protected distribution
|
||||
//! directory during enrollment. Every download still uses the customer's own
|
||||
//! catalog, stable-worker pin and verified object store.
|
||||
use super::*;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Starter {
|
||||
envelope: ReleaseEnvelope,
|
||||
worker: Pin,
|
||||
}
|
||||
|
||||
pub(super) async fn publish_missing(tx: &mut Transaction<'_, Postgres>, tenant: Uuid) -> Result<(), Error> {
|
||||
let Some(slot) = std::env::var_os("RMM_AGENT_BOOTSTRAP_LINUX_FILE") else { return Ok(()) };
|
||||
let Some(config_dir) = FsPath::new(&slot).parent() else { return Err(invalid()) };
|
||||
let distribution = config_dir.join("customer-starters");
|
||||
if !distribution.try_exists().map_err(|_| fail("STARTER_CONFIGURATION"))? { return Ok(()) }
|
||||
for platform in [Platform::LinuxX64, Platform::WindowsGnuX64, Platform::WindowsX64] {
|
||||
let name = platform_name(platform);
|
||||
let exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT FROM agent_update_releases WHERE platform=$1)")
|
||||
.bind(name).fetch_one(&mut **tx).await?;
|
||||
if exists { continue; }
|
||||
let path = distribution.join(format!("{name}.json"));
|
||||
if !path.try_exists().map_err(|_| fail("STARTER_CONFIGURATION"))? { continue; }
|
||||
// Other requests may be publishing the first package for this customer.
|
||||
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 312))")
|
||||
.bind(format!("{tenant}/{name}")).execute(&mut **tx).await?;
|
||||
let exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT FROM agent_update_releases WHERE platform=$1)")
|
||||
.bind(name).fetch_one(&mut **tx).await?;
|
||||
if exists { continue; }
|
||||
let package: Starter = serde_json::from_slice(&protected_file(&path, 65536)?)?;
|
||||
let manifest = verify_envelope(&package.envelope, None)?;
|
||||
if manifest.platform != platform { return Err(invalid()); }
|
||||
let root = std::env::var("RMM_AGENT_UPDATE_ARTIFACT_DIR").map_err(|_| fail("STARTER_STORE"))?;
|
||||
if !FsPath::new(&root).is_absolute() { return Err(invalid()); }
|
||||
let owner = fs::symlink_metadata(&path).map_err(|_| fail("STARTER_CONFIGURATION"))?.uid();
|
||||
let src = distribution.clone();
|
||||
let mut files: Vec<_> = manifest.artifacts.iter().map(|a| (a.sha256.clone(),a.bytes)).collect();
|
||||
files.push((package.worker.sha256.clone(), package.worker.bytes));
|
||||
tokio::task::spawn_blocking(move || -> Result<(), Error> {
|
||||
let store = UpdateArtifacts::private_directory(root.into(), owner)?;
|
||||
for (digest, size) in files {
|
||||
let mut staged = store.begin(tenant,&digest,size)?;
|
||||
let mut file = fs::OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
|
||||
.open(src.join(&digest)).map_err(|_| fail("STARTER_OBJECT_MISSING"))?;
|
||||
let meta = file.metadata().map_err(|_| fail("STARTER_OBJECT_METADATA"))?;
|
||||
if !meta.is_file() || meta.uid()!=owner || meta.mode() & 0o777 != 0o600 || meta.len()!=size { return Err(fail("STARTER_OBJECT_METADATA")); }
|
||||
let mut buffer = [0; 65536];
|
||||
loop {
|
||||
let n = file.read(&mut buffer).map_err(|_| fail("STARTER_OBJECT_READ"))?;
|
||||
if n == 0 { break; }
|
||||
staged.append(&buffer[..n])?;
|
||||
}
|
||||
staged.finish(&store,tenant)?;
|
||||
}
|
||||
Ok(())
|
||||
}).await.map_err(|_| fail("STARTER_OBJECT_COPY"))??;
|
||||
for artifact in &manifest.artifacts {
|
||||
sqlx::query("INSERT INTO agent_update_artifacts(tenant_id,artifact_id,sha256,size_bytes) VALUES($1,$2,$3,$4) ON CONFLICT DO NOTHING")
|
||||
.bind(tenant).bind(artifact.artifact_id).bind(&artifact.sha256).bind(artifact.bytes as i64).execute(&mut **tx).await?;
|
||||
}
|
||||
let raw = encode(&package.envelope)?;
|
||||
let a = &manifest.artifacts[0];
|
||||
let h = &manifest.artifacts[1];
|
||||
sqlx::query("INSERT INTO agent_update_releases(tenant_id,release_id,platform,release_sequence,manifest_sha256,envelope_sha256,envelope,agent_artifact_id,agent_sha256,agent_bytes,helper_artifact_id,helper_sha256,helper_bytes) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)")
|
||||
.bind(tenant).bind(manifest.release_id).bind(name).bind(i64::try_from(manifest.release_sequence).map_err(|_|invalid())?)
|
||||
.bind(hash(&package.envelope.decode().map_err(|_|invalid())?.payload_bytes)).bind(hash(&raw)).bind(raw)
|
||||
.bind(a.artifact_id).bind(&a.sha256).bind(a.bytes as i64).bind(h.artifact_id).bind(&h.sha256).bind(h.bytes as i64).execute(&mut **tx).await?;
|
||||
sqlx::query("INSERT INTO customer_starter_workers VALUES($1,$2,$3,$4)")
|
||||
.bind(tenant).bind(name).bind(package.worker.sha256).bind(package.worker.bytes as i64).execute(&mut **tx).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -25,6 +25,10 @@ pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/revocation",
|
||||
post(revoke_device),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/archive",
|
||||
post(archive_device),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/operation-plans/{plan}/revocation",
|
||||
post(revoke_plan),
|
||||
@@ -63,6 +67,39 @@ async fn audit(
|
||||
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,$4,$5,now())").bind(p.tenant).bind(Uuid::new_v4()).bind(&p.name).bind(event).bind(json!({"decision":data,"session_hash":p.session_hash,"approval_origin":p.approval_origin(),"testsimulation":p.testsimulation})).execute(&mut **tx).await?;
|
||||
Ok(())
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Archive {
|
||||
archived: bool,
|
||||
}
|
||||
async fn archive_device(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path((tenant, asset)): Path<(Uuid, Uuid)>,
|
||||
Json(input): Json<Archive>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let event = if input.archived {
|
||||
"device_archived"
|
||||
} else {
|
||||
"device_restored"
|
||||
};
|
||||
let (p, mut tx) = context(&s, &h, tenant, "devices:revoke", event).await?;
|
||||
let current: Option<chrono::DateTime<chrono::Utc>> = sqlx::query_scalar(
|
||||
"SELECT archived_at FROM assets WHERE tenant_id=$1 AND asset_id=$2 FOR UPDATE",
|
||||
)
|
||||
.bind(tenant)
|
||||
.bind(asset)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
||||
if current.is_some() != input.archived {
|
||||
sqlx::query("UPDATE assets SET archived_at=CASE WHEN $3 THEN now() END WHERE tenant_id=$1 AND asset_id=$2")
|
||||
.bind(tenant).bind(asset).bind(input.archived).execute(&mut *tx).await?;
|
||||
audit(&mut tx, &p, event, json!({"asset_id":asset})).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Json(json!({"asset_id":asset, "archived":input.archived})))
|
||||
}
|
||||
pub async fn revoke_device(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//! Customer directory administration. Customer IDs are the existing tenant IDs.
|
||||
use crate::{auth::Principal, jobs::Error};
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Transaction};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub fn database_error(e: sqlx::Error) -> Error {
|
||||
match e.as_database_error().and_then(|e| e.code()).as_deref() {
|
||||
Some("23505") => Error(StatusCode::CONFLICT, "CUSTOMER_ALREADY_EXISTS"),
|
||||
Some("42501") => Error(StatusCode::FORBIDDEN, "FORBIDDEN"),
|
||||
Some("22023") => Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"),
|
||||
_ => e.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn can_manage(
|
||||
p: &Principal,
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
) -> Result<bool, sqlx::Error> {
|
||||
if p.testsimulation
|
||||
|| p.session_hash.is_none()
|
||||
|| p.csrf.is_none()
|
||||
|| !p.name.starts_with("local:")
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
sqlx::query_scalar("SELECT is_customer_admin($1)")
|
||||
.bind(&p.name)
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Input {
|
||||
name: String,
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(state): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Json(input): Json<Input>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
manage(&state, &headers, input, None).await
|
||||
}
|
||||
pub async fn rename(
|
||||
State(state): State<crate::State>,
|
||||
Path(id): Path<Uuid>,
|
||||
headers: HeaderMap,
|
||||
Json(input): Json<Input>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
manage(&state, &headers, input, Some(id)).await
|
||||
}
|
||||
async fn manage(
|
||||
state: &crate::State,
|
||||
headers: &HeaderMap,
|
||||
input: Input,
|
||||
existing: Option<Uuid>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let p = state
|
||||
.auth
|
||||
.principal(state, headers, true)
|
||||
.await
|
||||
.map_err(|s| Error(s, crate::auth::error_code(s)))?;
|
||||
if input.name.is_empty()
|
||||
|| input.name.trim() != input.name
|
||||
|| input.name.chars().count() > 120
|
||||
|| input.name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
if existing.is_some_and(|id| id != p.tenant) {
|
||||
return Err(Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, p.tenant).await?;
|
||||
if !can_manage(&p, &mut tx).await? {
|
||||
return Err(Error(StatusCode::FORBIDDEN, "CUSTOMER_ADMIN_REQUIRED"));
|
||||
}
|
||||
let id = existing.unwrap_or_else(Uuid::new_v4);
|
||||
sqlx::query("SELECT manage_customer($1,$2,$3,$4)")
|
||||
.bind(&p.name)
|
||||
.bind(id)
|
||||
.bind(&input.name)
|
||||
.bind(existing.is_none())
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(database_error)?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(json!({"tenant_id":id,"name":input.name})))
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
WITH classified AS (
|
||||
SELECT a.tenant_id,a.asset_id,a.agent_id,a.created_at,a.revoked_at,a.last_contact_at,
|
||||
a.last_authenticated_at,a.last_authenticated_certificate_sha256,a.certificate_sha256,
|
||||
a.enrollment_generation,a.assignment_version,a.capabilities,a.reported_agent_version,
|
||||
asset.archived_at,t.name AS customer_name,
|
||||
CASE
|
||||
WHEN a.revoked_at IS NOT NULL THEN 'revoked'
|
||||
WHEN asset.archived_at IS NOT NULL THEN 'archived'
|
||||
WHEN a.last_contact_at IS NULL THEN 'never_seen'
|
||||
WHEN a.last_authenticated_at IS NULL THEN 'unverified'
|
||||
WHEN EXISTS (
|
||||
SELECT 1 FROM agent_installations newer
|
||||
WHERE newer.tenant_id=a.tenant_id AND newer.asset_id=a.asset_id
|
||||
AND newer.enrollment_generation>a.enrollment_generation
|
||||
AND newer.last_contact_at IS NOT NULL AND newer.last_authenticated_at IS NOT NULL
|
||||
AND newer.created_at<=$2
|
||||
) THEN 'replaced'
|
||||
ELSE 'current'
|
||||
END AS lifecycle,
|
||||
CASE WHEN a.last_contact_at IS NULL THEN 'never_seen'
|
||||
WHEN a.last_contact_at>$2::timestamptz-interval '90 seconds' THEN 'online'
|
||||
ELSE 'offline' END AS status
|
||||
FROM agent_installations a
|
||||
JOIN assets asset USING (tenant_id,asset_id)
|
||||
JOIN tenants t USING(tenant_id)
|
||||
WHERE a.tenant_id=$1 AND a.created_at<=$2 AND a.agent_id>$3
|
||||
AND ($4::uuid IS NULL OR a.asset_id=$4)
|
||||
AND ($5::uuid IS NULL OR a.agent_id=$5)
|
||||
)
|
||||
SELECT c.*,o.observed_at,o.received_at,o.data,o.source_id FROM classified c
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT observed_at,received_at,data,source_id FROM observations
|
||||
WHERE tenant_id=c.tenant_id AND agent_id=c.agent_id AND received_at<=$2
|
||||
AND source_id IN ('linux.base','windows.base')
|
||||
ORDER BY observed_at DESC,received_at DESC,sequence DESC LIMIT 1
|
||||
) o ON true
|
||||
WHERE ($6::text IS NULL OR (c.lifecycle='current')=($6='current'))
|
||||
AND ($7::text IS NULL OR c.status=$7)
|
||||
AND ($8='' OR strpos(lower(o.data->>'hostname'),lower($8))>0)
|
||||
ORDER BY CASE WHEN $4 IS NOT NULL THEN (c.lifecycle='current') END DESC,
|
||||
CASE WHEN $4 IS NOT NULL THEN c.enrollment_generation END DESC,
|
||||
CASE WHEN $4 IS NOT NULL THEN c.created_at END DESC, c.agent_id
|
||||
LIMIT $9
|
||||
@@ -0,0 +1,478 @@
|
||||
//! Visible inventory for the fleet and for a single customer. Each database
|
||||
//! read stays inside an authorized customer's transaction, including pagination.
|
||||
use crate::{
|
||||
jobs::Error,
|
||||
pagination::{Cursor, PageQuery},
|
||||
};
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, Query, State},
|
||||
http::{HeaderMap, HeaderValue, StatusCode},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Row, Transaction, postgres::PgRow};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Default, Deserialize, Serialize, schemars::JsonSchema, Clone, Copy)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum View {
|
||||
#[default]
|
||||
Current,
|
||||
History,
|
||||
}
|
||||
impl View {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Current => "current",
|
||||
Self::History => "history",
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Deserialize, Serialize, schemars::JsonSchema, Clone, Copy)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Status {
|
||||
Online,
|
||||
Offline,
|
||||
}
|
||||
impl Status {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Online => "online",
|
||||
Self::Offline => "offline",
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Default, Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Filters {
|
||||
pub cursor: Option<String>,
|
||||
pub limit: Option<u16>,
|
||||
#[serde(default)]
|
||||
pub view: View,
|
||||
pub status: Option<Status>,
|
||||
pub q: Option<String>,
|
||||
}
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DetailQuery {
|
||||
pub agent_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
pub async fn page(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path(tenant): Path<Uuid>,
|
||||
Query(q): Query<Filters>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
list(&s, &h, Some(tenant), q).await.map(Json)
|
||||
}
|
||||
pub async fn all(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Query(q): Query<Filters>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
list(&s, &h, None, q).await.map(Json)
|
||||
}
|
||||
|
||||
struct Selection<'a> {
|
||||
tenant: Uuid,
|
||||
asset: Option<Uuid>,
|
||||
agent: Option<Uuid>,
|
||||
view: Option<View>,
|
||||
status: Option<Status>,
|
||||
hostname: &'a str,
|
||||
last: Uuid,
|
||||
as_of: DateTime<Utc>,
|
||||
limit: i64,
|
||||
}
|
||||
impl Selection<'_> {
|
||||
async fn rows(&self, tx: &mut Transaction<'_, Postgres>) -> Result<Vec<PgRow>, Error> {
|
||||
Ok(sqlx::query(include_str!("device_list.sql"))
|
||||
.bind(self.tenant)
|
||||
.bind(self.as_of)
|
||||
.bind(self.last)
|
||||
.bind(self.asset)
|
||||
.bind(self.agent)
|
||||
.bind(self.view.map(View::name))
|
||||
.bind(self.status.map(Status::name))
|
||||
.bind(self.hostname)
|
||||
.bind(self.limit)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
s: &crate::State,
|
||||
h: &HeaderMap,
|
||||
tenant: Option<Uuid>,
|
||||
q: Filters,
|
||||
) -> Result<Value, Error> {
|
||||
let p = crate::jobs::principal(s, h, false).await?;
|
||||
let mut tenants = match tenant {
|
||||
Some(id) => {
|
||||
crate::jobs::scope(&p, id, false)?;
|
||||
vec![id]
|
||||
}
|
||||
None => p.tenants.clone(),
|
||||
};
|
||||
tenants.sort_unstable();
|
||||
tenants.dedup();
|
||||
let hostname = q.q.as_deref().unwrap_or("").trim();
|
||||
if hostname.len() > 255 || hostname.chars().any(char::is_control) {
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
let binding = json!([tenant, tenants, q.view, q.status, hostname]);
|
||||
let scope = format!(
|
||||
"device-fleet:{}",
|
||||
rmm_domain::jobs::hash(binding.to_string().as_bytes())
|
||||
);
|
||||
let mut page = Cursor::parse(
|
||||
s,
|
||||
&p,
|
||||
&scope,
|
||||
PageQuery {
|
||||
cursor: q.cursor,
|
||||
limit: q.limit,
|
||||
},
|
||||
)
|
||||
.map_err(|code| Error(code, crate::auth::error_code(code)))?;
|
||||
let capacity = usize::from(page.limit);
|
||||
let mut items = Vec::new();
|
||||
let mut last = None;
|
||||
let mut truncated = false;
|
||||
let mut authorized = false;
|
||||
for customer in tenants {
|
||||
if page.last_tenant.is_some_and(|after| customer < after) {
|
||||
continue;
|
||||
}
|
||||
let mut headers = h.clone();
|
||||
headers.insert(
|
||||
"x-rmm-tenant",
|
||||
HeaderValue::from_str(&customer.to_string())
|
||||
.map_err(|_| Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"))?,
|
||||
);
|
||||
let current = crate::jobs::principal(s, &headers, false).await?;
|
||||
crate::jobs::scope(¤t, customer, false)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, customer).await?;
|
||||
match crate::permissions::require_principal(&mut tx, ¤t, "inventory:read").await {
|
||||
Err(Error(StatusCode::FORBIDDEN, _)) if tenant.is_none() => continue,
|
||||
other => other?,
|
||||
}
|
||||
authorized = true;
|
||||
let rows = Selection {
|
||||
tenant: customer,
|
||||
asset: None,
|
||||
agent: None,
|
||||
view: Some(q.view),
|
||||
status: q.status,
|
||||
hostname,
|
||||
last: if page.last_tenant == Some(customer) {
|
||||
page.last
|
||||
} else {
|
||||
Uuid::nil()
|
||||
},
|
||||
as_of: page.as_of,
|
||||
limit: (capacity + 1 - items.len()) as i64,
|
||||
}
|
||||
.rows(&mut tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
for row in rows {
|
||||
if items.len() == capacity {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
last = Some((customer, row.get::<Uuid, _>("agent_id")));
|
||||
items.push(project(&row, page.as_of, tenant.is_some()));
|
||||
}
|
||||
if truncated {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !authorized {
|
||||
return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
|
||||
}
|
||||
let next = if let Some((customer, agent)) = last.filter(|_| truncated) {
|
||||
page.last_tenant = Some(customer);
|
||||
Some(
|
||||
page.next(s, agent)
|
||||
.map_err(|code| Error(code, crate::auth::error_code(code)))?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(
|
||||
json!({"items":items,"next_cursor":next,"truncated":truncated,"completeness":if truncated{"partial"}else{"complete"},"as_of":page.as_of}),
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn detail(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path((tenant, asset)): Path<(Uuid, Uuid)>,
|
||||
Query(query): Query<DetailQuery>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let p = crate::jobs::principal(&s, &h, false).await?;
|
||||
crate::jobs::scope(&p, tenant, false)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
|
||||
let now = Utc::now();
|
||||
let row = Selection {
|
||||
tenant,
|
||||
asset: Some(asset),
|
||||
agent: query.agent_id,
|
||||
view: None,
|
||||
status: None,
|
||||
hostname: "",
|
||||
last: Uuid::nil(),
|
||||
as_of: now,
|
||||
limit: 1,
|
||||
}
|
||||
.rows(&mut tx)
|
||||
.await?
|
||||
.pop()
|
||||
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
||||
let mut item = project(&row, now, true);
|
||||
item["volumes"] = volumes(&item["inventory"]);
|
||||
item["recent_jobs"] = if p.permits_scope("operations:read")
|
||||
&& crate::permissions::allowed(&mut tx, &p.name, "operations:read").await?
|
||||
{
|
||||
sqlx::query_scalar::<_,Value>("SELECT jsonb_build_object('job_id',j.job_id,'operation_id',j.operation_id,'state',j.state,'created_at',r.created_at) FROM jobs j JOIN approval_requests r USING(tenant_id,operation_id) WHERE j.tenant_id=$1 AND j.asset_id=$2 AND j.agent_id=$3 ORDER BY r.created_at DESC,j.job_id LIMIT 20")
|
||||
.bind(tenant).bind(asset).bind(row.get::<Uuid,_>("agent_id")).fetch_all(&mut *tx).await?.into()
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
tx.commit().await?;
|
||||
Ok(Json(item))
|
||||
}
|
||||
|
||||
fn observed<'a>(data: &'a Value, scope: &str) -> &'a Value {
|
||||
data["observations"]
|
||||
.as_array()
|
||||
.and_then(|items| {
|
||||
items
|
||||
.iter()
|
||||
.find(|o| o["scope"] == scope && o["quality"] == "valid")
|
||||
})
|
||||
.map(|o| &o["data"])
|
||||
.unwrap_or(&Value::Null)
|
||||
}
|
||||
fn volumes(data: &Value) -> Value {
|
||||
let mut items = Vec::new();
|
||||
if let Some(rows) = observed(data, "linux.volumes").as_array() {
|
||||
for entry in rows.iter().filter(|entry| entry["quality"] == "valid") {
|
||||
let v = &entry["data"];
|
||||
if v["mount_point"].is_string() {
|
||||
items.push(json!({"name":v["mount_point"],"free_bytes":v["available_bytes"].as_u64(),"total_bytes":v["total_bytes"].as_u64()}));
|
||||
}
|
||||
}
|
||||
}
|
||||
if items.is_empty() && data["root_total_bytes"].is_number() {
|
||||
let name = if observed(data, "windows.volumes").is_object() {
|
||||
"Systemvolume"
|
||||
} else {
|
||||
"/"
|
||||
};
|
||||
items.push(json!({"name":name,"free_bytes":data["root_available_bytes"],"total_bytes":data["root_total_bytes"]}));
|
||||
}
|
||||
items.into()
|
||||
}
|
||||
fn os_label(data: &Value) -> Option<String> {
|
||||
let raw = data["os"].as_str()?;
|
||||
if let Some(pretty) = observed(data, "linux.os")["release"]["PRETTY_NAME"].as_str() {
|
||||
return Some(pretty.to_owned());
|
||||
}
|
||||
if let Some(pretty) = raw.lines().find_map(|l| l.strip_prefix("PRETTY_NAME=")) {
|
||||
return Some(pretty.trim_matches(['"', '\'']).to_owned());
|
||||
}
|
||||
let product = observed(data, "windows.os");
|
||||
if let Some(name) = product["product_name"].as_str() {
|
||||
// Windows 11 can retain a Windows 10 client ProductName for compatibility.
|
||||
let product_name = match (
|
||||
name.strip_prefix("Windows 10 "),
|
||||
product["build"]
|
||||
.as_str()
|
||||
.and_then(|s| s.parse::<u32>().ok()),
|
||||
) {
|
||||
(Some(edition), Some(build))
|
||||
if build >= 22000
|
||||
&& ["Home", "Pro", "Enterprise", "Education", "IoT"]
|
||||
.iter()
|
||||
.any(|prefix| {
|
||||
edition == *prefix
|
||||
|| edition
|
||||
.strip_prefix(prefix)
|
||||
.is_some_and(|suffix| suffix.starts_with(' '))
|
||||
}) =>
|
||||
{
|
||||
format!("Windows 11 {edition}")
|
||||
}
|
||||
_ => name.to_owned(),
|
||||
};
|
||||
return Some(
|
||||
match product["display_version"]
|
||||
.as_str()
|
||||
.filter(|v| !v.is_empty())
|
||||
{
|
||||
Some(version) => format!("{product_name} {version}"),
|
||||
None => product_name,
|
||||
},
|
||||
);
|
||||
}
|
||||
if !raw.contains('\n') {
|
||||
Some(raw.to_owned())
|
||||
} else {
|
||||
Some("Linux".to_owned())
|
||||
}
|
||||
}
|
||||
fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
|
||||
let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null);
|
||||
let cpu = observed(&data, "linux.cpu");
|
||||
let windows = observed(&data, "windows.hardware");
|
||||
let last = row.get::<Option<DateTime<Utc>>, _>("last_contact_at");
|
||||
let revoked = row.get::<Option<DateTime<Utc>>, _>("revoked_at");
|
||||
let presence = match (revoked, last.map(|t| (now - t).num_seconds())) {
|
||||
(Some(_), _) => "revoked",
|
||||
(_, None) => "never_seen",
|
||||
(_, Some(age)) if age < 90 => "online",
|
||||
(_, Some(age)) if age < 180 => "stale",
|
||||
_ => "unreachable",
|
||||
};
|
||||
let mut item = json!({
|
||||
"tenant_id":row.get::<Uuid,_>("tenant_id"),"customer_name":row.get::<String,_>("customer_name"),
|
||||
"agent_id":row.get::<Uuid,_>("agent_id"),"asset_id":row.get::<Uuid,_>("asset_id"),
|
||||
"status":row.get::<String,_>("status"),"lifecycle":row.get::<String,_>("lifecycle"),
|
||||
"archived_at":row.get::<Option<DateTime<Utc>>,_>("archived_at"),"revoked_at":revoked,
|
||||
"hostname":data["hostname"].as_str(),"os":os_label(&data),
|
||||
"disk_free_bytes":data["root_available_bytes"].as_u64(),"disk_total_bytes":data["root_total_bytes"].as_u64(),
|
||||
"cpu_model":cpu["model"].as_str().or_else(||windows["cpu_model"].as_str()),
|
||||
"cpu_logical_count":cpu["logical_processors"].as_u64().or_else(||windows["logical_processors_visible"].as_u64()),
|
||||
"ram_total_bytes":observed(&data,"linux.memory")["total_bytes"].as_u64().or_else(||windows["memory_total_bytes"].as_u64()),
|
||||
"last_contact_at":last,"agent_version":row.get::<Option<String>,_>("reported_agent_version"),
|
||||
"presence":presence,"observed_at":row.get::<Option<DateTime<Utc>>,_>("observed_at"),
|
||||
"received_at":row.get::<Option<DateTime<Utc>>,_>("received_at"),
|
||||
"source_id":row.get::<Option<String>,_>("source_id"),"quality":if data.is_null(){"unknown"}else{"valid"},
|
||||
"completeness":"partial","health":"unknown"
|
||||
});
|
||||
if full {
|
||||
item["inventory"] = data;
|
||||
item["capabilities"] = row.get("capabilities");
|
||||
item["enrollment_generation"] = row.get::<i64, _>("enrollment_generation").into();
|
||||
item["assignment_version"] = row.get::<i64, _>("assignment_version").into();
|
||||
item["certificate_sha256"] = row.get::<String, _>("certificate_sha256").into();
|
||||
item["last_authenticated_certificate_sha256"] =
|
||||
json!(row.get::<Option<String>, _>("last_authenticated_certificate_sha256"));
|
||||
item["last_authenticated_at"] =
|
||||
json!(row.get::<Option<DateTime<Utc>>, _>("last_authenticated_at"));
|
||||
}
|
||||
item
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn windows_os(name: &str, build: &str) -> String {
|
||||
let old = json!({"os":name,"observations":[{"scope":"windows.os","quality":"valid",
|
||||
"data":{"product_name":name,"build":build,"display_version":"26H2"}}]});
|
||||
os_label(&old).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_labels_keep_the_edition_and_handle_existing_snapshots() {
|
||||
assert_eq!(windows_os("Windows 10 Pro", "26300"), "Windows 11 Pro 26H2");
|
||||
assert_eq!(windows_os("Windows 10 Pro", "19045"), "Windows 10 Pro 26H2");
|
||||
assert_eq!(
|
||||
windows_os("Windows Server 2025", "26100"),
|
||||
"Windows Server 2025 26H2"
|
||||
);
|
||||
assert_eq!(
|
||||
windows_os("Windows 10 Pro", "invalid"),
|
||||
"Windows 10 Pro 26H2"
|
||||
);
|
||||
assert_eq!(
|
||||
windows_os("Windows 10 Custom", "26100"),
|
||||
"Windows 10 Custom 26H2"
|
||||
);
|
||||
let linux = json!({"os":"NAME=Example\nPRETTY_NAME=\"Test Linux 1.2\"\nID=linux"});
|
||||
assert_eq!(os_label(&linux).as_deref(), Some("Test Linux 1.2"));
|
||||
assert!(os_label(&Value::Null).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
|
||||
async fn visibility_is_filtered_before_the_cursor_limit() {
|
||||
let admin = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let app = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let tenant = Uuid::new_v4();
|
||||
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'Filter test')")
|
||||
.bind(tenant)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
// In this order: archived, revoked, never connected, old unauthenticated
|
||||
// metadata, confirmed offline, confirmed online. Same hostnames are intentional.
|
||||
for n in 1..=6_i32 {
|
||||
let id = Uuid::from_u128(n as u128);
|
||||
sqlx::query("INSERT INTO assets(tenant_id,asset_id,archived_at) VALUES($1,$2,CASE WHEN $3=1 THEN now() END)")
|
||||
.bind(tenant).bind(id).bind(n).execute(&admin).await.unwrap();
|
||||
let cert = hex::encode(openssl::sha::sha256(format!("{tenant}/{id}").as_bytes()));
|
||||
sqlx::query("INSERT INTO agent_installations(tenant_id,asset_id,agent_id,certificate_sha256,revoked_at,last_contact_at,last_authenticated_at,last_authenticated_certificate_sha256) VALUES($1,$2,$2,$3,CASE WHEN $4=2 THEN now() END,CASE WHEN $4=5 THEN now()-interval '30 days' WHEN $4<>3 THEN now() END,CASE WHEN $4 NOT IN (3,4) THEN now() END, CASE WHEN $4 NOT IN (3,4) THEN $3 END)")
|
||||
.bind(tenant).bind(id).bind(cert).bind(n).execute(&admin).await.unwrap();
|
||||
let data = json!({"hostname":"same-host","os":"Ubuntu","root_available_bytes":10,"root_total_bytes":20,
|
||||
"observations":[{"scope":"linux.memory","quality":"valid","data":{"total_bytes":1024}},{"scope":"linux.cpu","quality":"valid","data":{"logical_processors":2,"model":"Test CPU"}}]});
|
||||
sqlx::query("INSERT INTO observations(tenant_id,agent_id,message_id,boot_id,sequence,observed_at,source_id,quality,completeness,snapshot_id,data,payload_sha256) VALUES($1,$2,$3,$4,1,now(),'linux.base','valid','partial',$5,$6,$7)")
|
||||
.bind(tenant).bind(id).bind(Uuid::new_v4()).bind(Uuid::new_v4()).bind(Uuid::new_v4()).bind(data).bind("0".repeat(64)).execute(&admin).await.unwrap();
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
|
||||
let mut q = Selection {
|
||||
tenant,
|
||||
asset: None,
|
||||
agent: None,
|
||||
view: Some(View::Current),
|
||||
status: None,
|
||||
hostname: "AME-h",
|
||||
last: Uuid::nil(),
|
||||
as_of: Utc::now(),
|
||||
limit: 1,
|
||||
};
|
||||
let row = q.rows(&mut tx).await.unwrap().pop().unwrap();
|
||||
let summary = project(&row, q.as_of, false);
|
||||
assert_eq!(summary["status"], "offline");
|
||||
assert_eq!(summary["ram_total_bytes"], 1024);
|
||||
assert_eq!(summary["cpu_model"], "Test CPU");
|
||||
assert_eq!(summary["disk_free_bytes"], 10);
|
||||
q.last = row.get("agent_id");
|
||||
assert_eq!(
|
||||
q.rows(&mut tx).await.unwrap()[0].get::<String, _>("status"),
|
||||
"online"
|
||||
);
|
||||
q.status = Some(Status::Offline);
|
||||
assert!(q.rows(&mut tx).await.unwrap().is_empty());
|
||||
q.status = None;
|
||||
q.last = Uuid::nil();
|
||||
q.view = Some(View::History);
|
||||
q.limit = 10;
|
||||
let got: Vec<String> = q
|
||||
.rows(&mut tx)
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|r| r.get("lifecycle"))
|
||||
.collect();
|
||||
assert_eq!(got, ["archived", "revoked", "never_seen", "unverified"]);
|
||||
q.hostname = "%";
|
||||
assert!(q.rows(&mut tx).await.unwrap().is_empty());
|
||||
q.hostname = "";
|
||||
q.tenant = Uuid::new_v4();
|
||||
assert!(q.rows(&mut tx).await.unwrap().is_empty());
|
||||
tx.rollback().await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1065,7 +1065,10 @@ pub async fn requester_enabled(
|
||||
tenant: Uuid,
|
||||
) -> std::result::Result<bool, sqlx::Error> {
|
||||
if name.starts_with("mcp:") {
|
||||
crate::mcp_tokens::enabled_in(tx, name).await
|
||||
crate::mcp_tokens::issuer_enabled(state, tx, name).await
|
||||
} else if name.starts_with("local:") {
|
||||
let Some(home)=state.auth.local.as_ref().and_then(|local|local.home(name)) else {return Ok(false);};
|
||||
sqlx::query_scalar("SELECT $3=ANY(local_customer_tenants($1,$2))").bind(name).bind(home).bind(tenant).fetch_one(&mut **tx).await
|
||||
} else {
|
||||
Ok(state.auth.operator_enabled(name, tenant))
|
||||
}
|
||||
|
||||
@@ -210,6 +210,12 @@ impl LocalAuth {
|
||||
workers: Arc::new(Semaphore::new(1)),
|
||||
})
|
||||
}
|
||||
pub fn home(&self, principal: &str) -> Option<Uuid> {
|
||||
self.users
|
||||
.iter()
|
||||
.find(|user| !user.disabled && user.principal == principal)
|
||||
.map(|user| user.tenant)
|
||||
}
|
||||
pub fn enabled(&self, principal: &str, tenant: Uuid) -> bool {
|
||||
self.users
|
||||
.iter()
|
||||
|
||||
@@ -6,10 +6,12 @@ mod agent_update_health;
|
||||
mod agent_update_policy;
|
||||
mod agent_updates;
|
||||
mod api;
|
||||
mod devices;
|
||||
mod artifact_store;
|
||||
mod auth;
|
||||
mod local_auth;
|
||||
mod mcp_tokens;
|
||||
mod customers;
|
||||
mod catalog;
|
||||
mod checkpoint_repair;
|
||||
mod controls;
|
||||
@@ -208,9 +210,11 @@ async fn main() -> Result<()> {
|
||||
.route("/auth/session", get(auth::session))
|
||||
.route("/auth/logout", post(auth::logout))
|
||||
.route("/api/v1/job-signing-key", get(api::job_signing_key))
|
||||
.route("/api/v1/tenants", get(api::tenants))
|
||||
.route("/api/v1/tenants/{tenant}/devices", get(api::devices_page))
|
||||
.route("/api/v1/tenants/{tenant}/devices/{asset}", get(api::device));
|
||||
.route("/api/v1/tenants", get(api::tenants).post(customers::create))
|
||||
.route("/api/v1/tenants/{tenant}", axum::routing::patch(customers::rename))
|
||||
.route("/api/v1/devices", get(devices::all))
|
||||
.route("/api/v1/tenants/{tenant}/devices", get(devices::page))
|
||||
.route("/api/v1/tenants/{tenant}/devices/{asset}", get(devices::detail));
|
||||
routes = mcp_tokens::routes(routes);
|
||||
routes = routes.route("/auth/local/login", post(auth::local_login));
|
||||
routes = jobs::routes(routes);
|
||||
|
||||
+29
-14
@@ -38,9 +38,21 @@ struct Devices {
|
||||
}
|
||||
#[derive(Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Fleet {
|
||||
tenant_id: Option<Uuid>,
|
||||
cursor: Option<String>,
|
||||
limit: Option<u16>,
|
||||
#[serde(default)]
|
||||
view: crate::devices::View,
|
||||
status: Option<crate::devices::Status>,
|
||||
q: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Device {
|
||||
tenant_id: Uuid,
|
||||
asset_id: Uuid,
|
||||
agent_id: Option<Uuid>,
|
||||
}
|
||||
#[derive(Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -96,9 +108,9 @@ fn tools() -> Vec<Tool> {
|
||||
"tenants.list",
|
||||
"List only the authenticated identity's tenants.",
|
||||
),
|
||||
tool::<Devices>(
|
||||
tool::<Fleet>(
|
||||
"inventory.list_devices",
|
||||
"Stored inventory with source, completeness and timestamps; no live collection.",
|
||||
"List current, previously connected devices. Omit tenant_id for all authorized customers. Use view=history for retired or never-seen installations.",
|
||||
),
|
||||
tool::<Device>(
|
||||
"inventory.get_device",
|
||||
@@ -195,29 +207,32 @@ impl Adapter {
|
||||
.0)
|
||||
}
|
||||
"inventory.list_devices" => {
|
||||
let i: Devices = parse(args)?;
|
||||
Ok(crate::api::devices_page(
|
||||
State(self.state.clone()),
|
||||
h,
|
||||
Path(i.tenant_id),
|
||||
axum::extract::Query(crate::pagination::PageQuery {
|
||||
let i: Fleet = parse(args)?;
|
||||
crate::devices::list(
|
||||
&self.state,
|
||||
&h,
|
||||
i.tenant_id,
|
||||
crate::devices::Filters {
|
||||
cursor: i.cursor,
|
||||
limit: i.limit,
|
||||
}),
|
||||
view: i.view,
|
||||
status: i.status,
|
||||
q: i.q,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(map_http)?
|
||||
.0)
|
||||
}
|
||||
"inventory.get_device" => {
|
||||
let i: Device = parse(args)?;
|
||||
Ok(crate::api::device(
|
||||
Ok(crate::devices::detail(
|
||||
State(self.state.clone()),
|
||||
h,
|
||||
Path((i.tenant_id, i.asset_id)),
|
||||
axum::extract::Query(crate::devices::DetailQuery {
|
||||
agent_id: i.agent_id,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.map_err(map_http)?
|
||||
.await?
|
||||
.0)
|
||||
}
|
||||
"monitoring.get_health" => {
|
||||
|
||||
+115
-22
@@ -31,8 +31,7 @@ const SCOPES: [&str; 11] = [
|
||||
"catalog:write",
|
||||
];
|
||||
const READ_SCOPES: [&str; 3] = ["inventory:read", "logs:read", "operations:read"];
|
||||
const COLUMNS: &str =
|
||||
"token_id,principal,name,scopes,created_at,expires_at,last_used_at,revoked_at";
|
||||
const COLUMNS: &str = "token_id,principal,name,scopes,created_at,expires_at,last_used_at,revoked_at,all_customers,coalesce(customer_ids,ARRAY[tenant_id]) AS customer_ids";
|
||||
|
||||
fn invalid() -> Error {
|
||||
Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR")
|
||||
@@ -70,6 +69,8 @@ fn metadata(row: &PgRow) -> Value {
|
||||
"token_id":row.get::<Uuid,_>("token_id"),
|
||||
"principal":row.get::<String,_>("principal"),
|
||||
"name":row.get::<String,_>("name"),
|
||||
"audience":if row.get::<bool,_>("all_customers") {"all"} else {"selected"},
|
||||
"tenant_ids":row.get::<Vec<Uuid>,_>("customer_ids"),
|
||||
"scopes":row.get::<Vec<String>,_>("scopes"),
|
||||
"created_at":row.get::<DateTime<Utc>,_>("created_at"),
|
||||
"expires_at":row.get::<DateTime<Utc>,_>("expires_at"),
|
||||
@@ -119,20 +120,31 @@ async fn list(
|
||||
headers: HeaderMap,
|
||||
Path(tenant): Path<Uuid>,
|
||||
) -> Result<Response, Error> {
|
||||
let (_, allowed, mut tx) = administration(&state, &headers, tenant, false).await?;
|
||||
let (principal, allowed, mut tx) = administration(&state, &headers, tenant, false).await?;
|
||||
let rows = sqlx::query(&format!(
|
||||
"SELECT {COLUMNS} FROM mcp_tokens ORDER BY created_at DESC,token_id"
|
||||
))
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
let can_select_all = crate::customers::can_manage(&principal, &mut tx).await?;
|
||||
tx.commit().await?;
|
||||
let mut available = Vec::new();
|
||||
for customer in &principal.tenants {
|
||||
let mut customer_tx = rmm_persistence::tenant_tx(&state.pool, *customer).await?;
|
||||
let name:Option<String>=sqlx::query_scalar("SELECT name FROM tenants WHERE tenant_id=$1 AND EXISTS(SELECT 1 FROM memberships WHERE principal=$2 AND kind='human' AND revoked_at IS NULL AND 'tokens:manage'=ANY(permissions))")
|
||||
.bind(customer).bind(&principal.name).fetch_optional(&mut *customer_tx).await?;
|
||||
if let Some(name) = name {
|
||||
available.push(json!({"tenant_id":customer,"name":name}));
|
||||
}
|
||||
customer_tx.commit().await?;
|
||||
}
|
||||
let defaults: Vec<_> = READ_SCOPES
|
||||
.into_iter()
|
||||
.filter(|scope| allowed.iter().any(|permission| permission == scope))
|
||||
.collect();
|
||||
Ok(private_json(
|
||||
json!({"tokens":rows.iter().map(metadata).collect::<Vec<_>>(),
|
||||
"allowed_scopes":allowed,"default_scopes":defaults}),
|
||||
"allowed_scopes":allowed,"default_scopes":defaults,"can_select_all":can_select_all,"available_customers":available}),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -140,6 +152,8 @@ async fn list(
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Create {
|
||||
name: String,
|
||||
audience: Option<String>,
|
||||
tenant_ids: Option<Vec<Uuid>>,
|
||||
scopes: Option<Vec<String>>,
|
||||
expires_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
@@ -200,15 +214,41 @@ async fn create(
|
||||
let (scopes, expiry) = selection(&input, &allowed, Utc::now())?;
|
||||
let token = generate()?;
|
||||
let id = Uuid::new_v4();
|
||||
sqlx::query("SELECT issue_mcp_token($1,$2,$3,$4,$5,$6)")
|
||||
let global = match input.audience.as_deref() {
|
||||
None | Some("selected") => false,
|
||||
Some("all") => true,
|
||||
_ => return Err(invalid()),
|
||||
};
|
||||
let customers = input
|
||||
.tenant_ids
|
||||
.unwrap_or_else(|| if global { vec![] } else { vec![tenant] });
|
||||
if global {
|
||||
if !customers.is_empty() {
|
||||
return Err(invalid());
|
||||
}
|
||||
if !crate::customers::can_manage(&principal, &mut tx).await? {
|
||||
return Err(denied());
|
||||
}
|
||||
} else if customers.is_empty()
|
||||
|| customers.len() > 512
|
||||
|| customers.iter().collect::<BTreeSet<_>>().len() != customers.len()
|
||||
{
|
||||
return Err(invalid());
|
||||
} else if customers.iter().any(|t| !principal.tenants.contains(t)) {
|
||||
return Err(denied());
|
||||
}
|
||||
sqlx::query("SELECT issue_customer_token($1,$2,$3,$4,$5,$6,$7,$8)")
|
||||
.bind(&principal.name)
|
||||
.bind(id)
|
||||
.bind(&input.name)
|
||||
.bind(hash(token.as_bytes()))
|
||||
.bind(scopes)
|
||||
.bind(expiry)
|
||||
.bind(global)
|
||||
.bind(&customers)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
.await
|
||||
.map_err(crate::customers::database_error)?;
|
||||
let row = sqlx::query(&format!(
|
||||
"SELECT {COLUMNS} FROM mcp_tokens WHERE token_id=$1"
|
||||
))
|
||||
@@ -251,7 +291,20 @@ pub async fn authenticate(
|
||||
raw: &str,
|
||||
selected: Option<Uuid>,
|
||||
) -> Result<Principal, StatusCode> {
|
||||
authenticate_pool(&state.pool, raw, selected).await
|
||||
let principal = authenticate_pool(&state.pool, raw, selected).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, principal.tenant)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
if !issuer_enabled(state, &mut tx, &principal.name)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?
|
||||
{
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
Ok(principal)
|
||||
}
|
||||
|
||||
async fn authenticate_pool(
|
||||
@@ -270,36 +323,49 @@ async fn authenticate_pool(
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let (tenant, id) = route.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
if selected.is_some_and(|value| value != tenant) {
|
||||
let (home, id) = route.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let tenants: Vec<Uuid> = sqlx::query_scalar("SELECT mcp_credential_customers($1)")
|
||||
.bind(&digest)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let default = tenants.first().copied().ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let tenant = selected.unwrap_or(default);
|
||||
if !tenants.contains(&tenant) {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
let principal = format!("mcp:{id}");
|
||||
let mut tx = rmm_persistence::tenant_tx(pool, tenant)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let row = sqlx::query("SELECT t.principal,t.scopes,m.permissions FROM mcp_tokens t JOIN memberships m USING(tenant_id,principal) WHERE t.token_id=$1 AND t.token_hash=$2 AND t.revoked_at IS NULL AND t.expires_at>now() AND m.kind='automation' AND m.revoked_at IS NULL")
|
||||
.bind(id).bind(digest).fetch_optional(&mut *tx).await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let allowed: Vec<String> = row.get("permissions");
|
||||
let effective: BTreeSet<String> = row
|
||||
.get::<Vec<String>, _>("scopes")
|
||||
let permissions: Vec<String> = sqlx::query_scalar("SELECT mcp_current_scopes($1)")
|
||||
.bind(&principal)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let effective: BTreeSet<String> = permissions
|
||||
.into_iter()
|
||||
.filter(|permission| allowed.contains(permission) && SCOPES.contains(&permission.as_str()))
|
||||
.filter(|p| SCOPES.contains(&p.as_str()))
|
||||
.collect();
|
||||
if effective.is_empty() {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
sqlx::query("UPDATE mcp_tokens SET last_used_at=now() WHERE token_id=$1")
|
||||
.bind(id)
|
||||
sqlx::query("SELECT set_config('app.tenant_id',$1,true)")
|
||||
.bind(home.to_string())
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let used=sqlx::query("UPDATE mcp_tokens SET last_used_at=now() WHERE token_id=$1 AND token_hash=$2 AND revoked_at IS NULL AND expires_at>now()")
|
||||
.bind(id).bind(&digest).execute(&mut *tx).await.map_err(|_|StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
if used.rows_affected() != 1 {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
Ok(Principal {
|
||||
tenant,
|
||||
name: row.get("principal"),
|
||||
name: principal,
|
||||
operator: effective
|
||||
.iter()
|
||||
.any(|scope| !READ_SCOPES.contains(&scope.as_str())),
|
||||
@@ -308,16 +374,41 @@ async fn authenticate_pool(
|
||||
scopes: Some(effective),
|
||||
testsimulation: false,
|
||||
identity: None,
|
||||
tenants: vec![tenant],
|
||||
tenants,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn issuer_enabled(
|
||||
state: &crate::State,
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
principal: &str,
|
||||
) -> Result<bool, sqlx::Error> {
|
||||
let issuer: Option<String> = sqlx::query_scalar("SELECT mcp_current_issuer($1)")
|
||||
.bind(principal)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
Ok(issuer.is_some_and(|actor| {
|
||||
if actor.starts_with("local:") {
|
||||
state
|
||||
.auth
|
||||
.local
|
||||
.as_ref()
|
||||
.and_then(|local| local.home(&actor))
|
||||
.is_some()
|
||||
} else {
|
||||
actor.starts_with("oidc:") && state.auth.oidc.is_some()
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn enabled_in(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
principal: &str,
|
||||
) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM mcp_tokens t JOIN memberships m USING(tenant_id,principal) WHERE t.principal=$1 AND t.revoked_at IS NULL AND t.expires_at>now() AND m.kind='automation' AND m.revoked_at IS NULL AND t.scopes && m.permissions)")
|
||||
.bind(principal).fetch_one(&mut **tx).await
|
||||
sqlx::query_scalar("SELECT cardinality(mcp_current_scopes($1))>0")
|
||||
.bind(principal)
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn enabled(pool: &PgPool, principal: &str, tenant: Uuid) -> bool {
|
||||
@@ -338,6 +429,8 @@ mod tests {
|
||||
let allowed: Vec<String> = SCOPES.into_iter().map(str::to_owned).collect();
|
||||
let mut input = Create {
|
||||
name: "Inventory reader".into(),
|
||||
audience: None,
|
||||
tenant_ids: None,
|
||||
scopes: None,
|
||||
expires_at: None,
|
||||
};
|
||||
|
||||
@@ -13,7 +13,14 @@ pub async fn health(
|
||||
h: HeaderMap,
|
||||
Path(t): Path<Uuid>,
|
||||
) -> Result<Json<Value>, StatusCode> {
|
||||
let Json(devices) = crate::api::devices(State(s), h, Path(t)).await?;
|
||||
let Json(devices) = crate::devices::page(
|
||||
State(s),
|
||||
h,
|
||||
Path(t),
|
||||
axum::extract::Query(Default::default()),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| e.0)?;
|
||||
Ok(Json(
|
||||
json!({"items":devices["items"],"next_cursor":null,"completeness":devices["completeness"],"truncated":devices["truncated"],"as_of":Utc::now(),"health":"unknown","source_id":"stored_agent_observations"}),
|
||||
))
|
||||
|
||||
@@ -17,6 +17,8 @@ pub struct Cursor {
|
||||
scope: String,
|
||||
pub as_of: DateTime<Utc>,
|
||||
pub last: Uuid,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_tenant: Option<Uuid>,
|
||||
pub limit: u16,
|
||||
}
|
||||
impl Cursor {
|
||||
@@ -71,6 +73,7 @@ impl Cursor {
|
||||
scope: scope.into(),
|
||||
as_of: Utc::now(),
|
||||
last: Uuid::nil(),
|
||||
last_tenant: None,
|
||||
limit: q.limit.unwrap_or(100),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,11 +3,10 @@ use anyhow::Result;
|
||||
use sqlx::{Postgres, Transaction};
|
||||
use uuid::Uuid;
|
||||
pub async fn maintain(tx: &mut Transaction<'_, Postgres>, agent: Option<Uuid>) -> Result<()> {
|
||||
sqlx::query("UPDATE approval_requests r SET approval_state='expired' FROM operation_plans p WHERE p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id AND r.approval_state='pending_approval' AND p.expires_at<=now()").execute(&mut **tx).await?;
|
||||
sqlx::query("UPDATE jobs j SET state='expired',pending_reason=NULL FROM operations o,approval_requests r,operation_plans p WHERE j.tenant_id=o.tenant_id AND j.operation_id=o.operation_id AND r.tenant_id=o.tenant_id AND r.operation_id=o.operation_id AND p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id AND ($1::uuid IS NULL OR j.agent_id=$1) AND j.state IN ('queued','accepted') AND NOT j.start_reserved AND p.expires_at<=now()").bind(agent).execute(&mut **tx).await?;
|
||||
sqlx::query("UPDATE jobs j SET state='unknown',pending_reason='reconciliation_required',result=COALESCE(j.result,'{}'::jsonb)||jsonb_build_object('error_code','START_OR_RESULT_UNCONFIRMED','source_id','server_grant_ledger') FROM execution_permits e WHERE e.tenant_id=j.tenant_id AND e.job_id=j.job_id AND ($1::uuid IS NULL OR j.agent_id=$1) AND j.start_reserved AND ((j.state='accepted' AND (convert_from(e.payload,'UTF8')::jsonb->>'start_before')::timestamptz<now()) OR (j.state IN ('running','verifying') AND (convert_from(e.payload,'UTF8')::jsonb->>'start_before')::timestamptz+make_interval(secs=>(convert_from(e.payload,'UTF8')::jsonb->>'max_runtime_seconds')::integer)<now()))").bind(agent).execute(&mut **tx).await?;
|
||||
sqlx::query("UPDATE jobs j SET pending_reason=CASE WHEN t.changes_stopped THEN 'tenant_stopped' WHEN r.approval_state<>'approved' THEN 'authorization_revoked' WHEN (convert_from(j.payload,'UTF8')::jsonb->>'not_before')::timestamptz>now() THEN 'maintenance_window' WHEN i.last_contact_at IS NULL OR i.last_contact_at<now()-interval '180 seconds' THEN 'device_offline' ELSE NULL END FROM tenants t,approval_requests r,agent_installations i WHERE j.tenant_id=t.tenant_id AND r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id AND i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id AND j.state IN ('queued','accepted') AND NOT j.start_reserved AND ($1::uuid IS NULL OR j.agent_id=$1)").bind(agent).execute(&mut **tx).await?;
|
||||
sqlx::query("UPDATE jobs j SET state='unknown',pending_reason='reconciliation_required',result=COALESCE(j.result,'{}'::jsonb)||jsonb_build_object('error_code','REBOOT_REJOIN_UNCONFIRMED','source_id','server_grant_ledger') FROM execution_permits e WHERE e.tenant_id=j.tenant_id AND e.job_id=j.job_id AND ($1::uuid IS NULL OR j.agent_id=$1) AND j.state='awaiting_reboot' AND (convert_from(e.payload,'UTF8')::jsonb->>'start_before')::timestamptz+make_interval(secs=>COALESCE((convert_from(j.payload,'UTF8')::jsonb->'action'->>'reconnect_timeout_seconds')::integer,3600))<now()").bind(agent).execute(&mut **tx).await?;
|
||||
sqlx::query("SELECT maintain_current_customer($1)")
|
||||
.bind(agent)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn start(state: crate::State) {
|
||||
@@ -15,26 +14,8 @@ pub fn start(state: crate::State) {
|
||||
let mut timer = tokio::time::interval(std::time::Duration::from_secs(1));
|
||||
loop {
|
||||
timer.tick().await;
|
||||
for tenant in [rmm_domain::TENANT_A, rmm_domain::TENANT_B] {
|
||||
let result = async {
|
||||
let tenant = Uuid::parse_str(tenant)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
||||
let acquired: bool = sqlx::query_scalar(
|
||||
"SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))",
|
||||
)
|
||||
.bind(format!("maintenance:{tenant}"))
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if acquired {
|
||||
maintain(&mut tx, None).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok::<(), anyhow::Error>(())
|
||||
}
|
||||
.await;
|
||||
if result.is_err() {
|
||||
eprintln!("tenant housekeeping failed; no starts authorized by scheduler");
|
||||
}
|
||||
if sqlx::query("SELECT maintain_customers()").execute(&state.pool).await.is_err() {
|
||||
eprintln!("customer housekeeping failed");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -54,6 +54,10 @@ impl UpdateArtifacts {
|
||||
profile == "development",
|
||||
"update object adapter is development-only"
|
||||
);
|
||||
Self::private_directory(root, owner)
|
||||
}
|
||||
|
||||
pub(crate) fn private_directory(root: PathBuf, owner: u32) -> Result<Self> {
|
||||
match fs::create_dir(&root) {
|
||||
Ok(()) => fs::set_permissions(&root, fs::Permissions::from_mode(0o700))?,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
-- Explicit customer administrator grants are provisioned by the database owner.
|
||||
-- The application role cannot add administrators or read the membership index.
|
||||
CREATE TABLE customer_admins (
|
||||
principal text PRIMARY KEY CHECK (principal LIKE 'local:%'),
|
||||
home uuid NOT NULL,
|
||||
FOREIGN KEY(home,principal) REFERENCES memberships(tenant_id,principal)
|
||||
);
|
||||
CREATE TABLE customer_member_index (
|
||||
principal text NOT NULL, customer uuid NOT NULL, kind text NOT NULL,
|
||||
permissions text[] NOT NULL,
|
||||
PRIMARY KEY(principal,customer)
|
||||
);
|
||||
REVOKE ALL ON customer_admins, customer_member_index FROM PUBLIC,rmm_app;
|
||||
CREATE FUNCTION index_customer_membership() RETURNS trigger
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
|
||||
BEGIN
|
||||
IF TG_OP <> 'INSERT' THEN
|
||||
DELETE FROM customer_member_index WHERE principal=OLD.principal AND customer=OLD.tenant_id;
|
||||
END IF;
|
||||
IF TG_OP <> 'DELETE' AND NEW.revoked_at IS NULL THEN
|
||||
INSERT INTO customer_member_index VALUES(NEW.principal,NEW.tenant_id,NEW.kind,NEW.permissions);
|
||||
END IF;
|
||||
RETURN NULL;
|
||||
END $$;
|
||||
REVOKE ALL ON FUNCTION index_customer_membership() FROM PUBLIC;
|
||||
CREATE TRIGGER maintain_customer_members AFTER INSERT OR UPDATE OR DELETE ON memberships
|
||||
FOR EACH ROW EXECUTE FUNCTION index_customer_membership();
|
||||
DO $$
|
||||
DECLARE t uuid;
|
||||
BEGIN
|
||||
FOR t IN SELECT tenant_id FROM tenants LOOP
|
||||
PERFORM set_config('app.tenant_id',t::text,true);
|
||||
INSERT INTO customer_member_index SELECT principal,tenant_id,kind,permissions FROM memberships
|
||||
WHERE tenant_id=t AND revoked_at IS NULL;
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
CREATE FUNCTION is_customer_admin(actor text) RETURNS boolean
|
||||
LANGUAGE sql STABLE SECURITY DEFINER SET search_path=pg_catalog,public AS $$
|
||||
SELECT EXISTS(SELECT 1 FROM customer_admins a JOIN customer_member_index m
|
||||
ON m.principal=a.principal AND m.customer=a.home WHERE a.principal=actor AND m.kind='human'
|
||||
AND 'tokens:manage'=ANY(m.permissions));
|
||||
$$;
|
||||
CREATE FUNCTION local_customer_tenants(actor text,home_id uuid) RETURNS uuid[]
|
||||
LANGUAGE sql STABLE SECURITY DEFINER SET search_path=pg_catalog,public AS $$
|
||||
SELECT ARRAY(SELECT customer FROM customer_member_index m WHERE m.principal=actor AND m.kind='human'
|
||||
AND (m.customer=home_id OR EXISTS(SELECT 1 FROM customer_admins a
|
||||
WHERE a.principal=actor AND a.home=home_id AND is_customer_admin(actor))) ORDER BY customer);
|
||||
$$;
|
||||
CREATE FUNCTION provision_customer_admin(home_id uuid,actor text) RETURNS void
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
|
||||
DECLARE previous_tenant text:=coalesce(current_setting('app.tenant_id',true),'');
|
||||
p text[]; t uuid;
|
||||
BEGIN
|
||||
-- Serialize changes to the customer directory with global grant creation.
|
||||
PERFORM pg_advisory_xact_lock(724035,28);
|
||||
SELECT permissions INTO STRICT p FROM customer_member_index WHERE principal=actor AND customer=home_id
|
||||
AND kind='human' AND 'tokens:manage'=ANY(permissions);
|
||||
INSERT INTO customer_admins(principal,home) VALUES(actor,home_id) ON CONFLICT(principal) DO NOTHING;
|
||||
IF NOT EXISTS(SELECT 1 FROM customer_admins WHERE principal=actor AND home=home_id) THEN
|
||||
RAISE EXCEPTION 'ADMIN_HOME_CONFLICT';
|
||||
END IF;
|
||||
FOR t IN SELECT tenant_id FROM tenants LOOP
|
||||
PERFORM set_config('app.tenant_id',t::text,true);
|
||||
INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES(t,actor,'human',p)
|
||||
ON CONFLICT(tenant_id,principal) DO NOTHING;
|
||||
END LOOP;
|
||||
PERFORM set_config('app.tenant_id',previous_tenant,true);
|
||||
END $$;
|
||||
REVOKE ALL ON FUNCTION provision_customer_admin(uuid,text) FROM PUBLIC,rmm_app;
|
||||
REVOKE ALL ON FUNCTION is_customer_admin(text), local_customer_tenants(text,uuid) FROM PUBLIC;
|
||||
GRANT EXECUTE ON FUNCTION is_customer_admin(text), local_customer_tenants(text,uuid) TO rmm_app;
|
||||
|
||||
ALTER TABLE mcp_tokens ADD COLUMN all_customers boolean NOT NULL DEFAULT false;
|
||||
ALTER TABLE mcp_tokens ADD COLUMN customer_ids uuid[];
|
||||
ALTER TABLE mcp_tokens ADD COLUMN issuer_admin_home uuid REFERENCES tenants;
|
||||
-- NULL is the preexisting single-customer audience. Global grants use [].
|
||||
ALTER TABLE mcp_tokens ADD CHECK (NOT all_customers OR (customer_ids IS NOT NULL AND cardinality(customer_ids)=0));
|
||||
CREATE UNIQUE INDEX mcp_route_principal ON mcp_token_routes (('mcp:'||token_id::text));
|
||||
CREATE TABLE global_mcp_credentials (
|
||||
home uuid NOT NULL, token uuid PRIMARY KEY,
|
||||
FOREIGN KEY(home,token) REFERENCES mcp_tokens(tenant_id,token_id)
|
||||
);
|
||||
REVOKE ALL ON global_mcp_credentials FROM PUBLIC,rmm_app;
|
||||
|
||||
CREATE FUNCTION issue_customer_token(actor text,id uuid,label text,digest text,requested text[],expiry timestamptz,
|
||||
global_access boolean,selected uuid[]) RETURNS void LANGUAGE plpgsql SECURITY DEFINER
|
||||
SET search_path=pg_catalog,public AS $$
|
||||
DECLARE home_id uuid:=current_setting('app.tenant_id')::uuid; customers uuid[]; t uuid; member text:='mcp:'||id::text;
|
||||
BEGIN
|
||||
PERFORM pg_advisory_xact_lock(724035,28);
|
||||
IF global_access THEN
|
||||
IF NOT is_customer_admin(actor) OR cardinality(selected) IS DISTINCT FROM 0 THEN
|
||||
RAISE EXCEPTION 'GLOBAL_ADMIN_REQUIRED' USING ERRCODE='42501';
|
||||
END IF;
|
||||
SELECT array_agg(tenant_id) INTO customers FROM tenants;
|
||||
ELSE
|
||||
IF cardinality(selected) IS NULL OR cardinality(selected) NOT BETWEEN 1 AND 512
|
||||
OR array_position(selected,NULL) IS NOT NULL
|
||||
OR cardinality(selected)<>(SELECT count(DISTINCT value) FROM unnest(selected) value)
|
||||
THEN RAISE EXCEPTION 'INVALID_CUSTOMER_SELECTION' USING ERRCODE='22023'; END IF;
|
||||
customers:=selected;
|
||||
END IF;
|
||||
FOREACH t IN ARRAY customers LOOP
|
||||
IF NOT EXISTS(SELECT 1 FROM customer_member_index WHERE principal=actor AND customer=t AND kind='human'
|
||||
AND 'tokens:manage'=ANY(permissions) AND requested <@ permissions) THEN
|
||||
RAISE EXCEPTION 'CUSTOMER_SCOPE_DENIED' USING ERRCODE='42501';
|
||||
END IF;
|
||||
END LOOP;
|
||||
PERFORM issue_mcp_token(actor,id,label,digest,requested,expiry);
|
||||
UPDATE mcp_tokens SET all_customers=global_access,customer_ids=selected,
|
||||
issuer_admin_home=(SELECT home FROM customer_admins WHERE principal=actor) WHERE tenant_id=home_id AND token_id=id;
|
||||
INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data)
|
||||
VALUES(home_id,gen_random_uuid(),actor,'mcp_token_audience',
|
||||
jsonb_build_object('token_id',id,'all_customers',global_access,'customer_ids',selected));
|
||||
IF global_access THEN INSERT INTO global_mcp_credentials VALUES(home_id,id); END IF;
|
||||
FOREACH t IN ARRAY customers LOOP
|
||||
IF t<>home_id THEN
|
||||
PERFORM set_config('app.tenant_id',t::text,true);
|
||||
INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES(t,member,'automation',requested);
|
||||
END IF;
|
||||
END LOOP;
|
||||
PERFORM set_config('app.tenant_id',home_id::text,true);
|
||||
END $$;
|
||||
REVOKE ALL ON FUNCTION issue_customer_token(text,uuid,text,text,text[],timestamptz,boolean,uuid[]) FROM PUBLIC;
|
||||
GRANT EXECUTE ON FUNCTION issue_customer_token(text,uuid,text,text,text[],timestamptz,boolean,uuid[]) TO rmm_app;
|
||||
|
||||
-- Authorization projection evaluated inside the credential's home RLS context.
|
||||
-- No direct grant on this view. Both the target's membership and the issuer's
|
||||
-- current delegation ceiling are checked, even for previously submitted jobs.
|
||||
CREATE VIEW customer_token_rights AS
|
||||
SELECT t.tenant_id,t.token_id,t.principal,t.created_by,m.customer,
|
||||
ARRAY(SELECT s FROM unnest(t.scopes) s WHERE s=ANY(h.permissions)
|
||||
AND s=ANY(m.permissions) AND s=ANY(issuer.permissions) AND s=ANY(target_issuer.permissions)) AS scopes
|
||||
FROM mcp_tokens t
|
||||
JOIN customer_member_index h ON h.principal=t.principal AND h.customer=t.tenant_id AND h.kind='automation'
|
||||
JOIN customer_member_index m ON m.principal=t.principal AND m.kind='automation'
|
||||
JOIN customer_member_index issuer ON issuer.principal=t.created_by AND issuer.customer=t.tenant_id
|
||||
AND issuer.kind='human' AND 'tokens:manage'=ANY(issuer.permissions)
|
||||
JOIN customer_member_index target_issuer ON target_issuer.principal=t.created_by AND target_issuer.customer=m.customer
|
||||
AND target_issuer.kind='human' AND 'tokens:manage'=ANY(target_issuer.permissions)
|
||||
WHERE t.revoked_at IS NULL AND t.expires_at>now()
|
||||
AND (t.all_customers OR m.customer=ANY(coalesce(t.customer_ids,ARRAY[t.tenant_id])))
|
||||
AND ((NOT t.all_customers AND (t.issuer_admin_home IS NULL OR
|
||||
(m.customer=t.issuer_admin_home AND t.tenant_id=t.issuer_admin_home))) OR is_customer_admin(t.created_by))
|
||||
AND (left(t.created_by,5)<>'oidc:' OR EXISTS(SELECT 1 FROM oidc_principals o WHERE o.principal=t.created_by
|
||||
AND NOT o.disabled AND m.customer=ANY(o.tenant_ids) AND t.tenant_id=ANY(o.tenant_ids)));
|
||||
REVOKE ALL ON customer_token_rights FROM PUBLIC,rmm_app;
|
||||
|
||||
-- Every authorization, including pending job admission, consults the original
|
||||
-- credential expiry/revocation, original membership and target membership.
|
||||
CREATE FUNCTION mcp_effective_scopes(member text,target_customer uuid) RETURNS text[]
|
||||
LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path=pg_catalog,public AS $$
|
||||
DECLARE previous_tenant text:=coalesce(current_setting('app.tenant_id',true),'');
|
||||
home_id uuid; result text[];
|
||||
BEGIN
|
||||
SELECT tenant_id INTO home_id FROM mcp_token_routes WHERE 'mcp:'||token_id::text=member;
|
||||
IF home_id IS NULL THEN RETURN '{}'; END IF;
|
||||
PERFORM set_config('app.tenant_id',home_id::text,true);
|
||||
SELECT scopes INTO result FROM customer_token_rights
|
||||
WHERE tenant_id=home_id AND principal=member AND customer=target_customer;
|
||||
PERFORM set_config('app.tenant_id',previous_tenant,true);
|
||||
RETURN coalesce(result,'{}');
|
||||
END $$;
|
||||
REVOKE ALL ON FUNCTION mcp_effective_scopes(text,uuid) FROM PUBLIC,rmm_app;
|
||||
CREATE FUNCTION mcp_current_scopes(member text) RETURNS text[] LANGUAGE sql STABLE SECURITY DEFINER
|
||||
SET search_path=pg_catalog,public AS $$
|
||||
SELECT mcp_effective_scopes(member,nullif(current_setting('app.tenant_id',true),'')::uuid);
|
||||
$$;
|
||||
CREATE OR REPLACE FUNCTION mcp_principal_permission(member text,permission text) RETURNS boolean
|
||||
LANGUAGE sql STABLE SET search_path=pg_catalog,public AS $$
|
||||
SELECT permission=ANY(mcp_current_scopes(member));
|
||||
$$;
|
||||
CREATE FUNCTION mcp_credential_customers(digest text) RETURNS uuid[] LANGUAGE plpgsql STABLE SECURITY DEFINER
|
||||
SET search_path=pg_catalog,public AS $$
|
||||
DECLARE previous_tenant text:=coalesce(current_setting('app.tenant_id',true),'');
|
||||
home_id uuid; id uuid; result uuid[];
|
||||
BEGIN
|
||||
SELECT tenant_id,token_id INTO home_id,id FROM mcp_token_routes WHERE token_hash=digest;
|
||||
IF home_id IS NULL THEN RETURN '{}'; END IF;
|
||||
PERFORM set_config('app.tenant_id',home_id::text,true);
|
||||
SELECT ARRAY(SELECT customer FROM customer_token_rights
|
||||
WHERE tenant_id=home_id AND token_id=id AND cardinality(scopes)>0
|
||||
ORDER BY (customer=home_id) DESC,customer) INTO result;
|
||||
PERFORM set_config('app.tenant_id',previous_tenant,true);
|
||||
RETURN result;
|
||||
END $$;
|
||||
REVOKE ALL ON FUNCTION mcp_credential_customers(text),mcp_current_scopes(text) FROM PUBLIC;
|
||||
GRANT EXECUTE ON FUNCTION mcp_credential_customers(text),mcp_current_scopes(text) TO rmm_app;
|
||||
|
||||
|
||||
-- Only return issuer metadata for a credential currently active in this tenant.
|
||||
CREATE FUNCTION mcp_current_issuer(member text) RETURNS text
|
||||
LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path=pg_catalog,public AS $$
|
||||
DECLARE target_id uuid:=nullif(current_setting('app.tenant_id',true),'')::uuid;home_id uuid;actor text;
|
||||
BEGIN
|
||||
IF target_id IS NULL THEN RETURN NULL; END IF;
|
||||
SELECT tenant_id INTO home_id FROM mcp_token_routes WHERE 'mcp:'||token_id::text=member;
|
||||
IF home_id IS NULL THEN RETURN NULL; END IF;
|
||||
PERFORM set_config('app.tenant_id',home_id::text,true);
|
||||
SELECT created_by INTO actor FROM customer_token_rights WHERE tenant_id=home_id AND principal=member
|
||||
AND customer=target_id AND cardinality(scopes)>0;
|
||||
PERFORM set_config('app.tenant_id',target_id::text,true);
|
||||
RETURN actor;
|
||||
END $$;
|
||||
REVOKE ALL ON FUNCTION mcp_current_issuer(text) FROM PUBLIC;
|
||||
GRANT EXECUTE ON FUNCTION mcp_current_issuer(text) TO rmm_app;
|
||||
|
||||
-- Provision every newly inserted tenant, including administrative imports.
|
||||
CREATE FUNCTION seed_customer_access() RETURNS trigger
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
|
||||
DECLARE previous_tenant text:=coalesce(current_setting('app.tenant_id',true),'');
|
||||
id uuid:=NEW.tenant_id; credential record; m record;
|
||||
BEGIN
|
||||
PERFORM pg_advisory_xact_lock(724035,28);
|
||||
PERFORM set_config('app.tenant_id',id::text,true);
|
||||
INSERT INTO tenant_limits(tenant_id) VALUES(id);
|
||||
FOR m IN SELECT a.principal,i.permissions FROM customer_admins a JOIN customer_member_index i
|
||||
ON i.principal=a.principal AND i.customer=a.home WHERE i.kind='human' AND 'tokens:manage'=ANY(i.permissions)
|
||||
LOOP
|
||||
INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES(id,m.principal,'human',m.permissions);
|
||||
END LOOP;
|
||||
FOR credential IN SELECT home,token FROM global_mcp_credentials LOOP
|
||||
PERFORM set_config('app.tenant_id',credential.home::text,true);
|
||||
SELECT t.principal, t.scopes INTO m FROM mcp_tokens t WHERE t.token_id=credential.token AND t.tenant_id=credential.home
|
||||
AND t.revoked_at IS NULL AND t.expires_at>now() AND t.all_customers;
|
||||
IF FOUND THEN
|
||||
PERFORM set_config('app.tenant_id',id::text,true);
|
||||
INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES(id,m.principal,'automation',m.scopes);
|
||||
END IF;
|
||||
END LOOP;
|
||||
PERFORM set_config('app.tenant_id',previous_tenant,true);
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
REVOKE ALL ON FUNCTION seed_customer_access() FROM PUBLIC,rmm_app;
|
||||
CREATE TRIGGER customer_access_created AFTER INSERT ON tenants FOR EACH ROW EXECUTE FUNCTION seed_customer_access();
|
||||
|
||||
CREATE FUNCTION manage_customer(actor text,id uuid,label text,new_customer boolean) RETURNS void
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
|
||||
DECLARE previous_tenant text:=coalesce(current_setting('app.tenant_id',true),'');
|
||||
BEGIN
|
||||
PERFORM pg_advisory_xact_lock(724035,28);
|
||||
IF NOT is_customer_admin(actor) THEN RAISE EXCEPTION 'ADMIN_REQUIRED' USING ERRCODE='42501'; END IF;
|
||||
IF label IS NULL OR label<>btrim(label) OR length(label) NOT BETWEEN 1 AND 120 OR label ~ '[[:cntrl:]]'
|
||||
THEN RAISE EXCEPTION 'INVALID_NAME' USING ERRCODE='22023'; END IF;
|
||||
IF EXISTS(SELECT 1 FROM tenants WHERE lower(name)=lower(label) AND tenant_id<>id) THEN
|
||||
RAISE EXCEPTION 'CUSTOMER_NAME_EXISTS' USING ERRCODE='23505';
|
||||
END IF;
|
||||
PERFORM set_config('app.tenant_id',id::text,true);
|
||||
IF new_customer THEN
|
||||
INSERT INTO tenants(tenant_id,name) VALUES(id,label);
|
||||
ELSE
|
||||
IF NOT EXISTS(SELECT 1 FROM customer_member_index WHERE customer=id AND principal=actor AND kind='human')
|
||||
THEN RAISE EXCEPTION 'CUSTOMER_DENIED' USING ERRCODE='42501'; END IF;
|
||||
UPDATE tenants SET name=label WHERE tenant_id=id;
|
||||
END IF;
|
||||
PERFORM set_config('app.tenant_id',id::text,true);
|
||||
INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data) VALUES(id,gen_random_uuid(),actor,
|
||||
CASE WHEN new_customer THEN 'customer_created' ELSE 'customer_renamed' END,jsonb_build_object('name',label));
|
||||
PERFORM set_config('app.tenant_id',previous_tenant,true);
|
||||
END $$;
|
||||
REVOKE ALL ON FUNCTION manage_customer(text,uuid,text,boolean) FROM PUBLIC;
|
||||
GRANT EXECUTE ON FUNCTION manage_customer(text,uuid,text,boolean) TO rmm_app;
|
||||
|
||||
|
||||
-- Both heartbeat and periodic maintenance apply the same existing expiry rules.
|
||||
CREATE FUNCTION maintain_current_customer(target_agent uuid) RETURNS void
|
||||
LANGUAGE sql SET search_path=pg_catalog,public AS $maintain$
|
||||
UPDATE approval_requests r SET approval_state='expired' FROM operation_plans p WHERE p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id AND r.approval_state='pending_approval' AND p.expires_at<=now();
|
||||
UPDATE jobs j SET state='expired',pending_reason=NULL FROM operations o,approval_requests r,operation_plans p WHERE j.tenant_id=o.tenant_id AND j.operation_id=o.operation_id AND r.tenant_id=o.tenant_id AND r.operation_id=o.operation_id AND p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id AND (target_agent IS NULL OR j.agent_id=target_agent) AND j.state IN ('queued','accepted') AND NOT j.start_reserved AND p.expires_at<=now();
|
||||
UPDATE jobs j SET state='unknown',pending_reason='reconciliation_required',result=COALESCE(j.result,'{}'::jsonb)||jsonb_build_object('error_code','START_OR_RESULT_UNCONFIRMED','source_id','server_grant_ledger') FROM execution_permits e WHERE e.tenant_id=j.tenant_id AND e.job_id=j.job_id AND (target_agent IS NULL OR j.agent_id=target_agent) AND j.start_reserved AND ((j.state='accepted' AND (convert_from(e.payload,'UTF8')::jsonb->>'start_before')::timestamptz<now()) OR (j.state IN ('running','verifying') AND (convert_from(e.payload,'UTF8')::jsonb->>'start_before')::timestamptz+make_interval(secs=>(convert_from(e.payload,'UTF8')::jsonb->>'max_runtime_seconds')::integer)<now()));
|
||||
UPDATE jobs j SET pending_reason=CASE WHEN t.changes_stopped THEN 'tenant_stopped' WHEN r.approval_state<>'approved' THEN 'authorization_revoked' WHEN (convert_from(j.payload,'UTF8')::jsonb->>'not_before')::timestamptz>now() THEN 'maintenance_window' WHEN i.last_contact_at IS NULL OR i.last_contact_at<now()-interval '180 seconds' THEN 'device_offline' ELSE NULL END FROM tenants t,approval_requests r,agent_installations i WHERE j.tenant_id=t.tenant_id AND r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id AND i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id AND j.state IN ('queued','accepted') AND NOT j.start_reserved AND (target_agent IS NULL OR j.agent_id=target_agent);
|
||||
UPDATE jobs j SET state='unknown',pending_reason='reconciliation_required',result=COALESCE(j.result,'{}'::jsonb)||jsonb_build_object('error_code','REBOOT_REJOIN_UNCONFIRMED','source_id','server_grant_ledger') FROM execution_permits e WHERE e.tenant_id=j.tenant_id AND e.job_id=j.job_id AND (target_agent IS NULL OR j.agent_id=target_agent) AND j.state='awaiting_reboot' AND (convert_from(e.payload,'UTF8')::jsonb->>'start_before')::timestamptz+make_interval(secs=>COALESCE((convert_from(j.payload,'UTF8')::jsonb->'action'->>'reconnect_timeout_seconds')::integer,3600))<now();
|
||||
$maintain$;
|
||||
REVOKE ALL ON FUNCTION maintain_current_customer(uuid) FROM PUBLIC;
|
||||
GRANT EXECUTE ON FUNCTION maintain_current_customer(uuid) TO rmm_app;
|
||||
|
||||
-- Periodic maintenance returns no customer IDs and provides no job start grant.
|
||||
CREATE FUNCTION maintain_customers() RETURNS void
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
|
||||
DECLARE home text:=coalesce(current_setting('app.tenant_id',true),''); customer uuid;
|
||||
BEGIN
|
||||
FOR customer IN SELECT tenant_id FROM tenants ORDER BY tenant_id LOOP
|
||||
IF pg_try_advisory_xact_lock(hashtextextended('maintenance:'||customer::text,0)) THEN
|
||||
PERFORM set_config('app.tenant_id',customer::text,true);
|
||||
PERFORM maintain_current_customer(NULL);
|
||||
END IF;
|
||||
END LOOP;
|
||||
PERFORM set_config('app.tenant_id',home,true);
|
||||
END $$;
|
||||
REVOKE ALL ON FUNCTION maintain_customers() FROM PUBLIC;
|
||||
GRANT EXECUTE ON FUNCTION maintain_customers() TO rmm_app;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Archive is an inventory visibility preference. Trust/revocation remains on the installation.
|
||||
ALTER TABLE assets ADD COLUMN archived_at timestamptz;
|
||||
GRANT UPDATE(archived_at) ON assets TO rmm_app;
|
||||
CREATE INDEX observations_device_summary ON observations
|
||||
(tenant_id, agent_id, observed_at DESC, received_at DESC, sequence DESC)
|
||||
WHERE source_id IN ('windows.base','linux.base');
|
||||
CREATE INDEX agent_installations_asset_generation ON agent_installations
|
||||
(tenant_id,asset_id,enrollment_generation)
|
||||
WHERE last_contact_at IS NOT NULL AND last_authenticated_at IS NOT NULL;
|
||||
@@ -0,0 +1,13 @@
|
||||
-- A bootstrap worker published with the operator's starter release for this customer.
|
||||
-- The administrator's explicit per-customer rotation file takes precedence.
|
||||
CREATE TABLE customer_starter_workers (
|
||||
tenant_id uuid NOT NULL REFERENCES tenants,
|
||||
platform text NOT NULL,
|
||||
sha256 text NOT NULL CHECK(sha256 ~ '^[0-9a-f]{64}$'),
|
||||
size_bytes bigint NOT NULL CHECK(size_bytes BETWEEN 1 AND 268435456),
|
||||
PRIMARY KEY(tenant_id,platform)
|
||||
);
|
||||
ALTER TABLE customer_starter_workers ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE customer_starter_workers FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY tenant_scope ON customer_starter_workers USING (tenant_id::text=current_setting('app.tenant_id',true));
|
||||
GRANT SELECT,INSERT ON customer_starter_workers TO rmm_app;
|
||||
@@ -19,6 +19,8 @@ test('dev/test browser simulation: login → fixed plan → pending → explicit
|
||||
await expect(page.getByRole('status')).toContainText('SIMULIERT');
|
||||
await expect(page.getByRole('status')).toContainText('kein menschlicher Produktions-Freigabenachweis');
|
||||
await page.getByRole('checkbox', { name: `Ziel ${asset}`, exact: true }).check();
|
||||
await page.getByRole('link', { name: 'Aufträge', exact: true }).click();
|
||||
await page.getByRole('link', { name: 'Auftrag planen', exact: true }).click();
|
||||
await page.getByLabel('Exakte UTF-8 Skriptbytes', { exact: false }).fill("printf '%s\\n' 'Hello World'\n");
|
||||
await page.getByLabel('Erwartete stdout-Ausgabe', { exact: false }).fill('Hello World\n');
|
||||
await page.getByLabel('Begründung', { exact: true }).fill('Dev/test browser simulation · Hello World');
|
||||
|
||||
@@ -17,6 +17,6 @@ test('real TLS login follows announced configuration and restores session withou
|
||||
if (!config.dev_login_enabled) { await expect(page.locator('input[type="password"]')).toHaveCount(0); return; }
|
||||
await expect(page.getByText('DEV/TEST · SIMULIERTER TESTPRINCIPAL', { exact: false })).toBeVisible();
|
||||
await login(page); await page.reload(); await expect(page.getByRole('status')).toContainText('SIMULIERT');
|
||||
await expect(page.getByRole('heading', { name: 'Mitgliedschaft und Ausführungsstopp' })).toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: 'Geräte', exact: true })).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Abmelden', exact: true }).click(); await expect(page.getByRole('button', { name: 'Anmelden', exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -7,10 +7,15 @@ test('real dev browser membership/catalog read and administrative controls stay
|
||||
page.on('request', r => { if (r.method() === 'POST' && !['/auth/dev/login', '/auth/logout'].includes(new URL(r.url()).pathname)) mutations++; });
|
||||
const catalog = page.waitForResponse(r => new URL(r.url()).pathname.endsWith('/package-recipes'));
|
||||
await test.step('management:login-banner', async () => { await login(page); await expect(page.getByRole('status')).toContainText('SIMULIERT'); });
|
||||
await page.getByRole('link', {name:'Verwaltung',exact:true}).click();
|
||||
await page.getByRole('link', {name:'Paketkataloge',exact:true}).click();
|
||||
await test.step('management:catalog-response', async () => { expect((await catalog).status()).toBe(200); });
|
||||
await test.step('management:catalog-heading', async () => { await expect(page.getByRole('heading', { name: 'Unveränderlicher Paketkatalog und Artefakte' })).toBeVisible(); });
|
||||
await page.getByRole('link', {name:'Rechte & Ausführungsstopp',exact:true}).click();
|
||||
await test.step('management:membership-heading', async () => { await expect(page.getByRole('heading', { name: 'Mitgliedschaft und Ausführungsstopp' })).toBeVisible(); });
|
||||
await test.step('management:unknown-stop', async () => { await expect(page.getByText('unknown — kein lesender Stopstatus-Endpunkt angekündigt', { exact: false })).toBeVisible(); });
|
||||
await page.getByRole('link', {name:'Aufträge',exact:true}).click();
|
||||
await page.getByRole('link', {name:'Auftrag planen',exact:true}).click();
|
||||
await test.step('management:action-option', async () => { await expect(page.getByLabel('Aktion', { exact: true }).locator('option[value="apt_native_acceptance"]')).toHaveCount(1); });
|
||||
await test.step('management:select-native', async () => { await page.getByLabel('Aktion', { exact: true }).selectOption('apt_native_acceptance'); });
|
||||
await test.step('management:native-hint', async () => { await expect(page.getByText('NUR SIMULIERTE DEV/TEST-NATIVABNAHME.', { exact: false })).toBeVisible(); });
|
||||
|
||||
@@ -34,8 +34,10 @@ test('simulated human prepares root request through UI only, without approving',
|
||||
const session = object(await (await sessionResponse).json());
|
||||
expect(session.testsimulation).toBe(true); expect(session.principal).toBe(expected.expected_principal);
|
||||
expect(session.approval_origin).toBe('dev_test_browser_simulation');
|
||||
await expect(page.getByLabel('Mandant', { exact: true })).toHaveValue(text(expected.tenant_id));
|
||||
await page.getByRole('combobox', { name: 'Kunde', exact: true }).selectOption(text(expected.tenant_id));
|
||||
await page.getByRole('checkbox', { name: `Ziel ${text(expected.asset_id)}`, exact: true }).check();
|
||||
await page.getByRole('link', { name: 'Aufträge', exact: true }).click();
|
||||
await page.getByRole('link', { name: 'Auftrag planen', exact: true }).click();
|
||||
await page.getByLabel('Aktion', { exact: true }).selectOption(text(request.action));
|
||||
if (request.action === 'run_script') {
|
||||
const variants = params.variants;
|
||||
@@ -93,8 +95,9 @@ test('one opted-in immutable dev/test action: inspect all fixed bytes → UI cli
|
||||
expect(session.testsimulation).toBe(true);
|
||||
expect(session.approval_origin).toBe('dev_test_browser_simulation');
|
||||
expect(session.principal).toBe(expected.expected_principal);
|
||||
await expect(page.getByLabel('Mandant', { exact: true })).toHaveValue(text(expected.tenant_id));
|
||||
await page.getByRole('combobox', { name: 'Kunde', exact: true }).selectOption(text(expected.tenant_id));
|
||||
const operation = text(expected.operation_id);
|
||||
await page.getByRole('link', { name: 'Aufträge', exact: true }).click();
|
||||
await page.getByRole('button', { name: operation, exact: true }).click();
|
||||
const op = page.locator('section').filter({ has: page.getByRole('heading', { name: `Antrag / Ausführung ${operation}`, exact: true }) });
|
||||
await expect(op.locator('p.warning')).toContainText('Antrag: pending_approval');
|
||||
|
||||
@@ -17,11 +17,13 @@ test('real TLS UI: login, tenant, fixed preview, pending, reload, CSRF denial an
|
||||
let authorizationRequests = 0;
|
||||
page.on('request', r => { if (new URL(r.url()).pathname.endsWith('/authorizations')) authorizationRequests++; });
|
||||
await login(page);
|
||||
await expect(page.getByLabel('Mandant', { exact: true })).not.toHaveValue('');
|
||||
await expect(page.getByRole('heading', { name: 'Geräte', exact: true })).toBeVisible();
|
||||
const cookies = await context.cookies();
|
||||
const authCookie = cookies.find(c => c.name === '__Host-rmm_session');
|
||||
expect(authCookie?.httpOnly).toBe(true); expect(authCookie?.secure).toBe(true); expect(authCookie?.sameSite).toBe('Strict');
|
||||
await page.getByRole('checkbox', { name: `Ziel ${asset}`, exact: true }).check();
|
||||
await page.getByRole('link', { name: 'Aufträge', exact: true }).click();
|
||||
await page.getByRole('link', { name: 'Auftrag planen', exact: true }).click();
|
||||
await page.getByLabel('Exakte UTF-8 Skriptbytes', { exact: false }).fill("printf '%s\\n' 'Hello World'\n");
|
||||
await page.getByLabel('Erwartete stdout-Ausgabe', { exact: false }).fill('Hello World\n');
|
||||
await page.getByLabel('Begründung', { exact: true }).fill('Authenticated synthetic local fixture · pending-only browser contract; do not execute');
|
||||
|
||||
@@ -8,6 +8,7 @@ test('preserved real VM: pending fixed Hello World → UI click → confirmed re
|
||||
const operation = process.env.RMM_E2E_OPERATION_ID;
|
||||
if (!asset || !operation) throw new Error('Fixed VM asset and existing pending operation required');
|
||||
await login(page);
|
||||
await page.getByRole('link', { name: 'Aufträge', exact: true }).click();
|
||||
await page.getByRole('button', { name: operation, exact: true }).click();
|
||||
const op = page.locator('section').filter({ has: page.getByRole('heading', { name: `Antrag / Ausführung ${operation}`, exact: true }) });
|
||||
await expect(op.locator('p.warning')).toContainText('Antrag: pending_approval');
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
-- Disposable PostgreSQL integration. Browser authentication is exercised separately.
|
||||
BEGIN;
|
||||
SELECT set_config('app.tenant_id','11111111-1111-4111-8111-111111111111',true);
|
||||
INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES
|
||||
('11111111-1111-4111-8111-111111111111','local:11112222-3333-4444-aaaa-000000000001','human',
|
||||
ARRAY['tokens:manage','inventory:read','operations:read','operations:plan']);
|
||||
SELECT provision_customer_admin('11111111-1111-4111-8111-111111111111','local:11112222-3333-4444-aaaa-000000000001');
|
||||
SET ROLE rmm_app;
|
||||
DO $$
|
||||
DECLARE
|
||||
a constant uuid:='11111111-1111-4111-8111-111111111111';
|
||||
b constant uuid:='22222222-2222-4222-8222-222222222222';
|
||||
c uuid:=gen_random_uuid();
|
||||
actor text:='local:11112222-3333-4444-aaaa-000000000001';
|
||||
selected_id uuid:=gen_random_uuid();
|
||||
both_id uuid:=gen_random_uuid();
|
||||
all_id uuid:=gen_random_uuid();
|
||||
selected_member text:='mcp:'||selected_id::text;
|
||||
all_member text:='mcp:'||all_id::text;
|
||||
scopes text[]:=ARRAY['inventory:read'];
|
||||
BEGIN
|
||||
IF has_function_privilege(current_user,'provision_customer_admin(uuid,text)','EXECUTE')
|
||||
OR has_table_privilege(current_user,'customer_member_index','SELECT')
|
||||
OR has_table_privilege(current_user,'customer_admins','INSERT')
|
||||
OR has_function_privilege(current_user,'mcp_effective_scopes(text,uuid)','EXECUTE') THEN
|
||||
RAISE EXCEPTION 'application credentials can alter the customer boundary';
|
||||
END IF;
|
||||
BEGIN
|
||||
PERFORM issue_customer_token('simulated-testprincipal-a',gen_random_uuid(),'forbidden',repeat('f',64),scopes,now()+interval '1 day',true,ARRAY[]::uuid[]);
|
||||
RAISE EXCEPTION 'simulated identity minted a global token';
|
||||
EXCEPTION WHEN insufficient_privilege THEN NULL; END;
|
||||
BEGIN
|
||||
PERFORM manage_customer('simulated-testprincipal-a',gen_random_uuid(),'Forbidden',true);
|
||||
RAISE EXCEPTION 'simulated identity created a customer';
|
||||
EXCEPTION WHEN insufficient_privilege THEN NULL; END;
|
||||
PERFORM issue_customer_token(actor,selected_id,'Only B',repeat('1',64),scopes,now()+interval '1 day',false,ARRAY[b]);
|
||||
PERFORM issue_customer_token(actor,both_id,'A+B',repeat('2',64),scopes,now()+interval '1 day',false,ARRAY[a,b]);
|
||||
PERFORM issue_customer_token(actor,all_id,'Global',repeat('3',64),scopes,now()+interval '1 day',true,ARRAY[]::uuid[]);
|
||||
IF mcp_credential_customers(repeat('1',64))<>ARRAY[b] OR mcp_principal_permission(selected_member,'inventory:read')
|
||||
OR NOT mcp_principal_permission(all_member,'inventory:read') THEN RAISE EXCEPTION 'unexpected issuing-customer visibility'; END IF;
|
||||
PERFORM manage_customer(actor,c,'New customer',true);
|
||||
PERFORM manage_customer(actor,c,'Renamed customer',false);
|
||||
IF cardinality(mcp_credential_customers(repeat('2',64)))<>2 OR c=ANY(mcp_credential_customers(repeat('2',64)))
|
||||
OR NOT c=ANY(mcp_credential_customers(repeat('3',64))) THEN RAISE EXCEPTION 'invalid future customer discovery'; END IF;
|
||||
PERFORM set_config('app.tenant_id',c::text,true);
|
||||
IF NOT mcp_principal_permission(all_member,'inventory:read') OR mcp_principal_permission(all_member,'operations:plan')
|
||||
OR mcp_principal_permission(selected_member,'inventory:read') OR current_setting('app.tenant_id')<>c::text
|
||||
OR (SELECT name FROM tenants) <> 'Renamed customer'
|
||||
OR NOT EXISTS(SELECT 1 FROM tenant_limits)
|
||||
OR NOT EXISTS(SELECT 1 FROM script_revisions)
|
||||
THEN RAISE EXCEPTION 'invalid new customer contents/permissions'; END IF;
|
||||
PERFORM set_config('app.tenant_id',b::text,true);
|
||||
IF NOT mcp_principal_permission(selected_member,'inventory:read') THEN RAISE EXCEPTION 'selected customer denied'; END IF;
|
||||
PERFORM set_config('app.tenant_id',a::text,true);
|
||||
PERFORM revoke_mcp_token(actor,all_id,gen_random_uuid());
|
||||
PERFORM set_config('app.tenant_id',c::text,true);
|
||||
IF cardinality(mcp_credential_customers(repeat('3',64)))<>0 OR cardinality(mcp_current_scopes(all_member))<>0
|
||||
THEN RAISE EXCEPTION 'revocation failed in foreign customer'; END IF;
|
||||
END $$;
|
||||
ROLLBACK;
|
||||
@@ -39,6 +39,8 @@ def main():
|
||||
ALTER SCHEMA public OWNER TO rmm_migrator;""")
|
||||
for path in sorted((ROOT / "migrations").glob("*.sql")):
|
||||
sql("rmm_migrator", path.read_text())
|
||||
sql("postgres", (ROOT / "tests/customer_access.sql").read_text())
|
||||
print("PASS selected, global and future customer grants, role boundaries, revocation and tenant context")
|
||||
test_command = [
|
||||
"docker", "run", "--rm", "--network", "container:" + name,
|
||||
"--read-only", "--tmpfs", "/tmp:rw,size=512m",
|
||||
@@ -50,7 +52,7 @@ def main():
|
||||
"--entrypoint", "cargo", "rust-discovery-windows-tls-full:local",
|
||||
"test", "--locked", "--offline", "-p", "rmm-server",
|
||||
]
|
||||
for test_filter in ("local_auth::tests", "mcp_tokens::tests"):
|
||||
for test_filter in ("local_auth::tests", "mcp_tokens::tests", "devices::tests"):
|
||||
output = command([*test_command, test_filter, "--", "--include-ignored", "--nocapture"], timeout=300)
|
||||
print(output.decode())
|
||||
print("PASS all migrations under NOSUPERUSER/NOBYPASSRLS owner; local MFA and MCP tests in isolated PostgreSQL")
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish selected signed agent packages for first enrollment in empty customer catalogs."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
from dev_stage import ssh_prefix
|
||||
|
||||
|
||||
def publish(tenant, platform, release):
|
||||
root = Path('/opt/rust-discovery/devstate/mvp-releases')
|
||||
labels = {'x86_64-pc-windows-gnu': 'windows-gnu', 'x86_64-unknown-linux-gnu': 'linux'}
|
||||
label = labels[platform]
|
||||
source = root / 'objects' / tenant
|
||||
config = root / 'config'
|
||||
dest = config / 'customer-starters'
|
||||
sql = """SELECT json_build_object('envelope',convert_from(envelope,'UTF8')::json,
|
||||
'agent',agent_sha256,'agent_size',agent_bytes,'helper',helper_sha256,'helper_size',helper_bytes)
|
||||
FROM agent_update_releases WHERE tenant_id=:'customer' AND platform=:'platform' AND release_id=:'release';"""
|
||||
row = json.loads(subprocess.check_output(['docker','exec','-i','rust-discovery-server-postgres-1',
|
||||
'psql','-XqtA','-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm','-v','customer='+tenant,
|
||||
'-v','platform='+platform,'-v','release='+release],input=sql.encode()))
|
||||
local_pin = config / (label+'-bootstrap.'+tenant+'.json')
|
||||
if local_pin.exists():
|
||||
worker = json.loads(local_pin.read_bytes())['current']
|
||||
else:
|
||||
default = json.loads((config / (label+'-bootstrap.json')).read_bytes())
|
||||
worker = {'sha256': default['updater_sha256'], 'bytes': default['updater_bytes']}
|
||||
desc = {'envelope': row['envelope'], 'worker': worker}
|
||||
dest.mkdir(mode=0o700,exist_ok=True)
|
||||
assert dest.is_dir() and not dest.is_symlink()
|
||||
os.chown(dest,10001,10001)
|
||||
os.chmod(dest,0o700)
|
||||
def write(name, blocks):
|
||||
with tempfile.NamedTemporaryFile(dir=dest,delete=False) as out:
|
||||
temp = Path(out.name)
|
||||
try:
|
||||
digest = hashlib.sha256()
|
||||
for data in blocks:
|
||||
out.write(data)
|
||||
digest.update(data)
|
||||
if len(name)==64 and digest.hexdigest()!=name:
|
||||
raise ValueError('Package object digest mismatch')
|
||||
out.flush()
|
||||
os.fchown(out.fileno(),10001,10001)
|
||||
os.fsync(out.fileno())
|
||||
os.replace(temp,dest/name)
|
||||
finally:
|
||||
temp.unlink(missing_ok=True)
|
||||
for digest,size in [(row['agent'],row['agent_size']),(row['helper'],row['helper_size']),(worker['sha256'],worker['bytes'])]:
|
||||
if not re.fullmatch('[a-f0-9]{64}',digest) or not 0<size<=268435456:
|
||||
raise ValueError('Invalid package descriptor')
|
||||
with os.fdopen(os.open(source/digest,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:
|
||||
info=os.fstat(f.fileno())
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_size!=size:
|
||||
raise ValueError('Missing regular package file')
|
||||
write(digest,iter(lambda:f.read(1024*1024),b''))
|
||||
write(platform+'.json',[json.dumps(desc,separators=(',',':')).encode()])
|
||||
print(json.dumps({'starter_platform':platform,'release_id':release}))
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--tenant',required=True,type=uuid.UUID)
|
||||
parser.add_argument('--platform',required=True,choices=['x86_64-unknown-linux-gnu','x86_64-pc-windows-gnu'])
|
||||
parser.add_argument('--release',required=True,type=uuid.UUID)
|
||||
args=parser.parse_args()
|
||||
imports='import hashlib,json,os,re,stat,subprocess,tempfile\nfrom pathlib import Path\n'
|
||||
script=imports+inspect.getsource(publish)+'\npublish'+repr((str(args.tenant),args.platform,str(args.release)))
|
||||
subprocess.run([*ssh_prefix('server'),'python3 -I -'],input=script,text=True,check=True)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -38,6 +38,21 @@ def on_server(payload):
|
||||
work.mkdir(mode=0o700,exist_ok=True)
|
||||
with (work/'deployment.lock').open('a') as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX)
|
||||
if payload['action']=='grant-customer-admin':
|
||||
principal = payload['principal']
|
||||
if 'local:' + str(uuid.UUID(principal.removeprefix('local:'))) != principal:
|
||||
raise ValueError('Invalid bootstrap principal')
|
||||
config_path = root / 'devstate/public-auth/users.json'
|
||||
configured = json.loads(config_path.read_bytes())['users']
|
||||
if not any(u['principal'] == principal and u['tenant_id'] == TENANT
|
||||
and u['username'] == 'kevin' and not u['disabled'] for u in configured):
|
||||
raise ValueError('Active public bootstrap account differs')
|
||||
query = f"SELECT provision_customer_admin('{TENANT}','{principal}');"
|
||||
subprocess.run(['docker','exec','-i','rust-discovery-server-postgres-1','psql','-XqAt',
|
||||
'-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm'],
|
||||
input=query,text=True,check=True,stdout=subprocess.DEVNULL)
|
||||
print(json.dumps({'customer_admin':principal}))
|
||||
return
|
||||
if payload['action']=='prepare':
|
||||
config=payload['accounts']
|
||||
user,=config['users']
|
||||
@@ -142,11 +157,11 @@ def on_server(payload):
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action',choices=('prepare','activate','publish'))
|
||||
parser.add_argument('action',choices=('prepare','activate','publish','grant-customer-admin'))
|
||||
args=parser.parse_args()
|
||||
os.umask(0o077)
|
||||
payload={'action':args.action}
|
||||
if args.action=='prepare':
|
||||
if args.action in ('prepare','grant-customer-admin'):
|
||||
path=ROOT/'credentials/public-webui-login.json'
|
||||
if path.exists():
|
||||
info=path.lstat()
|
||||
@@ -154,6 +169,8 @@ def main():
|
||||
raise ValueError('Unsafe bootstrap credential file')
|
||||
credentials=json.loads(path.read_bytes())
|
||||
else:
|
||||
if args.action=='grant-customer-admin':
|
||||
raise ValueError('Provision the local login before granting customer administration')
|
||||
secret=base64.b32encode(secrets.token_bytes(20)).decode().rstrip('=')
|
||||
password=secrets.token_urlsafe(32);salt=secrets.token_bytes(32)
|
||||
derived=hashlib.scrypt(password.encode(),salt=salt,n=1<<17,r=8,p=1,dklen=64,maxmem=256*1024*1024)
|
||||
@@ -164,7 +181,11 @@ def main():
|
||||
'accounts':{'schema_version':1,'users':[account]}}
|
||||
with path.open('x') as stream:json.dump(credentials,stream,indent=2)
|
||||
path.chmod(0o600)
|
||||
payload['accounts']=credentials['accounts']
|
||||
if args.action=='grant-customer-admin':
|
||||
account,=credentials['accounts']['users']
|
||||
payload['principal']=account['principal']
|
||||
else:
|
||||
payload['accounts']=credentials['accounts']
|
||||
else:
|
||||
names=['server.public-access.compose.yaml'] if args.action=='activate' else ['server-bootstrap-ingress.conf','server-bootstrap-ingress.service']
|
||||
payload['files']={name:base64.b64encode((ROOT/'deploy'/name).read_bytes()).decode() for name in names}
|
||||
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
<!doctype html>
|
||||
<html lang="de"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>RMM · Linux Verwaltung</title></head><body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body></html>
|
||||
<html lang="de"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta name="theme-color" content="#152d2a"/><title>Rust Discovery · Geräteverwaltung</title></head><body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body></html>
|
||||
|
||||
+3
-3
@@ -45,11 +45,11 @@ export function page(value: unknown): Page {
|
||||
return { items: r.items.map(v => record(v)), next_cursor: r.next_cursor, completeness: stringField(r, 'completeness'), truncated: r.truncated !== false, as_of: stringField(r, 'as_of') };
|
||||
}
|
||||
export class ApiError extends Error { constructor(public status: number, public code: string, message: string, public correlation: string) { super(`${code}: ${message}${correlation ? ` (Korrelation ${correlation})` : ''}`); } }
|
||||
export async function request(path: string, options: { body?: unknown; csrf?: string; signal?: AbortSignal } = {}): Promise<unknown> {
|
||||
export async function request(path: string, options: { body?: unknown; csrf?: string; signal?: AbortSignal; method?: 'PATCH'; tenantId?: string } = {}): Promise<unknown> {
|
||||
if (!path.startsWith('/') || path.startsWith('//')) throw new Error('Nur gleiche Origin erlaubt');
|
||||
const changing = options.body !== undefined;
|
||||
const response = await fetch(path, { method: changing ? 'POST' : 'GET', credentials: 'same-origin', cache: 'no-store', signal: options.signal,
|
||||
headers: changing ? { 'Content-Type': 'application/json', ...(options.csrf ? { 'X-CSRF-Token': options.csrf } : {}) } : {}, body: changing ? JSON.stringify(options.body) : undefined });
|
||||
const response = await fetch(path, { method: options.method ?? (changing ? 'POST' : 'GET'), credentials: 'same-origin', cache: 'no-store', signal: options.signal,
|
||||
headers: { ...(changing ? { 'Content-Type': 'application/json' } : {}), ...(changing && options.csrf ? { 'X-CSRF-Token': options.csrf } : {}), ...(options.tenantId ? { 'X-RMM-Tenant': options.tenantId } : {}) }, body: changing ? JSON.stringify(options.body) : undefined });
|
||||
const raw: unknown = response.status === 204 ? {} : await response.json().catch(() => { throw new ApiError(response.status, 'HTTP_ERROR', 'keine JSON-Antwort', ''); });
|
||||
if (!response.ok) { const r = record(raw); throw new ApiError(response.status, stringField(r, 'code'), stringField(r, 'message'), typeof r.correlation_id === 'string' ? r.correlation_id : ''); }
|
||||
return raw;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { request, tenant, tenantPath, type Session, type Tenant } from './api';
|
||||
|
||||
interface Props {
|
||||
auth: Session;
|
||||
customers: Tenant[];
|
||||
canManage: boolean;
|
||||
onChange: () => void;
|
||||
onSelect: (tenantId: string) => void;
|
||||
}
|
||||
|
||||
export function CustomerManagement({ auth, customers, canManage, onChange, onSelect }: Props) {
|
||||
const [editing, setEditing] = useState<Tenant | 'new' | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [notice, setNotice] = useState('');
|
||||
|
||||
function edit(customer: Tenant | 'new') {
|
||||
setEditing(customer);
|
||||
setName(customer === 'new' ? '' : customer.name);
|
||||
setError('');
|
||||
setNotice('');
|
||||
}
|
||||
|
||||
async function save(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
if (!canManage || !editing || pending || !name.trim()) return;
|
||||
setPending(true);
|
||||
setError('');
|
||||
try {
|
||||
const change = { csrf: auth.csrf_token, body: { name: name.trim() } };
|
||||
const response = editing === 'new'
|
||||
? await request('/api/v1/tenants', change)
|
||||
: await request(tenantPath(editing.tenant_id), { ...change, method: 'PATCH', tenantId: editing.tenant_id });
|
||||
const saved = tenant(response);
|
||||
setNotice(editing === 'new' ? `Kunde „${saved.name}“ angelegt.` : `Kundenname in „${saved.name}“ geändert.`);
|
||||
setEditing(null);
|
||||
onChange();
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Der Kunde konnte nicht gespeichert werden.');
|
||||
} finally { setPending(false); }
|
||||
}
|
||||
|
||||
return <section aria-label="Kundenverwaltung">
|
||||
<div className="section-heading"><h2>Kundenverzeichnis</h2>
|
||||
{canManage && <button type="button" onClick={() => edit('new')} disabled={pending}>Kunde anlegen</button>}</div>
|
||||
{canManage && editing && <form onSubmit={save}><fieldset disabled={pending}>
|
||||
<legend>{editing === 'new' ? 'Neuer Kunde' : 'Kunde umbenennen'}</legend>
|
||||
<label>Kundenname<input autoFocus required maxLength={120} value={name} onChange={e => setName(e.target.value)}/></label>
|
||||
{error && <p role="alert" className="error">{error}</p>}
|
||||
<button type="submit" disabled={!name.trim()}>Speichern</button>{' '}
|
||||
<button type="button" onClick={() => setEditing(null)}>Abbrechen</button>
|
||||
</fieldset></form>}
|
||||
{notice && <p role="status">{notice}</p>}
|
||||
<div className="table"><table><thead><tr><th>Kunde</th><th>Aktionen</th></tr></thead>
|
||||
<tbody>{customers.map(customer => <tr key={customer.tenant_id}>
|
||||
<td>{customer.name}</td><td><button type="button" onClick={() => onSelect(customer.tenant_id)} aria-label={`Geräte von ${customer.name} anzeigen`}>Geräte anzeigen</button>{' '}
|
||||
{canManage && <button type="button" onClick={() => edit(customer)} disabled={pending} aria-label={`${customer.name} umbenennen`}>Umbenennen</button>}</td>
|
||||
</tr>)}</tbody></table></div>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { objectId, page, pretty, record, request, session, tenantPath, type RecordValue, type Session, type Tenant } from './api';
|
||||
import { AdminControl } from './management';
|
||||
import { allowed } from './safety';
|
||||
import { CatalogCheckNotice } from './catalog-check';
|
||||
import { ErrorBox, errorText, useResource } from './resource';
|
||||
import { NavIcon } from './navigation';
|
||||
import { RecoveryReview, recoveryAsset, recoveryTenant } from './recovery-review';
|
||||
import { EchoProbeReview } from './echo-probe-review';
|
||||
import { EchoCompletionReview } from './echo-completion-review';
|
||||
import { SyncAlignmentReview } from './sync-alignment-review';
|
||||
import { SystemNonstartReview } from './system-nonstart-review';
|
||||
|
||||
const unknown = 'Nicht gemeldet';
|
||||
const number = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 1 });
|
||||
const date = new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium', timeStyle: 'short' });
|
||||
function label(value: unknown) { return typeof value === 'string' && value.trim() ? value : unknown; }
|
||||
function time(value: unknown) {
|
||||
const t = typeof value === 'string' ? Date.parse(value) : NaN;
|
||||
return Number.isFinite(t) ? date.format(t) : unknown;
|
||||
}
|
||||
function gib(v: unknown) { return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? number.format(v / 2 ** 30) : null; }
|
||||
function capacity(free: unknown, total: unknown) {
|
||||
const f = gib(free), t = gib(total);
|
||||
return f === null && t === null ? unknown : `${f ?? '–'} / ${t ?? '–'} GiB`;
|
||||
}
|
||||
function cpu(d: RecordValue) {
|
||||
const model = label(d.cpu_model), count = d.cpu_logical_count;
|
||||
const threads = typeof count === 'number' && count > 0 ? `${count} log. CPU${count === 1 ? '' : 's'}` : '';
|
||||
return { primary: model === unknown ? threads || unknown : model, secondary: model === unknown ? '' : threads };
|
||||
}
|
||||
const states: Record<string,string> = { online: 'Online', offline: 'Offline', never_seen: 'Ohne Erstkontakt', revoked: 'Widerrufen', archived: 'Archiviert', replaced: 'Ersetzt', unverified: 'Identität unbestätigt' };
|
||||
function Presence({ d }: { d: RecordValue }) {
|
||||
const state = typeof d.lifecycle === 'string' && d.lifecycle !== 'current' ? d.lifecycle : String(d.status);
|
||||
return <span className={'presence ' + (state === 'online' ? 'online' : state === 'offline' ? 'offline' : 'historic')}><i/>{states[state] ?? 'Unbekannt'}</span>;
|
||||
}
|
||||
function Storage({ d }: { d: RecordValue }) {
|
||||
const free = d.disk_free_bytes, total = d.disk_total_bytes;
|
||||
return <><span>{capacity(free,total)}</span>{typeof free === 'number' && typeof total === 'number' && free >= 0 && free <= total && total > 0 &&
|
||||
<span className="capacity-track" title={`${number.format(100*free/total)} % frei`} aria-hidden="true"><i style={{ width: `${100*(total-free)/total}%` }}/></span>}</>;
|
||||
}
|
||||
|
||||
type Target = { customer: string; ids: string[] };
|
||||
type Props = {
|
||||
auth: Session; customers: Tenant[]; filter: string; onFilter: (id: string) => void;
|
||||
selection: Target; onSelection: (s: Target) => void;
|
||||
onScripts: () => void; onEnroll: () => void; onOperation: (customer: string, id: string) => void;
|
||||
};
|
||||
function devicePath(customer: string, asset: string) { return tenantPath(customer, '/devices/' + encodeURIComponent(asset)); }
|
||||
|
||||
function DeviceDetail({ customer, asset, agent, auth, back, openOperation, changed }: {
|
||||
customer: string; asset: string; agent: string; auth: Session; back: () => void;
|
||||
openOperation: (id: string) => void; changed: () => void;
|
||||
}) {
|
||||
const path = devicePath(customer, asset);
|
||||
const detail = useResource(async signal => record(await request(path+'?agent_id='+encodeURIComponent(agent), { signal })), [customer,asset,agent], true);
|
||||
const membership = useResource(async signal => session(await request('/auth/session', { signal, tenantId: customer })), [customer,auth.principal.id]);
|
||||
const [busy, setBusy] = useState(false), [error, setError] = useState<string|null>(null);
|
||||
const d = detail.data;
|
||||
const scoped = membership.data;
|
||||
const volumes = Array.isArray(d?.volumes) ? d.volumes.map(v=>record(v)) : [];
|
||||
const jobs = Array.isArray(d?.recent_jobs) ? d.recent_jobs.map(v=>record(v)) : null;
|
||||
const facts = d && [
|
||||
['Kunde', label(d.customer_name)], ['Betriebssystem',label(d.os)], ['RAM', gib(d.ram_total_bytes) === null ? unknown : gib(d.ram_total_bytes)+' GiB'],
|
||||
['CPU',[cpu(d).primary,cpu(d).secondary].filter(Boolean).join(' · ')], ['Speicher frei / gesamt',capacity(d.disk_free_bytes,d.disk_total_bytes)],
|
||||
['Letzter Kontakt',time(d.last_contact_at)], ['Inventar erhoben',time(d.observed_at)], ['Agentversion',label(d.agent_version)]
|
||||
];
|
||||
return <div className="device-detail">
|
||||
<button className="quiet" onClick={back}><NavIcon name="zurueck"/> Zur Geräteliste</button>
|
||||
<ErrorBox error={detail.error ?? membership.error ?? error}/>
|
||||
{!d && !detail.error && <p>Inventar wird geladen …</p>}
|
||||
{d && <><div className="page-title"><div><h1>{label(d.hostname)}</h1><Presence d={d}/></div></div>
|
||||
<section><h2>Geräteinformationen</h2><dl className="facts">{facts?.map(([k,v])=><div key={k}><dt>{k}</dt><dd>{v}</dd></div>)}</dl></section>
|
||||
{volumes.length > 0 && <section><h2>Laufwerke</h2><div className="table"><table><thead><tr><th>Laufwerk</th><th>Speicher frei / gesamt</th></tr></thead><tbody>{volumes.map((v,i)=><tr key={i}><td>{label(v.name)}</td><td>{capacity(v.free_bytes,v.total_bytes)}</td></tr>)}</tbody></table></div></section>}
|
||||
{jobs && <section><h2>Letzte Aufträge</h2>{jobs.length === 0 ? <p className="muted">Keine Aufträge für dieses Gerät.</p> : <ul className="job-list">{jobs.map(j=><li key={objectId(j,'job')}><button className="link" onClick={()=>openOperation(objectId(j,'operation'))}>Auftrag vom {time(j.created_at)}</button><span>{label(j.state)}</span></li>)}</ul>}</section>}
|
||||
<section><details><summary>Technische Daten</summary><CatalogCheckNotice device={d}/><pre aria-label="Vollständiges Geräteinventar">{pretty(d)}</pre></details>
|
||||
{scoped && allowed(scoped,'devices:revoke') && <details><summary>Gerät verwalten</summary>
|
||||
{['archived','current'].includes(String(d.lifecycle)) && <button disabled={busy} onClick={async()=>{
|
||||
setBusy(true);setError(null);
|
||||
try { await request(path+'/archive',{csrf:scoped.csrf_token,body:{archived:d.lifecycle!=='archived'}});changed(); }
|
||||
catch(e){ setError(errorText(e)); } finally{ setBusy(false); }
|
||||
}}>{d.lifecycle==='archived' ? 'Zurück in den Bestand' : 'In die Historie verschieben'}</button>}
|
||||
{d.lifecycle==='current' && <AdminControl auth={scoped} path={path+'/revocation'} permission="devices:revoke" title="Geräteidentität widerrufen" warning="Der Widerruf unterbricht die Geräteverwaltung und sperrt neue Starts. Die Wiederaufnahme erfordert eine neue Registrierung." done={changed}/>}
|
||||
</details>}</section>
|
||||
{scoped && customer===recoveryTenant && asset===recoveryAsset && allowed(scoped,'inventory:read') && <details><summary>Entwicklungsabnahmen</summary><SystemNonstartReview auth={scoped}/><SyncAlignmentReview auth={scoped}/><EchoProbeReview auth={scoped}/><EchoCompletionReview auth={scoped}/><RecoveryReview auth={scoped}/></details>}
|
||||
</>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function Devices({ auth, customers, filter, onFilter, selection, onSelection, onEnroll, onScripts, onOperation }: Props) {
|
||||
const [search,setSearch]=useState(''), [query,setQuery]=useState(''), [status,setStatus]=useState(''), [history,setHistory]=useState(false);
|
||||
const [routes,setRoutes]=useState<string[]>([]), [target,setTarget]=useState<{customer:string;asset:string;agent:string}|null>(null);
|
||||
const cursor=routes[routes.length-1];
|
||||
useEffect(()=>{ const timer=setTimeout(()=>{ setQuery(search.trim());setRoutes([]); },200);return ()=>clearTimeout(timer); },[search]);
|
||||
const list=useResource(async signal=>{
|
||||
if(target) return null;
|
||||
const params=new URLSearchParams({view:history?'history':'current',limit:'40'});
|
||||
if(query) params.set('q',query);if(status && !history) params.set('status',status);if(cursor) params.set('cursor',cursor);
|
||||
const path=filter?tenantPath(filter,'/devices'):'/api/v1/devices';
|
||||
return page(await request(path+'?'+params, {signal}));
|
||||
},[filter,query,history,status,cursor,target],true);
|
||||
function setView(historic:boolean){setRoutes([]);setHistory(historic);onSelection({customer:'',ids:[]});}
|
||||
function select(d:RecordValue,checked:boolean) {
|
||||
const asset=objectId(d,'asset'),customer=objectId(d,'tenant');
|
||||
if(checked && selection.ids.length && customer!==selection.customer) return;
|
||||
const ids=checked?[...selection.ids,asset]:selection.ids.filter(id=>id!==asset);
|
||||
onSelection({ customer:ids.length?customer:'',ids });
|
||||
}
|
||||
if(target) return <DeviceDetail key={target.agent} {...target} auth={auth} back={()=>setTarget(null)} openOperation={id=>onOperation(target.customer,id)}
|
||||
changed={()=>{setTarget(null);setRoutes([]);onSelection({customer:'',ids:[]});list.reload();}}/>;
|
||||
return <>
|
||||
<div className="page-title"><div><h1>Geräte</h1></div>{allowed(auth,'devices:enroll') && <button className="primary" onClick={onEnroll}><NavIcon name="plus"/> Gerät aufnehmen</button>}</div>
|
||||
<section className="fleet" aria-label="Gerätebestand">
|
||||
<div className="fleet-tabs"><button aria-pressed={!history} onClick={()=>{if(history)setView(false);}}>Bestand</button><button aria-pressed={history} onClick={()=>{if(!history)setView(true);}}>Historie</button></div>
|
||||
<div className="filters"><label className="search-box"><span className="sr-only">Hostname suchen</span><NavIcon name="suchen"/><input type="search" placeholder="Hostname suchen …" maxLength={120} value={search} onChange={e=>setSearch(e.target.value)}/></label>
|
||||
<label><span>Kunde</span><select value={filter} onChange={e=>{setRoutes([]);onFilter(e.target.value);}}><option value="">Alle Kunden</option>{customers.map(c=><option value={c.tenant_id} key={c.tenant_id}>{c.name}</option>)}</select></label>
|
||||
{!history && <label><span>Status</span><select value={status} onChange={e=>{setRoutes([]);setStatus(e.target.value);}}><option value="">Jeder Status</option><option value="online">Online</option><option value="offline">Offline</option></select></label>}
|
||||
</div>
|
||||
<ErrorBox error={list.error}/>
|
||||
{history && <p className="history-hint">Ausgemusterte Geräte und Registrierungen ohne bestätigte Identität.</p>}
|
||||
{!list.data && !list.error && <p className="list-message">Geräte werden geladen …</p>}
|
||||
{list.data && <><div className="table fleet-table"><table><thead><tr>{!history && <th className="target-col"><span className="sr-only">Ziel auswählen</span></th>}{['Hostname','OS','Status','Speicher frei / gesamt','RAM','CPU','Kunde'].map(h=><th scope="col" key={h}>{h}</th>)}</tr></thead>
|
||||
<tbody>{list.data.items.map(d=>{
|
||||
const asset=objectId(d,'asset'), agent=objectId(d,'agent'),customer=objectId(d,'tenant'),model=cpu(d);
|
||||
const show=()=>setTarget({asset,agent,customer});
|
||||
const another=selection.ids.length>0 && selection.customer!==customer;
|
||||
return <tr key={agent} onClick={show}>
|
||||
{!history && <td className="target-col" onClick={e=>e.stopPropagation()}><input type="checkbox" aria-label={'Ziel '+asset} title={another?'Aufträge werden je Kunde geplant':'Für Auftrag auswählen'} disabled={another} checked={selection.customer===customer && selection.ids.includes(asset)} onChange={e=>select(d,e.target.checked)}/></td>}
|
||||
<td className="hostname"><button className="host-link" onClick={e=>{e.stopPropagation();show();}}>{label(d.hostname)}</button></td>
|
||||
<td data-label="OS">{label(d.os)}</td><td data-label="Status" className="device-presence"><Presence d={d}/>{d.status==='offline' && d.lifecycle==='current' && <small>Zuletzt {time(d.last_contact_at)}</small>}</td>
|
||||
<td data-label="Speicher frei / gesamt" className="storage"><Storage d={d}/></td><td data-label="RAM">{gib(d.ram_total_bytes)===null?unknown:gib(d.ram_total_bytes)+' GiB'}</td>
|
||||
<td data-label="CPU">{model.primary}{model.secondary && <small>{model.secondary}</small>}</td><td data-label="Kunde">{label(d.customer_name)}</td>
|
||||
</tr>;
|
||||
})}</tbody></table></div>
|
||||
{!list.data.items.length && <div className="empty-list"><NavIcon name="geraete"/><h3>{query||filter||status?'Keine passenden Geräte':'Keine Geräte in dieser Ansicht'}</h3>{(query||filter||status) && <button className="quiet" onClick={()=>{setSearch('');setQuery('');setRoutes([]);setStatus('');onFilter('');}}>Filter zurücksetzen</button>}</div>}
|
||||
<div className="list-footer"><span>{list.data.items.length} {list.data.items.length===1?'Gerät':'Geräte'}{cursor||list.data.next_cursor?' auf dieser Seite':''} · Stand {time(list.data.as_of)}</span>
|
||||
{(cursor||list.data.next_cursor) && <div><button className="quiet" disabled={!cursor} onClick={()=>setRoutes(old=>old.slice(0,-1))}>Zurück</button><button className="quiet" disabled={!list.data.next_cursor} onClick={()=>{const next=list.data?.next_cursor;if(next)setRoutes(old=>[...old,next]);}}>Weiter</button></div>}</div>
|
||||
</>}
|
||||
</section>
|
||||
{!!selection.ids.length && <div className="selection"><div><strong>{selection.ids.length} {selection.ids.length===1?'Gerät':'Geräte'} ausgewählt</strong><small>{customers.find(c=>c.tenant_id===selection.customer)?.name}</small></div>
|
||||
<button className="quiet" onClick={()=>onSelection({customer:'',ids:[]})}>Auswahl aufheben</button><button onClick={onScripts}>Skript auswählen</button></div>}
|
||||
</>;
|
||||
}
|
||||
+86
-47
@@ -1,23 +1,20 @@
|
||||
import { Devices } from './devices';
|
||||
import { CustomerManagement } from './customer-management';
|
||||
import { ErrorBox, useResource, errorText } from './resource';
|
||||
import { NavIcon, type NavKey } from './navigation';
|
||||
import { ScriptLibrary } from './script-library';
|
||||
import { McpTokenManagement } from './mcp-token-management';
|
||||
import { CatalogCheckNotice } from './catalog-check';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput, windowsPowerShellRemoteSignedProfile, fullMaintenanceScriptProfile } from './api';
|
||||
import './style.css';
|
||||
import { AdminControl, Catalog, TenantControls } from './management';
|
||||
import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs, windowsMsiApprovalBlockers, windowsMsiPlanJobs, verifyWindowsMsiManifest, fullMaintenanceWarning } from './safety';
|
||||
import { RecoveryReview, recoveryAsset, recoveryTenant } from './recovery-review';
|
||||
import { EchoProbeReview } from './echo-probe-review';
|
||||
import { EchoCompletionReview } from './echo-completion-review';
|
||||
import { SyncAlignmentReview } from './sync-alignment-review';
|
||||
import { SystemNonstartReview } from './system-nonstart-review';
|
||||
import { Login } from './login';
|
||||
import { ConsoleOutput, outputText } from './console-output';
|
||||
import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console';
|
||||
import { agentUpdateWarning, agentUpdatePlanJobs, agentUpdateApprovalBlockers, verifyAgentUpdatePlan, verifyReleaseMetadata, releaseEnvelope, uploadAgentUpdateArtifact } from './agent-updates';
|
||||
|
||||
const errorText = (error: unknown) => error instanceof Error ? error.message : 'Unbekannter Fehler';
|
||||
export function JsonView({ value, label = 'Vollständige Daten' }: { value: unknown; label?: string }) { return <details open><summary>{label}</summary><pre aria-label={label}>{pretty(value)}</pre></details>; }
|
||||
export function AgentUpdatePlanNotice({ plan }: { plan: RecordValue }) {
|
||||
try {
|
||||
@@ -94,33 +91,7 @@ export function QueryLogsPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
return <aside className="warning" aria-label="Feste Live-Logfenster"><p>UI-genehmigte Liveabfrage aus hashgeprüften gespeicherten Planbytes; kein passives Inventar, keine automatische Erhebung.</p><ul>{jobs.map((job, i) => <li key={i}>Asset: {job.assetId} · Quelle: {job.source}{job.windows ? <> · Kanal: {job.channel} · Provider: {job.provider} · agent_service</> : ' · Linux-Journal'} · UTC-Fenster: [{job.since}, {job.until}) · maximal {job.maxLines} {job.windows ? 'Events' : 'Zeilen'} · {job.outputBytes} Bytes · äußere Joblaufzeit {job.runtimeSeconds}s{job.windows && ' · inneres Abfragebudget höchstens5000ms, zwischen Win32-Aufrufen kooperativ geprüft'}</li>)}</ul><p>Grenzen, Abbruch, fehlende Rechte und Teilabdeckung bleiben sichtbar. Keine Bookmarkfortschreibung durch diesen Auftrag; die Abfrage behauptet keine vollständige Sammlung aller Systemlogs.</p></aside>;
|
||||
} catch { return <aside role="alert" className="error">Logfenster ist nicht verifiziert oder wurde verändert. Keine Genehmigung ohne gültige gespeicherte Planbytes.</aside>; }
|
||||
}
|
||||
function ErrorBox({ error }: { error: string | null }) { return error ? <div role="alert" className="error">{error}</div> : null; }
|
||||
function useResource<T>(load: (signal: AbortSignal) => Promise<T>, deps: React.DependencyList, poll = false) {
|
||||
const [data, setData] = useState<T | null>(null), [error, setError] = useState<string | null>(null), [revision, setRevision] = useState(0);
|
||||
useEffect(() => {
|
||||
let active = true; const controller = new AbortController(); let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
setData(null); setError(null);
|
||||
const run = async () => { try { const result = await load(controller.signal); if (active) { setData(result); setError(null); } } catch (e) { if (active) setError(errorText(e)); }
|
||||
finally { if (active && poll) timer = setTimeout(run, 4000); } };
|
||||
void run(); return () => { active = false; controller.abort(); clearTimeout(timer); };
|
||||
}, [...deps, revision]);
|
||||
return { data, error, reload: () => setRevision(v => v + 1) };
|
||||
}
|
||||
function PageStatus({ data }: { data: Page }) { return <p className={data.completeness === 'complete' && !data.truncated ? 'muted' : 'warning'}>Listenstand: {data.as_of} · Vollständigkeit: {data.completeness} · begrenzt: {String(data.truncated)}. Fehlende Einträge sind kein Löschungsnachweis.</p>; }
|
||||
function Age({ value }: { value: unknown }) { const ms = typeof value === 'string' ? Date.parse(value) : NaN; return <span>{Number.isFinite(ms) ? `${Math.max(0, Math.floor((Date.now() - ms) / 1000))} s` : 'unknown'}</span>; }
|
||||
|
||||
function Devices({ tenantId, auth, selected, setSelected }: { tenantId: string; auth: Session; selected: string[]; setSelected: (ids: string[]) => void }) {
|
||||
const [cursor, setCursor] = useState<string | null>(null), [asset, setAsset] = useState<string | null>(null);
|
||||
const list = useResource(async signal => page(await request(tenantPath(tenantId, `/devices${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`), { signal })), [tenantId, cursor], true);
|
||||
const detail = useResource(async signal => asset ? record(await request(tenantPath(tenantId, `/devices/${encodeURIComponent(asset)}`), { signal })) : null, [tenantId, asset], true);
|
||||
return <section><h2>Geräte und gespeichertes Inventar</h2><p>Präsenz, Datenfrische und fachliche Gesundheit sind unabhängig. „unreachable“ bedeutet nicht „ausgeschaltet“.</p><ErrorBox error={list.error}/>
|
||||
{!list.data ? <p>Lade Geräte …</p> : <><PageStatus data={list.data}/><div className="table"><table><thead><tr><th>Fest auswählen</th><th>Gerät / Asset-ID</th><th>Präsenz / Gesundheit</th><th>Quelle / Qualität</th><th>Erhebung / Alter / Empfang</th></tr></thead><tbody>{list.data.items.map(d => { const id = objectId(d, 'asset'); return <tr key={id}><td><input aria-label={`Ziel ${id}`} type="checkbox" checked={selected.includes(id)} onChange={e => setSelected(e.target.checked ? [...selected, id] : selected.filter(v => v !== id))}/></td><td><button className="link" onClick={() => setAsset(id)}>{typeof d.hostname === 'string' ? d.hostname : id}</button><small>{id}</small></td><td>{stringField(d, 'presence')} / {stringField(d, 'health')}<small>Kontakt: {stringField(d, 'last_contact_at')}</small></td><td>{stringField(d, 'source_id')} / {stringField(d, 'quality')}<small>{stringField(d, 'completeness')}</small></td><td>{stringField(d, 'observed_at')}<small>Alter: <Age value={d.observed_at}/> · empfangen: {stringField(d, 'received_at')}</small></td></tr>; })}</tbody></table></div>{!list.data.items.length && <p>Keine sichtbaren Geräte in diesem Listenabschnitt.</p>}<button disabled={!cursor} onClick={() => setCursor(null)}>Erste Seite</button> <button disabled={!list.data.next_cursor} onClick={() => setCursor(list.data?.next_cursor ?? null)}>Nächste Seite</button></>}
|
||||
<p>Fester Auswahlsnapshot ({selected.length}): {selected.join(', ') || 'keine Ziele'}</p>
|
||||
{asset && <article><h3>Inventardetail {asset}</h3><ErrorBox error={detail.error}/>{detail.data && <><CatalogCheckNotice device={detail.data}/><JsonView value={detail.data} label="Inventar, Capabilities, Metriken, Dienste, Software, Updates, Logs und Quellen (soweit geliefert)"/></>}<AdminControl auth={auth} path={tenantPath(tenantId, `/devices/${encodeURIComponent(asset)}/revocation`)} permission="devices:revoke" title="Geräteidentität widerrufen" warning="ACHTUNG: Widerruf unterbricht die Geräteverwaltung und sperrt neue Starts. Kein Entfernen aus einer Liste, kein Rollback. Wiederaufnahme erfordert einen gesonderten sicheren Enrollment-/Recoveryprozess." done={detail.reload}/></article>}
|
||||
{tenantId === recoveryTenant && asset === recoveryAsset && allowed(auth, 'inventory:read') &&
|
||||
<><SystemNonstartReview key={auth.principal.id + '-system-nonstart-221'} auth={auth}/><SyncAlignmentReview key={auth.principal.id + '-alignment'} auth={auth}/><EchoProbeReview key={auth.principal.id + '-probe'} auth={auth}/><EchoCompletionReview key={auth.principal.id + '-completion'} auth={auth}/><RecoveryReview key={auth.principal.id} auth={auth}/></>}
|
||||
</section>;
|
||||
}
|
||||
const initialParameters: Record<Action, RecordValue> = {
|
||||
run_script: {}, refresh_inventory: { scope: 'linux.base' }, query_logs: { unit: '', since: '', until: '', max_lines: 1000 }, set_service_state: { unit: '', state: 'running' }, ensure_package: { provider: 'apt', recipe_version: '', package: '', version: '', architecture: 'amd64', installation_context: 'system', apt_manifest: null }, apply_updates: { provider: 'apt', packages: [], reboot_policy: 'never', apt_manifest: null }, reboot: { reason: '', dependency_group: '', reconnect_timeout_seconds: 300 }, apt_native_acceptance: { recipe_id: 'rmm-apt-fixture-install-1.0', recipe_version: '1', apt_manifest: null },
|
||||
update_agent: { release_id: '' },
|
||||
@@ -175,7 +146,7 @@ function WindowsMsiCatalog({ tenantId, auth }: { tenantId: string; auth: Session
|
||||
</section>;
|
||||
}
|
||||
|
||||
function AgentReleaseCatalog({ tenantId, auth }: { tenantId: string; auth: Session }) {
|
||||
function AgentReleaseCatalog({ tenantId, auth, customerName, enrollmentOpen }: { tenantId: string; auth: Session; customerName: string; enrollmentOpen: boolean }) {
|
||||
const [cursor, setCursor] = useState<string | null>(null), [revision, setRevision] = useState(0), [source, setSource] = useState('{}'), [busy, setBusy] = useState(false), [error, setError] = useState<string | null>(null), [receipts, setReceipts] = useState<unknown[]>([]);
|
||||
const [enrollment, setEnrollment] = useState<{ token: string; expires: string; origin: string | null; platforms: string[] } | null>(null);
|
||||
const [enrollmentError, setEnrollmentError] = useState<string | null>(null);
|
||||
@@ -205,9 +176,9 @@ function AgentReleaseCatalog({ tenantId, auth }: { tenantId: string; auth: Sessi
|
||||
<button disabled={busy || !allowed(auth, 'catalog:write')}>Release für Clients veröffentlichen</button><ErrorBox error={error}/>{receipts.length > 0 && <JsonView value={receipts} label="Tatsächliche Teilimport- und Veröffentlichungsbelege"/>}
|
||||
</form>
|
||||
</details>
|
||||
<details onToggle={event => { if (!event.currentTarget.open) setEnrollment(null); }}>
|
||||
<details open={enrollmentOpen || undefined} onToggle={event => { if (!event.currentTarget.open) setEnrollment(null); }}>
|
||||
<summary>Neues Gerät aufnehmen</summary>
|
||||
<p>Das HTTPS-Installationsskript fragt auf dem Gerät nach dem Einmalcode. Er gilt für den ausgewählten Mandanten und läuft nach 15 Minuten ab.</p>
|
||||
<p>Das HTTPS-Installationsskript fragt auf dem Gerät nach dem Einmalcode. Er gilt für <strong>{customerName}</strong> und läuft nach 15 Minuten ab.</p>
|
||||
<button disabled={issuing || !allowed(auth, 'devices:enroll')} onClick={async () => {
|
||||
setIssuing(true); setEnrollment(null); setEnrollmentError(null);
|
||||
try {
|
||||
@@ -287,18 +258,86 @@ function UnknownClosure({ tenantId, id, job, auth, done }: { tenantId: string; i
|
||||
await request(tenantPath(tenantId, `/jobs/${encodeURIComponent(id)}/unknown-closure`), { csrf: auth.csrf_token, body: { attempt_id: stringField(job, 'attempt_id'), revision: job.revision, reason: reason.trim() } }); setConfirmed(false); done();
|
||||
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>{auth.principal.simulated ? 'SIMULIERT: Unknown-Job ausdrücklich abschließen' : 'Unknown-Job ausdrücklich abschließen'}</button></section>;
|
||||
}
|
||||
function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
||||
const tenants = useResource(async signal => page(await request('/api/v1/tenants', { signal })), []);
|
||||
const [tenantId, setTenant] = useState(auth.tenants[0]?.tenant_id ?? ''), [error, setError] = useState<string | null>(null);
|
||||
const options = tenants.data?.items.map(tenant) ?? auth.tenants;
|
||||
useEffect(() => { if (!tenantId && options[0]) setTenant(options[0].tenant_id); }, [options, tenantId]);
|
||||
return <><header><div><h1>RMM <span>Geräteverwaltung</span></h1><p>{auth.principal.display_name} · {auth.principal.id}</p></div><button onClick={async () => { try { await request('/auth/logout', { csrf: auth.csrf_token, body: {} }); logout(); } catch (e) { setError(errorText(e)); } }}>Abmelden</button></header>
|
||||
{auth.principal.simulated && <aside className="simulation" role="status">SIMULIERT · dev/test-Testprincipal · Genehmigung ist eine Entwicklungs-Browsersimulation, kein menschlicher Produktions-Freigabenachweis.</aside>}
|
||||
<main><ErrorBox error={error}/><ErrorBox error={tenants.error}/><label>Mandant<select aria-label="Mandant" value={tenantId} onChange={e => setTenant(e.target.value)}><option value="" disabled>Mandant wählen</option>{options.map(t => <option key={t.tenant_id} value={t.tenant_id}>{t.name} · {t.tenant_id}</option>)}</select></label>{tenantId && <TenantWorkspace key={tenantId} tenantId={tenantId} auth={auth}/>}</main></>;
|
||||
const pages: Record<NavKey,string> = { geraete: 'Geräte', auftraege: 'Aufträge', skripte: 'Skripte', kunden: 'Kunden', verwaltung: 'Verwaltung' };
|
||||
function currentRoute() {
|
||||
const [key = 'geraete',tab] = window.location.hash.slice(1).split('/');
|
||||
return { page: (Object.hasOwn(pages,key) ? key : 'geraete') as NavKey, tab: tab ?? '' };
|
||||
}
|
||||
function TenantWorkspace({ tenantId, auth }: { tenantId: string; auth: Session }) {
|
||||
const [selected, setSelected] = useState<string[]>([]), [planId, setPlan] = useState<string | null>(null), [operationId, setOperation] = useState<string | null>(null);
|
||||
return <><Devices tenantId={tenantId} auth={auth} selected={selected} setSelected={setSelected}/><ScriptLibrary tenantId={tenantId} auth={auth} selected={selected} showPlan={setPlan}/><Planner tenantId={tenantId} auth={auth} selected={selected} showPlan={setPlan}/><Catalog tenantId={tenantId} auth={auth}/><WindowsMsiCatalog tenantId={tenantId} auth={auth}/><AgentReleaseCatalog tenantId={tenantId} auth={auth}/><TenantControls tenantId={tenantId} auth={auth}/><McpTokenManagement tenantId={tenantId} auth={auth}/><Operations tenantId={tenantId} open={setOperation}/>{operationId && <OperationDetail key={operationId} tenantId={tenantId} id={operationId} auth={auth} openPlan={setPlan}/ >}{planId && <PlanDetail key={planId} tenantId={tenantId} id={planId} auth={auth} onOperation={setOperation}/>}</>;
|
||||
function go(page: NavKey, tab = '') { window.location.hash = page + (tab ? '/' + tab : ''); }
|
||||
|
||||
function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
||||
const [route,setRoute] = useState(currentRoute);
|
||||
useEffect(()=>{ const change=()=>{setRoute(currentRoute());window.scrollTo(0,0);}; window.addEventListener('hashchange',change);return ()=>window.removeEventListener('hashchange',change); },[]);
|
||||
useEffect(()=>{document.title=pages[route.page]+' · Rust Discovery';},[route.page]);
|
||||
const tenants=useResource(async signal=>{
|
||||
const data=record(await request('/api/v1/tenants',{signal}));
|
||||
return {items:page(data).items.map(tenant),canManage:data.can_manage_customers===true};
|
||||
},[auth.principal.id]);
|
||||
const customers=tenants.data?.items ?? auth.tenants;
|
||||
const [customer,setCustomer]=useState(auth.tenants[0]?.tenant_id ?? '');
|
||||
const [fleetFilter,setFleetFilter]=useState('');
|
||||
const [selection,setSelection]=useState<{customer:string;ids:string[]}>({customer:'',ids:[]});
|
||||
const [error,setError]=useState<string|null>(null);
|
||||
const [planId,setPlan]=useState<string|null>(null), [operationId,setOperation]=useState<string|null>(null);
|
||||
function switchCustomer(id:string) {
|
||||
if(id===customer)return;
|
||||
setSelection({customer:'',ids:[]});setPlan(null);setOperation(null);setCustomer(id);
|
||||
}
|
||||
function selectFleetCustomer(id:string) {
|
||||
setFleetFilter(id);setSelection({customer:'',ids:[]});
|
||||
if(id) switchCustomer(id);
|
||||
}
|
||||
const primaryTenant=auth.tenants[0]?.tenant_id;
|
||||
const current = useResource(async signal=>{
|
||||
if(!customer || customer===primaryTenant)return {id:customer,auth};
|
||||
const scoped=session(await request('/auth/session',{signal,tenantId:customer}));
|
||||
return {id:customer,auth:scoped};
|
||||
},[customer,auth]);
|
||||
// Gate rendering during a tenant change; a previously loaded session is scoped to its own customer.
|
||||
const scoped=current.data?.id===customer ? current.data.auth : null;
|
||||
const customerName=customers.find(c=>c.tenant_id===customer)?.name ?? '';
|
||||
const openOperation=(id:string)=>{setPlan(null);setOperation(id);go('auftraege');};
|
||||
const showPlan=(id:string)=>{setOperation(null);setPlan(id);go('auftraege');};
|
||||
const selected=selection.customer===customer?selection.ids:[];
|
||||
const tabs: [string,string][]= [['zugang','MCP-Tokens'],['aufnahme','Agent-Releases & Aufnahme'],['kataloge','Paketkataloge'],['rechte','Rechte & Ausführungsstopp']];
|
||||
const adminTab=tabs.some(([id])=>id===route.tab)?route.tab:'zugang';
|
||||
return <div className="workbench">
|
||||
<aside className="sidebar">
|
||||
<a className="brand" href="#geraete" aria-label="Rust Discovery – Geräte"><span className="brand-mark" aria-hidden="true"><i/><i/><i/></span>Rust Discovery</a>
|
||||
<nav aria-label="Hauptnavigation">{(Object.entries(pages) as [NavKey,string][]).map(([key,title])=><a key={key} href={'#'+key} aria-current={route.page===key?'page':undefined}><NavIcon name={key}/><span>{title}</span></a>)}</nav>
|
||||
<div className="account"><div><span className="account-dot" aria-hidden="true"/><span title={auth.principal.id}>{auth.principal.display_name}</span></div><button onClick={async()=>{
|
||||
try {await request('/auth/logout',{csrf:auth.csrf_token,body:{}});window.history.replaceState(null,'',window.location.pathname+window.location.search);logout();}
|
||||
catch(e){setError(errorText(e));}
|
||||
}}><NavIcon name="abmelden"/> Abmelden</button></div>
|
||||
</aside>
|
||||
<div className="work-area"><header className="topline"><div className="crumb"><span>Arbeitsbereich</span><i aria-hidden="true">/</i><b>{pages[route.page]}</b></div>
|
||||
{route.page!=='geraete' && route.page!=='kunden' && <label className="context"><span>Kunde</span><select value={customer} onChange={e=>switchCustomer(e.target.value)}>{customers.map(c=><option value={c.tenant_id} key={c.tenant_id}>{c.name}</option>)}</select></label>}
|
||||
</header>
|
||||
{auth.principal.simulated && <aside className="simulation" role="status">SIMULIERT · dev/test-Testprincipal · Genehmigung ist eine Entwicklungs-Browsersimulation, kein menschlicher Produktions-Freigabenachweis.</aside>}
|
||||
<main className="content"><ErrorBox error={error}/><ErrorBox error={tenants.error}/><ErrorBox error={current.error}/>
|
||||
{route.page==='geraete' && <Devices auth={scoped ?? auth} customers={customers} filter={fleetFilter} onFilter={selectFleetCustomer}
|
||||
selection={selection} onSelection={value=>{if(value.customer)switchCustomer(value.customer);setSelection(value);}}
|
||||
onEnroll={()=>go('verwaltung','aufnahme')} onScripts={()=>go('skripte')}
|
||||
onOperation={(tenantId,id)=>{switchCustomer(tenantId);openOperation(id);}}/>}
|
||||
{route.page==='kunden' && <><div className="page-title"><h1>Kunden</h1></div><CustomerManagement auth={auth} customers={customers} canManage={tenants.data?.canManage===true} onChange={tenants.reload} onSelect={id=>{selectFleetCustomer(id);go('geraete');}}/></>}
|
||||
{!['geraete','kunden'].includes(route.page) && (!customer || !scoped) && !current.error && <p>Kundenbereich wird geladen …</p>}
|
||||
{scoped && <React.Fragment key={customer}>
|
||||
{route.page==='skripte' && <><div className="page-title"><h1>Skripte</h1><a className="soft-button" href="#geraete">Geräte auswählen</a></div>
|
||||
{selected.length>0 && <p className="target-note">{selected.length} {selected.length===1?'Zielgerät':'Zielgeräte'} für {customerName} ausgewählt</p>}
|
||||
<ScriptLibrary tenantId={customer} auth={scoped} selected={selected} showPlan={showPlan}/></>}
|
||||
{route.page==='auftraege' && <><div className="page-title"><h1>Aufträge</h1>{route.tab!=='neu' && <a className="soft-button" href="#auftraege/neu"><NavIcon name="plus"/> Auftrag planen</a>}</div>
|
||||
{route.tab==='neu' ? <><a className="quiet" href="#geraete">Geräte auswählen</a><p className="target-note">{selected.length} {selected.length===1?'Zielgerät':'Zielgeräte'} für {customerName} ausgewählt</p><Planner tenantId={customer} auth={scoped} selected={selected} showPlan={showPlan}/></> : <>
|
||||
{operationId && <OperationDetail key={operationId} tenantId={customer} id={operationId} auth={scoped} openPlan={id=>setPlan(id)}/>}
|
||||
{planId && <PlanDetail key={planId} tenantId={customer} id={planId} auth={scoped} onOperation={setOperation}/>}
|
||||
<Operations tenantId={customer} open={openOperation}/></>}</>}
|
||||
{route.page==='verwaltung' && <><div className="page-title"><h1>Verwaltung</h1></div><nav className="subnav" aria-label="Verwaltungsbereiche">{tabs.map(([id,title])=><a href={'#verwaltung/'+id} key={id} aria-current={adminTab===id?'page':undefined}>{title}</a>)}</nav>
|
||||
{adminTab==='zugang' && <McpTokenManagement tenantId={customer} auth={scoped}/>}
|
||||
{adminTab==='aufnahme' && <AgentReleaseCatalog tenantId={customer} auth={scoped} customerName={customerName} enrollmentOpen/>}
|
||||
{adminTab==='kataloge' && <><Catalog tenantId={customer} auth={scoped}/><WindowsMsiCatalog tenantId={customer} auth={scoped}/></>}
|
||||
{adminTab==='rechte' && <TenantControls tenantId={customer} auth={scoped}/>}</>}
|
||||
</React.Fragment>}
|
||||
</main></div>
|
||||
</div>;
|
||||
}
|
||||
function App() {
|
||||
const [auth, setAuth] = useState<Session | null>(null), [loading, setLoading] = useState(true), [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from 'react';
|
||||
import { ApiError, record, request, tenantPath, type Session } from './api';
|
||||
import { ApiError, record, request, tenant, tenantPath, type Tenant, type Session } from './api';
|
||||
|
||||
const scopeLabels = {
|
||||
'inventory:read': 'Inventar lesen',
|
||||
@@ -27,8 +27,10 @@ export interface McpToken {
|
||||
expires_at: string;
|
||||
last_used_at: string | null;
|
||||
revoked_at: string | null;
|
||||
audience?: 'selected' | 'all';
|
||||
tenant_ids?: string[];
|
||||
}
|
||||
interface Listing { tokens: McpToken[]; allowed_scopes: Scope[]; default_scopes: Scope[] }
|
||||
interface Listing { tokens: McpToken[]; allowed_scopes: Scope[]; default_scopes: Scope[]; available_customers?: Tenant[]; can_select_all: boolean }
|
||||
|
||||
function requireContract(condition: unknown): asserts condition {
|
||||
if (!condition) throw new Error('Ungültige Antwort der Tokenverwaltung');
|
||||
@@ -46,7 +48,13 @@ export function mcpToken(value: unknown): McpToken {
|
||||
const r = record(value);
|
||||
requireContract(typeof r.token_id === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(r.token_id)
|
||||
&& typeof r.name === 'string' && r.name.length > 0 && typeof r.principal === 'string' && r.principal.length > 0);
|
||||
return { token_id: r.token_id, name: r.name, principal: r.principal, scopes: scopes(r.scopes),
|
||||
const audience = r.audience;
|
||||
if (audience !== undefined) {
|
||||
requireContract(audience === 'selected' || audience === 'all');
|
||||
requireContract(Array.isArray(r.tenant_ids) && r.tenant_ids.every(id => typeof id === 'string'));
|
||||
requireContract(audience === 'all' ? r.tenant_ids.length === 0 : r.tenant_ids.length > 0);
|
||||
}
|
||||
return { ...(audience === undefined ? {} : { audience, tenant_ids: r.tenant_ids as string[] }), token_id: r.token_id, name: r.name, principal: r.principal, scopes: scopes(r.scopes),
|
||||
created_at: timestamp(r.created_at), expires_at: timestamp(r.expires_at),
|
||||
last_used_at: r.last_used_at === null ? null : timestamp(r.last_used_at),
|
||||
revoked_at: r.revoked_at === null ? null : timestamp(r.revoked_at) };
|
||||
@@ -58,7 +66,9 @@ export function mcpTokenListing(value: unknown): Listing {
|
||||
requireContract(defaults.every(s => readScopes.has(s) && allowed.includes(s)));
|
||||
const tokens = r.tokens.map(mcpToken);
|
||||
requireContract(new Set(tokens.map(t => t.token_id)).size === tokens.length);
|
||||
return { tokens, allowed_scopes: allowed, default_scopes: defaults };
|
||||
if (r.available_customers !== undefined) requireContract(Array.isArray(r.available_customers));
|
||||
return { tokens, allowed_scopes: allowed, default_scopes: defaults,
|
||||
available_customers: r.available_customers?.map(tenant), can_select_all: r.can_select_all === true };
|
||||
}
|
||||
export function canManageMcpTokens(auth: Session, tenantId: string): boolean {
|
||||
return auth.principal.simulated === false && !!auth.csrf_token && auth.permissions?.includes('tokens:manage') === true
|
||||
@@ -95,6 +105,8 @@ function TokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }
|
||||
const [listing, setListing] = useState<Listing | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [selected, setSelected] = useState<Scope[]>([]);
|
||||
const [allCustomers, setAllCustomers] = useState(false);
|
||||
const [customerIds, setCustomerIds] = useState([tenantId]);
|
||||
const [expires, setExpires] = useState(defaultExpiry);
|
||||
const [secret, setSecret] = useState<{ token: string; tokenId: string; name: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -126,7 +138,12 @@ function TokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }
|
||||
event.preventDefault();
|
||||
if (busy || secret || !listing) return;
|
||||
let body;
|
||||
try { body = mcpTokenDraft(name, selected, listing.allowed_scopes, expires); }
|
||||
try { body = mcpTokenDraft(name, selected, listing.allowed_scopes, expires);
|
||||
if (listing.available_customers) {
|
||||
if (allCustomers && !listing.can_select_all) throw new Error('Keine Berechtigung für alle Kunden.');
|
||||
if (!allCustomers && (!customerIds.length || customerIds.some(id => !listing.available_customers!.some(c => c.tenant_id === id)))) throw new Error('Bitte mindestens einen verfügbaren Kunden auswählen.');
|
||||
body = { ...body, audience: allCustomers ? 'all' : 'selected', tenant_ids: allCustomers ? [] : customerIds };
|
||||
} }
|
||||
catch (err) { setError(err instanceof Error ? err.message : 'Tokenangaben prüfen.'); return; }
|
||||
setBusy(true); setError(''); setNotice('');
|
||||
const controller = new AbortController(); mutation.current = controller;
|
||||
@@ -137,7 +154,7 @@ function TokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }
|
||||
requireContract(typeof reply.token === 'string' && reply.token.length >= 32 && reply.token.length <= 512);
|
||||
setSecret({ token: reply.token, tokenId: metadata.token_id, name: metadata.name });
|
||||
setListing(current => current && { ...current, tokens: [metadata, ...current.tokens] });
|
||||
setName(''); setSelected(listing.default_scopes); setExpires(defaultExpiry());
|
||||
setName(''); setAllCustomers(false); setCustomerIds([tenantId]); setSelected(listing.default_scopes); setExpires(defaultExpiry());
|
||||
} catch (err) {
|
||||
if (mounted.current) {
|
||||
setError(requestFailure(err, 'Die Erstellung konnte nicht bestätigt werden. Prüfen Sie vor einem neuen Versuch die aktualisierte Tokenliste.'));
|
||||
@@ -187,6 +204,11 @@ function TokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }
|
||||
<fieldset disabled={busy || secret !== null || listing.allowed_scopes.length === 0}>
|
||||
<legend>Neues MCP-Token</legend>
|
||||
<label>Name<input value={name} onChange={e => setName(e.target.value)} maxLength={240} required autoComplete="off" placeholder="Zum Beispiel mein MCP-Client"/></label>
|
||||
{listing.available_customers && <fieldset><legend>Kundenzugriff</legend>
|
||||
{listing.can_select_all && <label><input type="checkbox" checked={allCustomers} onChange={e => setAllCustomers(e.target.checked)}/>Alle aktuellen und zukünftigen Kunden</label>}
|
||||
{!allCustomers && listing.available_customers.map(customer => <label key={customer.tenant_id}><input type="checkbox" checked={customerIds.includes(customer.tenant_id)}
|
||||
onChange={e => setCustomerIds(previous => e.target.checked ? [...previous, customer.tenant_id] : previous.filter(id => id !== customer.tenant_id))}/>{customer.name}</label>)}
|
||||
</fieldset>}
|
||||
<fieldset><legend>Rechte</legend>
|
||||
{listing.allowed_scopes.map(scope => <label key={scope}>
|
||||
<input type="checkbox" checked={selected.includes(scope)} onChange={e => setSelected(current => e.target.checked ? [...current, scope] : current.filter(s => s !== scope))}/>
|
||||
@@ -195,16 +217,17 @@ function TokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }
|
||||
</fieldset>
|
||||
<label>Ablaufdatum und Uhrzeit<input type="datetime-local" required value={expires} onChange={e => setExpires(e.target.value)}/></label>
|
||||
<small>Ortszeit dieses Browsers. Höchstens 365 Tage Gültigkeit.</small>
|
||||
<button disabled={!selected.length} type="submit">Token erstellen</button>
|
||||
<button disabled={!selected.length || (!allCustomers && !customerIds.length)} type="submit">Token erstellen</button>
|
||||
</fieldset>
|
||||
{listing.allowed_scopes.length === 0 && <p>Ihre Mitgliedschaft bietet keine Rechte für ein MCP-Token.</p>}
|
||||
</form>
|
||||
<h3>Ausgestellte Tokens</h3>
|
||||
<button type="button" disabled={busy} onClick={() => { setError(''); setReload(value => value + 1); }}>Tokenliste aktualisieren</button>
|
||||
{!listing.tokens.length ? <p>Es wurden noch keine Tokens erstellt.</p> : <div className="table"><table>
|
||||
<thead><tr><th>Name und ID</th><th>Rechte</th><th>Erstellt und zuletzt verwendet</th><th>Gültigkeit</th><th>Verwaltung</th></tr></thead>
|
||||
<thead><tr><th>Name und ID</th><th>Kundenzugriff</th><th>Rechte</th><th>Erstellt und zuletzt verwendet</th><th>Gültigkeit</th><th>Verwaltung</th></tr></thead>
|
||||
<tbody>{listing.tokens.map(token => <tr key={token.token_id}>
|
||||
<td>{token.name}<small><code>{token.token_id}</code></small><small>{token.principal}</small></td>
|
||||
<td>{token.audience === 'all' ? 'Alle aktuellen und zukünftigen Kunden' : (token.tenant_ids ?? [tenantId]).map(id => listing.available_customers?.find(c => c.tenant_id === id)?.name ?? auth.tenants.find(c => c.tenant_id === id)?.name ?? id).join(', ')}</td>
|
||||
<td>{token.scopes.map(scope => <small key={scope}>{scopeLabels[scope]} <code>{scope}</code></small>)}</td>
|
||||
<td><DateLabel value={token.created_at}/><small>Zuletzt verwendet</small><DateLabel value={token.last_used_at}/></td>
|
||||
<td>{token.revoked_at ? <>Widerrufen am <DateLabel value={token.revoked_at}/></> : <>{Date.parse(token.expires_at) <= Date.now() ? 'Abgelaufen am ' : 'Läuft ab am '}<DateLabel value={token.expires_at}/></>}</td>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
export type NavKey = 'geraete' | 'auftraege' | 'skripte' | 'kunden' | 'verwaltung';
|
||||
const glyphs = {
|
||||
geraete: 'M3 4h18v12H3z M8 20h8 M12 16v4',
|
||||
auftraege: 'M8 5H5v16h14V5h-3 M9 3h6v4H9z M8 12h8 M8 16h5',
|
||||
skripte: 'M7 7l-5 5 5 5 M17 7l5 5-5 5 M14 4l-4 16',
|
||||
kunden: 'M4 21V5l10-2v18 M14 10h6v11 M2 21h20 M7 8h1 M10 8h1 M7 12h1 M10 12h1 M8 21v-4h3v4',
|
||||
verwaltung: 'M3 6h7 M14 6h7 M3 12h12 M19 12h2 M3 18h3 M10 18h11 M10 3v6 M16 9v6 M8 15v6',
|
||||
suchen: 'M16 16l5 5 M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0',
|
||||
plus: 'M12 5v14 M5 12h14',
|
||||
abmelden: 'M10 4H4v16h6 M8 12h13 M16 7l5 5-5 5',
|
||||
zurueck: 'M20 12H4 M10 6l-6 6 6 6',
|
||||
};
|
||||
export function NavIcon({ name }: { name: keyof typeof glyphs }) {
|
||||
return <svg className="nav-icon" aria-hidden="true" focusable="false" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.65" strokeLinecap="round" strokeLinejoin="round"><path d={glyphs[name]}/></svg>;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
|
||||
export const errorText = (error: unknown) => error instanceof Error ? error.message : 'Unbekannter Fehler';
|
||||
export function ErrorBox({ error }: { error: string | null }) { return error ? <div role="alert" className="error">{error}</div> : null; }
|
||||
export function useResource<T>(load: (signal: AbortSignal) => Promise<T>, deps: React.DependencyList, poll = false) {
|
||||
const [data, setData] = useState<T | null>(null), [error, setError] = useState<string | null>(null), [revision, setRevision] = useState(0);
|
||||
useEffect(() => {
|
||||
let active = true; const controller = new AbortController(); let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
setData(null); setError(null);
|
||||
const run = async () => { try { const result = await load(controller.signal); if (active) { setData(result); setError(null); } } catch (e) { if (active) setError(errorText(e)); }
|
||||
finally { if (active && poll) timer = setTimeout(run, 4000); } };
|
||||
void run(); return () => { active = false; controller.abort(); clearTimeout(timer); };
|
||||
}, [...deps, revision]);
|
||||
return { data, error, reload: () => setRevision(v => v + 1) };
|
||||
}
|
||||
+135
-1
@@ -1 +1,135 @@
|
||||
:root{font-family:system-ui,-apple-system,sans-serif;color:#dfe9f3;background:#101824;color-scheme:dark;font-size:15px;line-height:1.55}*{box-sizing:border-box}body{margin:0}header{display:flex;justify-content:space-between;align-items:center;padding:20px 4%;background:#172536;border-bottom:1px solid #36485d}h1{font-size:25px;margin:0}h1 span{font-size:17px;font-weight:400;color:#a6bad0}h2{font-size:21px;margin-top:0}h3{font-size:18px}main{max-width:1400px;margin:auto;padding:28px}section{border:1px solid #35485e;border-radius:10px;padding:24px;margin:24px 0;background:#172230}article{padding:18px;border:1px solid #506178;margin-top:18px}label{display:block;margin:12px 0;font-weight:600}input,select,textarea{display:block;width:100%;margin-top:5px;border:1px solid #586f87;background:#101a28;color:#f0f5fc;border-radius:5px;padding:10px;font:inherit}textarea,pre,code{font-family:ui-monospace,monospace}textarea{tab-size:2}button{background:#a5d7ff;color:#10243a;border:0;border-radius:5px;padding:10px 15px;font:inherit;font-weight:600;cursor:pointer;margin:4px 3px 4px 0}button:disabled{opacity:.45;cursor:not-allowed}.danger{background:#ffbb83}.link{background:none;color:#a5d7ff;padding:0;text-align:left;text-decoration:underline}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:3px solid #facc66;outline-offset:3px}.simulation{background:#52380a;color:#ffdd85;padding:16px 4%;font-weight:750;border-bottom:2px solid #ffc96e}.warning{padding:12px;border-left:4px solid #ffc96e;background:#332e22;color:#ffe1a0}.error{white-space:pre-wrap;overflow-wrap:anywhere;padding:14px;background:#452b31;border:1px solid #f08c9c;color:#ffd9df;margin:12px 0}.muted,small{color:#b4c3d3}small{display:block}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#101a28;padding:16px;max-height:650px;overflow:auto}summary{cursor:pointer;color:#bddfff}details{margin:14px 0}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:5px 22px}.table{overflow-x:auto}table{border-collapse:collapse;width:100%}td,th{text-align:left;vertical-align:top;padding:12px;border-bottom:1px solid #3c4e64}input[type=checkbox]{width:20px;height:20px;display:inline-block;vertical-align:middle;margin:0 10px 0 0}.check{padding:15px;border:1px solid #8a7956}.login{max-width:560px;margin:6vh auto}@media(max-width:600px){main{padding:12px}section{padding:14px}header{align-items:flex-start}h1 span{display:block}}
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--canvas: #f4f6f5; --surface: #fff; --ink: #1b2e2c; --subtle: #526563; --line: #d7e0dd;
|
||||
--accent: #17634f; --nav: #152d2a; --blue: #235e73;
|
||||
font: 15px/1.55 system-ui, -apple-system, sans-serif; color: var(--ink); background: var(--canvas);
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; }
|
||||
h1, h2, h3, h4 { line-height: 1.25; margin: 0 0 .7em; text-wrap: pretty; }
|
||||
h1 { font-size: clamp(1.9rem, 3.4vw, 2.65rem); font-weight: 680; letter-spacing: -.047em; }
|
||||
h2 { font-size: 1.26rem; letter-spacing: -.025em; } h3 { font-size: 1.06rem; }
|
||||
a, summary { color: var(--accent); }
|
||||
p, li, td, dd, code { overflow-wrap: anywhere; }
|
||||
main { padding: 28px; }
|
||||
section, article, .login {
|
||||
background: var(--surface); border: 1px solid var(--line); border-radius: 12px;
|
||||
padding: clamp(17px, 2.3vw, 27px); margin: 16px 0; min-width: 0;
|
||||
}
|
||||
article { background: #fbfcfb; }
|
||||
label { display: block; margin: 12px 0; font-size: .92rem; font-weight: 600; }
|
||||
input, select, textarea { display:block; width:100%; margin-top:5px; background:#fff; color:var(--ink); border:1px solid #adbfba; border-radius:6px; padding:9px 11px; font:inherit; font-weight:400; }
|
||||
input[type=checkbox] { width:17px; height:17px; margin:0 7px 0 0; display:inline-block; vertical-align:middle; accent-color:var(--accent); }
|
||||
button,.soft-button { background:var(--accent); color:white; border:1px solid transparent; border-radius:6px; font:inherit; font-weight:600; font-size:.91rem; padding:9px 14px; cursor:pointer; margin:3px 4px 3px 0; }
|
||||
button:hover,.soft-button:hover { filter:brightness(.94); }
|
||||
button:disabled { opacity:.48; cursor:not-allowed; filter:none; }
|
||||
button.primary,.soft-button,.quiet { display:inline-flex; align-items:center; gap:7px; text-decoration:none; }
|
||||
.quiet,.soft-button { background:white; color:var(--ink); border:1px solid var(--line); }
|
||||
a.quiet { border-radius:6px; padding:7px 12px; }
|
||||
.danger { color:#7b3029; background:#fdf1ee; border-color:#e6c4bc; }
|
||||
.link { color:var(--blue); background:transparent; text-decoration:underline; padding:0; text-align:left; }
|
||||
:focus-visible { outline:3px solid #318aad; outline-offset:3px; }
|
||||
details { margin:12px 0; } summary { cursor:pointer; font-weight:600; }
|
||||
pre,code,textarea { font-family:ui-monospace,monospace; } pre { padding:16px; background:#f0f4f2; border:1px solid var(--line); border-radius:6px; max-height:650px; overflow:auto; white-space:pre-wrap; overflow-wrap:anywhere; font-size:.88rem; } textarea { tab-size:2; }
|
||||
.muted,small { color:var(--subtle); } small { display:block; font-size:.82rem; }
|
||||
.warning,.check,.simulation,.error { padding:12px 15px; border-radius:5px; }
|
||||
.warning,.check,.simulation { color:#694913; background:#fff6dc; border-left:3px solid #c78c1b; }
|
||||
.simulation { margin:12px clamp(16px,3vw,48px) 0; }
|
||||
.error { background:#fff2ef; border:1px solid #e3b9b1; color:#842f27; white-space:pre-wrap; overflow-wrap:anywhere; margin:12px 0; }
|
||||
.grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,230px),1fr)); gap:5px 22px; }
|
||||
.table { overflow-x:auto; }
|
||||
table { border-collapse:collapse; width:100%; font-size:.93rem; }
|
||||
th,td { text-align:left; padding:12px; border-bottom:1px solid var(--line); vertical-align:middle; }
|
||||
thead th { background:#f7f9f8; color:var(--subtle); font-weight:620; font-size:.81rem; }
|
||||
.login { max-width:450px; margin:clamp(20px,10vh,100px) auto; border-top:4px solid var(--accent); padding:32px; }
|
||||
.login h1 { margin-bottom:1em; font-size:1.8rem; }
|
||||
.login form > button { width:100%; margin-top:12px; }
|
||||
.workbench { display:grid; grid-template-columns:195px minmax(0,1fr); min-height:100vh; }
|
||||
.sidebar { position:sticky; top:0; height:100vh; height:100dvh; background:var(--nav); color:#eef7f3; display:flex; flex-direction:column; padding:25px 12px 15px; }
|
||||
.brand { display:flex; align-items:center; gap:10px; padding:0 7px; color:white; text-decoration:none; font-weight:675; font-size:1.13rem; letter-spacing:-.035em; white-space:nowrap; }
|
||||
.brand-mark { width:28px; height:28px; position:relative; transform:rotate(-6deg); display:inline-block; }
|
||||
.brand-mark i { position:absolute; width:18px; height:13px; border:2px solid #85c7a9; background:var(--nav); border-radius:3px; transform:skewY(-17deg); left:4px; top:11px; }
|
||||
.brand-mark i:nth-child(2) { top:7px; } .brand-mark i:nth-child(3) { top:3px; background:#b5e9c7; border-color:#b5e9c7; }
|
||||
.sidebar nav { margin-top:36px; display:grid; gap:5px; }
|
||||
.sidebar nav a { position:relative; display:flex; align-items:center; gap:12px; padding:10px 13px; border-radius:7px; color:#c9d8d3; text-decoration:none; font-weight:500; }
|
||||
.sidebar nav a:hover { background:#203d37; color:white; }
|
||||
.sidebar nav a[aria-current=page] { background:#2c5045; color:#e4ffee; }
|
||||
.sidebar nav a[aria-current=page]::before { position:absolute; content:""; left:0; height:16px; width:3px; background:#a4deb7; border-radius:2px; }
|
||||
.nav-icon { width:19px; height:19px; flex:none; }
|
||||
.account { margin-top:auto; border-top:1px solid #39504b; padding:15px 8px 2px; min-width:0; }
|
||||
.account > div { display:flex; align-items:center; gap:7px; min-width:0; }
|
||||
.account span:last-child { text-overflow:ellipsis; overflow:hidden; white-space:nowrap; font-size:.88rem; }
|
||||
.account-dot { width:7px; height:7px; background:#91cfa3; border-radius:50%; flex:none; }
|
||||
.account button { background:none; padding:5px 0; font-size:.83rem; font-weight:450; display:flex; align-items:center; gap:6px; color:#c5d8d0; }
|
||||
.account button svg { width:14px; height:14px; }
|
||||
.work-area { min-width:0; }
|
||||
.topline { display:flex; min-height:64px; gap:16px; align-items:center; justify-content:space-between; border-bottom:1px solid var(--line); padding:8px clamp(16px,3vw,48px); background:#fafcfb; }
|
||||
.crumb { display:flex; gap:10px; align-items:center; color:var(--subtle); font-size:.85rem; }
|
||||
.crumb i { color:#889b94; font-style:normal; } .crumb b { font-weight:600; color:var(--ink); }
|
||||
.context { display:flex; align-items:center; gap:8px; margin:0; font-size:.84rem; color:var(--subtle); }
|
||||
.context select { width:auto; max-width:35vw; margin:0; padding:5px 8px; font-size:.86rem; }
|
||||
.content { max-width:1800px; margin:0 auto; padding:clamp(20px,3.6vw,52px) clamp(16px,3vw,48px) 50px; }
|
||||
.page-title { display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px; margin-bottom:24px; }
|
||||
.page-title h1 { margin:0; }
|
||||
.page-title > div:has(.presence) { display:flex; align-items:center; gap:15px; flex-wrap:wrap; }
|
||||
section.fleet { padding:0; overflow:hidden; }
|
||||
.fleet-tabs,.subnav { display:flex; gap:19px; flex-wrap:wrap; border-bottom:1px solid var(--line); }
|
||||
.fleet-tabs { padding:0 21px; }
|
||||
.fleet-tabs button,.subnav a { background:none; border:0; border-radius:0; font-size:.93rem; font-weight:550; margin:0; padding:14px 1px 11px; border-bottom:3px solid transparent; color:var(--subtle); text-decoration:none; }
|
||||
.fleet-tabs [aria-pressed=true],.subnav a[aria-current=page] { border-color:var(--accent); color:var(--accent); }
|
||||
.filters { padding:17px 20px; display:flex; align-items:end; gap:12px; }
|
||||
.filters label { margin:0; }
|
||||
.filters label > span:not(.sr-only) { font-size:.78rem; color:var(--subtle); }
|
||||
.filters input,.filters select { font-size:.9rem; padding:8px 10px; height:37px; }
|
||||
.filters select { min-width:130px; max-width:210px; }
|
||||
.search-box { position:relative; flex:1; min-width:100px; }
|
||||
.search-box .nav-icon { position:absolute; bottom:10px; left:11px; width:16px; height:16px; color:var(--subtle); }
|
||||
.search-box input { padding-left:34px; }
|
||||
.fleet-table table { table-layout:fixed; }
|
||||
.fleet-table td,.fleet-table th { padding:14px 9px; font-size:.88rem; }
|
||||
.fleet-table th { font-size:.79rem; vertical-align:bottom; }
|
||||
.fleet-table th:first-child,.fleet-table td:first-child { padding-left:18px; }
|
||||
.fleet-table th:last-child,.fleet-table td:last-child { padding-right:18px; }
|
||||
.fleet-table tbody tr { cursor:pointer; } .fleet-table tbody tr:hover,.fleet-table tr:focus-within { background:#f2f7f4; }
|
||||
.fleet-table .target-col { width:35px; }
|
||||
.fleet-table input[type=checkbox] { margin:0; }
|
||||
.host-link { padding:0; background:none; color:var(--accent); text-align:left; font-weight:680; margin:0; overflow-wrap:anywhere; }
|
||||
.fleet-table .storage { font-variant-numeric:tabular-nums; }
|
||||
.capacity-track { display:block; width:min(90px,100%); border-radius:2px; background:#e1ebe6; height:4px; margin-top:6px; overflow:hidden; }
|
||||
.capacity-track i { display:block; height:100%; background:#659d84; }
|
||||
.presence { display:inline-flex; align-items:center; gap:5px; border-radius:20px; padding:2px 8px; background:#edf1ef; color:#4d5f59; font-size:.8rem; font-weight:650; }
|
||||
.presence i { width:6px; height:6px; border-radius:50%; background:currentColor; }
|
||||
.presence.online { color:#236343; background:#e6f4e9; }
|
||||
.presence.historic { color:#80581c; background:#faf1df; }
|
||||
.fleet small { font-size:.75rem; margin-top:3px; }
|
||||
.list-message,.history-hint,.empty-list,.fleet > .error { margin:14px 20px; }
|
||||
.history-hint,.list-footer { color:var(--subtle); font-size:.83rem; }
|
||||
.empty-list { text-align:center; padding:28px 12px; } .empty-list svg { color:var(--subtle); } .empty-list h3 { margin:9px 0; }
|
||||
.list-footer { padding:11px 19px; display:flex; align-items:center; justify-content:space-between; gap:12px; }
|
||||
.selection { display:flex; align-items:center; gap:12px; flex-wrap:wrap; padding:14px 18px; background:#ecf5ee; border:1px solid #b8d6c1; border-radius:8px; }
|
||||
.selection > div { flex:1; }
|
||||
.facts { display:grid; grid-template-columns:repeat(auto-fit,minmax(175px,1fr)); gap:18px 24px; margin-bottom:0; }
|
||||
.facts dt { color:var(--subtle); font-size:.82rem; } .facts dd { margin:2px 0; font-weight:600; }
|
||||
.job-list { list-style:none; padding:0; } .job-list li { display:flex; align-items:center; gap:10px; flex-wrap:wrap; padding:8px 0; border-top:1px solid var(--line); }
|
||||
.device-detail > .quiet { margin-bottom:18px; }
|
||||
.sr-only { position:absolute; width:1px; height:1px; margin:-1px; padding:0; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }
|
||||
@media(max-width:1100px) and (min-width:761px) { .workbench {grid-template-columns:165px minmax(0,1fr);} .content {padding-left:18px;padding-right:18px;} .brand {font-size:1rem;} .fleet-table th,.fleet-table td {padding-inline:6px;} }
|
||||
@media(max-width:760px) {
|
||||
.workbench { display:block; }
|
||||
.sidebar { position:static; height:auto; padding:13px 15px 0; display:grid; grid-template-columns:1fr auto; grid-template-areas:'brand account' 'nav nav'; align-items:center; gap:12px; }
|
||||
.brand {grid-area:brand;padding:0;} .account {grid-area:account;border:0;margin:0;padding:0;} .account > div {display:none;} .account button {margin:0;}
|
||||
.sidebar nav {grid-area:nav; display:flex; gap:1px; margin:0; padding-bottom:4px; overflow-x:auto;}
|
||||
.sidebar nav a {display:flex; flex:1; justify-content:center; gap:5px; padding:7px 5px; font-size:.82rem;}
|
||||
.sidebar nav .nav-icon {width:14px;height:14px;} .sidebar nav a[aria-current=page]::before {display:none;}
|
||||
.topline {min-height:42px;} .content {padding-top:22px;} .page-title {margin-bottom:14px;}
|
||||
.filters {flex-wrap:wrap;gap:8px;padding:12px 14px;align-items:stretch;} .filters label {flex:1 1 110px;} .filters .search-box {flex:1 0 100%;} .filters select {min-width:0;max-width:100%;} .fleet-tabs {padding:0 14px;}
|
||||
.fleet-table thead {position:absolute;clip:rect(0,0,0,0);width:1px;height:1px;overflow:hidden;}
|
||||
.fleet-table table,.fleet-table tbody {display:block;} .fleet-table tr {display:grid;position:relative;grid-template-columns:1fr 1fr;gap:8px 14px;padding:15px 16px;border-top:1px solid var(--line);}
|
||||
.fleet-table td,.fleet-table td:first-child,.fleet-table td:last-child {display:block;padding:0;border:0;font-size:.9rem;}
|
||||
.fleet-table td[data-label]::before {content:attr(data-label);display:block;color:var(--subtle);font-size:.73rem;}
|
||||
.fleet-table .hostname {grid-column:1/-1;padding-right:28px;} .host-link {font-size:1rem;}
|
||||
.fleet-table .target-col {position:absolute;right:14px;top:14px;width:auto;} .capacity-track {width:76px;}
|
||||
.list-footer {border-top:1px solid var(--line);flex-wrap:wrap;} .facts {grid-template-columns:1fr 1fr;gap:12px;}
|
||||
}
|
||||
@media(max-width:450px) { .sidebar nav a {flex-direction:column;gap:2px;} .crumb span,.crumb i {display:none;} .login {margin:18px 12px;} .facts {grid-template-columns:1fr;} }
|
||||
@media(prefers-reduced-motion:no-preference) { a, button {transition:background-color 100ms,color 100ms;} }
|
||||
|
||||
Reference in New Issue
Block a user