Add local password-TOTP sessions and scoped revocable MCP tokens
This commit is contained in:
@@ -55,6 +55,7 @@ pub struct Auth {
|
||||
operator_b: Option<String>,
|
||||
pub origin: String,
|
||||
pub oidc: Option<crate::oidc::Provider>,
|
||||
pub local: Option<crate::local_auth::LocalAuth>,
|
||||
development: bool,
|
||||
}
|
||||
impl Auth {
|
||||
@@ -79,7 +80,10 @@ impl Auth {
|
||||
Ok(())
|
||||
}
|
||||
pub fn operator_enabled(&self, name: &str, tenant: Uuid) -> bool {
|
||||
(self.oidc.is_some() && name.starts_with("oidc:") && name.len() == 69)
|
||||
self.local
|
||||
.as_ref()
|
||||
.is_some_and(|local| local.enabled(name, tenant))
|
||||
|| (self.oidc.is_some() && name.starts_with("oidc:") && name.len() == 69)
|
||||
|| (name == "simulated-testprincipal-a"
|
||||
&& tenant.to_string() == TENANT_A
|
||||
&& self.username.is_some())
|
||||
@@ -125,10 +129,11 @@ impl Auth {
|
||||
url.scheme() == "https" && url.origin().ascii_serialization() == origin,
|
||||
"UI origin must be an exact HTTPS origin"
|
||||
);
|
||||
let local = crate::local_auth::LocalAuth::configured()?;
|
||||
let oidc = crate::oidc::configured(profile, &origin).await?;
|
||||
anyhow::ensure!(
|
||||
development || oidc.is_some(),
|
||||
"production OIDC not_configured"
|
||||
development || local.is_some() || oidc.is_some(),
|
||||
"production authentication not_configured"
|
||||
);
|
||||
Ok(Self {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
@@ -139,6 +144,7 @@ impl Auth {
|
||||
operator_b: secret("RMM_OPERATOR_B")?,
|
||||
origin,
|
||||
oidc,
|
||||
local,
|
||||
development,
|
||||
})
|
||||
}
|
||||
@@ -195,7 +201,9 @@ impl Auth {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some((tenant, operator)) = local {
|
||||
if raw.starts_with("rmm_mcp_") {
|
||||
crate::mcp_tokens::authenticate(state, raw, selected).await?
|
||||
} else if let Some((tenant, operator)) = local {
|
||||
let tenant =
|
||||
Uuid::parse_str(tenant).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Principal {
|
||||
@@ -253,6 +261,14 @@ impl Auth {
|
||||
}
|
||||
p
|
||||
};
|
||||
if p.name.starts_with("local:")
|
||||
&& !self
|
||||
.local
|
||||
.as_ref()
|
||||
.is_some_and(|local| local.enabled(&p.name, p.tenant))
|
||||
{
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
if selected.is_some_and(|t| t != p.tenant) {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
@@ -260,9 +276,10 @@ impl Auth {
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let active: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM memberships WHERE principal=$1 AND revoked_at IS NULL)",
|
||||
"SELECT EXISTS(SELECT 1 FROM memberships WHERE principal=$1 AND revoked_at IS NULL AND ($2=false OR kind='human'))",
|
||||
)
|
||||
.bind(&p.name)
|
||||
.bind(p.name.starts_with("local:"))
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
@@ -446,9 +463,29 @@ pub async fn login(
|
||||
.insert("content-type", HeaderValue::from_static("application/json"));
|
||||
Ok(response)
|
||||
}
|
||||
pub async fn local_login(
|
||||
State(state): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
input: Result<Json<crate::local_auth::Login>, axum::extract::rejection::JsonRejection>,
|
||||
) -> Result<Response, StatusCode> {
|
||||
state.auth.origin(&h)?;
|
||||
state.auth.rate_limit()?;
|
||||
let local = state.auth.local.as_ref().ok_or(StatusCode::NOT_FOUND)?;
|
||||
let Json(input) = input.map_err(|_| StatusCode::UNAUTHORIZED)?;
|
||||
let principal = local.authenticate(&state.pool, input).await?;
|
||||
let mut response = state.auth.establish(principal)?;
|
||||
*response.status_mut() = StatusCode::OK;
|
||||
response.headers_mut().remove("location");
|
||||
*response.body_mut() =
|
||||
axum::body::Body::from("{\"authenticated\":true,\"testsimulation\":false}");
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", HeaderValue::from_static("application/json"));
|
||||
Ok(response)
|
||||
}
|
||||
pub async fn configuration(State(state): State<crate::State>) -> Json<serde_json::Value> {
|
||||
Json(
|
||||
json!({"oidc_configured":state.auth.oidc.is_some(),"oidc_login_url":state.auth.oidc.as_ref().map(|_|"/auth/oidc/login"),"dev_login_enabled":state.auth.username.is_some()}),
|
||||
json!({"local_login_enabled":state.auth.local.is_some(),"oidc_configured":state.auth.oidc.is_some(),"oidc_login_url":state.auth.oidc.as_ref().map(|_|"/auth/oidc/login"),"dev_login_enabled":state.auth.username.is_some()}),
|
||||
)
|
||||
}
|
||||
pub async fn oidc_login(State(state): State<crate::State>) -> Result<Response, StatusCode> {
|
||||
|
||||
@@ -571,8 +571,8 @@ pub async fn permit(
|
||||
|| row
|
||||
.get::<Option<chrono::DateTime<Utc>>, _>("device_revoked")
|
||||
.is_some()
|
||||
|| !crate::jobs::requester_enabled(state, &plan.principal, tenant)
|
||||
|| !crate::jobs::requester_enabled(state, &row.get::<String, _>("approver"), tenant)
|
||||
|| !crate::jobs::requester_enabled(state, &mut tx, &plan.principal, tenant).await?
|
||||
|| !crate::jobs::requester_enabled(state, &mut tx, &row.get::<String, _>("approver"), tenant).await?
|
||||
{
|
||||
return Ok(denied("AUTHORIZATION_REVOKED"));
|
||||
}
|
||||
|
||||
@@ -1015,7 +1015,7 @@ async fn authorize_http(
|
||||
recheck(&mut tx, &plan).await?;
|
||||
// Both requester and approver retain explicit operator rights: the only
|
||||
// shipped dev principals are fixed-scope and cannot grant memberships.
|
||||
if !requester_enabled(&state, &plan.principal, tenant) {
|
||||
if !requester_enabled(&state, &mut tx, &plan.principal, tenant).await? {
|
||||
return Err(fail("AUTHORIZATION_REVOKED"));
|
||||
}
|
||||
for job in &plan.jobs {
|
||||
@@ -1058,8 +1058,17 @@ async fn authorize_http(
|
||||
tx.commit().await?;
|
||||
Ok(Json(operation(&state, &p, tenant, op).await?))
|
||||
}
|
||||
pub fn requester_enabled(state: &crate::State, name: &str, tenant: Uuid) -> bool {
|
||||
state.auth.operator_enabled(name, tenant)
|
||||
pub async fn requester_enabled(
|
||||
state: &crate::State,
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
name: &str,
|
||||
tenant: Uuid,
|
||||
) -> std::result::Result<bool, sqlx::Error> {
|
||||
if name.starts_with("mcp:") {
|
||||
crate::mcp_tokens::enabled_in(tx, name).await
|
||||
} else {
|
||||
Ok(state.auth.operator_enabled(name, tenant))
|
||||
}
|
||||
}
|
||||
pub async fn operation(
|
||||
state: &crate::State,
|
||||
|
||||
@@ -0,0 +1,538 @@
|
||||
//! Password and TOTP authentication for explicitly provisioned local human users.
|
||||
use anyhow::{Result, ensure};
|
||||
use axum::http::StatusCode;
|
||||
use openssl::{hash::MessageDigest, pkey::PKey, sign::Signer};
|
||||
use rmm_domain::jobs::hash;
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
fs::OpenOptions,
|
||||
io::Read,
|
||||
os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt},
|
||||
path::Path,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::sync::Semaphore;
|
||||
use uuid::Uuid;
|
||||
|
||||
const SCRYPT_N: u64 = 1 << 17;
|
||||
const SCRYPT_MAX_MEMORY: u64 = 256 * 1024 * 1024;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FileConfig {
|
||||
schema_version: u32,
|
||||
users: Vec<FileUser>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FileUser {
|
||||
username: String,
|
||||
principal: String,
|
||||
tenant_id: Uuid,
|
||||
disabled: bool,
|
||||
password_scrypt: PasswordHash,
|
||||
totp_secret_base32: String,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct PasswordHash {
|
||||
salt_hex: String,
|
||||
hash_hex: String,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct Account {
|
||||
username: String,
|
||||
principal: String,
|
||||
tenant: Uuid,
|
||||
disabled: bool,
|
||||
salt: Vec<u8>,
|
||||
password_hash: Vec<u8>,
|
||||
secret: Vec<u8>,
|
||||
}
|
||||
pub struct LocalAuth {
|
||||
users: Vec<Account>,
|
||||
attempts: Mutex<Vec<Vec<Instant>>>,
|
||||
workers: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Login {
|
||||
username: String,
|
||||
password: String,
|
||||
totp_code: String,
|
||||
}
|
||||
|
||||
fn username_valid(value: &str) -> bool {
|
||||
!value.is_empty()
|
||||
&& value.len() <= 64
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"_.@-".contains(&b))
|
||||
}
|
||||
fn decode_secret(value: &str) -> Result<Vec<u8>> {
|
||||
ensure!(
|
||||
value.len() == 32,
|
||||
"TOTP requires exactly 160 bits in unpadded uppercase base32"
|
||||
);
|
||||
let mut bytes = Vec::with_capacity(20);
|
||||
let mut buffer = 0u16;
|
||||
let mut bits = 0;
|
||||
for b in value.bytes() {
|
||||
let digit = match b {
|
||||
b'A'..=b'Z' => b - b'A',
|
||||
b'2'..=b'7' => b - b'2' + 26,
|
||||
_ => anyhow::bail!("Invalid TOTP base32"),
|
||||
};
|
||||
buffer = (buffer << 5) | u16::from(digit);
|
||||
bits += 5;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
bytes.push((buffer >> bits) as u8);
|
||||
buffer &= (1 << bits) - 1;
|
||||
}
|
||||
}
|
||||
ensure!(bytes.len() == 20 && bits == 0, "Invalid TOTP secret length");
|
||||
Ok(bytes)
|
||||
}
|
||||
fn derive_password(password: &[u8], salt: &[u8]) -> Result<[u8; 64]> {
|
||||
let mut derived = [0; 64];
|
||||
openssl::pkcs5::scrypt(
|
||||
password,
|
||||
salt,
|
||||
SCRYPT_N,
|
||||
8,
|
||||
1,
|
||||
SCRYPT_MAX_MEMORY,
|
||||
&mut derived,
|
||||
)?;
|
||||
Ok(derived)
|
||||
}
|
||||
fn code(secret: &[u8], step: u64) -> Result<u32> {
|
||||
let key = PKey::hmac(secret)?;
|
||||
let mut signer = Signer::new(MessageDigest::sha1(), &key)?;
|
||||
signer.update(&step.to_be_bytes())?;
|
||||
let mac = signer.sign_to_vec()?;
|
||||
let offset = usize::from(mac[19] & 15);
|
||||
let value = u32::from_be_bytes(mac[offset..offset + 4].try_into()?) & 0x7fff_ffff;
|
||||
Ok(value % 1_000_000)
|
||||
}
|
||||
fn matching_step(secret: &[u8], supplied: &str, now: i64) -> Result<Option<i64>> {
|
||||
if supplied.len() != 6 || !supplied.bytes().all(|b| b.is_ascii_digit()) || now < 30 {
|
||||
return Ok(None);
|
||||
}
|
||||
let current = now / 30;
|
||||
let mut matched = None;
|
||||
for step in current - 1..=current + 1 {
|
||||
let expected = format!("{:06}", code(secret, step as u64)?);
|
||||
if openssl::memcmp::eq(expected.as_bytes(), supplied.as_bytes()) {
|
||||
// If adjacent timesteps happen to collide, consume the highest one.
|
||||
matched = Some(step);
|
||||
}
|
||||
}
|
||||
Ok(matched)
|
||||
}
|
||||
impl LocalAuth {
|
||||
pub fn configured() -> Result<Option<Self>> {
|
||||
let Some(path) = std::env::var_os("RMM_LOCAL_AUTH_FILE") else {
|
||||
return Ok(None);
|
||||
};
|
||||
let path = Path::new(&path);
|
||||
ensure!(path.is_absolute(), "Local auth path must be absolute");
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(libc::O_NOFOLLOW)
|
||||
.open(path)
|
||||
.map_err(|_| anyhow::anyhow!("Local authentication file unavailable"))?;
|
||||
let metadata = file.metadata()?;
|
||||
ensure!(
|
||||
metadata.is_file()
|
||||
&& metadata.uid() == 10001
|
||||
&& metadata.permissions().mode() & 0o777 == 0o600
|
||||
&& metadata.nlink() == 1
|
||||
&& metadata.len() <= 65536,
|
||||
"Unsafe local authentication file"
|
||||
);
|
||||
let mut content = Vec::new();
|
||||
file.by_ref().take(65537).read_to_end(&mut content)?;
|
||||
ensure!(
|
||||
content.len() <= 65536,
|
||||
"Oversized local authentication file"
|
||||
);
|
||||
Self::parse(&content).map(Some)
|
||||
}
|
||||
fn parse(content: &[u8]) -> Result<Self> {
|
||||
let config: FileConfig = serde_json::from_slice(content)
|
||||
.map_err(|_| anyhow::anyhow!("Invalid local authentication configuration"))?;
|
||||
ensure!(
|
||||
config.schema_version == 1 && !config.users.is_empty() && config.users.len() <= 100,
|
||||
"Invalid local authentication schema or user limit"
|
||||
);
|
||||
let mut usernames = BTreeSet::new();
|
||||
let mut principals = BTreeSet::new();
|
||||
let mut users = Vec::new();
|
||||
for user in config.users {
|
||||
let id = user
|
||||
.principal
|
||||
.strip_prefix("local:")
|
||||
.and_then(|s| Uuid::parse_str(s).ok())
|
||||
.filter(|id| !id.is_nil() && user.principal == format!("local:{id}"));
|
||||
ensure!(
|
||||
id.is_some()
|
||||
&& !user.tenant_id.is_nil()
|
||||
&& username_valid(&user.username)
|
||||
&& usernames.insert(user.username.clone())
|
||||
&& principals.insert(user.principal.clone()),
|
||||
"Invalid or duplicate local identity"
|
||||
);
|
||||
let salt = hex::decode(&user.password_scrypt.salt_hex)?;
|
||||
let password_hash = hex::decode(&user.password_scrypt.hash_hex)?;
|
||||
ensure!(
|
||||
salt.len() == 32 && password_hash.len() == 64,
|
||||
"Invalid scrypt credential"
|
||||
);
|
||||
users.push(Account {
|
||||
username: user.username,
|
||||
principal: user.principal,
|
||||
tenant: user.tenant_id,
|
||||
disabled: user.disabled,
|
||||
salt,
|
||||
password_hash,
|
||||
secret: decode_secret(&user.totp_secret_base32)?,
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
attempts: Mutex::new(vec![vec![]; users.len() + 1]),
|
||||
users,
|
||||
workers: Arc::new(Semaphore::new(1)),
|
||||
})
|
||||
}
|
||||
pub fn enabled(&self, principal: &str, tenant: Uuid) -> bool {
|
||||
self.users
|
||||
.iter()
|
||||
.any(|u| !u.disabled && u.principal == principal && u.tenant == tenant)
|
||||
}
|
||||
fn limit(&self, index: usize) -> Result<(), StatusCode> {
|
||||
let mut buckets = self
|
||||
.attempts
|
||||
.lock()
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let attempts = &mut buckets[index];
|
||||
attempts.retain(|t| t.elapsed() < Duration::from_secs(60));
|
||||
if attempts.len() >= 6 {
|
||||
return Err(StatusCode::TOO_MANY_REQUESTS);
|
||||
}
|
||||
attempts.push(Instant::now());
|
||||
Ok(())
|
||||
}
|
||||
pub async fn authenticate(
|
||||
&self,
|
||||
pool: &PgPool,
|
||||
input: Login,
|
||||
) -> Result<crate::auth::Principal, StatusCode> {
|
||||
if !username_valid(&input.username)
|
||||
|| input.password.is_empty()
|
||||
|| input.password.len() > 1024
|
||||
|| input.totp_code.len() != 6
|
||||
|| !input.totp_code.bytes().all(|b| b.is_ascii_digit())
|
||||
{
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
let index = self.users.iter().position(|u| u.username == input.username);
|
||||
self.limit(index.unwrap_or(self.users.len()))?;
|
||||
let permit = self
|
||||
.workers
|
||||
.clone()
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| StatusCode::TOO_MANY_REQUESTS)?;
|
||||
// Unknown usernames perform the same expensive derivation against a fixed dummy record.
|
||||
let account = index.map(|i| self.users[i].clone());
|
||||
let checking = account.clone().unwrap_or(Account {
|
||||
username: String::new(),
|
||||
principal: String::new(),
|
||||
tenant: Uuid::nil(),
|
||||
disabled: true,
|
||||
salt: vec![0; 32],
|
||||
password_hash: vec![0; 64],
|
||||
secret: vec![0; 20],
|
||||
});
|
||||
let matched = tokio::task::spawn_blocking(move || -> Result<Option<i64>> {
|
||||
let _permit = permit; // Held until computation ends, including a disconnected HTTP caller.
|
||||
let password = derive_password(input.password.as_bytes(), &checking.salt)?;
|
||||
let matches = openssl::memcmp::eq(&password, &checking.password_hash);
|
||||
let step = matching_step(
|
||||
&checking.secret,
|
||||
&input.totp_code,
|
||||
chrono::Utc::now().timestamp(),
|
||||
)?;
|
||||
Ok(step.filter(|_| matches && !checking.disabled))
|
||||
})
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let account = account.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let step = matched.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
consume(pool, &account, step).await?;
|
||||
Ok(crate::auth::Principal {
|
||||
tenant: account.tenant,
|
||||
name: account.principal,
|
||||
operator: true,
|
||||
session_hash: None,
|
||||
csrf: None,
|
||||
scopes: None,
|
||||
testsimulation: false,
|
||||
identity: None,
|
||||
tenants: vec![account.tenant],
|
||||
})
|
||||
}
|
||||
}
|
||||
async fn consume(pool: &PgPool, account: &Account, step: i64) -> Result<(), StatusCode> {
|
||||
let mut tx = rmm_persistence::tenant_tx(pool, account.tenant)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let consumed: bool = sqlx::query_scalar("SELECT local_totp_consume($1,$2,$3)")
|
||||
.bind(&account.principal)
|
||||
.bind(hash(&account.secret))
|
||||
.bind(step)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
if !consumed {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::Utc;
|
||||
use serde_json::json;
|
||||
|
||||
fn sample(principal: &str, tenant: Uuid, password_hash: &str) -> serde_json::Value {
|
||||
json!({"schema_version":1,"users":[{
|
||||
"username":"kevin","principal":principal,"tenant_id":tenant,"disabled":false,
|
||||
"password_scrypt":{"salt_hex":hex::encode([7;32]),"hash_hex":password_hash},
|
||||
"totp_secret_base32":"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
|
||||
}]})
|
||||
}
|
||||
fn configured(data: &serde_json::Value) -> LocalAuth {
|
||||
LocalAuth::parse(&serde_json::to_vec(data).unwrap()).unwrap()
|
||||
}
|
||||
fn input(password: &str, secret: &[u8]) -> Login {
|
||||
Login {
|
||||
username: "kevin".into(),
|
||||
password: password.into(),
|
||||
totp_code: format!(
|
||||
"{:06}",
|
||||
code(secret, (Utc::now().timestamp() / 30) as u64).unwrap()
|
||||
),
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn rfc6238_and_strict_adjacent_steps() {
|
||||
let secret = decode_secret("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ").unwrap();
|
||||
assert_eq!(secret, b"12345678901234567890");
|
||||
for (now, expected) in [
|
||||
(59, 287082),
|
||||
(1111111109, 81804),
|
||||
(1111111111, 50471),
|
||||
(1234567890, 5924),
|
||||
(2000000000, 279037),
|
||||
(20000000000, 353130),
|
||||
] {
|
||||
let text = format!("{expected:06}");
|
||||
assert_eq!(code(&secret, (now / 30) as u64).unwrap(), expected);
|
||||
assert_eq!(matching_step(&secret, &text, now).unwrap(), Some(now / 30));
|
||||
}
|
||||
let now = 1_234_567_890;
|
||||
for offset in [-1, 0, 1] {
|
||||
let text = format!("{:06}", code(&secret, (now / 30 + offset) as u64).unwrap());
|
||||
assert_eq!(
|
||||
matching_step(&secret, &text, now).unwrap(),
|
||||
Some(now / 30 + offset)
|
||||
);
|
||||
}
|
||||
let old = format!("{:06}", code(&secret, (now / 30 - 2) as u64).unwrap());
|
||||
assert_eq!(matching_step(&secret, &old, now).unwrap(), None);
|
||||
for text in ["", "12345", "1234567", "12 456", "123456"] {
|
||||
assert_eq!(matching_step(&secret, text, now).unwrap(), None);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn rejects_ambiguous_configuration_and_bounds_rate_limit() {
|
||||
let p = format!("local:{}", Uuid::new_v4());
|
||||
let tenant = Uuid::new_v4();
|
||||
let good = sample(&p, tenant, &hex::encode([1; 64]));
|
||||
let local = configured(&good);
|
||||
assert!(local.enabled(&p, tenant));
|
||||
assert!(!local.enabled(&p, Uuid::new_v4()));
|
||||
for _ in 0..6 {
|
||||
assert!(local.limit(0).is_ok());
|
||||
}
|
||||
assert_eq!(local.limit(0), Err(StatusCode::TOO_MANY_REQUESTS));
|
||||
let mut disabled = good.clone();
|
||||
disabled["users"][0]["disabled"] = json!(true);
|
||||
assert!(!configured(&disabled).enabled(&p, tenant));
|
||||
for (key, value) in [
|
||||
("principal", json!("simulated-testprincipal-a")),
|
||||
("tenant_id", json!(Uuid::nil())),
|
||||
("totp_secret_base32", json!("short")),
|
||||
("username", json!("../kevin")),
|
||||
] {
|
||||
let mut bad = good.clone();
|
||||
bad["users"][0][key] = value;
|
||||
assert!(LocalAuth::parse(&serde_json::to_vec(&bad).unwrap()).is_err());
|
||||
}
|
||||
let mut duplicate = good.clone();
|
||||
duplicate["users"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(good["users"][0].clone());
|
||||
assert!(LocalAuth::parse(&serde_json::to_vec(&duplicate).unwrap()).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires isolated PostgreSQL with current migrations"]
|
||||
async fn local_password_totp_database() {
|
||||
let admin = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let pool = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
rmm_persistence::verify_application_role(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let tenant = Uuid::new_v4();
|
||||
let p = format!("local:{}", Uuid::new_v4());
|
||||
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'local auth test')")
|
||||
.bind(tenant)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES($1,$2,'human',ARRAY['inventory:read'])")
|
||||
.bind(tenant).bind(&p).execute(&admin).await.unwrap();
|
||||
let password = "isolated unit test password";
|
||||
let derived = derive_password(password.as_bytes(), &[7; 32]).unwrap();
|
||||
let data = sample(&p, tenant, &hex::encode(derived));
|
||||
let local = configured(&data);
|
||||
let secret = &local.users[0].secret;
|
||||
let held = local.workers.clone().acquire_owned().await.unwrap();
|
||||
assert_eq!(
|
||||
local
|
||||
.authenticate(&pool, input(password, secret))
|
||||
.await
|
||||
.err(),
|
||||
Some(StatusCode::TOO_MANY_REQUESTS)
|
||||
);
|
||||
drop(held);
|
||||
assert_eq!(
|
||||
local
|
||||
.authenticate(&pool, input("wrong password", secret))
|
||||
.await
|
||||
.err(),
|
||||
Some(StatusCode::UNAUTHORIZED)
|
||||
);
|
||||
let mut incorrect = input(password, secret);
|
||||
incorrect.totp_code = "x".repeat(6);
|
||||
assert_eq!(
|
||||
local.authenticate(&pool, incorrect).await.err(),
|
||||
Some(StatusCode::UNAUTHORIZED)
|
||||
);
|
||||
let mut wrong_code = input(password, secret);
|
||||
let current = Utc::now().timestamp();
|
||||
wrong_code.totp_code = (0..1_000_000)
|
||||
.map(|n| format!("{n:06}"))
|
||||
.find(|v| matching_step(secret, v, current).unwrap().is_none())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
local.authenticate(&pool, wrong_code).await.err(),
|
||||
Some(StatusCode::UNAUTHORIZED)
|
||||
);
|
||||
let valid_input = input(password, secret);
|
||||
let consumed_code = valid_input.totp_code.clone();
|
||||
let valid = local.authenticate(&pool, valid_input).await.unwrap();
|
||||
assert_eq!(valid.name, p);
|
||||
assert_eq!(valid.tenant, tenant);
|
||||
assert!(!valid.testsimulation);
|
||||
assert!(valid.session_hash.is_none());
|
||||
assert_eq!(
|
||||
local
|
||||
.authenticate(
|
||||
&pool,
|
||||
Login {
|
||||
username: "kevin".into(),
|
||||
password: password.into(),
|
||||
totp_code: consumed_code.clone()
|
||||
}
|
||||
)
|
||||
.await
|
||||
.err(),
|
||||
Some(StatusCode::UNAUTHORIZED)
|
||||
);
|
||||
// Replay remains rejected by the database after constructing a fresh auth provider.
|
||||
let restarted = configured(&data);
|
||||
assert_eq!(
|
||||
restarted
|
||||
.authenticate(
|
||||
&pool,
|
||||
Login {
|
||||
username: "kevin".into(),
|
||||
password: password.into(),
|
||||
totp_code: consumed_code
|
||||
}
|
||||
)
|
||||
.await
|
||||
.err(),
|
||||
Some(StatusCode::UNAUTHORIZED)
|
||||
);
|
||||
let mut disabled = data.clone();
|
||||
disabled["users"][0]["disabled"] = json!(true);
|
||||
assert_eq!(
|
||||
configured(&disabled)
|
||||
.authenticate(&pool, input(password, secret))
|
||||
.await
|
||||
.err(),
|
||||
Some(StatusCode::UNAUTHORIZED)
|
||||
);
|
||||
|
||||
let step = Utc::now().timestamp() / 30 + 1;
|
||||
let a = consume(&pool, &local.users[0], step);
|
||||
let b = consume(&pool, &local.users[0], step);
|
||||
let (one, two) = tokio::join!(a, b);
|
||||
assert_eq!(usize::from(one.is_ok()) + usize::from(two.is_ok()), 1);
|
||||
assert_eq!(one.err().or(two.err()), Some(StatusCode::UNAUTHORIZED));
|
||||
let foreign = Account {
|
||||
tenant: Uuid::new_v4(),
|
||||
..local.users[0].clone()
|
||||
};
|
||||
assert_eq!(
|
||||
consume(&pool, &foreign, step + 1).await,
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
);
|
||||
sqlx::query("UPDATE memberships SET revoked_at=now() WHERE tenant_id=$1 AND principal=$2")
|
||||
.bind(tenant)
|
||||
.bind(&p)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
consume(&pool, &local.users[0], step + 1).await,
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
);
|
||||
sqlx::query("UPDATE memberships SET revoked_at=NULL,kind='automation' WHERE tenant_id=$1 AND principal=$2")
|
||||
.bind(tenant).bind(&p).execute(&admin).await.unwrap();
|
||||
assert_eq!(
|
||||
consume(&pool, &local.users[0], step + 1).await,
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
);
|
||||
pool.close().await;
|
||||
admin.close().await;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ mod agent_updates;
|
||||
mod api;
|
||||
mod artifact_store;
|
||||
mod auth;
|
||||
mod local_auth;
|
||||
mod mcp_tokens;
|
||||
mod catalog;
|
||||
mod checkpoint_repair;
|
||||
mod controls;
|
||||
@@ -209,6 +211,8 @@ async fn main() -> Result<()> {
|
||||
.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));
|
||||
routes = mcp_tokens::routes(routes);
|
||||
routes = routes.route("/auth/local/login", post(auth::local_login));
|
||||
routes = jobs::routes(routes);
|
||||
routes = script_library::routes(routes);
|
||||
routes = controls::routes(routes);
|
||||
|
||||
@@ -0,0 +1,572 @@
|
||||
//! Tenant-bound, independently revocable automation credentials.
|
||||
use crate::{auth::Principal, jobs::Error};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use rmm_domain::jobs::hash;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{PgPool, Postgres, Row, Transaction, postgres::PgRow};
|
||||
use std::collections::BTreeSet;
|
||||
use uuid::Uuid;
|
||||
|
||||
const PREFIX: &str = "rmm_mcp_";
|
||||
const SCOPES: [&str; 11] = [
|
||||
"inventory:read",
|
||||
"logs:read",
|
||||
"operations:read",
|
||||
"operations:plan",
|
||||
"operations:submit",
|
||||
"jobs:cancel",
|
||||
"scripts:execute",
|
||||
"system:execute",
|
||||
"root:execute",
|
||||
"updates:apply",
|
||||
"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";
|
||||
|
||||
fn invalid() -> Error {
|
||||
Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR")
|
||||
}
|
||||
|
||||
fn denied() -> Error {
|
||||
Error(StatusCode::FORBIDDEN, "INTERACTIVE_TOKEN_ADMIN_REQUIRED")
|
||||
}
|
||||
|
||||
fn private_json(value: Value) -> Response {
|
||||
(
|
||||
[
|
||||
("cache-control", "private, no-store"),
|
||||
("pragma", "no-cache"),
|
||||
],
|
||||
Json(value),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub fn routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||
router
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/mcp-tokens",
|
||||
get(list).post(create),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/mcp-tokens/{token}/revoke",
|
||||
post(revoke),
|
||||
)
|
||||
}
|
||||
|
||||
fn metadata(row: &PgRow) -> Value {
|
||||
json!({
|
||||
"token_id":row.get::<Uuid,_>("token_id"),
|
||||
"principal":row.get::<String,_>("principal"),
|
||||
"name":row.get::<String,_>("name"),
|
||||
"scopes":row.get::<Vec<String>,_>("scopes"),
|
||||
"created_at":row.get::<DateTime<Utc>,_>("created_at"),
|
||||
"expires_at":row.get::<DateTime<Utc>,_>("expires_at"),
|
||||
"last_used_at":row.get::<Option<DateTime<Utc>>,_>("last_used_at"),
|
||||
"revoked_at":row.get::<Option<DateTime<Utc>>,_>("revoked_at"),
|
||||
})
|
||||
}
|
||||
|
||||
fn interactive(principal: &Principal) -> Result<(), Error> {
|
||||
if principal.session_hash.is_none()
|
||||
|| principal.csrf.is_none()
|
||||
|| principal.testsimulation
|
||||
|| principal.scopes.is_some()
|
||||
{
|
||||
return Err(denied());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn administration<'a>(
|
||||
state: &'a crate::State,
|
||||
headers: &HeaderMap,
|
||||
tenant: Uuid,
|
||||
write: bool,
|
||||
) -> Result<(Principal, Vec<String>, Transaction<'a, Postgres>), Error> {
|
||||
let principal = state
|
||||
.auth
|
||||
.principal(state, headers, write)
|
||||
.await
|
||||
.map_err(|status| Error(status, crate::auth::error_code(status)))?;
|
||||
crate::jobs::scope(&principal, tenant, write)?;
|
||||
interactive(&principal)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
||||
let permissions: Option<Vec<String>> = sqlx::query_scalar(
|
||||
"SELECT permissions FROM memberships WHERE principal=$1 AND kind='human' AND revoked_at IS NULL AND 'tokens:manage'=ANY(permissions)",
|
||||
).bind(&principal.name).fetch_optional(&mut *tx).await?;
|
||||
let allowed = permissions
|
||||
.ok_or_else(denied)?
|
||||
.into_iter()
|
||||
.filter(|permission| SCOPES.contains(&permission.as_str()))
|
||||
.collect();
|
||||
Ok((principal, allowed, tx))
|
||||
}
|
||||
|
||||
async fn list(
|
||||
State(state): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path(tenant): Path<Uuid>,
|
||||
) -> Result<Response, Error> {
|
||||
let (_, 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?;
|
||||
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}),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Create {
|
||||
name: String,
|
||||
scopes: Option<Vec<String>>,
|
||||
expires_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
fn selection(
|
||||
input: &Create,
|
||||
allowed: &[String],
|
||||
now: DateTime<Utc>,
|
||||
) -> Result<(Vec<String>, DateTime<Utc>), Error> {
|
||||
if input.name.is_empty()
|
||||
|| input.name.trim() != input.name
|
||||
|| input.name.chars().count() > 120
|
||||
|| input.name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
let selected: BTreeSet<_> = match &input.scopes {
|
||||
Some(scopes) => {
|
||||
if scopes.len() > SCOPES.len() {
|
||||
return Err(invalid());
|
||||
}
|
||||
scopes.iter().cloned().collect()
|
||||
}
|
||||
None => READ_SCOPES
|
||||
.into_iter()
|
||||
.filter(|scope| allowed.iter().any(|p| p == scope))
|
||||
.map(str::to_owned)
|
||||
.collect(),
|
||||
};
|
||||
if selected.is_empty()
|
||||
|| selected
|
||||
.iter()
|
||||
.any(|scope| !SCOPES.contains(&scope.as_str()) || !allowed.contains(scope))
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
let expires = input.expires_at.unwrap_or(now + Duration::days(90));
|
||||
if expires <= now || expires > now + Duration::days(365) {
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok((selected.into_iter().collect(), expires))
|
||||
}
|
||||
|
||||
fn generate() -> Result<String, Error> {
|
||||
let mut random = [0_u8; 32];
|
||||
openssl::rand::rand_bytes(&mut random)
|
||||
.map_err(|_| Error(StatusCode::SERVICE_UNAVAILABLE, "ENTROPY_UNAVAILABLE"))?;
|
||||
Ok(format!("{PREFIX}{}", URL_SAFE_NO_PAD.encode(random)))
|
||||
}
|
||||
|
||||
async fn create(
|
||||
State(state): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path(tenant): Path<Uuid>,
|
||||
Json(input): Json<Create>,
|
||||
) -> Result<Response, Error> {
|
||||
let (principal, allowed, mut tx) = administration(&state, &headers, tenant, true).await?;
|
||||
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)")
|
||||
.bind(&principal.name)
|
||||
.bind(id)
|
||||
.bind(&input.name)
|
||||
.bind(hash(token.as_bytes()))
|
||||
.bind(scopes)
|
||||
.bind(expiry)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let row = sqlx::query(&format!(
|
||||
"SELECT {COLUMNS} FROM mcp_tokens WHERE token_id=$1"
|
||||
))
|
||||
.bind(id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
let mut response = metadata(&row);
|
||||
response["token"] = Value::String(token);
|
||||
Ok(private_json(response))
|
||||
}
|
||||
|
||||
async fn revoke(
|
||||
State(state): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path((tenant, id)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<Response, Error> {
|
||||
let (principal, _, mut tx) = administration(&state, &headers, tenant, true).await?;
|
||||
let found: bool = sqlx::query_scalar("SELECT revoke_mcp_token($1,$2,$3)")
|
||||
.bind(&principal.name)
|
||||
.bind(id)
|
||||
.bind(Uuid::new_v4())
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if !found {
|
||||
return Err(Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
|
||||
}
|
||||
let row = sqlx::query(&format!(
|
||||
"SELECT {COLUMNS} FROM mcp_tokens WHERE token_id=$1"
|
||||
))
|
||||
.bind(id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(private_json(metadata(&row)))
|
||||
}
|
||||
|
||||
pub async fn authenticate(
|
||||
state: &crate::State,
|
||||
raw: &str,
|
||||
selected: Option<Uuid>,
|
||||
) -> Result<Principal, StatusCode> {
|
||||
authenticate_pool(&state.pool, raw, selected).await
|
||||
}
|
||||
|
||||
async fn authenticate_pool(
|
||||
pool: &PgPool,
|
||||
raw: &str,
|
||||
selected: Option<Uuid>,
|
||||
) -> Result<Principal, StatusCode> {
|
||||
let encoded = raw.strip_prefix(PREFIX).ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
if encoded.len() != 43 || URL_SAFE_NO_PAD.decode(encoded).is_err() {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
let digest = hash(raw.as_bytes());
|
||||
let route: Option<(Uuid, Uuid)> =
|
||||
sqlx::query_as("SELECT tenant_id,token_id FROM mcp_token_route($1)")
|
||||
.bind(&digest)
|
||||
.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) {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
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")
|
||||
.into_iter()
|
||||
.filter(|permission| allowed.contains(permission) && SCOPES.contains(&permission.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)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
Ok(Principal {
|
||||
tenant,
|
||||
name: row.get("principal"),
|
||||
operator: effective
|
||||
.iter()
|
||||
.any(|scope| !READ_SCOPES.contains(&scope.as_str())),
|
||||
session_hash: None,
|
||||
csrf: None,
|
||||
scopes: Some(effective),
|
||||
testsimulation: false,
|
||||
identity: None,
|
||||
tenants: vec![tenant],
|
||||
})
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
pub async fn enabled(pool: &PgPool, principal: &str, tenant: Uuid) -> bool {
|
||||
let Ok(mut tx) = rmm_persistence::tenant_tx(pool, tenant).await else {
|
||||
return false;
|
||||
};
|
||||
let allowed = enabled_in(&mut tx, principal).await.unwrap_or(false);
|
||||
tx.commit().await.is_ok() && allowed
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn mcp_token_selection_is_explicit_and_bounded() {
|
||||
let now = Utc::now();
|
||||
let allowed: Vec<String> = SCOPES.into_iter().map(str::to_owned).collect();
|
||||
let mut input = Create {
|
||||
name: "Inventory reader".into(),
|
||||
scopes: None,
|
||||
expires_at: None,
|
||||
};
|
||||
let (selected, expiry) = selection(&input, &allowed, now).unwrap();
|
||||
assert_eq!(selected, READ_SCOPES.map(str::to_owned));
|
||||
assert_eq!(expiry, now + Duration::days(90));
|
||||
for permission in [
|
||||
"plans:approve",
|
||||
"plans:revoke",
|
||||
"tokens:manage",
|
||||
"unknown",
|
||||
"",
|
||||
] {
|
||||
input.scopes = Some(vec![permission.into()]);
|
||||
assert!(selection(&input, &allowed, now).is_err());
|
||||
}
|
||||
input.scopes = Some(vec!["scripts:execute".into()]);
|
||||
assert!(selection(&input, &["inventory:read".into()], now).is_err());
|
||||
for expires in [now, now - Duration::seconds(1), now + Duration::days(366)] {
|
||||
input.expires_at = Some(expires);
|
||||
assert!(selection(&input, &allowed, now).is_err());
|
||||
}
|
||||
input.expires_at = None;
|
||||
for name in [
|
||||
"".into(),
|
||||
" x ".into(),
|
||||
"secret\nname".into(),
|
||||
"a".repeat(121),
|
||||
] {
|
||||
input.name = name;
|
||||
assert!(selection(&input, &allowed, now).is_err());
|
||||
}
|
||||
let first = generate().unwrap();
|
||||
let second = generate().unwrap();
|
||||
assert_ne!(first, second);
|
||||
assert_eq!(
|
||||
URL_SAFE_NO_PAD
|
||||
.decode(&first[PREFIX.len()..])
|
||||
.unwrap()
|
||||
.len(),
|
||||
32
|
||||
);
|
||||
}
|
||||
|
||||
async fn mint(
|
||||
pool: &PgPool,
|
||||
tenant: Uuid,
|
||||
actor: &str,
|
||||
permissions: &[&str],
|
||||
) -> (Uuid, String) {
|
||||
let id = Uuid::new_v4();
|
||||
let token = generate().unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(pool, tenant).await.unwrap();
|
||||
sqlx::query("SELECT issue_mcp_token($1,$2,'test token',$3,$4,now()+interval '1 day')")
|
||||
.bind(actor)
|
||||
.bind(id)
|
||||
.bind(hash(token.as_bytes()))
|
||||
.bind(permissions)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.unwrap();
|
||||
tx.commit().await.unwrap();
|
||||
(id, token)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires disposable PostgreSQL with all migrations applied"]
|
||||
async fn mcp_tokens_database() {
|
||||
let app = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let admin = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let tenant = Uuid::parse_str(rmm_domain::TENANT_A).unwrap();
|
||||
let other = Uuid::parse_str(rmm_domain::TENANT_B).unwrap();
|
||||
let actor = format!("local:{}", Uuid::new_v4());
|
||||
sqlx::query("INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES($1,$2,'human',ARRAY['inventory:read','logs:read','operations:read','operations:plan','operations:submit','scripts:execute','tokens:manage'])")
|
||||
.bind(tenant).bind(&actor).execute(&admin).await.unwrap();
|
||||
let (id, token) = mint(
|
||||
&app,
|
||||
tenant,
|
||||
&actor,
|
||||
&["inventory:read", "operations:plan", "scripts:execute"],
|
||||
)
|
||||
.await;
|
||||
let principal = authenticate_pool(&app, &token, None).await.unwrap();
|
||||
assert_eq!(principal.tenant, tenant);
|
||||
assert_eq!(principal.name, format!("mcp:{id}"));
|
||||
assert!(principal.operator && !principal.testsimulation);
|
||||
assert!(principal.session_hash.is_none() && principal.csrf.is_none());
|
||||
assert!(interactive(&principal).is_err());
|
||||
assert!(principal.permits_scope("scripts:execute"));
|
||||
for banned in ["plans:approve", "plans:revoke", "tokens:manage"] {
|
||||
assert!(!principal.permits_scope(banned));
|
||||
}
|
||||
assert_eq!(
|
||||
authenticate_pool(&app, &token, Some(other)).await.err(),
|
||||
Some(StatusCode::NOT_FOUND)
|
||||
);
|
||||
assert_eq!(
|
||||
authenticate_pool(&app, &generate().unwrap(), None)
|
||||
.await
|
||||
.err(),
|
||||
Some(StatusCode::UNAUTHORIZED)
|
||||
);
|
||||
assert!(enabled(&app, &principal.name, tenant).await);
|
||||
assert!(!enabled(&app, &principal.name, other).await);
|
||||
assert!(
|
||||
sqlx::query("SELECT * FROM mcp_token_routes")
|
||||
.fetch_all(&app)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let outside: i64 = sqlx::query_scalar("SELECT count(*) FROM mcp_tokens")
|
||||
.fetch_one(&app)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(outside, 0);
|
||||
let mut tx = rmm_persistence::tenant_tx(&app, other).await.unwrap();
|
||||
let foreign: i64 = sqlx::query_scalar("SELECT count(*) FROM mcp_tokens WHERE token_id=$1")
|
||||
.bind(id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(foreign, 0);
|
||||
tx.commit().await.unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
|
||||
let row = sqlx::query(&format!(
|
||||
"SELECT {COLUMNS} FROM mcp_tokens WHERE token_id=$1"
|
||||
))
|
||||
.bind(id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.unwrap();
|
||||
let public = metadata(&row);
|
||||
assert!(public["last_used_at"].is_string());
|
||||
assert!(!public.to_string().contains(&token) && public.get("token_hash").is_none());
|
||||
tx.commit().await.unwrap();
|
||||
|
||||
// A later membership edit cannot add permission beyond the original scopes.
|
||||
sqlx::query("UPDATE memberships SET permissions=ARRAY['inventory:read','plans:approve','tokens:manage'] WHERE tenant_id=$1 AND principal=$2")
|
||||
.bind(tenant).bind(&principal.name).execute(&admin).await.unwrap();
|
||||
let reduced = authenticate_pool(&app, &token, None).await.unwrap();
|
||||
assert!(
|
||||
!reduced.operator
|
||||
&& reduced.permits_scope("inventory:read")
|
||||
&& !reduced.permits_scope("plans:approve")
|
||||
);
|
||||
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
|
||||
for permission in ["plans:approve", "tokens:manage", "scripts:execute"] {
|
||||
let allowed: bool = sqlx::query_scalar("SELECT mcp_principal_permission($1,$2)")
|
||||
.bind(&principal.name)
|
||||
.bind(permission)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!allowed);
|
||||
}
|
||||
tx.commit().await.unwrap();
|
||||
sqlx::query("UPDATE memberships SET revoked_at=now() WHERE tenant_id=$1 AND principal=$2")
|
||||
.bind(tenant)
|
||||
.bind(&principal.name)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
authenticate_pool(&app, &token, None).await.err(),
|
||||
Some(StatusCode::UNAUTHORIZED)
|
||||
);
|
||||
assert!(!enabled(&app, &principal.name, tenant).await);
|
||||
|
||||
let (revoked_id, revoked) = mint(&app, tenant, &actor, &["inventory:read"]).await;
|
||||
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
|
||||
let found: bool = sqlx::query_scalar("SELECT revoke_mcp_token($1,$2,$3)")
|
||||
.bind(&actor)
|
||||
.bind(revoked_id)
|
||||
.bind(Uuid::new_v4())
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(found);
|
||||
tx.commit().await.unwrap();
|
||||
assert_eq!(
|
||||
authenticate_pool(&app, &revoked, None).await.err(),
|
||||
Some(StatusCode::UNAUTHORIZED)
|
||||
);
|
||||
assert!(!enabled(&app, &format!("mcp:{revoked_id}"), tenant).await);
|
||||
let (expired_id, expired) = mint(&app, tenant, &actor, &["inventory:read"]).await;
|
||||
sqlx::query("UPDATE mcp_tokens SET created_at=now()-interval '2 days',expires_at=now()-interval '1 day' WHERE tenant_id=$1 AND token_id=$2")
|
||||
.bind(tenant).bind(expired_id).execute(&admin).await.unwrap();
|
||||
assert_eq!(
|
||||
authenticate_pool(&app, &expired, None).await.err(),
|
||||
Some(StatusCode::UNAUTHORIZED)
|
||||
);
|
||||
assert!(!enabled(&app, &format!("mcp:{expired_id}"), tenant).await);
|
||||
|
||||
// The narrow definer rejects automation administrators and forbidden scopes.
|
||||
for (who, permissions) in [
|
||||
(&principal.name, vec!["inventory:read"]),
|
||||
(&actor, vec!["plans:approve"]),
|
||||
(&actor, vec!["root:execute"]),
|
||||
] {
|
||||
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
|
||||
let denied =
|
||||
sqlx::query("SELECT issue_mcp_token($1,$2,'denied',$3,$4,now()+interval '1 day')")
|
||||
.bind(who)
|
||||
.bind(Uuid::new_v4())
|
||||
.bind(hash(generate().unwrap().as_bytes()))
|
||||
.bind(permissions)
|
||||
.execute(&mut *tx)
|
||||
.await;
|
||||
assert!(denied.is_err());
|
||||
tx.rollback().await.unwrap();
|
||||
}
|
||||
let audit: Vec<Value> =
|
||||
sqlx::query_scalar("SELECT data FROM audit_events WHERE event_type LIKE 'mcp_token_%'")
|
||||
.fetch_all(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
audit
|
||||
.iter()
|
||||
.all(|row| row.get("token").is_none() && row.get("token_hash").is_none())
|
||||
);
|
||||
println!(
|
||||
"PASS MCP random credentials, RLS routing, live membership/scopes, expiry, revoke, admin restrictions and secret-free metadata"
|
||||
);
|
||||
app.close().await;
|
||||
admin.close().await;
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ pub async fn allowed(
|
||||
principal: &str,
|
||||
permission: &str,
|
||||
) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM memberships WHERE principal=$1 AND revoked_at IS NULL AND $2=ANY(permissions)) AND (left($1,5)<>'oidc:' OR oidc_principal_enabled($1))").bind(principal).bind(permission).fetch_one(&mut **tx).await
|
||||
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM memberships WHERE principal=$1 AND revoked_at IS NULL AND $2=ANY(permissions)) AND (left($1,5)<>'oidc:' OR oidc_principal_enabled($1)) AND (left($1,4)<>'mcp:' OR mcp_principal_permission($1,$2))").bind(principal).bind(permission).fetch_one(&mut **tx).await
|
||||
}
|
||||
pub async fn require_principal(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
-- A TOTP timestep may authenticate once per independently provisioned secret.
|
||||
CREATE TABLE local_totp_replay (
|
||||
tenant_id uuid NOT NULL,
|
||||
principal text NOT NULL,
|
||||
secret_sha256 text NOT NULL CHECK (secret_sha256 ~ '^[0-9a-f]{64}$'),
|
||||
last_step bigint NOT NULL CHECK (last_step >= 0),
|
||||
consumed_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (tenant_id, principal, secret_sha256),
|
||||
FOREIGN KEY (tenant_id, principal) REFERENCES memberships (tenant_id, principal)
|
||||
);
|
||||
ALTER TABLE local_totp_replay ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE local_totp_replay FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY tenant_scope ON local_totp_replay
|
||||
USING (tenant_id::text = current_setting('app.tenant_id', true))
|
||||
WITH CHECK (tenant_id::text = current_setting('app.tenant_id', true));
|
||||
REVOKE ALL ON local_totp_replay FROM PUBLIC;
|
||||
GRANT SELECT ON local_totp_replay TO rmm_app;
|
||||
|
||||
-- The application cannot modify memberships. The owner performs the row lock
|
||||
-- and atomic replay consumption in the caller's selected tenant transaction.
|
||||
CREATE FUNCTION local_totp_consume(selected_principal text, secret_hash text, selected_step bigint)
|
||||
RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
|
||||
DECLARE selected_tenant uuid;
|
||||
BEGIN
|
||||
selected_tenant := nullif(current_setting('app.tenant_id', true), '')::uuid;
|
||||
IF selected_tenant IS NULL THEN RETURN false; END IF;
|
||||
PERFORM 1 FROM memberships WHERE tenant_id=selected_tenant AND principal=selected_principal
|
||||
AND kind='human' AND revoked_at IS NULL FOR SHARE;
|
||||
IF NOT FOUND THEN RETURN false; END IF;
|
||||
INSERT INTO local_totp_replay(tenant_id,principal,secret_sha256,last_step)
|
||||
VALUES(selected_tenant,selected_principal,secret_hash,selected_step)
|
||||
ON CONFLICT(tenant_id,principal,secret_sha256) DO UPDATE
|
||||
SET last_step=excluded.last_step,consumed_at=now()
|
||||
WHERE local_totp_replay.last_step < excluded.last_step;
|
||||
RETURN FOUND;
|
||||
END;
|
||||
$$;
|
||||
REVOKE ALL ON FUNCTION local_totp_consume(text,text,bigint) FROM PUBLIC;
|
||||
GRANT EXECUTE ON FUNCTION local_totp_consume(text,text,bigint) TO rmm_app;
|
||||
|
||||
DO $$
|
||||
DECLARE current_tenant uuid;
|
||||
BEGIN
|
||||
FOR current_tenant IN SELECT tenant_id FROM tenants LOOP
|
||||
PERFORM set_config('app.tenant_id', current_tenant::text, true);
|
||||
UPDATE memberships SET permissions = array_append(permissions, 'tokens:manage')
|
||||
WHERE tenant_id = current_tenant AND kind = 'human' AND revoked_at IS NULL
|
||||
AND 'plans:approve' = ANY(permissions) AND NOT ('tokens:manage' = ANY(permissions));
|
||||
END LOOP;
|
||||
END;
|
||||
$$;
|
||||
@@ -0,0 +1,90 @@
|
||||
CREATE TABLE mcp_tokens (
|
||||
tenant_id uuid NOT NULL REFERENCES tenants,
|
||||
token_id uuid NOT NULL,
|
||||
principal text NOT NULL,
|
||||
name text NOT NULL CHECK(length(name) BETWEEN 1 AND 120 AND name !~ '[[:cntrl:]]'),
|
||||
token_hash text NOT NULL UNIQUE CHECK(token_hash ~ '^[0-9a-f]{64}$'),
|
||||
scopes text[] NOT NULL CHECK(cardinality(scopes) BETWEEN 1 AND 11 AND scopes <@ ARRAY[
|
||||
'inventory:read','logs:read','operations:read','operations:plan','operations:submit',
|
||||
'jobs:cancel','scripts:execute','system:execute','root:execute','updates:apply','catalog:write']::text[]),
|
||||
created_by text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL CHECK(expires_at > created_at AND expires_at <= created_at + interval '365 days'),
|
||||
last_used_at timestamptz,
|
||||
revoked_at timestamptz,
|
||||
PRIMARY KEY(tenant_id,token_id),
|
||||
UNIQUE(tenant_id,principal),
|
||||
CHECK(principal='mcp:'||token_id::text),
|
||||
FOREIGN KEY(tenant_id,principal) REFERENCES memberships(tenant_id,principal),
|
||||
FOREIGN KEY(tenant_id,created_by) REFERENCES memberships(tenant_id,principal)
|
||||
);
|
||||
ALTER TABLE mcp_tokens ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE mcp_tokens FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY tenant_scope ON mcp_tokens
|
||||
USING(tenant_id::text=current_setting('app.tenant_id',true))
|
||||
WITH CHECK(tenant_id::text=current_setting('app.tenant_id',true));
|
||||
GRANT SELECT,UPDATE(last_used_at) ON mcp_tokens TO rmm_app;
|
||||
|
||||
-- Only this exact-digest routing index can be read without a tenant context.
|
||||
-- It grants no membership or token authority. Every scoped lookup checks them live.
|
||||
CREATE TABLE mcp_token_routes (
|
||||
token_hash text PRIMARY KEY CHECK(token_hash ~ '^[0-9a-f]{64}$'),
|
||||
tenant_id uuid NOT NULL,
|
||||
token_id uuid NOT NULL,
|
||||
FOREIGN KEY(tenant_id,token_id) REFERENCES mcp_tokens(tenant_id,token_id)
|
||||
);
|
||||
REVOKE ALL ON mcp_token_routes FROM PUBLIC,rmm_app;
|
||||
CREATE FUNCTION mcp_token_route(digest text) RETURNS TABLE(tenant_id uuid,token_id uuid)
|
||||
LANGUAGE sql STABLE SECURITY DEFINER SET search_path=pg_catalog AS $$
|
||||
SELECT r.tenant_id,r.token_id FROM public.mcp_token_routes r WHERE r.token_hash=digest;
|
||||
$$;
|
||||
REVOKE ALL ON FUNCTION mcp_token_route(text) FROM PUBLIC;
|
||||
GRANT EXECUTE ON FUNCTION mcp_token_route(text) TO rmm_app;
|
||||
|
||||
CREATE FUNCTION issue_mcp_token(actor text,id uuid,label text,digest text,requested text[],expiry timestamptz)
|
||||
RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog AS $$
|
||||
DECLARE
|
||||
tenant uuid := current_setting('app.tenant_id')::uuid;
|
||||
member text := 'mcp:'||id::text;
|
||||
BEGIN
|
||||
IF id='00000000-0000-0000-0000-000000000000'::uuid OR NOT EXISTS(
|
||||
SELECT 1 FROM public.memberships m WHERE m.tenant_id=tenant AND m.principal=actor
|
||||
AND m.kind='human' AND m.revoked_at IS NULL AND 'tokens:manage'=ANY(m.permissions)
|
||||
AND requested <@ m.permissions
|
||||
) THEN RAISE EXCEPTION 'MCP_TOKEN_FORBIDDEN' USING ERRCODE='42501'; END IF;
|
||||
INSERT INTO public.memberships(tenant_id,principal,kind,permissions) VALUES(tenant,member,'automation',requested);
|
||||
INSERT INTO public.mcp_tokens(tenant_id,token_id,principal,name,token_hash,scopes,created_by,expires_at)
|
||||
VALUES(tenant,id,member,label,digest,requested,actor,expiry);
|
||||
INSERT INTO public.mcp_token_routes VALUES(digest,tenant,id);
|
||||
INSERT INTO public.audit_events(tenant_id,event_id,principal,event_type,data)
|
||||
VALUES(tenant,id,actor,'mcp_token_created',jsonb_build_object('token_id',id,'principal',member,'scopes',requested,'expires_at',expiry));
|
||||
END $$;
|
||||
CREATE FUNCTION revoke_mcp_token(actor text,id uuid,event uuid) RETURNS boolean
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog AS $$
|
||||
DECLARE
|
||||
tenant uuid := current_setting('app.tenant_id')::uuid;
|
||||
member text;
|
||||
BEGIN
|
||||
IF NOT EXISTS(SELECT 1 FROM public.memberships m WHERE m.tenant_id=tenant AND m.principal=actor
|
||||
AND m.kind='human' AND m.revoked_at IS NULL AND 'tokens:manage'=ANY(m.permissions))
|
||||
THEN RAISE EXCEPTION 'MCP_TOKEN_FORBIDDEN' USING ERRCODE='42501'; END IF;
|
||||
SELECT t.principal INTO member FROM public.mcp_tokens t WHERE t.tenant_id=tenant AND t.token_id=id FOR UPDATE;
|
||||
IF member IS NULL THEN RETURN false; END IF;
|
||||
UPDATE public.mcp_tokens SET revoked_at=coalesce(revoked_at,now()) WHERE tenant_id=tenant AND token_id=id;
|
||||
UPDATE public.memberships SET revoked_at=coalesce(revoked_at,now()) WHERE tenant_id=tenant AND principal=member;
|
||||
INSERT INTO public.audit_events(tenant_id,event_id,principal,event_type,data)
|
||||
VALUES(tenant,event,actor,'mcp_token_revoked',jsonb_build_object('token_id',id,'principal',member));
|
||||
RETURN true;
|
||||
END $$;
|
||||
REVOKE ALL ON FUNCTION issue_mcp_token(text,uuid,text,text,text[],timestamptz),revoke_mcp_token(text,uuid,uuid) FROM PUBLIC;
|
||||
GRANT EXECUTE ON FUNCTION issue_mcp_token(text,uuid,text,text,text[],timestamptz),revoke_mcp_token(text,uuid,uuid) TO rmm_app;
|
||||
|
||||
-- SECURITY INVOKER intentionally retains the caller's tenant RLS context.
|
||||
CREATE FUNCTION mcp_principal_permission(member text,permission text) RETURNS boolean
|
||||
LANGUAGE sql STABLE SET search_path=pg_catalog AS $$
|
||||
SELECT EXISTS(SELECT 1 FROM public.mcp_tokens t JOIN public.memberships m USING(tenant_id,principal)
|
||||
WHERE t.principal=member AND t.revoked_at IS NULL AND t.expires_at>now()
|
||||
AND m.kind='automation' AND m.revoked_at IS NULL AND permission=ANY(t.scopes) AND permission=ANY(m.permissions));
|
||||
$$;
|
||||
REVOKE ALL ON FUNCTION mcp_principal_permission(text,text) FROM PUBLIC;
|
||||
GRANT EXECUTE ON FUNCTION mcp_principal_permission(text,text) TO rmm_app;
|
||||
@@ -0,0 +1,112 @@
|
||||
import { test, expect } from '../../web/node_modules/@playwright/test/index.js';
|
||||
import { createServer, type ViteDevServer } from '../../web/node_modules/vite/dist/node/index.js';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
// The actual component runs in Chromium. All API data and secrets in this test are synthetic.
|
||||
let server: ViteDevServer;
|
||||
let origin: string;
|
||||
const tenant = '11111111-1111-4111-8111-111111111111';
|
||||
const metadata = { token_id: '22222222-2222-4222-8222-222222222222', name: 'MCP client', principal: 'test-human',
|
||||
scopes: ['inventory:read'], created_at: '2026-01-01T12:00:00Z', expires_at: '2030-01-01T12:00:00Z', last_used_at: null, revoked_at: null as string | null };
|
||||
const syntheticSecret = 'synthetic-test-token-not-a-real-credential-123456789';
|
||||
const endpoint = `/api/v1/tenants/${tenant}/mcp-tokens`;
|
||||
const auth = { principal: { id: 'test-human', display_name: 'Test', simulated: false }, tenants: [{ tenant_id: tenant, name: 'Test' }],
|
||||
csrf_token: 'synthetic-csrf', permissions: ['tokens:manage', 'inventory:read', 'operations:submit'] };
|
||||
|
||||
test.beforeAll(async () => {
|
||||
server = await createServer({ root: resolve(__dirname, '../../web'), configFile: false, server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
|
||||
await server.listen();
|
||||
const address = server.httpServer!.address();
|
||||
if (!address || typeof address === 'string') throw new Error('Missing local fixture address');
|
||||
origin = `http://127.0.0.1:${address.port}`;
|
||||
});
|
||||
test.afterAll(async () => { await server?.close(); });
|
||||
|
||||
async function mount(page: import('../../web/node_modules/@playwright/test/index.js').Page) {
|
||||
await page.route(`${origin}/fixture`, route => route.fulfill({ contentType: 'text/html', body: `<!doctype html><html lang="de"><body><div id="root"></div><script type="module">
|
||||
import React from '/node_modules/.vite/deps/react.js';
|
||||
import ReactDOM from '/node_modules/.vite/deps/react-dom_client.js';
|
||||
import { McpTokenManagement } from '/src/mcp-token-management.tsx';
|
||||
const root = ReactDOM.createRoot(document.getElementById('root'));
|
||||
window.renderTokenFixture = session => root.render(React.createElement(McpTokenManagement, { auth: session, tenantId: '${tenant}' }));
|
||||
window.renderTokenFixture(${JSON.stringify(auth)});
|
||||
</script></body></html>` }));
|
||||
await page.goto(`${origin}/fixture`);
|
||||
}
|
||||
|
||||
test('creates with selected rights, displays once, copies, revokes and keeps secrets out of browser storage', async ({ page, context }) => {
|
||||
let tokens: typeof metadata[] = [];
|
||||
const posted: unknown[] = [];
|
||||
await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin });
|
||||
await page.route(`${origin}${endpoint}**`, async route => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'GET') {
|
||||
await route.fulfill({ json: { tokens, allowed_scopes: ['inventory:read', 'operations:submit'], default_scopes: ['inventory:read'] } });
|
||||
} else {
|
||||
expect(req.headers()['x-csrf-token']).toBe(auth.csrf_token);
|
||||
if (req.url().endsWith('/revoke')) {
|
||||
expect(req.postDataJSON()).toEqual({});
|
||||
tokens = [{ ...metadata, revoked_at: new Date().toISOString() }];
|
||||
await route.fulfill({ json: tokens[0] });
|
||||
} else {
|
||||
posted.push(req.postDataJSON()); tokens = [metadata];
|
||||
await route.fulfill({ json: { ...metadata, token: syntheticSecret } });
|
||||
}
|
||||
}
|
||||
});
|
||||
await mount(page);
|
||||
await expect(page.getByRole('checkbox', { name: /Inventar lesen/ })).toBeChecked();
|
||||
await expect(page.getByRole('checkbox', { name: /Genehmigung einreichen/ })).not.toBeChecked();
|
||||
await page.getByLabel('Name', { exact: true }).fill('MCP client');
|
||||
await page.getByRole('button', { name: 'Token erstellen', exact: true }).click();
|
||||
await expect(page.getByLabel('Einmaliger Token')).toHaveValue(syntheticSecret);
|
||||
expect(posted).toHaveLength(1);
|
||||
expect(posted[0]).toMatchObject({ name: 'MCP client', scopes: ['inventory:read'] });
|
||||
await page.getByRole('button', { name: 'Token kopieren', exact: true }).click();
|
||||
await expect(page.getByRole('status')).toHaveText('Token kopiert.');
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(syntheticSecret);
|
||||
expect(await page.evaluate(() => [localStorage.length, sessionStorage.length])).toEqual([0, 0]);
|
||||
await page.getByRole('button', { name: 'Tokenanzeige schließen' }).click();
|
||||
await expect(page.getByLabel('Einmaliger Token')).toHaveCount(0);
|
||||
await page.getByRole('button', { name: 'Tokenliste aktualisieren' }).click();
|
||||
await expect(page.getByLabel('Einmaliger Token')).toHaveCount(0);
|
||||
await page.getByRole('button', { name: 'Widerrufen', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Widerruf bestätigen' }).click();
|
||||
await expect(page.getByRole('status')).toContainText('widerrufen');
|
||||
await expect(page.getByRole('button', { name: 'Widerrufen', exact: true })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('clears a displayed secret on session switch and refuses a simulated management session', async ({ page }) => {
|
||||
await page.route(`${origin}${endpoint}`, route => route.fulfill({ json: route.request().method() === 'GET'
|
||||
? { tokens: [], allowed_scopes: ['inventory:read'], default_scopes: ['inventory:read'] }
|
||||
: { ...metadata, token: syntheticSecret } }));
|
||||
await mount(page);
|
||||
await page.getByLabel('Name', { exact: true }).fill('MCP client');
|
||||
await page.getByRole('button', { name: 'Token erstellen', exact: true }).click();
|
||||
await expect(page.getByLabel('Einmaliger Token')).toHaveValue(syntheticSecret);
|
||||
await page.evaluate(next => (window as unknown as { renderTokenFixture: (session: unknown) => void }).renderTokenFixture(next),
|
||||
{ ...auth, csrf_token: 'new-session' });
|
||||
await expect(page.getByLabel('Einmaliger Token')).toHaveCount(0);
|
||||
await page.evaluate(next => (window as unknown as { renderTokenFixture: (session: unknown) => void }).renderTokenFixture(next),
|
||||
{ ...auth, principal: { ...auth.principal, simulated: true } });
|
||||
await expect(page.getByRole('heading', { name: 'MCP-Tokens', exact: true })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('discards a late create response after the owning session changes', async ({ page }) => {
|
||||
let created!: (route: import('../../web/node_modules/@playwright/test/index.js').Route) => void;
|
||||
const pending = new Promise<import('../../web/node_modules/@playwright/test/index.js').Route>(resolve => { created = resolve; });
|
||||
await page.route(`${origin}${endpoint}`, async route => {
|
||||
if (route.request().method() === 'POST') { created(route); return; }
|
||||
await route.fulfill({ json: { tokens: [], allowed_scopes: ['inventory:read'], default_scopes: ['inventory:read'] } });
|
||||
});
|
||||
await mount(page);
|
||||
await page.getByLabel('Name', { exact: true }).fill('MCP client');
|
||||
await page.getByRole('button', { name: 'Token erstellen', exact: true }).click();
|
||||
const creation = await pending;
|
||||
await page.evaluate(next => (window as unknown as { renderTokenFixture: (session: unknown) => void }).renderTokenFixture(next),
|
||||
{ ...auth, csrf_token: 'replacement-session' });
|
||||
await expect(page.getByLabel('Name', { exact: true })).toHaveValue('');
|
||||
await creation.fulfill({ json: { ...metadata, token: syntheticSecret } });
|
||||
await expect(page.getByLabel('Einmaliger Token')).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: 'Token erstellen', exact: true })).toBeEnabled();
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise local MFA and MCP credentials against disposable PostgreSQL with tenant RLS."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def command(args, data=None, timeout=120):
|
||||
result = subprocess.run(args, input=data, capture_output=True, timeout=timeout)
|
||||
if result.returncode:
|
||||
raise RuntimeError(result.stderr.decode(errors="replace")[-4000:])
|
||||
return result.stdout
|
||||
|
||||
|
||||
def main():
|
||||
name = "rmm-mcp-token-" + uuid.uuid4().hex[:10]
|
||||
command(["docker", "run", "-d", "--network", "none", "--name", name,
|
||||
"-e", "POSTGRES_HOST_AUTH_METHOD=trust", "postgres:17.6-bookworm"])
|
||||
try:
|
||||
for _ in range(100):
|
||||
ready = subprocess.run(["docker", "exec", name, "pg_isready", "-U", "postgres"],
|
||||
capture_output=True)
|
||||
if ready.returncode == 0 and b"init process complete" in command(["docker", "logs", name]):
|
||||
break
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
raise RuntimeError("ISOLATED_POSTGRES_NOT_READY")
|
||||
|
||||
def sql(role, statement):
|
||||
return command(["docker", "exec", "-i", name, "psql", "-XqAt", "-v",
|
||||
"ON_ERROR_STOP=1", "-U", role, "-d", "postgres"], statement.encode())
|
||||
|
||||
sql("postgres", """CREATE ROLE rmm_migrator LOGIN NOSUPERUSER NOBYPASSRLS;
|
||||
CREATE ROLE rmm_app LOGIN NOINHERIT NOSUPERUSER NOBYPASSRLS;
|
||||
ALTER DATABASE postgres OWNER TO rmm_migrator;
|
||||
ALTER SCHEMA public OWNER TO rmm_migrator;""")
|
||||
for path in sorted((ROOT / "migrations").glob("*.sql")):
|
||||
sql("rmm_migrator", path.read_text())
|
||||
test_command = [
|
||||
"docker", "run", "--rm", "--network", "container:" + name,
|
||||
"--read-only", "--tmpfs", "/tmp:rw,size=512m",
|
||||
"-v", str(ROOT) + ":/src:ro", "-w", "/src",
|
||||
"-v", str(ROOT / "devstate/windows-server-contract/target") + ":/target",
|
||||
"-e", "CARGO_TARGET_DIR=/target",
|
||||
"-e", "RMM_TEST_REPAIR_ADMIN_URL=postgres://postgres@127.0.0.1/postgres",
|
||||
"-e", "RMM_TEST_REPAIR_APP_URL=postgres://rmm_app@127.0.0.1/postgres",
|
||||
"--entrypoint", "cargo", "rust-discovery-windows-tls-full:local",
|
||||
"test", "--locked", "--offline", "-p", "rmm-server",
|
||||
]
|
||||
for test_filter in ("local_auth::tests", "mcp_tokens::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")
|
||||
finally:
|
||||
subprocess.run(["docker", "rm", "-f", name], capture_output=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+3
-2
@@ -13,14 +13,15 @@ export function stringField(value: RecordValue, key: string): string { return ty
|
||||
export interface Tenant { tenant_id: string; name: string }
|
||||
export interface Session { principal: { id: string; display_name: string; simulated: boolean }; tenants: Tenant[]; csrf_token: string; permissions?: string[]; roles?: string[] }
|
||||
export interface Page { items: RecordValue[]; next_cursor: string | null; completeness: string; truncated: boolean; as_of: string }
|
||||
export interface AuthConfig { oidc_configured: boolean; oidc_login_url: '/auth/oidc/login' | null; dev_login_enabled: boolean }
|
||||
export interface AuthConfig { oidc_configured: boolean; oidc_login_url: '/auth/oidc/login' | null; dev_login_enabled: boolean; local_login_enabled: boolean }
|
||||
export function authConfig(value: unknown): AuthConfig {
|
||||
const r = record(value, 'Auth-Konfiguration');
|
||||
if (typeof r.oidc_configured !== 'boolean' || typeof r.dev_login_enabled !== 'boolean') throw new Error('CONTRACT_ERROR: Anmeldemodi nicht ausdrücklich konfiguriert');
|
||||
// Only the canonical same-origin server entrypoint is allowed. No issuer,
|
||||
// return URL, query, fragment, credentials or externally supplied redirect.
|
||||
if (r.oidc_configured ? r.oidc_login_url !== '/auth/oidc/login' : r.oidc_login_url !== null) throw new Error('CONTRACT_ERROR: OIDC-Anmeldepfad ungültig');
|
||||
return { oidc_configured: r.oidc_configured, dev_login_enabled: r.dev_login_enabled, oidc_login_url: r.oidc_configured ? '/auth/oidc/login' : null };
|
||||
if (r.local_login_enabled !== undefined && typeof r.local_login_enabled !== 'boolean') throw new Error('CONTRACT_ERROR: Lokale Anmeldung ungültig');
|
||||
return { local_login_enabled: r.local_login_enabled === true, oidc_configured: r.oidc_configured, dev_login_enabled: r.dev_login_enabled, oidc_login_url: r.oidc_configured ? '/auth/oidc/login' : null };
|
||||
}
|
||||
export function tenant(value: unknown): Tenant { const r = record(value); return { tenant_id: text(r.tenant_id ?? r.id, 'tenant_id'), name: text(r.name, 'tenant.name') }; }
|
||||
export function session(value: unknown): Session {
|
||||
|
||||
@@ -34,3 +34,14 @@ describe('server-announced auth configuration', () => {
|
||||
expect(() => session({ principal: 'simulated-testprincipal-a', tenant_id: 't', csrf_token: 'csrf', roles: ['dev_test_member'] })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
it('renders the local password and TOTP login only when explicitly enabled', () => {
|
||||
const config = authConfig({ oidc_configured: false, oidc_login_url: null, dev_login_enabled: false, local_login_enabled: true });
|
||||
const html = renderToStaticMarkup(<Login config={config} configError={null} onLogin={onLogin}/>);
|
||||
expect(html).toContain('type="password"');
|
||||
expect(html).toContain('Authenticator-Code');
|
||||
expect(html).toContain('autoComplete="one-time-code"');
|
||||
expect(html).not.toContain('SIMULIERTER');
|
||||
expect(html).not.toContain('OIDC');
|
||||
expect(() => authConfig({ oidc_configured:false, oidc_login_url:null, dev_login_enabled:false, local_login_enabled:'true' })).toThrow();
|
||||
});
|
||||
|
||||
+27
-12
@@ -1,19 +1,34 @@
|
||||
import { useState } from 'react';
|
||||
import { AuthConfig, request, session, Session } from './api';
|
||||
|
||||
export function Login({ config, configError, onLogin }: { config: AuthConfig | null; configError: string | null; onLogin: (s: Session) => void }) {
|
||||
function CredentialsForm({ local, onLogin }: { local: boolean; onLogin: (s: Session) => void }) {
|
||||
const [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false);
|
||||
return <main className="login"><h1>RMM · Linux Verwaltung</h1>
|
||||
{configError ? <div role="alert" className="error">Anmeldekonfiguration nicht verfügbar: {configError}. Keine unsichere Standardanmeldung. Bitte nach Behebung neu laden.</div> : !config ? <p>Anmeldemodi werden über die geschützte gleiche Origin geprüft …</p> : <>
|
||||
{config.oidc_configured && config.oidc_login_url ? <section><h2>Single Sign-on</h2><p>Anmeldung über den serverseitig konfigurierten Identitätsanbieter. Zugangscodes und Tokens verarbeitet ausschließlich der Backend-Callback.</p><a href={config.oidc_login_url} rel="noreferrer">Mit SSO anmelden</a></section> : <p>OIDC: not_configured · kein Identitätsanbieter angekündigt.</p>}
|
||||
{config.dev_login_enabled && <><p className="warning">DEV/TEST · SIMULIERTER TESTPRINCIPAL · ausschließlich Entwicklungsanmeldung, kein Produktionslogin und kein menschlicher Produktions-Freigabenachweis.</p><form onSubmit={async e => { e.preventDefault(); const form = e.currentTarget; const data = new FormData(form); setBusy(true); setError(null); try {
|
||||
await request('/auth/dev/login', { body: { username: data.get('username'), password: data.get('password') } });
|
||||
form.reset(); onLogin(session(await request('/auth/session')));
|
||||
} catch (e) { setError(e instanceof Error ? e.message : 'Anmeldung fehlgeschlagen'); } finally { form.reset(); setBusy(false); } }}>
|
||||
<label>Benutzername<input name="username" autoComplete="username" required maxLength={128}/></label>
|
||||
<label>Passwort<input name="password" type="password" autoComplete="current-password" required maxLength={256}/></label>
|
||||
<button disabled={busy}>Anmelden</button>{error && <div role="alert" className="error">{error}</div>}</form></>}
|
||||
{!config.oidc_configured && !config.dev_login_enabled && <p className="warning">Anmeldung: not_configured · kein freigegebener Anmeldemodus verfügbar. Administrator kontaktieren.</p>}
|
||||
return <form aria-label={local ? 'Passwort und Authenticator-Code' : 'Entwicklungsanmeldung'} onSubmit={async event => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget, data = new FormData(form);
|
||||
setBusy(true); setError(null);
|
||||
try {
|
||||
await request(local ? '/auth/local/login' : '/auth/dev/login', {
|
||||
body: { username: data.get('username'), password: data.get('password'), ...(local ? { totp_code: data.get('totp') } : {}) }
|
||||
});
|
||||
form.reset(); onLogin(session(await request('/auth/session')));
|
||||
} catch (error) { setError(error instanceof Error ? error.message : 'Anmeldung fehlgeschlagen'); }
|
||||
finally { form.reset(); setBusy(false); }
|
||||
}}>
|
||||
<label>Benutzername<input name="username" autoComplete="username" required maxLength={128}/></label>
|
||||
<label>Passwort<input name="password" type="password" autoComplete="current-password" required maxLength={256}/></label>
|
||||
{local && <label>Authenticator-Code<input name="totp" type="text" inputMode="numeric" autoComplete="one-time-code" pattern="[0-9]{6}" minLength={6} maxLength={6} required/></label>}
|
||||
<button disabled={busy}>Anmelden</button>{error && <div role="alert" className="error">{error}</div>}
|
||||
</form>;
|
||||
}
|
||||
|
||||
export function Login({ config, configError, onLogin }: { config: AuthConfig | null; configError: string | null; onLogin: (s: Session) => void }) {
|
||||
return <main className="login"><h1>Rust Discovery</h1>
|
||||
{configError ? <div role="alert" className="error">Anmeldekonfiguration nicht verfügbar: {configError}. Bitte nach Behebung neu laden.</div> : !config ? <p>Anmeldemodi werden geladen …</p> : <>
|
||||
{config.local_login_enabled && <><h2>Anmelden</h2><CredentialsForm local onLogin={onLogin}/></>}
|
||||
{config.oidc_configured && config.oidc_login_url ? <section><h2>Single Sign-on</h2><p>Anmeldung über den serverseitig konfigurierten Identitätsanbieter.</p><a href={config.oidc_login_url} rel="noreferrer">Mit SSO anmelden</a></section> : !config.local_login_enabled && <p>OIDC: not_configured · kein Identitätsanbieter angekündigt.</p>}
|
||||
{config.dev_login_enabled && <><p className="warning">DEV/TEST · SIMULIERTER TESTPRINCIPAL · ausschließlich Entwicklungsanmeldung, kein Produktionslogin und kein menschlicher Produktions-Freigabenachweis.</p><CredentialsForm local={false} onLogin={onLogin}/></>}
|
||||
{!config.oidc_configured && !config.dev_login_enabled && !config.local_login_enabled && <p className="warning">Anmeldung: not_configured · Administrator kontaktieren.</p>}
|
||||
</>}
|
||||
</main>;
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
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';
|
||||
@@ -297,7 +298,7 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
||||
}
|
||||
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}/><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}/>}</>;
|
||||
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 App() {
|
||||
const [auth, setAuth] = useState<Session | null>(null), [loading, setLoading] = useState(true), [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { type Session } from './api';
|
||||
import { canManageMcpTokens, McpTokenManagement, mcpToken, mcpTokenDraft, mcpTokenListing } from './mcp-token-management';
|
||||
|
||||
const now = Date.parse('2026-11-17T12:00:00Z');
|
||||
const auth: Session = { principal: { id: 'test-human', display_name: 'Test', simulated: false },
|
||||
tenants: [{ tenant_id: 'tenant-a', name: 'Tenant' }], csrf_token: 'test-csrf', permissions: ['tokens:manage', 'inventory:read'] };
|
||||
const metadata = { token_id: '11111111-1111-4111-8111-111111111111', name: 'Test client', principal: 'test-human',
|
||||
scopes: ['inventory:read'], created_at: '2026-11-17T12:00:00Z', expires_at: '2026-12-17T12:00:00Z', last_used_at: null, revoked_at: null };
|
||||
|
||||
describe('MCP token management', () => {
|
||||
it('requires a real session with management permission and matching tenant', () => {
|
||||
expect(canManageMcpTokens(auth, 'tenant-a')).toBe(true);
|
||||
for (const session of [
|
||||
{ ...auth, principal: { ...auth.principal, simulated: true } }, { ...auth, csrf_token: '' },
|
||||
{ ...auth, permissions: ['approvals:approve'] }, { ...auth, tenants: [] }, { ...auth, permissions: undefined },
|
||||
]) {
|
||||
expect(canManageMcpTokens(session, 'tenant-a')).toBe(false);
|
||||
expect(renderToStaticMarkup(<McpTokenManagement auth={session} tenantId="tenant-a"/>)).toBe('');
|
||||
}
|
||||
expect(renderToStaticMarkup(<McpTokenManagement auth={auth} tenantId="tenant-b"/>)).toBe('');
|
||||
expect(renderToStaticMarkup(<McpTokenManagement auth={auth} tenantId="tenant-a"/>)).toContain('MCP-Tokens');
|
||||
});
|
||||
it('projects metadata independently from an accidentally repeated secret', () => {
|
||||
expect(mcpToken({ ...metadata, token: 'synthetic-must-not-enter-list-state', private_key: 'synthetic' })).toEqual(metadata);
|
||||
expect(() => mcpToken({ ...metadata, expires_at: 'tomorrow' })).toThrow();
|
||||
expect(() => mcpToken({ ...metadata, last_used_at: undefined })).toThrow();
|
||||
});
|
||||
it('requires read-only defaults and exact declared available rights', () => {
|
||||
const listing = { tokens: [metadata], allowed_scopes: ['inventory:read', 'operations:submit'], default_scopes: ['inventory:read'] };
|
||||
expect(mcpTokenListing(listing).default_scopes).toEqual(['inventory:read']);
|
||||
for (const altered of [
|
||||
{ ...listing, default_scopes: ['operations:submit'] }, { ...listing, default_scopes: ['logs:read'] },
|
||||
{ ...listing, allowed_scopes: ['approvals:approve'] }, { ...listing, allowed_scopes: ['tokens:manage'] },
|
||||
{ ...listing, allowed_scopes: ['inventory:read', 'inventory:read'] }, { ...listing, tokens: [metadata, metadata] },
|
||||
]) expect(() => mcpTokenListing(altered)).toThrow();
|
||||
});
|
||||
it('binds creation to explicit current rights and a finite expiry', () => {
|
||||
expect(mcpTokenDraft(' Client ', ['inventory:read'], ['inventory:read'], metadata.expires_at, now)).toEqual({
|
||||
name: 'Client', scopes: ['inventory:read'], expires_at: '2026-12-17T12:00:00.000Z',
|
||||
});
|
||||
for (const selected of [[], ['inventory:read', 'inventory:read'], ['system:execute'], ['approvals:approve'], ['tokens:manage']]) {
|
||||
expect(() => mcpTokenDraft('Client', selected, ['inventory:read'], metadata.expires_at, now)).toThrow();
|
||||
}
|
||||
for (const expires of ['invalid', new Date(now).toISOString(), new Date(now + 366 * 86400000).toISOString()]) {
|
||||
expect(() => mcpTokenDraft('Client', ['inventory:read'], ['inventory:read'], expires, now)).toThrow();
|
||||
}
|
||||
expect(mcpTokenDraft('🙂'.repeat(120), ['inventory:read'], ['inventory:read'], metadata.expires_at, now).name).toHaveLength(240);
|
||||
expect(() => mcpTokenDraft('Client\u0000', ['inventory:read'], ['inventory:read'], metadata.expires_at, now)).toThrow();
|
||||
expect(() => mcpTokenDraft(' ', ['inventory:read'], ['inventory:read'], metadata.expires_at, now)).toThrow();
|
||||
expect(() => mcpTokenDraft('x'.repeat(121), ['inventory:read'], ['inventory:read'], metadata.expires_at, now)).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from 'react';
|
||||
import { ApiError, record, request, tenantPath, type Session } from './api';
|
||||
|
||||
const scopeLabels = {
|
||||
'inventory:read': 'Inventar lesen',
|
||||
'logs:read': 'Gespeicherte Protokolle lesen',
|
||||
'operations:read': 'Aufträge und Ergebnisse lesen',
|
||||
'operations:plan': 'Aufträge planen',
|
||||
'operations:submit': 'Aufträge zur Genehmigung einreichen',
|
||||
'jobs:cancel': 'Abbruch von Aufträgen anfordern',
|
||||
'scripts:execute': 'Skriptaufträge anfordern',
|
||||
'system:execute': 'SYSTEM-Aufträge anfordern',
|
||||
'root:execute': 'root-Aufträge anfordern',
|
||||
'updates:apply': 'Updateaufträge anfordern',
|
||||
'catalog:write': 'Katalogeinträge schreiben',
|
||||
} as const;
|
||||
type Scope = keyof typeof scopeLabels;
|
||||
const readScopes = new Set<string>(['inventory:read', 'logs:read', 'operations:read']);
|
||||
const day = 24 * 60 * 60 * 1000;
|
||||
|
||||
export interface McpToken {
|
||||
token_id: string;
|
||||
name: string;
|
||||
principal: string;
|
||||
scopes: Scope[];
|
||||
created_at: string;
|
||||
expires_at: string;
|
||||
last_used_at: string | null;
|
||||
revoked_at: string | null;
|
||||
}
|
||||
interface Listing { tokens: McpToken[]; allowed_scopes: Scope[]; default_scopes: Scope[] }
|
||||
|
||||
function requireContract(condition: unknown): asserts condition {
|
||||
if (!condition) throw new Error('Ungültige Antwort der Tokenverwaltung');
|
||||
}
|
||||
function scopes(value: unknown): Scope[] {
|
||||
requireContract(Array.isArray(value) && value.every(s => typeof s === 'string' && Object.hasOwn(scopeLabels, s))
|
||||
&& new Set(value).size === value.length);
|
||||
return [...value] as Scope[];
|
||||
}
|
||||
function timestamp(value: unknown): string {
|
||||
requireContract(typeof value === 'string' && Number.isFinite(Date.parse(value)));
|
||||
return value;
|
||||
}
|
||||
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),
|
||||
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) };
|
||||
}
|
||||
export function mcpTokenListing(value: unknown): Listing {
|
||||
const r = record(value);
|
||||
requireContract(Array.isArray(r.tokens));
|
||||
const allowed = scopes(r.allowed_scopes), defaults = scopes(r.default_scopes);
|
||||
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 };
|
||||
}
|
||||
export function canManageMcpTokens(auth: Session, tenantId: string): boolean {
|
||||
return auth.principal.simulated === false && !!auth.csrf_token && auth.permissions?.includes('tokens:manage') === true
|
||||
&& auth.tenants.some(tenant => tenant.tenant_id === tenantId);
|
||||
}
|
||||
export function mcpTokenDraft(name: string, selected: string[], allowed: string[], expires: string, now = Date.now()) {
|
||||
const cleanName = name.trim(), selectedScopes = scopes(selected), expiresAt = new Date(expires).getTime();
|
||||
if (!cleanName || Array.from(cleanName).length > 120 || /\p{Cc}/u.test(cleanName)) throw new Error('Ein Name mit höchstens 120 Zeichen ist erforderlich.');
|
||||
if (!selectedScopes.length || !selectedScopes.every(s => allowed.includes(s))) throw new Error('Mindestens ein verfügbares Recht auswählen.');
|
||||
if (!Number.isFinite(expiresAt) || expiresAt <= now || expiresAt > now + 365 * day) throw new Error('Das Ablaufdatum muss in den nächsten 365 Tagen liegen.');
|
||||
return { name: cleanName, scopes: selectedScopes, expires_at: new Date(expiresAt).toISOString() };
|
||||
}
|
||||
function defaultExpiry(): string {
|
||||
const value = new Date(Date.now() + 90 * day);
|
||||
return new Date(value.getTime() - value.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
|
||||
}
|
||||
function DateLabel({ value }: { value: string | null }) {
|
||||
return value ? <time dateTime={value}>{new Date(value).toLocaleString('de-DE')}</time> : <>Bisher ungenutzt</>;
|
||||
}
|
||||
function requestFailure(error: unknown, fallback: string): string {
|
||||
if (error instanceof ApiError && [401, 403].includes(error.status)) return 'Die Sitzung oder Berechtigung ist abgelaufen. Bitte erneut anmelden.';
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function McpTokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }) {
|
||||
if (!canManageMcpTokens(auth, tenantId)) return null;
|
||||
// Reset even an in-flight creation when the actual session, tenant or rights change.
|
||||
const context = JSON.stringify([tenantId, auth.principal.id, auth.csrf_token, auth.permissions]);
|
||||
return <TokenManagement key={context} auth={auth} tenantId={tenantId}/>;
|
||||
}
|
||||
|
||||
function TokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }) {
|
||||
const path = tenantPath(tenantId, '/mcp-tokens');
|
||||
const [listing, setListing] = useState<Listing | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [selected, setSelected] = useState<Scope[]>([]);
|
||||
const [expires, setExpires] = useState(defaultExpiry);
|
||||
const [secret, setSecret] = useState<{ token: string; tokenId: string; name: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [notice, setNotice] = useState('');
|
||||
const [reload, setReload] = useState(0);
|
||||
const [revokeId, setRevokeId] = useState<string | null>(null);
|
||||
const mounted = useRef(false);
|
||||
const mutation = useRef<AbortController | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => { mounted.current = false; mutation.current?.abort(); };
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
request(path, { signal: controller.signal }).then(value => {
|
||||
if (controller.signal.aborted) return;
|
||||
const next = mcpTokenListing(value);
|
||||
setListing(next);
|
||||
setSelected(current => reload === 0 ? next.default_scopes : current.filter(s => next.allowed_scopes.includes(s)));
|
||||
}).catch(err => {
|
||||
if (!controller.signal.aborted) setError(requestFailure(err, 'Die Tokenliste konnte nicht geladen werden.'));
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [path, reload]);
|
||||
|
||||
async function create(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (busy || secret || !listing) return;
|
||||
let body;
|
||||
try { body = mcpTokenDraft(name, selected, listing.allowed_scopes, expires); }
|
||||
catch (err) { setError(err instanceof Error ? err.message : 'Tokenangaben prüfen.'); return; }
|
||||
setBusy(true); setError(''); setNotice('');
|
||||
const controller = new AbortController(); mutation.current = controller;
|
||||
try {
|
||||
const reply = record(await request(path, { body, csrf: auth.csrf_token, signal: controller.signal }));
|
||||
if (!mounted.current) return;
|
||||
const metadata = mcpToken(reply);
|
||||
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());
|
||||
} 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.'));
|
||||
setReload(value => value + 1);
|
||||
}
|
||||
} finally { if (mounted.current) setBusy(false); }
|
||||
}
|
||||
async function revoke(token: McpToken) {
|
||||
if (busy) return;
|
||||
setBusy(true); setError(''); setNotice('');
|
||||
const controller = new AbortController(); mutation.current = controller;
|
||||
try {
|
||||
const metadata = mcpToken(await request(`${path}/${encodeURIComponent(token.token_id)}/revoke`,
|
||||
{ body: {}, csrf: auth.csrf_token, signal: controller.signal }));
|
||||
if (!mounted.current) return;
|
||||
requireContract(metadata.token_id === token.token_id && metadata.revoked_at !== null);
|
||||
setListing(current => current && { ...current, tokens: current.tokens.map(row => row.token_id === metadata.token_id ? metadata : row) });
|
||||
if (secret?.tokenId === token.token_id) setSecret(null);
|
||||
setRevokeId(null); setNotice(`Token „${metadata.name}“ widerrufen.`);
|
||||
} catch (err) {
|
||||
if (mounted.current) {
|
||||
setError(requestFailure(err, 'Der Widerruf konnte nicht bestätigt werden. Der aktuelle Tokenstatus wird erneut geladen.'));
|
||||
setReload(value => value + 1);
|
||||
}
|
||||
} finally { if (mounted.current) setBusy(false); }
|
||||
}
|
||||
async function copy() {
|
||||
if (!secret) return;
|
||||
try { await navigator.clipboard.writeText(secret.token); if (mounted.current) setNotice('Token kopiert.'); }
|
||||
catch { if (mounted.current) setError('Kopieren ist im Browser nicht verfügbar. Sie können den angezeigten Token markieren und kopieren.'); }
|
||||
}
|
||||
|
||||
return <section aria-label="MCP-Tokens">
|
||||
<h2>MCP-Tokens</h2>
|
||||
<p>Erstellen Sie einen Zugang für Ihren MCP-Client. Skript- und Wartungsaufträge benötigen weiterhin die Genehmigung in der WebUI.</p>
|
||||
{error && <p className="error" role="alert">{error}</p>}
|
||||
{notice && <p role="status">{notice}</p>}
|
||||
{secret && <article aria-label="Neu erstelltes MCP-Token">
|
||||
<h3>Token für {secret.name}</h3>
|
||||
<p>Kopieren Sie diesen Token jetzt. Nach dem Schließen dieser Anzeige ist der Geheimwert nicht erneut abrufbar.</p>
|
||||
<label>Einmaliger Token<textarea readOnly rows={3} value={secret.token} autoComplete="off" spellCheck={false}/></label>
|
||||
<button type="button" onClick={() => void copy()}>Token kopieren</button>
|
||||
<button type="button" onClick={() => { setSecret(null); setNotice(''); }}>Tokenanzeige schließen</button>
|
||||
</article>}
|
||||
{!listing ? <p role="status">Tokenliste wird geladen …</p> : <>
|
||||
<form onSubmit={create}>
|
||||
<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>
|
||||
<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))}/>
|
||||
{scopeLabels[scope]} <code>{scope}</code>
|
||||
</label>)}
|
||||
</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>
|
||||
</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>
|
||||
<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.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>
|
||||
<td>{token.revoked_at === null && (revokeId === token.token_id ? <>
|
||||
<p>Zugang für „{token.name}“ jetzt beenden?</p>
|
||||
<button type="button" className="danger" disabled={busy} onClick={() => void revoke(token)}>Widerruf bestätigen</button>
|
||||
<button type="button" disabled={busy} onClick={() => setRevokeId(null)}>Abbrechen</button>
|
||||
</> : <button type="button" disabled={busy} onClick={() => setRevokeId(token.token_id)}>Widerrufen</button>)}</td>
|
||||
</tr>)}</tbody>
|
||||
</table></div>}
|
||||
</>}
|
||||
</section>;
|
||||
}
|
||||
Reference in New Issue
Block a user