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.

21.7 KB
Raw Blame
use std::sync::Arc;

use super::*;
use crate::{
    domain::models::{
        BotAccessScope, BotReceiptScope, EditAccessLevel, EntityAccessAuth, ViewAccessLevel,
    },
    inbound::axum_extractors::test_support::{
        BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BOT_TEAM_ID, BotAccessCall,
        FakeEntityAccessService, MALFORMED_SYSTEM_BOT_TOKEN, VALID_BOT_TOKEN,
        malformed_system_bot_authentication, user_scoped_bot_authentication,
        valid_bot_authentication,
    },
};
use axum::{
    body::{Body, to_bytes},
    extract::{FromRef, FromRequestParts},
    http::{Request, StatusCode, header},
    response::IntoResponse,
};
use macro_authorization::{
    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::{
    LEGACY_DSS_INTERNAL_API_KEY_HEADER, LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER,
};
use macro_user_id::user_id::MacroUserIdStr;
use model::document::DocumentBasic;
use model_owner::Owner;
use model_user::UserContext;
use rootcause::Report;

const DOCUMENT_ID: &str = "document-1";
const OWNER_ID: &str = "macro|[email protected]";
const USER_ID: &str = "macro|[email protected]";
const STANDARD_ACT_AS_ID: &str = "macro|[email protected]";
const LEGACY_ACT_AS_ID: &str = "macro|[email protected]";
const DEFAULT_INTERNAL_ID: &str = "macro|[email protected]";
const INTERNAL_KEY: &str = "valid-internal-key";
const OWNER_ACTING_BOT_TOKEN: &str = "owner-acting-bot-token";

#[derive(Clone, Debug, Default)]
struct FakeAuthorizationService {
    default_internal_user_id: Option<String>,
}

impl FakeAuthorizationService {
    fn with_default_internal_user() -> Self {
        Self {
            default_internal_user_id: Some(DEFAULT_INTERNAL_ID.to_string()),
        }
    }
}

impl MacroAuthorizationService for FakeAuthorizationService {
    async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
        match jwt {
            "owner" => Ok(user_context(OWNER_ID)),
            "valid" => Ok(user_context(USER_ID)),
            "expired" => Err(Report::new(MacroAuthorizationError::CredentialsExpired)),
            _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
        }
    }

    async fn authorize_identity(
        &self,
        jwt: &str,
    ) -> Result<macro_authorization::ValidatedCredential, Report<MacroAuthorizationError>> {
        self.authorize(jwt)
            .await
            .map(macro_authorization::ValidatedCredential::session)
    }

    async fn authorize_bot(
        &self,
        token: &str,
        bot_scope: BotScope,
        _claims: Option<BotActingUserClaims>,
    ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
        match token {
            VALID_BOT_TOKEN => Ok(valid_bot_authentication(bot_scope)),
            MALFORMED_SYSTEM_BOT_TOKEN => Ok(malformed_system_bot_authentication(bot_scope)),
            OWNER_ACTING_BOT_TOKEN => Ok(owner_scoped_bot_authentication()),
            _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
        }
    }

    async fn authorize_internal(
        &self,
        provided_key: &str,
        claims: InternalIdentityClaims,
    ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {
        if provided_key != INTERNAL_KEY {
            return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
        }

        Ok(claims
            .user_id
            .or_else(|| self.default_internal_user_id.clone())
            .map(|user_id| user_context(&user_id)))
    }
}

struct TestState {
    entity_access: Arc<FakeEntityAccessService>,
    authorization: MacroAuthorizationState<FakeAuthorizationService>,
}

impl TestState {
    fn new(access_level: Option<AccessLevel>) -> Self {
        Self::with_authorization(access_level, FakeAuthorizationService::default())
    }

    fn with_authorization(
        access_level: Option<AccessLevel>,
        authorization: FakeAuthorizationService,
    ) -> Self {
        Self::with_service_and_authorization(
            FakeEntityAccessService::new(access_level),
            authorization,
        )
    }

    fn with_service(entity_access: FakeEntityAccessService) -> Self {
        Self::with_service_and_authorization(entity_access, FakeAuthorizationService::default())
    }

    fn with_service_and_authorization(
        entity_access: FakeEntityAccessService,
        authorization: FakeAuthorizationService,
    ) -> Self {
        Self {
            entity_access: Arc::new(entity_access),
            authorization: MacroAuthorizationState::new(Arc::new(authorization)),
        }
    }
}

impl FromRef<TestState> for Arc<FakeEntityAccessService> {
    fn from_ref(state: &TestState) -> Self {
        state.entity_access.clone()
    }
}

impl FromRef<TestState> for MacroAuthorizationState<FakeAuthorizationService> {
    fn from_ref(state: &TestState) -> Self {
        state.authorization.clone()
    }
}

fn user_context(user_id: &str) -> UserContext {
    UserContext {
        user_id: user_id.to_string(),
        fusion_user_id: "fusion-user-id".to_string(),
        organization_id: None,
        permissions: None,
    }
}

fn owner_scoped_bot_authentication() -> BotAuthentication {
    let mut authentication = user_scoped_bot_authentication();
    let acting_user = authentication
        .acting_user
        .as_mut()
        .expect("user-scoped bot should have an acting user");
    acting_user.macro_user_id =
        MacroUserIdStr::parse_from_str(OWNER_ID).expect("owner id should be valid");
    acting_user.user_context = user_context(OWNER_ID);
    authentication
}

fn document(deleted: bool) -> DocumentBasic {
    let mut document = DocumentBasic {
        document_id: DOCUMENT_ID.to_string(),
        document_name: "Test document".to_string(),
        owner: Owner::from_principal_str(OWNER_ID).expect("owner id should be valid"),
        file_type: None,
        sub_type: None,
        branched_from_id: None,
        branched_from_version_id: None,
        document_family_id: None,
        project_id: None,
        deleted_at: None,
    };
    if deleted {
        document.deleted_at = Some(
            "2026-01-01T00:00:00Z"
                .parse()
                .expect("deleted timestamp should be valid"),
        );
    }
    document
}

fn request(token: Option<&str>, document: DocumentBasic) -> Request<Body> {
    let mut request = Request::new(Body::empty());
    request.extensions_mut().insert(document);
    if let Some(token) = token {
        request.headers_mut().insert(
            header::AUTHORIZATION,
            format!("Bearer {token}")
                .parse()
                .expect("header should be valid"),
        );
    }
    request
}

fn bot_request(bot_scope: BotScope, token: &str, document: DocumentBasic) -> Request<Body> {
    let mut request = request(None, document);
    request.headers_mut().insert(
        BOT_TOKEN_HEADER,
        token.parse().expect("bot token should be valid"),
    );
    request.headers_mut().insert(
        BOT_SCOPE_HEADER,
        bot_scope
            .as_str()
            .parse()
            .expect("bot scope should be valid"),
    );
    request
}

fn internal_request(
    key_header: &'static str,
    user_header: Option<&'static str>,
    user_id: Option<&str>,
    document: DocumentBasic,
) -> Request<Body> {
    let mut request = request(None, document);
    request.headers_mut().insert(
        key_header,
        INTERNAL_KEY.parse().expect("key should be valid"),
    );
    if let (Some(user_header), Some(user_id)) = (user_header, user_id) {
        request.headers_mut().insert(
            user_header,
            user_id.parse().expect("user id should be valid"),
        );
    }
    request
}

async fn extract<T: RequiredPermission>(
    request: Request<Body>,
    state: &TestState,
) -> Result<
    DocumentAccessExtractor<T, FakeEntityAccessService, FakeAuthorizationService>,
    ExtractorError,
> {
    let (mut parts, _) = request.into_parts();
    DocumentAccessExtractor::from_request_parts(&mut parts, state).await
}

#[tokio::test]
async fn anonymous_link_share_access_returns_unauthenticated_receipt() {
    let state = TestState::new(Some(AccessLevel::View));
    let extracted = extract::<ViewAccessLevel>(request(None, document(false)), &state)
        .await
        .expect("public link access should be allowed");

    assert!(matches!(
        extracted.entity_access_receipt.auth(),
        EntityAccessAuth::Unauthenticated
    ));
    assert_eq!(state.entity_access.calls()[0].user_id, None);
}

#[tokio::test]
async fn authenticated_owner_bypasses_access_lookup() {
    let state = TestState::new(None);
    let extracted = extract::<EditAccessLevel>(request(Some("owner"), document(false)), &state)
        .await
        .expect("the owner should be allowed");

    assert!(matches!(
        extracted.entity_access_receipt.entity_permission(),
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Owner
        }
    ));
    assert!(state.entity_access.calls().is_empty());
}

