feat: slack agents through a workspace's own slack app (#11912)

* feat: let Slack agents answer through a workspace's own Slack app, with signing secrets set from the UI

The instance Slack app's signing secret can be set in its OAuth setting as well as
SLACK_SIGNING_SECRET, and a workspace's own Slack app takes its own in the workspace
settings. Each secret only vouches for the workspaces connected through its app, so
/windmill keeps working for a workspace whose app has none set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep Slack signing secrets out of logs and verify an own app without a secret with the instance's

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: report a workspace app's own signing secret in the Slack agents status

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: check Slack approval callbacks against the instance signing secret only

An approval can be sent through any Slack resource, so the team's workspace
connections do not tell which app signed its callback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: share the Slack app setup instructions and require the signing secret for agents

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: tidy the Slack signing secret copy and show a set secret as masked

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: check a workspace app only against its own signing secret, and approvals against their workspace's

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: accept a Slack approval signed by the workspace's app or the instance's

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: check Slack's signature on approvals only when sent through the workspace's Slack connection

Any other Slack resource may belong to any Slack app, so its callbacks rest
on the payload HMAC alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: address review findings on Slack signature checks and the signing secret field

- reject Slack signatures older than five minutes, so a captured request cannot be replayed
- let a reachable workspace's command script take a message before another workspace's help reply
- remove a saved workspace signing secret from its field: the button reads Remove when it is empty
- set the signing secret on connect only when one was entered
- tell non-admins who can set the signing secret

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep SLACK_SIGNING_SECRET for workspace apps without a secret, and route a verified request only to its workspaces

- a workspace on its own app with no secret of its own is checked against SLACK_SIGNING_SECRET,
  which may hold that app's secret from before workspaces had one; the instance setting's secret
  still never applies to it
- once a secret verifies a request, only the workspaces it verified take it, command scripts
  included: it proves which app sent the request
- compute the replay window with abs_diff, which cannot overflow

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: update ee-repo-ref to c8d562aa9d75a7e99bf0ecd1ac224f532452a07e

This commit updates the EE repository reference after PR #907 was merged in windmill-ee-private.

Previous ee-repo-ref: 0864b0ab943defa8b8d55838ef09ab7dacfac17f

New ee-repo-ref: c8d562aa9d75a7e99bf0ecd1ac224f532452a07e

