feat: add platform key usage to mcp auth
This commit is contained in:
Generated
+2
@@ -1168,6 +1168,7 @@ name = "mcp-server"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum",
|
"axum",
|
||||||
|
"base64",
|
||||||
"crank-adapter-grpc",
|
"crank-adapter-grpc",
|
||||||
"crank-core",
|
"crank-core",
|
||||||
"crank-mapping",
|
"crank-mapping",
|
||||||
@@ -1177,6 +1178,7 @@ dependencies = [
|
|||||||
"reqwest",
|
"reqwest",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
"sqlx",
|
"sqlx",
|
||||||
"time",
|
"time",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
|||||||
@@ -2,15 +2,14 @@
|
|||||||
|
|
||||||
## Current
|
## Current
|
||||||
|
|
||||||
### `feat/demo-assets`
|
### `feat/platform-key-usage`
|
||||||
|
|
||||||
Status: in_progress
|
Status: completed
|
||||||
|
|
||||||
DoD:
|
DoD:
|
||||||
- project has an idempotent PostgreSQL demo seed for live UI screens
|
- platform API keys authenticate real machine access
|
||||||
- demo seed fills workspaces, memberships, invitations, operations, agents, keys and usage
|
- `last_used_at` updates from successful platform key usage
|
||||||
- seed is controlled by env and does not live in migrations
|
- UI API keys page reflects honest runtime usage rather than seed-only metadata
|
||||||
- docs explain how to enable and use demo data
|
|
||||||
|
|
||||||
## Next
|
## Next
|
||||||
|
|
||||||
@@ -18,6 +17,4 @@ DoD:
|
|||||||
|
|
||||||
## Backlog
|
## Backlog
|
||||||
|
|
||||||
- `feat/current-workspace-session-model`
|
- `feat/alpine-polish`
|
||||||
- `feat/agent-lifecycle-polish`
|
|
||||||
- `feat/platform-key-usage`
|
|
||||||
|
|||||||
@@ -7,12 +7,14 @@ version.workspace = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
axum.workspace = true
|
axum.workspace = true
|
||||||
|
base64.workspace = true
|
||||||
crank-core = { path = "../../crates/crank-core" }
|
crank-core = { path = "../../crates/crank-core" }
|
||||||
crank-registry = { path = "../../crates/crank-registry" }
|
crank-registry = { path = "../../crates/crank-registry" }
|
||||||
crank-runtime = { path = "../../crates/crank-runtime" }
|
crank-runtime = { path = "../../crates/crank-runtime" }
|
||||||
crank-schema = { path = "../../crates/crank-schema" }
|
crank-schema = { path = "../../crates/crank-schema" }
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
|
sha2.workspace = true
|
||||||
time.workspace = true
|
time.workspace = true
|
||||||
tokio = { workspace = true, features = ["sync"] }
|
tokio = { workspace = true, features = ["sync"] }
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
|
|||||||
@@ -8,18 +8,21 @@ use axum::{
|
|||||||
extract::{Path, State},
|
extract::{Path, State},
|
||||||
http::{
|
http::{
|
||||||
HeaderMap, HeaderValue, StatusCode,
|
HeaderMap, HeaderValue, StatusCode,
|
||||||
header::{self, ACCEPT},
|
header::{self, ACCEPT, AUTHORIZATION},
|
||||||
},
|
},
|
||||||
response::{IntoResponse, Response},
|
response::{IntoResponse, Response},
|
||||||
routing::get,
|
routing::get,
|
||||||
};
|
};
|
||||||
|
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||||
use crank_core::{
|
use crank_core::{
|
||||||
InvocationLevel, InvocationLog, InvocationLogId, InvocationSource, InvocationStatus,
|
InvocationLevel, InvocationLog, InvocationLogId, InvocationSource, InvocationStatus,
|
||||||
|
PlatformApiKeyScope,
|
||||||
};
|
};
|
||||||
use crank_registry::{CreateInvocationLogRequest, PostgresRegistry, PublishedAgentTool};
|
use crank_registry::{CreateInvocationLogRequest, PostgresRegistry, PublishedAgentTool};
|
||||||
use crank_runtime::{RuntimeError, RuntimeExecutor, RuntimeOperation};
|
use crank_runtime::{RuntimeError, RuntimeExecutor, RuntimeOperation};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -106,6 +109,12 @@ async fn mcp_delete(
|
|||||||
State(state): State<Arc<AppState>>,
|
State(state): State<Arc<AppState>>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
|
if let Err(status) =
|
||||||
|
require_platform_api_key(&state, &path, &headers, PlatformApiKeyScope::Read).await
|
||||||
|
{
|
||||||
|
return status.into_response();
|
||||||
|
}
|
||||||
|
|
||||||
match session_id_from_headers(&headers) {
|
match session_id_from_headers(&headers) {
|
||||||
Ok(Some(session_id)) => match state.sessions.get(&session_id).await {
|
Ok(Some(session_id)) => match state.sessions.get(&session_id).await {
|
||||||
Some(session)
|
Some(session)
|
||||||
@@ -149,6 +158,14 @@ async fn mcp_post(
|
|||||||
Err(status) => return status.into_response(),
|
Err(status) => return status.into_response(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let required_scope = match method_name(&message) {
|
||||||
|
Some("tools/call") => PlatformApiKeyScope::Write,
|
||||||
|
_ => PlatformApiKeyScope::Read,
|
||||||
|
};
|
||||||
|
if let Err(status) = require_platform_api_key(&state, &path, &headers, required_scope).await {
|
||||||
|
return status.into_response();
|
||||||
|
}
|
||||||
|
|
||||||
match method_name(&message) {
|
match method_name(&message) {
|
||||||
Some("initialize") if is_request(&message) => {
|
Some("initialize") if is_request(&message) => {
|
||||||
handle_initialize(state, &path, &message).await
|
handle_initialize(state, &path, &message).await
|
||||||
@@ -467,6 +484,71 @@ async fn require_initialized_session(
|
|||||||
Ok(session)
|
Ok(session)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn require_platform_api_key(
|
||||||
|
state: &Arc<AppState>,
|
||||||
|
path: &AgentRoutePath,
|
||||||
|
headers: &HeaderMap,
|
||||||
|
required_scope: PlatformApiKeyScope,
|
||||||
|
) -> Result<(), StatusCode> {
|
||||||
|
let secret = bearer_token(headers).ok_or(StatusCode::UNAUTHORIZED)?;
|
||||||
|
let secret_hash = hash_access_secret(secret);
|
||||||
|
let Some(api_key) = state
|
||||||
|
.registry
|
||||||
|
.get_platform_api_key_by_secret_for_workspace_slug(&path.workspace_slug, &secret_hash)
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
|
else {
|
||||||
|
return Err(StatusCode::UNAUTHORIZED);
|
||||||
|
};
|
||||||
|
|
||||||
|
if !allows_scope(&api_key.api_key.scopes, required_scope) {
|
||||||
|
return Err(StatusCode::FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
let used_at = OffsetDateTime::now_utc()
|
||||||
|
.format(&Rfc3339)
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
state
|
||||||
|
.registry
|
||||||
|
.touch_platform_api_key(&api_key.api_key.workspace_id, &api_key.api_key.id, &used_at)
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bearer_token(headers: &HeaderMap) -> Option<&str> {
|
||||||
|
let value = headers.get(AUTHORIZATION)?.to_str().ok()?;
|
||||||
|
let (scheme, token) = value.split_once(' ')?;
|
||||||
|
if !scheme.eq_ignore_ascii_case("Bearer") || token.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(token)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn allows_scope(scopes: &[PlatformApiKeyScope], required_scope: PlatformApiKeyScope) -> bool {
|
||||||
|
match required_scope {
|
||||||
|
PlatformApiKeyScope::Read => scopes.iter().any(|scope| {
|
||||||
|
matches!(
|
||||||
|
scope,
|
||||||
|
PlatformApiKeyScope::Read
|
||||||
|
| PlatformApiKeyScope::Write
|
||||||
|
| PlatformApiKeyScope::Deploy
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
PlatformApiKeyScope::Write => scopes.iter().any(|scope| {
|
||||||
|
matches!(
|
||||||
|
scope,
|
||||||
|
PlatformApiKeyScope::Write | PlatformApiKeyScope::Deploy
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
PlatformApiKeyScope::Deploy => scopes
|
||||||
|
.iter()
|
||||||
|
.any(|scope| matches!(scope, PlatformApiKeyScope::Deploy)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn validate_origin(
|
fn validate_origin(
|
||||||
allowed_origins: &AllowedOrigins,
|
allowed_origins: &AllowedOrigins,
|
||||||
headers: &HeaderMap,
|
headers: &HeaderMap,
|
||||||
@@ -611,6 +693,11 @@ fn runtime_error_code(error: &RuntimeError) -> &'static str {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn hash_access_secret(secret: &str) -> String {
|
||||||
|
let digest = Sha256::digest(secret.as_bytes());
|
||||||
|
URL_SAFE_NO_PAD.encode(digest)
|
||||||
|
}
|
||||||
|
|
||||||
fn json_response(
|
fn json_response(
|
||||||
status: StatusCode,
|
status: StatusCode,
|
||||||
payload: Value,
|
payload: Value,
|
||||||
|
|||||||
+185
-10
@@ -49,19 +49,22 @@ mod tests {
|
|||||||
};
|
};
|
||||||
|
|
||||||
use axum::{Json, Router, http::header, routing::post};
|
use axum::{Json, Router, http::header, routing::post};
|
||||||
|
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||||
use crank_adapter_grpc::test_support as grpc_test_support;
|
use crank_adapter_grpc::test_support as grpc_test_support;
|
||||||
use crank_core::{
|
use crank_core::{
|
||||||
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, DescriptorId,
|
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, DescriptorId,
|
||||||
ExecutionConfig, GraphqlOperationType, GraphqlTarget, GrpcTarget, HttpMethod, Operation,
|
ExecutionConfig, GraphqlOperationType, GraphqlTarget, GrpcTarget, HttpMethod, Operation,
|
||||||
OperationId, OperationStatus, Protocol, RestTarget, Target, ToolDescription, WorkspaceId,
|
OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyScope,
|
||||||
|
PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolDescription, WorkspaceId,
|
||||||
};
|
};
|
||||||
use crank_mapping::{MappingRule, MappingSet};
|
use crank_mapping::{MappingRule, MappingSet};
|
||||||
use crank_registry::{
|
use crank_registry::{
|
||||||
CreateAgentRequest, ListInvocationLogsQuery, PostgresRegistry, PublishAgentRequest,
|
CreateAgentRequest, CreatePlatformApiKeyRequest, ListInvocationLogsQuery, PostgresRegistry,
|
||||||
PublishRequest,
|
PublishAgentRequest, PublishRequest,
|
||||||
};
|
};
|
||||||
use crank_schema::{Schema, SchemaKind};
|
use crank_schema::{Schema, SchemaKind};
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
use sqlx::{Executor, postgres::PgPoolOptions};
|
use sqlx::{Executor, postgres::PgPoolOptions};
|
||||||
use tokio::net::TcpListener;
|
use tokio::net::TcpListener;
|
||||||
|
|
||||||
@@ -96,6 +99,12 @@ mod tests {
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
publish_agent_for_operation(®istry, &operation, "sales-rest").await;
|
publish_agent_for_operation(®istry, &operation, "sales-rest").await;
|
||||||
|
let api_key = create_platform_api_key(
|
||||||
|
®istry,
|
||||||
|
"mcp-rest",
|
||||||
|
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
let base_url = spawn_mcp_server(build_app(
|
let base_url = spawn_mcp_server(build_app(
|
||||||
registry.clone(),
|
registry.clone(),
|
||||||
@@ -105,11 +114,12 @@ mod tests {
|
|||||||
.await;
|
.await;
|
||||||
let client = reqwest::Client::new();
|
let client = reqwest::Client::new();
|
||||||
let mcp_url = agent_mcp_url(&base_url, "sales-rest");
|
let mcp_url = agent_mcp_url(&base_url, "sales-rest");
|
||||||
let initialized_session = initialize_session(&client, &mcp_url).await;
|
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
|
||||||
|
|
||||||
let tools = post_jsonrpc(
|
let tools = post_jsonrpc(
|
||||||
&client,
|
&client,
|
||||||
&mcp_url,
|
&mcp_url,
|
||||||
|
&api_key,
|
||||||
Some(&initialized_session),
|
Some(&initialized_session),
|
||||||
json!({
|
json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
@@ -122,6 +132,7 @@ mod tests {
|
|||||||
let call_result = post_jsonrpc(
|
let call_result = post_jsonrpc(
|
||||||
&client,
|
&client,
|
||||||
&mcp_url,
|
&mcp_url,
|
||||||
|
&api_key,
|
||||||
Some(&initialized_session),
|
Some(&initialized_session),
|
||||||
json!({
|
json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
@@ -165,6 +176,12 @@ mod tests {
|
|||||||
);
|
);
|
||||||
assert_eq!(logs[0].log.status, crank_core::InvocationStatus::Ok);
|
assert_eq!(logs[0].log.status, crank_core::InvocationStatus::Ok);
|
||||||
assert_eq!(logs[0].log.tool_name, "crm_create_lead");
|
assert_eq!(logs[0].log.tool_name, "crm_create_lead");
|
||||||
|
|
||||||
|
let keys = registry
|
||||||
|
.list_platform_api_keys(&test_workspace_id())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(keys[0].api_key.last_used_at.is_some());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -188,6 +205,12 @@ mod tests {
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
publish_agent_for_operation(®istry, &operation, "sales-graphql").await;
|
publish_agent_for_operation(®istry, &operation, "sales-graphql").await;
|
||||||
|
let api_key = create_platform_api_key(
|
||||||
|
®istry,
|
||||||
|
"mcp-graphql",
|
||||||
|
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
let base_url = spawn_mcp_server(build_app(
|
let base_url = spawn_mcp_server(build_app(
|
||||||
registry,
|
registry,
|
||||||
@@ -197,11 +220,12 @@ mod tests {
|
|||||||
.await;
|
.await;
|
||||||
let client = reqwest::Client::new();
|
let client = reqwest::Client::new();
|
||||||
let mcp_url = agent_mcp_url(&base_url, "sales-graphql");
|
let mcp_url = agent_mcp_url(&base_url, "sales-graphql");
|
||||||
let initialized_session = initialize_session(&client, &mcp_url).await;
|
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
|
||||||
|
|
||||||
let call_result = post_jsonrpc(
|
let call_result = post_jsonrpc(
|
||||||
&client,
|
&client,
|
||||||
&mcp_url,
|
&mcp_url,
|
||||||
|
&api_key,
|
||||||
Some(&initialized_session),
|
Some(&initialized_session),
|
||||||
json!({
|
json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
@@ -245,6 +269,12 @@ mod tests {
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
publish_agent_for_operation(®istry, &operation, "sales-grpc").await;
|
publish_agent_for_operation(®istry, &operation, "sales-grpc").await;
|
||||||
|
let api_key = create_platform_api_key(
|
||||||
|
®istry,
|
||||||
|
"mcp-grpc",
|
||||||
|
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
let base_url = spawn_mcp_server(build_app(
|
let base_url = spawn_mcp_server(build_app(
|
||||||
registry,
|
registry,
|
||||||
@@ -254,11 +284,12 @@ mod tests {
|
|||||||
.await;
|
.await;
|
||||||
let client = reqwest::Client::new();
|
let client = reqwest::Client::new();
|
||||||
let mcp_url = agent_mcp_url(&base_url, "sales-grpc");
|
let mcp_url = agent_mcp_url(&base_url, "sales-grpc");
|
||||||
let initialized_session = initialize_session(&client, &mcp_url).await;
|
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
|
||||||
|
|
||||||
let call_result = post_jsonrpc(
|
let call_result = post_jsonrpc(
|
||||||
&client,
|
&client,
|
||||||
&mcp_url,
|
&mcp_url,
|
||||||
|
&api_key,
|
||||||
Some(&initialized_session),
|
Some(&initialized_session),
|
||||||
json!({
|
json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
@@ -284,6 +315,9 @@ mod tests {
|
|||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn requires_initialized_notification_before_tool_methods() {
|
async fn requires_initialized_notification_before_tool_methods() {
|
||||||
let registry = test_registry().await;
|
let registry = test_registry().await;
|
||||||
|
publish_agent_with_bindings(®istry, "sales-init", vec![]).await;
|
||||||
|
let api_key =
|
||||||
|
create_platform_api_key(®istry, "mcp-init", &[PlatformApiKeyScope::Read]).await;
|
||||||
let base_url = spawn_mcp_server(build_app(
|
let base_url = spawn_mcp_server(build_app(
|
||||||
registry,
|
registry,
|
||||||
Duration::from_millis(0),
|
Duration::from_millis(0),
|
||||||
@@ -295,6 +329,7 @@ mod tests {
|
|||||||
let initialize_response = client
|
let initialize_response = client
|
||||||
.post(&mcp_url)
|
.post(&mcp_url)
|
||||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||||
|
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
|
||||||
.json(&json!({
|
.json(&json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"id": 1,
|
"id": 1,
|
||||||
@@ -316,6 +351,7 @@ mod tests {
|
|||||||
let tools_list = client
|
let tools_list = client
|
||||||
.post(&mcp_url)
|
.post(&mcp_url)
|
||||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||||
|
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
|
||||||
.header("MCP-Session-Id", session_id)
|
.header("MCP-Session-Id", session_id)
|
||||||
.header("MCP-Protocol-Version", "2025-11-25")
|
.header("MCP-Protocol-Version", "2025-11-25")
|
||||||
.json(&json!({
|
.json(&json!({
|
||||||
@@ -346,11 +382,18 @@ mod tests {
|
|||||||
.await;
|
.await;
|
||||||
let client = reqwest::Client::new();
|
let client = reqwest::Client::new();
|
||||||
let mcp_url = agent_mcp_url(&base_url, "sales-refresh");
|
let mcp_url = agent_mcp_url(&base_url, "sales-refresh");
|
||||||
let initialized_session = initialize_session(&client, &mcp_url).await;
|
let api_key = create_platform_api_key(
|
||||||
|
®istry,
|
||||||
|
"mcp-refresh",
|
||||||
|
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
|
||||||
|
|
||||||
let before_publish = post_jsonrpc(
|
let before_publish = post_jsonrpc(
|
||||||
&client,
|
&client,
|
||||||
&mcp_url,
|
&mcp_url,
|
||||||
|
&api_key,
|
||||||
Some(&initialized_session),
|
Some(&initialized_session),
|
||||||
json!({
|
json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
@@ -381,6 +424,7 @@ mod tests {
|
|||||||
let after_publish = post_jsonrpc(
|
let after_publish = post_jsonrpc(
|
||||||
&client,
|
&client,
|
||||||
&mcp_url,
|
&mcp_url,
|
||||||
|
&api_key,
|
||||||
Some(&initialized_session),
|
Some(&initialized_session),
|
||||||
json!({
|
json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
@@ -434,6 +478,12 @@ mod tests {
|
|||||||
vec![binding_for_operation(&operation_b)],
|
vec![binding_for_operation(&operation_b)],
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
let api_key = create_platform_api_key(
|
||||||
|
®istry,
|
||||||
|
"mcp-agents",
|
||||||
|
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
let base_url = spawn_mcp_server(build_app(
|
let base_url = spawn_mcp_server(build_app(
|
||||||
registry,
|
registry,
|
||||||
@@ -444,12 +494,13 @@ mod tests {
|
|||||||
let client = reqwest::Client::new();
|
let client = reqwest::Client::new();
|
||||||
let agent_a_url = agent_mcp_url(&base_url, "sales-a");
|
let agent_a_url = agent_mcp_url(&base_url, "sales-a");
|
||||||
let agent_b_url = agent_mcp_url(&base_url, "sales-b");
|
let agent_b_url = agent_mcp_url(&base_url, "sales-b");
|
||||||
let session_a = initialize_session(&client, &agent_a_url).await;
|
let session_a = initialize_session(&client, &agent_a_url, &api_key).await;
|
||||||
let session_b = initialize_session(&client, &agent_b_url).await;
|
let session_b = initialize_session(&client, &agent_b_url, &api_key).await;
|
||||||
|
|
||||||
let tools_a = post_jsonrpc(
|
let tools_a = post_jsonrpc(
|
||||||
&client,
|
&client,
|
||||||
&agent_a_url,
|
&agent_a_url,
|
||||||
|
&api_key,
|
||||||
Some(&session_a),
|
Some(&session_a),
|
||||||
json!({
|
json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
@@ -462,6 +513,7 @@ mod tests {
|
|||||||
let tools_b = post_jsonrpc(
|
let tools_b = post_jsonrpc(
|
||||||
&client,
|
&client,
|
||||||
&agent_b_url,
|
&agent_b_url,
|
||||||
|
&api_key,
|
||||||
Some(&session_b),
|
Some(&session_b),
|
||||||
json!({
|
json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
@@ -476,10 +528,97 @@ mod tests {
|
|||||||
assert_eq!(tools_b["result"]["tools"][0]["name"], "crm_update_lead");
|
assert_eq!(tools_b["result"]["tools"][0]["name"], "crm_update_lead");
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn initialize_session(client: &reqwest::Client, mcp_url: &str) -> String {
|
#[tokio::test]
|
||||||
|
async fn rejects_initialize_without_platform_api_key() {
|
||||||
|
let registry = test_registry().await;
|
||||||
|
publish_agent_with_bindings(®istry, "sales-auth", vec![]).await;
|
||||||
|
let base_url = spawn_mcp_server(build_app(
|
||||||
|
registry,
|
||||||
|
Duration::from_millis(0),
|
||||||
|
Some("https://crank.example.com".to_owned()),
|
||||||
|
))
|
||||||
|
.await;
|
||||||
|
let client = reqwest::Client::new();
|
||||||
|
let response = client
|
||||||
|
.post(agent_mcp_url(&base_url, "sales-auth"))
|
||||||
|
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||||
|
.json(&json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 1,
|
||||||
|
"method": "initialize",
|
||||||
|
"params": {
|
||||||
|
"protocolVersion": "2025-11-25"
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(response.status(), reqwest::StatusCode::UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rejects_tool_call_with_read_only_platform_api_key() {
|
||||||
|
let registry = test_registry().await;
|
||||||
|
let upstream_base_url = spawn_upstream_server().await;
|
||||||
|
let operation = test_operation(&upstream_base_url, "crm_read_only");
|
||||||
|
|
||||||
|
registry
|
||||||
|
.create_operation(&test_workspace_id(), &operation, Some("alice"))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
registry
|
||||||
|
.publish_operation(PublishRequest {
|
||||||
|
workspace_id: &test_workspace_id(),
|
||||||
|
operation_id: &operation.id,
|
||||||
|
version: 1,
|
||||||
|
published_at: "2026-03-26T10:00:00Z",
|
||||||
|
published_by: Some("alice"),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
publish_agent_for_operation(®istry, &operation, "sales-read-only").await;
|
||||||
|
let api_key =
|
||||||
|
create_platform_api_key(®istry, "mcp-read", &[PlatformApiKeyScope::Read]).await;
|
||||||
|
|
||||||
|
let base_url = spawn_mcp_server(build_app(
|
||||||
|
registry,
|
||||||
|
Duration::from_millis(0),
|
||||||
|
Some("https://crank.example.com".to_owned()),
|
||||||
|
))
|
||||||
|
.await;
|
||||||
|
let client = reqwest::Client::new();
|
||||||
|
let mcp_url = agent_mcp_url(&base_url, "sales-read-only");
|
||||||
|
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
|
||||||
|
let response = client
|
||||||
|
.post(&mcp_url)
|
||||||
|
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||||
|
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
|
||||||
|
.header("MCP-Session-Id", initialized_session)
|
||||||
|
.header("MCP-Protocol-Version", "2025-11-25")
|
||||||
|
.json(&json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 3,
|
||||||
|
"method": "tools/call",
|
||||||
|
"params": {
|
||||||
|
"name": "crm_read_only",
|
||||||
|
"arguments": {
|
||||||
|
"email": "user@example.com"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(response.status(), reqwest::StatusCode::FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn initialize_session(client: &reqwest::Client, mcp_url: &str, api_key: &str) -> String {
|
||||||
let initialize_response = client
|
let initialize_response = client
|
||||||
.post(mcp_url)
|
.post(mcp_url)
|
||||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||||
|
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
|
||||||
.json(&json!({
|
.json(&json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"id": 1,
|
"id": 1,
|
||||||
@@ -502,6 +641,7 @@ mod tests {
|
|||||||
let initialized_response = client
|
let initialized_response = client
|
||||||
.post(mcp_url)
|
.post(mcp_url)
|
||||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||||
|
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
|
||||||
.header("MCP-Session-Id", &session_id)
|
.header("MCP-Session-Id", &session_id)
|
||||||
.header("MCP-Protocol-Version", "2025-11-25")
|
.header("MCP-Protocol-Version", "2025-11-25")
|
||||||
.json(&json!({
|
.json(&json!({
|
||||||
@@ -521,12 +661,14 @@ mod tests {
|
|||||||
async fn post_jsonrpc(
|
async fn post_jsonrpc(
|
||||||
client: &reqwest::Client,
|
client: &reqwest::Client,
|
||||||
mcp_url: &str,
|
mcp_url: &str,
|
||||||
|
api_key: &str,
|
||||||
session_id: Option<&str>,
|
session_id: Option<&str>,
|
||||||
payload: Value,
|
payload: Value,
|
||||||
) -> Value {
|
) -> Value {
|
||||||
let mut request = client
|
let mut request = client
|
||||||
.post(mcp_url)
|
.post(mcp_url)
|
||||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||||
|
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
|
||||||
.header("MCP-Protocol-Version", "2025-11-25");
|
.header("MCP-Protocol-Version", "2025-11-25");
|
||||||
|
|
||||||
if let Some(session_id) = session_id {
|
if let Some(session_id) = session_id {
|
||||||
@@ -543,6 +685,39 @@ mod tests {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn create_platform_api_key(
|
||||||
|
registry: &PostgresRegistry,
|
||||||
|
name: &str,
|
||||||
|
scopes: &[PlatformApiKeyScope],
|
||||||
|
) -> String {
|
||||||
|
let secret = format!("crk_{}_{}", name, uuid::Uuid::now_v7().simple());
|
||||||
|
let api_key = PlatformApiKey {
|
||||||
|
id: PlatformApiKeyId::new(format!("pk_{name}")),
|
||||||
|
workspace_id: test_workspace_id(),
|
||||||
|
name: name.to_owned(),
|
||||||
|
prefix: secret.chars().take(16).collect(),
|
||||||
|
scopes: scopes.to_vec(),
|
||||||
|
status: PlatformApiKeyStatus::Active,
|
||||||
|
created_at: "2026-03-26T10:00:00Z".to_owned(),
|
||||||
|
last_used_at: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
registry
|
||||||
|
.create_platform_api_key(CreatePlatformApiKeyRequest {
|
||||||
|
api_key: &api_key,
|
||||||
|
secret_hash: &hash_access_secret(&secret),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
secret
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hash_access_secret(secret: &str) -> String {
|
||||||
|
let digest = Sha256::digest(secret.as_bytes());
|
||||||
|
URL_SAFE_NO_PAD.encode(digest)
|
||||||
|
}
|
||||||
|
|
||||||
async fn spawn_upstream_server() -> String {
|
async fn spawn_upstream_server() -> String {
|
||||||
let app = Router::new().route("/crm/leads", post(create_lead));
|
let app = Router::new().route("/crm/leads", post(create_lead));
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
|||||||
@@ -115,7 +115,7 @@
|
|||||||
<div class="page-header">
|
<div class="page-header">
|
||||||
<div class="page-header-text">
|
<div class="page-header-text">
|
||||||
<h1 class="page-title" data-i18n="apikeys.title">API Keys</h1>
|
<h1 class="page-title" data-i18n="apikeys.title">API Keys</h1>
|
||||||
<p class="page-subtitle">Keys authenticate external clients and CI pipelines to the Crank API.</p>
|
<p class="page-subtitle">Keys authenticate external MCP clients and workspace automation against Crank.</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="page-header-actions">
|
<div class="page-header-actions">
|
||||||
<button class="btn-primary" id="btn-create-key" type="button">
|
<button class="btn-primary" id="btn-create-key" type="button">
|
||||||
@@ -131,7 +131,7 @@
|
|||||||
<path d="M8 11V8M8 5.5V5"/>
|
<path d="M8 11V8M8 5.5V5"/>
|
||||||
</svg>
|
</svg>
|
||||||
<div>
|
<div>
|
||||||
<strong>Keys are only shown once.</strong> Copy and store them securely immediately after creation — Crank stores only a hash. Revoked keys cannot be restored.
|
<strong>Keys are only shown once.</strong> Copy and store them securely immediately after creation — Crank stores only a hash. `Last used` updates after successful MCP authentication.
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -175,19 +175,19 @@
|
|||||||
<div style="font-size:12.5px;font-weight:600;color:var(--text-primary);margin-bottom:4px;display:flex;align-items:center;gap:6px;">
|
<div style="font-size:12.5px;font-weight:600;color:var(--text-primary);margin-bottom:4px;display:flex;align-items:center;gap:6px;">
|
||||||
<span class="badge badge-scope">read</span>
|
<span class="badge badge-scope">read</span>
|
||||||
</div>
|
</div>
|
||||||
<div style="font-size:12px;color:var(--text-muted);line-height:1.55;">List operations, read configs, query logs and usage metrics.</div>
|
<div style="font-size:12px;color:var(--text-muted);line-height:1.55;">Initialize MCP sessions, ping the server, and list tools for a workspace agent.</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div style="font-size:12.5px;font-weight:600;color:var(--text-primary);margin-bottom:4px;">
|
<div style="font-size:12.5px;font-weight:600;color:var(--text-primary);margin-bottom:4px;">
|
||||||
<span class="badge badge-scope">write</span>
|
<span class="badge badge-scope">write</span>
|
||||||
</div>
|
</div>
|
||||||
<div style="font-size:12px;color:var(--text-muted);line-height:1.55;">Create, update, and delete operations and their configurations.</div>
|
<div style="font-size:12px;color:var(--text-muted);line-height:1.55;">Execute `tools/call` requests against published agent toolsets.</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div style="font-size:12.5px;font-weight:600;color:var(--text-primary);margin-bottom:4px;">
|
<div style="font-size:12.5px;font-weight:600;color:var(--text-primary);margin-bottom:4px;">
|
||||||
<span class="badge badge-scope">deploy</span>
|
<span class="badge badge-scope">deploy</span>
|
||||||
</div>
|
</div>
|
||||||
<div style="font-size:12px;color:var(--text-muted);line-height:1.55;">Publish agents and operations and perform deploy-scoped platform actions.</div>
|
<div style="font-size:12px;color:var(--text-muted);line-height:1.55;">Reserved for deploy-scoped automation. Today it also permits MCP read/write flows.</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ var search = '';
|
|||||||
|
|
||||||
var SCOPES = ['read', 'write', 'deploy'];
|
var SCOPES = ['read', 'write', 'deploy'];
|
||||||
var SCOPE_DESC = {
|
var SCOPE_DESC = {
|
||||||
read: 'Read operations, logs, and usage',
|
read: 'Initialize MCP sessions and list tools',
|
||||||
write: 'Create and update operations',
|
write: 'Execute published tools through MCP',
|
||||||
deploy: 'Publish agents and operations',
|
deploy: 'Reserved for deploy-scoped automation',
|
||||||
};
|
};
|
||||||
|
|
||||||
function mapKeyRecord(record) {
|
function mapKeyRecord(record) {
|
||||||
|
|||||||
@@ -584,6 +584,36 @@ impl PostgresRegistry {
|
|||||||
rows.iter().map(map_platform_api_key_record).collect()
|
rows.iter().map(map_platform_api_key_record).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn get_platform_api_key_by_secret_for_workspace_slug(
|
||||||
|
&self,
|
||||||
|
workspace_slug: &str,
|
||||||
|
secret_hash: &str,
|
||||||
|
) -> Result<Option<PlatformApiKeyRecord>, RegistryError> {
|
||||||
|
let row = sqlx::query(
|
||||||
|
"select
|
||||||
|
k.id,
|
||||||
|
k.workspace_id,
|
||||||
|
k.name,
|
||||||
|
k.prefix,
|
||||||
|
k.scopes_json,
|
||||||
|
k.status,
|
||||||
|
to_char(k.created_at at time zone 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') as created_at,
|
||||||
|
to_char(k.last_used_at at time zone 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') as last_used_at
|
||||||
|
from platform_api_keys k
|
||||||
|
join workspaces w on w.id = k.workspace_id
|
||||||
|
where w.slug = $1
|
||||||
|
and k.secret_hash = $2
|
||||||
|
and k.status = 'active'
|
||||||
|
limit 1",
|
||||||
|
)
|
||||||
|
.bind(workspace_slug)
|
||||||
|
.bind(secret_hash)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
row.as_ref().map(map_platform_api_key_record).transpose()
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn create_platform_api_key(
|
pub async fn create_platform_api_key(
|
||||||
&self,
|
&self,
|
||||||
request: CreatePlatformApiKeyRequest<'_>,
|
request: CreatePlatformApiKeyRequest<'_>,
|
||||||
@@ -680,6 +710,32 @@ impl PostgresRegistry {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn touch_platform_api_key(
|
||||||
|
&self,
|
||||||
|
workspace_id: &WorkspaceId,
|
||||||
|
key_id: &PlatformApiKeyId,
|
||||||
|
used_at: &str,
|
||||||
|
) -> Result<(), RegistryError> {
|
||||||
|
let result = sqlx::query(
|
||||||
|
"update platform_api_keys
|
||||||
|
set last_used_at = $3::timestamptz
|
||||||
|
where workspace_id = $1 and id = $2",
|
||||||
|
)
|
||||||
|
.bind(workspace_id.as_str())
|
||||||
|
.bind(key_id.as_str())
|
||||||
|
.bind(used_at)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
return Err(RegistryError::PlatformApiKeyNotFound {
|
||||||
|
key_id: key_id.as_str().to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn create_invocation_log(
|
pub async fn create_invocation_log(
|
||||||
&self,
|
&self,
|
||||||
request: CreateInvocationLogRequest<'_>,
|
request: CreateInvocationLogRequest<'_>,
|
||||||
|
|||||||
@@ -145,6 +145,7 @@
|
|||||||
- `POST /platform-api-keys` возвращает metadata ключа и одноразовый `secret`;
|
- `POST /platform-api-keys` возвращает metadata ключа и одноразовый `secret`;
|
||||||
- `secret` доступен только в create-response;
|
- `secret` доступен только в create-response;
|
||||||
- list endpoints возвращают только metadata, `prefix`, `status`, `scopes` и `last_used_at`.
|
- list endpoints возвращают только metadata, `prefix`, `status`, `scopes` и `last_used_at`.
|
||||||
|
- `last_used_at` обновляется при успешной machine-auth аутентификации этим ключом в `mcp-server`.
|
||||||
|
|
||||||
### 5.8. Observability
|
### 5.8. Observability
|
||||||
|
|
||||||
|
|||||||
@@ -201,7 +201,6 @@ UI-файлы:
|
|||||||
|
|
||||||
Что еще не хватает:
|
Что еще не хватает:
|
||||||
|
|
||||||
- отдельный usage/last-used update flow, когда ключи реально начнут использоваться в runtime;
|
|
||||||
- если захотим richer UX, можно добавить server-side pagination и фильтрацию по статусу.
|
- если захотим richer UX, можно добавить server-side pagination и фильтрацию по статусу.
|
||||||
|
|
||||||
Отдельный конфликт:
|
Отдельный конфликт:
|
||||||
@@ -213,7 +212,8 @@ UI-файлы:
|
|||||||
|
|
||||||
- страница уже сажается на текущий backend без новых ручек;
|
- страница уже сажается на текущий backend без новых ручек;
|
||||||
- live `list/create/revoke/delete` можно считать закрытым;
|
- live `list/create/revoke/delete` можно считать закрытым;
|
||||||
- следующий реальный шаг здесь только в polishing вокруг usage и audit trail.
|
- `last_used_at` теперь обновляется через успешную machine-auth аутентификацию в `mcp-server`;
|
||||||
|
- следующий реальный шаг здесь только в polishing вокруг audit trail и richer filtering.
|
||||||
|
|
||||||
### 4.5. Logs
|
### 4.5. Logs
|
||||||
|
|
||||||
|
|||||||
@@ -93,6 +93,19 @@
|
|||||||
- конкретный curated toolset;
|
- конкретный curated toolset;
|
||||||
- набор usage и log labels.
|
- набор usage и log labels.
|
||||||
|
|
||||||
|
## 7.1. MCP authentication
|
||||||
|
|
||||||
|
`mcp-server` использует workspace-scoped `platform API keys` как machine credentials.
|
||||||
|
|
||||||
|
Контракт:
|
||||||
|
|
||||||
|
- клиент передает `Authorization: Bearer crk_...`;
|
||||||
|
- ключ должен принадлежать workspace из path;
|
||||||
|
- `read` разрешает `initialize`, `notifications/initialized`, `ping`, `tools/list`;
|
||||||
|
- `write` разрешает `tools/call`;
|
||||||
|
- `deploy` сейчас включает те же MCP права, что и `write`, и зарезервирован для deploy-scoped automation;
|
||||||
|
- успешная аутентификация обновляет `platform_api_keys.last_used_at`.
|
||||||
|
|
||||||
## 8. MCP lifecycle
|
## 8. MCP lifecycle
|
||||||
|
|
||||||
Поддерживаемые JSON-RPC методы:
|
Поддерживаемые JSON-RPC методы:
|
||||||
|
|||||||
Reference in New Issue
Block a user