#[tokio::test]
async fn bot_owner_does_not_take_user_owner_fast_path() {
    let state = TestState::new(Some(AccessLevel::Edit));
    let mut document = document(false);
    document.owner = Owner::from_principal_str("bot|00000000-0000-0000-0000-00000000a1a1")
        .expect("bot owner should be valid");

    let extracted = extract::<EditAccessLevel>(request(Some("valid"), document), &state)
        .await
        .expect("non-owner should fall through to entity_access");

    assert!(matches!(
        extracted.entity_access_receipt.entity_permission(),
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Edit
        }
    ));
    assert_eq!(state.entity_access.calls().len(), 1);
    assert_eq!(
        state.entity_access.calls()[0].user_id.as_deref(),
        Some(USER_ID)
    );
}

#[tokio::test]
async fn team_owner_does_not_take_user_owner_fast_path() {
    let state = TestState::new(Some(AccessLevel::View));
    let mut document = document(false);
    document.owner = Owner::from_principal_str("01234567-89ab-cdef-0123-456789abcdef")
        .expect("team owner should be valid");

    let extracted = extract::<ViewAccessLevel>(request(Some("valid"), document), &state)
        .await
        .expect("non-owner should fall through to entity_access");

    assert!(matches!(
        extracted.entity_access_receipt.entity_permission(),
        EntityPermission::AccessLevel {
            access_level: AccessLevel::View
        }
    ));
    assert_eq!(state.entity_access.calls().len(), 1);
    assert_eq!(
        state.entity_access.calls()[0].user_id.as_deref(),
        Some(USER_ID)
    );
}

