feat: add platform key usage to mcp auth

This commit is contained in:
a.tolmachev
2026-03-31 15:48:09 +03:00
parent 84f4437ce0
commit 563e17c3df
11 changed files with 363 additions and 30 deletions
+88 -1
View File
@@ -8,18 +8,21 @@ use axum::{
extract::{Path, State},
http::{
HeaderMap, HeaderValue, StatusCode,
header::{self, ACCEPT},
header::{self, ACCEPT, AUTHORIZATION},
},
response::{IntoResponse, Response},
routing::get,
};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use crank_core::{
InvocationLevel, InvocationLog, InvocationLogId, InvocationSource, InvocationStatus,
PlatformApiKeyScope,
};
use crank_registry::{CreateInvocationLogRequest, PostgresRegistry, PublishedAgentTool};
use crank_runtime::{RuntimeError, RuntimeExecutor, RuntimeOperation};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use crate::{
@@ -106,6 +109,12 @@ async fn mcp_delete(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
) -> 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) {
Ok(Some(session_id)) => match state.sessions.get(&session_id).await {
Some(session)
@@ -149,6 +158,14 @@ async fn mcp_post(
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) {
Some("initialize") if is_request(&message) => {
handle_initialize(state, &path, &message).await
@@ -467,6 +484,71 @@ async fn require_initialized_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(
allowed_origins: &AllowedOrigins,
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(
status: StatusCode,
payload: Value,