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>,
|
||||
|
||||
Reference in New Issue
Block a user