#[tokio::test]
async fn insufficient_access_is_rejected() {
    let state = TestState::new(Some(AccessLevel::View));
    let result = extract::<EditAccessLevel>(request(Some("valid"), document(false)), &state).await;

    assert!(matches!(result, Err(ExtractorError::Unauthorized)));
}

#[tokio::test]
async fn deleted_document_allows_owner_but_rejects_non_owner() {
    let owner_state = TestState::new(None);
    extract::<EditAccessLevel>(request(Some("owner"), document(true)), &owner_state)
        .await
        .expect("the owner should access a deleted document");

    let non_owner_state = TestState::new(Some(AccessLevel::Owner));
    let result =
        extract::<ViewAccessLevel>(request(Some("valid"), document(true)), &non_owner_state).await;
    assert!(matches!(
        result,
        Err(ExtractorError::UnauthorizedWithMessage(
            "only owner can access deleted resource"
        ))
    ));
    assert!(non_owner_state.entity_access.calls().is_empty());
}

async fn assert_internal_act_as_uses_acl(
    key_header: &'static str,
    user_header: &'static str,
    user_id: &str,
) {
    let state = TestState::new(Some(AccessLevel::Edit));
    let extracted = extract::<EditAccessLevel>(
        internal_request(
            key_header,
            Some(user_header),
            Some(user_id),
            document(false),
        ),
        &state,
    )
    .await
    .expect("internal act-as identity should use its ACL");

    assert!(matches!(
        extracted.entity_access_receipt.auth(),
        EntityAccessAuth::Authenticated(actual) if actual.as_ref() == user_id
    ));
    assert_eq!(
        state.entity_access.calls()[0].user_id.as_deref(),
        Some(user_id)
    );
}

#[tokio::test]
async fn standard_internal_act_as_uses_ordinary_acl_evaluation() {
    assert_internal_act_as_uses_acl(
        INTERNAL_API_KEY_HEADER,
        INTERNAL_MACRO_USER_ID_HEADER,
        STANDARD_ACT_AS_ID,
    )
    .await;
}

#[allow(deprecated)]
#[tokio::test]
async fn legacy_internal_act_as_uses_ordinary_acl_evaluation() {
    assert_internal_act_as_uses_acl(
        LEGACY_DSS_INTERNAL_API_KEY_HEADER,
        LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER,
        LEGACY_ACT_AS_ID,
    )
    .await;
}

