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(auth): user api key authorization (#6067)

Will Hutchinsona69b5b4cfa21
diff --git a/.sqlx/query-5392d04a21e2f3c41dc84a6193f1cd004c9c571ae61a47c448a4f1e28f678255.json b/.sqlx/query-5392d04a21e2f3c41dc84a6193f1cd004c9c571ae61a47c448a4f1e28f678255.json
new file mode 100644
index 0000000000..1b6e64017a
--- /dev/null
+++ b/.sqlx/query-5392d04a21e2f3c41dc84a6193f1cd004c9c571ae61a47c448a4f1e28f678255.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"UserApiKey\" (id, name, user_id, hash)\n VALUES ($1, $2, $3, $4)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Bytea"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5392d04a21e2f3c41dc84a6193f1cd004c9c571ae61a47c448a4f1e28f678255"
+}
diff --git a/.sqlx/query-fe966cb819586e1b423deafea194c0bd97468a16d1f81fae7ad0884cc79aa395.json b/.sqlx/query-fe966cb819586e1b423deafea194c0bd97468a16d1f81fae7ad0884cc79aa395.json
new file mode 100644
index 0000000000..7b3c21e418
--- /dev/null
+++ b/.sqlx/query-fe966cb819586e1b423deafea194c0bd97468a16d1f81fae7ad0884cc79aa395.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n u.id,\n u.macro_user_id AS \"fusion_user_id?\",\n u.\"organizationId\" AS \"organization_id?\"\n FROM \"UserApiKey\" k\n JOIN \"User\" u ON u.id = k.user_id\n WHERE k.hash = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "fusion_user_id?",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "organization_id?",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Bytea"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "fe966cb819586e1b423deafea194c0bd97468a16d1f81fae7ad0884cc79aa395"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 6eb61a21e1..066eb86354 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -9413,6 +9413,7 @@ dependencies = [
"serde",
"serde_json",
"serde_urlencoded",
+ "sha2 0.10.9",
"sqlx",
"thiserror 2.0.18",
"tokio",
diff --git a/crates/agent_harness/src/inbound/runtime_gateway/test.rs b/crates/agent_harness/src/inbound/runtime_gateway/test.rs
index e251eff943..53a8d2ff5f 100644
--- a/crates/agent_harness/src/inbound/runtime_gateway/test.rs
+++ b/crates/agent_harness/src/inbound/runtime_gateway/test.rs
@@ -12,7 +12,7 @@ use bot_id::BotId;
use macro_authorization::{
BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotAuthorizer,
BotScope, InternalAuthConfig, JwtValidator, MacroAuthorizationError,
- MacroAuthorizationServiceImpl, ValidatedIdentity,
+ MacroAuthorizationServiceImpl, NoUserApiKeyAuthorizer, ValidatedIdentity,
};
use macro_user_id::user_id::MacroUserIdStr;
use rootcause::Report;
@@ -98,6 +98,7 @@ async fn serve(directory: FactsDirectory) -> (Arc<RuntimeRegistry<GatewaySender>
default_user_id: None,
},
SelfBotAuthorizer,
+ NoUserApiKeyAuthorizer,
);
let app: Router = Router::new().nest(
"/runtime",
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
index b87f8245c9..42ff459b94 100644
--- a/crates/agent_session/src/inbound/axum_router/test.rs
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -6,7 +6,7 @@ use chrono::Utc;
use macro_authorization::{
BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotAuthorizer,
BotScope, InternalAuthConfig, JwtValidator, MacroAuthorizationError,
- MacroAuthorizationServiceImpl, ValidatedIdentity,
+ MacroAuthorizationServiceImpl, NoUserApiKeyAuthorizer, ValidatedIdentity,
};
use rootcause::Report;
use std::sync::{Arc, Mutex};
@@ -179,6 +179,7 @@ fn router_for(opener: Arc<RecordingOpener>, bots: OneBotDirectory) -> Router {
default_user_id: None,
},
SelfBotAuthorizer,
+ NoUserApiKeyAuthorizer,
);
agent_session_create_router(CreateSessionState::new(
opener,
diff --git a/crates/bots/src/inbound/axum_router/tests.rs b/crates/bots/src/inbound/axum_router/tests.rs
index e732a10a74..33aa5fcd44 100644
--- a/crates/bots/src/inbound/axum_router/tests.rs
+++ b/crates/bots/src/inbound/axum_router/tests.rs
@@ -21,7 +21,8 @@ use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccess
use macro_authorization::{
BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotAuthorizer,
BotScope, InternalAuthConfig, JwtValidator, MacroAuthorizationError,
- MacroAuthorizationServiceImpl, MacroAuthorizationState, NoBotAuthorizer, ValidatedIdentity,
+ MacroAuthorizationServiceImpl, MacroAuthorizationState, NoBotAuthorizer,
+ NoUserApiKeyAuthorizer, ValidatedIdentity,
};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_event_broker::NoopMacroEventBroker;
@@ -368,6 +369,7 @@ fn authorization_state() -> MacroAuthorizationState<TestAuthorizationService> {
default_user_id: None,
},
NoBotAuthorizer,
+ NoUserApiKeyAuthorizer,
);
MacroAuthorizationState::new(Arc::new(service))
}
@@ -410,6 +412,7 @@ fn authorization_state_with_bot(
default_user_id: None,
},
SelfBotAuthorizer { bot_id },
+ NoUserApiKeyAuthorizer,
);
MacroAuthorizationState::new(Arc::new(service))
}
diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rs
index ce4e533f44..b58682a186 100644
--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs
+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs
@@ -24,7 +24,7 @@ use macro_authorization::{
BotActingUserClaims as AuthorizationBotActingUserClaims, BotAuthentication, BotAuthorizer,
BotScope, InternalAuthConfig, JwtValidator, MacroAuthorizationError,
MacroAuthorizationServiceImpl, MacroAuthorizationState, MacroUserAuthentication,
- ValidatedIdentity,
+ NoUserApiKeyAuthorizer, ValidatedIdentity,
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use rootcause::Report;
@@ -592,6 +592,7 @@ fn authorization_state(
default_user_id: None,
},
bot_authorizer,
+ NoUserApiKeyAuthorizer,
);
MacroAuthorizationState::new(Arc::new(service))
}
diff --git a/crates/channels/src/inbound/axum_router/test.rs b/crates/channels/src/inbound/axum_router/test.rs
index e349411abb..e017f9e996 100644
--- a/crates/channels/src/inbound/axum_router/test.rs
+++ b/crates/channels/src/inbound/axum_router/test.rs
@@ -932,6 +932,7 @@ fn authorization_state_with_default(
default_user_id: default_user_id.map(str::to_string),
},
macro_authorization::NoBotAuthorizer,
+ macro_authorization::NoUserApiKeyAuthorizer,
);
(MacroAuthorizationState::new(Arc::new(service)), validator)
}
diff --git a/crates/channels/src/inbound/list_router/test.rs b/crates/channels/src/inbound/list_router/test.rs
index d27c4a6366..30ae5bb52e 100644
--- a/crates/channels/src/inbound/list_router/test.rs
+++ b/crates/channels/src/inbound/list_router/test.rs
@@ -134,6 +134,7 @@ fn test_router_with_channels(
default_user_id: default_user_id.map(str::to_owned),
},
macro_authorization::NoBotAuthorizer,
+ macro_authorization::NoUserApiKeyAuthorizer,
);
let state = ChannelListRouterState::new(
list_service,
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index 9ce9349b2d..1a3413b422 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -188,6 +188,7 @@ impl FromRef<SchemaOnlyState> for MacroAuthorizationState<SchemaOnlyAuthorizatio
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ macro_authorization::NoUserApiKeyAuthorizer,
);
MacroAuthorizationState::new(Arc::new(service))
}
diff --git a/crates/contacts/src/inbound/http/test.rs b/crates/contacts/src/inbound/http/test.rs
index 82167baafd..d766dc661b 100644
--- a/crates/contacts/src/inbound/http/test.rs
+++ b/crates/contacts/src/inbound/http/test.rs
@@ -124,6 +124,7 @@ fn build_test_router(should_exceed: bool) -> (Router, FakeJwtValidator) {
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ macro_authorization::NoUserApiKeyAuthorizer,
);
let state = ContactsRouterState {
contacts_service: Arc::new(MockService),
diff --git a/crates/crm/src/inbound/axum_extractors/test.rs b/crates/crm/src/inbound/axum_extractors/test.rs
index ead0c41d67..a88a61bec1 100644
--- a/crates/crm/src/inbound/axum_extractors/test.rs
+++ b/crates/crm/src/inbound/axum_extractors/test.rs
@@ -533,6 +533,7 @@ fn test_router(
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ macro_authorization::NoUserApiKeyAuthorizer,
);
let state: CrmRouterState<FakeCrmService, FakeEntityAccessService, TestAuthorizationService> =
CrmRouterState {
diff --git a/crates/macro_authorization/Cargo.toml b/crates/macro_authorization/Cargo.toml
index b2c5c426ed..30c1e80f70 100644
--- a/crates/macro_authorization/Cargo.toml
+++ b/crates/macro_authorization/Cargo.toml
@@ -14,7 +14,7 @@ axum = [
default = ["axum", "outbound"]
local_auth = ["dep:macro_env_var"]
outbound = ["dep:macro_auth"]
-postgres = ["dep:sqlx"]
+postgres = ["dep:sqlx", "dep:sha2"]
[dependencies]
axum = { workspace = true, optional = true }
@@ -28,6 +28,7 @@ model-error-response = { path = "../model-error-response", optional = true }
model_user = { path = "../model_user" }
rootcause = { workspace = true }
serde = { workspace = true, optional = true }
+sha2 = { workspace = true, optional = true }
sqlx = { workspace = true, optional = true }
thiserror = { workspace = true }
tracing = { workspace = true }
diff --git a/crates/macro_authorization/src/domain.rs b/crates/macro_authorization/src/domain.rs
index 16e799cd60..467e83248b 100644
--- a/crates/macro_authorization/src/domain.rs
+++ b/crates/macro_authorization/src/domain.rs
@@ -8,3 +8,5 @@ pub mod models;
pub mod ports;
/// Authorization service implementation.
pub mod service;
+/// User API key credential authorization policy.
+pub mod user_api_key_authorizer;
diff --git a/crates/macro_authorization/src/domain/models.rs b/crates/macro_authorization/src/domain/models.rs
index 4041820833..0a271162fb 100644
--- a/crates/macro_authorization/src/domain/models.rs
+++ b/crates/macro_authorization/src/domain/models.rs
@@ -138,6 +138,17 @@ pub struct ResolvedBotActingUser {
pub organization_id: Option<i32>,
}
+/// User identity facts resolved for a valid user API key.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct ResolvedApiKeyUser {
+ /// The user's parsed Macro identifier.
+ pub macro_user_id: MacroUserIdStr<'static>,
+ /// The user's FusionAuth identifier.
+ pub fusion_user_id: String,
+ /// The user's organization, when present.
+ pub organization_id: Option<i32>,
+}
+
/// Unverified acting-user claims presented by a bot.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct BotActingUserClaims {
diff --git a/crates/macro_authorization/src/domain/ports.rs b/crates/macro_authorization/src/domain/ports.rs
index 09f3df33b3..cc063be382 100644
--- a/crates/macro_authorization/src/domain/ports.rs
+++ b/crates/macro_authorization/src/domain/ports.rs
@@ -5,7 +5,8 @@ use rootcause::Report;
use super::models::{
BotActingUserClaims, BotAuthentication, BotScope, BotTokenAuthorization,
- InternalIdentityClaims, MacroAuthorizationError, ResolvedBotActingUser, ValidatedIdentity,
+ InternalIdentityClaims, MacroAuthorizationError, ResolvedApiKeyUser, ResolvedBotActingUser,
+ ValidatedIdentity,
};
use uuid::Uuid;
@@ -64,6 +65,43 @@ impl BotAuthorizer for NoBotAuthorizer {
}
}
+/// Persistence facts required to authorize a user API key.
+pub trait UserApiKeyAuthorizationRepo: Clone + Send + Sync + 'static {
+ /// Repository error.
+ type Err: Debug + Send;
+
+ /// Resolve the owner identity of a currently valid user API key.
+ ///
+ /// `api_key` is the raw secret from the request. Implementations persist
+ /// and match SHA-256 of its UTF-8 bytes, never the secret itself.
+ fn find_key_owner(
+ &self,
+ api_key: &str,
+ ) -> impl Future<Output = Result<Option<ResolvedApiKeyUser>, Self::Err>> + Send;
+}
+
+/// Validates user API key credentials and resolves the owner's identity.
+pub trait UserApiKeyAuthorizer: Clone + Send + Sync + 'static {
+ /// Authorize a user API key and return the owner's user context.
+ fn authorize_user_api_key(
+ &self,
+ api_key: &str,
+ ) -> impl Future<Output = Result<UserContext, Report<MacroAuthorizationError>>> + Send;
+}
+
+/// User API key authorizer used by services that do not support this credential.
+#[derive(Clone)]
+pub struct NoUserApiKeyAuthorizer;
+
+impl UserApiKeyAuthorizer for NoUserApiKeyAuthorizer {
+ async fn authorize_user_api_key(
+ &self,
+ _api_key: &str,
+ ) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+}
+
/// Cryptographic credential validation used by the authorization domain.
///
/// Implementations resolve any required secrets during startup, allowing this
@@ -107,4 +145,15 @@ pub trait MacroAuthorizationService: Clone + Send + Sync + 'static {
provided_key: &str,
claims: InternalIdentityClaims,
) -> impl Future<Output = Result<Option<UserContext>, Report<MacroAuthorizationError>>> + Send;
+
+ /// Authorize a user API key and return the owner's user context.
+ ///
+ /// Services reject user API keys unless they explicitly provide a user API
+ /// key authorizer.
+ fn authorize_user_api_key(
+ &self,
+ _api_key: &str,
+ ) -> impl Future<Output = Result<UserContext, Report<MacroAuthorizationError>>> + Send {
+ async { Err(Report::new(MacroAuthorizationError::InvalidCredentials)) }
+ }
}
diff --git a/crates/macro_authorization/src/domain/service.rs b/crates/macro_authorization/src/domain/service.rs
index 761f3aac0b..ddbdd23dab 100644
--- a/crates/macro_authorization/src/domain/service.rs
+++ b/crates/macro_authorization/src/domain/service.rs
@@ -12,7 +12,7 @@ use super::{
BotActingUserClaims, BotAuthentication, BotScope, InternalAuthConfig,
InternalIdentityClaims, MacroAuthorizationError,
},
- ports::{BotAuthorizer, JwtValidator, MacroAuthorizationService},
+ ports::{BotAuthorizer, JwtValidator, MacroAuthorizationService, UserApiKeyAuthorizer},
};
type BotAuthorizationFuture<'a> = Pin<
@@ -49,25 +49,44 @@ where
}
}
+type UserApiKeyAuthorizationFuture<'a> =
+ Pin<Box<dyn Future<Output = Result<UserContext, Report<MacroAuthorizationError>>> + Send + 'a>>;
+
+trait DynUserApiKeyAuthorizer: Send + Sync {
+ fn authorize_user_api_key<'a>(&'a self, api_key: &'a str) -> UserApiKeyAuthorizationFuture<'a>;
+}
+
+impl<A> DynUserApiKeyAuthorizer for A
+where
+ A: UserApiKeyAuthorizer,
+{
+ fn authorize_user_api_key<'a>(&'a self, api_key: &'a str) -> UserApiKeyAuthorizationFuture<'a> {
+ Box::pin(UserApiKeyAuthorizer::authorize_user_api_key(self, api_key))
+ }
+}
+
/// Default authorization service backed by a credential validator.
#[derive(Clone)]
pub struct MacroAuthorizationServiceImpl<V> {
validator: V,
internal_auth: InternalAuthConfig,
bot_authorizer: Arc<dyn DynBotAuthorizer>,
+ user_api_key_authorizer: Arc<dyn DynUserApiKeyAuthorizer>,
}
impl<V> MacroAuthorizationServiceImpl<V> {
- /// Create an authorization service with required user, internal, and bot authorization dependencies.
+ /// Create an authorization service with required user, internal, bot, and user API key authorization dependencies.
pub fn new(
validator: V,
internal_auth: InternalAuthConfig,
bot_authorizer: impl BotAuthorizer,
+ user_api_key_authorizer: impl UserApiKeyAuthorizer,
) -> Self {
Self {
validator,
internal_auth,
bot_authorizer: Arc::new(bot_authorizer),
+ user_api_key_authorizer: Arc::new(user_api_key_authorizer),
}
}
}
@@ -126,6 +145,24 @@ where
Ok(bot)
}
+ #[tracing::instrument(
+ err,
+ skip_all,
+ fields(user_id = tracing::field::Empty)
+ )]
+ async fn authorize_user_api_key(
+ &self,
+ api_key: &str,
+ ) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ let user = self
+ .user_api_key_authorizer
+ .authorize_user_api_key(api_key)
+ .await?;
+
+ tracing::Span::current().record("user_id", tracing::field::display(&user.user_id));
+ Ok(user)
+ }
+
async fn authorize_internal(
&self,
provided_key: &str,
diff --git a/crates/macro_authorization/src/domain/service/test.rs b/crates/macro_authorization/src/domain/service/test.rs
index ffcf11c4a0..0d790ae90f 100644
--- a/crates/macro_authorization/src/domain/service/test.rs
+++ b/crates/macro_authorization/src/domain/service/test.rs
@@ -16,7 +16,10 @@ use crate::domain::{
InternalIdentityClaims, MacroAuthorizationError, MacroUserAuthentication,
ValidatedIdentity,
},
- ports::{BotAuthorizer, JwtValidator, MacroAuthorizationService, NoBotAuthorizer},
+ ports::{
+ BotAuthorizer, JwtValidator, MacroAuthorizationService, NoBotAuthorizer,
+ NoUserApiKeyAuthorizer, UserApiKeyAuthorizer,
+ },
};
#[derive(Clone)]
@@ -56,6 +59,39 @@ impl FakeBotAuthorizer {
}
}
+#[derive(Clone)]
+struct FakeUserApiKeyAuthorizer {
+ calls: Arc<Mutex<Vec<String>>>,
+ result: Result<UserContext, MacroAuthorizationError>,
+}
+
+impl FakeUserApiKeyAuthorizer {
+ fn new(result: Result<UserContext, MacroAuthorizationError>) -> Self {
+ Self {
+ calls: Arc::new(Mutex::new(Vec::new())),
+ result,
+ }
+ }
+
+ fn calls(&self) -> Vec<String> {
+ self.calls.lock().expect("calls lock poisoned").clone()
+ }
+}
+
+impl UserApiKeyAuthorizer for FakeUserApiKeyAuthorizer {
+ async fn authorize_user_api_key(
+ &self,
+ api_key: &str,
+ ) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(api_key.to_string());
+
+ self.result.clone().map_err(Report::new)
+ }
+}
+
impl BotAuthorizer for FakeBotAuthorizer {
async fn authorize_bot(
&self,
@@ -114,6 +150,7 @@ fn service_with_internal_auth(
},
internal_auth_config(default_user_id),
NoBotAuthorizer,
+ NoUserApiKeyAuthorizer,
)
}
@@ -220,6 +257,7 @@ async fn authorize_bot_delegates_token_and_exact_acting_user_claims() {
},
internal_auth_config(None),
authorizer.clone(),
+ NoUserApiKeyAuthorizer,
);
let bot = service
@@ -252,6 +290,7 @@ async fn authorize_bot_passes_through_authorizer_errors() {
},
internal_auth_config(None),
FakeBotAuthorizer::new(Err(expected)),
+ NoUserApiKeyAuthorizer,
);
let error = service
@@ -277,6 +316,7 @@ async fn authorize_constructs_user_context_from_validated_identity() {
},
internal_auth_config(None),
NoBotAuthorizer,
+ NoUserApiKeyAuthorizer,
);
let context = service.authorize("valid-jwt").await.unwrap();
@@ -361,6 +401,7 @@ async fn authorize_propagates_expired_credentials() {
},
internal_auth_config(None),
NoBotAuthorizer,
+ NoUserApiKeyAuthorizer,
);
let error = service.authorize("expired-jwt").await.unwrap_err();
@@ -379,6 +420,7 @@ async fn authorize_propagates_invalid_credentials() {
},
internal_auth_config(None),
NoBotAuthorizer,
+ NoUserApiKeyAuthorizer,
);
let error = service.authorize("invalid-jwt").await.unwrap_err();
@@ -388,3 +430,96 @@ async fn authorize_propagates_invalid_credentials() {
&MacroAuthorizationError::InvalidCredentials
);
}
+
+#[tokio::test]
+async fn no_user_api_key_authorizer_rejects_user_api_keys() {
+ let error = NoUserApiKeyAuthorizer
+ .authorize_user_api_key("mak_secret")
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.current_context(),
+ &MacroAuthorizationError::InvalidCredentials
+ );
+}
+
+#[tokio::test]
+async fn authorization_service_trait_rejects_user_api_keys_by_default() {
+ let error = DefaultRejectingAuthorizationService
+ .authorize_user_api_key("mak_secret")
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.current_context(),
+ &MacroAuthorizationError::InvalidCredentials
+ );
+}
+
+#[tokio::test]
+async fn authorization_service_impl_rejects_user_api_keys_with_explicit_no_authorizer() {
+ let error = service_with_internal_auth(None)
+ .authorize_user_api_key("mak_secret")
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.current_context(),
+ &MacroAuthorizationError::InvalidCredentials
+ );
+}
+
+fn api_key_user_context() -> UserContext {
+ UserContext {
+ user_id: "macro|[email protected]".to_string(),
+ fusion_user_id: "fusion-api-key-user".to_string(),
+ permissions: None,
+ organization_id: Some(42),
+ }
+}
+
+#[tokio::test]
+async fn authorize_user_api_key_delegates_the_exact_key() {
+ let authorizer = FakeUserApiKeyAuthorizer::new(Ok(api_key_user_context()));
+ let service = MacroAuthorizationServiceImpl::new(
+ FakeJwtValidator {
+ result: Err(MacroAuthorizationError::InvalidCredentials),
+ },
+ internal_auth_config(None),
+ NoBotAuthorizer,
+ authorizer.clone(),
+ );
+
+ let context = service.authorize_user_api_key("mak_secret").await.unwrap();
+
+ assert_eq!(context.user_id, "macro|[email protected]");
+ assert_eq!(context.fusion_user_id, "fusion-api-key-user");
+ assert_eq!(context.organization_id, Some(42));
+ assert_eq!(context.permissions, None);
+ assert_eq!(authorizer.calls(), vec!["mak_secret".to_string()]);
+}
+
+#[tokio::test]
+async fn authorize_user_api_key_passes_through_authorizer_errors() {
+ for expected in [
+ MacroAuthorizationError::InvalidCredentials,
+ MacroAuthorizationError::Unavailable,
+ ] {
+ let service = MacroAuthorizationServiceImpl::new(
+ FakeJwtValidator {
+ result: Err(MacroAuthorizationError::InvalidCredentials),
+ },
+ internal_auth_config(None),
+ NoBotAuthorizer,
+ FakeUserApiKeyAuthorizer::new(Err(expected)),
+ );
+
+ let error = service
+ .authorize_user_api_key("mak_secret")
+ .await
+ .unwrap_err();
+
+ assert_eq!(error.current_context(), &expected);
+ }
+}
diff --git a/crates/macro_authorization/src/domain/user_api_key_authorizer.rs b/crates/macro_authorization/src/domain/user_api_key_authorizer.rs
new file mode 100644
index 0000000000..1ee2a8a0c1
--- /dev/null
+++ b/crates/macro_authorization/src/domain/user_api_key_authorizer.rs
@@ -0,0 +1,66 @@
+//! User API key credential authorization policy.
+
+#[cfg(test)]
+mod test;
+
+use model_user::UserContext;
+use rootcause::Report;
+
+use super::{
+ models::{MacroAuthorizationError, ResolvedApiKeyUser},
+ ports::{UserApiKeyAuthorizationRepo, UserApiKeyAuthorizer},
+};
+
+/// User API key authorizer backed by transport-independent authorization facts.
+#[derive(Clone, Debug)]
+pub struct UserApiKeyAuthorizerService<R> {
+ repo: R,
+}
+
+impl<R> UserApiKeyAuthorizerService<R> {
+ /// Create a user API key authorizer backed by the supplied repository.
+ pub fn new(repo: R) -> Self {
+ Self { repo }
+ }
+}
+
+impl<R> UserApiKeyAuthorizer for UserApiKeyAuthorizerService<R>
+where
+ R: UserApiKeyAuthorizationRepo,
+{
+ #[tracing::instrument(err, skip_all)]
+ async fn authorize_user_api_key(
+ &self,
+ api_key: &str,
+ ) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ let owner = self
+ .repo
+ .find_key_owner(api_key)
+ .await
+ .map_err(|error| repository_error(error, "find key owner"))?
+ .ok_or_else(|| Report::new(MacroAuthorizationError::InvalidCredentials))?;
+
+ Ok(user_context(owner))
+ }
+}
+
+fn user_context(owner: ResolvedApiKeyUser) -> UserContext {
+ UserContext {
+ user_id: owner.macro_user_id.as_ref().to_owned(),
+ fusion_user_id: owner.fusion_user_id,
+ permissions: None,
+ organization_id: owner.organization_id,
+ }
+}
+
+fn repository_error(
+ error: impl std::fmt::Debug,
+ operation: &'static str,
+) -> Report<MacroAuthorizationError> {
+ tracing::error!(
+ error=?error,
+ operation,
+ "user api key authorization repository failed"
+ );
+ Report::new(MacroAuthorizationError::Unavailable)
+}
diff --git a/crates/macro_authorization/src/domain/user_api_key_authorizer/test.rs b/crates/macro_authorization/src/domain/user_api_key_authorizer/test.rs
new file mode 100644
index 0000000000..24d6f391ee
--- /dev/null
+++ b/crates/macro_authorization/src/domain/user_api_key_authorizer/test.rs
@@ -0,0 +1,115 @@
+use std::sync::{Arc, Mutex};
+
+use super::*;
+use crate::domain::{models::ResolvedApiKeyUser, ports::UserApiKeyAuthorizationRepo};
+use macro_user_id::user_id::MacroUserIdStr;
+
+const API_KEY: &str = "mak_test_secret";
+const USER_ID: &str = "macro|[email protected]";
+const FUSION_USER_ID: &str = "fusion-api-key-user";
+const ORGANIZATION_ID: i32 = 42;
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum Failure {
+ FindKeyOwner,
+}
+
+#[derive(Clone)]
+struct FakeRepo {
+ owner: Option<ResolvedApiKeyUser>,
+ failure: Option<Failure>,
+ keys: Arc<Mutex<Vec<String>>>,
+}
+
+impl FakeRepo {
+ fn found() -> Self {
+ Self {
+ owner: Some(resolved_user()),
+ failure: None,
+ keys: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn missing() -> Self {
+ Self {
+ owner: None,
+ failure: None,
+ keys: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn fail() -> Self {
+ Self {
+ owner: None,
+ failure: Some(Failure::FindKeyOwner),
+ keys: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn keys(&self) -> Vec<String> {
+ self.keys.lock().expect("keys lock poisoned").clone()
+ }
+}
+
+impl UserApiKeyAuthorizationRepo for FakeRepo {
+ type Err = &'static str;
+
+ async fn find_key_owner(&self, api_key: &str) -> Result<Option<ResolvedApiKeyUser>, Self::Err> {
+ self.keys
+ .lock()
+ .expect("keys lock poisoned")
+ .push(api_key.to_string());
+ if self.failure == Some(Failure::FindKeyOwner) {
+ return Err("find key owner failed");
+ }
+ Ok(self.owner.clone())
+ }
+}
+
+fn resolved_user() -> ResolvedApiKeyUser {
+ ResolvedApiKeyUser {
+ macro_user_id: MacroUserIdStr::try_from(USER_ID.to_string()).expect("valid Macro user id"),
+ fusion_user_id: FUSION_USER_ID.to_string(),
+ organization_id: Some(ORGANIZATION_ID),
+ }
+}
+
+#[tokio::test]
+async fn found_key_constructs_user_context() {
+ let repo = FakeRepo::found();
+ let authorizer = UserApiKeyAuthorizerService::new(repo.clone());
+
+ let context = authorizer.authorize_user_api_key(API_KEY).await.unwrap();
+
+ assert_eq!(context.user_id, USER_ID);
+ assert_eq!(context.fusion_user_id, FUSION_USER_ID);
+ assert_eq!(context.organization_id, Some(ORGANIZATION_ID));
+ assert_eq!(context.permissions, None);
+ assert_eq!(repo.keys(), vec![API_KEY.to_string()]);
+}
+
+#[tokio::test]
+async fn missing_key_is_invalid_credentials() {
+ let error = UserApiKeyAuthorizerService::new(FakeRepo::missing())
+ .authorize_user_api_key(API_KEY)
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.current_context(),
+ &MacroAuthorizationError::InvalidCredentials
+ );
+}
+
+#[tokio::test]
+async fn repository_error_is_unavailable() {
+ let error = UserApiKeyAuthorizerService::new(FakeRepo::fail())
+ .authorize_user_api_key(API_KEY)
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.current_context(),
+ &MacroAuthorizationError::Unavailable
+ );
+}
diff --git a/crates/macro_authorization/src/inbound.rs b/crates/macro_authorization/src/inbound.rs
index e5bd58ba90..348d650457 100644
--- a/crates/macro_authorization/src/inbound.rs
+++ b/crates/macro_authorization/src/inbound.rs
@@ -13,7 +13,7 @@ pub use axum::{
InternalEntity, InternalOnly, LEGACY_DSS_INTERNAL_API_KEY_HEADER,
LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER, MacroAuthorizationExtractor,
MacroAuthorizationRejection, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
- UserOnly, UserOrBot, UserOrBotAuthorization, UserOrBotEntity, UserOrInternal,
- UserOrInternalAuthorization, UserOrInternalCaller, UserOrInternalEntity, UserOrInternalService,
- UserOrInternalServiceAuthorization,
+ USER_API_KEY_HEADER, UserOnly, UserOrBot, UserOrBotAuthorization, UserOrBotEntity,
+ 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 f9e850885a..58d478e8a0 100644
--- a/crates/macro_authorization/src/inbound/axum.rs
+++ b/crates/macro_authorization/src/inbound/axum.rs
@@ -7,6 +7,7 @@ mod macro_authorization;
mod optional;
mod policy;
mod user;
+mod user_api_key;
use std::{borrow::Cow, fmt, sync::Arc};
@@ -41,6 +42,7 @@ pub use policy::{
UserOrInternalCaller, UserOrInternalEntity, UserOrInternalService,
UserOrInternalServiceAuthorization,
};
+pub use user_api_key::USER_API_KEY_HEADER;
/// The authenticated entity responsible for a request.
///
diff --git a/crates/macro_authorization/src/inbound/axum/macro_authorization.rs b/crates/macro_authorization/src/inbound/axum/macro_authorization.rs
index bcc7f6143d..07296835f9 100644
--- a/crates/macro_authorization/src/inbound/axum/macro_authorization.rs
+++ b/crates/macro_authorization/src/inbound/axum/macro_authorization.rs
@@ -13,6 +13,7 @@ use super::{
internal::{authorize_internal_request, internal_header_convention},
rejection, status_rejection,
user::{authorize_optional_user_request, explicit_user_credential_present},
+ user_api_key::{USER_API_KEY_HEADER, authorize_user_api_key_request},
};
/// Extracts and authorizes the request principal, then narrows it with `Policy`.
@@ -71,9 +72,11 @@ where
{
let internal_convention = internal_header_convention(&parts.headers);
let has_bot_token = parts.headers.contains_key(BOT_TOKEN_HEADER);
+ let has_user_api_key = parts.headers.contains_key(USER_API_KEY_HEADER);
let has_explicit_user_credential = explicit_user_credential_present(parts);
let explicit_credential_count = usize::from(internal_convention.is_some())
+ usize::from(has_bot_token)
+ + usize::from(has_user_api_key)
+ usize::from(has_explicit_user_credential);
if explicit_credential_count > 1 {
@@ -87,6 +90,11 @@ where
return authorize_internal_request::<S, Svc>(parts, state, convention).await;
}
+ if has_user_api_key {
+ let user = authorize_user_api_key_request::<S, Svc>(parts, state).await?;
+ return Ok(Some(MacroAuthorization::User(user)));
+ }
+
if has_bot_token {
let bot = authorize_optional_bot_request::<S, Svc>(parts, state)
.await?
diff --git a/crates/macro_authorization/src/inbound/axum/test.rs b/crates/macro_authorization/src/inbound/axum/test.rs
index e91ec1a53d..743ea63d3e 100644
--- a/crates/macro_authorization/src/inbound/axum/test.rs
+++ b/crates/macro_authorization/src/inbound/axum/test.rs
@@ -37,10 +37,13 @@ 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";
+const API_KEY_USER_ID: &str = "macro|[email protected]";
+const VALID_USER_API_KEY: &str = "mak_valid";
#[derive(Clone, Debug, Eq, PartialEq)]
enum AuthorizationCall {
Jwt(String),
+ UserApiKey(String),
Bot {
token: String,
bot_scope: BotScope,
@@ -84,6 +87,22 @@ impl MacroAuthorizationService for FakeAuthorizationService {
}
}
+ async fn authorize_user_api_key(
+ &self,
+ api_key: &str,
+ ) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(AuthorizationCall::UserApiKey(api_key.to_string()));
+
+ match api_key {
+ VALID_USER_API_KEY => Ok(user_context(API_KEY_USER_ID, Some(42))),
+ "mak_unavailable" => Err(Report::new(MacroAuthorizationError::Unavailable)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
+ }
+ }
+
async fn authorize_bot(
&self,
token: &str,
@@ -413,6 +432,10 @@ fn bot_request(path: &str, token: &str) -> ::axum::http::request::Builder {
.header(BOT_SCOPE_HEADER, BotScope::User.as_str())
}
+fn user_api_key_request(path: &str, key: &str) -> ::axum::http::request::Builder {
+ request(path).header(USER_API_KEY_HEADER, key)
+}
+
fn empty_body(request: ::axum::http::request::Builder) -> Request<Body> {
request.body(Body::empty()).unwrap()
}
@@ -1231,6 +1254,198 @@ fn bot_header_constants_use_the_resolved_names() {
);
}
+#[test]
+fn user_api_key_header_constant_uses_the_resolved_name() {
+ assert_eq!(USER_API_KEY_HEADER, "x-macro-user-api-key");
+}
+
+#[tokio::test]
+async fn user_api_key_authenticates_as_the_user() {
+ let (router, service) = test_router();
+
+ for path in ["/user", "/required", "/required/user-only"] {
+ let (status, body) = send(
+ &router,
+ empty_body(user_api_key_request(path, VALID_USER_API_KEY)),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "path {path}");
+ assert_eq!(body["acting_entity"], API_KEY_USER_ID);
+ if path != "/required/user-only" {
+ assert_eq!(body["macro_user_id"], API_KEY_USER_ID);
+ }
+ }
+
+ assert_eq!(
+ service.calls(),
+ [
+ AuthorizationCall::UserApiKey(VALID_USER_API_KEY.to_string()),
+ AuthorizationCall::UserApiKey(VALID_USER_API_KEY.to_string()),
+ AuthorizationCall::UserApiKey(VALID_USER_API_KEY.to_string()),
+ ]
+ );
+}
+
+#[tokio::test]
+async fn user_api_key_is_forbidden_for_bot_and_internal_only_policies() {
+ let (router, service) = test_router();
+
+ for path in ["/required/bot-only", "/required/internal-only"] {
+ let (status, body) = send(
+ &router,
+ empty_body(user_api_key_request(path, VALID_USER_API_KEY)),
+ )
+ .await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "path {path}");
+ assert_eq!(body, json!({ "message": "forbidden" }));
+ }
+
+ assert_eq!(
+ service.calls(),
+ [
+ AuthorizationCall::UserApiKey(VALID_USER_API_KEY.to_string()),
+ AuthorizationCall::UserApiKey(VALID_USER_API_KEY.to_string()),
+ ]
+ );
+}
+
+#[tokio::test]
+async fn invalid_user_api_key_is_unauthorized() {
+ let (router, service) = test_router();
+ let (status, body) = send(
+ &router,
+ empty_body(user_api_key_request("/required", "mak_invalid")),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "unauthorized" }));
+ assert_eq!(
+ service.calls(),
+ [AuthorizationCall::UserApiKey("mak_invalid".to_string())]
+ );
+}
+
+#[tokio::test]
+async fn unavailable_user_api_key_lookup_is_internal_server_error() {
+ let (router, service) = test_router();
+ let (status, body) = send(
+ &router,
+ empty_body(user_api_key_request("/required", "mak_unavailable")),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
+ assert_eq!(body, json!({ "message": "internal server error" }));
+ assert_eq!(
+ service.calls(),
+ [AuthorizationCall::UserApiKey("mak_unavailable".to_string())]
+ );
+}
+
+#[tokio::test]
+async fn empty_user_api_key_header_is_unauthorized_without_a_service_call() {
+ let (router, service) = test_router();
+ let (status, body) = send(
+ &router,
+ empty_body(user_api_key_request("/required", " ")),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "unauthorized" }));
+ assert!(service.calls().is_empty());
+}
+
+#[tokio::test]
+async fn user_api_key_combined_with_other_explicit_credentials_is_ambiguous() {
+ let (router, service) = test_router();
+ let requests = [
+ empty_body(
+ user_api_key_request("/required", VALID_USER_API_KEY)
+ .header("authorization", "Bearer valid"),
+ ),
+ empty_body(
+ bot_request("/required", "bot-acting").header(USER_API_KEY_HEADER, VALID_USER_API_KEY),
+ ),
+ empty_body(
+ request("/required")
+ .header(INTERNAL_API_KEY_HEADER, VALID_INTERNAL_KEY)
+ .header(USER_API_KEY_HEADER, VALID_USER_API_KEY),
+ ),
+ empty_body(
+ request("/required?macro-api-token=query")
+ .header(USER_API_KEY_HEADER, VALID_USER_API_KEY),
+ ),
+ ];
+
+ for request in requests {
+ let (status, body) = send(&router, request).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert_eq!(body, json!({ "message": "ambiguous credentials" }));
+ }
+
+ assert!(service.calls().is_empty());
+}
+
+#[tokio::test]
+async fn user_api_key_wins_over_ambient_cookies() {
+ let (router, service) = test_router();
+ let (status, body) = send(
+ &router,
+ empty_body(
+ user_api_key_request("/user", VALID_USER_API_KEY)
+ .header("cookie", format!("{ACCESS_TOKEN_COOKIE}=cookie")),
+ ),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["macro_user_id"], API_KEY_USER_ID);
+ assert_eq!(
+ service.calls(),
+ [AuthorizationCall::UserApiKey(
+ VALID_USER_API_KEY.to_string()
+ )]
+ );
+}
+
+#[tokio::test]
+async fn optional_extractor_rejects_an_invalid_user_api_key() {
+ let (router, service) = test_router();
+ let (status, body) = send(
+ &router,
+ empty_body(user_api_key_request("/optional", "mak_invalid")),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_eq!(body, json!({ "message": "unauthorized" }));
+ assert_eq!(
+ service.calls(),
+ [AuthorizationCall::UserApiKey("mak_invalid".to_string())]
+ );
+}
+
+#[tokio::test]
+async fn optional_extractor_accepts_a_valid_user_api_key() {
+ let (router, service) = test_router();
+ let (status, body) = send(
+ &router,
+ empty_body(user_api_key_request("/optional", VALID_USER_API_KEY)),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body["macro_user_id"], API_KEY_USER_ID);
+ assert_eq!(
+ service.calls(),
+ [AuthorizationCall::UserApiKey(
+ VALID_USER_API_KEY.to_string()
+ )]
+ );
+}
+
#[tokio::test]
async fn acting_user_and_any_principal_accept_bot_with_verified_acting_user() {
let (router, service) = test_router();
diff --git a/crates/macro_authorization/src/inbound/axum/user_api_key.rs b/crates/macro_authorization/src/inbound/axum/user_api_key.rs
new file mode 100644
index 0000000000..291a102f29
--- /dev/null
+++ b/crates/macro_authorization/src/inbound/axum/user_api_key.rs
@@ -0,0 +1,62 @@
+use ::axum::{
+ extract::FromRef,
+ http::{HeaderMap, StatusCode, request::Parts},
+};
+use rootcause::Report;
+
+use crate::{MacroAuthorizationError, MacroAuthorizationService, MacroUserAuthentication};
+
+use super::{
+ MacroAuthorizationRejection, MacroAuthorizationState, authenticated_user, rejection,
+ status_rejection,
+};
+
+/// Header carrying a user API key.
+pub const USER_API_KEY_HEADER: &str = "x-macro-user-api-key";
+
+pub(super) async fn authorize_user_api_key_request<S, Svc>(
+ parts: &Parts,
+ state: &S,
+) -> Result<MacroUserAuthentication, MacroAuthorizationRejection>
+where
+ MacroAuthorizationState<Svc>: FromRef<S>,
+ Svc: MacroAuthorizationService,
+{
+ let api_key = user_api_key(&parts.headers)?;
+ let authorization = MacroAuthorizationState::<Svc>::from_ref(state);
+ let user_context = authorization
+ .service
+ .authorize_user_api_key(&api_key)
+ .await
+ .map_err(user_api_key_authorization_rejection)?;
+
+ authenticated_user(user_context)
+}
+
+fn user_api_key(headers: &HeaderMap) -> Result<String, MacroAuthorizationRejection> {
+ let header = headers
+ .get(USER_API_KEY_HEADER)
+ .ok_or_else(|| rejection("unauthorized"))?;
+ let key = header.to_str().map_err(|_| rejection("unauthorized"))?;
+ if key.trim().is_empty() {
+ return Err(rejection("unauthorized"));
+ }
+
+ Ok(key.to_owned())
+}
+
+fn user_api_key_authorization_rejection(
+ error: Report<MacroAuthorizationError>,
+) -> MacroAuthorizationRejection {
+ let rejection = match error.current_context() {
+ MacroAuthorizationError::CredentialsExpired
+ | MacroAuthorizationError::InvalidCredentials
+ | MacroAuthorizationError::ActingUserNotAuthorized
+ | MacroAuthorizationError::BotScopeNotAuthorized => rejection("unauthorized"),
+ MacroAuthorizationError::Unavailable => {
+ status_rejection(StatusCode::INTERNAL_SERVER_ERROR, "internal server error")
+ }
+ };
+ tracing::error!(error=?error, "user api key authorization failed");
+ rejection
+}
diff --git a/crates/macro_authorization/src/lib.rs b/crates/macro_authorization/src/lib.rs
index 4195bda3d7..72d15d56b2 100644
--- a/crates/macro_authorization/src/lib.rs
+++ b/crates/macro_authorization/src/lib.rs
@@ -1,12 +1,18 @@
#![deny(missing_docs)]
//! Transport-independent authorization services and optional transport adapters.
//!
-//! The domain layer validates user, bot, and internal service credentials and
-//! returns a typed principal with any authenticated or verified acting user.
-//! [`MacroAuthorizationServiceImpl::new`] requires bot authorization to be
-//! configured explicitly, just like internal authorization. Services backed by
-//! MacroDB should use `PgBotAuthorizer`; services that intentionally reject
-//! bot credentials must pass [`NoBotAuthorizer`].
+//! The domain layer validates user, bot, internal service, and user API key
+//! credentials and returns a typed principal with any authenticated or
+//! verified acting user. [`MacroAuthorizationServiceImpl::new`] requires bot
+//! and user API key authorization to be configured explicitly, just like
+//! internal authorization. Services backed by MacroDB should use
+//! `PgBotAuthorizer` and, when they accept user API keys,
+//! `PgUserApiKeyAuthorizer`. Services that intentionally reject bot
+//! credentials must pass [`NoBotAuthorizer`]. User API key authorization is
+//! wired with [`PgUserApiKeyAuthorizer`] in every service that already has a
+//! MacroDB pool. Services without MacroDB (`image_proxy_service`,
+//! `static_file_service`), tests, and schema-only composition roots keep
+//! [`NoUserApiKeyAuthorizer`].
//!
//! # Choosing an Axum extractor
//!
@@ -30,12 +36,12 @@
//! 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,
-//! while access-token cookies are ambient; an explicit credential wins over a
-//! cookie. Local-auth fallback and cookies are considered only when no explicit
-//! credential is present. A valid principal not admitted by the selected policy
-//! is rejected with `403 Forbidden`.
+//! (internal key, bot token, user API key, or user query/bearer) with
+//! `400 Bad Request` rather than choosing a principal. Query and bearer
+//! credentials are one user type, while access-token cookies are ambient; an
+//! explicit credential wins over a cookie. Local-auth fallback and cookies are
+//! considered only when no explicit credential is present. A valid principal
+//! not admitted by the selected policy is rejected with `403 Forbidden`.
//!
//! These extractors authenticate the caller; they do not decide whether that
//! caller may act on a particular entity. Entity authorization and business
@@ -55,13 +61,15 @@ pub use domain::{
models::{
BotActingUserClaims, BotAuthentication, BotAuthorizationOwner, BotScope,
BotTokenAuthorization, InternalAuthConfig, InternalIdentityClaims, MacroAuthorization,
- MacroAuthorizationError, MacroUserAuthentication, ResolvedBotActingUser, ValidatedIdentity,
+ MacroAuthorizationError, MacroUserAuthentication, ResolvedApiKeyUser,
+ ResolvedBotActingUser, ValidatedIdentity,
},
ports::{
BotAuthorizationRepo, BotAuthorizer, JwtValidator, MacroAuthorizationService,
- NoBotAuthorizer,
+ NoBotAuthorizer, NoUserApiKeyAuthorizer, UserApiKeyAuthorizationRepo, UserApiKeyAuthorizer,
},
service::MacroAuthorizationServiceImpl,
+ user_api_key_authorizer::UserApiKeyAuthorizerService,
};
/// Service-backed Axum authorization extractors, state, headers, and rejection type.
#[allow(deprecated)]
@@ -75,13 +83,15 @@ pub use inbound::{
InternalEntity, InternalOnly, LEGACY_DSS_INTERNAL_API_KEY_HEADER,
LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER, MacroAuthorizationExtractor,
MacroAuthorizationRejection, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
- UserOnly, UserOrBot, UserOrBotAuthorization, UserOrBotEntity, UserOrInternal,
- UserOrInternalAuthorization, UserOrInternalCaller, UserOrInternalEntity, UserOrInternalService,
- UserOrInternalServiceAuthorization,
+ USER_API_KEY_HEADER, UserOnly, UserOrBot, UserOrBotAuthorization, UserOrBotEntity,
+ UserOrInternal, UserOrInternalAuthorization, UserOrInternalCaller, UserOrInternalEntity,
+ UserOrInternalService, UserOrInternalServiceAuthorization,
};
/// JWT validation adapters for user-authenticated and internal-only services.
#[cfg(feature = "outbound")]
pub use outbound::{MacroAuthJwtValidator, NoopMacroAuthJwtValidator};
/// PostgreSQL bot authorization repository and concrete authorizer.
#[cfg(feature = "postgres")]
-pub use outbound::{PgBotAuthorizationRepo, PgBotAuthorizer};
+pub use outbound::{
+ PgBotAuthorizationRepo, PgBotAuthorizer, PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,
+};
diff --git a/crates/macro_authorization/src/outbound.rs b/crates/macro_authorization/src/outbound.rs
index 59ddf0e0ca..12ba7ef72f 100644
--- a/crates/macro_authorization/src/outbound.rs
+++ b/crates/macro_authorization/src/outbound.rs
@@ -9,6 +9,9 @@ pub mod noop;
/// PostgreSQL facts for bot authorization.
#[cfg(feature = "postgres")]
pub mod pg_bot_authorization;
+/// PostgreSQL facts for user API key authorization.
+#[cfg(feature = "postgres")]
+pub mod pg_user_api_key_authorization;
/// JWT validator backed by the shared `macro_auth` implementation.
#[cfg(feature = "outbound")]
@@ -19,3 +22,6 @@ pub use noop::NoopMacroAuthJwtValidator;
/// PostgreSQL bot authorization repository and concrete authorizer.
#[cfg(feature = "postgres")]
pub use pg_bot_authorization::{PgBotAuthorizationRepo, PgBotAuthorizer};
+/// PostgreSQL user API key authorization repository and concrete authorizer.
+#[cfg(feature = "postgres")]
+pub use pg_user_api_key_authorization::{PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer};
diff --git a/crates/macro_authorization/src/outbound/pg_user_api_key_authorization.rs b/crates/macro_authorization/src/outbound/pg_user_api_key_authorization.rs
new file mode 100644
index 0000000000..5352306aa5
--- /dev/null
+++ b/crates/macro_authorization/src/outbound/pg_user_api_key_authorization.rs
@@ -0,0 +1,99 @@
+//! PostgreSQL user API key authorization facts.
+
+#[cfg(test)]
+mod test;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use sha2::{Digest, Sha256};
+use sqlx::PgPool;
+use thiserror::Error;
+
+use crate::domain::{models::ResolvedApiKeyUser, ports::UserApiKeyAuthorizationRepo};
+
+/// SHA-256 of a raw user API key's UTF-8 bytes.
+///
+/// Must stay identical to `user_api_key::hash_key` and `bot_token::hash_token`.
+fn hash_user_api_key(api_key: &str) -> [u8; 32] {
+ Sha256::digest(api_key.as_bytes()).into()
+}
+
+/// PostgreSQL facts required by user API key authorization policy.
+#[derive(Clone, Debug)]
+pub struct PgUserApiKeyAuthorizationRepo {
+ pool: PgPool,
+}
+
+impl PgUserApiKeyAuthorizationRepo {
+ /// Create a PostgreSQL user API key authorization repository.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+/// User API key authorizer backed by PostgreSQL.
+pub type PgUserApiKeyAuthorizer =
+ crate::domain::user_api_key_authorizer::UserApiKeyAuthorizerService<
+ PgUserApiKeyAuthorizationRepo,
+ >;
+
+/// PostgreSQL user API key authorization repository error.
+#[derive(Debug, Error)]
+pub enum PgUserApiKeyAuthorizationRepoError {
+ /// A database operation failed.
+ #[error("user api key authorization database operation failed")]
+ Database(#[from] sqlx::Error),
+ /// Persisted user data could not be represented as a Macro user identifier.
+ #[error("invalid persisted user identity")]
+ InvalidUserIdentity,
+}
+
+#[derive(Debug)]
+struct ApiKeyUserRow {
+ id: String,
+ fusion_user_id: Option<uuid::Uuid>,
+ organization_id: Option<i32>,
+}
+
+impl TryFrom<ApiKeyUserRow> for ResolvedApiKeyUser {
+ type Error = PgUserApiKeyAuthorizationRepoError;
+
+ fn try_from(row: ApiKeyUserRow) -> Result<Self, Self::Error> {
+ let macro_user_id = MacroUserIdStr::try_from(row.id)
+ .map_err(|_| PgUserApiKeyAuthorizationRepoError::InvalidUserIdentity)?;
+ let fusion_user_id = row
+ .fusion_user_id
+ .ok_or(PgUserApiKeyAuthorizationRepoError::InvalidUserIdentity)?
+ .to_string();
+
+ Ok(Self {
+ macro_user_id,
+ fusion_user_id,
+ organization_id: row.organization_id,
+ })
+ }
+}
+
+impl UserApiKeyAuthorizationRepo for PgUserApiKeyAuthorizationRepo {
+ type Err = PgUserApiKeyAuthorizationRepoError;
+
+ async fn find_key_owner(&self, api_key: &str) -> Result<Option<ResolvedApiKeyUser>, Self::Err> {
+ let key_hash = hash_user_api_key(api_key);
+ let row = sqlx::query_as!(
+ ApiKeyUserRow,
+ r#"
+ SELECT
+ u.id,
+ u.macro_user_id AS "fusion_user_id?",
+ u."organizationId" AS "organization_id?"
+ FROM "UserApiKey" k
+ JOIN "User" u ON u.id = k.user_id
+ WHERE k.hash = $1
+ "#,
+ &key_hash[..],
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+
+ row.map(ResolvedApiKeyUser::try_from).transpose()
+ }
+}
diff --git a/crates/macro_authorization/src/outbound/pg_user_api_key_authorization/test.rs b/crates/macro_authorization/src/outbound/pg_user_api_key_authorization/test.rs
new file mode 100644
index 0000000000..0f079b573a
--- /dev/null
+++ b/crates/macro_authorization/src/outbound/pg_user_api_key_authorization/test.rs
@@ -0,0 +1,76 @@
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use super::*;
+use crate::domain::ports::UserApiKeyAuthorizationRepo as _;
+
+const API_KEY: &str = "mak_authorization_test_secret";
+const USER_EMAIL: &str = "[email protected]";
+const USER_ID: &str = "macro|[email protected]";
+
+async fn insert_user_and_key(pool: &PgPool, user_id: &str, email: &str, key: &str) -> Uuid {
+ let macro_user_id = Uuid::new_v4();
+ sqlx::query!(
+ r#"
+ INSERT INTO macro_user (id, username, email, stripe_customer_id)
+ VALUES ($1, $2, $2, $3)
+ "#,
+ macro_user_id,
+ email,
+ format!("stripe_{macro_user_id}"),
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ r#"
+ INSERT INTO "User" (id, email, macro_user_id)
+ VALUES ($1, $2, $3)
+ "#,
+ user_id,
+ email,
+ macro_user_id,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ r#"
+ INSERT INTO "UserApiKey" (id, name, user_id, hash)
+ VALUES ($1, $2, $3, $4)
+ "#,
+ Uuid::new_v4(),
+ "test key",
+ user_id,
+ &hash_user_api_key(key)[..],
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ macro_user_id
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn finds_owner_from_user_id_and_macro_user_id(pool: PgPool) {
+ let fusion_user_id = insert_user_and_key(&pool, USER_ID, USER_EMAIL, API_KEY).await;
+ let repo = PgUserApiKeyAuthorizationRepo::new(pool);
+
+ let owner = repo
+ .find_key_owner(API_KEY)
+ .await
+ .unwrap()
+ .expect("valid key");
+
+ assert_eq!(owner.macro_user_id.as_ref(), USER_ID);
+ assert_eq!(owner.fusion_user_id, fusion_user_id.to_string());
+ assert_eq!(owner.organization_id, None);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn unknown_key_returns_none(pool: PgPool) {
+ insert_user_and_key(&pool, USER_ID, USER_EMAIL, API_KEY).await;
+ let repo = PgUserApiKeyAuthorizationRepo::new(pool);
+
+ assert!(repo.find_key_owner("mak_unknown").await.unwrap().is_none());
+}
diff --git a/crates/properties/src/inbound/axum_router/test.rs b/crates/properties/src/inbound/axum_router/test.rs
index 4d7397bdaa..b1cffea412 100644
--- a/crates/properties/src/inbound/axum_router/test.rs
+++ b/crates/properties/src/inbound/axum_router/test.rs
@@ -251,6 +251,7 @@ fn authorization_state() -> MacroAuthorizationState<TestAuthorizationService> {
default_user_id: Some(DEFAULT_INTERNAL_USER_ID.to_string()),
},
macro_authorization::NoBotAuthorizer,
+ macro_authorization::NoUserApiKeyAuthorizer,
);
MacroAuthorizationState::new(Arc::new(service))
}
diff --git a/crates/user_api_key/src/domain/ports.rs b/crates/user_api_key/src/domain/ports.rs
index 4a4b87f9d4..446dca0c1f 100644
--- a/crates/user_api_key/src/domain/ports.rs
+++ b/crates/user_api_key/src/domain/ports.rs
@@ -42,7 +42,8 @@ pub trait UserApiKeysRepo: Send + Sync + 'static {
id: UserApiKeyId,
) -> impl Future<Output = Result<bool, Self::Err>> + Send;
- /// Owner of a key, for the future authenticate-by-key use case.
+ /// Owner of a key. Authenticate-by-key is implemented by
+ /// `macro_authorization`'s `PgUserApiKeyAuthorizationRepo`.
///
/// Looks up by SHA-256 of the presented secret. Not exposed through
/// [UserApiKeyService] in this slice.
diff --git a/crates/user_api_key/src/lib.rs b/crates/user_api_key/src/lib.rs
index 956c42b60c..5bbfc54e2f 100644
--- a/crates/user_api_key/src/lib.rs
+++ b/crates/user_api_key/src/lib.rs
@@ -3,8 +3,9 @@
//! hexagonal architecture pattern.
//!
//! Keys are user-owned rows in `"UserApiKey"`. This crate owns that table's
-//! lifecycle. Authenticating a request *with* a key is a later slice; the
-//! repository port already exposes a lookup-by-key method for that use case.
+//! lifecycle. Authenticating a request *with* a key lives in
+//! `macro_authorization` (`x-macro-user-api-key`). The repository port still
+//! exposes a lookup-by-key method for that use case.
//!
//! # Architecture
//!
diff --git a/crates/user_api_key/src/outbound/pg_user_api_keys_repo/tests.rs b/crates/user_api_key/src/outbound/pg_user_api_keys_repo/tests.rs
index 444ffe8d37..a974fe85c7 100644
--- a/crates/user_api_key/src/outbound/pg_user_api_keys_repo/tests.rs
+++ b/crates/user_api_key/src/outbound/pg_user_api_keys_repo/tests.rs
@@ -81,6 +81,37 @@ async fn insert_and_list_return_id_name_and_created_at_scoped_per_user(pool: PgP
assert!(!key_column_exists);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn user_scoped_reads_use_composite_created_at_index(pool: PgPool) {
+ let indexes: Vec<(String, String)> = sqlx::query_as(
+ r#"
+ SELECT indexname, indexdef
+ FROM pg_indexes
+ WHERE tablename = 'UserApiKey'
+ ORDER BY indexname
+ "#,
+ )
+ .fetch_all(&pool)
+ .await
+ .expect("index catalog should load");
+
+ let composite = indexes
+ .iter()
+ .find(|(name, _)| name == "UserApiKey_user_id_created_at_id_idx");
+ let (name, definition) = composite.expect("user-scoped list/count index should exist");
+ assert_eq!(name, "UserApiKey_user_id_created_at_id_idx");
+ assert!(
+ definition.contains("(user_id, created_at DESC, id DESC)"),
+ "composite index should match list/count order: {definition}"
+ );
+ assert!(
+ indexes
+ .iter()
+ .all(|(index_name, _)| index_name != "UserApiKey_user_id_idx"),
+ "user_id-only index is redundant with the composite prefix"
+ );
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn count_keys_counts_only_caller_rows(pool: PgPool) {
insert_user(&pool, USER_A).await;
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 6c85e55653..e64412d357 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -77,6 +77,7 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_authorization::{
InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,
MacroAuthorizationState, PgBotAuthorizationRepo, PgBotAuthorizer,
+ PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,
};
use macro_entrypoint::{MacroEntrypoint, shutdown_signal};
use macro_event_broker::{
@@ -420,6 +421,7 @@ async fn run() -> anyhow::Result<()> {
default_user_id: None,
},
PgBotAuthorizer::new(PgBotAuthorizationRepo::new(pool.clone())),
+ PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(pool.clone())),
);
let read_state = AgentSessionRouterState::new(
AgentSessionServiceImpl::new(
diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.toml
index a91600777e..c4c27c97e0 100644
--- a/services/authentication_service/Cargo.toml
+++ b/services/authentication_service/Cargo.toml
@@ -79,7 +79,9 @@ jsonwebtoken = { workspace = true }
last_online_tracker = { path = "../../crates/last_online_tracker" }
loops_client = { path = "../../crates/loops_client" }
macro_auth = { path = "../../crates/macro_auth" }
-macro_authorization = { path = "../../crates/macro_authorization" }
+macro_authorization = { path = "../../crates/macro_authorization", features = [
+ "postgres",
+] }
macro_aws_config = { path = "../../crates/macro_aws_config" }
macro_cache_client = { path = "../../crates/macro_cache_client", default-features = false, features = [
"auth",
diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rs
index 7480540418..bcab0e67c3 100644
--- a/services/authentication_service/src/main.rs
+++ b/services/authentication_service/src/main.rs
@@ -34,7 +34,10 @@ use github::{
};
use loops_client::LoopsClient;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
-use macro_authorization::{InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationState};
+use macro_authorization::{
+ InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationState,
+ PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,
+};
use macro_entrypoint::MacroEntrypoint;
use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};
use macro_service_urls::{
@@ -245,6 +248,7 @@ async fn main() -> anyhow::Result<()> {
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(db.clone())),
)));
let redis_client = redis::Client::open(config.redis_uri.to_string().as_str())
diff --git a/services/connection_gateway/Cargo.toml b/services/connection_gateway/Cargo.toml
index 117b0c1839..78ef93496e 100644
--- a/services/connection_gateway/Cargo.toml
+++ b/services/connection_gateway/Cargo.toml
@@ -50,7 +50,9 @@ http-body-util = { workspace = true }
itertools = { workspace = true }
last_online_tracker = { path = "../../crates/last_online_tracker" }
macro_auth = { path = "../../crates/macro_auth" }
-macro_authorization = { path = "../../crates/macro_authorization" }
+macro_authorization = { path = "../../crates/macro_authorization", features = [
+ "postgres",
+] }
macro_user_id = { path = "../../crates/macro_user_id" }
macro_aws_config = { path = "../../crates/macro_aws_config" }
macro_config = { path = "../../crates/macro_config" }
diff --git a/services/connection_gateway/src/api/test.rs b/services/connection_gateway/src/api/test.rs
index ca25a02e78..31fd06a116 100644
--- a/services/connection_gateway/src/api/test.rs
+++ b/services/connection_gateway/src/api/test.rs
@@ -73,6 +73,7 @@ fn test_state() -> TestState {
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ macro_authorization::NoUserApiKeyAuthorizer,
);
TestState {
diff --git a/services/connection_gateway/src/main.rs b/services/connection_gateway/src/main.rs
index 736b418520..550ead31bc 100644
--- a/services/connection_gateway/src/main.rs
+++ b/services/connection_gateway/src/main.rs
@@ -32,7 +32,10 @@ use last_online_tracker::{
outbound::{redis::RedisLastOnlineRepo, time::DefaultTime as LastOnlineDefaultTime},
};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
-use macro_authorization::{InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationState};
+use macro_authorization::{
+ InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationState,
+ PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,
+};
use macro_entrypoint::MacroEntrypoint;
use macro_env::Environment;
use macro_tower_layers::MacroRequestIdAndTracingLayer;
@@ -130,6 +133,7 @@ async fn main() -> Result<()> {
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(pgpool.clone())),
)));
let app = router(AppState {
diff --git a/services/contacts_service/Cargo.toml b/services/contacts_service/Cargo.toml
index c65337b0e5..806e2de842 100644
--- a/services/contacts_service/Cargo.toml
+++ b/services/contacts_service/Cargo.toml
@@ -24,7 +24,9 @@ aws-sdk-sqs = { workspace = true }
axum = { workspace = true }
contacts = { path = "../../crates/contacts", features = ["axum"] }
macro_auth = { path = "../../crates/macro_auth" }
-macro_authorization = { path = "../../crates/macro_authorization" }
+macro_authorization = { path = "../../crates/macro_authorization", features = [
+ "postgres",
+] }
macro_aws_config = { path = "../../crates/macro_aws_config" }
macro_cors = { path = "../../crates/macro_cors" }
macro_entrypoint = { path = "../../crates/macro_entrypoint" }
diff --git a/services/contacts_service/src/main.rs b/services/contacts_service/src/main.rs
index f33f91dd00..798ba44d00 100644
--- a/services/contacts_service/src/main.rs
+++ b/services/contacts_service/src/main.rs
@@ -12,7 +12,7 @@ use contacts::outbound::gateway::ConnectionGatewayNotifier;
use contacts::outbound::repository::DbContactsRepository;
use macro_authorization::{
InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,
- MacroAuthorizationState,
+ MacroAuthorizationState, PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,
};
use macro_entrypoint::MacroEntrypoint;
use macro_service_urls::ConnectionGatewayUrl;
@@ -116,6 +116,7 @@ async fn main() -> anyhow::Result<()> {
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(db.clone())),
);
let authorization_state = MacroAuthorizationState::new(Arc::new(authorization_service));
diff --git a/services/convert_service/Cargo.toml b/services/convert_service/Cargo.toml
index 6cd2c615db..3b0326ce00 100644
--- a/services/convert_service/Cargo.toml
+++ b/services/convert_service/Cargo.toml
@@ -27,7 +27,9 @@ futures = { workspace = true }
http-body-util = { workspace = true }
lambda_client = { path = "../../crates/lambda_client" }
macro_auth = { path = "../../crates/macro_auth" }
-macro_authorization = { path = "../../crates/macro_authorization" }
+macro_authorization = { path = "../../crates/macro_authorization", features = [
+ "postgres",
+] }
macro_aws_config = { path = "../../crates/macro_aws_config", features = ["s3"] }
macro_cors = { path = "../../crates/macro_cors" }
macro_config = { path = "../../crates/macro_config" }
diff --git a/services/convert_service/src/main.rs b/services/convert_service/src/main.rs
index de7ff38466..5c05941d2c 100644
--- a/services/convert_service/src/main.rs
+++ b/services/convert_service/src/main.rs
@@ -2,7 +2,10 @@
use crate::api::context::{ApiContext, AuthorizationService};
use anyhow::Context;
use config::{Config, Environment};
-use macro_authorization::{InternalAuthConfig, MacroAuthorizationState, NoopMacroAuthJwtValidator};
+use macro_authorization::{
+ InternalAuthConfig, MacroAuthorizationState, NoopMacroAuthJwtValidator,
+ PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,
+};
use macro_entrypoint::MacroEntrypoint;
use process::runner::run_worker;
use sqlx::postgres::PgPoolOptions;
@@ -67,6 +70,13 @@ async fn main() -> anyhow::Result<()> {
let aws_config = macro_aws_config::get_macro_aws_config().await;
+ let db = PgPoolOptions::new()
+ .min_connections(1)
+ .max_connections(5)
+ .connect(&config.database_url)
+ .await
+ .context("could not connect to db")?;
+
let authorization_state = MacroAuthorizationState::new(Arc::new(AuthorizationService::new(
NoopMacroAuthJwtValidator, // we only have internal calls in this service.
InternalAuthConfig {
@@ -74,15 +84,9 @@ async fn main() -> anyhow::Result<()> {
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(db.clone())),
)));
- let db = PgPoolOptions::new()
- .min_connections(1)
- .max_connections(5)
- .connect(&config.database_url)
- .await
- .context("could not connect to db")?;
-
tracing::trace!("initialized config");
let queue_aws_config = macro_aws_config::get_macro_aws_config().await;
diff --git a/services/document_cognition_service/Cargo.toml b/services/document_cognition_service/Cargo.toml
index 5ede1caef2..76166595ac 100644
--- a/services/document_cognition_service/Cargo.toml
+++ b/services/document_cognition_service/Cargo.toml
@@ -77,7 +77,9 @@ macro_env = { path = "../../crates/macro_env" }
macro_env_var = { path = "../../crates/macro_env_var" }
macro_event_broker = { path = "../../crates/macro_event_broker" }
macro_queues = { path = "../../crates/macro_queues" }
-macro_authorization = { path = "../../crates/macro_authorization" }
+macro_authorization = { path = "../../crates/macro_authorization", features = [
+ "postgres",
+] }
macro_middleware = { path = "../../crates/macro_middleware", default-features = false, features = [
"cloud_storage",
] }
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 2d7d62c9cc..1ac9daabec 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -497,6 +497,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ macro_authorization::NoUserApiKeyAuthorizer,
)));
let user_permissions_service = Arc::new(
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index c869a6b3ab..3e1a1b5bc7 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -30,7 +30,7 @@ use frecency::outbound::postgres::FrecencyPgStorage;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_authorization::{
InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,
- MacroAuthorizationState,
+ MacroAuthorizationState, PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,
};
use macro_entrypoint::MacroEntrypoint;
use macro_service_urls::{
@@ -152,6 +152,7 @@ async fn main() -> anyhow::Result<()> {
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(db.clone())),
)));
let lexical_client = Arc::new(lexical_client::LexicalClient::new(
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 36d149616c..fe9f4eec60 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -90,6 +90,7 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_authorization::{
InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,
MacroAuthorizationState, PgBotAuthorizationRepo, PgBotAuthorizer,
+ PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,
};
use macro_entrypoint::MacroEntrypoint;
use macro_env_var::maybe_env_vars;
@@ -327,6 +328,7 @@ async fn run() -> anyhow::Result<()> {
default_user_id: Some(MACRO_INTERNAL_USER_ID.to_string()),
},
PgBotAuthorizer::new(PgBotAuthorizationRepo::new(db.clone())),
+ PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(db.clone())),
);
let authorization_state = MacroAuthorizationState::new(Arc::new(authorization_service));
diff --git a/services/email_service/Cargo.toml b/services/email_service/Cargo.toml
index 20788a13d7..ff14c55cbe 100644
--- a/services/email_service/Cargo.toml
+++ b/services/email_service/Cargo.toml
@@ -113,7 +113,9 @@ infer = "0.19.0"
item_filters = { path = "../../crates/item_filters" }
lol_html = { workspace = true }
macro_auth = { path = "../../crates/macro_auth" }
-macro_authorization = { path = "../../crates/macro_authorization" }
+macro_authorization = { path = "../../crates/macro_authorization", features = [
+ "postgres",
+] }
macro_cors = { path = "../../crates/macro_cors" }
macro_config = { path = "../../crates/macro_config" }
macro_db_client = { path = "../../crates/macro_db_client" }
diff --git a/services/email_service/src/main.rs b/services/email_service/src/main.rs
index 55c1b08fd8..d8b6807189 100644
--- a/services/email_service/src/main.rs
+++ b/services/email_service/src/main.rs
@@ -23,7 +23,10 @@ use email_service::pubsub::calendar_backfill_adapters::RedisCalendarRequestGate;
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
-use macro_authorization::{InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationState};
+use macro_authorization::{
+ InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationState,
+ PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,
+};
use macro_entrypoint::MacroEntrypoint;
use macro_env::Environment;
use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};
@@ -142,6 +145,7 @@ async fn main() -> anyhow::Result<()> {
default_user_id: Some("macro|[email protected]".to_string()),
},
macro_authorization::NoBotAuthorizer,
+ PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(db.clone())),
)));
let sqs_client = Arc::new(sqs_client);
diff --git a/services/image_proxy_service/src/api/test.rs b/services/image_proxy_service/src/api/test.rs
index 0e6cd29c8b..68603ed3f1 100644
--- a/services/image_proxy_service/src/api/test.rs
+++ b/services/image_proxy_service/src/api/test.rs
@@ -30,6 +30,7 @@ fn test_context() -> ApiContext {
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ macro_authorization::NoUserApiKeyAuthorizer,
);
ApiContext {
diff --git a/services/image_proxy_service/src/main.rs b/services/image_proxy_service/src/main.rs
index d024528810..35104ad370 100644
--- a/services/image_proxy_service/src/main.rs
+++ b/services/image_proxy_service/src/main.rs
@@ -35,6 +35,7 @@ async fn main() -> anyhow::Result<()> {
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ macro_authorization::NoUserApiKeyAuthorizer,
);
let authorization_state = MacroAuthorizationState::new(Arc::new(authorization_service));
diff --git a/services/notification_service/Cargo.toml b/services/notification_service/Cargo.toml
index 1ad3c37dc8..308ed6651f 100644
--- a/services/notification_service/Cargo.toml
+++ b/services/notification_service/Cargo.toml
@@ -33,7 +33,9 @@ http-body-util = { workspace = true }
itertools = { workspace = true }
last_online_tracker = { path = "../../crates/last_online_tracker" }
macro_auth = { path = "../../crates/macro_auth" }
-macro_authorization = { path = "../../crates/macro_authorization" }
+macro_authorization = { path = "../../crates/macro_authorization", features = [
+ "postgres",
+] }
macro_aws_config = { path = "../../crates/macro_aws_config" }
macro_config = { path = "../../crates/macro_config" }
macro_cors = { path = "../../crates/macro_cors" }
diff --git a/services/notification_service/src/main.rs b/services/notification_service/src/main.rs
index 48871201f8..cc5a7bcc03 100644
--- a/services/notification_service/src/main.rs
+++ b/services/notification_service/src/main.rs
@@ -20,7 +20,10 @@ use config::Config;
use email_formatting::EmailDigestNotification;
use hmac::{Hmac, Mac};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
-use macro_authorization::{InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationState};
+use macro_authorization::{
+ InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationState,
+ PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,
+};
use macro_entrypoint::MacroEntrypoint;
use macro_env::Environment;
use macro_event_broker::{GlobalSpawner, KafkaEventPublisher, MacroEventBrokerService};
@@ -142,6 +145,7 @@ pub async fn main() -> anyhow::Result<()> {
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(db.clone())),
)));
let notification_repository =
diff --git a/services/scheduled_action/Cargo.toml b/services/scheduled_action/Cargo.toml
index 07608e2192..fe7911299f 100644
--- a/services/scheduled_action/Cargo.toml
+++ b/services/scheduled_action/Cargo.toml
@@ -26,7 +26,9 @@ serde_json = { workspace = true }
macro_env_var = { path = "../../crates/macro_env_var" }
macro_queues = { path = "../../crates/macro_queues" }
macro_config = { path = "../../crates/macro_config" }
-macro_authorization = { path = "../../crates/macro_authorization" }
+macro_authorization = { path = "../../crates/macro_authorization", features = [
+ "postgres",
+] }
database_env_vars = { path = "../../crates/database_env_vars" }
doppler-config = { workspace = true }
sqlx = { workspace = true }
diff --git a/services/scheduled_action/src/bins/service.rs b/services/scheduled_action/src/bins/service.rs
index be9fbe9301..d7b89ea412 100644
--- a/services/scheduled_action/src/bins/service.rs
+++ b/services/scheduled_action/src/bins/service.rs
@@ -8,7 +8,7 @@ use connection_gateway_client::client::ConnectionGatewayClient;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_authorization::{
InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,
- MacroAuthorizationState,
+ MacroAuthorizationState, PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,
};
use macro_entrypoint::MacroEntrypoint;
use macro_service_urls::ConnectionGatewayUrl;
@@ -121,6 +121,7 @@ async fn main() -> Result<()> {
default_user_id: None,
},
macro_authorization::NoBotAuthorizer,
+ PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(db.clone())),
);
let authorization_state = MacroAuthorizationState::new(Arc::new(authorization_service));
diff --git a/services/search_processing_service/Cargo.toml b/services/search_processing_service/Cargo.toml
index dcc5695213..4752326b19 100644
--- a/services/search_processing_service/Cargo.toml
+++ b/services/search_processing_service/Cargo.toml
@@ -59,7 +59,9 @@ http-body-util = { workspace = true }
kafka_util = { path = "../../crates/kafka_util", optional = true }
lexical_client = { path = "../../crates/lexical_client" }
macro_auth = { path = "../../crates/macro_auth" }
-macro_authorization = { path = "../../crates/macro_authorization" }
+macro_authorization = { path = "../../crates/macro_authorization", features = [
+ "postgres",
+] }
macro_aws_config = { path = "../../crates/macro_aws_config", features = ["s3"] }
macro_cors = { path = "../../crates/macro_cors" }
macro_config = { path = "../../crates/macro_config" }
diff --git a/services/search_processing_service/src/main.rs b/services/search_processing_service/src/main.rs
index 827a988da5..23b45680b1 100644
--- a/services/search_processing_service/src/main.rs
+++ b/services/search_processing_service/src/main.rs
@@ -16,7 +16,10 @@ use crate::{
use anyhow::Context;
use config::{Config, Environment};
use lexical_client::LexicalClient;
-use macro_authorization::{InternalAuthConfig, MacroAuthorizationState, NoopMacroAuthJwtValidator};
+use macro_authorization::{
+ InternalAuthConfig, MacroAuthorizationState, NoopMacroAuthJwtValidator,
+ PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,
+};
use macro_entrypoint::MacroEntrypoint;
use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};
use opensearch_client::OpensearchClient;
@@ -146,22 +149,6 @@ async fn main() -> anyhow::Result<()> {
let config = Config::from_env().context("expected to be able to generate config")?;
tracing::trace!("initialized config");
- let authorization_state = MacroAuthorizationState::new(Arc::new(AuthorizationService::new(
- NoopMacroAuthJwtValidator, // we only have internal calls in this service.
- InternalAuthConfig {
- api_key: config.internal_api_key.to_string(),
- default_user_id: None,
- },
- macro_authorization::NoBotAuthorizer,
- )));
-
- let aws_config = macro_aws_config::get_macro_aws_config().await;
- let search_event_queue = macro_queues::SearchEventQueue::new();
- let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config))
- .search_event_queue(&search_event_queue);
-
- let s3_client = Arc::new(s3_client::S3::new(macro_aws_config::s3_client().await));
-
let (min_connections, max_connections): (u32, u32) = match config.environment {
Environment::Production => (5, 50),
Environment::Develop => (1, 25),
@@ -181,6 +168,23 @@ async fn main() -> anyhow::Result<()> {
"initialized db connection"
);
+ let authorization_state = MacroAuthorizationState::new(Arc::new(AuthorizationService::new(
+ NoopMacroAuthJwtValidator, // we only have internal calls in this service.
+ InternalAuthConfig {
+ api_key: config.internal_api_key.to_string(),
+ default_user_id: None,
+ },
+ macro_authorization::NoBotAuthorizer,
+ PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(db.clone())),
+ )));
+
+ let aws_config = macro_aws_config::get_macro_aws_config().await;
+ let search_event_queue = macro_queues::SearchEventQueue::new();
+ let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config))
+ .search_event_queue(&search_event_queue);
+
+ let s3_client = Arc::new(s3_client::S3::new(macro_aws_config::s3_client().await));
+
let opensearch_client = Arc::new(
OpensearchClient::new(
config.opensearch_url.to_string(),
diff --git a/services/static_file_service/src/api.rs b/services/static_file_service/src/api.rs
index 8194c3c1ca..868207b9c6 100644
--- a/services/static_file_service/src/api.rs
+++ b/services/static_file_service/src/api.rs
@@ -53,6 +53,7 @@ pub async fn setup_and_serve(
default_user_id: Some(MACRO_INTERNAL_USER_ID.to_string()),
},
macro_authorization::NoBotAuthorizer,
+ macro_authorization::NoUserApiKeyAuthorizer,
)));
let state = AppState {