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(entity_access): add initiative access query, explain, and extractor (#6411)

Will Hutchinson7d2063f6b5e8
diff --git a/.sqlx/query-208b28f3881a82f50ed877d206912b3b2694558116c70df1e9768f5a16a1c635.json b/.sqlx/query-208b28f3881a82f50ed877d206912b3b2694558116c70df1e9768f5a16a1c635.json
new file mode 100644
index 0000000000..ee44e6ce9d
--- /dev/null
+++ b/.sqlx/query-208b28f3881a82f50ed877d206912b3b2694558116c70df1e9768f5a16a1c635.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n sp.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\",\n owner_team.team_id AS \"owner_team_id!\"\n FROM initiative i\n JOIN \"SharePermission\" sp ON sp.id = i.share_permission_id\n JOIN team_user owner_team\n ON owner_team.user_id = i.owner_user_id\n AND owner_team.team_id::text = ANY($2)\n WHERE i.id = $1\n AND sp.\"linkShare\" = 'TEAM'\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 1,
+ "name": "owner_team_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ true,
+ false
+ ]
+ },
+ "hash": "208b28f3881a82f50ed877d206912b3b2694558116c70df1e9768f5a16a1c635"
+}
diff --git a/.sqlx/query-32829f5748c29623d263db1021e98216c9cea3186e3347d1b642681f4010a42e.json b/.sqlx/query-32829f5748c29623d263db1021e98216c9cea3186e3347d1b642681f4010a42e.json
new file mode 100644
index 0000000000..2b0b8c1840
--- /dev/null
+++ b/.sqlx/query-32829f5748c29623d263db1021e98216c9cea3186e3347d1b642681f4010a42e.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO initiative (id, name, owner_user_id, share_permission_id)\n VALUES ($1, 'Test initiative', $2, $3)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "32829f5748c29623d263db1021e98216c9cea3186e3347d1b642681f4010a42e"
+}
diff --git a/.sqlx/query-3a9e3a9cf8a2d98d68a73afc178c6ba16546178b64c81c98bed193abca3f2626.json b/.sqlx/query-3a9e3a9cf8a2d98d68a73afc178c6ba16546178b64c81c98bed193abca3f2626.json
new file mode 100644
index 0000000000..0d0b00fc45
--- /dev/null
+++ b/.sqlx/query-3a9e3a9cf8a2d98d68a73afc178c6ba16546178b64c81c98bed193abca3f2626.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH entity_access_grants AS (\n SELECT ea.access_level\n FROM entity_access ea\n WHERE ea.entity_id = $1\n AND ea.entity_type = 'initiative'\n AND ea.source_id = ANY($2)\n ),\n link_share_grants AS (\n SELECT sp.\"linkShareAccessLevel\" AS access_level\n FROM initiative i\n JOIN \"SharePermission\" sp ON sp.id = i.share_permission_id\n WHERE i.id = $1\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n sp.\"linkShare\" = 'PUBLIC'\n OR (\n sp.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM team_user owner_team\n WHERE owner_team.user_id = i.owner_user_id\n AND owner_team.team_id::text = ANY($2)\n )\n )\n )\n )\n SELECT access_level AS \"access_level!: AccessLevel\"\n FROM (\n SELECT access_level FROM entity_access_grants\n UNION ALL\n SELECT access_level FROM link_share_grants\n ) AS grants\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3a9e3a9cf8a2d98d68a73afc178c6ba16546178b64c81c98bed193abca3f2626"
+}
diff --git a/.sqlx/query-8f46bd0e859d168c1886db023f992787e118795ab8d73238eb26de5d5d7a0dda.json b/.sqlx/query-8f46bd0e859d168c1886db023f992787e118795ab8d73238eb26de5d5d7a0dda.json
new file mode 100644
index 0000000000..de4402c04a
--- /dev/null
+++ b/.sqlx/query-8f46bd0e859d168c1886db023f992787e118795ab8d73238eb26de5d5d7a0dda.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO initiative_member (initiative_id, user_id)\n VALUES ($1, $2)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "8f46bd0e859d168c1886db023f992787e118795ab8d73238eb26de5d5d7a0dda"
+}
diff --git a/.sqlx/query-b3bbc6103dddd5d4842a8b17bea580471840667e2b3818f09c7415a0e499fb05.json b/.sqlx/query-b3bbc6103dddd5d4842a8b17bea580471840667e2b3818f09c7415a0e499fb05.json
new file mode 100644
index 0000000000..5e04a41879
--- /dev/null
+++ b/.sqlx/query-b3bbc6103dddd5d4842a8b17bea580471840667e2b3818f09c7415a0e499fb05.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_access (\n entity_id,\n entity_type,\n source_id,\n source_type,\n access_level\n )\n VALUES ($1, 'initiative', $2, $3::text::entity_access_source_type, $4::text::\"AccessLevel\")\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b3bbc6103dddd5d4842a8b17bea580471840667e2b3818f09c7415a0e499fb05"
+}
diff --git a/.sqlx/query-f5b04d8345ac8ce93b6a97cb0b0f955b8f8fbaa373972713ae37268a2eb03198.json b/.sqlx/query-f5b04d8345ac8ce93b6a97cb0b0f955b8f8fbaa373972713ae37268a2eb03198.json
new file mode 100644
index 0000000000..b5d0121218
--- /dev/null
+++ b/.sqlx/query-f5b04d8345ac8ce93b6a97cb0b0f955b8f8fbaa373972713ae37268a2eb03198.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT sp.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM initiative i\n JOIN \"SharePermission\" sp ON sp.id = i.share_permission_id\n WHERE i.id = $1\n AND sp.\"linkShare\" = 'PUBLIC'\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "f5b04d8345ac8ce93b6a97cb0b0f955b8f8fbaa373972713ae37268a2eb03198"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 2ecafa2026..b90504dbc3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6238,6 +6238,7 @@ dependencies = [
"cool_asserts",
"database_env_vars",
"futures",
+ "harness_id",
"macro_authorization",
"macro_db_migrator",
"macro_entrypoint",
diff --git a/crates/entity_access/Cargo.toml b/crates/entity_access/Cargo.toml
index c9ed57914f..ae83c84d7e 100644
--- a/crates/entity_access/Cargo.toml
+++ b/crates/entity_access/Cargo.toml
@@ -70,6 +70,7 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
cool_asserts = "2"
+harness_id = { path = "../harness_id" }
macro_db_migrator = { path = "../macro_db_migrator" }
mockall = { workspace = true }
model_user = { path = "../model_user" }
diff --git a/crates/entity_access/src/inbound/axum_extractors.rs b/crates/entity_access/src/inbound/axum_extractors.rs
index c9e26484fb..554058eebc 100644
--- a/crates/entity_access/src/inbound/axum_extractors.rs
+++ b/crates/entity_access/src/inbound/axum_extractors.rs
@@ -18,6 +18,7 @@ mod entity_body;
mod entity_permission;
mod foreign_entity;
mod history;
+mod initiative;
mod pin;
mod project;
mod reminder;
@@ -33,6 +34,7 @@ pub use entity_body::EntityBodyAccessLevelExtractor;
pub use entity_permission::EntityPermissionExtractor;
pub use foreign_entity::ForeignEntityAccessLevelExtractor;
pub use history::HistoryAccessExtractor;
+pub use initiative::InitiativeAccessExtractor;
pub use pin::PinAccessLevelExtractor;
pub use project::{ProjectAccessLevelExtractor, ProjectBodyAccessLevelExtractorV2};
pub use reminder::ReminderAccessExtractor;
diff --git a/crates/entity_access/src/inbound/axum_extractors/initiative.rs b/crates/entity_access/src/inbound/axum_extractors/initiative.rs
new file mode 100644
index 0000000000..11c2218c3e
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/initiative.rs
@@ -0,0 +1,146 @@
+//! Initiative access extractor.
+
+#[cfg(test)]
+mod test;
+
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+use axum::{
+ RequestPartsExt,
+ extract::{FromRef, FromRequestParts, Path},
+ http::request::Parts,
+};
+use macro_authorization::{
+ AnyPrincipal, BotAuthentication, MacroAuthorization, MacroAuthorizationService,
+ MacroAuthorizationState, OptionalMacroAuthorizationExtractor,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::{ExtractorError, RequiredPermission, bot::generate_bot_entity_access_receipt};
+use crate::domain::{
+ models::{Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType},
+ ports::EntityAccessService,
+};
+
+#[derive(Debug, serde::Deserialize)]
+struct InitiativeAccessParams {
+ initiative_id: String,
+}
+
+/// Validates that the caller satisfies the required permission for the
+/// initiative named by an `initiative_id` path parameter.
+///
+/// Type parameter `T` specifies the required permission marker.
+/// Type parameter `Svc` is the entity access service implementation.
+/// Type parameter `Auth` is the authorization service implementation.
+#[derive(Debug)]
+pub struct InitiativeAccessExtractor<T: RequiredPermission, Svc, Auth> {
+ /// The entity access receipt for the initiative.
+ pub entity_access_receipt: EntityAccessReceipt<T>,
+ _marker: PhantomData<(T, Svc, Auth)>,
+}
+
+#[derive(Debug)]
+enum Caller<'a> {
+ Bot(&'a BotAuthentication),
+ InternalService,
+ Person(Option<MacroUserIdStr<'static>>),
+}
+
+impl<'a> From<Option<&'a MacroAuthorization>> for Caller<'a> {
+ fn from(authorization: Option<&'a MacroAuthorization>) -> Self {
+ match authorization {
+ Some(MacroAuthorization::Bot(bot)) => Self::Bot(bot),
+ Some(MacroAuthorization::Internal(None)) => Self::InternalService,
+ Some(MacroAuthorization::User(user))
+ | Some(MacroAuthorization::Internal(Some(user))) => {
+ Self::Person(Some(user.macro_user_id.clone()))
+ }
+ Some(MacroAuthorization::Harness(harness)) => {
+ Self::Person(Some(harness.acting_user.macro_user_id.clone()))
+ }
+ None => Self::Person(None),
+ }
+ }
+}
+
+impl<T, S, Svc, Auth> FromRequestParts<S> for InitiativeAccessExtractor<T, Svc, Auth>
+where
+ T: RequiredPermission,
+ Arc<Svc>: FromRef<S>,
+ Svc: EntityAccessService,
+ MacroAuthorizationState<Auth>: FromRef<S>,
+ Auth: MacroAuthorizationService,
+ S: Send + Sync + 'static,
+{
+ type Rejection = ExtractorError;
+
+ #[tracing::instrument(err, skip(state, parts))]
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let service = <Arc<Svc>>::from_ref(state);
+
+ let authorization =
+ OptionalMacroAuthorizationExtractor::<Auth, AnyPrincipal>::from_request_parts(
+ parts, state,
+ )
+ .await
+ .map_err(ExtractorError::from)?
+ .authorization;
+
+ let Path(InitiativeAccessParams { initiative_id }) = parts
+ .extract::<Path<InitiativeAccessParams>>()
+ .await
+ .map_err(|_| ExtractorError::BadRequest("missing initiative_id path parameter"))?;
+
+ let entity_access_receipt = match Caller::from(authorization.as_ref()) {
+ Caller::Bot(bot) => {
+ generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ bot,
+ &initiative_id,
+ EntityType::Initiative,
+ )
+ .await?
+ }
+ Caller::InternalService => EntityAccessReceipt::dangerously_assert_internal_user(
+ &initiative_id,
+ EntityType::Initiative,
+ ),
+ Caller::Person(user) => {
+ person_receipt::<T>(service.as_ref(), user, initiative_id).await?
+ }
+ };
+
+ Ok(Self {
+ entity_access_receipt,
+ _marker: PhantomData,
+ })
+ }
+}
+
+async fn person_receipt<T: RequiredPermission>(
+ service: &impl EntityAccessService,
+ user: Option<MacroUserIdStr<'static>>,
+ initiative_id: String,
+) -> Result<EntityAccessReceipt<T>, ExtractorError> {
+ let access_level = service
+ .get_access_level(user.as_deref(), &initiative_id, EntityType::Initiative)
+ .await
+ .map_err(ExtractorError::from)?
+ .ok_or(ExtractorError::Unauthorized)?;
+
+ let auth = user
+ .map(EntityAccessAuth::Authenticated)
+ .unwrap_or(EntityAccessAuth::Unauthenticated);
+
+ EntityAccessReceipt::try_new(
+ auth,
+ Entity {
+ entity_id: initiative_id,
+ entity_type: EntityType::Initiative,
+ },
+ EntityPermission::AccessLevel { access_level },
+ )
+ .map_err(ExtractorError::from)
+}
diff --git a/crates/entity_access/src/inbound/axum_extractors/initiative/test.rs b/crates/entity_access/src/inbound/axum_extractors/initiative/test.rs
new file mode 100644
index 0000000000..323a505534
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/initiative/test.rs
@@ -0,0 +1,322 @@
+use axum::{
+ Router,
+ body::{Body, to_bytes},
+ http::{Request, StatusCode, header},
+ routing::get,
+};
+use harness_id::HarnessId;
+use macro_authorization::{
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotScope, HarnessAuthentication, HarnessAuthorizationOwner,
+ INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, MacroAuthorization,
+ MacroUserAuthentication,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_user::UserContext;
+use tower::ServiceExt;
+use uuid::Uuid;
+
+use super::*;
+use crate::{
+ domain::models::{
+ AccessLevel, BotAccessScope, EditAccessLevel, EntityAccessAuth, EntityType, ViewAccessLevel,
+ },
+ inbound::axum_extractors::test_support::{
+ AccessCall, BOT_ID, BOT_TEAM_ID, BotAccessCall, FakeAuthorizationService,
+ FakeEntityAccessService, INTERNAL_KEY, TestState, USER_ID, VALID_BOT_TOKEN,
+ user_scoped_bot_authentication,
+ },
+};
+
+const INITIATIVE_ID: &str = "01a0a11f-b147-79fe-a5f1-87833710bbeb";
+const HARNESS_ACTING_USER_ID: &str = "macro|[email protected]";
+
+type ViewExtractor =
+ InitiativeAccessExtractor<ViewAccessLevel, FakeEntityAccessService, FakeAuthorizationService>;
+type EditExtractor =
+ InitiativeAccessExtractor<EditAccessLevel, FakeEntityAccessService, FakeAuthorizationService>;
+
+async fn view_handler(access: ViewExtractor) -> &'static str {
+ receipt_auth_name(access.entity_access_receipt.auth())
+}
+
+async fn edit_handler(access: EditExtractor) -> &'static str {
+ receipt_auth_name(access.entity_access_receipt.auth())
+}
+
+fn receipt_auth_name(auth: &EntityAccessAuth) -> &'static str {
+ match auth {
+ EntityAccessAuth::Authenticated(_) => "authenticated",
+ EntityAccessAuth::Unauthenticated => "unauthenticated",
+ EntityAccessAuth::Internal => "internal",
+ EntityAccessAuth::Bot(_) => "bot",
+ }
+}
+
+fn view_router(state: TestState) -> Router {
+ Router::new()
+ .route("/initiatives/{initiative_id}", get(view_handler))
+ .with_state(state)
+}
+
+fn edit_router(state: TestState) -> Router {
+ Router::new()
+ .route("/initiatives/{initiative_id}", get(edit_handler))
+ .with_state(state)
+}
+
+fn request() -> axum::http::request::Builder {
+ Request::get(format!("/initiatives/{INITIATIVE_ID}"))
+}
+
+fn bot_request(scope: BotScope, token: &str) -> Request<Body> {
+ request()
+ .header(BOT_TOKEN_HEADER, token)
+ .header(BOT_SCOPE_HEADER, scope.as_str())
+ .body(Body::empty())
+ .expect("bot request should be valid")
+}
+
+async fn response_body(response: axum::response::Response) -> String {
+ let body = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response body should be readable");
+ String::from_utf8(body.to_vec()).expect("response body should be UTF-8")
+}
+
+fn user_authentication(user_id: &str) -> MacroUserAuthentication {
+ MacroUserAuthentication {
+ macro_user_id: MacroUserIdStr::try_from(user_id.to_string()).expect("valid user id"),
+ user_context: UserContext {
+ user_id: user_id.to_string(),
+ fusion_user_id: "fusion-user-id".to_string(),
+ organization_id: None,
+ permissions: None,
+ },
+ }
+}
+
+fn caller_kind(caller: Caller<'_>) -> (&'static str, Option<String>) {
+ match caller {
+ Caller::Bot(_) => ("bot", None),
+ Caller::InternalService => ("internal", None),
+ Caller::Person(user) => ("person", user.map(|user_id| user_id.as_ref().to_string())),
+ }
+}
+
+#[test]
+fn caller_from_authorization_table() {
+ let bot = user_scoped_bot_authentication();
+ let user = user_authentication(USER_ID);
+ let harness_acting_user = user_authentication(HARNESS_ACTING_USER_ID);
+ let harness = HarnessAuthentication {
+ harness_id: HarnessId::new_from_uuid(Uuid::from_u128(1)),
+ token_id: Uuid::from_u128(2),
+ owner: HarnessAuthorizationOwner::User {
+ user_id: USER_ID.to_string(),
+ },
+ acting_user: harness_acting_user,
+ };
+
+ let cases = [
+ (Some(MacroAuthorization::Bot(bot)), ("bot", None)),
+ (Some(MacroAuthorization::Internal(None)), ("internal", None)),
+ (
+ Some(MacroAuthorization::Internal(Some(user.clone()))),
+ ("person", Some(USER_ID.to_string())),
+ ),
+ (
+ Some(MacroAuthorization::User(user)),
+ ("person", Some(USER_ID.to_string())),
+ ),
+ (
+ Some(MacroAuthorization::Harness(harness)),
+ ("person", Some(HARNESS_ACTING_USER_ID.to_string())),
+ ),
+ (None, ("person", None)),
+ ];
+
+ for (authorization, expected) in cases {
+ assert_eq!(
+ caller_kind(Caller::from(authorization.as_ref())),
+ expected,
+ "authorization: {authorization:?}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn anonymous_caller_reaches_public_acl() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = view_router(state.clone())
+ .oneshot(request().body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, "unauthenticated");
+ assert_eq!(
+ state.entity_access.calls(),
+ [AccessCall {
+ user_id: None,
+ entity_id: INITIATIVE_ID.to_string(),
+ entity_type: EntityType::Initiative,
+ }]
+ );
+ assert!(state.entity_access.bot_calls().is_empty());
+}
+
+#[tokio::test]
+async fn anonymous_caller_without_public_link_is_unauthorized() {
+ let state = TestState::new(None);
+ let response = view_router(state.clone())
+ .oneshot(request().body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ state.entity_access.calls(),
+ [AccessCall {
+ user_id: None,
+ entity_id: INITIATIVE_ID.to_string(),
+ entity_type: EntityType::Initiative,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn authenticated_user_uses_acl() {
+ let state = TestState::new(Some(AccessLevel::Edit));
+ let response = edit_router(state.clone())
+ .oneshot(
+ request()
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, "authenticated");
+ assert_eq!(
+ state.entity_access.calls()[0].user_id.as_deref(),
+ Some(USER_ID)
+ );
+}
+
+#[tokio::test]
+async fn insufficient_level_is_unauthorized() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = edit_router(state.clone())
+ .oneshot(
+ request()
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+}
+
+#[tokio::test]
+async fn identity_less_internal_receives_owner_without_acl_lookup() {
+ let state = TestState::new(None);
+ let response = edit_router(state.clone())
+ .oneshot(
+ request()
+ .header(INTERNAL_API_KEY_HEADER, INTERNAL_KEY)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, "internal");
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn internal_act_as_uses_acl() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = view_router(state.clone())
+ .oneshot(
+ request()
+ .header(INTERNAL_API_KEY_HEADER, INTERNAL_KEY)
+ .header(INTERNAL_MACRO_USER_ID_HEADER, USER_ID)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, "authenticated");
+ assert_eq!(
+ state.entity_access.calls()[0].user_id.as_deref(),
+ Some(USER_ID)
+ );
+}
+
+#[tokio::test]
+async fn team_scoped_bot_uses_bot_policy() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = view_router(state.clone())
+ .oneshot(bot_request(BotScope::Team, VALID_BOT_TOKEN))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(response_body(response).await, "bot");
+ assert_eq!(
+ state.entity_access.bot_calls(),
+ [BotAccessCall {
+ bot_id: BOT_ID,
+ scope: BotAccessScope::Team {
+ team_id: BOT_TEAM_ID,
+ },
+ entity_id: INITIATIVE_ID.to_string(),
+ entity_type: EntityType::Initiative,
+ }]
+ );
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn missing_path_parameter_is_bad_request() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let response = Router::new()
+ .route("/initiatives", get(view_handler))
+ .with_state(state.clone())
+ .oneshot(Request::get("/initiatives").body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert!(state.entity_access.calls().is_empty());
+}
+
+#[tokio::test]
+async fn an_expired_token_is_still_an_authorization_error() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let response = view_router(state.clone())
+ .oneshot(
+ request()
+ .header(header::AUTHORIZATION, "Bearer expired")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ response_body(response).await,
+ r#"{"message":"jwt expired"}"#
+ );
+ assert!(state.entity_access.calls().is_empty());
+ assert!(state.entity_access.bot_calls().is_empty());
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/initiative_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/initiative_access.rs
index d2ea1fdeeb..122d3f84f9 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/initiative_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/initiative_access.rs
@@ -1,3 +1,8 @@
+//! Query for initiative access level.
+
+#[cfg(test)]
+mod test;
+
#[cfg(feature = "explain_binary")]
use crate::{
domain::models::AccessGrant, outbound::pg_access_repo::queries::list_entity_access_grants,
@@ -7,18 +12,58 @@ use crate::{domain::models::AccessLevel, outbound::pg_access_repo::queries::Sour
use model_entity::EntityType;
use sqlx::PgPool;
+/// Highest access level the caller's `source_ids` reach on an initiative.
#[tracing::instrument(err, skip(pool, source_ids))]
pub async fn get_initiative_access(
pool: &PgPool,
initiative_id: &uuid::Uuid,
source_ids: &SourceIds,
) -> Result<Option<AccessLevel>, sqlx::Error> {
- // The entity_access + SharePermission join is the follow-up query task.
- // Returning None keeps exhaustive matches compiling without a new sqlx::query!.
- let _ = (pool, initiative_id, source_ids);
- Ok(None)
+ let levels: Vec<AccessLevel> = sqlx::query_scalar!(
+ r#"
+ WITH entity_access_grants AS (
+ SELECT ea.access_level
+ FROM entity_access ea
+ WHERE ea.entity_id = $1
+ AND ea.entity_type = 'initiative'
+ AND ea.source_id = ANY($2)
+ ),
+ link_share_grants AS (
+ SELECT sp."linkShareAccessLevel" AS access_level
+ FROM initiative i
+ JOIN "SharePermission" sp ON sp.id = i.share_permission_id
+ WHERE i.id = $1
+ AND sp."linkShareAccessLevel" IS NOT NULL
+ AND (
+ sp."linkShare" = 'PUBLIC'
+ OR (
+ sp."linkShare" = 'TEAM'
+ AND EXISTS (
+ SELECT 1
+ FROM team_user owner_team
+ WHERE owner_team.user_id = i.owner_user_id
+ AND owner_team.team_id::text = ANY($2)
+ )
+ )
+ )
+ )
+ SELECT access_level AS "access_level!: AccessLevel"
+ FROM (
+ SELECT access_level FROM entity_access_grants
+ UNION ALL
+ SELECT access_level FROM link_share_grants
+ ) AS grants
+ "#,
+ initiative_id,
+ &source_ids.0,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(levels.into_iter().max())
}
+/// Every grant path behind [`get_initiative_access`], labeled.
#[cfg(feature = "explain_binary")]
#[tracing::instrument(err, skip(pool, source_ids))]
pub async fn explain_initiative_access(
@@ -26,5 +71,47 @@ pub async fn explain_initiative_access(
initiative_id: &uuid::Uuid,
source_ids: &SourceIds,
) -> Result<Vec<AccessGrant>, sqlx::Error> {
- list_entity_access_grants(pool, initiative_id, EntityType::Initiative, source_ids).await
+ let mut grants =
+ list_entity_access_grants(pool, initiative_id, EntityType::Initiative, source_ids).await?;
+
+ let public_level: Option<AccessLevel> = sqlx::query_scalar!(
+ r#"
+ SELECT sp."linkShareAccessLevel" AS "access_level!: AccessLevel"
+ FROM initiative i
+ JOIN "SharePermission" sp ON sp.id = i.share_permission_id
+ WHERE i.id = $1
+ AND sp."linkShare" = 'PUBLIC'
+ AND sp."linkShareAccessLevel" IS NOT NULL
+ "#,
+ initiative_id,
+ )
+ .fetch_optional(pool)
+ .await?;
+ grants.extend(public_level.map(|access_level| AccessGrant::PublicLink { access_level }));
+
+ let team_rows = sqlx::query!(
+ r#"
+ SELECT
+ sp."linkShareAccessLevel" AS "access_level!: AccessLevel",
+ owner_team.team_id AS "owner_team_id!"
+ FROM initiative i
+ JOIN "SharePermission" sp ON sp.id = i.share_permission_id
+ JOIN team_user owner_team
+ ON owner_team.user_id = i.owner_user_id
+ AND owner_team.team_id::text = ANY($2)
+ WHERE i.id = $1
+ AND sp."linkShare" = 'TEAM'
+ AND sp."linkShareAccessLevel" IS NOT NULL
+ "#,
+ initiative_id,
+ &source_ids.0,
+ )
+ .fetch_all(pool)
+ .await?;
+ grants.extend(team_rows.into_iter().map(|row| AccessGrant::TeamLink {
+ access_level: row.access_level,
+ owner_team_id: row.owner_team_id,
+ }));
+
+ Ok(grants)
}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/initiative_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/initiative_access/test.rs
new file mode 100644
index 0000000000..642b3ff0d6
--- /dev/null
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/initiative_access/test.rs
@@ -0,0 +1,432 @@
+use super::*;
+use crate::outbound::pg_access_repo::queries::get_user_source_ids;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+const OWNER: &str = "macro|[email protected]";
+const GRANTEE: &str = "macro|[email protected]";
+const STRANGER: &str = "macro|[email protected]";
+const OWNER_TEAM: Uuid = Uuid::from_u128(0x0000_0000_0000_0000_0000_0000_0000_1a01);
+const OTHER_TEAM: Uuid = Uuid::from_u128(0x0000_0000_0000_0000_0000_0000_0000_1a02);
+const GRANTED_TEAM: Uuid = Uuid::from_u128(0x0000_0000_0000_0000_0000_0000_0000_1a03);
+
+#[derive(Clone, Copy)]
+enum LinkShare {
+ Off,
+ Public(AccessLevel),
+ Team(AccessLevel),
+}
+
+impl LinkShare {
+ fn columns(self) -> (Option<&'static str>, Option<String>) {
+ match self {
+ Self::Off => (None, None),
+ Self::Public(level) => (Some("PUBLIC"), Some(level.to_string())),
+ Self::Team(level) => (Some("TEAM"), Some(level.to_string())),
+ }
+ }
+}
+
+async fn insert_user(pool: &PgPool, user_id: &str) -> anyhow::Result<()> {
+ let macro_user_id = Uuid::now_v7();
+ let email = user_id.trim_start_matches("macro|");
+
+ sqlx::query!(
+ r#"
+ INSERT INTO macro_user (id, username, email, stripe_customer_id)
+ VALUES ($1, $2, $3, $2)
+ "#,
+ macro_user_id,
+ user_id,
+ email,
+ )
+ .execute(pool)
+ .await?;
+
+ sqlx::query!(
+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#,
+ user_id,
+ email,
+ macro_user_id,
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+async fn insert_initiative(pool: &PgPool, owner: &str, link: LinkShare) -> anyhow::Result<Uuid> {
+ let share_permission_id = Uuid::now_v7().to_string();
+ let (link_share, access_level) = link.columns();
+
+ sqlx::query!(
+ r#"
+ INSERT INTO "SharePermission" (
+ id,
+ "linkShare",
+ "linkShareAccessLevel"
+ )
+ VALUES ($1, $2, $3::text::"AccessLevel")
+ "#,
+ share_permission_id,
+ link_share,
+ access_level,
+ )
+ .execute(pool)
+ .await?;
+
+ let initiative_id = Uuid::now_v7();
+ sqlx::query!(
+ r#"
+ INSERT INTO initiative (id, name, owner_user_id, share_permission_id)
+ VALUES ($1, 'Test initiative', $2, $3)
+ "#,
+ initiative_id,
+ owner,
+ share_permission_id,
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(initiative_id)
+}
+
+async fn insert_team(pool: &PgPool, team_id: Uuid, owner_id: &str) -> anyhow::Result<()> {
+ sqlx::query!(
+ r#"INSERT INTO team (id, name, owner_id) VALUES ($1, 'Test Team', $2)"#,
+ team_id,
+ owner_id,
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+async fn add_team_user(
+ pool: &PgPool,
+ team_id: Uuid,
+ user_id: &str,
+ role: &str,
+) -> anyhow::Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO team_user (user_id, team_id, team_role)
+ VALUES ($1, $2, $3::text::team_role)
+ "#,
+ user_id,
+ team_id,
+ role,
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+async fn grant(
+ pool: &PgPool,
+ initiative_id: Uuid,
+ source_id: &str,
+ source_type: &str,
+ level: AccessLevel,
+) -> anyhow::Result<()> {
+ let access_level = level.to_string();
+
+ sqlx::query!(
+ r#"
+ INSERT INTO entity_access (
+ entity_id,
+ entity_type,
+ source_id,
+ source_type,
+ access_level
+ )
+ VALUES ($1, 'initiative', $2, $3::text::entity_access_source_type, $4::text::"AccessLevel")
+ "#,
+ initiative_id,
+ source_id,
+ source_type,
+ access_level,
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+fn sources(ids: &[&str]) -> SourceIds {
+ SourceIds(ids.iter().map(ToString::to_string).collect())
+}
+
+fn anonymous() -> SourceIds {
+ SourceIds(Vec::new())
+}
+
+#[cfg(feature = "explain_binary")]
+fn user(id: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(id.to_string()).expect("valid user id")
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn owner_row_grants_owner(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let initiative_id = insert_initiative(&pool, OWNER, LinkShare::Off).await?;
+
+ let before = get_initiative_access(&pool, &initiative_id, &sources(&[OWNER])).await?;
+ assert_eq!(before, None);
+
+ grant(&pool, initiative_id, OWNER, "user", AccessLevel::Owner).await?;
+
+ let after = get_initiative_access(&pool, &initiative_id, &sources(&[OWNER])).await?;
+ assert_eq!(after, Some(AccessLevel::Owner));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn owner_column_is_not_a_grant(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let initiative_id = insert_initiative(&pool, OWNER, LinkShare::Off).await?;
+
+ let access = get_initiative_access(&pool, &initiative_id, &sources(&[OWNER])).await?;
+ assert_eq!(access, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn initiative_member_is_not_a_grant(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ insert_user(&pool, GRANTEE).await?;
+ let initiative_id = insert_initiative(&pool, OWNER, LinkShare::Off).await?;
+
+ sqlx::query!(
+ r#"
+ INSERT INTO initiative_member (initiative_id, user_id)
+ VALUES ($1, $2)
+ "#,
+ initiative_id,
+ GRANTEE,
+ )
+ .execute(&pool)
+ .await?;
+
+ let access = get_initiative_access(&pool, &initiative_id, &sources(&[GRANTEE])).await?;
+ assert_eq!(access, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn direct_user_grant_is_returned(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let initiative_id = insert_initiative(&pool, OWNER, LinkShare::Off).await?;
+ grant(&pool, initiative_id, GRANTEE, "user", AccessLevel::Edit).await?;
+
+ let grantee = get_initiative_access(&pool, &initiative_id, &sources(&[GRANTEE])).await?;
+ let stranger = get_initiative_access(&pool, &initiative_id, &sources(&[STRANGER])).await?;
+
+ assert_eq!(grantee, Some(AccessLevel::Edit));
+ assert_eq!(stranger, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn team_grant_reaches_team_members(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let initiative_id = insert_initiative(&pool, OWNER, LinkShare::Off).await?;
+ grant(
+ &pool,
+ initiative_id,
+ &GRANTED_TEAM.to_string(),
+ "team",
+ AccessLevel::Comment,
+ )
+ .await?;
+
+ let with_team = get_initiative_access(
+ &pool,
+ &initiative_id,
+ &sources(&[GRANTEE, &GRANTED_TEAM.to_string()]),
+ )
+ .await?;
+ let user_only = get_initiative_access(&pool, &initiative_id, &sources(&[GRANTEE])).await?;
+
+ assert_eq!(with_team, Some(AccessLevel::Comment));
+ assert_eq!(user_only, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn team_grant_resolves_through_user_source_ids(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ insert_user(&pool, GRANTEE).await?;
+ let initiative_id = insert_initiative(&pool, OWNER, LinkShare::Off).await?;
+ insert_team(&pool, GRANTED_TEAM, OWNER).await?;
+ add_team_user(&pool, GRANTED_TEAM, GRANTEE, "member").await?;
+ grant(
+ &pool,
+ initiative_id,
+ &GRANTED_TEAM.to_string(),
+ "team",
+ AccessLevel::Comment,
+ )
+ .await?;
+
+ let requester = MacroUserIdStr::parse_from_str(GRANTEE).expect("valid requester id");
+ let source_ids = get_user_source_ids(&pool, Some(&*requester)).await?;
+ let access = get_initiative_access(&pool, &initiative_id, &source_ids).await?;
+
+ assert_eq!(access, Some(AccessLevel::Comment));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn team_link_grants_owner_team_members(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ insert_team(&pool, OWNER_TEAM, OWNER).await?;
+ add_team_user(&pool, OWNER_TEAM, OWNER, "owner").await?;
+ let initiative_id = insert_initiative(&pool, OWNER, LinkShare::Team(AccessLevel::View)).await?;
+
+ let owner_team = get_initiative_access(
+ &pool,
+ &initiative_id,
+ &sources(&[GRANTEE, &OWNER_TEAM.to_string()]),
+ )
+ .await?;
+ let other_team = get_initiative_access(
+ &pool,
+ &initiative_id,
+ &sources(&[GRANTEE, &OTHER_TEAM.to_string()]),
+ )
+ .await?;
+ let unauthenticated = get_initiative_access(&pool, &initiative_id, &anonymous()).await?;
+
+ assert_eq!(owner_team, Some(AccessLevel::View));
+ assert_eq!(other_team, None);
+ assert_eq!(unauthenticated, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn public_link_grants_anonymous_access(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let initiative_id =
+ insert_initiative(&pool, OWNER, LinkShare::Public(AccessLevel::Comment)).await?;
+
+ let unauthenticated = get_initiative_access(&pool, &initiative_id, &anonymous()).await?;
+ let stranger = get_initiative_access(&pool, &initiative_id, &sources(&[STRANGER])).await?;
+
+ assert_eq!(unauthenticated, Some(AccessLevel::Comment));
+ assert_eq!(stranger, Some(AccessLevel::Comment));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn no_grant_and_no_link_denies(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let initiative_id = insert_initiative(&pool, OWNER, LinkShare::Off).await?;
+
+ let stranger = get_initiative_access(&pool, &initiative_id, &sources(&[STRANGER])).await?;
+ let unauthenticated = get_initiative_access(&pool, &initiative_id, &anonymous()).await?;
+ let unknown = get_initiative_access(&pool, &Uuid::now_v7(), &sources(&[OWNER])).await?;
+
+ assert_eq!(stranger, None);
+ assert_eq!(unauthenticated, None);
+ assert_eq!(unknown, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn highest_level_across_arms_wins(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let public_higher =
+ insert_initiative(&pool, OWNER, LinkShare::Public(AccessLevel::Edit)).await?;
+ grant(&pool, public_higher, GRANTEE, "user", AccessLevel::View).await?;
+
+ let grant_higher =
+ insert_initiative(&pool, OWNER, LinkShare::Public(AccessLevel::View)).await?;
+ grant(&pool, grant_higher, GRANTEE, "user", AccessLevel::Edit).await?;
+
+ let from_public = get_initiative_access(&pool, &public_higher, &sources(&[GRANTEE])).await?;
+ let from_grant = get_initiative_access(&pool, &grant_higher, &sources(&[GRANTEE])).await?;
+
+ assert_eq!(from_public, Some(AccessLevel::Edit));
+ assert_eq!(from_grant, Some(AccessLevel::Edit));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn team_link_denies_when_owner_has_no_team(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let initiative_id = insert_initiative(&pool, OWNER, LinkShare::Team(AccessLevel::Edit)).await?;
+
+ let access = get_initiative_access(
+ &pool,
+ &initiative_id,
+ &sources(&[GRANTEE, &OTHER_TEAM.to_string()]),
+ )
+ .await?;
+
+ assert_eq!(access, None);
+ Ok(())
+}
+
+#[cfg(feature = "explain_binary")]
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn explain_agrees_with_access_level(pool: PgPool) -> anyhow::Result<()> {
+ use crate::domain::models::{AccessExplanation, AccessGrant, Entity, EntityType};
+
+ insert_user(&pool, OWNER).await?;
+ insert_team(&pool, OWNER_TEAM, OWNER).await?;
+ add_team_user(&pool, OWNER_TEAM, OWNER, "owner").await?;
+ let team_initiative =
+ insert_initiative(&pool, OWNER, LinkShare::Team(AccessLevel::View)).await?;
+ grant(&pool, team_initiative, GRANTEE, "user", AccessLevel::Edit).await?;
+
+ let src = sources(&[GRANTEE, &OWNER_TEAM.to_string()]);
+ let grants = explain_initiative_access(&pool, &team_initiative, &src).await?;
+ let explained = AccessExplanation::from_grants(
+ user(GRANTEE),
+ Entity {
+ entity_id: team_initiative.to_string(),
+ entity_type: EntityType::Initiative,
+ },
+ grants.clone(),
+ );
+ let queried = get_initiative_access(&pool, &team_initiative, &src).await?;
+
+ assert!(grants.iter().any(|grant| matches!(
+ grant,
+ AccessGrant::EntityAccess {
+ source_id,
+ access_level: AccessLevel::Edit,
+ ..
+ } if source_id == GRANTEE
+ )));
+ assert!(grants.iter().any(|grant| matches!(
+ grant,
+ AccessGrant::TeamLink {
+ access_level: AccessLevel::View,
+ owner_team_id,
+ } if *owner_team_id == OWNER_TEAM
+ )));
+ assert!(
+ !grants
+ .iter()
+ .any(|grant| matches!(grant, AccessGrant::PublicLink { .. }))
+ );
+ assert_eq!(explained.effective_access_level(), queried);
+ assert_eq!(queried, Some(AccessLevel::Edit));
+
+ let public_initiative =
+ insert_initiative(&pool, OWNER, LinkShare::Public(AccessLevel::Comment)).await?;
+ let public_grants = explain_initiative_access(&pool, &public_initiative, &anonymous()).await?;
+ assert_eq!(
+ public_grants,
+ vec![AccessGrant::PublicLink {
+ access_level: AccessLevel::Comment
+ }]
+ );
+ Ok(())
+}