mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-12-01 00:08:24 +00:00
fix(mcp): hold each MCP call to its own token, workspace and route (#12709)
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
//! The gateway checks scopes on and acts as one and the same token.
|
||||
//!
|
||||
//! A multi-workspace session checks a call against the MCP scopes of `ApiAuthed`, then runs
|
||||
//! it as the owner of the token the gateway middleware picked. `ApiAuthed` prefers the
|
||||
//! `token` cookie over `?token=` and the gateway never reads the cookie, so a request
|
||||
//! carrying both must still be held to the URL token's scopes.
|
||||
#![cfg(feature = "mcp")]
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use sqlx::{Pool, Postgres};
|
||||
use windmill_test_utils::*;
|
||||
|
||||
/// Both workspace-less, which puts the gateway in multi-workspace mode.
|
||||
async fn insert_mcp_tokens(db: &Pool<Postgres>) -> anyhow::Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin, scopes) VALUES
|
||||
(encode(sha256('OWNER_ONE_SCRIPT'::bytea), 'hex'), 'OWNER_ONE_', 'OWNER_ONE_SCRIPT', 'test@windmill.dev', 'agent', true, ARRAY['mcp:scripts:u/test-user/weekly_report']),
|
||||
(encode(sha256('OTHER_MCP_ALL'::bytea), 'hex'), 'OTHER_MCP_', 'OTHER_MCP_ALL', 'test2@windmill.dev', 'mine', false, ARRAY['mcp:all'])",
|
||||
)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The endpoint answers `application/json` or a single-event SSE stream.
|
||||
async fn gateway_post(port: u16, cookie: Option<&str>, body: Value) -> anyhow::Result<Value> {
|
||||
let mut req = reqwest::Client::new()
|
||||
.post(format!(
|
||||
"http://localhost:{port}/api/mcp/gateway?token=OWNER_ONE_SCRIPT"
|
||||
))
|
||||
.header("Accept", "application/json, text/event-stream")
|
||||
.json(&body);
|
||||
if let Some(cookie) = cookie {
|
||||
req = req.header("Cookie", format!("token={cookie}"));
|
||||
}
|
||||
let text = req.send().await?.text().await?;
|
||||
let payload = text
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("data: "))
|
||||
.unwrap_or(text.trim());
|
||||
serde_json::from_str(payload).map_err(|e| anyhow::anyhow!("unparseable MCP body {text:?}: {e}"))
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
|
||||
async fn test_mcp_gateway_cookie_does_not_widen_url_token(
|
||||
db: Pool<Postgres>,
|
||||
) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
set_jwt_secret().await;
|
||||
insert_mcp_tokens(&db).await?;
|
||||
let server = ApiServer::start_mcp(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
|
||||
let call = json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {
|
||||
"name": "getVariable",
|
||||
"arguments": { "workspace_id": "test-workspace", "path": "u/test-user/db_password" },
|
||||
}});
|
||||
let list = json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} });
|
||||
|
||||
for cookie in [None, Some("OTHER_MCP_ALL")] {
|
||||
let resp = gateway_post(port, cookie, call.clone()).await?;
|
||||
assert!(
|
||||
resp["error"]["message"]
|
||||
.as_str()
|
||||
.is_some_and(|m| m.contains("endpoint 'getVariable' not in token scope")),
|
||||
"cookie {cookie:?}: a one-script token reached getVariable: {resp}"
|
||||
);
|
||||
|
||||
let resp = gateway_post(port, cookie, list.clone()).await?;
|
||||
let tools = resp["result"]["tools"]
|
||||
.as_array()
|
||||
.ok_or_else(|| anyhow::anyhow!("no tool list in {resp}"))?;
|
||||
assert!(
|
||||
!tools.iter().any(|t| t["name"] == "getVariable"),
|
||||
"cookie {cookie:?}: a one-script token was offered getVariable"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -510,6 +510,16 @@ const INSTANCE_ROUTES: &[&str] = &[
|
||||
"/workspaces/users",
|
||||
];
|
||||
|
||||
/// Whether `w_id` has the shape of a workspace id (the `workspace.proper_id` alphabet).
|
||||
/// A caller-supplied workspace is spliced into API URLs, where `/`, `.`, `?` or `%`
|
||||
/// would move the call to another route.
|
||||
pub(crate) fn is_plain_workspace_id(w_id: &str) -> bool {
|
||||
!w_id.is_empty()
|
||||
&& w_id
|
||||
.chars()
|
||||
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
|
||||
}
|
||||
|
||||
/// The URL of an API call, refused unless it lands on the route its handler wrote.
|
||||
///
|
||||
/// The JWT behind a call carries the caller's full rights, and paths embed arguments a
|
||||
@@ -529,11 +539,8 @@ fn guarded_url(
|
||||
.strip_prefix("/w/")
|
||||
.and_then(|rest| rest.strip_prefix(w_id))
|
||||
.is_some_and(|rest| rest.starts_with('/'));
|
||||
let workspace_is_plain = w_id
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
|
||||
if path.contains('#')
|
||||
|| !workspace_is_plain
|
||||
|| !is_plain_workspace_id(w_id)
|
||||
|| !(in_workspace || INSTANCE_ROUTES.iter().any(|r| route.starts_with(r)))
|
||||
{
|
||||
return Err(refused());
|
||||
|
||||
@@ -18,7 +18,7 @@ use windmill_mcp::server::{
|
||||
RunOutcome, SessionAccess, Tool,
|
||||
};
|
||||
|
||||
use crate::auth::AuthCache;
|
||||
use crate::auth::{AuthCache, Tokened};
|
||||
use crate::db::ApiAuthed;
|
||||
use crate::jobs::{
|
||||
result_to_response, run_wait_result_flow_by_path_internal,
|
||||
@@ -733,6 +733,11 @@ pub async fn extract_workspace_from_token(
|
||||
next: Next,
|
||||
) -> Response {
|
||||
if let Some(token) = extract_gateway_token(&request) {
|
||||
// `ApiAuthed` must resolve this same token: it otherwise picks its own, preferring
|
||||
// the `token` cookie, while the session acts as the owner of `McpToken`.
|
||||
request
|
||||
.extensions_mut()
|
||||
.insert(Tokened { token: token.clone() });
|
||||
let t_hash = hash_token(&token);
|
||||
match sqlx::query!(
|
||||
"SELECT workspace_id, scopes FROM token WHERE token_hash = $1 AND (expiration > NOW() OR expiration IS NULL)",
|
||||
|
||||
@@ -426,6 +426,14 @@ pub fn substitute_path_params(
|
||||
args_map: &serde_json::Map<String, Value>,
|
||||
path_schema: &Option<Value>,
|
||||
) -> BackendResult<String> {
|
||||
// Global tools carry no workspace, and multi-workspace mode passes an empty one.
|
||||
if path.contains("{workspace}") && !crate::ai_session_tools::is_plain_workspace_id(workspace_id)
|
||||
{
|
||||
return Err(ErrorData::invalid_params(
|
||||
"Invalid workspace_id: only letters, digits, '_' and '-' are allowed".to_string(),
|
||||
None,
|
||||
));
|
||||
}
|
||||
let mut path_template = path.replace("{workspace}", workspace_id);
|
||||
|
||||
if let Some(schema) = path_schema {
|
||||
@@ -1321,6 +1329,20 @@ mod tests {
|
||||
result.is_err(),
|
||||
"traversal payload must be rejected before URL substitution"
|
||||
);
|
||||
|
||||
args.insert("path".to_string(), json!("x"));
|
||||
for workspace in ["x/../../settings/global/jwt_secret?", "a%2F..", "a.b", ""] {
|
||||
assert!(
|
||||
substitute_path_params(
|
||||
"/w/{workspace}/resources/get/{path}",
|
||||
workspace,
|
||||
&args,
|
||||
&path_schema,
|
||||
)
|
||||
.is_err(),
|
||||
"workspace {workspace:?} must be rejected"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user