P4: Slack inbound @mention — broker-verified signatures drive real runs

- Broker op VerifySlackSignature: v0 HMAC-SHA256 computed INSIDE the broker
  (constant-time compare); the signing secret never crosses the socket.
  Slack secrets are one JSON credential {bot_token, signing_secret}; the
  broker extracts the right field per operation
- Public POST /api/slack/events: signature verified against connected slack
  connections via the broker; forged signatures 401; url_verification
  handshake echoed only when signed; app_mention starts a real run in the
  agent's dedicated '💬 Slack' session — and the agent's reply is itself a
  gated outbound post
- SlackApp Connection tab captures bot token + signing secret
- Integration test: forged 401, signed challenge, signed mention -> run ->
  slack.post pending in the approval queue
- E2E: full loop — connect, gated outbound (sink empty -> exactly one post),
  then a node-crypto-signed mention -> approval card -> approve -> 'On it!'
  lands in the sink

134 Rust + 63 frontend tests + 21 Playwright journeys.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Omar Sobh
2026-06-10 06:40:04 -05:00
co-authored by Claude Fable 5
parent 000b9b3a4b
commit 6dbdd20ee0
16 changed files with 548 additions and 2 deletions
+125
View File
@@ -0,0 +1,125 @@
//! Slack inbound events (§7.3: "Agent replies on @mention"). This route is
//! public — authenticity comes from Slack's request signature, which the
//! BROKER verifies against the stored signing secret (it never leaves the
//! broker). A verified @mention starts a real run in the agent's dedicated
//! Slack session; any reply the agent attempts is itself a gated outbound
//! post.
use axum::body::Bytes;
use axum::extract::State;
use axum::http::{HeaderMap, StatusCode};
use axum::Json;
use serde_json::{json, Value};
use tc_domain::AgentId;
use crate::AppState;
const SLACK_SESSION_TITLE: &str = "💬 Slack";
/// Finds the slack connection whose signing secret validates this request.
async fn verified_connection(
state: &AppState,
timestamp: &str,
body: &str,
signature: &str,
) -> Option<tc_db::repo::connections::AppConnection> {
let socket = state.broker_socket.as_ref()?;
let connections = sqlx::query!(
r#"SELECT id, workspace_id, agent_id, provider, auth_type, status, secret_ref
FROM app_connections WHERE provider = 'slack' AND status = 'connected'"#,
)
.fetch_all(&state.pool)
.await
.ok()?;
for row in connections {
let Some(secret_ref) = row.secret_ref else {
continue;
};
let Ok(mut broker) = tc_secrets::BrokerClient::connect(socket).await else {
return None;
};
if broker
.verify_slack_signature(secret_ref, timestamp, body, signature)
.await
.unwrap_or(false)
{
return Some(tc_db::repo::connections::AppConnection {
id: row.id,
workspace_id: row.workspace_id,
agent_id: row.agent_id,
provider: row.provider,
auth_type: row.auth_type,
status: row.status,
secret_ref: row.secret_ref,
});
}
}
None
}
/// POST /api/slack/events
pub async fn events(
State(state): State<AppState>,
headers: HeaderMap,
body: Bytes,
) -> Result<Json<Value>, StatusCode> {
let timestamp = headers
.get("x-slack-request-timestamp")
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
let signature = headers
.get("x-slack-signature")
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
let raw = String::from_utf8_lossy(&body).into_owned();
let connection = verified_connection(&state, timestamp, &raw, signature)
.await
.ok_or(StatusCode::UNAUTHORIZED)?;
let event: Value = serde_json::from_str(&raw).map_err(|_| StatusCode::BAD_REQUEST)?;
// Slack's endpoint handshake.
if event["type"] == "url_verification" {
return Ok(Json(json!({ "challenge": event["challenge"] })));
}
if event["type"] == "event_callback" && event["event"]["type"] == "app_mention" {
let text = event["event"]["text"]
.as_str()
.unwrap_or_default()
.to_owned();
let Some(agent_uuid) = connection.agent_id else {
return Ok(Json(json!({ "ok": true })));
};
let agent_id = AgentId::from(agent_uuid);
let Ok(agent) = tc_db::repo::agents::get(&state.pool, agent_id).await else {
return Ok(Json(json!({ "ok": true })));
};
// One recognizable session per agent for Slack traffic.
let session = match tc_db::repo::sessions::list_by_agent(&state.pool, agent_id)
.await
.ok()
.and_then(|sessions| {
sessions
.into_iter()
.find(|s| s.title == SLACK_SESSION_TITLE)
}) {
Some(existing) => existing,
None => tc_db::repo::sessions::create(
&state.pool,
agent_id,
agent.workspace_id,
SLACK_SESSION_TITLE,
)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
};
// Fire-and-forget: Slack expects a fast 200; the run streams into
// the session (and any outbound reply is gated as usual).
let runtime = state.runtime.clone();
tokio::spawn(async move {
let _ = runtime.send_message(session.id, &text).await;
});
}
Ok(Json(json!({ "ok": true })))
}