#[tokio::test]
async fn default_internal_identity_uses_ordinary_acl_evaluation() {
    let state = TestState::with_authorization(
        Some(AccessLevel::View),
        FakeAuthorizationService::with_default_internal_user(),
    );
    let extracted = extract::<ViewAccessLevel>(
        internal_request(INTERNAL_API_KEY_HEADER, None, None, document(false)),
        &state,
    )
    .await
    .expect("default internal identity should use its ACL");

    assert!(matches!(
        extracted.entity_access_receipt.auth(),
        EntityAccessAuth::Authenticated(actual) if actual.as_ref() == DEFAULT_INTERNAL_ID
    ));
    assert_eq!(
        state.entity_access.calls()[0].user_id.as_deref(),
        Some(DEFAULT_INTERNAL_ID)
    );
}

#[tokio::test]
async fn identity_less_internal_request_receives_owner_without_acl_lookup() {
    let state = TestState::new(None);
    let extracted = extract::<EditAccessLevel>(
        internal_request(INTERNAL_API_KEY_HEADER, None, None, document(false)),
        &state,
    )
    .await
    .expect("identity-less internal access should be allowed");

    assert!(matches!(
        extracted.entity_access_receipt.auth(),
        EntityAccessAuth::Internal
    ));
    assert!(matches!(
        extracted.entity_access_receipt.entity_permission(),
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Owner
        }
    ));
    assert!(state.entity_access.calls().is_empty());
}

#[tokio::test]
async fn invalid_internal_credentials_are_rejected_without_acl_lookup() {
    let state = TestState::new(Some(AccessLevel::Owner));
    let mut request = internal_request(INTERNAL_API_KEY_HEADER, None, None, document(false));
    request
        .headers_mut()
        .insert(INTERNAL_API_KEY_HEADER, "invalid".parse().unwrap());
    let error = extract::<ViewAccessLevel>(request, &state)
        .await
        .expect_err("invalid credentials should be rejected");
    let response = error.into_response();

    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    assert!(state.entity_access.calls().is_empty());
}

#[tokio::test]
async fn user_scoped_bot_uses_acting_user_scope() {
    let state = TestState::with_service(FakeEntityAccessService::new(None).with_bot_permission(
        EntityPermission::AccessLevel {
            access_level: AccessLevel::View,
        },
    ));

    let extracted = extract::<ViewAccessLevel>(
        bot_request(BotScope::User, VALID_BOT_TOKEN, document(false)),
        &state,
    )
    .await
    .expect("user-scoped bot should use its delegated access");

    assert_eq!(
        extracted
            .entity_access_receipt
            .get_authenticated_bot()
            .expect("receipt should authenticate a bot")
            .bot_id(),
        BOT_ID
    );
    assert_eq!(
        extracted
            .entity_access_receipt
            .get_authenticated_bot_auth()
            .expect("receipt should retain bot scope")
            .scope(),
        &BotReceiptScope::User {
            acting_user: MacroUserIdStr::parse_from_str(BOT_ACTING_USER_ID)
                .expect("acting user id should be valid"),
        }
    );
    assert_eq!(
        state.entity_access.bot_calls(),
        [BotAccessCall {
            bot_id: BOT_ID,
            scope: BotAccessScope::User {
                user_id: MacroUserIdStr::parse_from_str(BOT_ACTING_USER_ID)
                    .expect("acting user id should be valid"),
                user_org_id: Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID)),
            },
            entity_id: DOCUMENT_ID.to_string(),
            entity_type: EntityType::Document,
        }]
    );
    assert!(state.entity_access.calls().is_empty());
}

#[tokio::test]
async fn team_scoped_bot_uses_owning_team_scope() {
    let state = TestState::with_service(FakeEntityAccessService::new(None).with_bot_permission(
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Edit,
        },
    ));

    let extracted = extract::<EditAccessLevel>(
        bot_request(BotScope::Team, VALID_BOT_TOKEN, document(false)),
        &state,
    )
    .await
    .expect("team-scoped bot should use its team access");

    assert_eq!(
        extracted
            .entity_access_receipt
            .get_authenticated_bot_auth()
            .expect("receipt should retain bot scope")
            .scope(),
        &BotReceiptScope::Team {
            team_id: BOT_TEAM_ID,
        }
    );
    assert_eq!(
        state.entity_access.bot_calls(),
        [BotAccessCall {
            bot_id: BOT_ID,
            scope: BotAccessScope::Team {
                team_id: BOT_TEAM_ID,
            },
            entity_id: DOCUMENT_ID.to_string(),
            entity_type: EntityType::Document,
        }]
    );
}

