Organize device inventory by customer and restrict token access to its audience
This commit is contained in:
+115
-22
@@ -31,8 +31,7 @@ const SCOPES: [&str; 11] = [
|
||||
"catalog:write",
|
||||
];
|
||||
const READ_SCOPES: [&str; 3] = ["inventory:read", "logs:read", "operations:read"];
|
||||
const COLUMNS: &str =
|
||||
"token_id,principal,name,scopes,created_at,expires_at,last_used_at,revoked_at";
|
||||
const COLUMNS: &str = "token_id,principal,name,scopes,created_at,expires_at,last_used_at,revoked_at,all_customers,coalesce(customer_ids,ARRAY[tenant_id]) AS customer_ids";
|
||||
|
||||
fn invalid() -> Error {
|
||||
Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR")
|
||||
@@ -70,6 +69,8 @@ fn metadata(row: &PgRow) -> Value {
|
||||
"token_id":row.get::<Uuid,_>("token_id"),
|
||||
"principal":row.get::<String,_>("principal"),
|
||||
"name":row.get::<String,_>("name"),
|
||||
"audience":if row.get::<bool,_>("all_customers") {"all"} else {"selected"},
|
||||
"tenant_ids":row.get::<Vec<Uuid>,_>("customer_ids"),
|
||||
"scopes":row.get::<Vec<String>,_>("scopes"),
|
||||
"created_at":row.get::<DateTime<Utc>,_>("created_at"),
|
||||
"expires_at":row.get::<DateTime<Utc>,_>("expires_at"),
|
||||
@@ -119,20 +120,31 @@ async fn list(
|
||||
headers: HeaderMap,
|
||||
Path(tenant): Path<Uuid>,
|
||||
) -> Result<Response, Error> {
|
||||
let (_, allowed, mut tx) = administration(&state, &headers, tenant, false).await?;
|
||||
let (principal, allowed, mut tx) = administration(&state, &headers, tenant, false).await?;
|
||||
let rows = sqlx::query(&format!(
|
||||
"SELECT {COLUMNS} FROM mcp_tokens ORDER BY created_at DESC,token_id"
|
||||
))
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
let can_select_all = crate::customers::can_manage(&principal, &mut tx).await?;
|
||||
tx.commit().await?;
|
||||
let mut available = Vec::new();
|
||||
for customer in &principal.tenants {
|
||||
let mut customer_tx = rmm_persistence::tenant_tx(&state.pool, *customer).await?;
|
||||
let name:Option<String>=sqlx::query_scalar("SELECT name FROM tenants WHERE tenant_id=$1 AND EXISTS(SELECT 1 FROM memberships WHERE principal=$2 AND kind='human' AND revoked_at IS NULL AND 'tokens:manage'=ANY(permissions))")
|
||||
.bind(customer).bind(&principal.name).fetch_optional(&mut *customer_tx).await?;
|
||||
if let Some(name) = name {
|
||||
available.push(json!({"tenant_id":customer,"name":name}));
|
||||
}
|
||||
customer_tx.commit().await?;
|
||||
}
|
||||
let defaults: Vec<_> = READ_SCOPES
|
||||
.into_iter()
|
||||
.filter(|scope| allowed.iter().any(|permission| permission == scope))
|
||||
.collect();
|
||||
Ok(private_json(
|
||||
json!({"tokens":rows.iter().map(metadata).collect::<Vec<_>>(),
|
||||
"allowed_scopes":allowed,"default_scopes":defaults}),
|
||||
"allowed_scopes":allowed,"default_scopes":defaults,"can_select_all":can_select_all,"available_customers":available}),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -140,6 +152,8 @@ async fn list(
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Create {
|
||||
name: String,
|
||||
audience: Option<String>,
|
||||
tenant_ids: Option<Vec<Uuid>>,
|
||||
scopes: Option<Vec<String>>,
|
||||
expires_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
@@ -200,15 +214,41 @@ async fn create(
|
||||
let (scopes, expiry) = selection(&input, &allowed, Utc::now())?;
|
||||
let token = generate()?;
|
||||
let id = Uuid::new_v4();
|
||||
sqlx::query("SELECT issue_mcp_token($1,$2,$3,$4,$5,$6)")
|
||||
let global = match input.audience.as_deref() {
|
||||
None | Some("selected") => false,
|
||||
Some("all") => true,
|
||||
_ => return Err(invalid()),
|
||||
};
|
||||
let customers = input
|
||||
.tenant_ids
|
||||
.unwrap_or_else(|| if global { vec![] } else { vec![tenant] });
|
||||
if global {
|
||||
if !customers.is_empty() {
|
||||
return Err(invalid());
|
||||
}
|
||||
if !crate::customers::can_manage(&principal, &mut tx).await? {
|
||||
return Err(denied());
|
||||
}
|
||||
} else if customers.is_empty()
|
||||
|| customers.len() > 512
|
||||
|| customers.iter().collect::<BTreeSet<_>>().len() != customers.len()
|
||||
{
|
||||
return Err(invalid());
|
||||
} else if customers.iter().any(|t| !principal.tenants.contains(t)) {
|
||||
return Err(denied());
|
||||
}
|
||||
sqlx::query("SELECT issue_customer_token($1,$2,$3,$4,$5,$6,$7,$8)")
|
||||
.bind(&principal.name)
|
||||
.bind(id)
|
||||
.bind(&input.name)
|
||||
.bind(hash(token.as_bytes()))
|
||||
.bind(scopes)
|
||||
.bind(expiry)
|
||||
.bind(global)
|
||||
.bind(&customers)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
.await
|
||||
.map_err(crate::customers::database_error)?;
|
||||
let row = sqlx::query(&format!(
|
||||
"SELECT {COLUMNS} FROM mcp_tokens WHERE token_id=$1"
|
||||
))
|
||||
@@ -251,7 +291,20 @@ pub async fn authenticate(
|
||||
raw: &str,
|
||||
selected: Option<Uuid>,
|
||||
) -> Result<Principal, StatusCode> {
|
||||
authenticate_pool(&state.pool, raw, selected).await
|
||||
let principal = authenticate_pool(&state.pool, raw, selected).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, principal.tenant)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
if !issuer_enabled(state, &mut tx, &principal.name)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?
|
||||
{
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
Ok(principal)
|
||||
}
|
||||
|
||||
async fn authenticate_pool(
|
||||
@@ -270,36 +323,49 @@ async fn authenticate_pool(
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let (tenant, id) = route.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
if selected.is_some_and(|value| value != tenant) {
|
||||
let (home, id) = route.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let tenants: Vec<Uuid> = sqlx::query_scalar("SELECT mcp_credential_customers($1)")
|
||||
.bind(&digest)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let default = tenants.first().copied().ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let tenant = selected.unwrap_or(default);
|
||||
if !tenants.contains(&tenant) {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
let principal = format!("mcp:{id}");
|
||||
let mut tx = rmm_persistence::tenant_tx(pool, tenant)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let row = sqlx::query("SELECT t.principal,t.scopes,m.permissions FROM mcp_tokens t JOIN memberships m USING(tenant_id,principal) WHERE t.token_id=$1 AND t.token_hash=$2 AND t.revoked_at IS NULL AND t.expires_at>now() AND m.kind='automation' AND m.revoked_at IS NULL")
|
||||
.bind(id).bind(digest).fetch_optional(&mut *tx).await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let allowed: Vec<String> = row.get("permissions");
|
||||
let effective: BTreeSet<String> = row
|
||||
.get::<Vec<String>, _>("scopes")
|
||||
let permissions: Vec<String> = sqlx::query_scalar("SELECT mcp_current_scopes($1)")
|
||||
.bind(&principal)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let effective: BTreeSet<String> = permissions
|
||||
.into_iter()
|
||||
.filter(|permission| allowed.contains(permission) && SCOPES.contains(&permission.as_str()))
|
||||
.filter(|p| SCOPES.contains(&p.as_str()))
|
||||
.collect();
|
||||
if effective.is_empty() {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
sqlx::query("UPDATE mcp_tokens SET last_used_at=now() WHERE token_id=$1")
|
||||
.bind(id)
|
||||
sqlx::query("SELECT set_config('app.tenant_id',$1,true)")
|
||||
.bind(home.to_string())
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
let used=sqlx::query("UPDATE mcp_tokens SET last_used_at=now() WHERE token_id=$1 AND token_hash=$2 AND revoked_at IS NULL AND expires_at>now()")
|
||||
.bind(id).bind(&digest).execute(&mut *tx).await.map_err(|_|StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
if used.rows_affected() != 1 {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
Ok(Principal {
|
||||
tenant,
|
||||
name: row.get("principal"),
|
||||
name: principal,
|
||||
operator: effective
|
||||
.iter()
|
||||
.any(|scope| !READ_SCOPES.contains(&scope.as_str())),
|
||||
@@ -308,16 +374,41 @@ async fn authenticate_pool(
|
||||
scopes: Some(effective),
|
||||
testsimulation: false,
|
||||
identity: None,
|
||||
tenants: vec![tenant],
|
||||
tenants,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn issuer_enabled(
|
||||
state: &crate::State,
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
principal: &str,
|
||||
) -> Result<bool, sqlx::Error> {
|
||||
let issuer: Option<String> = sqlx::query_scalar("SELECT mcp_current_issuer($1)")
|
||||
.bind(principal)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
Ok(issuer.is_some_and(|actor| {
|
||||
if actor.starts_with("local:") {
|
||||
state
|
||||
.auth
|
||||
.local
|
||||
.as_ref()
|
||||
.and_then(|local| local.home(&actor))
|
||||
.is_some()
|
||||
} else {
|
||||
actor.starts_with("oidc:") && state.auth.oidc.is_some()
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn enabled_in(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
principal: &str,
|
||||
) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM mcp_tokens t JOIN memberships m USING(tenant_id,principal) WHERE t.principal=$1 AND t.revoked_at IS NULL AND t.expires_at>now() AND m.kind='automation' AND m.revoked_at IS NULL AND t.scopes && m.permissions)")
|
||||
.bind(principal).fetch_one(&mut **tx).await
|
||||
sqlx::query_scalar("SELECT cardinality(mcp_current_scopes($1))>0")
|
||||
.bind(principal)
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn enabled(pool: &PgPool, principal: &str, tenant: Uuid) -> bool {
|
||||
@@ -338,6 +429,8 @@ mod tests {
|
||||
let allowed: Vec<String> = SCOPES.into_iter().map(str::to_owned).collect();
|
||||
let mut input = Create {
|
||||
name: "Inventory reader".into(),
|
||||
audience: None,
|
||||
tenant_ids: None,
|
||||
scopes: None,
|
||||
expires_at: None,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user