Automated by sync-ee-ref workflow.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
This commit is contained in:
hugocasa
2026-10-22 13:51:09 +02:00
committed by GitHub
co-authored by Claude Opus 5.5 windmill-internal-app[bot]
parent 9202a74071
commit 34de8bc06d
30 changed files with 740 additions and 189 deletions
-6
View File
@@ -9,8 +9,6 @@
use crate::db::ApiAuthed;
#[cfg(feature = "embedding")]
use crate::embeddings::load_embeddings_db;
#[cfg(feature = "oauth2")]
use crate::oauth2_oss::SlackVerifier;
#[cfg(feature = "smtp")]
use crate::smtp_server_oss::SmtpServer;
use axum::middleware::from_fn_with_state;
@@ -250,10 +248,6 @@ pub use windmill_oauth::OAUTH_CLIENTS;
#[cfg(feature = "oauth2")]
lazy_static::lazy_static! {
pub static ref SLACK_SIGNING_SECRET: Option<SlackVerifier> = std::env::var("SLACK_SIGNING_SECRET")
.ok()
.map(|x| SlackVerifier::new(x).unwrap());
// Comma-separated Slack v2 OAuth bot scopes requested when connecting a workspace.
// Must be a subset of the bot scopes declared in the Slack app manifest. Default matches
// Windmill's recommended manifest at docs.windmill.dev/docs/misc/setup_oauth.
+1
View File
@@ -82,6 +82,7 @@ pub async fn build_oauth_clients(
logins: HashMap::default(),
connects: HashMap::default(),
slack: None,
slack_signing_secret: None,
});
}
+216 -31
View File
@@ -62,19 +62,190 @@ struct SlackAgentsStatus {
signing_secret_set: bool,
}
async fn status(_authed: ApiAuthed) -> Json<SlackAgentsStatus> {
Json(SlackAgentsStatus { signing_secret_set: signing_secret_set() })
async fn status(
_authed: ApiAuthed,
Extension(db): Extension<DB>,
Path(w_id): Path<String>,
) -> JsonResult<SlackAgentsStatus> {
Ok(Json(SlackAgentsStatus {
signing_secret_set: signing_secret_set(&db, &w_id).await?,
}))
}
/// Agents answer only when the server verifies Slack's request signatures.
fn signing_secret_set() -> bool {
/// Which of the workspaces connected to a Slack team a request may reach.
#[derive(Clone, Debug, Default)]
pub struct SlackRequest {
/// Those whose app's signing secret verified it or, when none did, those whose app has none
/// set, which take requests unauthenticated.
pub reachable: Vec<String>,
/// Those whose app's signing secret verified it, the only ones agents answer for.
pub verified: Vec<String>,
}
fn env_signing_secret() -> Option<String> {
std::env::var("SLACK_SIGNING_SECRET")
.ok()
.filter(|s| !s.is_empty())
}
fn instance_signing_secrets() -> Vec<String> {
#[cfg(feature = "oauth2")]
{
crate::SLACK_SIGNING_SECRET.is_some()
env_signing_secret()
.into_iter()
.chain(crate::OAUTH_CLIENTS.load().slack_signing_secret.clone())
.filter(|s| !s.is_empty())
.collect()
}
#[cfg(not(feature = "oauth2"))]
{
false
vec![]
}
}
/// Agents answer only when the server verifies Slack's request signatures, with the secret of the
/// app the workspace is connected through: its own app's, or else the instance's.
async fn signing_secret_set(db: &DB, w_id: &str) -> Result<bool> {
let own_app = sqlx::query!(
"SELECT slack_oauth_client_id IS NOT NULL AS \"own_app!\",
slack_signing_secret IS NOT NULL AS \"own_secret!\"
FROM workspace_settings WHERE workspace_id = $1",
w_id
)
.fetch_optional(db)
.await?;
Ok(match own_app {
Some(r) if r.own_app => r.own_secret || env_signing_secret().is_some(),
_ => !instance_signing_secrets().is_empty(),
})
}
/// Whether a Slack request was signed by the app a workspace is connected through: `None` when that
/// app has no secret set, which leaves the request unauthenticated. A workspace's own app is checked
/// against its own secret, never the instance setting's: the instance's app signs nothing for it, so
/// setting an instance secret must not start rejecting its requests. Without its own secret it falls
/// back to `SLACK_SIGNING_SECRET`, which may hold that app's secret from before workspaces had one.
#[cfg(feature = "oauth2")]
fn workspace_verified(
own_app: bool,
own_secret: Option<String>,
instance_verified: Option<bool>,
matches: impl Fn(&str) -> bool,
) -> Option<bool> {
if own_app {
own_secret.or_else(env_signing_secret).map(|s| matches(&s))
} else {
instance_verified
}
}
#[cfg(feature = "oauth2")]
fn slack_signature_matcher<'a>(
sig: &'a str,
ts: &'a str,
body: &'a str,
) -> impl Fn(&str) -> bool + 'a {
// Slack's recommended replay window: a captured request stops verifying after it.
let fresh = ts
.parse::<i64>()
.is_ok_and(|t| chrono::Utc::now().timestamp().abs_diff(t) <= 5 * 60);
move |secret: &str| {
fresh
&& windmill_oauth::SlackVerifier::new(secret)
.is_ok_and(|v| v.verify(ts, body, sig).is_ok())
}
}
#[cfg(feature = "oauth2")]
fn instance_verified(matches: &impl Fn(&str) -> bool) -> Option<bool> {
let instance = instance_signing_secrets();
(!instance.is_empty()).then(|| instance.iter().any(|s| matches(s)))
}
#[cfg(feature = "oauth2")]
fn signature_rejected<T>() -> Result<T> {
Err(Error::BadRequest(
"Slack signature verification failed".to_string(),
))
}
/// Checks a Slack request, for each workspace connected to `team_id`, against the signing secret
/// of the app it is connected through (see [`workspace_verified`]). For a team no workspace is
/// connected to, only the instance's secret applies. An error when the request can reach no
/// workspace.
#[cfg(feature = "oauth2")]
pub async fn verify_slack_request(
db: &DB,
team_id: &str,
sig: &str,
ts: &str,
body: &str,
) -> Result<SlackRequest> {
let matches = slack_signature_matcher(sig, ts, body);
let instance_verified = instance_verified(&matches);
let workspaces = sqlx::query!(
"SELECT workspace_id, slack_oauth_client_id IS NOT NULL AS \"own_app!\",
slack_signing_secret
FROM workspace_settings WHERE slack_team_id = $1",
team_id
)
.fetch_all(db)
.await?;
if workspaces.is_empty() {
return match instance_verified {
Some(false) => signature_rejected(),
_ => Ok(SlackRequest::default()),
};
}
let mut req = SlackRequest::default();
for w in workspaces {
let verified = workspace_verified(
w.own_app,
w.slack_signing_secret,
instance_verified,
&matches,
);
if verified != Some(false) {
req.reachable.push(w.workspace_id.clone());
}
if verified == Some(true) {
req.verified.push(w.workspace_id);
}
}
if req.reachable.is_empty() {
return signature_rejected();
}
// A matching secret proves which app sent the request, so a workspace that merely has no secret
// to rule it out must not take it.
if !req.verified.is_empty() {
req.reachable = req.verified.clone();
}
Ok(req)
}
/// Checks a Slack approval callback sent through `w_id`'s Slack connection against the secret of
/// the app it is connected through (see [`workspace_verified`]).
#[cfg(feature = "oauth2")]
pub async fn verify_approval_slack_request(
db: &DB,
w_id: &str,
sig: &str,
ts: &str,
body: &str,
) -> Result<()> {
let matches = slack_signature_matcher(sig, ts, body);
let (own_app, own_secret) = sqlx::query!(
"SELECT slack_oauth_client_id IS NOT NULL AS \"own_app!\", slack_signing_secret
FROM workspace_settings WHERE workspace_id = $1",
w_id
)
.fetch_optional(db)
.await?
.map_or((false, None), |s| (s.own_app, s.slack_signing_secret));
match workspace_verified(own_app, own_secret, instance_verified(&matches), &matches) {
Some(false) => signature_rejected(),
_ => Ok(()),
}
}
@@ -199,7 +370,7 @@ async fn get_agent_slack(
};
Ok(Json(AgentSlack {
slack_team_name,
signing_secret_set: signing_secret_set(),
signing_secret_set: signing_secret_set(&db, &w_id).await?,
bot_name,
missing_scopes: missing_scopes.unwrap_or_default(),
runs_as,
@@ -454,9 +625,9 @@ pub struct SlackMessage {
pub text: String,
pub ts: String,
pub thread_ts: Option<String>,
/// Whether this request's Slack signature was verified. Carried from the check rather than
/// re-read from the setting, which can be enabled between the two.
pub signed: bool,
/// The workspaces whose Slack app's signing secret verified this request. Carried from the
/// check rather than re-read from the settings, which can change between the two.
pub verified: Vec<String>,
}
enum Route {
@@ -477,7 +648,7 @@ struct SharedHere {
/// `false` leaves the message to the workspace's command script.
pub async fn try_answer(db: &DB, msg: SlackMessage) -> Result<bool> {
// Without it the Slack endpoints take unsigned requests, and anyone could post as a channel.
if !msg.signed {
if msg.verified.is_empty() {
return Ok(false);
}
let text = decode_entities(&msg.text);
@@ -490,9 +661,12 @@ pub async fn try_answer(db: &DB, msg: SlackMessage) -> Result<bool> {
"SELECT c.workspace_id, c.agent_path, c.is_default FROM slack_agent_channel c
JOIN workspace_settings ws ON ws.workspace_id = c.workspace_id
AND ws.slack_team_id = c.slack_team_id
WHERE c.slack_team_id = $1 AND c.channel_id = $2 ORDER BY c.agent_path",
WHERE c.slack_team_id = $1 AND c.channel_id = $2
AND ws.workspace_id = ANY($3)
ORDER BY c.agent_path",
msg.team_id,
msg.channel_id
msg.channel_id,
&msg.verified
)
.fetch_all(db)
.await?;
@@ -543,20 +717,22 @@ pub async fn try_answer(db: &DB, msg: SlackMessage) -> Result<bool> {
"channel_default"
},
),
None => match workspace_without_command_script(db, &msg.team_id).await? {
Some(w_id) => {
return start_answer(
db,
w_id,
Route::Help { note: None },
"help",
question,
msg,
)
.await;
None => {
match workspace_without_command_script(db, &msg.team_id, &msg.verified).await? {
Some(w_id) => {
return start_answer(
db,
w_id,
Route::Help { note: None },
"help",
question,
msg,
)
.await;
}
None => return Ok(false),
}
None => return Ok(false),
},
}
},
};
let w_id = here.workspace_id.clone();
@@ -671,12 +847,18 @@ fn decode_entities(text: &str) -> String {
/// The team's workspace when no workspace of the team has a command script to take the message:
/// the only one connected to it.
async fn workspace_without_command_script(db: &DB, team_id: &str) -> Result<Option<String>> {
async fn workspace_without_command_script(
db: &DB,
team_id: &str,
verified: &[String],
) -> Result<Option<String>> {
let rows = sqlx::query!(
"SELECT workspace_id, slack_command_script IS NOT NULL AS \"has_script!\"
FROM workspace_settings WHERE slack_team_id = $1
FROM workspace_settings ws WHERE slack_team_id = $1
AND ws.workspace_id = ANY($2)
ORDER BY slack_command_script IS NOT NULL DESC LIMIT 2",
team_id
team_id,
verified
)
.fetch_all(db)
.await?;
@@ -692,9 +874,12 @@ async fn help_text(db: &DB, msg: &SlackMessage, note: Option<String>) -> Result<
"SELECT c.agent_path FROM slack_agent_channel c
JOIN workspace_settings ws ON ws.workspace_id = c.workspace_id
AND ws.slack_team_id = c.slack_team_id
WHERE c.slack_team_id = $1 AND c.channel_id = $2 ORDER BY c.agent_path LIMIT 11",
WHERE c.slack_team_id = $1 AND c.channel_id = $2
AND ws.workspace_id = ANY($3)
ORDER BY c.agent_path LIMIT 11",
msg.team_id,
msg.channel_id
msg.channel_id,
&msg.verified
)
.fetch_all(db)
.await?;
+62 -27
View File
@@ -138,37 +138,70 @@ struct PrivateMetadata {
skin: ApprovalSkin,
}
// Opportunistic transport-level check: when `SLACK_SIGNING_SECRET` is configured we verify
// the Slack request signature (which also defeats replay). It is NOT the primary defense:
// the secret is unset in the default deployment, so authorization of the sensitive actions
// is instead anchored on a per-workspace HMAC over the callback payload itself (see
// `verify_slack_payload`), which holds even when this check is a no-op.
#[cfg(feature = "oauth2")]
fn verify_slack_callback_signature(headers: &HeaderMap, body: &str) -> Result<(), Error> {
if let Some(sv) = crate::SLACK_SIGNING_SECRET.as_ref() {
let sig = headers
.get("X-Slack-Signature")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let ts = headers
.get("X-Slack-Request-Timestamp")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
sv.verify(ts, body, sig)
.map_err(|_| Error::BadRequest("Slack signature verification failed".to_string()))?;
/// Slack's signature over a callback, checked once the workspace it belongs to is known.
#[cfg_attr(not(feature = "oauth2"), allow(dead_code))]
struct SlackCallbackSignature {
sig: String,
ts: String,
body: String,
}
impl SlackCallbackSignature {
fn new(headers: &HeaderMap, body: &str) -> Self {
let header = |name: &str| {
headers
.get(name)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string()
};
Self {
sig: header("X-Slack-Signature"),
ts: header("X-Slack-Request-Timestamp"),
body: body.to_string(),
}
}
Ok(())
}
// Transport-level check, which also defeats replay. It is NOT the primary defense: authorization of
// the sensitive actions is anchored on a per-workspace HMAC over the callback payload itself (see
// `verify_slack_payload`). Only an approval sent through the workspace's Slack connection comes from
// an app whose secret Windmill knows; any other resource may belong to any Slack app, so its
// callbacks are left to the HMAC.
#[cfg(feature = "oauth2")]
async fn verify_slack_callback_signature(
db: &DB,
w_id: &str,
resource_path: &str,
request: &SlackCallbackSignature,
) -> Result<(), Error> {
if resource_path != windmill_common::oauth2::WORKSPACE_SLACK_BOT_TOKEN_PATH {
return Ok(());
}
crate::slack_agents::verify_approval_slack_request(
db,
w_id,
&request.sig,
&request.ts,
&request.body,
)
.await
}
#[cfg(not(feature = "oauth2"))]
fn verify_slack_callback_signature(_headers: &HeaderMap, _body: &str) -> Result<(), Error> {
async fn verify_slack_callback_signature(
_db: &DB,
_w_id: &str,
_resource_path: &str,
_request: &SlackCallbackSignature,
) -> Result<(), Error> {
Ok(())
}
/// HMAC keyed on the per-workspace encryption key (the same trust anchor as resume-URL
/// signatures). Used to authenticate the `/api/slack` callback payload itself so the
/// unauthenticated route cannot be driven into decrypting arbitrary workspace variables,
/// regardless of whether `SLACK_SIGNING_SECRET` is configured.
/// whether or not a Slack signing secret is set.
type SlackPayloadHmac = Hmac<Sha256>;
/// Domain-separation tag prepended to every Slack-payload MAC. The workspace key is also used
@@ -232,8 +265,7 @@ pub async fn slack_app_callback_handler(
headers: HeaderMap,
body: Bytes,
) -> Result<StatusCode, Error> {
let body_str = String::from_utf8_lossy(&body);
verify_slack_callback_signature(&headers, &body_str)?;
let request = SlackCallbackSignature::new(&headers, &String::from_utf8_lossy(&body));
let form_data: SlackFormData = serde_urlencoded::from_bytes(&body)
.map_err(|e| Error::BadRequest(format!("invalid form data: {}", e)))?;
@@ -244,10 +276,10 @@ pub async fn slack_app_callback_handler(
match payload.r#type {
PayloadType::ViewSubmission => {
handle_submission(authed, opt_tokened, db, &payload, "resume").await?
handle_submission(authed, opt_tokened, db, &payload, &request, "resume").await?
}
PayloadType::ViewClosed => {
handle_submission(authed, opt_tokened, db, &payload, "cancel").await?
handle_submission(authed, opt_tokened, db, &payload, &request, "cancel").await?
}
_ => {
if let Some(actions) = &payload.actions {
@@ -274,8 +306,8 @@ pub async fn slack_app_callback_handler(
// payload was minted by `send_slack_message` with an HMAC over
// (w_id, job_id, path) keyed on the workspace key. Without a valid
// signature an unauthenticated caller cannot reach the decryption
// below for an arbitrary variable, even when SLACK_SIGNING_SECRET
// is unset.
// below for an arbitrary variable, even when no Slack signing
// secret is set.
verify_slack_payload(
&db,
w_id,
@@ -283,6 +315,7 @@ pub async fn slack_app_callback_handler(
parsed_value.signature.as_deref(),
)
.await?;
verify_slack_callback_signature(&db, w_id, path, &request).await?;
// Map any lookup/decryption failure to a generic error: the
// raw error echoes the probed `path`/`w_id` back, which would be
@@ -411,6 +444,7 @@ async fn handle_submission(
opt_tokened: OptTokened,
db: DB,
payload: &Payload,
request: &SlackCallbackSignature,
action: &str,
) -> Result<(), Error> {
let view = payload
@@ -455,6 +489,7 @@ async fn handle_submission(
// the resume/cancel and reach the decryption below with a swapped path. Require the
// workspace-keyed HMAC minted when the modal was built.
verify_slack_payload(&db, w_id, &[resource_path.as_bytes()], signature.as_deref()).await?;
verify_slack_callback_signature(&db, w_id, &resource_path, request).await?;
// Use the common handler to process the resume/cancel action
handle_resume_action(