#[tokio::test]
async fn user_scoped_bot_without_acting_user_is_rejected_before_acl_lookup() {
    let state = TestState::with_service(FakeEntityAccessService::new(None).with_bot_permission(
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Owner,
        },
    ));

    let error = extract::<ViewAccessLevel>(
        bot_request(BotScope::User, MALFORMED_SYSTEM_BOT_TOKEN, document(false)),
        &state,
    )
    .await
    .expect_err("user scope should require an acting user");

    assert!(matches!(
        error,
        ExtractorError::UnauthorizedWithMessage("bot user scope requires an acting user")
    ));
    assert!(state.entity_access.bot_calls().is_empty());
    assert!(state.entity_access.calls().is_empty());
}

#[tokio::test]
async fn bot_receipt_must_satisfy_the_required_access_level() {
    let state = TestState::with_service(FakeEntityAccessService::new(None).with_bot_permission(
        EntityPermission::AccessLevel {
            access_level: AccessLevel::View,
        },
    ));

    let result = extract::<EditAccessLevel>(
        bot_request(BotScope::Team, VALID_BOT_TOKEN, document(false)),
        &state,
    )
    .await;

    assert!(matches!(result, Err(ExtractorError::Unauthorized)));
    assert_eq!(state.entity_access.bot_calls().len(), 1);
}

#[tokio::test]
async fn bot_acting_as_document_owner_still_uses_scoped_service() {
    let state = TestState::with_service(FakeEntityAccessService::new(None).with_bot_permission(
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Owner,
        },
    ));

    let extracted = extract::<EditAccessLevel>(
        bot_request(BotScope::User, OWNER_ACTING_BOT_TOKEN, document(false)),
        &state,
    )
    .await
    .expect("the scoped service should delegate owner access");

    assert!(matches!(
        extracted.entity_access_receipt.auth(),
        EntityAccessAuth::Bot(_)
    ));
    assert_eq!(state.entity_access.bot_calls().len(), 1);
    assert!(state.entity_access.calls().is_empty());
    assert_eq!(
        state.entity_access.bot_calls()[0].scope,
        BotAccessScope::User {
            user_id: MacroUserIdStr::parse_from_str(OWNER_ID).expect("owner id should be valid"),
            user_org_id: None,
        }
    );
}

#[tokio::test]
async fn deleted_document_requires_owner_permission_from_scoped_service() {
    let owner_state = TestState::with_service(
        FakeEntityAccessService::new(None).with_bot_permission(EntityPermission::AccessLevel {
            access_level: AccessLevel::Owner,
        }),
    );
    extract::<EditAccessLevel>(
        bot_request(BotScope::Team, VALID_BOT_TOKEN, document(true)),
        &owner_state,
    )
    .await
    .expect("owner permission should allow deleted document access");
    assert_eq!(owner_state.entity_access.bot_calls().len(), 1);

    let edit_state = TestState::with_service(
        FakeEntityAccessService::new(None).with_bot_permission(EntityPermission::AccessLevel {
            access_level: AccessLevel::Edit,
        }),
    );
    let result = extract::<ViewAccessLevel>(
        bot_request(BotScope::Team, VALID_BOT_TOKEN, document(true)),
        &edit_state,
    )
    .await;

    assert!(matches!(
        result,
        Err(ExtractorError::UnauthorizedWithMessage(
            "only owner can access deleted resource"
        ))
    ));
    assert_eq!(edit_state.entity_access.bot_calls().len(), 1);
}

#[tokio::test]
async fn expired_token_preserves_exact_unauthorized_json() {
    let state = TestState::new(Some(AccessLevel::Owner));
    let error = extract::<ViewAccessLevel>(request(Some("expired"), document(false)), &state)
        .await
        .expect_err("expired credentials should be rejected");
    let response = error.into_response();

    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    let body = to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("response body should be readable");
    assert_eq!(body.as_ref(), br#"{"message":"jwt expired"}"#);
    assert!(state.entity_access.calls().is_empty());
}