Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(bot): support bot authentication scope user and team (#5138)

Will Hutchinsonfceebbdc70fd
diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rs
index 2ebce1c8db..f410a0fbd4 100644
--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs
+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs
@@ -18,10 +18,11 @@ use entity_access::domain::{
};
use macro_authorization::{
BOT_FOR_FUSIONAUTH_USER_ID_HEADER, BOT_FOR_MACRO_USER_ID_HEADER,
- BOT_FOR_ORGANIZATION_ID_HEADER, BOT_TOKEN_HEADER,
+ BOT_FOR_ORGANIZATION_ID_HEADER, BOT_SCOPE_HEADER, BOT_TOKEN_HEADER,
BotActingUserClaims as AuthorizationBotActingUserClaims, BotAuthentication, BotAuthorizer,
- InternalAuthConfig, JwtValidator, MacroAuthorizationError, MacroAuthorizationServiceImpl,
- MacroAuthorizationState, MacroUserAuthentication, ValidatedIdentity,
+ BotScope, InternalAuthConfig, JwtValidator, MacroAuthorizationError,
+ MacroAuthorizationServiceImpl, MacroAuthorizationState, MacroUserAuthentication,
+ ValidatedIdentity,
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use rootcause::Report;
@@ -484,6 +485,7 @@ enum TestBotAuthorizationMode {
#[derive(Debug, Clone, Eq, PartialEq)]
struct BotAuthorizationCall {
token: String,
+ bot_scope: BotScope,
claims: Option<AuthorizationBotActingUserClaims>,
}
@@ -528,6 +530,7 @@ impl BotAuthorizer for TestBotAuthorizer {
async fn authorize_bot(
&self,
bot_token: &str,
+ bot_scope: BotScope,
acting_user: Option<AuthorizationBotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
self.calls
@@ -535,6 +538,7 @@ impl BotAuthorizer for TestBotAuthorizer {
.expect("bot authorization calls mutex poisoned")
.push(BotAuthorizationCall {
token: bot_token.to_string(),
+ bot_scope,
claims: acting_user.clone(),
});
@@ -544,7 +548,9 @@ impl BotAuthorizer for TestBotAuthorizer {
expected_claims,
authentication,
} if bot_token == expected_token && acting_user == *expected_claims => {
- Ok(authentication.as_ref().clone())
+ let mut authentication = authentication.as_ref().clone();
+ authentication.bot_scope = bot_scope;
+ Ok(authentication)
}
TestBotAuthorizationMode::Ok { .. } => {
Err(Report::new(MacroAuthorizationError::InvalidCredentials))
@@ -633,6 +639,8 @@ fn bot_authentication(bot_id: BotId) -> BotAuthentication {
BotAuthentication {
bot_id,
token_id: Uuid::new_v4(),
+ bot_scope: BotScope::User,
+ team_id: None,
acting_user: None,
}
}
@@ -641,6 +649,8 @@ fn bot_authentication_with_acting_user(bot_id: BotId) -> BotAuthentication {
BotAuthentication {
bot_id,
token_id: Uuid::new_v4(),
+ bot_scope: BotScope::User,
+ team_id: None,
acting_user: Some(MacroUserAuthentication {
macro_user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
user_context: Default::default(),
@@ -767,6 +777,7 @@ async fn channel_webhook_router_preferred_token_posts_as_bot() {
let authorizer = TestBotAuthorizer::authorized(token, None, bot_authentication(bot_id));
let request = webhook_request(channel_id)
.header(BOT_TOKEN_HEADER, token)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.body(Body::from(
serde_json::json!({ "content": "hello preferred" }).to_string(),
))
@@ -818,6 +829,7 @@ async fn channel_webhook_router_verified_acting_user_is_not_used_for_attribution
);
let request = webhook_request(channel_id)
.header(BOT_TOKEN_HEADER, token)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.header(
BOT_FOR_MACRO_USER_ID_HEADER,
claims.user_id.as_deref().unwrap(),
@@ -850,6 +862,7 @@ async fn channel_webhook_router_verified_acting_user_is_not_used_for_attribution
.as_slice(),
&[BotAuthorizationCall {
token: token.to_string(),
+ bot_scope: BotScope::User,
claims: Some(claims),
}]
);
@@ -905,6 +918,7 @@ async fn channel_webhook_router_bot_token_and_user_are_ambiguous_without_posting
let authorizer = rejecting_bot_authorizer();
let request = webhook_request(channel_id)
.header(BOT_TOKEN_HEADER, "mbot_test_preferred")
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.header(
header::AUTHORIZATION,
"Bearer macro|[email protected]",
@@ -948,6 +962,7 @@ async fn channel_webhook_router_both_bot_headers_are_ambiguous_before_validation
let authorizer = rejecting_bot_authorizer();
let request = webhook_request(channel_id)
.header(BOT_TOKEN_HEADER, "mbot_test_invalid_preferred")
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.header(CHANNEL_BOT_TOKEN_HEADER, legacy_token)
.body(Body::from(
serde_json::json!({ "content": "ambiguous" }).to_string(),
@@ -986,6 +1001,7 @@ async fn channel_webhook_router_invalid_preferred_token_does_not_fall_back_to_le
let authorizer = rejecting_bot_authorizer();
let request = webhook_request(channel_id)
.header(BOT_TOKEN_HEADER, "mbot_test_invalid_preferred")
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.body(Body::from(
serde_json::json!({ "content": "invalid preferred" }).to_string(),
))
@@ -1020,6 +1036,7 @@ async fn channel_webhook_router_preferred_bot_outside_channel_is_unauthorized()
let authorizer = TestBotAuthorizer::authorized(token, None, bot_authentication(bot_id));
let request = webhook_request(channel_id)
.header(BOT_TOKEN_HEADER, token)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.body(Body::from(
serde_json::json!({ "content": "outside channel" }).to_string(),
))
@@ -1052,6 +1069,7 @@ async fn channel_webhook_router_rejected_acting_user_is_forbidden_without_postin
let authorizer = TestBotAuthorizer::rejecting(MacroAuthorizationError::ActingUserNotAuthorized);
let request = webhook_request(channel_id)
.header(BOT_TOKEN_HEADER, "mbot_test_forbidden_claims")
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.header(BOT_FOR_MACRO_USER_ID_HEADER, "macro|[email protected]")
.body(Body::from(
serde_json::json!({ "content": "forbidden" }).to_string(),
diff --git a/crates/entity_access/src/inbound/axum_extractors/call/test.rs b/crates/entity_access/src/inbound/axum_extractors/call/test.rs
index da1fcf2686..04f9787429 100644
--- a/crates/entity_access/src/inbound/axum_extractors/call/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/call/test.rs
@@ -8,9 +8,9 @@ use axum::{
routing::get,
};
use macro_authorization::{
- BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
- INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
- MacroAuthorizationService, MacroAuthorizationState,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotScope,
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
+ MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -241,13 +241,14 @@ impl MacroAuthorizationService for FakeAuthorizationService {
async fn authorize_bot(
&self,
token: &str,
+ bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
if token != VALID_BOT_TOKEN {
return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
}
- Ok(valid_bot_authentication())
+ Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -391,6 +392,7 @@ fn bot_request(path: String) -> Request<Body> {
Request::builder()
.uri(path)
.header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.body(Body::empty())
.expect("request should be valid")
}
diff --git a/crates/entity_access/src/inbound/axum_extractors/channel/test.rs b/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
index e9d871a4b2..9f6dbdf2c7 100644
--- a/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/channel/test.rs
@@ -8,9 +8,9 @@ use axum::{
routing::get,
};
use macro_authorization::{
- BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
- INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
- MacroAuthorizationService, MacroAuthorizationState,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotScope,
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
+ MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -195,13 +195,14 @@ impl MacroAuthorizationService for FakeAuthorizationService {
async fn authorize_bot(
&self,
token: &str,
+ bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
if token != VALID_BOT_TOKEN {
return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
}
- Ok(valid_bot_authentication())
+ Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -472,6 +473,13 @@ async fn bot_credentials_are_forbidden_without_permission_lookup() {
BOT_TOKEN_HEADER,
VALID_BOT_TOKEN.parse().expect("bot token should be valid"),
);
+ request.headers_mut().insert(
+ BOT_SCOPE_HEADER,
+ BotScope::User
+ .as_str()
+ .parse()
+ .expect("bot scope should be valid"),
+ );
let response = app(state.clone(), member_handler)
.oneshot(request)
.await
diff --git a/crates/entity_access/src/inbound/axum_extractors/chat/test.rs b/crates/entity_access/src/inbound/axum_extractors/chat/test.rs
index bc433bca0a..78221f6be7 100644
--- a/crates/entity_access/src/inbound/axum_extractors/chat/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/chat/test.rs
@@ -7,9 +7,9 @@ use axum::{
response::IntoResponse,
};
use macro_authorization::{
- BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
- INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
- MacroAuthorizationService, MacroAuthorizationState,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotScope,
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
+ MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -193,13 +193,14 @@ impl MacroAuthorizationService for FakeAuthorizationService {
async fn authorize_bot(
&self,
token: &str,
+ bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
if token != VALID_BOT_TOKEN {
return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
}
- Ok(valid_bot_authentication())
+ Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -453,6 +454,13 @@ async fn bot_credentials_are_forbidden_without_acl_lookup() {
BOT_TOKEN_HEADER,
VALID_BOT_TOKEN.parse().expect("bot token should be valid"),
);
+ request.headers_mut().insert(
+ BOT_SCOPE_HEADER,
+ BotScope::User
+ .as_str()
+ .parse()
+ .expect("bot scope should be valid"),
+ );
let error = extract::<ViewAccessLevel>(request, &state)
.await
.expect_err("bot credentials should be forbidden");
diff --git a/crates/entity_access/src/inbound/axum_extractors/document/test.rs b/crates/entity_access/src/inbound/axum_extractors/document/test.rs
index 9045aca0ae..249d228a04 100644
--- a/crates/entity_access/src/inbound/axum_extractors/document/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/document/test.rs
@@ -7,9 +7,9 @@ use axum::{
response::IntoResponse,
};
use macro_authorization::{
- BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
- INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
- MacroAuthorizationService, MacroAuthorizationState,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotScope,
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
+ MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
#[allow(deprecated)]
use macro_authorization::{
@@ -198,13 +198,14 @@ impl MacroAuthorizationService for FakeAuthorizationService {
async fn authorize_bot(
&self,
token: &str,
+ bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
if token != VALID_BOT_TOKEN {
return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
}
- Ok(valid_bot_authentication())
+ Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -509,6 +510,13 @@ async fn bot_credentials_are_forbidden_without_acl_lookup() {
BOT_TOKEN_HEADER,
VALID_BOT_TOKEN.parse().expect("bot token should be valid"),
);
+ request.headers_mut().insert(
+ BOT_SCOPE_HEADER,
+ BotScope::User
+ .as_str()
+ .parse()
+ .expect("bot scope should be valid"),
+ );
let error = extract::<ViewAccessLevel>(request, &state)
.await
.expect_err("bot credentials should be forbidden");
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs b/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs
index b0c7fa0a88..4ae7fe45d6 100644
--- a/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_body/test.rs
@@ -5,7 +5,7 @@ use axum::{
routing::post,
};
use macro_authorization::{
- BOT_TOKEN_HEADER, INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
};
use serde::Deserialize;
use tower::ServiceExt;
@@ -180,6 +180,7 @@ async fn bot_access_is_forbidden_before_body_and_acl_lookup() {
.oneshot(
request("/view")
.header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, "user")
.body(body("document", ENTITY_ID))
.unwrap(),
)
diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs b/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs
index fc77040084..3005aedd45 100644
--- a/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/entity_permission/test.rs
@@ -8,9 +8,10 @@ use axum::{
routing::get,
};
use macro_authorization::{
- BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
- INTERNAL_MACRO_ORGANIZATION_ID_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
- MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotScope,
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_ORGANIZATION_ID_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
+ InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
+ MacroAuthorizationState,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -221,6 +222,7 @@ impl MacroAuthorizationService for FakeAuthorizationService {
async fn authorize_bot(
&self,
token: &str,
+ bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
self.calls
@@ -232,7 +234,7 @@ impl MacroAuthorizationService for FakeAuthorizationService {
return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
}
- Ok(valid_bot_authentication())
+ Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -431,7 +433,9 @@ async fn invalid_and_expired_tokens_preserve_authorization_rejections() {
async fn bot_credentials_are_forbidden_without_permission_lookup() {
let (router, entity_access, authorization) = test_router();
let request = empty_body(
- request(&format!("/entity/document/{ENTITY_ID}")).header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN),
+ request(&format!("/entity/document/{ENTITY_ID}"))
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str()),
);
let (status, body) = send(&router, request).await;
diff --git a/crates/entity_access/src/inbound/axum_extractors/foreign_entity/test.rs b/crates/entity_access/src/inbound/axum_extractors/foreign_entity/test.rs
index 02f342a28b..e682258d7b 100644
--- a/crates/entity_access/src/inbound/axum_extractors/foreign_entity/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/foreign_entity/test.rs
@@ -4,7 +4,7 @@ use axum::{
http::{Request, StatusCode},
routing::get,
};
-use macro_authorization::BOT_TOKEN_HEADER;
+use macro_authorization::{BOT_SCOPE_HEADER, BOT_TOKEN_HEADER};
use tower::ServiceExt;
use super::*;
@@ -35,6 +35,7 @@ async fn bot_credentials_are_forbidden_without_permission_lookup() {
.with_state(state.clone());
let request = Request::get(format!("/foreign/{FOREIGN_ENTITY_ID}"))
.header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, "user")
.body(Body::empty())
.expect("request should be valid");
diff --git a/crates/entity_access/src/inbound/axum_extractors/history/test.rs b/crates/entity_access/src/inbound/axum_extractors/history/test.rs
index 0ad3bbbcd8..94afd9569c 100644
--- a/crates/entity_access/src/inbound/axum_extractors/history/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/history/test.rs
@@ -5,7 +5,7 @@ use axum::{
routing::post,
};
use macro_authorization::{
- BOT_TOKEN_HEADER, INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
};
use tower::ServiceExt;
@@ -116,6 +116,7 @@ async fn bot_history_access_is_forbidden_before_acl_lookup() {
.oneshot(
request()
.header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, "user")
.body(Body::empty())
.unwrap(),
)
diff --git a/crates/entity_access/src/inbound/axum_extractors/pin/test.rs b/crates/entity_access/src/inbound/axum_extractors/pin/test.rs
index 31c0be80cb..9beadcb00d 100644
--- a/crates/entity_access/src/inbound/axum_extractors/pin/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/pin/test.rs
@@ -5,7 +5,7 @@ use axum::{
routing::post,
};
use macro_authorization::{
- BOT_TOKEN_HEADER, INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER,
};
use serde::Deserialize;
use tower::ServiceExt;
@@ -159,6 +159,7 @@ async fn bot_pin_access_is_forbidden_before_acl_lookup() {
.oneshot(
request()
.header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, "user")
.body(body())
.unwrap(),
)
diff --git a/crates/entity_access/src/inbound/axum_extractors/project/test.rs b/crates/entity_access/src/inbound/axum_extractors/project/test.rs
index 57adf6e2d8..714ad7a65f 100644
--- a/crates/entity_access/src/inbound/axum_extractors/project/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/project/test.rs
@@ -7,9 +7,9 @@ use axum::{
response::IntoResponse,
};
use macro_authorization::{
- BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
- INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
- MacroAuthorizationService, MacroAuthorizationState,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotScope,
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
+ MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};
use model_user::UserContext;
@@ -189,13 +189,14 @@ impl MacroAuthorizationService for FakeAuthorizationService {
async fn authorize_bot(
&self,
token: &str,
+ bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
if token != VALID_BOT_TOKEN {
return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
}
- Ok(valid_bot_authentication())
+ Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -279,6 +280,7 @@ fn bot_request(body: &str) -> Request<Body> {
Request::post("/")
.header(header::CONTENT_TYPE, "application/json")
.header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.body(Body::from(body.to_string()))
.expect("request should be valid")
}
@@ -383,6 +385,13 @@ async fn bot_project_access_is_forbidden_before_acl_lookup() {
BOT_TOKEN_HEADER,
VALID_BOT_TOKEN.parse().expect("bot token should be valid"),
);
+ request.headers_mut().insert(
+ BOT_SCOPE_HEADER,
+ BotScope::User
+ .as_str()
+ .parse()
+ .expect("bot scope should be valid"),
+ );
let error = extract_project_access::<ViewAccessLevel>(request, &state)
.await
.expect_err("bot credentials should be forbidden");
diff --git a/crates/entity_access/src/inbound/axum_extractors/team/test.rs b/crates/entity_access/src/inbound/axum_extractors/team/test.rs
index 31258d9ea6..eaaa449c25 100644
--- a/crates/entity_access/src/inbound/axum_extractors/team/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/team/test.rs
@@ -12,9 +12,9 @@ use axum::{
#[allow(deprecated)]
use macro_authorization::LEGACY_DSS_INTERNAL_API_KEY_HEADER;
use macro_authorization::{
- BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
- INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
- MacroAuthorizationService, MacroAuthorizationState,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotScope,
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
+ MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -199,13 +199,14 @@ impl MacroAuthorizationService for FakeAuthorizationService {
async fn authorize_bot(
&self,
token: &str,
+ bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
if token != VALID_BOT_TOKEN {
return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
}
- Ok(valid_bot_authentication())
+ Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -387,6 +388,7 @@ async fn team_extractors_forbid_bots_without_membership_lookup() {
let optional_error = extract_v2(
Request::builder()
.header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.body(Body::empty())
.expect("request should be valid"),
&optional_state,
@@ -406,6 +408,7 @@ async fn team_extractors_forbid_bots_without_membership_lookup() {
let required_error = extract_required_v2(
Request::builder()
.header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.body(Body::empty())
.expect("request should be valid"),
&required_state,
diff --git a/crates/entity_access/src/inbound/axum_extractors/test_support.rs b/crates/entity_access/src/inbound/axum_extractors/test_support.rs
index 81577948a9..1ffd93fedb 100644
--- a/crates/entity_access/src/inbound/axum_extractors/test_support.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/test_support.rs
@@ -2,8 +2,8 @@ use std::sync::{Arc, Mutex};
use axum::extract::FromRef;
use macro_authorization::{
- BotActingUserClaims, BotAuthentication, InternalIdentityClaims, MacroAuthorizationError,
- MacroAuthorizationService, MacroAuthorizationState,
+ BotActingUserClaims, BotAuthentication, BotScope, InternalIdentityClaims,
+ MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{
lowercased::Lowercase,
@@ -173,13 +173,14 @@ impl MacroAuthorizationService for FakeAuthorizationService {
async fn authorize_bot(
&self,
token: &str,
+ bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
if token != VALID_BOT_TOKEN {
return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
}
- Ok(valid_bot_authentication())
+ Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -195,10 +196,12 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
}
-pub(super) fn valid_bot_authentication() -> BotAuthentication {
+pub(super) fn valid_bot_authentication(bot_scope: BotScope) -> BotAuthentication {
BotAuthentication {
bot_id: BotId::new_from_uuid(Uuid::from_u128(1)),
token_id: Uuid::from_u128(2),
+ bot_scope,
+ team_id: (bot_scope == BotScope::Team).then_some(Uuid::from_u128(3)),
acting_user: None,
}
}
diff --git a/crates/entity_access/src/inbound/axum_extractors/thread/test.rs b/crates/entity_access/src/inbound/axum_extractors/thread/test.rs
index 326990f90a..23a71b6306 100644
--- a/crates/entity_access/src/inbound/axum_extractors/thread/test.rs
+++ b/crates/entity_access/src/inbound/axum_extractors/thread/test.rs
@@ -8,9 +8,9 @@ use axum::{
routing::get,
};
use macro_authorization::{
- BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, INTERNAL_API_KEY_HEADER,
- INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims, MacroAuthorizationError,
- MacroAuthorizationService, MacroAuthorizationState,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotScope,
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,
+ MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
use model_user::UserContext;
use rootcause::Report;
@@ -59,13 +59,14 @@ impl MacroAuthorizationService for FakeAuthorizationService {
async fn authorize_bot(
&self,
token: &str,
+ bot_scope: BotScope,
_claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
if token != VALID_BOT_TOKEN {
return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
}
- Ok(valid_bot_authentication())
+ Ok(valid_bot_authentication(bot_scope))
}
async fn authorize_internal(
@@ -315,6 +316,7 @@ async fn bot_thread_access_is_forbidden_before_acl_lookup() {
.oneshot(
request()
.header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.body(Body::empty())
.unwrap(),
)
diff --git a/crates/graphql_common/src/authorization/test.rs b/crates/graphql_common/src/authorization/test.rs
index ddaa8326b2..16294ee0e9 100644
--- a/crates/graphql_common/src/authorization/test.rs
+++ b/crates/graphql_common/src/authorization/test.rs
@@ -9,8 +9,9 @@ use axum::{
http::{Request as HttpRequest, header},
};
use macro_authorization::{
- BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, InternalIdentityClaims,
- MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotScope,
+ InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
+ MacroAuthorizationState,
};
use model_user::UserContext;
use rootcause::Report;
@@ -51,6 +52,7 @@ impl MacroAuthorizationService for FakeAuthorizationService {
async fn authorize_bot(
&self,
token: &str,
+ bot_scope: BotScope,
_acting_user: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
self.authorization_calls.fetch_add(1, Ordering::SeqCst);
@@ -64,6 +66,8 @@ impl MacroAuthorizationService for FakeAuthorizationService {
.parse()
.expect("valid bot ID"),
token_id: uuid::Uuid::from_u128(2),
+ bot_scope,
+ team_id: (bot_scope == BotScope::Team).then_some(uuid::Uuid::from_u128(3)),
acting_user: None,
})
}
@@ -127,6 +131,7 @@ async fn execute(
.unwrap(),
RequestCredentials::Bot(token) => HttpRequest::builder()
.header(BOT_TOKEN_HEADER, token)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.body(())
.unwrap(),
};
diff --git a/crates/macro_authorization/src/domain/bot_authorizer.rs b/crates/macro_authorization/src/domain/bot_authorizer.rs
index 46c2670867..aac18eb012 100644
--- a/crates/macro_authorization/src/domain/bot_authorizer.rs
+++ b/crates/macro_authorization/src/domain/bot_authorizer.rs
@@ -9,8 +9,9 @@ use rootcause::Report;
use super::{
models::{
- BotActingUserClaims, BotAuthentication, BotAuthorizationOwner, BotTokenAuthorization,
- MacroAuthorizationError, MacroUserAuthentication, ResolvedBotActingUser,
+ BotActingUserClaims, BotAuthentication, BotAuthorizationOwner, BotScope,
+ BotTokenAuthorization, MacroAuthorizationError, MacroUserAuthentication,
+ ResolvedBotActingUser,
},
ports::{BotAuthorizationRepo, BotAuthorizer},
};
@@ -109,6 +110,7 @@ where
async fn authorize_bot(
&self,
bot_token: &str,
+ bot_scope: BotScope,
acting_user: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
let token = self
@@ -123,6 +125,14 @@ where
.await
.map_err(|error| repository_error(error, "mark bot token used"))?;
+ let team_id = match &token.owner {
+ BotAuthorizationOwner::Team { team_id } => Some(*team_id),
+ BotAuthorizationOwner::User { .. } | BotAuthorizationOwner::System => None,
+ };
+ if bot_scope == BotScope::Team && team_id.is_none() {
+ return Err(Report::new(MacroAuthorizationError::BotScopeNotAuthorized));
+ }
+
let acting_user = match acting_user {
Some(claims) => Some(user_authentication(
self.resolve_acting_user(&token, &claims).await?,
@@ -133,6 +143,8 @@ where
Ok(BotAuthentication {
bot_id: token.bot_id,
token_id: token.token_id,
+ bot_scope,
+ team_id,
acting_user,
})
}
diff --git a/crates/macro_authorization/src/domain/bot_authorizer/test.rs b/crates/macro_authorization/src/domain/bot_authorizer/test.rs
index d126fbb338..1dba87f487 100644
--- a/crates/macro_authorization/src/domain/bot_authorizer/test.rs
+++ b/crates/macro_authorization/src/domain/bot_authorizer/test.rs
@@ -139,13 +139,15 @@ fn assert_error(
async fn authorizes_bare_bot_and_marks_the_valid_token_used() {
let repo = FakeRepo::owned_by_user();
let authentication = BotAuthorizerService::new(repo.clone())
- .authorize_bot(RAW_TOKEN, None)
+ .authorize_bot(RAW_TOKEN, BotScope::User, None)
.await
.unwrap();
let token = repo.token.as_ref().unwrap();
assert_eq!(authentication.bot_id, token.bot_id);
assert_eq!(authentication.token_id, token.token_id);
+ assert_eq!(authentication.bot_scope, BotScope::User);
+ assert_eq!(authentication.team_id, None);
assert!(authentication.acting_user.is_none());
let calls = repo.calls.lock().unwrap();
@@ -158,10 +160,12 @@ async fn authorizes_bare_bot_and_marks_the_valid_token_used() {
async fn authorizes_exact_user_owner_with_consistent_claims() {
let repo = FakeRepo::owned_by_user();
let authentication = BotAuthorizerService::new(repo.clone())
- .authorize_bot(RAW_TOKEN, Some(claims()))
+ .authorize_bot(RAW_TOKEN, BotScope::User, Some(claims()))
.await
.unwrap();
+ assert_eq!(authentication.bot_scope, BotScope::User);
+ assert_eq!(authentication.team_id, None);
let acting_user = authentication.acting_user.unwrap();
assert_eq!(acting_user.macro_user_id.as_ref(), OWNER_ID);
assert_eq!(acting_user.user_context.user_id, OWNER_ID);
@@ -174,6 +178,46 @@ async fn authorizes_exact_user_owner_with_consistent_claims() {
assert_eq!(repo.calls.lock().unwrap().acting_user_claims, [claims()]);
}
+#[tokio::test]
+async fn rejects_team_scope_for_user_and_system_bots() {
+ for owner in [
+ BotAuthorizationOwner::User {
+ user_id: OWNER_ID.to_string(),
+ },
+ BotAuthorizationOwner::System,
+ ] {
+ let mut repo = FakeRepo::owned_by_user();
+ repo.token.as_mut().unwrap().owner = owner;
+ let token_id = repo.token.as_ref().unwrap().token_id;
+
+ let result = BotAuthorizerService::new(repo.clone())
+ .authorize_bot(RAW_TOKEN, BotScope::Team, None)
+ .await;
+
+ assert_error(result, MacroAuthorizationError::BotScopeNotAuthorized);
+ let calls = repo.calls.lock().unwrap();
+ assert_eq!(calls.marked_token_ids, [token_id]);
+ assert!(calls.acting_user_claims.is_empty());
+ assert!(calls.team_lookups.is_empty());
+ }
+}
+
+#[tokio::test]
+async fn user_scope_preserves_the_owning_team_id() {
+ let team_id = Uuid::from_u128(3);
+ let mut repo = FakeRepo::owned_by_user();
+ repo.token.as_mut().unwrap().owner = BotAuthorizationOwner::Team { team_id };
+
+ let authentication = BotAuthorizerService::new(repo.clone())
+ .authorize_bot(RAW_TOKEN, BotScope::User, None)
+ .await
+ .unwrap();
+
+ assert_eq!(authentication.bot_scope, BotScope::User);
+ assert_eq!(authentication.team_id, Some(team_id));
+ assert!(repo.calls.lock().unwrap().team_lookups.is_empty());
+}
+
#[tokio::test]
async fn authorizes_current_team_member_and_rejects_non_member() {
let team_id = Uuid::from_u128(3);
@@ -189,13 +233,15 @@ async fn authorizes_current_team_member_and_rejects_non_member() {
repo.user_has_team = has_team;
let result = BotAuthorizerService::new(repo.clone())
- .authorize_bot(RAW_TOKEN, Some(claims()))
+ .authorize_bot(RAW_TOKEN, BotScope::Team, Some(claims()))
.await;
if let Some(expected) = expected {
assert_error(result, expected);
} else {
- result.unwrap();
+ let authentication = result.unwrap();
+ assert_eq!(authentication.bot_scope, BotScope::Team);
+ assert_eq!(authentication.team_id, Some(team_id));
}
assert_eq!(
repo.calls.lock().unwrap().team_lookups,
@@ -210,7 +256,7 @@ async fn rejects_system_bot_claims_before_user_lookups() {
repo.token.as_mut().unwrap().owner = BotAuthorizationOwner::System;
let result = BotAuthorizerService::new(repo.clone())
- .authorize_bot(RAW_TOKEN, Some(claims()))
+ .authorize_bot(RAW_TOKEN, BotScope::User, Some(claims()))
.await;
assert_error(result, MacroAuthorizationError::ActingUserNotAuthorized);
@@ -242,7 +288,7 @@ async fn rejects_missing_malformed_or_inconsistent_acting_user_claims() {
for claims in invalid_claims {
let result = BotAuthorizerService::new(FakeRepo::owned_by_user())
- .authorize_bot(RAW_TOKEN, Some(claims))
+ .authorize_bot(RAW_TOKEN, BotScope::User, Some(claims))
.await;
assert_error(result, MacroAuthorizationError::ActingUserNotAuthorized);
}
@@ -254,7 +300,7 @@ async fn rejects_unknown_token_without_marking_or_policy_lookups() {
repo.token = None;
let result = BotAuthorizerService::new(repo.clone())
- .authorize_bot(RAW_TOKEN, Some(claims()))
+ .authorize_bot(RAW_TOKEN, BotScope::User, Some(claims()))
.await;
assert_error(result, MacroAuthorizationError::InvalidCredentials);
@@ -271,7 +317,7 @@ async fn maps_repository_failures_to_unavailable() {
Failure::FindActingUser,
] {
let result = BotAuthorizerService::new(FakeRepo::owned_by_user().fail_at(failure))
- .authorize_bot(RAW_TOKEN, Some(claims()))
+ .authorize_bot(RAW_TOKEN, BotScope::User, Some(claims()))
.await;
assert_error(result, MacroAuthorizationError::Unavailable);
}
@@ -280,7 +326,7 @@ async fn maps_repository_failures_to_unavailable() {
let mut repo = FakeRepo::owned_by_user().fail_at(Failure::UserHasTeam);
repo.token.as_mut().unwrap().owner = BotAuthorizationOwner::Team { team_id };
let result = BotAuthorizerService::new(repo)
- .authorize_bot(RAW_TOKEN, Some(claims()))
+ .authorize_bot(RAW_TOKEN, BotScope::User, Some(claims()))
.await;
assert_error(result, MacroAuthorizationError::Unavailable);
}
diff --git a/crates/macro_authorization/src/domain/models.rs b/crates/macro_authorization/src/domain/models.rs
index 0c0353ed70..4041820833 100644
--- a/crates/macro_authorization/src/domain/models.rs
+++ b/crates/macro_authorization/src/domain/models.rs
@@ -1,7 +1,7 @@
#[cfg(test)]
mod test;
-use std::collections::HashSet;
+use std::{collections::HashSet, fmt};
use bot_id::BotId;
use macro_user_id::user_id::MacroUserIdStr;
@@ -18,6 +18,31 @@ pub struct MacroUserAuthentication {
pub user_context: UserContext,
}
+/// The access scope selected for a bot-authorized request.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum BotScope {
+ /// Authorize access in the bot's user scope.
+ User,
+ /// Authorize access in the bot's team scope.
+ Team,
+}
+
+impl BotScope {
+ /// Return the header representation of this scope.
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::User => "user",
+ Self::Team => "team",
+ }
+ }
+}
+
+impl fmt::Display for BotScope {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str(self.as_str())
+ }
+}
+
/// A bot principal whose token has been validated.
///
/// The raw token is deliberately excluded so it cannot flow into handlers,
@@ -28,6 +53,10 @@ pub struct BotAuthentication {
pub bot_id: BotId,
/// The token row used to authenticate, for audit and telemetry.
pub token_id: Uuid,
+ /// The access scope required by this bot-authorized request.
+ pub bot_scope: BotScope,
+ /// The bot's owning team for team-owned bots, regardless of the requested scope.
+ pub team_id: Option<Uuid>,
/// The verified acting user, when one was requested and authorized.
pub acting_user: Option<MacroUserAuthentication>,
}
@@ -156,7 +185,7 @@ pub struct ValidatedIdentity {
pub permissions: Option<HashSet<String>>,
}
-/// Errors returned when a credential cannot authorize a user.
+/// Errors returned when a credential cannot authorize a caller.
///
/// The variants deliberately omit validation implementation details so callers
/// can handle authorization failures without exposing sensitive information.
@@ -171,6 +200,9 @@ pub enum MacroAuthorizationError {
/// The authenticated bot is not authorized to act for the claimed user.
#[error("acting user not authorized")]
ActingUserNotAuthorized,
+ /// The authenticated bot cannot use the requested access scope.
+ #[error("bot scope not authorized")]
+ BotScopeNotAuthorized,
/// Authorization could not be completed because a required service failed.
#[error("authorization unavailable")]
Unavailable,
diff --git a/crates/macro_authorization/src/domain/models/test.rs b/crates/macro_authorization/src/domain/models/test.rs
index 574debd156..f6651db41d 100644
--- a/crates/macro_authorization/src/domain/models/test.rs
+++ b/crates/macro_authorization/src/domain/models/test.rs
@@ -4,12 +4,13 @@ use model_user::UserContext;
use uuid::Uuid;
use super::{
- BotActingUserClaims, BotAuthentication, MacroAuthorization, MacroAuthorizationError,
+ BotActingUserClaims, BotAuthentication, BotScope, MacroAuthorization, MacroAuthorizationError,
MacroUserAuthentication,
};
const BOT_ID: BotId = BotId::new_from_uuid(Uuid::from_u128(1));
const TOKEN_ID: Uuid = Uuid::from_u128(2);
+const TEAM_ID: Uuid = Uuid::from_u128(3);
fn user_authentication() -> MacroUserAuthentication {
MacroUserAuthentication {
@@ -54,6 +55,8 @@ fn bot_authorization_exposes_the_bot_and_verified_acting_user() {
let authorization = MacroAuthorization::Bot(BotAuthentication {
bot_id: BOT_ID,
token_id: TOKEN_ID,
+ bot_scope: BotScope::Team,
+ team_id: Some(TEAM_ID),
acting_user: Some(user_authentication()),
});
@@ -67,6 +70,8 @@ fn bot_authorization_exposes_the_bot_and_verified_acting_user() {
let bot = authorization.bot().expect("expected bot authorization");
assert_eq!(bot.bot_id, BOT_ID);
assert_eq!(bot.token_id, TOKEN_ID);
+ assert_eq!(bot.bot_scope, BotScope::Team);
+ assert_eq!(bot.team_id, Some(TEAM_ID));
assert_acting_user(
bot.acting_user
.as_ref()
@@ -76,10 +81,14 @@ fn bot_authorization_exposes_the_bot_and_verified_acting_user() {
let BotAuthentication {
bot_id,
token_id,
+ bot_scope,
+ team_id,
acting_user,
} = bot.clone();
assert_eq!(bot_id, BOT_ID);
assert_eq!(token_id, TOKEN_ID);
+ assert_eq!(bot_scope, BotScope::Team);
+ assert_eq!(team_id, Some(TEAM_ID));
assert!(acting_user.is_some());
}
@@ -88,6 +97,8 @@ fn bare_bot_authorization_has_no_acting_user() {
let authorization = MacroAuthorization::Bot(BotAuthentication {
bot_id: BOT_ID,
token_id: TOKEN_ID,
+ bot_scope: BotScope::User,
+ team_id: None,
acting_user: None,
});
@@ -136,6 +147,14 @@ fn bot_acting_user_claims_carry_unverified_values() {
assert_eq!(claims.organization_id, Some(7));
}
+#[test]
+fn bot_scopes_have_stable_header_values() {
+ assert_eq!(BotScope::User.as_str(), "user");
+ assert_eq!(BotScope::User.to_string(), "user");
+ assert_eq!(BotScope::Team.as_str(), "team");
+ assert_eq!(BotScope::Team.to_string(), "team");
+}
+
#[test]
fn authorization_errors_remain_clone_and_copy() {
fn assert_clone_and_copy<T: Clone + Copy>() {}
@@ -146,6 +165,7 @@ fn authorization_errors_remain_clone_and_copy() {
MacroAuthorizationError::CredentialsExpired,
MacroAuthorizationError::InvalidCredentials,
MacroAuthorizationError::ActingUserNotAuthorized,
+ MacroAuthorizationError::BotScopeNotAuthorized,
MacroAuthorizationError::Unavailable,
];
let copied_errors = errors;
diff --git a/crates/macro_authorization/src/domain/ports.rs b/crates/macro_authorization/src/domain/ports.rs
index d82857fc9f..09f3df33b3 100644
--- a/crates/macro_authorization/src/domain/ports.rs
+++ b/crates/macro_authorization/src/domain/ports.rs
@@ -4,8 +4,8 @@ use model_user::UserContext;
use rootcause::Report;
use super::models::{
- BotActingUserClaims, BotAuthentication, BotTokenAuthorization, InternalIdentityClaims,
- MacroAuthorizationError, ResolvedBotActingUser, ValidatedIdentity,
+ BotActingUserClaims, BotAuthentication, BotScope, BotTokenAuthorization,
+ InternalIdentityClaims, MacroAuthorizationError, ResolvedBotActingUser, ValidatedIdentity,
};
use uuid::Uuid;
@@ -44,6 +44,7 @@ pub trait BotAuthorizer: Clone + Send + Sync + 'static {
fn authorize_bot(
&self,
bot_token: &str,
+ bot_scope: BotScope,
acting_user: Option<BotActingUserClaims>,
) -> impl Future<Output = Result<BotAuthentication, Report<MacroAuthorizationError>>> + Send;
}
@@ -56,6 +57,7 @@ impl BotAuthorizer for NoBotAuthorizer {
async fn authorize_bot(
&self,
_bot_token: &str,
+ _bot_scope: BotScope,
_acting_user: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
Err(Report::new(MacroAuthorizationError::InvalidCredentials))
@@ -89,6 +91,7 @@ pub trait MacroAuthorizationService: Clone + Send + Sync + 'static {
fn authorize_bot(
&self,
_bot_token: &str,
+ _bot_scope: BotScope,
_acting_user: Option<BotActingUserClaims>,
) -> impl Future<Output = Result<BotAuthentication, Report<MacroAuthorizationError>>> + Send
{
diff --git a/crates/macro_authorization/src/domain/service.rs b/crates/macro_authorization/src/domain/service.rs
index 9bc166d991..761f3aac0b 100644
--- a/crates/macro_authorization/src/domain/service.rs
+++ b/crates/macro_authorization/src/domain/service.rs
@@ -9,8 +9,8 @@ use rootcause::Report;
use super::{
models::{
- BotActingUserClaims, BotAuthentication, InternalAuthConfig, InternalIdentityClaims,
- MacroAuthorizationError,
+ BotActingUserClaims, BotAuthentication, BotScope, InternalAuthConfig,
+ InternalIdentityClaims, MacroAuthorizationError,
},
ports::{BotAuthorizer, JwtValidator, MacroAuthorizationService},
};
@@ -25,6 +25,7 @@ trait DynBotAuthorizer: Send + Sync {
fn authorize_bot<'a>(
&'a self,
bot_token: &'a str,
+ bot_scope: BotScope,
acting_user: Option<BotActingUserClaims>,
) -> BotAuthorizationFuture<'a>;
}
@@ -36,9 +37,15 @@ where
fn authorize_bot<'a>(
&'a self,
bot_token: &'a str,
+ bot_scope: BotScope,
acting_user: Option<BotActingUserClaims>,
) -> BotAuthorizationFuture<'a> {
- Box::pin(BotAuthorizer::authorize_bot(self, bot_token, acting_user))
+ Box::pin(BotAuthorizer::authorize_bot(
+ self,
+ bot_token,
+ bot_scope,
+ acting_user,
+ ))
}
}
@@ -86,22 +93,29 @@ where
fields(
bot_id = tracing::field::Empty,
token_id = tracing::field::Empty,
+ bot_scope = tracing::field::Empty,
+ team_id = tracing::field::Empty,
acting_user_id = tracing::field::Empty,
)
)]
async fn authorize_bot(
&self,
bot_token: &str,
+ bot_scope: BotScope,
acting_user: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
let bot = self
.bot_authorizer
- .authorize_bot(bot_token, acting_user)
+ .authorize_bot(bot_token, bot_scope, acting_user)
.await?;
let span = tracing::Span::current();
span.record("bot_id", tracing::field::display(bot.bot_id));
span.record("token_id", tracing::field::display(bot.token_id));
+ span.record("bot_scope", tracing::field::display(bot.bot_scope));
+ if let Some(team_id) = bot.team_id {
+ span.record("team_id", tracing::field::display(team_id));
+ }
if let Some(acting_user) = &bot.acting_user {
span.record(
"acting_user_id",
diff --git a/crates/macro_authorization/src/domain/service/test.rs b/crates/macro_authorization/src/domain/service/test.rs
index 59b2c2923e..ffcf11c4a0 100644
--- a/crates/macro_authorization/src/domain/service/test.rs
+++ b/crates/macro_authorization/src/domain/service/test.rs
@@ -12,8 +12,9 @@ use uuid::Uuid;
use super::MacroAuthorizationServiceImpl;
use crate::domain::{
models::{
- BotActingUserClaims, BotAuthentication, InternalAuthConfig, InternalIdentityClaims,
- MacroAuthorizationError, MacroUserAuthentication, ValidatedIdentity,
+ BotActingUserClaims, BotAuthentication, BotScope, InternalAuthConfig,
+ InternalIdentityClaims, MacroAuthorizationError, MacroUserAuthentication,
+ ValidatedIdentity,
},
ports::{BotAuthorizer, JwtValidator, MacroAuthorizationService, NoBotAuthorizer},
};
@@ -32,6 +33,7 @@ impl JwtValidator for FakeJwtValidator {
#[derive(Clone, Debug, Eq, PartialEq)]
struct BotAuthorizationCall {
bot_token: String,
+ bot_scope: BotScope,
acting_user: Option<BotActingUserClaims>,
}
@@ -58,6 +60,7 @@ impl BotAuthorizer for FakeBotAuthorizer {
async fn authorize_bot(
&self,
bot_token: &str,
+ bot_scope: BotScope,
acting_user: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
self.calls
@@ -65,6 +68,7 @@ impl BotAuthorizer for FakeBotAuthorizer {
.expect("calls lock poisoned")
.push(BotAuthorizationCall {
bot_token: bot_token.to_string(),
+ bot_scope,
acting_user,
});
@@ -92,6 +96,7 @@ impl MacroAuthorizationService for DefaultRejectingAuthorizationService {
const INTERNAL_API_KEY: &str = "secret-key";
const BOT_ID: BotId = BotId::new_from_uuid(Uuid::from_u128(1));
const TOKEN_ID: Uuid = Uuid::from_u128(2);
+const TEAM_ID: Uuid = Uuid::from_u128(3);
fn internal_auth_config(default_user_id: Option<&str>) -> InternalAuthConfig {
InternalAuthConfig {
@@ -116,6 +121,8 @@ fn bot_authentication() -> BotAuthentication {
BotAuthentication {
bot_id: BOT_ID,
token_id: TOKEN_ID,
+ bot_scope: BotScope::Team,
+ team_id: Some(TEAM_ID),
acting_user: Some(MacroUserAuthentication {
macro_user_id: MacroUserIdStr::try_from("macro|[email protected]".to_string())
.expect("valid Macro user id"),
@@ -132,6 +139,8 @@ fn bot_authentication() -> BotAuthentication {
fn assert_bot_authentication(bot: &BotAuthentication) {
assert_eq!(bot.bot_id, BOT_ID);
assert_eq!(bot.token_id, TOKEN_ID);
+ assert_eq!(bot.bot_scope, BotScope::Team);
+ assert_eq!(bot.team_id, Some(TEAM_ID));
let acting_user = bot
.acting_user
@@ -155,6 +164,7 @@ async fn no_bot_authorizer_rejects_bot_credentials() {
let error = NoBotAuthorizer
.authorize_bot(
"bot-token",
+ BotScope::User,
Some(BotActingUserClaims {
user_id: Some("macro|[email protected]".to_string()),
fusion_user_id: None,
@@ -173,7 +183,7 @@ async fn no_bot_authorizer_rejects_bot_credentials() {
#[tokio::test]
async fn authorization_service_trait_rejects_bots_by_default() {
let error = DefaultRejectingAuthorizationService
- .authorize_bot("bot-token", None)
+ .authorize_bot("bot-token", BotScope::User, None)
.await
.unwrap_err();
@@ -186,7 +196,7 @@ async fn authorization_service_trait_rejects_bots_by_default() {
#[tokio::test]
async fn authorization_service_impl_rejects_bots_with_explicit_no_bot_authorizer() {
let error = service_with_internal_auth(None)
- .authorize_bot("bot-token", None)
+ .authorize_bot("bot-token", BotScope::User, None)
.await
.unwrap_err();
@@ -213,7 +223,7 @@ async fn authorize_bot_delegates_token_and_exact_acting_user_claims() {
);
let bot = service
- .authorize_bot("bot-token", Some(claims.clone()))
+ .authorize_bot("bot-token", BotScope::Team, Some(claims.clone()))
.await
.unwrap();
@@ -222,6 +232,7 @@ async fn authorize_bot_delegates_token_and_exact_acting_user_claims() {
authorizer.calls(),
vec![BotAuthorizationCall {
bot_token: "bot-token".to_string(),
+ bot_scope: BotScope::Team,
acting_user: Some(claims),
}]
);
@@ -232,6 +243,7 @@ async fn authorize_bot_passes_through_authorizer_errors() {
for expected in [
MacroAuthorizationError::InvalidCredentials,
MacroAuthorizationError::ActingUserNotAuthorized,
+ MacroAuthorizationError::BotScopeNotAuthorized,
MacroAuthorizationError::Unavailable,
] {
let service = MacroAuthorizationServiceImpl::new(
@@ -242,7 +254,10 @@ async fn authorize_bot_passes_through_authorizer_errors() {
FakeBotAuthorizer::new(Err(expected)),
);
- let error = service.authorize_bot("bot-token", None).await.unwrap_err();
+ let error = service
+ .authorize_bot("bot-token", BotScope::User, None)
+ .await
+ .unwrap_err();
assert_eq!(error.current_context(), &expected);
}
diff --git a/crates/macro_authorization/src/inbound.rs b/crates/macro_authorization/src/inbound.rs
index a42c0c01a7..303775d981 100644
--- a/crates/macro_authorization/src/inbound.rs
+++ b/crates/macro_authorization/src/inbound.rs
@@ -7,12 +7,12 @@ pub mod axum;
pub use axum::{
ActingEntity, ActingUser, ActingUserAuthorization, AnyPrincipal, AuthorizationPolicy,
BOT_FOR_FUSIONAUTH_USER_ID_HEADER, BOT_FOR_MACRO_USER_ID_HEADER,
- BOT_FOR_ORGANIZATION_ID_HEADER, BOT_TOKEN_HEADER, BotOnly, INTERNAL_API_KEY_HEADER,
- INTERNAL_FUSIONAUTH_USER_ID_HEADER, INTERNAL_MACRO_ORGANIZATION_ID_HEADER,
- INTERNAL_MACRO_USER_ID_HEADER, InternalAuthorization, InternalEntity, InternalOnly,
- LEGACY_DSS_INTERNAL_API_KEY_HEADER, LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER,
- MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationState,
- OptionalMacroAuthorizationExtractor, UserOnly, UserOrInternal, UserOrInternalAuthorization,
- UserOrInternalCaller, UserOrInternalEntity, UserOrInternalService,
- UserOrInternalServiceAuthorization,
+ BOT_FOR_ORGANIZATION_ID_HEADER, BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotOnly,
+ INTERNAL_API_KEY_HEADER, INTERNAL_FUSIONAUTH_USER_ID_HEADER,
+ INTERNAL_MACRO_ORGANIZATION_ID_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalAuthorization,
+ InternalEntity, InternalOnly, LEGACY_DSS_INTERNAL_API_KEY_HEADER,
+ LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER, MacroAuthorizationExtractor,
+ MacroAuthorizationRejection, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOnly, UserOrInternal, UserOrInternalAuthorization, UserOrInternalCaller,
+ UserOrInternalEntity, UserOrInternalService, UserOrInternalServiceAuthorization,
};
diff --git a/crates/macro_authorization/src/inbound/axum.rs b/crates/macro_authorization/src/inbound/axum.rs
index 2476c75c6a..d129aa2450 100644
--- a/crates/macro_authorization/src/inbound/axum.rs
+++ b/crates/macro_authorization/src/inbound/axum.rs
@@ -24,7 +24,7 @@ use crate::{MacroAuthorization, MacroUserAuthentication};
pub use bot::{
BOT_FOR_FUSIONAUTH_USER_ID_HEADER, BOT_FOR_MACRO_USER_ID_HEADER,
- BOT_FOR_ORGANIZATION_ID_HEADER, BOT_TOKEN_HEADER,
+ BOT_FOR_ORGANIZATION_ID_HEADER, BOT_SCOPE_HEADER, BOT_TOKEN_HEADER,
};
#[allow(deprecated)]
pub use internal::{
diff --git a/crates/macro_authorization/src/inbound/axum/bot.rs b/crates/macro_authorization/src/inbound/axum/bot.rs
index 5b4d133588..aa49dc49ae 100644
--- a/crates/macro_authorization/src/inbound/axum/bot.rs
+++ b/crates/macro_authorization/src/inbound/axum/bot.rs
@@ -5,13 +5,16 @@ use ::axum::{
use rootcause::Report;
use crate::{
- BotActingUserClaims, BotAuthentication, MacroAuthorizationError, MacroAuthorizationService,
+ BotActingUserClaims, BotAuthentication, BotScope, MacroAuthorizationError,
+ MacroAuthorizationService,
};
use super::{MacroAuthorizationRejection, MacroAuthorizationState, rejection, status_rejection};
/// Header carrying a bot authentication token.
pub const BOT_TOKEN_HEADER: &str = "x-macro-bot-token";
+/// Header carrying the access scope for a bot-authorized request.
+pub const BOT_SCOPE_HEADER: &str = "x-macro-bot-scope";
/// Header carrying the Macro user ID a bot claims to act for.
pub const BOT_FOR_MACRO_USER_ID_HEADER: &str = "x-macro-bot-for-macro-user-id";
/// Header carrying the FusionAuth user ID a bot claims to act for.
@@ -30,11 +33,12 @@ where
let Some(token) = bot_token(&parts.headers)? else {
return Ok(None);
};
+ let bot_scope = bot_scope(&parts.headers)?;
let claims = bot_acting_user_claims(&parts.headers)?;
let authorization = MacroAuthorizationState::<Svc>::from_ref(state);
let bot = authorization
.service
- .authorize_bot(&token, claims)
+ .authorize_bot(&token, bot_scope, claims)
.await
.map_err(bot_authorization_rejection)?;
@@ -53,6 +57,20 @@ fn bot_token(headers: &HeaderMap) -> Result<Option<String>, MacroAuthorizationRe
Ok(Some(token.to_owned()))
}
+fn bot_scope(headers: &HeaderMap) -> Result<BotScope, MacroAuthorizationRejection> {
+ let scope = headers
+ .get(BOT_SCOPE_HEADER)
+ .ok_or_else(invalid_bot_scope_rejection)?
+ .to_str()
+ .map_err(|_| invalid_bot_scope_rejection())?;
+
+ match scope {
+ "user" => Ok(BotScope::User),
+ "team" => Ok(BotScope::Team),
+ _ => Err(invalid_bot_scope_rejection()),
+ }
+}
+
fn bot_acting_user_claims(
headers: &HeaderMap,
) -> Result<Option<BotActingUserClaims>, MacroAuthorizationRejection> {
@@ -89,6 +107,10 @@ fn bot_claim_header(
.transpose()
}
+fn invalid_bot_scope_rejection() -> MacroAuthorizationRejection {
+ status_rejection(StatusCode::BAD_REQUEST, "invalid bot scope")
+}
+
fn invalid_bot_claims_rejection() -> MacroAuthorizationRejection {
status_rejection(StatusCode::BAD_REQUEST, "invalid bot claims")
}
@@ -99,7 +121,8 @@ fn bot_authorization_rejection(
let rejection = match error.current_context() {
MacroAuthorizationError::CredentialsExpired
| MacroAuthorizationError::InvalidCredentials => rejection("unauthorized"),
- MacroAuthorizationError::ActingUserNotAuthorized => {
+ MacroAuthorizationError::ActingUserNotAuthorized
+ | MacroAuthorizationError::BotScopeNotAuthorized => {
status_rejection(StatusCode::FORBIDDEN, "forbidden")
}
MacroAuthorizationError::Unavailable => {
diff --git a/crates/macro_authorization/src/inbound/axum/test.rs b/crates/macro_authorization/src/inbound/axum/test.rs
index 3dc5299fb9..0e54da229a 100644
--- a/crates/macro_authorization/src/inbound/axum/test.rs
+++ b/crates/macro_authorization/src/inbound/axum/test.rs
@@ -20,7 +20,7 @@ use uuid::Uuid;
use super::*;
use crate::{
- BotActingUserClaims, BotAuthentication, InternalIdentityClaims, MacroAuthorization,
+ BotActingUserClaims, BotAuthentication, BotScope, InternalIdentityClaims, MacroAuthorization,
MacroAuthorizationError, MacroAuthorizationService, MacroUserAuthentication,
};
@@ -35,6 +35,7 @@ const BOT_ACTING_USER_ID: &str = "macro|[email protected]";
const VALID_INTERNAL_KEY: &str = "valid-internal-key";
const BOT_ID: BotId = BotId::new_from_uuid(Uuid::from_u128(1));
const BOT_TOKEN_ID: Uuid = Uuid::from_u128(2);
+const BOT_TEAM_ID: Uuid = Uuid::from_u128(3);
const ACCESS_TOKEN_COOKIE: &str = "macro-access-token";
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -42,6 +43,7 @@ enum AuthorizationCall {
Jwt(String),
Bot {
token: String,
+ bot_scope: BotScope,
claims: Option<BotActingUserClaims>,
},
Internal {
@@ -85,6 +87,7 @@ impl MacroAuthorizationService for FakeAuthorizationService {
async fn authorize_bot(
&self,
token: &str,
+ bot_scope: BotScope,
claims: Option<BotActingUserClaims>,
) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
self.calls
@@ -92,16 +95,20 @@ impl MacroAuthorizationService for FakeAuthorizationService {
.expect("calls lock poisoned")
.push(AuthorizationCall::Bot {
token: token.to_owned(),
+ bot_scope,
claims: claims.clone(),
});
match token {
- "bot-bare" => Ok(bot_authentication(None)),
- "bot-acting" => Ok(bot_authentication(Some(BOT_ACTING_USER_ID))),
+ "bot-bare" => Ok(bot_authentication(bot_scope, None)),
+ "bot-acting" => Ok(bot_authentication(bot_scope, Some(BOT_ACTING_USER_ID))),
"bot-expired" => Err(Report::new(MacroAuthorizationError::CredentialsExpired)),
"bot-forbidden" => Err(Report::new(
MacroAuthorizationError::ActingUserNotAuthorized,
)),
+ "bot-scope-forbidden" => {
+ Err(Report::new(MacroAuthorizationError::BotScopeNotAuthorized))
+ }
"bot-unavailable" => Err(Report::new(MacroAuthorizationError::Unavailable)),
_ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
}
@@ -146,10 +153,12 @@ fn user_context(user_id: &str, organization_id: Option<i32>) -> UserContext {
}
}
-fn bot_authentication(acting_user_id: Option<&str>) -> BotAuthentication {
+fn bot_authentication(bot_scope: BotScope, acting_user_id: Option<&str>) -> BotAuthentication {
BotAuthentication {
bot_id: BOT_ID,
token_id: BOT_TOKEN_ID,
+ bot_scope,
+ team_id: (bot_scope == BotScope::Team).then_some(BOT_TEAM_ID),
acting_user: acting_user_id.map(|user_id| MacroUserAuthentication {
macro_user_id: MacroUserIdStr::try_from(user_id.to_owned())
.expect("valid bot acting user id"),
@@ -306,6 +315,8 @@ fn bot_json(bot: &BotAuthentication, acting_entity: &str) -> Value {
"acting_entity": acting_entity,
"bot_id": bot.bot_id.to_string(),
"token_id": bot.token_id.to_string(),
+ "bot_scope": bot.bot_scope.as_str(),
+ "team_id": bot.team_id.map(|team_id| team_id.to_string()),
"acting_user_id": bot
.acting_user
.as_ref()
@@ -391,6 +402,12 @@ fn request(path: &str) -> ::axum::http::request::Builder {
Request::get(path)
}
+fn bot_request(path: &str, token: &str) -> ::axum::http::request::Builder {
+ request(path)
+ .header(BOT_TOKEN_HEADER, token)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
+}
+
fn empty_body(request: ::axum::http::request::Builder) -> Request<Body> {
request.body(Body::empty()).unwrap()
}
@@ -460,7 +477,7 @@ async fn extractors_report_the_authenticating_entity() {
Some(VALID_USER_ID.to_string()),
),
(
- empty_body(request("/required/acting-user").header(BOT_TOKEN_HEADER, "bot-acting")),
+ empty_body(bot_request("/required/acting-user", "bot-acting")),
Some(BOT_ID.to_string()),
),
(
@@ -476,7 +493,7 @@ async fn extractors_report_the_authenticating_entity() {
Some(OPTIONAL_USER_ID.to_string()),
),
(
- empty_body(request("/optional/any-principal").header(BOT_TOKEN_HEADER, "bot-bare")),
+ empty_body(bot_request("/optional/any-principal", "bot-bare")),
Some(BOT_ID.to_string()),
),
(
@@ -489,7 +506,7 @@ async fn extractors_report_the_authenticating_entity() {
Some(VALID_USER_ID.to_string()),
),
(
- empty_body(request("/bot").header(BOT_TOKEN_HEADER, "bot-bare")),
+ empty_body(bot_request("/bot", "bot-bare")),
Some(BOT_ID.to_string()),
),
(
@@ -1194,6 +1211,7 @@ async fn malformed_internal_organization_is_ignored() {
#[test]
fn bot_header_constants_use_the_resolved_names() {
assert_eq!(BOT_TOKEN_HEADER, "x-macro-bot-token");
+ assert_eq!(BOT_SCOPE_HEADER, "x-macro-bot-scope");
assert_eq!(
BOT_FOR_MACRO_USER_ID_HEADER,
"x-macro-bot-for-macro-user-id"
@@ -1214,8 +1232,7 @@ async fn acting_user_and_any_principal_accept_bot_with_verified_acting_user() {
for path in ["/required/acting-user", "/optional/any-principal"] {
let request = empty_body(
- request(path)
- .header(BOT_TOKEN_HEADER, "bot-acting")
+ bot_request(path, "bot-acting")
.header(BOT_FOR_MACRO_USER_ID_HEADER, BOT_ACTING_USER_ID)
.header(BOT_FOR_FUSIONAUTH_USER_ID_HEADER, "fusion-claimed")
.header(BOT_FOR_ORGANIZATION_ID_HEADER, "42"),
@@ -1236,10 +1253,12 @@ async fn acting_user_and_any_principal_accept_bot_with_verified_acting_user() {
[
AuthorizationCall::Bot {
token: "bot-acting".to_owned(),
+ bot_scope: BotScope::User,
claims: claims.clone(),
},
AuthorizationCall::Bot {
token: "bot-acting".to_owned(),
+ bot_scope: BotScope::User,
claims,
},
]
@@ -1250,31 +1269,21 @@ async fn acting_user_and_any_principal_accept_bot_with_verified_acting_user() {
async fn bare_bot_is_forbidden_by_no_bot_policies_and_accepted_by_bot_only() {
let (router, service) = test_router();
- let (status, body) = send(
- &router,
- empty_body(request("/required").header(BOT_TOKEN_HEADER, "bot-bare")),
- )
- .await;
+ let (status, body) = send(&router, empty_body(bot_request("/required", "bot-bare"))).await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert_eq!(body, json!({ "message": "forbidden" }));
- let (status, body) = send(
- &router,
- empty_body(request("/optional").header(BOT_TOKEN_HEADER, "bot-bare")),
- )
- .await;
+ let (status, body) = send(&router, empty_body(bot_request("/optional", "bot-bare"))).await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert_eq!(body, json!({ "message": "forbidden" }));
for path in ["/bot", "/optional-bot"] {
- let (status, body) = send(
- &router,
- empty_body(request(path).header(BOT_TOKEN_HEADER, "bot-bare")),
- )
- .await;
+ let (status, body) = send(&router, empty_body(bot_request(path, "bot-bare"))).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["bot_id"], BOT_ID.to_string());
assert_eq!(body["token_id"], BOT_TOKEN_ID.to_string());
+ assert_eq!(body["bot_scope"], BotScope::User.as_str());
+ assert_eq!(body["team_id"], Value::Null);
assert_eq!(body["acting_user_id"], Value::Null);
}
@@ -1283,6 +1292,7 @@ async fn bare_bot_is_forbidden_by_no_bot_policies_and_accepted_by_bot_only() {
vec![
AuthorizationCall::Bot {
token: "bot-bare".to_owned(),
+ bot_scope: BotScope::User,
claims: None,
};
4
@@ -1290,6 +1300,60 @@ async fn bare_bot_is_forbidden_by_no_bot_policies_and_accepted_by_bot_only() {
);
}
+#[tokio::test]
+async fn bot_scope_is_required_and_must_be_user_or_team() {
+ let (router, service) = test_router();
+
+ for request in [
+ request("/bot").header(BOT_TOKEN_HEADER, "bot-bare"),
+ request("/bot")
+ .header(BOT_TOKEN_HEADER, "bot-bare")
+ .header(BOT_SCOPE_HEADER, ""),
+ request("/bot")
+ .header(BOT_TOKEN_HEADER, "bot-bare")
+ .header(BOT_SCOPE_HEADER, "organization"),
+ ] {
+ let (status, body) = send(&router, empty_body(request)).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert_eq!(body, json!({ "message": "invalid bot scope" }));
+ }
+
+ let malformed_scope = HeaderValue::from_bytes(b"\xff").unwrap();
+ let request = empty_body(
+ request("/bot")
+ .header(BOT_TOKEN_HEADER, "bot-bare")
+ .header(BOT_SCOPE_HEADER, malformed_scope),
+ );
+ let (status, body) = send(&router, request).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert_eq!(body, json!({ "message": "invalid bot scope" }));
+ assert!(service.calls().is_empty());
+}
+
+#[tokio::test]
+async fn team_bot_scope_is_forwarded_and_returned() {
+ let (router, service) = test_router();
+ let request = empty_body(
+ request("/bot")
+ .header(BOT_TOKEN_HEADER, "bot-bare")
+ .header(BOT_SCOPE_HEADER, BotScope::Team.as_str()),
+ );
+
+ let (status, body) = send(&router, request).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["bot_scope"], BotScope::Team.as_str());
+ assert_eq!(body["team_id"], BOT_TEAM_ID.to_string());
+ assert_eq!(
+ service.calls(),
+ [AuthorizationCall::Bot {
+ token: "bot-bare".to_owned(),
+ bot_scope: BotScope::Team,
+ claims: None,
+ }]
+ );
+}
+
#[tokio::test]
async fn missing_malformed_and_blank_bot_tokens_follow_required_and_optional_contracts() {
let (router, service) = test_router();
@@ -1306,18 +1370,18 @@ async fn missing_malformed_and_blank_bot_tokens_follow_required_and_optional_con
let malformed_token = HeaderValue::from_bytes(b"\xff").unwrap();
let (status, body) = send(
&router,
- empty_body(request(path).header(BOT_TOKEN_HEADER, malformed_token)),
+ empty_body(
+ request(path)
+ .header(BOT_TOKEN_HEADER, malformed_token)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str()),
+ ),
)
.await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, json!({ "message": "unauthorized" }));
for blank_token in ["", " "] {
- let (status, body) = send(
- &router,
- empty_body(request(path).header(BOT_TOKEN_HEADER, blank_token)),
- )
- .await;
+ let (status, body) = send(&router, empty_body(bot_request(path, blank_token))).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, json!({ "message": "unauthorized" }));
}
@@ -1332,35 +1396,25 @@ async fn bot_authorization_errors_have_generic_status_specific_responses() {
for token in ["bot-invalid", "bot-expired", "bot-revoked"] {
for path in ["/required", "/optional", "/bot", "/optional-bot"] {
- let (status, body) = send(
- &router,
- empty_body(request(path).header(BOT_TOKEN_HEADER, token)),
- )
- .await;
+ let (status, body) = send(&router, empty_body(bot_request(path, token))).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, json!({ "message": "unauthorized" }));
}
}
for path in ["/required", "/optional", "/bot", "/optional-bot"] {
- let (status, body) = send(
- &router,
- empty_body(request(path).header(BOT_TOKEN_HEADER, "bot-forbidden")),
- )
- .await;
- assert_eq!(status, StatusCode::FORBIDDEN);
- assert_eq!(body, json!({ "message": "forbidden" }));
+ for token in ["bot-forbidden", "bot-scope-forbidden"] {
+ let (status, body) = send(&router, empty_body(bot_request(path, token))).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert_eq!(body, json!({ "message": "forbidden" }));
+ }
- let (status, body) = send(
- &router,
- empty_body(request(path).header(BOT_TOKEN_HEADER, "bot-unavailable")),
- )
- .await;
+ let (status, body) = send(&router, empty_body(bot_request(path, "bot-unavailable"))).await;
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(body, json!({ "message": "internal server error" }));
}
- assert_eq!(service.calls().len(), 20);
+ assert_eq!(service.calls().len(), 24);
assert!(
service
.calls()
@@ -1381,11 +1435,7 @@ async fn bot_claim_headers_are_strictly_parsed_before_authorization() {
] {
let (status, body) = send(
&router,
- empty_body(
- request("/bot")
- .header(BOT_TOKEN_HEADER, "bot-acting")
- .header(header, malformed_header.clone()),
- ),
+ empty_body(bot_request("/bot", "bot-acting").header(header, malformed_header.clone())),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
@@ -1396,8 +1446,7 @@ async fn bot_claim_headers_are_strictly_parsed_before_authorization() {
let (status, body) = send(
&router,
empty_body(
- request("/bot")
- .header(BOT_TOKEN_HEADER, "bot-acting")
+ bot_request("/bot", "bot-acting")
.header(BOT_FOR_ORGANIZATION_ID_HEADER, organization_id),
),
)
@@ -1413,9 +1462,7 @@ async fn bot_claim_headers_are_strictly_parsed_before_authorization() {
async fn bot_claims_without_a_user_identifier_reach_the_authorizer() {
let (router, service) = test_router();
let request = empty_body(
- request("/bot")
- .header(BOT_TOKEN_HEADER, "bot-forbidden")
- .header(BOT_FOR_ORGANIZATION_ID_HEADER, "42"),
+ bot_request("/bot", "bot-forbidden").header(BOT_FOR_ORGANIZATION_ID_HEADER, "42"),
);
let (status, body) = send(&router, request).await;
@@ -1426,6 +1473,7 @@ async fn bot_claims_without_a_user_identifier_reach_the_authorizer() {
service.calls(),
[AuthorizationCall::Bot {
token: "bot-forbidden".to_owned(),
+ bot_scope: BotScope::User,
claims: Some(BotActingUserClaims {
user_id: None,
fusion_user_id: None,
@@ -1461,26 +1509,24 @@ async fn every_combination_of_multiple_explicit_credential_types_is_ambiguous()
.header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
.header("authorization", "Bearer valid"),
),
- empty_body(
- request(path)
- .header(BOT_TOKEN_HEADER, "bot-acting")
- .header("authorization", "Bearer valid"),
- ),
+ empty_body(bot_request(path, "bot-acting").header("authorization", "Bearer valid")),
empty_body(
request(path)
.header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
- .header(BOT_TOKEN_HEADER, "bot-acting"),
+ .header(BOT_TOKEN_HEADER, "bot-acting")
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str()),
),
empty_body(
request(path)
.header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
.header(BOT_TOKEN_HEADER, "bot-acting")
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
.header("authorization", "Bearer valid"),
),
empty_body(
request(&path_with_query).header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY),
),
- empty_body(request(&path_with_query).header(BOT_TOKEN_HEADER, "bot-acting")),
+ empty_body(bot_request(&path_with_query, "bot-acting")),
];
for request in requests {
@@ -1498,8 +1544,7 @@ async fn explicit_credentials_win_over_ambient_cookies_without_fallback() {
let (router, service) = test_router();
let valid_bot_request = empty_body(
- request("/required")
- .header(BOT_TOKEN_HEADER, "bot-acting")
+ bot_request("/required", "bot-acting")
.header("cookie", format!("{ACCESS_TOKEN_COOKIE}=cookie")),
);
let (status, body) = send(&router, valid_bot_request).await;
@@ -1507,8 +1552,7 @@ async fn explicit_credentials_win_over_ambient_cookies_without_fallback() {
assert_eq!(body, json!({ "message": "forbidden" }));
let invalid_bot_request = empty_body(
- request("/required")
- .header(BOT_TOKEN_HEADER, "bot-invalid")
+ bot_request("/required", "bot-invalid")
.header("cookie", format!("{ACCESS_TOKEN_COOKIE}=cookie")),
);
let (status, body) = send(&router, invalid_bot_request).await;
@@ -1529,10 +1573,12 @@ async fn explicit_credentials_win_over_ambient_cookies_without_fallback() {
[
AuthorizationCall::Bot {
token: "bot-acting".to_owned(),
+ bot_scope: BotScope::User,
claims: None,
},
AuthorizationCall::Bot {
token: "bot-invalid".to_owned(),
+ bot_scope: BotScope::User,
claims: None,
},
]
@@ -1561,12 +1607,8 @@ const PRINCIPAL_CREDENTIALS: [PrincipalCredentials; 6] = [
fn principal_request(path: &str, credentials: PrincipalCredentials) -> Request<Body> {
let request = match credentials {
PrincipalCredentials::User => request(path).header("authorization", "Bearer valid"),
- PrincipalCredentials::BotWithActingUser => {
- request(path).header(BOT_TOKEN_HEADER, "bot-acting")
- }
- PrincipalCredentials::BotWithoutActingUser => {
- request(path).header(BOT_TOKEN_HEADER, "bot-bare")
- }
+ PrincipalCredentials::BotWithActingUser => bot_request(path, "bot-acting"),
+ PrincipalCredentials::BotWithoutActingUser => bot_request(path, "bot-bare"),
PrincipalCredentials::InternalWithActingUser => request(path)
.header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
.header(INTERNAL_MACRO_USER_ID_HEADER, STANDARD_INTERNAL_USER_ID),
@@ -1780,7 +1822,7 @@ async fn assert_policy_matrix<const N: usize>(policies: [(&str, [StatusCode; 6])
fn policies_report_typed_acting_entity_variants_with_display_parity() {
let user = macro_user_authentication(VALID_USER_ID);
let internal_user = macro_user_authentication(STANDARD_INTERNAL_USER_ID);
- let bot = bot_authentication(Some(BOT_ACTING_USER_ID));
+ let bot = bot_authentication(BotScope::User, Some(BOT_ACTING_USER_ID));
let direct_user = MacroAuthorization::User(user.clone());
let user_or_internal = UserOrInternal::narrow(direct_user.clone()).unwrap();
diff --git a/crates/macro_authorization/src/inbound/axum/user.rs b/crates/macro_authorization/src/inbound/axum/user.rs
index 82877ca810..6b15268029 100644
--- a/crates/macro_authorization/src/inbound/axum/user.rs
+++ b/crates/macro_authorization/src/inbound/axum/user.rs
@@ -146,6 +146,7 @@ fn authorization_rejection(error: Report<MacroAuthorizationError>) -> MacroAutho
MacroAuthorizationError::CredentialsExpired => "jwt expired",
MacroAuthorizationError::InvalidCredentials
| MacroAuthorizationError::ActingUserNotAuthorized
+ | MacroAuthorizationError::BotScopeNotAuthorized
| MacroAuthorizationError::Unavailable => "unauthorized",
};
tracing::error!(error=?error, "credential authorization failed");
diff --git a/crates/macro_authorization/src/lib.rs b/crates/macro_authorization/src/lib.rs
index d95bd93a2e..7e5459f17a 100644
--- a/crates/macro_authorization/src/lib.rs
+++ b/crates/macro_authorization/src/lib.rs
@@ -24,6 +24,10 @@
//! | [`InternalOnly`] | Internal service, with optional acting user | [`InternalAuthorization`] |
//! | [`AnyPrincipal`] | Any authenticated principal | [`MacroAuthorization`] |
//!
+//! Bot requests must include `x-macro-bot-scope` with the value `user` or
+//! `team`; a missing or invalid scope is rejected with `400 Bad Request`, and
+//! only a team-owned bot may request team scope. Successful bot authorization
+//! includes the owning team ID when the bot is team-owned.
//! Both extractors reject requests that combine explicit credential types
//! (internal key, bot token, or user query/bearer) with `400 Bad Request` rather
//! than choosing a principal. Query and bearer credentials are one user type,
@@ -48,9 +52,9 @@ pub mod outbound;
pub use domain::{
bot_authorizer::BotAuthorizerService,
models::{
- BotActingUserClaims, BotAuthentication, BotAuthorizationOwner, BotTokenAuthorization,
- InternalAuthConfig, InternalIdentityClaims, MacroAuthorization, MacroAuthorizationError,
- MacroUserAuthentication, ResolvedBotActingUser, ValidatedIdentity,
+ BotActingUserClaims, BotAuthentication, BotAuthorizationOwner, BotScope,
+ BotTokenAuthorization, InternalAuthConfig, InternalIdentityClaims, MacroAuthorization,
+ MacroAuthorizationError, MacroUserAuthentication, ResolvedBotActingUser, ValidatedIdentity,
},
ports::{
BotAuthorizationRepo, BotAuthorizer, JwtValidator, MacroAuthorizationService,
@@ -64,14 +68,14 @@ pub use domain::{
pub use inbound::{
ActingEntity, ActingUser, ActingUserAuthorization, AnyPrincipal, AuthorizationPolicy,
BOT_FOR_FUSIONAUTH_USER_ID_HEADER, BOT_FOR_MACRO_USER_ID_HEADER,
- BOT_FOR_ORGANIZATION_ID_HEADER, BOT_TOKEN_HEADER, BotOnly, INTERNAL_API_KEY_HEADER,
- INTERNAL_FUSIONAUTH_USER_ID_HEADER, INTERNAL_MACRO_ORGANIZATION_ID_HEADER,
- INTERNAL_MACRO_USER_ID_HEADER, InternalAuthorization, InternalEntity, InternalOnly,
- LEGACY_DSS_INTERNAL_API_KEY_HEADER, LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER,
- MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationState,
- OptionalMacroAuthorizationExtractor, UserOnly, UserOrInternal, UserOrInternalAuthorization,
- UserOrInternalCaller, UserOrInternalEntity, UserOrInternalService,
- UserOrInternalServiceAuthorization,
+ BOT_FOR_ORGANIZATION_ID_HEADER, BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotOnly,
+ INTERNAL_API_KEY_HEADER, INTERNAL_FUSIONAUTH_USER_ID_HEADER,
+ INTERNAL_MACRO_ORGANIZATION_ID_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalAuthorization,
+ InternalEntity, InternalOnly, LEGACY_DSS_INTERNAL_API_KEY_HEADER,
+ LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER, MacroAuthorizationExtractor,
+ MacroAuthorizationRejection, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+ UserOnly, UserOrInternal, UserOrInternalAuthorization, UserOrInternalCaller,
+ UserOrInternalEntity, UserOrInternalService, UserOrInternalServiceAuthorization,
};
/// JWT validation adapters for user-authenticated and internal-only services.
#[cfg(feature = "outbound")]