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(ownership): scheduledaction typed owner entityaccess grants and receipts (#7257)

Will Hutchinsonb31578690df4
diff --git a/.sqlx/query-6698a34f1ed6f260bf83aee8dd6b50ac6af61a813d540a5e60942ead60de42e5.json b/.sqlx/query-1787312f37ce2a63f3a448f70e719581607988c79c9d2f4ead58811d60d5bec7.json
similarity index 56%
rename from .sqlx/query-6698a34f1ed6f260bf83aee8dd6b50ac6af61a813d540a5e60942ead60de42e5.json
rename to .sqlx/query-1787312f37ce2a63f3a448f70e719581607988c79c9d2f4ead58811d60d5bec7.json
index acb6bf88aa..3001af3ce5 100644
--- a/.sqlx/query-6698a34f1ed6f260bf83aee8dd6b50ac6af61a813d540a5e60942ead60de42e5.json
+++ b/.sqlx/query-1787312f37ce2a63f3a448f70e719581607988c79c9d2f4ead58811d60d5bec7.json
@@ -1,15 +1,14 @@
{
"db_name": "PostgreSQL",
- "query": "\n DELETE FROM scheduled_action\n WHERE id = $1 AND owner = $2\n ",
+ "query": "\n DELETE FROM scheduled_action\n WHERE id = $1\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
- "Uuid",
- "Text"
+ "Uuid"
]
},
"nullable": []
},
- "hash": "6698a34f1ed6f260bf83aee8dd6b50ac6af61a813d540a5e60942ead60de42e5"
+ "hash": "1787312f37ce2a63f3a448f70e719581607988c79c9d2f4ead58811d60d5bec7"
}
diff --git a/.sqlx/query-ba729b8cb47ea097fd61d047b968b5de0a47e7955becb6183d2636fabf801429.json b/.sqlx/query-3319425b09d174caa61311c5db42f9b1bb5bb2b9cf667e4331b6b076810dd034.json
similarity index 91%
rename from .sqlx/query-ba729b8cb47ea097fd61d047b968b5de0a47e7955becb6183d2636fabf801429.json
rename to .sqlx/query-3319425b09d174caa61311c5db42f9b1bb5bb2b9cf667e4331b6b076810dd034.json
index baa382e597..f1bb8aeb02 100644
--- a/.sqlx/query-ba729b8cb47ea097fd61d047b968b5de0a47e7955becb6183d2636fabf801429.json
+++ b/.sqlx/query-3319425b09d174caa61311c5db42f9b1bb5bb2b9cf667e4331b6b076810dd034.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at\n FROM scheduled_action\n WHERE id = $1 AND owner = $2\n ",
+ "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at\n FROM scheduled_action\n WHERE id = $1\n ",
"describe": {
"columns": [
{
@@ -86,8 +86,7 @@
],
"parameters": {
"Left": [
- "Uuid",
- "Text"
+ "Uuid"
]
},
"nullable": [
@@ -109,5 +108,5 @@
true
]
},
- "hash": "ba729b8cb47ea097fd61d047b968b5de0a47e7955becb6183d2636fabf801429"
+ "hash": "3319425b09d174caa61311c5db42f9b1bb5bb2b9cf667e4331b6b076810dd034"
}
diff --git a/.sqlx/query-3ba1b5f429b1d41317e5b607e8d49d4ba9ca16f05ae85c224476b30aecfca3c4.json b/.sqlx/query-3ba1b5f429b1d41317e5b607e8d49d4ba9ca16f05ae85c224476b30aecfca3c4.json
new file mode 100644
index 0000000000..f5e938e96e
--- /dev/null
+++ b/.sqlx/query-3ba1b5f429b1d41317e5b607e8d49d4ba9ca16f05ae85c224476b30aecfca3c4.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO macro_user (id, username, email, stripe_customer_id)\n VALUES ($1, $2, $3, $2)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3ba1b5f429b1d41317e5b607e8d49d4ba9ca16f05ae85c224476b30aecfca3c4"
+}
diff --git a/.sqlx/query-5df1ebd365045326be20bde16b25580d273cbc9c8cdf99b84b44f4e4eacc4885.json b/.sqlx/query-5df1ebd365045326be20bde16b25580d273cbc9c8cdf99b84b44f4e4eacc4885.json
new file mode 100644
index 0000000000..4017f592e7
--- /dev/null
+++ b/.sqlx/query-5df1ebd365045326be20bde16b25580d273cbc9c8cdf99b84b44f4e4eacc4885.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity (id, entity_type, owner_type, owner_id)\n VALUES ($1, 'scheduled_action', 'user', 'macro|[email protected]')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5df1ebd365045326be20bde16b25580d273cbc9c8cdf99b84b44f4e4eacc4885"
+}
diff --git a/.sqlx/query-650b4cd0147a1ccb52430eb4879f77ff76e035e74e9b958745c3baefac59415b.json b/.sqlx/query-650b4cd0147a1ccb52430eb4879f77ff76e035e74e9b958745c3baefac59415b.json
new file mode 100644
index 0000000000..be74de2a43
--- /dev/null
+++ b/.sqlx/query-650b4cd0147a1ccb52430eb4879f77ff76e035e74e9b958745c3baefac59415b.json
@@ -0,0 +1,112 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at\n FROM scheduled_action\n WHERE id = ANY($1)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "schedule",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "timezone",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "task",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 7,
+ "name": "claimed",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "next_run_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 11,
+ "name": "enabled",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "trigger_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
+ "name": "event_filters",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 14,
+ "name": "configuration_revision",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 15,
+ "name": "event_activated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ false,
+ true,
+ false,
+ true,
+ false,
+ false,
+ true,
+ false,
+ false,
+ true,
+ false,
+ true
+ ]
+ },
+ "hash": "650b4cd0147a1ccb52430eb4879f77ff76e035e74e9b958745c3baefac59415b"
+}
diff --git a/.sqlx/query-83aa76a5608d26ff825dfe283bd6db93c5ccbed720a5ad29a36eaaea2fe32a90.json b/.sqlx/query-83aa76a5608d26ff825dfe283bd6db93c5ccbed720a5ad29a36eaaea2fe32a90.json
new file mode 100644
index 0000000000..9bf664e2ca
--- /dev/null
+++ b/.sqlx/query-83aa76a5608d26ff825dfe283bd6db93c5ccbed720a5ad29a36eaaea2fe32a90.json
@@ -0,0 +1,18 @@
+{
+ "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, $2, $3, $4::text::entity_access_source_type, $5::text::\"AccessLevel\")\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "83aa76a5608d26ff825dfe283bd6db93c5ccbed720a5ad29a36eaaea2fe32a90"
+}
diff --git a/.sqlx/query-bc3992d24b7ddccaca9a279d9cd5ee7ee8c88cc958432fa5b5a79b2cb78e1a53.json b/.sqlx/query-bc3992d24b7ddccaca9a279d9cd5ee7ee8c88cc958432fa5b5a79b2cb78e1a53.json
new file mode 100644
index 0000000000..b759bd66b8
--- /dev/null
+++ b/.sqlx/query-bc3992d24b7ddccaca9a279d9cd5ee7ee8c88cc958432fa5b5a79b2cb78e1a53.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT access_level AS \"access_level!: AccessLevel\"\n FROM entity_access\n WHERE entity_id = $1 AND entity_type = 'scheduled_action' AND source_id = ANY($2)\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": [
+ false
+ ]
+ },
+ "hash": "bc3992d24b7ddccaca9a279d9cd5ee7ee8c88cc958432fa5b5a79b2cb78e1a53"
+}
diff --git a/.sqlx/query-c30723f16aa362fb2ea817c8550babcf551858c45dea5facc00775defcb0bd95.json b/.sqlx/query-c30723f16aa362fb2ea817c8550babcf551858c45dea5facc00775defcb0bd95.json
new file mode 100644
index 0000000000..811e41b226
--- /dev/null
+++ b/.sqlx/query-c30723f16aa362fb2ea817c8550babcf551858c45dea5facc00775defcb0bd95.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT DISTINCT ea.entity_id\n FROM entity_access ea\n JOIN scheduled_action sa ON sa.id = ea.entity_id\n WHERE ea.entity_type = 'scheduled_action' AND ea.source_id = ANY($1)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "c30723f16aa362fb2ea817c8550babcf551858c45dea5facc00775defcb0bd95"
+}
diff --git a/.sqlx/query-c95fe44857da7de19d5f72d146238283bdfcc125f856829d669e8717379a4805.json b/.sqlx/query-c95fe44857da7de19d5f72d146238283bdfcc125f856829d669e8717379a4805.json
new file mode 100644
index 0000000000..547b6b3405
--- /dev/null
+++ b/.sqlx/query-c95fe44857da7de19d5f72d146238283bdfcc125f856829d669e8717379a4805.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE entity_access\n SET access_level = 'view'\n WHERE entity_id = $1 AND entity_type = 'scheduled_action'\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c95fe44857da7de19d5f72d146238283bdfcc125f856829d669e8717379a4805"
+}
diff --git a/.sqlx/query-e2267d44c0767ecc833984a98488623ffca5cdd79dd448f66196db389906e8d5.json b/.sqlx/query-e2267d44c0767ecc833984a98488623ffca5cdd79dd448f66196db389906e8d5.json
new file mode 100644
index 0000000000..9b23a0572f
--- /dev/null
+++ b/.sqlx/query-e2267d44c0767ecc833984a98488623ffca5cdd79dd448f66196db389906e8d5.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO scheduled_action\n (id, owner, name, schedule, kind, timezone, task, next_run_at, enabled)\n VALUES ($1, $2, 'legacy', $3, 'Agent', 'UTC', $4, $5, true)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e2267d44c0767ecc833984a98488623ffca5cdd79dd448f66196db389906e8d5"
+}
diff --git a/.sqlx/query-4889cf7b6100a28da3f99b43b9264f7607636456460db845b8abfe3814b7b7f7.json b/.sqlx/query-ede240f34972b67da0876150e37e382f7b1c28ea0ad00f2ba330dfe8a3441934.json
similarity index 74%
rename from .sqlx/query-4889cf7b6100a28da3f99b43b9264f7607636456460db845b8abfe3814b7b7f7.json
rename to .sqlx/query-ede240f34972b67da0876150e37e382f7b1c28ea0ad00f2ba330dfe8a3441934.json
index c893416058..cc158d0458 100644
--- a/.sqlx/query-4889cf7b6100a28da3f99b43b9264f7607636456460db845b8abfe3814b7b7f7.json
+++ b/.sqlx/query-ede240f34972b67da0876150e37e382f7b1c28ea0ad00f2ba330dfe8a3441934.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE scheduled_action\n SET name = $1,\n schedule = $2,\n kind = $3,\n timezone = $4,\n task = $5,\n next_run_at = $6,\n enabled = $7,\n trigger_type = $8,\n event_filters = $9,\n configuration_revision = $10,\n event_activated_at = $11,\n updated_at = now()\n WHERE id = $12 AND owner = $13\n AND configuration_revision = $10::bigint - 1\n AND (\n claimed IS NULL OR claimed < $14\n OR (\n NOT $7 AND name = $1 AND kind = $3 AND task = $5\n AND trigger_type = $8\n AND schedule IS NOT DISTINCT FROM $2\n AND timezone IS NOT DISTINCT FROM $4\n AND event_filters IS NOT DISTINCT FROM $9\n )\n )\n RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at\n ",
+ "query": "\n UPDATE scheduled_action\n SET name = $1,\n schedule = $2,\n kind = $3,\n timezone = $4,\n task = $5,\n next_run_at = $6,\n enabled = $7,\n trigger_type = $8,\n event_filters = $9,\n configuration_revision = $10,\n event_activated_at = $11,\n updated_at = now()\n WHERE id = $12\n AND configuration_revision = $10::bigint - 1\n AND (\n claimed IS NULL OR claimed < $13\n OR (\n NOT $7 AND name = $1 AND kind = $3 AND task = $5\n AND trigger_type = $8\n AND schedule IS NOT DISTINCT FROM $2\n AND timezone IS NOT DISTINCT FROM $4\n AND event_filters IS NOT DISTINCT FROM $9\n )\n )\n RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at\n ",
"describe": {
"columns": [
{
@@ -98,7 +98,6 @@
"Int8",
"Timestamptz",
"Uuid",
- "Text",
"Timestamptz"
]
},
@@ -121,5 +120,5 @@
true
]
},
- "hash": "4889cf7b6100a28da3f99b43b9264f7607636456460db845b8abfe3814b7b7f7"
+ "hash": "ede240f34972b67da0876150e37e382f7b1c28ea0ad00f2ba330dfe8a3441934"
}
diff --git a/.sqlx/query-f917f7fe8609711fe7beb3033b422d44877e9462f2dc83fd12f6c1df0dbb33b0.json b/.sqlx/query-f917f7fe8609711fe7beb3033b422d44877e9462f2dc83fd12f6c1df0dbb33b0.json
new file mode 100644
index 0000000000..810aff2022
--- /dev/null
+++ b/.sqlx/query-f917f7fe8609711fe7beb3033b422d44877e9462f2dc83fd12f6c1df0dbb33b0.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO scheduled_action (\n id, owner, name, schedule, kind, timezone, task, next_run_at, enabled\n )\n VALUES ($1, $2, 'routine', '0 * * * *', 'Agent', 'UTC', '{}'::jsonb, NOW(), true)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f917f7fe8609711fe7beb3033b422d44877e9462f2dc83fd12f6c1df0dbb33b0"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 9245b23eb7..280ec26a3f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15812,6 +15812,7 @@ dependencies = [
"documents",
"doppler-config",
"entity_access",
+ "entity_access_db_utils",
"entity_registry",
"entity_registry_db_utils",
"futures",
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts
index f2e598e215..049508ba81 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts
@@ -143,6 +143,11 @@ export type createScheduledActionResponse401 = {
status: 401;
};
+export type createScheduledActionResponse403 = {
+ data: string;
+ status: 403;
+};
+
export type createScheduledActionResponse500 = {
data: string;
status: 500;
@@ -155,6 +160,7 @@ export type createScheduledActionResponseSuccess =
export type createScheduledActionResponseError = (
| createScheduledActionResponse400
| createScheduledActionResponse401
+ | createScheduledActionResponse403
| createScheduledActionResponse500
) & {
headers: Headers;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
index b6a14e699e..cdc331a606 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
@@ -134,6 +134,16 @@
}
}
},
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index 93a2000c5a..3fd2b10a94 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -668,7 +668,7 @@ where
resolve_task_initiative_references(ctx, self.user_id.clone(), task_ids).await
}
- /// AI routines owned by the authenticated user.
+ /// AI routines the authenticated user can access.
async fn scheduled_actions(
&self,
ctx: &Context<'_>,
diff --git a/crates/complete_graph/src/schema/test/scheduled_actions.rs b/crates/complete_graph/src/schema/test/scheduled_actions.rs
index 078edaafc7..7e4b0cdce2 100644
--- a/crates/complete_graph/src/schema/test/scheduled_actions.rs
+++ b/crates/complete_graph/src/schema/test/scheduled_actions.rs
@@ -11,7 +11,7 @@ struct RecordingScheduledActionReader {
}
impl ScheduledActionReadService for RecordingScheduledActionReader {
- async fn list_owned(
+ async fn list_accessible(
&self,
user_id: MacroUserIdStr<'static>,
) -> Result<Vec<ScheduledAction>, Report> {
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index 43167259d2..dcac12d81e 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -476,7 +476,7 @@ fn scheduled_actions_hang_off_the_authenticated_user() {
&sdl,
"union GraphqlScheduledActionTrigger = GraphqlScheduledActionCronTrigger | GraphqlScheduledActionEventsTrigger",
);
- assert!(sdl.contains("AI routines owned by the authenticated user."));
+ assert!(sdl.contains("AI routines the authenticated user can access."));
for value in [
"DOCUMENT_CREATED",
"DOCUMENT_UPDATED",
diff --git a/crates/entity_access/src/domain/ports.rs b/crates/entity_access/src/domain/ports.rs
index 9b39c1007c..c3597c9075 100644
--- a/crates/entity_access/src/domain/ports.rs
+++ b/crates/entity_access/src/domain/ports.rs
@@ -81,6 +81,22 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
initiative_id: &str,
user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
+
+ /// Highest grant the caller's sources hold on one scheduled action.
+ ///
+ /// A non-uuid id is not a routine, so the lookup returns `None`.
+ fn get_scheduled_action_access(
+ &self,
+ scheduled_action_id: &str,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
+
+ /// Live scheduled action ids the caller's sources can manage.
+ fn accessible_scheduled_action_ids(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> impl Future<Output = Result<Vec<Uuid>, AccessError>> + Send;
+
/// Document owning an agent session's still-live originating message thread.
/// This is a persisted relationship, not a caller-supplied grant.
fn get_agent_session_document(
@@ -261,6 +277,16 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
) -> impl Future<Output = Result<Option<UserTeamInfo>, AccessError>> + Send;
}
+/// Scheduled actions the user can reach through any of their sources
+/// (user id, active channels, teams). Source resolution stays inside entity_access.
+pub trait ScheduledActionGrants: Send + Sync + 'static {
+ /// Ids of live scheduled actions `user_id` can manage.
+ fn accessible_scheduled_action_ids(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> impl Future<Output = Result<Vec<Uuid>, AccessError>> + Send;
+}
+
/// Repository that returns labeled grant paths instead of a collapsed level.
#[cfg(feature = "explain_binary")]
pub trait ExplainAccessRepository: Clone + Send + Sync + 'static {
diff --git a/crates/entity_access/src/domain/service.rs b/crates/entity_access/src/domain/service.rs
index 5cec82bb4d..a43f833553 100644
--- a/crates/entity_access/src/domain/service.rs
+++ b/crates/entity_access/src/domain/service.rs
@@ -8,7 +8,7 @@ use crate::domain::{
CrmEntityAccess, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission,
EntityType, RequiredPermission, TeamRole, UserTeamInfo, ViewAccessLevel,
},
- ports::{AccessRepository, EntityAccessService},
+ ports::{AccessRepository, EntityAccessService, ScheduledActionGrants},
};
use futures::{StreamExt, stream};
use macro_user_id::{
@@ -68,6 +68,11 @@ where
Ok(direct.max(inherited))
}
EntityType::Initiative => self.repo.get_initiative_access(entity_id, user_id).await,
+ EntityType::ScheduledAction => {
+ self.repo
+ .get_scheduled_action_access(entity_id, user_id)
+ .await
+ }
EntityType::CalendarEvent => {
self.repo
.get_calendar_event_access(entity_id, user_id)
@@ -440,7 +445,8 @@ where
| EntityType::Call
| EntityType::CalendarEvent
| EntityType::AgentSession
- | EntityType::Initiative => {
+ | EntityType::Initiative
+ | EntityType::ScheduledAction => {
self.get_optimized_access(entity_id, user_id, entity_type)
.await
}
@@ -462,8 +468,7 @@ where
EntityType::Team
| EntityType::User
| EntityType::ChannelMessage
- | EntityType::Skill
- | EntityType::ScheduledAction => Ok(None),
+ | EntityType::Skill => Ok(None),
}
}
@@ -517,7 +522,8 @@ where
| EntityType::Call
| EntityType::CalendarEvent
| EntityType::AgentSession
- | EntityType::Initiative => {
+ | EntityType::Initiative
+ | EntityType::ScheduledAction => {
let access = self
.get_optimized_access(entity_id, user_id, entity_type)
.await?;
@@ -682,6 +688,15 @@ where
}
}
+impl<R: AccessRepository> ScheduledActionGrants for EntityAccessServiceImpl<R> {
+ async fn accessible_scheduled_action_ids(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Vec<Uuid>, AccessError> {
+ self.repo.accessible_scheduled_action_ids(user_id).await
+ }
+}
+
fn channel_role_result_to_permission(
result: ChannelRoleResult,
) -> Result<EntityPermission, AccessError> {
diff --git a/crates/entity_access/src/domain/service/test.rs b/crates/entity_access/src/domain/service/test.rs
index 862a7609b7..6063fd763b 100644
--- a/crates/entity_access/src/domain/service/test.rs
+++ b/crates/entity_access/src/domain/service/test.rs
@@ -8,6 +8,7 @@ use crate::domain::models::{
MemberParticipantRole, MemberTeamRole, OwnerParticipantRole, ParticipantRole, UserTeamInfo,
ViewAccessLevel, ViewOnly,
};
+use crate::domain::ports::ScheduledActionGrants;
use macro_user_id::user_id::MacroUserIdStr;
use models_permissions::share_permission::access_level::OwnerAccessLevel;
use std::sync::{
@@ -29,6 +30,8 @@ struct MockRepo {
call_access: Arc<Mutex<Option<AccessLevel>>>,
agent_session_access: Arc<Mutex<Option<AccessLevel>>>,
initiative_access: Arc<Mutex<Option<AccessLevel>>>,
+ scheduled_action_access: Arc<Mutex<Option<AccessLevel>>>,
+ accessible_scheduled_action_ids: Arc<Mutex<Vec<Uuid>>>,
agent_session_document: Arc<Mutex<Option<String>>>,
reminder_access: Arc<Mutex<Option<AccessLevel>>>,
team_entity_access: Arc<Mutex<Option<AccessLevel>>>,
@@ -68,6 +71,8 @@ impl MockRepo {
call_access: Arc::new(Mutex::new(None)),
agent_session_access: Arc::new(Mutex::new(None)),
initiative_access: Arc::new(Mutex::new(None)),
+ scheduled_action_access: Arc::new(Mutex::new(None)),
+ accessible_scheduled_action_ids: Arc::new(Mutex::new(Vec::new())),
agent_session_document: Arc::default(),
reminder_access: Arc::new(Mutex::new(None)),
team_entity_access: Arc::new(Mutex::new(None)),
@@ -136,6 +141,16 @@ impl MockRepo {
self
}
+ fn with_scheduled_action_access(mut self, level: AccessLevel) -> Self {
+ self.scheduled_action_access = Arc::new(Mutex::new(Some(level)));
+ self
+ }
+
+ fn with_accessible_scheduled_action_ids(mut self, ids: Vec<Uuid>) -> Self {
+ self.accessible_scheduled_action_ids = Arc::new(Mutex::new(ids));
+ self
+ }
+
fn with_team_entity_access(mut self, level: AccessLevel) -> Self {
self.team_entity_access = Arc::new(Mutex::new(Some(level)));
self
@@ -328,6 +343,21 @@ impl AccessRepository for MockRepo {
Ok(*self.initiative_access.lock().await)
}
+ async fn get_scheduled_action_access(
+ &self,
+ _scheduled_action_id: &str,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Ok(*self.scheduled_action_access.lock().await)
+ }
+
+ async fn accessible_scheduled_action_ids(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Vec<Uuid>, AccessError> {
+ Ok(self.accessible_scheduled_action_ids.lock().await.clone())
+ }
+
async fn get_reminder_access(
&self,
_reminder_id: &str,
@@ -779,6 +809,79 @@ async fn test_get_entity_permission_agent_session_no_access_returns_unauthorized
assert!(matches!(result, Err(AccessError::Unauthorized)));
}
+#[tokio::test]
+async fn test_get_access_level_scheduled_action_returns_scripted_level() {
+ let repo = MockRepo::new().with_scheduled_action_access(AccessLevel::Edit);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_access_level(
+ Some(&user_id),
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::ScheduledAction,
+ )
+ .await;
+
+ assert_eq!(result.unwrap(), Some(AccessLevel::Edit));
+}
+
+#[tokio::test]
+async fn test_get_entity_permission_scheduled_action_returns_scripted_level() {
+ let repo = MockRepo::new().with_scheduled_action_access(AccessLevel::Edit);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .get_entity_permission(
+ Some(&user_id),
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::ScheduledAction,
+ None,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ result,
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit
+ }
+ );
+}
+
+#[tokio::test]
+async fn test_get_entity_permission_scheduled_action_without_grant_is_unauthorized() {
+ let service = EntityAccessServiceImpl::new(MockRepo::new());
+ let user_id = test_user_id();
+
+ let result = service
+ .get_entity_permission(
+ Some(&user_id),
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::ScheduledAction,
+ None,
+ )
+ .await;
+
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+}
+
+#[tokio::test]
+async fn test_accessible_scheduled_action_ids_passes_through() {
+ let id = Uuid::from_u128(0x0000_0000_0000_0000_0000_0000_0000_5a01);
+ let repo = MockRepo::new().with_accessible_scheduled_action_ids(vec![id]);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let ids = service
+ .accessible_scheduled_action_ids(&user_id)
+ .await
+ .unwrap();
+
+ assert_eq!(ids, vec![id]);
+}
+
#[tokio::test]
async fn test_get_entity_permission_foreign_entity_returns_view_access_level() {
let repo = MockRepo::new().with_foreign_entity_access(true);
diff --git a/crates/entity_access/src/inbound/axum_extractors.rs b/crates/entity_access/src/inbound/axum_extractors.rs
index 123fec2aa3..34279b46c1 100644
--- a/crates/entity_access/src/inbound/axum_extractors.rs
+++ b/crates/entity_access/src/inbound/axum_extractors.rs
@@ -23,6 +23,7 @@ mod pin;
mod principal;
mod project;
mod reminder;
+mod scheduled_action;
mod team;
mod thread;
@@ -40,6 +41,7 @@ pub use pin::PinAccessLevelExtractor;
pub use principal::principal_entity_access_receipt;
pub use project::{ProjectAccessLevelExtractor, ProjectBodyAccessLevelExtractorV2};
pub use reminder::ReminderAccessExtractor;
+pub use scheduled_action::ScheduledActionAccessExtractor;
pub use team::{MacroUserTeamExtractorV2, OptionalMacroUserTeamExtractorV2};
pub use thread::ThreadAccessLevelExtractor;
diff --git a/crates/entity_access/src/inbound/axum_extractors/scheduled_action.rs b/crates/entity_access/src/inbound/axum_extractors/scheduled_action.rs
new file mode 100644
index 0000000000..958895e4aa
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/scheduled_action.rs
@@ -0,0 +1,125 @@
+//! Authorizes one scheduled action for a caller who may manage it.
+//!
+//! The grant is an `entity_access` row with `entity_type = 'scheduled_action'`.
+//! Unlike the agent-session extractor, an anonymous caller is not given View,
+//! an internal caller must name an acting user (a routine runs as a person, so
+//! a user-less receipt authorizes nothing), and the route parameter is `{id}`.
+
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+use axum::{
+ RequestPartsExt,
+ extract::{FromRef, FromRequestParts, Path},
+ http::request::Parts,
+};
+use macro_authorization::{
+ AnyPrincipal, MacroAuthorization, MacroAuthorizationService, MacroAuthorizationState,
+ OptionalMacroAuthorizationExtractor,
+};
+use uuid::Uuid;
+
+use super::{ExtractorError, bot::generate_bot_entity_access_receipt};
+use crate::domain::{
+ models::{Entity, EntityAccessAuth, EntityAccessReceipt, EntityType, RequiredPermission},
+ ports::EntityAccessService,
+};
+
+#[derive(Debug, serde::Deserialize)]
+struct ScheduledActionAccessParams {
+ id: Uuid,
+}
+
+/// Receipt for the scheduled action named by the `{id}` path parameter.
+#[derive(Debug)]
+pub struct ScheduledActionAccessExtractor<T: RequiredPermission, Svc, Auth> {
+ /// Capability for this routine at permission `T` or stronger.
+ pub entity_access_receipt: EntityAccessReceipt<T>,
+ _marker: PhantomData<(T, Svc, Auth)>,
+}
+
+impl<T, S, Svc, Auth> FromRequestParts<S> for ScheduledActionAccessExtractor<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)?;
+
+ let Path(ScheduledActionAccessParams { id }) = parts
+ .extract::<Path<ScheduledActionAccessParams>>()
+ .await
+ .map_err(|_| {
+ ExtractorError::BadRequest("missing scheduled action id path parameter")
+ })?;
+
+ if let Some(MacroAuthorization::Bot(authentication)) = authorization.authorization.as_ref()
+ {
+ let entity_access_receipt = generate_bot_entity_access_receipt::<T>(
+ service.as_ref(),
+ authentication,
+ &id.to_string(),
+ EntityType::ScheduledAction,
+ )
+ .await?;
+
+ return Ok(Self {
+ entity_access_receipt,
+ _marker: PhantomData,
+ });
+ }
+
+ let Some(user) = authorization
+ .authorization
+ .as_ref()
+ .and_then(MacroAuthorization::acting_user)
+ .map(|user| user.macro_user_id.clone())
+ else {
+ return Err(ExtractorError::Unauthorized);
+ };
+
+ let permission = service
+ .get_entity_permission(
+ Some(&user),
+ &id.to_string(),
+ EntityType::ScheduledAction,
+ None,
+ )
+ .await
+ .map_err(ExtractorError::from)?;
+
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::Unauthorized);
+ }
+
+ Ok(Self {
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: id.to_string(),
+ entity_type: EntityType::ScheduledAction,
+ },
+ auth: EntityAccessAuth::Authenticated(user),
+ entity_permission: permission,
+ _marker: PhantomData,
+ },
+ _marker: PhantomData,
+ })
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/entity_access/src/inbound/axum_extractors/scheduled_action/test.rs b/crates/entity_access/src/inbound/axum_extractors/scheduled_action/test.rs
new file mode 100644
index 0000000000..2c77ab88bd
--- /dev/null
+++ b/crates/entity_access/src/inbound/axum_extractors/scheduled_action/test.rs
@@ -0,0 +1,228 @@
+use axum::{
+ Router,
+ body::Body,
+ http::{Request, StatusCode, header},
+ routing::put,
+};
+use macro_authorization::{BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotScope, INTERNAL_API_KEY_HEADER};
+use macro_user_id::user_id::MacroUserIdStr;
+use tower::ServiceExt;
+
+use super::*;
+use crate::{
+ domain::models::{
+ AccessLevel, BotAccessScope, EditAccessLevel, EntityPermission, OwnerAccessLevel,
+ ViewAccessLevel,
+ },
+ inbound::axum_extractors::test_support::{
+ BOT_ACTING_USER_ID, BOT_ACTING_USER_ORGANIZATION_ID, BOT_ID, BotAccessCall,
+ FakeAuthorizationService, FakeEntityAccessService, INTERNAL_KEY, TestState, USER_ID,
+ VALID_BOT_TOKEN,
+ },
+};
+
+const ACTION_ID: &str = "11111111-1111-4111-8111-111111111111";
+
+type EditExtractor = ScheduledActionAccessExtractor<
+ EditAccessLevel,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+>;
+type OwnerExtractor = ScheduledActionAccessExtractor<
+ OwnerAccessLevel,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+>;
+type ViewExtractor = ScheduledActionAccessExtractor<
+ ViewAccessLevel,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+>;
+
+fn user_request() -> Request<Body> {
+ Request::put(format!("/scheduled-actions/{ACTION_ID}"))
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .body(Body::empty())
+ .unwrap()
+}
+
+async fn status(app: Router, request: Request<Body>) -> StatusCode {
+ app.oneshot(request).await.unwrap().status()
+}
+
+fn assert_authenticated(auth: &EntityAccessAuth) {
+ assert!(matches!(
+ auth,
+ EntityAccessAuth::Authenticated(user) if user.as_ref() == USER_ID
+ ));
+}
+
+#[tokio::test]
+async fn edit_route_accepts_edit_and_owner_and_rejects_view() {
+ for (level, expected) in [
+ (AccessLevel::Edit, StatusCode::NO_CONTENT),
+ (AccessLevel::Owner, StatusCode::NO_CONTENT),
+ (AccessLevel::View, StatusCode::UNAUTHORIZED),
+ ] {
+ let state = TestState::new(Some(level));
+ let app = Router::new()
+ .route(
+ "/scheduled-actions/{id}",
+ put(move |access: EditExtractor| async move {
+ assert_authenticated(access.entity_access_receipt.auth());
+ assert_eq!(
+ access.entity_access_receipt.entity_permission(),
+ &EntityPermission::AccessLevel {
+ access_level: level
+ }
+ );
+ StatusCode::NO_CONTENT
+ }),
+ )
+ .with_state(state);
+ assert_eq!(status(app, user_request()).await, expected, "{level:?}");
+ }
+}
+
+#[tokio::test]
+async fn owner_route_rejects_edit() {
+ let state = TestState::new(Some(AccessLevel::Edit));
+ let app = Router::new()
+ .route(
+ "/scheduled-actions/{id}",
+ put(|_access: OwnerExtractor| async { StatusCode::NO_CONTENT }),
+ )
+ .with_state(state);
+ assert_eq!(status(app, user_request()).await, StatusCode::UNAUTHORIZED);
+}
+
+#[tokio::test]
+async fn view_route_accepts_view() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let app = Router::new()
+ .route(
+ "/scheduled-actions/{id}",
+ put(|access: ViewExtractor| async move {
+ assert_authenticated(access.entity_access_receipt.auth());
+ assert_eq!(
+ access.entity_access_receipt.entity_permission(),
+ &EntityPermission::AccessLevel {
+ access_level: AccessLevel::View
+ }
+ );
+ StatusCode::NO_CONTENT
+ }),
+ )
+ .with_state(state);
+ assert_eq!(status(app, user_request()).await, StatusCode::NO_CONTENT);
+}
+
+#[tokio::test]
+async fn missing_grant_is_unauthorized() {
+ let state = TestState::new(None);
+ let app = Router::new()
+ .route(
+ "/scheduled-actions/{id}",
+ put(|_access: ViewExtractor| async { StatusCode::NO_CONTENT }),
+ )
+ .with_state(state);
+ assert_eq!(status(app, user_request()).await, StatusCode::UNAUTHORIZED);
+}
+
+#[tokio::test]
+async fn anonymous_is_unauthorized_without_a_lookup() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let app = Router::new()
+ .route(
+ "/scheduled-actions/{id}",
+ put(|_access: ViewExtractor| async { StatusCode::NO_CONTENT }),
+ )
+ .with_state(state.clone());
+ let request = Request::put(format!("/scheduled-actions/{ACTION_ID}"))
+ .body(Body::empty())
+ .unwrap();
+
+ assert_eq!(status(app, request).await, StatusCode::UNAUTHORIZED);
+ assert_eq!(state.entity_access.calls(), []);
+ assert_eq!(state.entity_access.bot_calls(), []);
+}
+
+#[tokio::test]
+async fn user_scoped_bot_uses_scheduled_action_bot_receipt() {
+ let state = TestState::new(Some(AccessLevel::View));
+ let app = Router::new()
+ .route(
+ "/scheduled-actions/{id}",
+ put(|access: ViewExtractor| async move {
+ assert!(matches!(
+ access.entity_access_receipt.auth(),
+ EntityAccessAuth::Bot(_)
+ ));
+ assert_eq!(
+ access.entity_access_receipt.entity_permission(),
+ &EntityPermission::AccessLevel {
+ access_level: AccessLevel::View
+ }
+ );
+ StatusCode::NO_CONTENT
+ }),
+ )
+ .with_state(state.clone());
+ let request = Request::put(format!("/scheduled-actions/{ACTION_ID}"))
+ .header(BOT_TOKEN_HEADER, VALID_BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, BotScope::User.as_str())
+ .body(Body::empty())
+ .unwrap();
+
+ assert_eq!(status(app, request).await, StatusCode::NO_CONTENT);
+ 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"),
+ user_org_id: Some(i64::from(BOT_ACTING_USER_ORGANIZATION_ID)),
+ },
+ entity_id: ACTION_ID.to_string(),
+ entity_type: EntityType::ScheduledAction,
+ }]
+ );
+ assert_eq!(state.entity_access.calls(), []);
+}
+
+#[tokio::test]
+async fn internal_without_user_is_unauthorized_without_a_lookup() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let app = Router::new()
+ .route(
+ "/scheduled-actions/{id}",
+ put(|_access: ViewExtractor| async { StatusCode::NO_CONTENT }),
+ )
+ .with_state(state.clone());
+ let request = Request::put(format!("/scheduled-actions/{ACTION_ID}"))
+ .header(INTERNAL_API_KEY_HEADER, INTERNAL_KEY)
+ .body(Body::empty())
+ .unwrap();
+
+ assert_eq!(status(app, request).await, StatusCode::UNAUTHORIZED);
+ assert_eq!(state.entity_access.calls(), []);
+ assert_eq!(state.entity_access.bot_calls(), []);
+}
+
+#[tokio::test]
+async fn malformed_id_is_bad_request() {
+ let state = TestState::new(Some(AccessLevel::Owner));
+ let app = Router::new()
+ .route(
+ "/scheduled-actions/{id}",
+ put(|_access: ViewExtractor| async { StatusCode::NO_CONTENT }),
+ )
+ .with_state(state.clone());
+ let request = Request::put("/scheduled-actions/not-a-uuid")
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .body(Body::empty())
+ .unwrap();
+
+ assert_eq!(status(app, request).await, StatusCode::BAD_REQUEST);
+ assert_eq!(state.entity_access.calls(), []);
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo.rs b/crates/entity_access/src/outbound/pg_access_repo.rs
index 76870a2cc8..9fa5a9255a 100644
--- a/crates/entity_access/src/outbound/pg_access_repo.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo.rs
@@ -290,6 +290,43 @@ impl AccessRepository for PgAccessRepository {
.await?)
}
+ async fn get_scheduled_action_access(
+ &self,
+ scheduled_action_id: &str,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ let Ok(scheduled_action_uuid) = scheduled_action_id.parse::<Uuid>() else {
+ return Ok(None);
+ };
+ let source_ids = queries::get_user_source_ids(&self.pool, user_id)
+ .await
+ .map_err(anyhow_access_error)?;
+ Ok(
+ queries::scheduled_action_access::get_scheduled_action_access(
+ &self.pool,
+ &scheduled_action_uuid,
+ &source_ids,
+ )
+ .await?,
+ )
+ }
+
+ async fn accessible_scheduled_action_ids(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Vec<Uuid>, AccessError> {
+ let source_ids = queries::get_user_source_ids(&self.pool, Some(user_id))
+ .await
+ .map_err(anyhow_access_error)?;
+ Ok(
+ queries::scheduled_action_access::accessible_scheduled_action_ids(
+ &self.pool,
+ &source_ids,
+ )
+ .await?,
+ )
+ }
+
// A macro user id embeds the user's email, so it stays out of the span; the
// reminder id is what identifies the lookup anyway.
#[tracing::instrument(err, skip(self, user_id))]
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries.rs b/crates/entity_access/src/outbound/pg_access_repo/queries.rs
index bd9881cca0..1e71bb90a7 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries.rs
@@ -34,6 +34,7 @@ pub mod document_access;
pub mod foreign_entity_access;
pub mod initiative_access;
pub mod project_access;
+pub mod scheduled_action_access;
pub mod team_access;
pub mod thread_access;
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/scheduled_action_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/scheduled_action_access.rs
new file mode 100644
index 0000000000..213369fa03
--- /dev/null
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/scheduled_action_access.rs
@@ -0,0 +1,50 @@
+//! Scheduled-action grants in `entity_access`.
+
+#[cfg(test)]
+mod test;
+
+use crate::{domain::models::AccessLevel, outbound::pg_access_repo::queries::SourceIds};
+use sqlx::PgPool;
+
+/// Highest grant the caller's sources hold on one scheduled action.
+#[tracing::instrument(err, skip(pool, source_ids))]
+pub async fn get_scheduled_action_access(
+ pool: &PgPool,
+ id: &uuid::Uuid,
+ source_ids: &SourceIds,
+) -> Result<Option<AccessLevel>, sqlx::Error> {
+ let levels: Vec<AccessLevel> = sqlx::query_scalar!(
+ r#"
+ SELECT access_level AS "access_level!: AccessLevel"
+ FROM entity_access
+ WHERE entity_id = $1 AND entity_type = 'scheduled_action' AND source_id = ANY($2)
+ "#,
+ id,
+ &source_ids.0,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(levels.into_iter().max())
+}
+
+/// Live scheduled-action ids the caller's sources can reach.
+///
+/// The join drops grants whose action row is gone.
+#[tracing::instrument(err, skip(pool, source_ids))]
+pub async fn accessible_scheduled_action_ids(
+ pool: &PgPool,
+ source_ids: &SourceIds,
+) -> Result<Vec<uuid::Uuid>, sqlx::Error> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT DISTINCT ea.entity_id
+ FROM entity_access ea
+ JOIN scheduled_action sa ON sa.id = ea.entity_id
+ WHERE ea.entity_type = 'scheduled_action' AND ea.source_id = ANY($1)
+ "#,
+ &source_ids.0,
+ )
+ .fetch_all(pool)
+ .await
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/scheduled_action_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/scheduled_action_access/test.rs
new file mode 100644
index 0000000000..b6066e9170
--- /dev/null
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/scheduled_action_access/test.rs
@@ -0,0 +1,262 @@
+use super::*;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+const OWNER: &str = "macro|[email protected]";
+const STRANGER: &str = "macro|[email protected]";
+const CHANNEL: Uuid = Uuid::from_u128(0x0000_0000_0000_0000_0000_0000_0000_5a11);
+const TEAM: Uuid = Uuid::from_u128(0x0000_0000_0000_0000_0000_0000_0000_5a12);
+
+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_scheduled_action(pool: &PgPool, owner: &str) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query!(
+ r#"
+ INSERT INTO scheduled_action (
+ id, owner, name, schedule, kind, timezone, task, next_run_at, enabled
+ )
+ VALUES ($1, $2, 'routine', '0 * * * *', 'Agent', 'UTC', '{}'::jsonb, NOW(), true)
+ "#,
+ id,
+ owner,
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(id)
+}
+
+async fn grant(
+ pool: &PgPool,
+ entity_id: Uuid,
+ entity_type: &str,
+ 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, $2, $3, $4::text::entity_access_source_type, $5::text::"AccessLevel")
+ "#,
+ entity_id,
+ entity_type,
+ source_id,
+ source_type,
+ access_level,
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+fn sources(ids: &[&str]) -> SourceIds {
+ SourceIds(ids.iter().map(ToString::to_string).collect())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn owner_grant_returns_owner(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let action_id = insert_scheduled_action(&pool, OWNER).await?;
+ grant(
+ &pool,
+ action_id,
+ "scheduled_action",
+ OWNER,
+ "user",
+ AccessLevel::Owner,
+ )
+ .await?;
+
+ let access = get_scheduled_action_access(&pool, &action_id, &sources(&[OWNER])).await?;
+
+ assert_eq!(access, Some(AccessLevel::Owner));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn stranger_source_ids_return_none(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let action_id = insert_scheduled_action(&pool, OWNER).await?;
+ grant(
+ &pool,
+ action_id,
+ "scheduled_action",
+ OWNER,
+ "user",
+ AccessLevel::Owner,
+ )
+ .await?;
+
+ let access = get_scheduled_action_access(&pool, &action_id, &sources(&[STRANGER])).await?;
+
+ assert_eq!(access, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn channel_source_grant_matches(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let action_id = insert_scheduled_action(&pool, OWNER).await?;
+ grant(
+ &pool,
+ action_id,
+ "scheduled_action",
+ &CHANNEL.to_string(),
+ "channel",
+ AccessLevel::Edit,
+ )
+ .await?;
+
+ let matched =
+ get_scheduled_action_access(&pool, &action_id, &sources(&[&CHANNEL.to_string()])).await?;
+ let without_channel =
+ get_scheduled_action_access(&pool, &action_id, &sources(&[OWNER])).await?;
+
+ assert_eq!(matched, Some(AccessLevel::Edit));
+ assert_eq!(without_channel, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn team_source_grant_matches(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let action_id = insert_scheduled_action(&pool, OWNER).await?;
+ grant(
+ &pool,
+ action_id,
+ "scheduled_action",
+ &TEAM.to_string(),
+ "team",
+ AccessLevel::Comment,
+ )
+ .await?;
+
+ let matched =
+ get_scheduled_action_access(&pool, &action_id, &sources(&[&TEAM.to_string()])).await?;
+ let without_team = get_scheduled_action_access(&pool, &action_id, &sources(&[OWNER])).await?;
+
+ assert_eq!(matched, Some(AccessLevel::Comment));
+ assert_eq!(without_team, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn higher_grant_wins(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let action_id = insert_scheduled_action(&pool, OWNER).await?;
+ grant(
+ &pool,
+ action_id,
+ "scheduled_action",
+ OWNER,
+ "user",
+ AccessLevel::View,
+ )
+ .await?;
+ grant(
+ &pool,
+ action_id,
+ "scheduled_action",
+ &CHANNEL.to_string(),
+ "channel",
+ AccessLevel::Edit,
+ )
+ .await?;
+
+ let access =
+ get_scheduled_action_access(&pool, &action_id, &sources(&[OWNER, &CHANNEL.to_string()]))
+ .await?;
+
+ assert_eq!(access, Some(AccessLevel::Edit));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn accessible_ids_return_the_live_granted_action_once(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER).await?;
+ let live_id = insert_scheduled_action(&pool, OWNER).await?;
+ grant(
+ &pool,
+ live_id,
+ "scheduled_action",
+ OWNER,
+ "user",
+ AccessLevel::Owner,
+ )
+ .await?;
+ grant(
+ &pool,
+ live_id,
+ "scheduled_action",
+ &CHANNEL.to_string(),
+ "channel",
+ AccessLevel::Edit,
+ )
+ .await?;
+
+ let project_id = Uuid::now_v7();
+ grant(
+ &pool,
+ project_id,
+ "project",
+ OWNER,
+ "user",
+ AccessLevel::Owner,
+ )
+ .await?;
+
+ let missing_action_id = Uuid::now_v7();
+ grant(
+ &pool,
+ missing_action_id,
+ "scheduled_action",
+ OWNER,
+ "user",
+ AccessLevel::View,
+ )
+ .await?;
+
+ let ids =
+ accessible_scheduled_action_ids(&pool, &sources(&[OWNER, &CHANNEL.to_string()])).await?;
+
+ assert_eq!(ids, vec![live_id]);
+ Ok(())
+}
diff --git a/crates/graphql_scheduled_action/src/context.rs b/crates/graphql_scheduled_action/src/context.rs
index c4a9e07c7c..dba7be0870 100644
--- a/crates/graphql_scheduled_action/src/context.rs
+++ b/crates/graphql_scheduled_action/src/context.rs
@@ -8,7 +8,7 @@ pub(crate) type ListFuture<'a> =
Pin<Box<dyn Future<Output = Result<Vec<ScheduledAction>, Report>> + Send + 'a>>;
pub(crate) trait ScheduledActionReader: Send + Sync {
- fn list_owned(&self, user_id: MacroUserIdStr<'static>) -> ListFuture<'_>;
+ fn list_accessible(&self, user_id: MacroUserIdStr<'static>) -> ListFuture<'_>;
}
/// Type-erased routine reader stored in GraphQL request data.
@@ -27,8 +27,8 @@ struct ReadServiceAdapter<S> {
}
impl<S: ScheduledActionReadService> ScheduledActionReader for ReadServiceAdapter<S> {
- fn list_owned(&self, user_id: MacroUserIdStr<'static>) -> ListFuture<'_> {
+ fn list_accessible(&self, user_id: MacroUserIdStr<'static>) -> ListFuture<'_> {
let service = Arc::clone(&self.service);
- Box::pin(async move { service.list_owned(user_id).await })
+ Box::pin(async move { service.list_accessible(user_id).await })
}
}
diff --git a/crates/graphql_scheduled_action/src/objects.rs b/crates/graphql_scheduled_action/src/objects.rs
index f610ba1454..563f0c679e 100644
--- a/crates/graphql_scheduled_action/src/objects.rs
+++ b/crates/graphql_scheduled_action/src/objects.rs
@@ -6,7 +6,7 @@ use scheduled_action::domain::{
};
use serde_json::Value;
-/// An AI routine owned by the authenticated user.
+/// An AI routine the authenticated user can access.
#[derive(SimpleObject)]
pub struct GraphqlScheduledAction {
/// Stable identifier of the routine.
diff --git a/crates/graphql_scheduled_action/src/query.rs b/crates/graphql_scheduled_action/src/query.rs
index a720658e18..723b3a90ef 100644
--- a/crates/graphql_scheduled_action/src/query.rs
+++ b/crates/graphql_scheduled_action/src/query.rs
@@ -8,7 +8,7 @@ use super::unavailable;
#[cfg(test)]
mod test;
-/// List routines owned by `user_id`.
+/// List routines `user_id` can access.
pub async fn resolve_scheduled_actions(
ctx: &Context<'_>,
user_id: MacroUserIdStr<'static>,
@@ -16,7 +16,7 @@ pub async fn resolve_scheduled_actions(
let actions = ctx
.data::<ScheduledActionGraphqlContext>()?
.0
- .list_owned(user_id)
+ .list_accessible(user_id)
.await
.map_err(unavailable)?;
actions
diff --git a/crates/graphql_scheduled_action/src/query/test.rs b/crates/graphql_scheduled_action/src/query/test.rs
index ab7d0cf95d..5b3cf4c11a 100644
--- a/crates/graphql_scheduled_action/src/query/test.rs
+++ b/crates/graphql_scheduled_action/src/query/test.rs
@@ -53,7 +53,7 @@ struct FakeReader {
}
impl ScheduledActionReadService for FakeReader {
- async fn list_owned(
+ async fn list_accessible(
&self,
user_id: MacroUserIdStr<'static>,
) -> Result<Vec<ScheduledAction>, Report> {
diff --git a/crates/macro_db_client/migrations/20260929195914_backfill_scheduled_action_owner_grants.sql b/crates/macro_db_client/migrations/20260929195914_backfill_scheduled_action_owner_grants.sql
new file mode 100644
index 0000000000..dd500c02c0
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260929195914_backfill_scheduled_action_owner_grants.sql
@@ -0,0 +1,33 @@
+-- Existing routines predate entity_access grants. Their entity rows were
+-- registered out of band, so only the owner grant is written here. Every routine
+-- written so far is user-owned (the owner column carried a FK to "User" until
+-- 20260923183235), so a non-user owner here is data this migration must not
+-- guess about. User source ids are lowercase, so a mixed-case owner would never
+-- match its own grant.
+DO $$
+BEGIN
+ IF EXISTS (
+ SELECT 1 FROM scheduled_action
+ WHERE owner NOT LIKE 'macro|%' OR owner <> lower(owner)
+ ) THEN
+ RAISE EXCEPTION 'scheduled_action has a non-user owner; backfill its grants by hand';
+ END IF;
+ IF EXISTS (
+ SELECT 1 FROM scheduled_action sa
+ JOIN entity e ON e.id = sa.id
+ WHERE e.entity_type <> 'scheduled_action'
+ OR e.owner_type <> 'user'
+ OR e.owner_id <> sa.owner
+ ) THEN
+ RAISE EXCEPTION 'scheduled_action conflicts with an existing entity registration';
+ END IF;
+END
+$$;
+
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+SELECT id, 'scheduled_action', owner, 'user', 'owner'
+FROM scheduled_action
+ON CONFLICT (entity_id, entity_type, source_id, source_type)
+WHERE granted_from_project_id IS NULL
+DO UPDATE SET access_level = EXCLUDED.access_level, updated_at = NOW()
+WHERE entity_access.access_level <> 'owner';
diff --git a/packages/sdk/generated/scheduled-action/types.gen.ts b/packages/sdk/generated/scheduled-action/types.gen.ts
index abc9cfc1e2..886bb8971f 100644
--- a/packages/sdk/generated/scheduled-action/types.gen.ts
+++ b/packages/sdk/generated/scheduled-action/types.gen.ts
@@ -303,6 +303,7 @@ export type CreateScheduledActionData = {
export type CreateScheduledActionErrors = {
400: string;
401: string;
+ 403: string;
500: string;
};
diff --git a/packages/sdk/specs/scheduled-action.json b/packages/sdk/specs/scheduled-action.json
index b6a14e699e..cdc331a606 100644
--- a/packages/sdk/specs/scheduled-action.json
+++ b/packages/sdk/specs/scheduled-action.json
@@ -134,6 +134,16 @@
}
}
},
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 2421e4935c..107eb8526c 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -521,7 +521,7 @@ async fn run() -> anyhow::Result<()> {
));
let project_service = Arc::new(ProjectServiceImpl::new(
- PgProjectRepo::new(db.clone(), owned_entity_registrar),
+ PgProjectRepo::new(db.clone(), owned_entity_registrar.clone()),
S3ProjectUploadAdapter::new(
macro_aws_config::s3_client().await,
config.document_storage_bucket.as_ref(),
@@ -1592,9 +1592,13 @@ async fn run() -> anyhow::Result<()> {
// Routine writes still use the scheduled-action service. Read from the
// primary pool here so the GraphQL list cannot restore stale state after
// a REST write.
- let scheduled_action_read_service = Arc::new(ScheduledActionReadServiceImpl::new(Arc::new(
- PgScheduledActionRepo::new(db.clone()),
- )));
+ let scheduled_action_read_service = Arc::new(ScheduledActionReadServiceImpl::new(
+ Arc::new(PgScheduledActionRepo::new(
+ db.clone(),
+ owned_entity_registrar.clone(),
+ )),
+ entity_access_service.clone(),
+ ));
let api_context = ApiContext {
dictation_state,
diff --git a/services/scheduled_action/Cargo.toml b/services/scheduled_action/Cargo.toml
index 6b45e65aab..3510824562 100644
--- a/services/scheduled_action/Cargo.toml
+++ b/services/scheduled_action/Cargo.toml
@@ -29,7 +29,8 @@ bots = { path = "../../crates/bots", default-features = false, features = ["outb
channel_sender = { path = "../../crates/channel_sender" }
channels = { path = "../../crates/channels", default-features = false }
documents = { path = "../../crates/documents", default-features = false }
-entity_access = { path = "../../crates/entity_access", default-features = false, features = ["ports"] }
+entity_access = { path = "../../crates/entity_access", default-features = false, features = ["inbound", "outbound"] }
+entity_access_db_utils = { path = "../../crates/entity_access_db_utils" }
kafka_util = { path = "../../crates/kafka_util" }
macro_event_broker = { path = "../../crates/macro_event_broker", features = ["outbound"] }
macro_event_topics = { path = "../../crates/macro_event_topics" }
@@ -73,7 +74,7 @@ memory = { path = "../../crates/memory" }
model = { path = "../../crates/model" }
model-entity = { path = "../../crates/model-entity" }
model_owner = { path = "../../crates/model_owner" }
-entity_registry = { path = "../../crates/entity_registry/entity_registry" }
+entity_registry = { path = "../../crates/entity_registry/entity_registry", features = ["axum"] }
entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }
model_notifications = { path = "../../crates/model_notifications" }
notification = { path = "../../crates/notification" }
@@ -93,4 +94,5 @@ macro_service_urls = { path = "../../crates/macro_service_urls" }
workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }
[dev-dependencies]
+bot_id = { path = "../../crates/bot_id", features = ["test-utils"] }
macro_db_migrator = { path = "../../crates/macro_db_migrator" }
diff --git a/services/scheduled_action/src/bins/service.rs b/services/scheduled_action/src/bins/service.rs
index e064dcc6fb..9ec6e15688 100644
--- a/services/scheduled_action/src/bins/service.rs
+++ b/services/scheduled_action/src/bins/service.rs
@@ -103,12 +103,14 @@ async fn main() -> Result<()> {
&conn_gateway_client,
)));
- let repo = Arc::new(PgScheduledActionRepo::new(db.clone()));
+ let registrar = OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(db.clone())));
+ let repo = Arc::new(PgScheduledActionRepo::new(db.clone(), registrar.clone()));
let event_repo = Arc::new(PgEventRunRepo::new(db.clone()));
- let event_access = Arc::new(EventAccessAdapter::new(EntityAccessServiceImpl::new(
- PgAccessRepository::new(db.clone()),
+ let access = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ db.clone(),
)));
+ let event_access = Arc::new(EventAccessAdapter::new(access.as_ref().clone()));
let memory = MemoryServiceImpl::new(
PgMemoryRepo::new(db.clone()),
tool_context.clone(),
@@ -116,10 +118,7 @@ async fn main() -> Result<()> {
);
let runner = Arc::new(AgentTaskRunner::new(
Arc::clone(&tool_context.chat_tool_context.service),
- PgChatRepo::new(
- db.clone(),
- OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(db.clone()))),
- ),
+ PgChatRepo::new(db.clone(), registrar),
memory,
tool_context,
notification_ingress,
@@ -200,18 +199,24 @@ async fn main() -> Result<()> {
);
let service = Arc::new(
- ScheduledActionServiceImpl::new(Arc::clone(&repo), service_executor, dispatcher_tx)
- .with_event_management_enabled(config.event_routines_enabled)
- .with_target_validation(TargetValidation::new(
- sessions,
- config.routine_agents_enabled,
- )),
+ ScheduledActionServiceImpl::new(
+ Arc::clone(&repo),
+ service_executor,
+ dispatcher_tx,
+ access.clone(),
+ )
+ .with_event_management_enabled(config.event_routines_enabled)
+ .with_target_validation(TargetValidation::new(
+ sessions,
+ config.routine_agents_enabled,
+ )),
);
let state = ScheduledActionRouterState {
service,
+ access_service: access,
authorization_state,
};
- let authed_routes = scheduled_action_router::<_, _, ()>(state);
+ let authed_routes = scheduled_action_router::<_, _, _, ()>(state);
let router = Router::new()
.merge(mount_at_root_and_prefix(
diff --git a/services/scheduled_action/src/domain/execution/test.rs b/services/scheduled_action/src/domain/execution/test.rs
index 71fd9c4b77..3f6f0b9813 100644
--- a/services/scheduled_action/src/domain/execution/test.rs
+++ b/services/scheduled_action/src/domain/execution/test.rs
@@ -62,14 +62,13 @@ impl ScheduledActionRepo for Repo {
async fn create_action(&self, _: ScheduledAction) -> Result<ScheduledAction> {
unimplemented!()
}
- async fn get_actions(&self, _: MacroUserIdStr<'static>) -> Result<Vec<ScheduledAction>> {
+ async fn get_owned_actions(&self, _: &MacroUserIdStr<'static>) -> Result<Vec<ScheduledAction>> {
unimplemented!()
}
- async fn get_action(
- &self,
- _: &Uuid,
- _: MacroUserIdStr<'static>,
- ) -> Result<Option<ScheduledAction>> {
+ async fn get_actions_by_ids(&self, _: &[Uuid]) -> Result<Vec<ScheduledAction>> {
+ unimplemented!()
+ }
+ async fn get_action(&self, _: &Uuid) -> Result<Option<ScheduledAction>> {
unimplemented!()
}
async fn get_next_unclaimed_actions(&self, _: i64) -> Result<Vec<ScheduledAction>> {
@@ -78,7 +77,7 @@ impl ScheduledActionRepo for Repo {
async fn update_action(&self, _: ScheduledAction) -> Result<ScheduledAction> {
unimplemented!()
}
- async fn delete_action(&self, _: &Uuid, _: MacroUserIdStr<'static>) -> Result<()> {
+ async fn delete_action(&self, _: &Uuid) -> Result<()> {
unimplemented!()
}
async fn get_execution_records(&self, _: &Uuid) -> Result<Vec<ActionExecutionRecord>> {
diff --git a/services/scheduled_action/src/domain/ports.rs b/services/scheduled_action/src/domain/ports.rs
index 9949379185..8a1291aee7 100644
--- a/services/scheduled_action/src/domain/ports.rs
+++ b/services/scheduled_action/src/domain/ports.rs
@@ -7,8 +7,12 @@ use super::models::{
};
use anyhow::Result;
use chrono::{DateTime, Utc};
+use entity_access::domain::models::{
+ EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
+};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
+use model_owner::CreationPrincipal;
use rootcause::Report;
use tokio::sync::mpsc::{Receiver, Sender};
@@ -27,17 +31,21 @@ pub trait ScheduledActionRepo: Send + Sync + 'static {
action: ScheduledAction,
) -> impl Future<Output = Result<ScheduledAction>> + Send;
- fn get_actions(
+ /// Account cleanup only: `WHERE owner = $1`. Never the HTTP list.
+ fn get_owned_actions(
&self,
- user_id: MacroUserIdStr<'static>,
+ owner: &MacroUserIdStr<'static>,
) -> impl Future<Output = Result<Vec<ScheduledAction>>> + Send;
- /// Look up one action owned by the caller, independently of list filtering.
- fn get_action(
+ /// Rows for ids the grants port already allowed. No owner predicate. Missing ids omitted.
+ fn get_actions_by_ids(
&self,
- id: &Uuid,
- user_id: MacroUserIdStr<'static>,
- ) -> impl Future<Output = Result<Option<ScheduledAction>>> + Send;
+ ids: &[Uuid],
+ ) -> impl Future<Output = Result<Vec<ScheduledAction>>> + Send;
+
+ /// By primary key, no owner predicate.
+ fn get_action(&self, id: &Uuid)
+ -> impl Future<Output = Result<Option<ScheduledAction>>> + Send;
/// Return the next `limit` enabled cron actions ordered by `next_run_at` ASC,
/// filtering out those currently claimed by another worker (i.e. claimed
@@ -47,20 +55,20 @@ pub trait ScheduledActionRepo: Send + Sync + 'static {
limit: i64,
) -> impl Future<Output = Result<Vec<ScheduledAction>>> + Send;
- /// Atomically replace configuration only when the stored revision is the
- /// predecessor of the supplied revision. While claimed, only disabling with
- /// otherwise identical configuration is allowed. Return UpdateConflict on
- /// stale revisions or a concurrent claim; never overwrite execution state.
+ /// Replace configuration when `id` matches and the stored revision is the
+ /// predecessor, plus the claim fence. No owner predicate. While claimed,
+ /// only disabling with otherwise identical configuration is allowed.
+ /// `UpdateConflict` on a stale revision or a concurrent claim; never
+ /// overwrite execution state.
fn update_action(
&self,
action: ScheduledAction,
) -> impl Future<Output = Result<ScheduledAction>> + Send;
- fn delete_action(
- &self,
- id: &Uuid,
- macro_user_id: MacroUserIdStr<'static>,
- ) -> impl Future<Output = Result<()>> + Send;
+ /// Deletes the action row, its `entity_access` rows (`entity_type =
+ /// 'scheduled_action'`) and the `entity` row in one transaction. A missing
+ /// row is `Ok(())`.
+ fn delete_action(&self, id: &Uuid) -> impl Future<Output = Result<()>> + Send;
/// Claim only while the stored configuration is still `revision`, so a
/// snapshot read before a pause or update can never start a run.
@@ -97,13 +105,12 @@ pub trait ScheduledActionRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<()>> + Send;
}
-/// Lists one user's routines for read-only clients.
+/// Lists routines a caller can access for read-only clients.
///
-/// The list includes cron and event triggers, keeps only actions whose owner
-/// is that user, and orders them by `(created_at, id)`.
+/// The list includes cron and event triggers and orders them by `(created_at, id)`.
pub trait ScheduledActionReadService: Send + Sync + 'static {
- /// Routines owned by `user_id` in stable `(created_at, id)` order.
- fn list_owned(
+ /// Cron and event actions the user can access, ordered by `(created_at, id)`.
+ fn list_accessible(
&self,
user_id: MacroUserIdStr<'static>,
) -> impl Future<Output = std::result::Result<Vec<ScheduledAction>, Report>> + Send;
@@ -117,14 +124,17 @@ pub trait ScheduledActionService: Send + Sync + 'static {
user_id: MacroUserIdStr<'static>,
) -> impl Future<Output = Result<()>> + Send;
+ /// Records `principal.owner()`. A non-user owner is `OwnerNotUserError`
+ /// before validation and before any write. `BotForUser` records the user.
fn create_action(
&self,
+ principal: &CreationPrincipal,
input: CreateScheduledAction,
- user_id: MacroUserIdStr<'static>,
) -> impl Future<Output = Result<ScheduledAction>> + Send;
- /// Legacy clients see cron actions only. Backend clients opt into events.
- /// ID-based operations and workers must never authorize through this list.
+ /// Actions `user_id` can access. Legacy clients see cron actions only;
+ /// backend clients opt into events. ID-based operations and workers must
+ /// never authorize through this list.
fn get_actions(
&self,
user_id: MacroUserIdStr<'static>,
@@ -133,36 +143,31 @@ pub trait ScheduledActionService: Send + Sync + 'static {
fn update_action(
&self,
- id: &Uuid,
+ receipt: EntityAccessReceipt<EditAccessLevel>,
input: UpdateScheduledAction,
- macro_user_id: MacroUserIdStr<'static>,
) -> impl Future<Output = Result<ScheduledAction>> + Send;
/// Change activation without touching configuration. Requesting the
/// current state returns the stored action unchanged.
fn set_enabled(
&self,
- id: &Uuid,
+ receipt: EntityAccessReceipt<EditAccessLevel>,
enabled: bool,
- macro_user_id: MacroUserIdStr<'static>,
) -> impl Future<Output = Result<ScheduledAction>> + Send;
fn delete_action(
&self,
- id: &Uuid,
- macro_user_id: MacroUserIdStr<'static>,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
) -> impl Future<Output = Result<()>> + Send;
fn execute_action_now(
&self,
- id: &Uuid,
- macro_user_id: MacroUserIdStr<'static>,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
) -> impl Future<Output = Result<InProgressExecution>> + Send;
fn get_execution_records(
&self,
- id: &Uuid,
- macro_user_id: MacroUserIdStr<'static>,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
) -> impl Future<Output = Result<Vec<ActionExecutionRecord>>> + Send;
}
diff --git a/services/scheduled_action/src/domain/read_service.rs b/services/scheduled_action/src/domain/read_service.rs
index 0dfb7870f5..d2a4320651 100644
--- a/services/scheduled_action/src/domain/read_service.rs
+++ b/services/scheduled_action/src/domain/read_service.rs
@@ -1,28 +1,34 @@
use std::sync::Arc;
+use entity_access::domain::ports::ScheduledActionGrants;
use macro_user_id::user_id::MacroUserIdStr;
use rootcause::Report;
use super::models::ScheduledAction;
use super::ports::{ScheduledActionReadService, ScheduledActionRepo};
-use super::service::list_owned_actions;
+use super::service::list_accessible_actions;
-pub struct ScheduledActionReadServiceImpl<R> {
+pub struct ScheduledActionReadServiceImpl<R, G> {
repo: Arc<R>,
+ grants: Arc<G>,
}
-impl<R> ScheduledActionReadServiceImpl<R> {
- pub fn new(repo: Arc<R>) -> Self {
- Self { repo }
+impl<R, G> ScheduledActionReadServiceImpl<R, G> {
+ pub fn new(repo: Arc<R>, grants: Arc<G>) -> Self {
+ Self { repo, grants }
}
}
-impl<R: ScheduledActionRepo> ScheduledActionReadService for ScheduledActionReadServiceImpl<R> {
- async fn list_owned(
+impl<R, G> ScheduledActionReadService for ScheduledActionReadServiceImpl<R, G>
+where
+ R: ScheduledActionRepo,
+ G: ScheduledActionGrants,
+{
+ async fn list_accessible(
&self,
user_id: MacroUserIdStr<'static>,
) -> Result<Vec<ScheduledAction>, Report> {
- list_owned_actions(self.repo.as_ref(), &user_id)
+ list_accessible_actions(self.repo.as_ref(), self.grants.as_ref(), &user_id)
.await
.map_err(|error| rootcause::report!(error).into_dynamic())
}
diff --git a/services/scheduled_action/src/domain/service.rs b/services/scheduled_action/src/domain/service.rs
index 94f67b6b68..71c817e1b0 100644
--- a/services/scheduled_action/src/domain/service.rs
+++ b/services/scheduled_action/src/domain/service.rs
@@ -2,16 +2,23 @@ use std::sync::Arc;
use anyhow::{Result, bail};
use chrono::{DateTime, Utc};
+use entity_access::domain::{
+ models::{
+ EditAccessLevel, EntityAccessReceipt, EntityType, OwnerAccessLevel, RequiredPermission,
+ ViewAccessLevel,
+ },
+ ports::ScheduledActionGrants,
+};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
-use model_owner::Owner;
+use model_owner::CreationPrincipal;
use tokio::sync::mpsc::Sender;
use super::event_runs::ConfigurationRevision;
use super::event_trigger::ActionTrigger;
use super::models::{
ActionConfiguration, ActionExecutionRecord, ActionPolicyError, CreateScheduledAction,
- DispatchEvent, InProgressExecution, ScheduledAction, UpdateScheduledAction,
+ DispatchEvent, InProgressExecution, OwnerNotUserError, ScheduledAction, UpdateScheduledAction,
};
use super::ports::{
ScheduledActionExecutor, ScheduledActionRepo, ScheduledActionService, TaskTargetValidator,
@@ -21,20 +28,27 @@ use super::target_validation::{ModelOnlyTargets, require_explicit_agent};
#[cfg(test)]
pub(crate) mod test;
-pub struct ScheduledActionServiceImpl<Rpo, Exe, Targets = ModelOnlyTargets> {
+pub struct ScheduledActionServiceImpl<Rpo, Exe, Grants, Targets = ModelOnlyTargets> {
repo: Arc<Rpo>,
executor: Arc<Exe>,
+ grants: Arc<Grants>,
dispatcher_tx: Sender<DispatchEvent>,
event_management_enabled: bool,
targets: Targets,
}
-impl<Rpo: ScheduledActionRepo, Exe> ScheduledActionServiceImpl<Rpo, Exe> {
+impl<Rpo: ScheduledActionRepo, Exe, Grants> ScheduledActionServiceImpl<Rpo, Exe, Grants> {
/// Event management defaults off until explicitly enabled by composition.
- pub fn new(repo: Arc<Rpo>, executor: Arc<Exe>, dispatcher_tx: Sender<DispatchEvent>) -> Self {
+ pub fn new(
+ repo: Arc<Rpo>,
+ executor: Arc<Exe>,
+ dispatcher_tx: Sender<DispatchEvent>,
+ grants: Arc<Grants>,
+ ) -> Self {
Self {
repo,
executor,
+ grants,
dispatcher_tx,
event_management_enabled: false,
targets: ModelOnlyTargets,
@@ -42,14 +56,17 @@ impl<Rpo: ScheduledActionRepo, Exe> ScheduledActionServiceImpl<Rpo, Exe> {
}
}
-impl<Rpo: ScheduledActionRepo, Exe, Targets> ScheduledActionServiceImpl<Rpo, Exe, Targets> {
+impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>
+ ScheduledActionServiceImpl<Rpo, Exe, Grants, Targets>
+{
pub fn with_target_validation<T: TaskTargetValidator>(
self,
targets: T,
- ) -> ScheduledActionServiceImpl<Rpo, Exe, T> {
+ ) -> ScheduledActionServiceImpl<Rpo, Exe, Grants, T> {
ScheduledActionServiceImpl {
repo: self.repo,
executor: self.executor,
+ grants: self.grants,
dispatcher_tx: self.dispatcher_tx,
event_management_enabled: self.event_management_enabled,
targets,
@@ -61,14 +78,19 @@ impl<Rpo: ScheduledActionRepo, Exe, Targets> ScheduledActionServiceImpl<Rpo, Exe
self
}
- async fn owned_action(
+ async fn load_granted<T: RequiredPermission>(
&self,
- id: &Uuid,
- caller: &MacroUserIdStr<'static>,
+ receipt: &EntityAccessReceipt<T>,
) -> Result<ScheduledAction> {
- match self.repo.get_action(id, caller.clone()).await? {
- Some(action) if action.owner.is_user(caller) => Ok(action),
- _ => Err(ActionPolicyError::NotFound.into()),
+ if receipt.entity().entity_type != EntityType::ScheduledAction {
+ bail!("scheduled action receipt has the wrong entity type");
+ }
+ let Ok(id) = receipt.entity().entity_id.parse::<Uuid>() else {
+ bail!("scheduled action receipt id is not a uuid");
+ };
+ match self.repo.get_action(&id).await? {
+ Some(action) => Ok(action),
+ None => Err(ActionPolicyError::NotFound.into()),
}
}
@@ -83,7 +105,6 @@ impl<Rpo: ScheduledActionRepo, Exe, Targets> ScheduledActionServiceImpl<Rpo, Exe
&self,
mut action: ScheduledAction,
input: ActionConfiguration,
- caller: &MacroUserIdStr<'static>,
) -> Result<ScheduledAction>
where
Targets: TaskTargetValidator,
@@ -106,7 +127,9 @@ impl<Rpo: ScheduledActionRepo, Exe, Targets> ScheduledActionServiceImpl<Rpo, Exe
return Err(ActionPolicyError::UpdateConflict.into());
}
if !disable_only {
- self.targets.validate_task(&input.task, caller).await?;
+ self.targets
+ .validate_task(&input.task, action.owner_user()?)
+ .await?;
action.next_run_at = next_run(&input.trigger)?;
}
action.event_activated_at = match &input.trigger {
@@ -147,16 +170,23 @@ fn next_run(trigger: &ActionTrigger) -> Result<Option<DateTime<Utc>>> {
}
}
-pub(crate) async fn list_owned_actions<R: ScheduledActionRepo>(
+pub(crate) async fn list_accessible_actions<R, G>(
repo: &R,
+ grants: &G,
user_id: &MacroUserIdStr<'static>,
-) -> Result<Vec<ScheduledAction>> {
- let mut actions = repo
- .get_actions(user_id.clone())
- .await?
- .into_iter()
- .filter(|action| action.owner.is_user(user_id))
- .collect::<Vec<_>>();
+) -> Result<Vec<ScheduledAction>>
+where
+ R: ScheduledActionRepo,
+ G: ScheduledActionGrants,
+{
+ let ids = grants
+ .accessible_scheduled_action_ids(user_id)
+ .await
+ .map_err(|error| anyhow::anyhow!("failed to list accessible scheduled actions: {error}"))?;
+ if ids.is_empty() {
+ return Ok(Vec::new());
+ }
+ let mut actions = repo.get_actions_by_ids(&ids).await?;
actions.sort_by(|left, right| {
left.created_at
.cmp(&right.created_at)
@@ -188,16 +218,18 @@ fn same_trigger(left: &ActionTrigger, right: &ActionTrigger) -> bool {
}
}
-impl<Rpo, Exe, Targets> ScheduledActionService for ScheduledActionServiceImpl<Rpo, Exe, Targets>
+impl<Rpo, Exe, Grants, Targets> ScheduledActionService
+ for ScheduledActionServiceImpl<Rpo, Exe, Grants, Targets>
where
Rpo: ScheduledActionRepo,
+ Grants: ScheduledActionGrants,
Targets: TaskTargetValidator,
Exe: ScheduledActionExecutor + Send + Sync + 'static,
{
async fn delete_user_actions(&self, user_id: MacroUserIdStr<'static>) -> Result<()> {
// Use the repository list, not the legacy cron-only service list, so
// event-triggered actions are also removed regardless of rollout gates.
- for action in self.repo.get_actions(user_id.clone()).await? {
+ for action in self.repo.get_owned_actions(&user_id).await? {
if !action.owner.is_user(&user_id) {
bail!("account cleanup returned an action owned by another principal");
}
@@ -207,7 +239,7 @@ where
// Reserve before deleting: a stopped dispatcher must not leave us
// reporting failure after losing the row needed to retry its event.
let permit = self.dispatcher_tx.reserve().await?;
- self.repo.delete_action(&id, user_id.clone()).await?;
+ self.repo.delete_action(&id).await?;
permit.send(DispatchEvent::Delete(action));
}
Ok(())
@@ -215,12 +247,16 @@ where
async fn create_action(
&self,
+ principal: &CreationPrincipal,
input: CreateScheduledAction,
- user_id: MacroUserIdStr<'static>,
) -> Result<ScheduledAction> {
+ let owner = principal.owner();
+ let owner_user = owner.as_user().ok_or(OwnerNotUserError {
+ owner_type: owner.owner_type(),
+ })?;
let input = ActionConfiguration::from(input);
self.check_event_management(&input.trigger)?;
- self.targets.validate_task(&input.task, &user_id).await?;
+ self.targets.validate_task(&input.task, owner_user).await?;
let now = Utc::now();
let next_run_at = next_run(&input.trigger)?;
let event_activated_at = match &input.trigger {
@@ -231,7 +267,7 @@ where
.repo
.create_action(ScheduledAction {
id: None,
- owner: Owner::User(user_id),
+ owner,
name: input.name,
trigger: input.trigger,
kind: input.kind,
@@ -257,32 +293,33 @@ where
user_id: MacroUserIdStr<'static>,
include_events: bool,
) -> Result<Vec<ScheduledAction>> {
- Ok(list_owned_actions(self.repo.as_ref(), &user_id)
- .await?
- .into_iter()
- .filter(|action| include_events || matches!(action.trigger, ActionTrigger::Cron { .. }))
- .collect())
+ Ok(
+ list_accessible_actions(self.repo.as_ref(), self.grants.as_ref(), &user_id)
+ .await?
+ .into_iter()
+ .filter(|action| {
+ include_events || matches!(action.trigger, ActionTrigger::Cron { .. })
+ })
+ .collect(),
+ )
}
async fn update_action(
&self,
- id: &Uuid,
+ receipt: EntityAccessReceipt<EditAccessLevel>,
input: UpdateScheduledAction,
- macro_user_id: MacroUserIdStr<'static>,
) -> Result<ScheduledAction> {
- let action = self.owned_action(id, &macro_user_id).await?;
+ let action = self.load_granted(&receipt).await?;
let input = input.into_configuration(action.enabled);
- self.replace_configuration(action, input, &macro_user_id)
- .await
+ self.replace_configuration(action, input).await
}
async fn set_enabled(
&self,
- id: &Uuid,
+ receipt: EntityAccessReceipt<EditAccessLevel>,
enabled: bool,
- macro_user_id: MacroUserIdStr<'static>,
) -> Result<ScheduledAction> {
- let action = self.owned_action(id, &macro_user_id).await?;
+ let action = self.load_granted(&receipt).await?;
if action.enabled == enabled {
return Ok(action);
}
@@ -293,13 +330,15 @@ where
task: action.task.clone(),
enabled,
};
- self.replace_configuration(action, input, &macro_user_id)
- .await
+ self.replace_configuration(action, input).await
}
- async fn delete_action(&self, id: &Uuid, macro_user_id: MacroUserIdStr<'static>) -> Result<()> {
- let action = self.owned_action(id, &macro_user_id).await?;
- self.repo.delete_action(id, macro_user_id).await?;
+ async fn delete_action(&self, receipt: EntityAccessReceipt<OwnerAccessLevel>) -> Result<()> {
+ let action = self.load_granted(&receipt).await?;
+ let Some(id) = action.id else {
+ bail!("cannot delete action without id");
+ };
+ self.repo.delete_action(&id).await?;
self.dispatcher_tx
.send(DispatchEvent::Delete(action))
.await
@@ -309,10 +348,9 @@ where
async fn execute_action_now(
&self,
- id: &Uuid,
- macro_user_id: MacroUserIdStr<'static>,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
) -> Result<InProgressExecution> {
- let action = self.owned_action(id, &macro_user_id).await?;
+ let action = self.load_granted(&receipt).await?;
action.owner_user()?;
// Manual execution deliberately has no event reference or event-run ID.
self.executor.execute_action(action).await
@@ -320,10 +358,12 @@ where
async fn get_execution_records(
&self,
- id: &Uuid,
- macro_user_id: MacroUserIdStr<'static>,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
) -> Result<Vec<ActionExecutionRecord>> {
- self.owned_action(id, &macro_user_id).await?;
- self.repo.get_execution_records(id).await
+ let action = self.load_granted(&receipt).await?;
+ let Some(id) = action.id else {
+ bail!("cannot read execution history without id");
+ };
+ self.repo.get_execution_records(&id).await
}
}
diff --git a/services/scheduled_action/src/domain/service/test.rs b/services/scheduled_action/src/domain/service/test.rs
index 44d597e211..72ba0deb73 100644
--- a/services/scheduled_action/src/domain/service/test.rs
+++ b/services/scheduled_action/src/domain/service/test.rs
@@ -18,7 +18,16 @@ use crate::domain::{
},
};
use agent_session::domain::routines::RoutineSessionError;
+use entity_access::domain::{
+ models::{
+ AccessError, EditAccessLevel, EntityAccessReceipt, EntityType, OwnerAccessLevel,
+ ViewAccessLevel,
+ },
+ ports::ScheduledActionGrants,
+};
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use macro_uuid::generate_uuid_v7;
+use model_owner::{CreationPrincipal, Owner};
use serde_json::json;
use std::sync::Mutex;
@@ -37,16 +46,26 @@ impl ScheduledActionRepo for FakeRepo {
Ok(action)
}
- async fn get_actions(&self, _user: MacroUserIdStr<'static>) -> Result<Vec<ScheduledAction>> {
- // Deliberately return all owners to exercise the service's owner check.
+ async fn get_owned_actions(
+ &self,
+ _owner: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<ScheduledAction>> {
+ // Return every stored owner so cleanup can reject a foreign row.
Ok(self.actions.lock().unwrap().clone())
}
- async fn get_action(
- &self,
- id: &Uuid,
- _user: MacroUserIdStr<'static>,
- ) -> Result<Option<ScheduledAction>> {
+ async fn get_actions_by_ids(&self, ids: &[Uuid]) -> Result<Vec<ScheduledAction>> {
+ Ok(self
+ .actions
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|action| action.id.is_some_and(|id| ids.contains(&id)))
+ .cloned()
+ .collect())
+ }
+
+ async fn get_action(&self, id: &Uuid) -> Result<Option<ScheduledAction>> {
Ok(self
.actions
.lock()
@@ -66,7 +85,7 @@ impl ScheduledActionRepo for FakeRepo {
Ok(action)
}
- async fn delete_action(&self, id: &Uuid, _user: MacroUserIdStr<'static>) -> Result<()> {
+ async fn delete_action(&self, id: &Uuid) -> Result<()> {
self.actions.lock().unwrap().retain(|a| a.id != Some(*id));
Ok(())
}
@@ -119,21 +138,119 @@ impl ScheduledActionExecutor for FakeExecutor {
}
}
-pub(crate) type TestService = ScheduledActionServiceImpl<FakeRepo, FakeExecutor>;
+pub(crate) struct FakeGrants {
+ repo: Arc<FakeRepo>,
+ only: Mutex<Option<Vec<Uuid>>>,
+ granted: Mutex<std::collections::HashMap<String, Vec<Uuid>>>,
+}
+
+impl FakeGrants {
+ pub(crate) fn all(repo: Arc<FakeRepo>) -> Self {
+ Self {
+ repo,
+ only: Mutex::new(None),
+ granted: Mutex::new(std::collections::HashMap::new()),
+ }
+ }
+}
+
+impl ScheduledActionGrants for FakeGrants {
+ async fn accessible_scheduled_action_ids(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Vec<Uuid>, AccessError> {
+ if user_id.as_ref() != USER {
+ return Ok(self
+ .granted
+ .lock()
+ .unwrap()
+ .get(user_id.as_ref())
+ .cloned()
+ .unwrap_or_default());
+ }
+ if let Some(ids) = self.only.lock().unwrap().clone() {
+ return Ok(ids);
+ }
+ Ok(self
+ .repo
+ .actions
+ .lock()
+ .unwrap()
+ .iter()
+ .filter_map(|action| action.id)
+ .collect())
+ }
+}
+
+pub(crate) fn set_stored_owner(service: &TestService, id: Uuid, owner: Owner) {
+ let mut actions = service.repo.actions.lock().unwrap();
+ let action = actions
+ .iter_mut()
+ .find(|action| action.id == Some(id))
+ .expect("stored action");
+ action.owner = owner;
+}
+
+pub(crate) fn grant_to(service: &TestService, user_id: &str, id: Uuid) {
+ service
+ .grants
+ .granted
+ .lock()
+ .unwrap()
+ .entry(user_id.to_owned())
+ .or_default()
+ .push(id);
+}
+
+pub(crate) type TestService = ScheduledActionServiceImpl<FakeRepo, FakeExecutor, FakeGrants>;
+
+fn grants(repo: &Arc<FakeRepo>) -> Arc<FakeGrants> {
+ Arc::new(FakeGrants::all(Arc::clone(repo)))
+}
pub(crate) fn service(enabled: bool) -> Arc<TestService> {
+ let repo = Arc::new(FakeRepo::default());
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
tokio::spawn(async move { while rx.recv().await.is_some() {} });
Arc::new(
TestService::new(
- Arc::new(FakeRepo::default()),
+ Arc::clone(&repo),
Arc::new(FakeExecutor::default()),
tx,
+ grants(&repo),
)
.with_event_management_enabled(enabled),
)
}
+fn user_principal() -> CreationPrincipal {
+ CreationPrincipal::User(user())
+}
+
+fn edit_receipt(id: Uuid) -> EntityAccessReceipt<EditAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_authenticated_user(
+ user(),
+ &id.to_string(),
+ EntityType::ScheduledAction,
+ )
+}
+
+fn owner_receipt(id: Uuid) -> EntityAccessReceipt<OwnerAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_authenticated_user(
+ user(),
+ &id.to_string(),
+ EntityType::ScheduledAction,
+ )
+}
+
+fn view_receipt(id: Uuid) -> EntityAccessReceipt<ViewAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_authenticated_user(
+ user(),
+ &id.to_string(),
+ EntityType::ScheduledAction,
+ )
+}
+
pub(crate) fn user() -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from(USER.to_owned()).unwrap()
}
@@ -172,13 +289,17 @@ async fn validates_before_persistence_and_rejects_cross_owner_selection() {
base.repo.clone(),
base.executor.clone(),
base.dispatcher_tx.clone(),
+ grants(&base.repo),
)
.with_target_validation(TargetValidation::new(sessions.clone(), true));
let mut config = configuration(false);
config.task = agent_task();
let foreign = MacroUserIdStr::parse_from_str(FOREIGN_USER).unwrap();
let error = svc
- .create_action(CreateScheduledAction::Canonical(config.clone()), foreign)
+ .create_action(
+ &CreationPrincipal::User(foreign),
+ CreateScheduledAction::Canonical(config.clone()),
+ )
.await
.unwrap_err();
assert_eq!(error.downcast_ref(), Some(&RoutineSessionError::Forbidden));
@@ -186,7 +307,10 @@ async fn validates_before_persistence_and_rejects_cross_owner_selection() {
config.task = json!({});
let error = svc
- .create_action(CreateScheduledAction::Canonical(config.clone()), user())
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(config.clone()),
+ )
.await
.unwrap_err();
assert_eq!(
@@ -197,14 +321,17 @@ async fn validates_before_persistence_and_rejects_cross_owner_selection() {
config.task = agent_task();
let created = svc
- .create_action(CreateScheduledAction::Canonical(config.clone()), user())
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(config.clone()),
+ )
.await
.unwrap();
let original = created.task;
*sessions.error.lock().unwrap() = Some(RoutineSessionError::Forbidden);
config.task["user_prompt"] = json!("replacement");
let error = svc
- .update_action(&created.id.unwrap(), update(config), user())
+ .update_action(edit_receipt(created.id.unwrap()), update(config))
.await
.unwrap_err();
assert_eq!(error.downcast_ref(), Some(&RoutineSessionError::Forbidden));
@@ -223,12 +350,16 @@ async fn gated_acceptance_allows_models_and_explicit_switch_but_rejects_old_clie
base.repo.clone(),
base.executor.clone(),
base.dispatcher_tx.clone(),
+ grants(&base.repo),
)
.with_target_validation(TargetValidation::new(Arc::new(Sessions::default()), true));
let mut config = configuration(false);
config.task = agent_task();
let error = base
- .create_action(CreateScheduledAction::Canonical(config.clone()), user())
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(config.clone()),
+ )
.await
.unwrap_err();
assert_eq!(
@@ -236,12 +367,15 @@ async fn gated_acceptance_allows_models_and_explicit_switch_but_rejects_old_clie
Some(&TargetValidationError::AgentsDisabled)
);
let created = svc
- .create_action(CreateScheduledAction::Canonical(config.clone()), user())
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(config.clone()),
+ )
.await
.unwrap();
let id = created.id.unwrap();
let error = base
- .update_action(&id, update(config), user())
+ .update_action(edit_receipt(id), update(config))
.await
.unwrap_err();
assert_eq!(
@@ -254,7 +388,7 @@ async fn gated_acceptance_allows_models_and_explicit_switch_but_rejects_old_clie
for enabled in [false, true] {
model.enabled = enabled;
let error = base
- .update_action(&id, update(model.clone()), user())
+ .update_action(edit_receipt(id), update(model.clone()))
.await
.unwrap_err();
assert_eq!(
@@ -265,11 +399,11 @@ async fn gated_acceptance_allows_models_and_explicit_switch_but_rejects_old_clie
}
model.task["agent"] = json!(null);
let switched = base
- .update_action(&id, update(model.clone()), user())
+ .update_action(edit_receipt(id), update(model.clone()))
.await
.unwrap();
assert_eq!(switched.task, model.task);
- base.create_action(CreateScheduledAction::Canonical(model), user())
+ base.create_action(&user_principal(), CreateScheduledAction::Canonical(model))
.await
.unwrap();
}
@@ -283,12 +417,16 @@ async fn unavailable_agents_can_be_paused_deleted_and_have_history_read_without_
base.repo.clone(),
base.executor.clone(),
base.dispatcher_tx.clone(),
+ grants(&base.repo),
)
.with_target_validation(TargetValidation::new(sessions.clone(), true));
let mut config = configuration(false);
config.task = agent_task();
let created = svc
- .create_action(CreateScheduledAction::Canonical(config.clone()), user())
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(config.clone()),
+ )
.await
.unwrap();
let id = created.id.unwrap();
@@ -298,7 +436,7 @@ async fn unavailable_agents_can_be_paused_deleted_and_have_history_read_without_
*sessions.error.lock().unwrap() = Some(RoutineSessionError::RuntimeUnavailable);
if !claimed {
let error = svc
- .update_action(&id, update(config.clone()), user())
+ .update_action(edit_receipt(id), update(config.clone()))
.await
.unwrap_err();
assert_eq!(
@@ -309,18 +447,18 @@ async fn unavailable_agents_can_be_paused_deleted_and_have_history_read_without_
let validations = sessions.validations.lock().unwrap().len();
config.enabled = false;
let paused = svc
- .update_action(&id, update(config.clone()), user())
+ .update_action(edit_receipt(id), update(config.clone()))
.await
.unwrap();
assert!(!paused.enabled);
assert_eq!(paused.task, created.task);
assert_eq!(paused.claimed.is_some(), claimed);
// Disabling still works if acceptance has since been turned off.
- base.update_action(&id, update(config), user())
+ base.update_action(edit_receipt(id), update(config))
.await
.unwrap();
- svc.get_execution_records(&id, user()).await.unwrap();
- svc.delete_action(&id, user()).await.unwrap();
+ svc.get_execution_records(view_receipt(id)).await.unwrap();
+ svc.delete_action(owner_receipt(id)).await.unwrap();
assert!(base.repo.actions.lock().unwrap().is_empty());
assert_eq!(sessions.validations.lock().unwrap().len(), validations);
}
@@ -357,12 +495,13 @@ async fn preparation_reauthorizes_previously_saved_selection_after_deletion_or_r
base.repo.clone(),
base.executor.clone(),
base.dispatcher_tx.clone(),
+ grants(&base.repo),
)
.with_target_validation(TargetValidation::new(sessions.clone(), true));
let mut config = configuration(false);
config.task = agent_task();
let created = svc
- .create_action(CreateScheduledAction::Canonical(config), user())
+ .create_action(&user_principal(), CreateScheduledAction::Canonical(config))
.await
.unwrap();
assert!(sessions.preparations.lock().unwrap().is_empty());
@@ -394,8 +533,8 @@ async fn creates_both_triggers_with_server_owned_state_and_legacy_input() {
let before = Utc::now();
let created = svc
.create_action(
+ &user_principal(),
CreateScheduledAction::Canonical(configuration(events)),
- user(),
)
.await
.unwrap();
@@ -415,7 +554,7 @@ async fn creates_both_triggers_with_server_owned_state_and_legacy_input() {
}))
.unwrap();
assert!(
- svc.create_action(legacy, user())
+ svc.create_action(&user_principal(), legacy)
.await
.unwrap()
.next_run_at
@@ -426,28 +565,30 @@ async fn creates_both_triggers_with_server_owned_state_and_legacy_input() {
#[tokio::test]
async fn default_gate_rejects_event_creation_and_transition_but_allows_cron() {
let (tx, _rx) = tokio::sync::mpsc::channel(8);
+ let repo = Arc::new(FakeRepo::default());
let svc = TestService::new(
- Arc::new(FakeRepo::default()),
+ repo.clone(),
Arc::new(FakeExecutor::default()),
tx,
+ grants(&repo),
);
assert_policy(
svc.create_action(
+ &user_principal(),
CreateScheduledAction::Canonical(configuration(true)),
- user(),
)
.await,
ActionPolicyError::EventManagementDisabled,
);
let cron = svc
.create_action(
+ &user_principal(),
CreateScheduledAction::Canonical(configuration(false)),
- user(),
)
.await
.unwrap();
assert_policy(
- svc.update_action(&cron.id.unwrap(), update(configuration(true)), user())
+ svc.update_action(edit_receipt(cron.id.unwrap()), update(configuration(true)))
.await,
ActionPolicyError::EventManagementDisabled,
);
@@ -459,19 +600,23 @@ async fn gate_off_rejects_enabling_an_existing_event_action() {
let mut config = configuration(true);
config.enabled = false;
let action = enabled
- .create_action(CreateScheduledAction::Canonical(config.clone()), user())
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(config.clone()),
+ )
.await
.unwrap();
let disabled = TestService::new(
enabled.repo.clone(),
enabled.executor.clone(),
enabled.dispatcher_tx.clone(),
+ grants(&enabled.repo),
)
.with_event_management_enabled(false);
config.enabled = true;
assert_policy(
disabled
- .update_action(&action.id.unwrap(), update(config), user())
+ .update_action(edit_receipt(action.id.unwrap()), update(config))
.await,
ActionPolicyError::EventManagementDisabled,
);
@@ -487,7 +632,7 @@ async fn cron_without_future_firings_is_bad_input() {
)
.unwrap();
assert_policy(
- svc.create_action(CreateScheduledAction::Canonical(input), user())
+ svc.create_action(&user_principal(), CreateScheduledAction::Canonical(input))
.await,
ActionPolicyError::NoFutureFirings,
);
@@ -498,82 +643,152 @@ async fn list_is_cron_only_by_default_but_id_operations_reach_events() {
let svc = service(true);
let cron = svc
.create_action(
+ &user_principal(),
CreateScheduledAction::Canonical(configuration(false)),
- user(),
)
.await
.unwrap();
let event = svc
.create_action(
+ &user_principal(),
CreateScheduledAction::Canonical(configuration(true)),
- user(),
)
.await
.unwrap();
assert_eq!(svc.get_actions(user(), false).await.unwrap()[0].id, cron.id);
assert_eq!(svc.get_actions(user(), false).await.unwrap().len(), 1);
assert_eq!(svc.get_actions(user(), true).await.unwrap().len(), 2);
- svc.get_execution_records(&event.id.unwrap(), user())
+ svc.get_execution_records(view_receipt(event.id.unwrap()))
+ .await
+ .unwrap();
+ svc.delete_action(owner_receipt(event.id.unwrap()))
.await
.unwrap();
- svc.delete_action(&event.id.unwrap(), user()).await.unwrap();
assert_eq!(svc.get_actions(user(), true).await.unwrap().len(), 1);
}
#[tokio::test]
-async fn foreign_and_non_user_owners_cannot_be_managed_or_executed() {
+async fn receipt_manages_another_owners_row_and_missing_row_is_not_found() {
let svc = service(true);
- for owner in [
- Owner::from_principal_str(FOREIGN_USER).unwrap(),
- Owner::from_principal_str(&format!("bot|{}", generate_uuid_v7())).unwrap(),
- Owner::from_principal_str(&generate_uuid_v7().to_string()).unwrap(),
- ] {
- let created = svc
- .create_action(
- CreateScheduledAction::Canonical(configuration(true)),
- user(),
- )
- .await
- .unwrap();
- let id = created.id.unwrap();
- svc.repo.actions.lock().unwrap().last_mut().unwrap().owner = owner;
- assert_policy(
- svc.update_action(&id, update(configuration(true)), user())
- .await,
- ActionPolicyError::NotFound,
- );
- assert_policy(
- svc.set_enabled(&id, false, user()).await,
- ActionPolicyError::NotFound,
- );
- assert_policy(
- svc.delete_action(&id, user()).await,
- ActionPolicyError::NotFound,
- );
- assert_policy(
- svc.get_execution_records(&id, user()).await,
- ActionPolicyError::NotFound,
- );
- assert_policy(
- svc.execute_action_now(&id, user()).await,
- ActionPolicyError::NotFound,
- );
- }
- assert!(svc.get_actions(user(), true).await.unwrap().is_empty());
- let enabled: Vec<bool> = svc
- .repo
- .actions
- .lock()
- .unwrap()
- .iter()
- .map(|a| a.enabled)
- .collect();
- assert_eq!(enabled, [true, true, true]);
- assert!(svc.executor.calls.lock().unwrap().is_empty());
- assert_policy(
- svc.execute_action_now(&generate_uuid_v7(), user()).await,
- ActionPolicyError::NotFound,
+ let created = svc
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(configuration(false)),
+ )
+ .await
+ .unwrap();
+ let id = created.id.unwrap();
+ svc.repo.actions.lock().unwrap()[0].owner = Owner::from_principal_str(FOREIGN_USER).unwrap();
+ svc.delete_action(owner_receipt(id)).await.unwrap();
+ assert!(svc.repo.actions.lock().unwrap().is_empty());
+ let error = svc.execute_action_now(owner_receipt(id)).await.unwrap_err();
+ assert!(matches!(
+ error.downcast_ref(),
+ Some(ActionPolicyError::NotFound)
+ ));
+}
+
+#[tokio::test]
+async fn bot_owned_execution_and_validating_update_need_a_user_owner() {
+ use crate::domain::target_validation::{
+ TargetValidation,
+ test::{Sessions, agent_task},
+ };
+ let base = service(true);
+ let sessions = Arc::new(Sessions::default());
+ let svc = TestService::new(
+ base.repo.clone(),
+ base.executor.clone(),
+ base.dispatcher_tx.clone(),
+ grants(&base.repo),
+ )
+ .with_target_validation(TargetValidation::new(sessions.clone(), true));
+ let mut config = configuration(false);
+ config.task = agent_task();
+ let created = svc
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(config.clone()),
+ )
+ .await
+ .unwrap();
+ let id = created.id.unwrap();
+ let editor = EntityAccessReceipt::<EditAccessLevel>::dangerously_assert_authenticated_user(
+ MacroUserIdStr::parse_from_str(FOREIGN_USER).unwrap(),
+ &id.to_string(),
+ EntityType::ScheduledAction,
+ );
+ config.task["prompt"] = json!("changed");
+ svc.update_action(editor, update(config.clone()))
+ .await
+ .unwrap();
+ assert_eq!(
+ sessions
+ .validations
+ .lock()
+ .unwrap()
+ .last()
+ .unwrap()
+ .owner
+ .as_ref(),
+ USER
);
+
+ svc.repo.actions.lock().unwrap()[0].owner = Owner::Bot(bot_id::BotId::TEST_A);
+ let before = sessions.validations.lock().unwrap().len();
+ let error = svc
+ .update_action(edit_receipt(id), update(config.clone()))
+ .await
+ .unwrap_err();
+ assert!(error.downcast_ref::<OwnerNotUserError>().is_some());
+ assert_eq!(sessions.validations.lock().unwrap().len(), before);
+
+ let disabled = svc.set_enabled(edit_receipt(id), false).await.unwrap();
+ assert!(!disabled.enabled);
+ assert_eq!(sessions.validations.lock().unwrap().len(), before);
+
+ let error = svc.execute_action_now(owner_receipt(id)).await.unwrap_err();
+ assert!(error.to_string().contains("owner is a bot"));
+ assert!(base.executor.calls.lock().unwrap().is_empty());
+
+ svc.repo.actions.lock().unwrap()[0].owner = Owner::User(user());
+ svc.execute_action_now(owner_receipt(id)).await.unwrap();
+ assert_eq!(base.executor.calls.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn user_and_bot_for_user_record_a_user_and_team_bot_writes_nothing() {
+ let svc = service(true);
+ let input = CreateScheduledAction::Canonical(configuration(false));
+ let as_user = svc
+ .create_action(&CreationPrincipal::User(user()), input.clone())
+ .await
+ .unwrap();
+ assert_eq!(as_user.owner, Owner::User(user()));
+ let as_bot = svc
+ .create_action(
+ &CreationPrincipal::BotForUser {
+ bot: bot_id::BotId::TEST_A,
+ user: user(),
+ },
+ input.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(as_bot.owner, Owner::User(user()));
+ let before = svc.repo.actions.lock().unwrap().len();
+ let error = svc
+ .create_action(
+ &CreationPrincipal::TeamBot {
+ bot: bot_id::NonSystemBotId::new(bot_id::BotId::TEST_A).unwrap(),
+ team: Uuid::from_u128(7),
+ },
+ input,
+ )
+ .await
+ .unwrap_err();
+ assert!(error.to_string().contains("owner is a bot"));
+ assert_eq!(svc.repo.actions.lock().unwrap().len(), before);
}
#[tokio::test]
@@ -583,17 +798,18 @@ async fn disabled_manual_runs_work_for_both_variants_even_with_gate_off() {
enabled.repo.clone(),
enabled.executor.clone(),
enabled.dispatcher_tx.clone(),
+ grants(&enabled.repo),
);
for events in [false, true] {
let mut config = configuration(events);
config.enabled = false;
let action = enabled
- .create_action(CreateScheduledAction::Canonical(config), user())
+ .create_action(&user_principal(), CreateScheduledAction::Canonical(config))
.await
.unwrap();
let id = action.id.unwrap();
- svc.execute_action_now(&id, user()).await.unwrap();
- let after = svc.owned_action(&id, &user()).await.unwrap();
+ svc.execute_action_now(owner_receipt(id)).await.unwrap();
+ let after = svc.repo.get_action(&id).await.unwrap().unwrap();
assert_eq!(after.configuration_revision, action.configuration_revision);
assert_eq!(after.event_activated_at, action.event_activated_at);
assert!(!after.enabled);
@@ -606,7 +822,10 @@ async fn updates_advance_revision_and_only_trigger_changes_or_enabling_reset_act
let svc = service(true);
let mut config = configuration(true);
let action = svc
- .create_action(CreateScheduledAction::Canonical(config.clone()), user())
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(config.clone()),
+ )
.await
.unwrap();
let id = action.id.unwrap();
@@ -614,7 +833,7 @@ async fn updates_advance_revision_and_only_trigger_changes_or_enabling_reset_act
svc.repo.actions.lock().unwrap()[0].event_activated_at = Some(past);
config.task["prompt"] = json!("changed");
let updated = svc
- .update_action(&id, update(config.clone()), user())
+ .update_action(edit_receipt(id), update(config.clone()))
.await
.unwrap();
assert_eq!(updated.configuration_revision.get(), 2);
@@ -622,14 +841,14 @@ async fn updates_advance_revision_and_only_trigger_changes_or_enabling_reset_act
assert_eq!(updated.event_activated_at, Some(past));
config.enabled = false;
let disabled = svc
- .update_action(&id, update(config.clone()), user())
+ .update_action(edit_receipt(id), update(config.clone()))
.await
.unwrap();
assert_eq!(disabled.configuration_revision.get(), 3);
assert_eq!(disabled.event_activated_at, Some(past));
config.enabled = true;
let enabled = svc
- .update_action(&id, update(config.clone()), user())
+ .update_action(edit_receipt(id), update(config.clone()))
.await
.unwrap();
assert_eq!(enabled.configuration_revision.get(), 4);
@@ -640,12 +859,12 @@ async fn updates_advance_revision_and_only_trigger_changes_or_enabling_reset_act
)
.unwrap();
let changed = svc
- .update_action(&id, update(config), user())
+ .update_action(edit_receipt(id), update(config))
.await
.unwrap();
assert!(changed.event_activated_at.unwrap() > past);
let cron = svc
- .update_action(&id, update(configuration(false)), user())
+ .update_action(edit_receipt(id), update(configuration(false)))
.await
.unwrap();
assert!(cron.event_activated_at.is_none());
@@ -657,7 +876,10 @@ async fn active_execution_blocks_replacement_but_allows_disabling_even_with_gate
let enabled = service(true);
let mut config = configuration(true);
let action = enabled
- .create_action(CreateScheduledAction::Canonical(config.clone()), user())
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(config.clone()),
+ )
.await
.unwrap();
let id = action.id.unwrap();
@@ -666,7 +888,7 @@ async fn active_execution_blocks_replacement_but_allows_disabling_even_with_gate
replacement.name = "new name".into();
assert_policy(
enabled
- .update_action(&id, update(replacement), user())
+ .update_action(edit_receipt(id), update(replacement))
.await,
ActionPolicyError::UpdateConflict,
);
@@ -674,14 +896,16 @@ async fn active_execution_blocks_replacement_but_allows_disabling_even_with_gate
enabled.repo.clone(),
enabled.executor.clone(),
enabled.dispatcher_tx.clone(),
+ grants(&enabled.repo),
);
assert_policy(
- svc.update_action(&id, update(config.clone()), user()).await,
+ svc.update_action(edit_receipt(id), update(config.clone()))
+ .await,
ActionPolicyError::EventManagementDisabled,
);
config.enabled = false;
let disabled = svc
- .update_action(&id, update(config), user())
+ .update_action(edit_receipt(id), update(config))
.await
.unwrap();
assert!(!disabled.enabled);
@@ -733,7 +957,10 @@ async fn expired_claim_allows_configuration_replacement() {
let svc = service(true);
let mut config = configuration(false);
let action = svc
- .create_action(CreateScheduledAction::Canonical(config.clone()), user())
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(config.clone()),
+ )
.await
.unwrap();
let id = action.id.unwrap();
@@ -741,7 +968,7 @@ async fn expired_claim_allows_configuration_replacement() {
Some(Utc::now() - MAX_ACTION_TIME - chrono::Duration::seconds(1));
config.name = "renamed".into();
let updated = svc
- .update_action(&id, update(config), user())
+ .update_action(edit_receipt(id), update(config))
.await
.unwrap();
assert_eq!(updated.name, "renamed");
@@ -780,28 +1007,30 @@ fn seeded(
#[tokio::test]
async fn activation_changes_are_idempotent_and_keep_configuration() {
let (tx, mut rx) = tokio::sync::mpsc::channel(8);
+ let repo = Arc::new(FakeRepo::default());
let svc = TestService::new(
- Arc::new(FakeRepo::default()),
+ repo.clone(),
Arc::new(FakeExecutor::default()),
tx,
+ grants(&repo),
);
let created = svc
.create_action(
+ &user_principal(),
CreateScheduledAction::Canonical(configuration(false)),
- user(),
)
.await
.unwrap();
let id = created.id.unwrap();
assert!(matches!(rx.try_recv(), Ok(DispatchEvent::Create(_))));
- let unchanged = svc.set_enabled(&id, true, user()).await.unwrap();
+ let unchanged = svc.set_enabled(edit_receipt(id), true).await.unwrap();
assert_eq!(unchanged.configuration_revision.get(), 1);
assert_eq!(unchanged.updated_at, created.updated_at);
assert!(rx.try_recv().is_err());
- let paused = svc.set_enabled(&id, false, user()).await.unwrap();
- let repeated = svc.set_enabled(&id, false, user()).await.unwrap();
+ let paused = svc.set_enabled(edit_receipt(id), false).await.unwrap();
+ let repeated = svc.set_enabled(edit_receipt(id), false).await.unwrap();
assert!(!repeated.enabled);
assert_eq!(repeated.configuration_revision.get(), 2);
assert_eq!(repeated.updated_at, paused.updated_at);
@@ -809,7 +1038,7 @@ async fn activation_changes_are_idempotent_and_keep_configuration() {
assert!(rx.try_recv().is_err());
svc.repo.actions.lock().unwrap()[0].next_run_at = Some(Utc::now() - chrono::Duration::days(1));
- let resumed = svc.set_enabled(&id, true, user()).await.unwrap();
+ let resumed = svc.set_enabled(edit_receipt(id), true).await.unwrap();
assert!(resumed.enabled);
assert_eq!(resumed.configuration_revision.get(), 3);
assert!(
@@ -846,36 +1075,51 @@ async fn read_service_keeps_both_triggers_for_the_owner_in_stable_order() {
"foreign",
),
seeded(4, Owner::User(user()), later, false, "first-equal"),
- seeded(9, Owner::User(user()), early, false, "early-cron"),
+ seeded(2, Owner::User(user()), early, false, "early-cron"),
seeded(
- 2,
+ 6,
Owner::from_principal_str(&format!("bot|{}", Uuid::from_u128(50))).unwrap(),
early,
false,
"bot",
),
seeded(
- 8,
+ 7,
Owner::from_principal_str(&Uuid::from_u128(77).hyphenated().to_string()).unwrap(),
early,
false,
"team",
),
- seeded(4, Owner::User(user()), later, false, "second-equal"),
+ seeded(5, Owner::User(user()), later, false, "second-equal"),
seeded(3, Owner::User(user()), later, false, "low-id"),
];
let (tx, _rx) = tokio::sync::mpsc::channel(1);
- let svc = TestService::new(repo.clone(), Arc::new(FakeExecutor::default()), tx);
- let reader = ScheduledActionReadServiceImpl::new(repo);
+ let accessible = Arc::new(FakeGrants::all(repo.clone()));
+ *accessible.only.lock().unwrap() = Some(vec![
+ Uuid::from_u128(1),
+ Uuid::from_u128(2),
+ Uuid::from_u128(3),
+ Uuid::from_u128(4),
+ Uuid::from_u128(5),
+ Uuid::from_u128(9),
+ ]);
+ let svc = TestService::new(
+ repo.clone(),
+ Arc::new(FakeExecutor::default()),
+ tx,
+ accessible.clone(),
+ );
+ let reader = ScheduledActionReadServiceImpl::new(repo.clone(), accessible);
let expected = vec![
+ "foreign",
"early-cron",
"low-id",
"first-equal",
"second-equal",
"event",
];
- let read = reader.list_owned(user()).await.unwrap();
+ let read = reader.list_accessible(user()).await.unwrap();
let names = |actions: &[ScheduledAction]| {
actions
.iter()
@@ -883,7 +1127,11 @@ async fn read_service_keeps_both_triggers_for_the_owner_in_stable_order() {
.collect::<Vec<_>>()
};
assert_eq!(names(&read), expected);
- assert!(read.iter().all(|action| action.owner.is_user(&user())));
+ assert!(read.iter().any(|action| action.name == "foreign"));
+ assert!(
+ read.iter()
+ .all(|action| action.name != "bot" && action.name != "team")
+ );
assert!(
read.iter()
.any(|action| matches!(action.trigger, ActionTrigger::Cron { .. }))
@@ -898,7 +1146,13 @@ async fn read_service_keeps_both_triggers_for_the_owner_in_stable_order() {
);
assert_eq!(
names(&svc.get_actions(user(), false).await.unwrap()),
- vec!["early-cron", "low-id", "first-equal", "second-equal"]
+ vec![
+ "foreign",
+ "early-cron",
+ "low-id",
+ "first-equal",
+ "second-equal"
+ ]
);
}
@@ -907,8 +1161,8 @@ async fn gate_off_allows_pausing_an_event_action_but_not_resuming_it() {
let enabled = service(true);
let action = enabled
.create_action(
+ &user_principal(),
CreateScheduledAction::Canonical(configuration(true)),
- user(),
)
.await
.unwrap();
@@ -917,19 +1171,20 @@ async fn gate_off_allows_pausing_an_event_action_but_not_resuming_it() {
enabled.repo.clone(),
enabled.executor.clone(),
enabled.dispatcher_tx.clone(),
+ grants(&enabled.repo),
);
- let paused = gated.set_enabled(&id, false, user()).await.unwrap();
+ let paused = gated.set_enabled(edit_receipt(id), false).await.unwrap();
assert!(!paused.enabled);
assert_eq!(paused.event_activated_at, action.event_activated_at);
assert_policy(
- gated.set_enabled(&id, true, user()).await,
+ gated.set_enabled(edit_receipt(id), true).await,
ActionPolicyError::EventManagementDisabled,
);
assert!(!enabled.repo.actions.lock().unwrap()[0].enabled);
let past = Utc::now() - chrono::Duration::days(1);
enabled.repo.actions.lock().unwrap()[0].event_activated_at = Some(past);
- let resumed = enabled.set_enabled(&id, true, user()).await.unwrap();
+ let resumed = enabled.set_enabled(edit_receipt(id), true).await.unwrap();
assert!(
resumed.event_activated_at.unwrap() > past,
"events published while paused must not be replayed"
@@ -941,18 +1196,18 @@ async fn running_actions_can_be_paused_but_not_resumed() {
let svc = service(true);
let created = svc
.create_action(
+ &user_principal(),
CreateScheduledAction::Canonical(configuration(false)),
- user(),
)
.await
.unwrap();
let id = created.id.unwrap();
svc.repo.actions.lock().unwrap()[0].claimed = Some(Utc::now());
- let paused = svc.set_enabled(&id, false, user()).await.unwrap();
+ let paused = svc.set_enabled(edit_receipt(id), false).await.unwrap();
assert!(!paused.enabled);
assert!(paused.claimed.is_some());
assert_policy(
- svc.set_enabled(&id, true, user()).await,
+ svc.set_enabled(edit_receipt(id), true).await,
ActionPolicyError::UpdateConflict,
);
assert!(!svc.repo.actions.lock().unwrap()[0].enabled);
@@ -966,29 +1221,30 @@ async fn resuming_revalidates_the_stored_agent_but_pausing_does_not() {
base.repo.clone(),
base.executor.clone(),
base.dispatcher_tx.clone(),
+ grants(&base.repo),
)
.with_target_validation(TargetValidation::new(sessions.clone(), true));
let mut config = configuration(false);
config.task = agent_task();
let created = svc
- .create_action(CreateScheduledAction::Canonical(config), user())
+ .create_action(&user_principal(), CreateScheduledAction::Canonical(config))
.await
.unwrap();
let id = created.id.unwrap();
*sessions.error.lock().unwrap() = Some(RoutineSessionError::RuntimeUnavailable);
let validations = sessions.validations.lock().unwrap().len();
- let paused = svc.set_enabled(&id, false, user()).await.unwrap();
+ let paused = svc.set_enabled(edit_receipt(id), false).await.unwrap();
assert_eq!(paused.task, created.task);
assert_eq!(sessions.validations.lock().unwrap().len(), validations);
- let error = svc.set_enabled(&id, true, user()).await.unwrap_err();
+ let error = svc.set_enabled(edit_receipt(id), true).await.unwrap_err();
assert_eq!(
error.downcast_ref(),
Some(&RoutineSessionError::RuntimeUnavailable)
);
assert!(!base.repo.actions.lock().unwrap()[0].enabled);
*sessions.error.lock().unwrap() = None;
- let resumed = svc.set_enabled(&id, true, user()).await.unwrap();
+ let resumed = svc.set_enabled(edit_receipt(id), true).await.unwrap();
assert!(resumed.enabled);
assert_eq!(resumed.task, created.task);
}
@@ -998,15 +1254,15 @@ async fn configuration_updates_that_omit_activation_keep_it() {
let svc = service(true);
let id = svc
.create_action(
+ &user_principal(),
CreateScheduledAction::Canonical(configuration(false)),
- user(),
)
.await
.unwrap()
.id
.unwrap();
for enabled in [false, true] {
- svc.set_enabled(&id, enabled, user()).await.unwrap();
+ svc.set_enabled(edit_receipt(id), enabled).await.unwrap();
let input = serde_json::from_value(json!({
"name": format!("renamed while enabled={enabled}"),
"kind": "Agent",
@@ -1014,7 +1270,7 @@ async fn configuration_updates_that_omit_activation_keep_it() {
"task": {"model": "model", "prompt": "summarize", "user_prompt": "task"},
}))
.unwrap();
- let updated = svc.update_action(&id, input, user()).await.unwrap();
+ let updated = svc.update_action(edit_receipt(id), input).await.unwrap();
assert_eq!(updated.enabled, enabled);
assert_eq!(updated.name, format!("renamed while enabled={enabled}"));
}
diff --git a/services/scheduled_action/src/domain/service/test/user_cleanup.rs b/services/scheduled_action/src/domain/service/test/user_cleanup.rs
index 3b40892399..0db564adb7 100644
--- a/services/scheduled_action/src/domain/service/test/user_cleanup.rs
+++ b/services/scheduled_action/src/domain/service/test/user_cleanup.rs
@@ -1,8 +1,22 @@
use super::super::*;
use super::{configuration, user};
use crate::domain::event_runs::ClaimToken;
+use entity_access::domain::{models::AccessError, ports::ScheduledActionGrants};
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use macro_uuid::Uuid;
+use model_owner::Owner;
use std::sync::Mutex;
+struct UnusedGrants;
+impl ScheduledActionGrants for UnusedGrants {
+ async fn accessible_scheduled_action_ids(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Vec<Uuid>, AccessError> {
+ Ok(Vec::new())
+ }
+}
+
#[derive(Default)]
struct FakeRepo {
actions: Mutex<Vec<ScheduledAction>>,
@@ -10,17 +24,23 @@ struct FakeRepo {
}
impl ScheduledActionRepo for FakeRepo {
- async fn get_actions(&self, user: MacroUserIdStr<'static>) -> Result<Vec<ScheduledAction>> {
+ async fn get_owned_actions(
+ &self,
+ owner: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<ScheduledAction>> {
Ok(self
.actions
.lock()
.unwrap()
.iter()
- .filter(|a| a.owner.is_user(&user))
+ .filter(|a| a.owner.is_user(owner))
.cloned()
.collect())
}
- async fn delete_action(&self, id: &Uuid, _: MacroUserIdStr<'static>) -> Result<()> {
+ async fn get_actions_by_ids(&self, _: &[Uuid]) -> Result<Vec<ScheduledAction>> {
+ unreachable!()
+ }
+ async fn delete_action(&self, id: &Uuid) -> Result<()> {
if *self.fail_delete.lock().unwrap() {
bail!("injected deletion failure");
}
@@ -30,11 +50,7 @@ impl ScheduledActionRepo for FakeRepo {
async fn create_action(&self, _: ScheduledAction) -> Result<ScheduledAction> {
unreachable!()
}
- async fn get_action(
- &self,
- _: &Uuid,
- _: MacroUserIdStr<'static>,
- ) -> Result<Option<ScheduledAction>> {
+ async fn get_action(&self, _: &Uuid) -> Result<Option<ScheduledAction>> {
unreachable!()
}
async fn get_next_unclaimed_actions(&self, _: i64) -> Result<Vec<ScheduledAction>> {
@@ -110,7 +126,12 @@ async fn deletes_disabled_and_claimed_actions_not_other_owners_and_retries_empty
];
let (tx, mut rx) = tokio::sync::mpsc::channel(10);
// Event management is disabled by default, but cleanup must still remove events.
- let service = ScheduledActionServiceImpl::new(repo.clone(), Arc::new(NeverExecutor), tx);
+ let service = ScheduledActionServiceImpl::new(
+ repo.clone(),
+ Arc::new(NeverExecutor),
+ tx,
+ Arc::new(UnusedGrants),
+ );
service.delete_user_actions(user()).await.unwrap();
service.delete_user_actions(user()).await.unwrap();
@@ -132,7 +153,12 @@ async fn repository_failure_keeps_retry_state_and_emits_no_delete() {
.push(action(Owner::User(user()), false));
*repo.fail_delete.lock().unwrap() = true;
let (tx, mut rx) = tokio::sync::mpsc::channel(10);
- let service = ScheduledActionServiceImpl::new(repo.clone(), Arc::new(NeverExecutor), tx);
+ let service = ScheduledActionServiceImpl::new(
+ repo.clone(),
+ Arc::new(NeverExecutor),
+ tx,
+ Arc::new(UnusedGrants),
+ );
assert!(service.delete_user_actions(user()).await.is_err());
assert_eq!(repo.actions.lock().unwrap().len(), 1);
assert!(rx.try_recv().is_err());
@@ -150,7 +176,12 @@ async fn closed_dispatcher_fails_before_deleting_rows() {
.push(action(Owner::User(user()), false));
let (tx, rx) = tokio::sync::mpsc::channel(10);
drop(rx);
- let service = ScheduledActionServiceImpl::new(repo.clone(), Arc::new(NeverExecutor), tx);
+ let service = ScheduledActionServiceImpl::new(
+ repo.clone(),
+ Arc::new(NeverExecutor),
+ tx,
+ Arc::new(UnusedGrants),
+ );
assert!(service.delete_user_actions(user()).await.is_err());
assert_eq!(repo.actions.lock().unwrap().len(), 1);
}
diff --git a/services/scheduled_action/src/domain/target_runner/test.rs b/services/scheduled_action/src/domain/target_runner/test.rs
index 3446f73870..ffd43d7665 100644
--- a/services/scheduled_action/src/domain/target_runner/test.rs
+++ b/services/scheduled_action/src/domain/target_runner/test.rs
@@ -473,14 +473,13 @@ impl ScheduledActionRepo for UnusedRepo {
async fn create_action(&self, _: ScheduledAction) -> Result<ScheduledAction> {
unimplemented!()
}
- async fn get_actions(&self, _: MacroUserIdStr<'static>) -> Result<Vec<ScheduledAction>> {
+ async fn get_owned_actions(&self, _: &MacroUserIdStr<'static>) -> Result<Vec<ScheduledAction>> {
unimplemented!()
}
- async fn get_action(
- &self,
- _: &Uuid,
- _: MacroUserIdStr<'static>,
- ) -> Result<Option<ScheduledAction>> {
+ async fn get_actions_by_ids(&self, _: &[Uuid]) -> Result<Vec<ScheduledAction>> {
+ unimplemented!()
+ }
+ async fn get_action(&self, _: &Uuid) -> Result<Option<ScheduledAction>> {
unimplemented!()
}
async fn get_next_unclaimed_actions(&self, _: i64) -> Result<Vec<ScheduledAction>> {
@@ -489,7 +488,7 @@ impl ScheduledActionRepo for UnusedRepo {
async fn update_action(&self, _: ScheduledAction) -> Result<ScheduledAction> {
unimplemented!()
}
- async fn delete_action(&self, _: &Uuid, _: MacroUserIdStr<'static>) -> Result<()> {
+ async fn delete_action(&self, _: &Uuid) -> Result<()> {
unimplemented!()
}
async fn claim_action(&self, _: &Uuid, _: ConfigurationRevision) -> Result<ClaimToken> {
diff --git a/services/scheduled_action/src/inbound/axum_router.rs b/services/scheduled_action/src/inbound/axum_router.rs
index b1632db42a..434f4f6d0f 100644
--- a/services/scheduled_action/src/inbound/axum_router.rs
+++ b/services/scheduled_action/src/inbound/axum_router.rs
@@ -14,12 +14,15 @@ use axum::response::IntoResponse;
use axum::routing::{delete, get, post, put};
use axum::{Json, Router};
use chrono_tz::Tz;
+use entity_access::domain::models::{EditAccessLevel, OwnerAccessLevel, ViewAccessLevel};
+use entity_access::domain::ports::EntityAccessService;
+use entity_access::inbound::axum_extractors::ScheduledActionAccessExtractor;
+use entity_registry::{CreationPrincipalExtractor, NonUserOwners};
use macro_authorization::{
InternalOnly, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
UserOrInternal,
};
use macro_user_id::user_id::MacroUserIdStr;
-use macro_uuid::Uuid;
use model::response::EmptyResponse;
use serde::{Deserialize, Serialize};
use utoipa::{IntoParams, ToSchema};
@@ -73,67 +76,92 @@ pub struct ListActionsQuery {
pub include_events: Option<bool>,
}
-pub struct ScheduledActionRouterState<S, Auth> {
+pub struct ScheduledActionRouterState<S, Svc, Auth> {
pub service: Arc<S>,
+ pub access_service: Arc<Svc>,
pub authorization_state: MacroAuthorizationState<Auth>,
}
-impl<S, Auth> Clone for ScheduledActionRouterState<S, Auth> {
+impl<S, Svc, Auth> Clone for ScheduledActionRouterState<S, Svc, Auth> {
fn clone(&self) -> Self {
Self {
service: Arc::clone(&self.service),
+ access_service: Arc::clone(&self.access_service),
authorization_state: self.authorization_state.clone(),
}
}
}
-impl<S, Auth> FromRef<ScheduledActionRouterState<S, Auth>> for MacroAuthorizationState<Auth> {
- fn from_ref(state: &ScheduledActionRouterState<S, Auth>) -> Self {
+impl<S, Svc, Auth> FromRef<ScheduledActionRouterState<S, Svc, Auth>> for Arc<Svc> {
+ fn from_ref(state: &ScheduledActionRouterState<S, Svc, Auth>) -> Self {
+ Arc::clone(&state.access_service)
+ }
+}
+
+impl<S, Svc, Auth> FromRef<ScheduledActionRouterState<S, Svc, Auth>>
+ for MacroAuthorizationState<Auth>
+{
+ fn from_ref(state: &ScheduledActionRouterState<S, Svc, Auth>) -> Self {
state.authorization_state.clone()
}
}
-pub fn scheduled_action_router<S, Auth, St>(
- state: ScheduledActionRouterState<S, Auth>,
+/// Team bots reach the domain so a non-user owner is `OwnerNotUserError`.
+///
+/// `NonUserOwners::Disabled` would reject that caller with a generic 403
+/// before the service could return the explicit message.
+impl<S, Svc, Auth> FromRef<ScheduledActionRouterState<S, Svc, Auth>> for NonUserOwners {
+ fn from_ref(_state: &ScheduledActionRouterState<S, Svc, Auth>) -> Self {
+ NonUserOwners::Enabled
+ }
+}
+
+pub fn scheduled_action_router<S, Svc, Auth, St>(
+ state: ScheduledActionRouterState<S, Svc, Auth>,
) -> Router<St>
where
S: ScheduledActionService + Send + Sync + 'static,
+ Svc: EntityAccessService,
Auth: MacroAuthorizationService,
St: Send + Sync,
{
Router::new()
.route(
"/scheduled-actions/user/{user_id}",
- delete(delete_user_actions::<S, Auth>),
+ delete(delete_user_actions::<S, Svc, Auth>),
)
.route(
"/scheduled-actions",
- get(list_actions::<S, Auth>).post(create_action::<S, Auth>),
+ get(list_actions::<S, Svc, Auth>).post(create_action::<S, Svc, Auth>),
)
.route(
"/scheduled-actions/{id}",
- put(update_action::<S, Auth>).delete(delete_action::<S, Auth>),
+ put(update_action::<S, Svc, Auth>).delete(delete_action::<S, Svc, Auth>),
)
.route(
"/scheduled-actions/{id}/enabled",
- put(set_action_enabled::<S, Auth>),
+ put(set_action_enabled::<S, Svc, Auth>),
)
.route(
"/scheduled-actions/{id}/execute",
- post(execute_action::<S, Auth>),
+ post(execute_action::<S, Svc, Auth>),
)
.route(
"/scheduled-actions/{id}/history",
- get(list_history::<S, Auth>),
+ get(list_history::<S, Svc, Auth>),
)
.with_state(state)
}
-async fn delete_user_actions<S: ScheduledActionService, Auth: MacroAuthorizationService>(
- State(state): State<ScheduledActionRouterState<S, Auth>>,
+async fn delete_user_actions<S, Svc, Auth>(
+ State(state): State<ScheduledActionRouterState<S, Svc, Auth>>,
_internal: MacroAuthorizationExtractor<Auth, InternalOnly>,
Path(user_id): Path<MacroUserIdStr<'static>>,
-) -> Result<StatusCode, ScheduledActionApiError> {
+) -> Result<StatusCode, ScheduledActionApiError>
+where
+ S: ScheduledActionService,
+ Auth: MacroAuthorizationService,
+{
state.service.delete_user_actions(user_id).await?;
Ok(StatusCode::NO_CONTENT)
}
@@ -161,22 +189,22 @@ pub async fn health() -> impl IntoResponse {
(status = 201, body = ScheduledActionResponse),
(status = 400, body = String),
(status = 401, body = String),
+ (status = 403, body = String),
(status = 500, body = String),
)
)]
-pub async fn create_action<
+pub async fn create_action<S, Svc, Auth>(
+ State(state): State<ScheduledActionRouterState<S, Svc, Auth>>,
+ CreationPrincipalExtractor { principal, .. }: CreationPrincipalExtractor<Auth>,
+ body: Result<Json<CreateScheduledAction>, JsonRejection>,
+) -> Result<impl IntoResponse, ScheduledActionApiError>
+where
S: ScheduledActionService + Send + Sync + 'static,
+ Svc: EntityAccessService,
Auth: MacroAuthorizationService,
->(
- State(state): State<ScheduledActionRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
- body: Result<Json<CreateScheduledAction>, JsonRejection>,
-) -> Result<impl IntoResponse, ScheduledActionApiError> {
+{
let Json(req) = body.map_err(ScheduledActionApiError::InvalidRequest)?;
- let created = state
- .service
- .create_action(req, user.authorization.user.macro_user_id.clone())
- .await?;
+ let created = state.service.create_action(&principal, req).await?;
Ok((
StatusCode::CREATED,
Json(ScheduledActionResponse::from(created)),
@@ -196,14 +224,15 @@ pub async fn create_action<
(status = 500, body = String),
)
)]
-pub async fn list_actions<
- S: ScheduledActionService + Send + Sync + 'static,
- Auth: MacroAuthorizationService,
->(
- State(state): State<ScheduledActionRouterState<S, Auth>>,
+pub async fn list_actions<S, Svc, Auth>(
+ State(state): State<ScheduledActionRouterState<S, Svc, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Query(query): Query<ListActionsQuery>,
-) -> Result<impl IntoResponse, ScheduledActionApiError> {
+) -> Result<impl IntoResponse, ScheduledActionApiError>
+where
+ S: ScheduledActionService + Send + Sync + 'static,
+ Auth: MacroAuthorizationService,
+{
let actions = state
.service
.get_actions(
@@ -235,19 +264,23 @@ pub async fn list_actions<
(status = 500, body = String),
)
)]
-pub async fn update_action<
+pub async fn update_action<S, Svc, Auth>(
+ State(state): State<ScheduledActionRouterState<S, Svc, Auth>>,
+ ScheduledActionAccessExtractor {
+ entity_access_receipt,
+ ..
+ }: ScheduledActionAccessExtractor<EditAccessLevel, Svc, Auth>,
+ body: Result<Json<UpdateScheduledAction>, JsonRejection>,
+) -> Result<impl IntoResponse, ScheduledActionApiError>
+where
S: ScheduledActionService + Send + Sync + 'static,
+ Svc: EntityAccessService,
Auth: MacroAuthorizationService,
->(
- State(state): State<ScheduledActionRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
- Path(id): Path<Uuid>,
- body: Result<Json<UpdateScheduledAction>, JsonRejection>,
-) -> Result<impl IntoResponse, ScheduledActionApiError> {
+{
let Json(req) = body.map_err(ScheduledActionApiError::InvalidRequest)?;
let updated = state
.service
- .update_action(&id, req, user.authorization.user.macro_user_id.clone())
+ .update_action(entity_access_receipt, req)
.await?;
Ok(Json(ScheduledActionResponse::from(updated)))
}
@@ -268,23 +301,23 @@ pub async fn update_action<
(status = 500, body = String),
)
)]
-pub async fn set_action_enabled<
+pub async fn set_action_enabled<S, Svc, Auth>(
+ State(state): State<ScheduledActionRouterState<S, Svc, Auth>>,
+ ScheduledActionAccessExtractor {
+ entity_access_receipt,
+ ..
+ }: ScheduledActionAccessExtractor<EditAccessLevel, Svc, Auth>,
+ body: Result<Json<SetScheduledActionEnabled>, JsonRejection>,
+) -> Result<impl IntoResponse, ScheduledActionApiError>
+where
S: ScheduledActionService + Send + Sync + 'static,
+ Svc: EntityAccessService,
Auth: MacroAuthorizationService,
->(
- State(state): State<ScheduledActionRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
- Path(id): Path<Uuid>,
- body: Result<Json<SetScheduledActionEnabled>, JsonRejection>,
-) -> Result<impl IntoResponse, ScheduledActionApiError> {
+{
let Json(req) = body.map_err(ScheduledActionApiError::InvalidRequest)?;
let action = state
.service
- .set_enabled(
- &id,
- req.enabled,
- user.authorization.user.macro_user_id.clone(),
- )
+ .set_enabled(entity_access_receipt, req.enabled)
.await?;
Ok(Json(ScheduledActionResponse::from(action)))
}
@@ -302,18 +335,19 @@ pub async fn set_action_enabled<
(status = 500, body = String),
)
)]
-pub async fn delete_action<
+pub async fn delete_action<S, Svc, Auth>(
+ State(state): State<ScheduledActionRouterState<S, Svc, Auth>>,
+ ScheduledActionAccessExtractor {
+ entity_access_receipt,
+ ..
+ }: ScheduledActionAccessExtractor<OwnerAccessLevel, Svc, Auth>,
+) -> Result<impl IntoResponse, ScheduledActionApiError>
+where
S: ScheduledActionService + Send + Sync + 'static,
+ Svc: EntityAccessService,
Auth: MacroAuthorizationService,
->(
- State(state): State<ScheduledActionRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
- Path(id): Path<Uuid>,
-) -> Result<impl IntoResponse, ScheduledActionApiError> {
- state
- .service
- .delete_action(&id, user.authorization.user.macro_user_id.clone())
- .await?;
+{
+ state.service.delete_action(entity_access_receipt).await?;
Ok(StatusCode::NO_CONTENT)
}
@@ -332,17 +366,21 @@ pub async fn delete_action<
(status = 500, body = String),
)
)]
-pub async fn execute_action<
+pub async fn execute_action<S, Svc, Auth>(
+ State(state): State<ScheduledActionRouterState<S, Svc, Auth>>,
+ ScheduledActionAccessExtractor {
+ entity_access_receipt,
+ ..
+ }: ScheduledActionAccessExtractor<OwnerAccessLevel, Svc, Auth>,
+) -> Result<impl IntoResponse, ScheduledActionApiError>
+where
S: ScheduledActionService + Send + Sync + 'static,
+ Svc: EntityAccessService,
Auth: MacroAuthorizationService,
->(
- State(state): State<ScheduledActionRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
- Path(id): Path<Uuid>,
-) -> Result<impl IntoResponse, ScheduledActionApiError> {
+{
let execution = state
.service
- .execute_action_now(&id, user.authorization.user.macro_user_id.clone())
+ .execute_action_now(entity_access_receipt)
.await?;
Ok(Json(execution))
}
@@ -360,17 +398,21 @@ pub async fn execute_action<
(status = 500, body = String),
)
)]
-pub async fn list_history<
+pub async fn list_history<S, Svc, Auth>(
+ State(state): State<ScheduledActionRouterState<S, Svc, Auth>>,
+ ScheduledActionAccessExtractor {
+ entity_access_receipt,
+ ..
+ }: ScheduledActionAccessExtractor<ViewAccessLevel, Svc, Auth>,
+) -> Result<impl IntoResponse, ScheduledActionApiError>
+where
S: ScheduledActionService + Send + Sync + 'static,
+ Svc: EntityAccessService,
Auth: MacroAuthorizationService,
->(
- State(state): State<ScheduledActionRouterState<S, Auth>>,
- user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
- Path(id): Path<Uuid>,
-) -> Result<impl IntoResponse, ScheduledActionApiError> {
+{
let records = state
.service
- .get_execution_records(&id, user.authorization.user.macro_user_id.clone())
+ .get_execution_records(entity_access_receipt)
.await?;
Ok(Json(records))
}
diff --git a/services/scheduled_action/src/inbound/axum_router/test.rs b/services/scheduled_action/src/inbound/axum_router/test.rs
index e429e33312..3f16b23f62 100644
--- a/services/scheduled_action/src/inbound/axum_router/test.rs
+++ b/services/scheduled_action/src/inbound/axum_router/test.rs
@@ -1,16 +1,37 @@
use super::*;
-use crate::domain::service::test::{USER, configuration, service};
+use crate::domain::service::test::{USER, configuration, grant_to, service, set_stored_owner};
use axum::{
body::{Body, to_bytes},
http::{Request, header},
};
-use macro_authorization::{InternalIdentityClaims, MacroAuthorizationError};
+use entity_access::domain::{
+ models::{
+ AccessError, AccessLevel, BotAccessScope, BotReceiptScope, CallChannelInfo, Entity,
+ EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission, UserTeamInfo,
+ },
+ ports::EntityAccessService,
+};
+use macro_authorization::{
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotScope,
+ InternalIdentityClaims, MacroAuthorizationError, MacroUserAuthentication,
+};
+use macro_user_id::{
+ lowercased::Lowercase,
+ user_id::{MacroUserId, MacroUserIdStr},
+};
use model::user::UserContext;
+use model_owner::Owner;
use rootcause::Report;
use serde_json::{Value, json};
+use std::collections::HashMap;
use tower::ServiceExt;
use utoipa::OpenApi;
+const OTHER: &str = "macro|[email protected]";
+const VIEWER: &str = "macro|[email protected]";
+const BOT_TOKEN: &str = "team-bot-token";
+const TEAM_ID: macro_uuid::Uuid = macro_uuid::Uuid::from_u128(0x7EA4);
+
#[derive(Clone)]
struct FakeAuth;
@@ -22,13 +43,50 @@ impl MacroAuthorizationService for FakeAuth {
..Default::default()
}),
"other" => Ok(UserContext {
- user_id: "macro|[email protected]".into(),
+ user_id: OTHER.into(),
+ ..Default::default()
+ }),
+ "viewer" => Ok(UserContext {
+ user_id: VIEWER.into(),
+ ..Default::default()
+ }),
+ "stranger" => Ok(UserContext {
+ user_id: "macro|[email protected]".into(),
..Default::default()
}),
_ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
}
}
+ async fn authorize_bot(
+ &self,
+ bot_token: &str,
+ bot_scope: BotScope,
+ acting_user: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ if bot_token != BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+ Ok(BotAuthentication {
+ bot_id: bot_id::BotId::TEST_A,
+ token_id: macro_uuid::Uuid::nil(),
+ bot_scope,
+ team_id: Some(TEAM_ID),
+ acting_user: acting_user
+ .and_then(|claims| claims.user_id)
+ .map(|user_id| {
+ let macro_user_id = MacroUserIdStr::try_from(user_id).expect("acting user id");
+ MacroUserAuthentication {
+ user_context: UserContext {
+ user_id: macro_user_id.to_string(),
+ ..Default::default()
+ },
+ macro_user_id,
+ }
+ }),
+ })
+ }
+
async fn authorize_internal(
&self,
key: &str,
@@ -44,9 +102,175 @@ impl MacroAuthorizationService for FakeAuth {
}
}
+#[derive(Clone)]
+struct FakeEntityAccessService {
+ levels: HashMap<String, AccessLevel>,
+}
+
+impl FakeEntityAccessService {
+ fn owner_only() -> Self {
+ Self {
+ levels: HashMap::from([(USER.to_owned(), AccessLevel::Owner)]),
+ }
+ }
+
+ fn with(levels: impl IntoIterator<Item = (&'static str, AccessLevel)>) -> Self {
+ Self {
+ levels: levels
+ .into_iter()
+ .map(|(user, level)| (user.to_owned(), level))
+ .collect(),
+ }
+ }
+}
+
+impl EntityAccessService for FakeEntityAccessService {
+ async fn generate_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_org_id: Option<i64>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ unimplemented!()
+ }
+
+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ bot_id: bot_id::BotId,
+ scope: BotAccessScope,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ let storage_id = bot_id.into_storage_id();
+ let Some(level) = self.levels.get(storage_id.as_ref()).copied() else {
+ return Err(AccessError::Unauthorized);
+ };
+ let scope = match scope {
+ BotAccessScope::User { user_id, .. } => BotReceiptScope::User {
+ acting_user: user_id,
+ },
+ BotAccessScope::Team { team_id } => BotReceiptScope::Team { team_id },
+ };
+ EntityAccessReceipt::try_new_bot(
+ storage_id,
+ scope,
+ Entity {
+ entity_id: entity_id.to_owned(),
+ entity_type,
+ },
+ EntityPermission::AccessLevel {
+ access_level: level,
+ },
+ )
+ }
+
+ async fn get_access_level(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ unimplemented!()
+ }
+
+ async fn check_access(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ unimplemented!()
+ }
+
+ async fn check_public_access(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ unimplemented!()
+ }
+
+ async fn get_entity_permission(
+ &self,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ entity_type: EntityType,
+ _user_org_id: Option<i64>,
+ ) -> Result<EntityPermission, AccessError> {
+ if entity_type != EntityType::ScheduledAction {
+ return Err(AccessError::BadRequest("unsupported entity type"));
+ }
+ let Some(user_id) = user_id else {
+ return Err(AccessError::Unauthorized);
+ };
+ let Some(level) = self.levels.get(user_id.as_ref()).copied() else {
+ return Err(AccessError::Unauthorized);
+ };
+ Ok(EntityPermission::AccessLevel {
+ access_level: level,
+ })
+ }
+
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<
+ (
+ EntityPermission,
+ macro_uuid::Uuid,
+ entity_access::domain::models::TeamRole,
+ ),
+ AccessError,
+ > {
+ unimplemented!()
+ }
+
+ async fn get_users_by_entity(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Vec<macro_user_id::user_id::MacroUserIdStr<'static>>, AccessError> {
+ unimplemented!()
+ }
+
+ async fn get_call_channel(
+ &self,
+ _call_id: &macro_uuid::Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ unimplemented!()
+ }
+
+ async fn get_call_channel_by_channel_id(
+ &self,
+ _channel_id: &macro_uuid::Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ unimplemented!()
+ }
+
+ async fn get_user_team(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<UserTeamInfo>, AccessError> {
+ unimplemented!()
+ }
+}
+
fn router(events: bool) -> Router {
+ router_with(service(events), FakeEntityAccessService::owner_only())
+}
+
+fn router_with<S: ScheduledActionService>(
+ service: Arc<S>,
+ access: FakeEntityAccessService,
+) -> Router {
scheduled_action_router(ScheduledActionRouterState {
- service: service(events),
+ service,
+ access_service: Arc::new(access),
authorization_state: MacroAuthorizationState::new(Arc::new(FakeAuth)),
})
}
@@ -205,7 +429,7 @@ async fn foreign_owner_operations_return_not_found_and_list_is_empty() {
] {
assert_eq!(
request(&app, method, &path, "other", body).await.0,
- StatusCode::NOT_FOUND
+ StatusCode::UNAUTHORIZED
);
}
assert_eq!(
@@ -420,7 +644,7 @@ async fn target_configuration_is_validated_through_http_and_gate_defaults_off()
#[tokio::test]
async fn agent_replacement_requires_explicit_null_and_unavailable_agent_remains_manageable() {
use crate::domain::{
- service::test::{FakeExecutor, FakeRepo, TestService},
+ service::test::{FakeExecutor, FakeGrants, FakeRepo, TestService},
target_validation::{
TargetValidation,
test::{Sessions, agent_task},
@@ -429,16 +653,15 @@ async fn agent_replacement_requires_explicit_null_and_unavailable_agent_remains_
let sessions = Arc::new(Sessions::default());
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
tokio::spawn(async move { while rx.recv().await.is_some() {} });
+ let repo = Arc::new(FakeRepo::default());
let svc = TestService::new(
- Arc::new(FakeRepo::default()),
+ repo.clone(),
Arc::new(FakeExecutor::default()),
tx,
+ Arc::new(FakeGrants::all(repo)),
)
.with_target_validation(TargetValidation::new(sessions.clone(), true));
- let app: Router = scheduled_action_router(ScheduledActionRouterState {
- service: Arc::new(svc),
- authorization_state: MacroAuthorizationState::new(Arc::new(FakeAuth)),
- });
+ let app = router_with(Arc::new(svc), FakeEntityAccessService::owner_only());
let mut input = legacy();
input["task"] = agent_task();
assert_eq!(
@@ -536,4 +759,159 @@ fn openapi_documents_canonical_legacy_and_event_opt_in_contracts() {
.any(|p| p["name"] == "include_events" && p["required"] == false)
);
assert!(!spec["paths"]["/scheduled-actions/{id}"]["put"]["responses"]["409"].is_null());
+ assert!(!spec["paths"]["/scheduled-actions"]["post"]["responses"]["403"].is_null());
+}
+
+#[tokio::test]
+async fn editor_can_update_another_owners_row_but_cannot_delete_it() {
+ let svc = service(true);
+ let app = router_with(
+ svc.clone(),
+ FakeEntityAccessService::with([
+ (USER, AccessLevel::Owner),
+ (OTHER, AccessLevel::Edit),
+ (VIEWER, AccessLevel::View),
+ ]),
+ );
+ let (_, created) = request(&app, "POST", "/scheduled-actions", "owner", legacy()).await;
+ let id = macro_uuid::Uuid::parse_str(created["id"].as_str().unwrap()).unwrap();
+ set_stored_owner(
+ svc.as_ref(),
+ id,
+ Owner::from_principal_str("macro|[email protected]").unwrap(),
+ );
+ let url = format!("/scheduled-actions/{id}");
+ let (status, updated) = request(&app, "PUT", &url, "other", legacy()).await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(updated["owner"], "macro|[email protected]");
+ assert_eq!(
+ request(&app, "PUT", &url, "viewer", legacy()).await.0,
+ StatusCode::UNAUTHORIZED
+ );
+ assert_eq!(
+ request(&app, "DELETE", &url, "other", Value::Null).await.0,
+ StatusCode::UNAUTHORIZED
+ );
+ assert_eq!(
+ request(
+ &app,
+ "GET",
+ &format!("{url}/history"),
+ "viewer",
+ Value::Null
+ )
+ .await
+ .0,
+ StatusCode::OK
+ );
+ assert_eq!(
+ request(
+ &app,
+ "GET",
+ &format!("{url}/history"),
+ "stranger",
+ Value::Null
+ )
+ .await
+ .0,
+ StatusCode::UNAUTHORIZED
+ );
+ assert_eq!(
+ request(&app, "DELETE", &url, "owner", Value::Null).await.0,
+ StatusCode::NO_CONTENT
+ );
+}
+
+#[tokio::test]
+async fn executing_a_bot_owned_row_returns_the_owner_message() {
+ let svc = service(true);
+ let app = router_with(svc.clone(), FakeEntityAccessService::owner_only());
+ let (_, created) = request(&app, "POST", "/scheduled-actions", "owner", legacy()).await;
+ let id = macro_uuid::Uuid::parse_str(created["id"].as_str().unwrap()).unwrap();
+ set_stored_owner(svc.as_ref(), id, Owner::Bot(bot_id::BotId::TEST_A));
+ let (status, body) = request(
+ &app,
+ "POST",
+ &format!("/scheduled-actions/{id}/execute"),
+ "owner",
+ Value::Null,
+ )
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(body.as_str().unwrap().contains("owner is a bot"));
+}
+
+#[tokio::test]
+async fn bare_internal_key_on_an_id_route_is_unauthorized() {
+ let app = router(false);
+ let response = app
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri(format!(
+ "/scheduled-actions/{}/execute",
+ macro_uuid::generate_uuid_v7()
+ ))
+ .header(
+ macro_authorization::INTERNAL_API_KEY_HEADER,
+ "test-internal-key",
+ )
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+}
+
+#[tokio::test]
+async fn team_bot_create_returns_400_with_the_owner_message() {
+ let svc = service(false);
+ let app = router_with(svc.clone(), FakeEntityAccessService::owner_only());
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/scheduled-actions")
+ .header(BOT_TOKEN_HEADER, BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, "team")
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(Body::from(legacy().to_string()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let body = String::from_utf8_lossy(&bytes);
+ assert!(body.contains("owner is a bot"));
+ let (_, list) = request(&app, "GET", "/scheduled-actions", "owner", Value::Null).await;
+ assert_eq!(list, json!([]));
+}
+
+#[tokio::test]
+async fn list_as_grantee_includes_the_granted_routine() {
+ let svc = service(true);
+ let app = router_with(svc.clone(), FakeEntityAccessService::owner_only());
+ let (_, created) = request(
+ &app,
+ "POST",
+ "/scheduled-actions",
+ "owner",
+ serde_json::to_value(configuration(true)).unwrap(),
+ )
+ .await;
+ let id = macro_uuid::Uuid::parse_str(created["id"].as_str().unwrap()).unwrap();
+ grant_to(svc.as_ref(), OTHER, id);
+ let (_, list) = request(
+ &app,
+ "GET",
+ "/scheduled-actions?include_events=true",
+ "other",
+ Value::Null,
+ )
+ .await;
+ assert_eq!(list.as_array().unwrap().len(), 1);
+ assert_eq!(list[0]["id"], created["id"]);
}
diff --git a/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs b/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs
index 0c28729adf..b8bd6c8cbb 100644
--- a/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs
+++ b/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs
@@ -62,15 +62,18 @@ impl ScheduledActionRepo for FakeRepository {
Ok(action)
}
- async fn get_actions(&self, _user_id: MacroUserIdStr<'static>) -> Result<Vec<ScheduledAction>> {
+ async fn get_owned_actions(
+ &self,
+ _owner: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<ScheduledAction>> {
Ok(Vec::new())
}
- async fn get_action(
- &self,
- _id: &Uuid,
- _user_id: MacroUserIdStr<'static>,
- ) -> Result<Option<ScheduledAction>> {
+ async fn get_actions_by_ids(&self, _ids: &[Uuid]) -> Result<Vec<ScheduledAction>> {
+ Ok(Vec::new())
+ }
+
+ async fn get_action(&self, _id: &Uuid) -> Result<Option<ScheduledAction>> {
Ok(None)
}
@@ -86,11 +89,7 @@ impl ScheduledActionRepo for FakeRepository {
Ok(action)
}
- async fn delete_action(
- &self,
- _id: &Uuid,
- _macro_user_id: MacroUserIdStr<'static>,
- ) -> Result<()> {
+ async fn delete_action(&self, _id: &Uuid) -> Result<()> {
Ok(())
}
diff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
index df925c3f34..35a166899b 100644
--- a/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
@@ -1,12 +1,14 @@
use anyhow::{Context, Result, bail};
use chrono::{DateTime, Utc};
use chrono_tz::Tz;
+use entity_registry::BotFacts;
use entity_registry_db_utils::{
- InsertOutcome, NewEntityRecord, RegisteredEntityType, WriteOutcome, delete_entity,
- insert_entity,
+ InsertOutcome, NewEntityRecord, OwnedEntityRegistrar, RegisteredEntityType, WriteOutcome,
+ delete_entity,
};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::{Uuid, generate_uuid_v7};
+use model_entity::EntityType;
use model_owner::Owner;
use serde_json::Value;
use sqlx::PgPool;
@@ -23,13 +25,20 @@ use crate::domain::ports::ScheduledActionRepo;
#[cfg(test)]
mod test;
-pub struct PgScheduledActionRepo {
+/// PostgreSQL scheduled-action store.
+///
+/// Create registers the recorded owner and that owner's direct grants through
+/// `registrar`. Lookup, update, and delete address a row by id; `owner` is who
+/// the routine runs as, not an authorization predicate.
+pub struct PgScheduledActionRepo<B> {
pool: PgPool,
+ registrar: OwnedEntityRegistrar<B>,
}
-impl PgScheduledActionRepo {
- pub fn new(pool: PgPool) -> Self {
- Self { pool }
+impl<B: BotFacts> PgScheduledActionRepo<B> {
+ /// Persist actions in `pool`, registering each created owner through `registrar`.
+ pub fn new(pool: PgPool, registrar: OwnedEntityRegistrar<B>) -> Self {
+ Self { pool, registrar }
}
}
@@ -132,7 +141,7 @@ impl TryFrom<&ActionTrigger> for TriggerColumns {
}
}
-impl ScheduledActionRepo for PgScheduledActionRepo {
+impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {
async fn create_action(&self, action: ScheduledAction) -> Result<ScheduledAction> {
let id = generate_uuid_v7();
let owner = action.owner.principal_id();
@@ -169,24 +178,31 @@ impl ScheduledActionRepo for PgScheduledActionRepo {
.await?;
let created = ScheduledAction::try_from(row)?;
- match insert_entity(
- &mut tx,
- NewEntityRecord::new(
- id,
- RegisteredEntityType::ScheduledAction,
- created.owner.clone(),
- ),
- )
- .await?
- {
+ match self
+ .registrar
+ .register_owned_entity(
+ &mut tx,
+ NewEntityRecord::new(
+ id,
+ RegisteredEntityType::ScheduledAction,
+ created.owner.clone(),
+ ),
+ )
+ .await
+ .map_err(|error| {
+ anyhow::anyhow!("failed to register scheduled action owner: {error:#}")
+ })? {
InsertOutcome::Inserted | InsertOutcome::AlreadyRegistered => {}
}
tx.commit().await?;
Ok(created)
}
- async fn get_actions(&self, user_id: MacroUserIdStr<'static>) -> Result<Vec<ScheduledAction>> {
- let owner = user_id.to_string();
+ async fn get_owned_actions(
+ &self,
+ owner: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<ScheduledAction>> {
+ let owner = owner.to_string();
let rows = sqlx::query_as!(
ActionRow,
r#"
@@ -203,12 +219,24 @@ impl ScheduledActionRepo for PgScheduledActionRepo {
rows.into_iter().map(ScheduledAction::try_from).collect()
}
- async fn get_action(
- &self,
- id: &Uuid,
- user_id: MacroUserIdStr<'static>,
- ) -> Result<Option<ScheduledAction>> {
- let owner = user_id.to_string();
+ async fn get_actions_by_ids(&self, ids: &[Uuid]) -> Result<Vec<ScheduledAction>> {
+ let rows = sqlx::query_as!(
+ ActionRow,
+ r#"
+ SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,
+ updated_at, next_run_at, enabled, trigger_type, event_filters,
+ configuration_revision, event_activated_at
+ FROM scheduled_action
+ WHERE id = ANY($1)
+ "#,
+ ids,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+ rows.into_iter().map(ScheduledAction::try_from).collect()
+ }
+
+ async fn get_action(&self, id: &Uuid) -> Result<Option<ScheduledAction>> {
sqlx::query_as!(
ActionRow,
r#"
@@ -216,10 +244,9 @@ impl ScheduledActionRepo for PgScheduledActionRepo {
updated_at, next_run_at, enabled, trigger_type, event_filters,
configuration_revision, event_activated_at
FROM scheduled_action
- WHERE id = $1 AND owner = $2
+ WHERE id = $1
"#,
*id,
- owner,
)
.fetch_optional(&self.pool)
.await?
@@ -253,7 +280,6 @@ impl ScheduledActionRepo for PgScheduledActionRepo {
let Some(id) = action.id else {
bail!("cannot update action without id");
};
- let owner = action.owner.principal_id();
let trigger = TriggerColumns::try_from(&action.trigger)?;
let kind = kind_to_str(&action.kind);
let row = sqlx::query_as!(
@@ -272,10 +298,10 @@ impl ScheduledActionRepo for PgScheduledActionRepo {
configuration_revision = $10,
event_activated_at = $11,
updated_at = now()
- WHERE id = $12 AND owner = $13
+ WHERE id = $12
AND configuration_revision = $10::bigint - 1
AND (
- claimed IS NULL OR claimed < $14
+ claimed IS NULL OR claimed < $13
OR (
NOT $7 AND name = $1 AND kind = $3 AND task = $5
AND trigger_type = $8
@@ -300,7 +326,6 @@ impl ScheduledActionRepo for PgScheduledActionRepo {
action.configuration_revision.get(),
action.event_activated_at,
id,
- owner,
Utc::now() - MAX_ACTION_TIME,
)
.fetch_optional(&self.pool)
@@ -309,16 +334,17 @@ impl ScheduledActionRepo for PgScheduledActionRepo {
ScheduledAction::try_from(row)
}
- async fn delete_action(&self, id: &Uuid, macro_user_id: MacroUserIdStr<'static>) -> Result<()> {
- let owner = macro_user_id.to_string();
+ async fn delete_action(&self, id: &Uuid) -> Result<()> {
let mut tx = self.pool.begin().await?;
+ entity_access_db_utils::delete_entity_access_rows(&mut tx, id, EntityType::ScheduledAction)
+ .await
+ .context("failed to delete scheduled action grants")?;
let deleted = sqlx::query!(
r#"
DELETE FROM scheduled_action
- WHERE id = $1 AND owner = $2
+ WHERE id = $1
"#,
*id,
- owner,
)
.execute(&mut *tx)
.await?;
diff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
index d1013c33e6..c6834326b5 100644
--- a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
@@ -1,6 +1,8 @@
mod user_cleanup;
use chrono::Utc;
+use entity_registry::{BotFacts, EntityRegistryResult, OwnerGrantPolicy};
+use entity_registry_db_utils::OwnedEntityRegistrar;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
@@ -26,6 +28,50 @@ fn user_owner(id: &'static str) -> Owner {
Owner::User(user(id))
}
+#[derive(Clone)]
+struct NoBots;
+
+impl BotFacts for NoBots {
+ async fn sponsor(&self, _bot: bot_id::BotId) -> EntityRegistryResult<Option<Owner>> {
+ Ok(None)
+ }
+}
+
+#[derive(Clone)]
+struct SponsoredBy(Owner);
+
+impl BotFacts for SponsoredBy {
+ async fn sponsor(&self, _bot: bot_id::BotId) -> EntityRegistryResult<Option<Owner>> {
+ Ok(Some(self.0.clone()))
+ }
+}
+
+fn test_repo(pool: PgPool) -> PgScheduledActionRepo<NoBots> {
+ PgScheduledActionRepo::new(
+ pool,
+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(NoBots)),
+ )
+}
+
+async fn direct_grants(pool: &PgPool, id: Uuid) -> Vec<(String, String, String)> {
+ sqlx::query!(
+ r#"
+ SELECT source_type::text AS "source_type!", source_id,
+ access_level::text AS "access_level!"
+ FROM entity_access
+ WHERE entity_id = $1 AND granted_from_project_id IS NULL
+ ORDER BY source_type::text, source_id
+ "#,
+ id,
+ )
+ .fetch_all(pool)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|row| (row.source_type, row.source_id, row.access_level))
+ .collect()
+}
+
async fn insert_user(pool: &PgPool, id: &str) {
let macro_user_id = macro_uuid::generate_uuid_v7();
sqlx::query!(
@@ -93,7 +139,7 @@ async fn scheduled_action_row_count(pool: &PgPool, id: Uuid) -> i64 {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn create_action_returns_id_and_is_listable_by_owner(pool: PgPool) {
insert_user(&pool, USER_A).await;
- let repo = PgScheduledActionRepo::new(pool);
+ let repo = test_repo(pool);
let created = repo
.create_action(sample_action(user_owner(USER_A), "standup"))
@@ -103,7 +149,7 @@ async fn create_action_returns_id_and_is_listable_by_owner(pool: PgPool) {
assert_eq!(created.owner, user_owner(USER_A));
let listed = repo
- .get_actions(user(USER_A))
+ .get_owned_actions(&user(USER_A))
.await
.expect("list should succeed");
assert_eq!(listed.len(), 1);
@@ -113,23 +159,23 @@ async fn create_action_returns_id_and_is_listable_by_owner(pool: PgPool) {
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn other_owner_list_is_empty(pool: PgPool) {
+async fn get_owned_actions_excludes_other_principals(pool: PgPool) {
insert_user(&pool, USER_A).await;
insert_user(&pool, USER_B).await;
- let repo = PgScheduledActionRepo::new(pool);
+ let repo = test_repo(pool);
repo.create_action(sample_action(user_owner(USER_A), "standup"))
.await
.expect("create should succeed");
let owner_listed = repo
- .get_actions(user(USER_A))
+ .get_owned_actions(&user(USER_A))
.await
.expect("owner list should succeed");
assert_eq!(owner_listed.len(), 1);
let listed = repo
- .get_actions(user(USER_B))
+ .get_owned_actions(&user(USER_B))
.await
.expect("list should succeed");
assert!(listed.is_empty());
@@ -138,7 +184,7 @@ async fn other_owner_list_is_empty(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn update_action_changes_name_schedule_and_enabled(pool: PgPool) {
insert_user(&pool, USER_A).await;
- let repo = PgScheduledActionRepo::new(pool);
+ let repo = test_repo(pool);
let created = repo
.create_action(sample_action(user_owner(USER_A), "standup"))
@@ -175,7 +221,7 @@ async fn update_action_changes_name_schedule_and_enabled(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn replacement_is_fenced_against_claims_and_stale_revisions(pool: PgPool) {
insert_user(&pool, USER_A).await;
- let repo = PgScheduledActionRepo::new(pool);
+ let repo = test_repo(pool);
let action = repo.create_action(event_action()).await.unwrap();
let id = action.id.unwrap();
let mut replacement = action.clone();
@@ -209,7 +255,7 @@ async fn replacement_is_fenced_against_claims_and_stale_revisions(pool: PgPool)
error.downcast_ref(),
Some(ActionPolicyError::UpdateConflict)
));
- let current = repo.get_action(&id, user(USER_A)).await.unwrap().unwrap();
+ let current = repo.get_action(&id).await.unwrap().unwrap();
assert!(!current.enabled);
assert_eq!(
current.configuration_revision,
@@ -220,7 +266,7 @@ async fn replacement_is_fenced_against_claims_and_stale_revisions(pool: PgPool)
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn second_claim_returns_already_running(pool: PgPool) {
insert_user(&pool, USER_A).await;
- let repo = PgScheduledActionRepo::new(pool);
+ let repo = test_repo(pool);
let created = repo
.create_action(sample_action(user_owner(USER_A), "standup"))
@@ -241,7 +287,7 @@ async fn second_claim_returns_already_running(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn claims_from_snapshots_older_than_a_pause_or_update_fail(pool: PgPool) {
insert_user(&pool, USER_A).await;
- let repo = PgScheduledActionRepo::new(pool);
+ let repo = test_repo(pool);
let polled = repo
.create_action(sample_action(user_owner(USER_A), "standup"))
.await
@@ -288,7 +334,7 @@ async fn claims_from_snapshots_older_than_a_pause_or_update_fail(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn release_is_fenced_to_its_own_execution(pool: PgPool) {
insert_user(&pool, USER_A).await;
- let repo = PgScheduledActionRepo::new(pool);
+ let repo = test_repo(pool);
let action = repo
.create_action(sample_action(user_owner(USER_A), "fenced"))
.await
@@ -312,7 +358,7 @@ async fn release_is_fenced_to_its_own_execution(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn delete_action_removes_row_from_owner_list(pool: PgPool) {
insert_user(&pool, USER_A).await;
- let repo = PgScheduledActionRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let created = repo
.create_action(sample_action(user_owner(USER_A), "standup"))
@@ -320,12 +366,12 @@ async fn delete_action_removes_row_from_owner_list(pool: PgPool) {
.expect("create should succeed");
let id = created.id.expect("create returns Some(id)");
- repo.delete_action(&id, user(USER_A))
+ repo.delete_action(&id)
.await
.expect("delete should succeed");
let listed = repo
- .get_actions(user(USER_A))
+ .get_owned_actions(&user(USER_A))
.await
.expect("list should succeed");
assert!(listed.is_empty());
@@ -334,7 +380,7 @@ async fn delete_action_removes_row_from_owner_list(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn create_action_registers_entity_row(pool: PgPool) {
insert_user(&pool, USER_A).await;
- let repo = PgScheduledActionRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let created = repo
.create_action(sample_action(user_owner(USER_A), "standup"))
@@ -361,12 +407,16 @@ async fn create_action_registers_entity_row(pool: PgPool) {
assert_eq!(row.owner_type, "user");
assert_eq!(row.owner_id, USER_A);
assert_eq!(row.deleted_at, None);
+ assert_eq!(
+ direct_grants(&pool, id).await,
+ vec![("user".to_owned(), USER_A.to_owned(), "owner".to_owned())]
+ );
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn delete_action_removes_entity_row(pool: PgPool) {
insert_user(&pool, USER_A).await;
- let repo = PgScheduledActionRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let created = repo
.create_action(sample_action(user_owner(USER_A), "standup"))
@@ -374,17 +424,22 @@ async fn delete_action_removes_entity_row(pool: PgPool) {
.expect("create should succeed");
let id = created.id.expect("create returns Some(id)");
- repo.delete_action(&id, user(USER_A))
+ repo.delete_action(&id)
.await
.expect("delete should succeed");
+ assert_eq!(scheduled_action_row_count(&pool, id).await, 0);
assert_eq!(entity_row_count(&pool, id).await, 0);
+ assert!(direct_grants(&pool, id).await.is_empty());
+ repo.delete_action(&id)
+ .await
+ .expect("deleting a missing row succeeds");
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn delete_action_succeeds_when_entity_row_is_missing(pool: PgPool) {
insert_user(&pool, USER_A).await;
- let repo = PgScheduledActionRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
let created = repo
.create_action(sample_action(user_owner(USER_A), "standup"))
@@ -397,7 +452,7 @@ async fn delete_action_succeeds_when_entity_row_is_missing(pool: PgPool) {
.await
.expect("entity row should delete");
- repo.delete_action(&id, user(USER_A))
+ repo.delete_action(&id)
.await
.expect("delete should succeed");
@@ -421,16 +476,16 @@ fn event_action() -> ScheduledAction {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn event_round_trip_and_bookkeeping_does_not_advance_configuration(pool: PgPool) {
insert_user(&pool, USER_A).await;
- let repo = PgScheduledActionRepo::new(pool);
+ let repo = test_repo(pool);
let created = repo.create_action(event_action()).await.unwrap();
let id = created.id.unwrap();
assert_eq!(id.get_version_num(), 7);
- let before = repo.get_action(&id, user(USER_A)).await.unwrap().unwrap();
+ let before = repo.get_action(&id).await.unwrap().unwrap();
assert!(matches!(before.trigger, ActionTrigger::Events { .. }));
assert_eq!(before.next_run_at, None);
assert!(before.event_activated_at.is_some());
repo.update_next_run_at(&id).await.unwrap();
- let after = repo.get_action(&id, user(USER_A)).await.unwrap().unwrap();
+ let after = repo.get_action(&id).await.unwrap().unwrap();
assert_eq!(after.updated_at, before.updated_at);
assert_eq!(after.next_run_at, None);
let token = repo
@@ -439,7 +494,7 @@ async fn event_round_trip_and_bookkeeping_does_not_advance_configuration(pool: P
.unwrap();
repo.release_action(&id, token).await.unwrap();
repo.update_last_executed(&id, Utc::now()).await.unwrap();
- let after = repo.get_action(&id, user(USER_A)).await.unwrap().unwrap();
+ let after = repo.get_action(&id).await.unwrap().unwrap();
assert_eq!(after.configuration_revision, before.configuration_revision);
assert_eq!(after.event_activated_at, before.event_activated_at);
assert_eq!(
@@ -479,27 +534,53 @@ async fn event_round_trip_and_bookkeeping_does_not_advance_configuration(pool: P
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn lookup_update_and_delete_are_owner_scoped(pool: PgPool) {
+async fn lookup_update_and_delete_are_id_scoped(pool: PgPool) {
insert_user(&pool, USER_A).await;
insert_user(&pool, USER_B).await;
- let repo = PgScheduledActionRepo::new(pool.clone());
+ let repo = test_repo(pool.clone());
for action in [sample_action(user_owner(USER_A), "cron"), event_action()] {
let created = repo.create_action(action).await.unwrap();
let id = created.id.unwrap();
- assert!(repo.get_action(&id, user(USER_B)).await.unwrap().is_none());
- let mut foreign_update = created.clone();
- foreign_update.owner = user_owner(USER_B);
- foreign_update.configuration_revision = created.configuration_revision.next().unwrap();
- assert!(repo.update_action(foreign_update).await.is_err());
- repo.delete_action(&id, user(USER_B)).await.unwrap();
- assert!(repo.get_action(&id, user(USER_A)).await.unwrap().is_some());
- assert_eq!(entity_row_count(&pool, id).await, 1);
- repo.delete_action(&id, user(USER_A)).await.unwrap();
- assert!(repo.get_action(&id, user(USER_A)).await.unwrap().is_none());
+ let loaded = repo.get_action(&id).await.unwrap().unwrap();
+ assert_eq!(loaded.owner, user_owner(USER_A));
+
+ let updated = repo
+ .update_action(ScheduledAction {
+ owner: user_owner(USER_B),
+ name: "renamed".into(),
+ configuration_revision: loaded.configuration_revision.next().unwrap(),
+ ..loaded
+ })
+ .await
+ .unwrap();
+ assert_eq!(updated.owner, user_owner(USER_A));
+ assert_eq!(updated.name, "renamed");
+
+ let stale = repo
+ .update_action(ScheduledAction {
+ name: "stale".into(),
+ configuration_revision: loaded.configuration_revision.next().unwrap(),
+ ..updated.clone()
+ })
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ stale.downcast_ref(),
+ Some(ActionPolicyError::UpdateConflict)
+ ));
+ assert_eq!(
+ repo.get_action(&id).await.unwrap().unwrap().owner,
+ user_owner(USER_A)
+ );
+
+ repo.delete_action(&id).await.unwrap();
+ assert!(repo.get_action(&id).await.unwrap().is_none());
assert_eq!(entity_row_count(&pool, id).await, 0);
+ assert!(direct_grants(&pool, id).await.is_empty());
+ repo.delete_action(&id).await.unwrap();
}
assert!(
- repo.get_action(&macro_uuid::generate_uuid_v7(), user(USER_A))
+ repo.get_action(&macro_uuid::generate_uuid_v7())
.await
.unwrap()
.is_none()
@@ -509,7 +590,7 @@ async fn lookup_update_and_delete_are_owner_scoped(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn trigger_transitions_replace_all_trigger_columns(pool: PgPool) {
insert_user(&pool, USER_A).await;
- let repo = PgScheduledActionRepo::new(pool);
+ let repo = test_repo(pool);
let cron = repo
.create_action(sample_action(user_owner(USER_A), "cron"))
.await
@@ -554,7 +635,7 @@ async fn trigger_transitions_replace_all_trigger_columns(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn polling_returns_only_enabled_unclaimed_cron_rows(pool: PgPool) {
insert_user(&pool, USER_A).await;
- let repo = PgScheduledActionRepo::new(pool);
+ let repo = test_repo(pool);
repo.create_action(event_action()).await.unwrap();
let disabled = ScheduledAction {
enabled: false,
@@ -595,12 +676,8 @@ async fn deployed_cron_insert_remains_valid(pool: PgPool) {
assert_eq!(row.configuration_revision, 1);
assert_eq!(row.event_filters, None);
assert_eq!(row.event_activated_at, None);
- let repo = PgScheduledActionRepo::new(pool);
- let action = repo
- .get_action(&row.id, user(USER_A))
- .await
- .unwrap()
- .unwrap();
+ let repo = test_repo(pool);
+ let action = repo.get_action(&row.id).await.unwrap().unwrap();
assert!(matches!(action.trigger, ActionTrigger::Cron { .. }));
assert!(action.next_run_at.is_some());
}
@@ -772,3 +849,141 @@ async fn database_rejects_invalid_trigger_shapes(pool: PgPool) {
);
}
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_actions_by_ids_returns_another_owners_row(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ insert_user(&pool, USER_B).await;
+ let repo = test_repo(pool);
+ let own = repo
+ .create_action(sample_action(user_owner(USER_A), "own"))
+ .await
+ .unwrap();
+ let other = repo
+ .create_action(sample_action(user_owner(USER_B), "other"))
+ .await
+ .unwrap();
+
+ let rows = repo.get_actions_by_ids(&[other.id.unwrap()]).await.unwrap();
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].id, other.id);
+ assert_eq!(rows[0].owner, user_owner(USER_B));
+
+ let rows = repo
+ .get_actions_by_ids(&[own.id.unwrap(), other.id.unwrap()])
+ .await
+ .unwrap();
+ assert_eq!(rows.len(), 2);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn bot_owner_create_writes_bot_and_sponsor_grants(pool: PgPool) {
+ let sponsor = user_owner(USER_A);
+ let repo = PgScheduledActionRepo::new(
+ pool.clone(),
+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(SponsoredBy(sponsor))),
+ );
+ let created = repo
+ .create_action(sample_action(
+ Owner::Bot(bot_id::BotId::TEST_A),
+ "bot routine",
+ ))
+ .await
+ .unwrap();
+ let bot_source = bot_id::BotId::TEST_A.into_storage_id().to_string();
+ assert_eq!(
+ direct_grants(&pool, created.id.unwrap()).await,
+ vec![
+ ("bot".to_owned(), bot_source, "owner".to_owned()),
+ ("user".to_owned(), USER_A.to_owned(), "owner".to_owned()),
+ ]
+ );
+}
+
+const BACKFILL_SQL: &str = include_str!(
+ "../../../../../crates/macro_db_client/migrations/20260929195914_backfill_scheduled_action_owner_grants.sql"
+);
+
+async fn insert_legacy_action(pool: &PgPool, id: Uuid, owner: &str) {
+ sqlx::query!(
+ r#"
+ INSERT INTO scheduled_action
+ (id, owner, name, schedule, kind, timezone, task, next_run_at, enabled)
+ VALUES ($1, $2, 'legacy', $3, 'Agent', 'UTC', $4, $5, true)
+ "#,
+ id,
+ owner,
+ DAILY_9AM,
+ json!({}),
+ Utc::now(),
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+async fn run_backfill(pool: &PgPool) -> Result<(), sqlx::Error> {
+ sqlx::raw_sql(BACKFILL_SQL).execute(pool).await?;
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn backfill_owner_grants_is_idempotent_and_fails_closed(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ let legacy_id = macro_uuid::generate_uuid_v7();
+ insert_legacy_action(&pool, legacy_id, USER_A).await;
+ sqlx::query!(
+ r#"
+ INSERT INTO entity (id, entity_type, owner_type, owner_id)
+ VALUES ($1, 'scheduled_action', 'user', $2)
+ "#,
+ legacy_id,
+ USER_A,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(direct_grants(&pool, legacy_id).await.is_empty());
+
+ run_backfill(&pool).await.unwrap();
+ assert_eq!(
+ direct_grants(&pool, legacy_id).await,
+ vec![("user".to_owned(), USER_A.to_owned(), "owner".to_owned())]
+ );
+
+ run_backfill(&pool).await.unwrap();
+ assert_eq!(entity_row_count(&pool, legacy_id).await, 1);
+ assert_eq!(direct_grants(&pool, legacy_id).await.len(), 1);
+
+ sqlx::query!(
+ r#"
+ UPDATE entity_access
+ SET access_level = 'view'
+ WHERE entity_id = $1 AND entity_type = 'scheduled_action'
+ "#,
+ legacy_id,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ run_backfill(&pool).await.unwrap();
+ assert_eq!(
+ direct_grants(&pool, legacy_id).await,
+ vec![("user".to_owned(), USER_A.to_owned(), "owner".to_owned())]
+ );
+
+ let conflict_id = macro_uuid::generate_uuid_v7();
+ insert_legacy_action(&pool, conflict_id, USER_A).await;
+ sqlx::query!(
+ r#"
+ INSERT INTO entity (id, entity_type, owner_type, owner_id)
+ VALUES ($1, 'scheduled_action', 'user', 'macro|[email protected]')
+ "#,
+ conflict_id,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(run_backfill(&pool).await.is_err());
+ assert!(direct_grants(&pool, conflict_id).await.is_empty());
+}
diff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rs
index ea109cf7ef..ee299a8066 100644
--- a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rs
+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rs
@@ -2,8 +2,20 @@ use super::*;
use crate::domain::models::InProgressExecution;
use crate::domain::ports::{ScheduledActionExecutor, ScheduledActionService};
use crate::domain::service::ScheduledActionServiceImpl;
+use entity_access::domain::{models::AccessError, ports::ScheduledActionGrants};
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use std::sync::Arc;
+struct UnusedGrants;
+impl ScheduledActionGrants for UnusedGrants {
+ async fn accessible_scheduled_action_ids(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> std::result::Result<Vec<macro_uuid::Uuid>, AccessError> {
+ Ok(Vec::new())
+ }
+}
+
struct NeverExecutor;
impl ScheduledActionExecutor for NeverExecutor {
async fn execute_action(&self, _: ScheduledAction) -> Result<InProgressExecution> {
@@ -16,7 +28,7 @@ impl ScheduledActionExecutor for NeverExecutor {
async fn deletes_user_actions_without_cascade_and_preserves_other_users(pool: PgPool) {
insert_user(&pool, USER_A).await;
insert_user(&pool, USER_B).await;
- let repo = Arc::new(PgScheduledActionRepo::new(pool.clone()));
+ let repo = Arc::new(super::test_repo(pool.clone()));
let enabled = repo
.create_action(sample_action(user_owner(USER_A), "enabled"))
.await
@@ -37,11 +49,21 @@ async fn deletes_user_actions_without_cascade_and_preserves_other_users(pool: Pg
.await
.unwrap();
let (tx, _rx) = tokio::sync::mpsc::channel(10);
- let service = ScheduledActionServiceImpl::new(repo.clone(), Arc::new(NeverExecutor), tx);
+ let service = ScheduledActionServiceImpl::new(
+ repo.clone(),
+ Arc::new(NeverExecutor),
+ tx,
+ Arc::new(UnusedGrants),
+ );
service.delete_user_actions(user(USER_A)).await.unwrap();
service.delete_user_actions(user(USER_A)).await.unwrap();
- assert!(repo.get_actions(user(USER_A)).await.unwrap().is_empty());
+ assert!(
+ repo.get_owned_actions(&user(USER_A))
+ .await
+ .unwrap()
+ .is_empty()
+ );
for id in [enabled.id.unwrap(), disabled.id.unwrap(), event.id.unwrap()] {
assert_eq!(scheduled_action_row_count(&pool, id).await, 0);
assert_eq!(entity_row_count(&pool, id).await, 0);
diff --git a/services/scheduled_action/tests/event_routines.rs b/services/scheduled_action/tests/event_routines.rs
index cf365eae16..488bc52a2c 100644
--- a/services/scheduled_action/tests/event_routines.rs
+++ b/services/scheduled_action/tests/event_routines.rs
@@ -13,10 +13,15 @@ use axum::{
body::{Body, to_bytes},
http::{Request, StatusCode, header},
};
+use bots::outbound::pg_bots_repo::PgBotsRepo;
use chrono::Utc;
use entity_access::domain::models::{
AccessLevel, Entity, EntityAccessReceipt, EntityPermission, EntityType,
};
+use entity_access::domain::service::EntityAccessServiceImpl;
+use entity_access::outbound::PgAccessRepository;
+use entity_registry::OwnerGrantPolicy;
+use entity_registry_db_utils::OwnedEntityRegistrar;
use macro_authorization::{
InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
MacroAuthorizationState,
@@ -185,14 +190,15 @@ impl ScheduledActionLiveUpdate for NoLiveUpdates {
async fn publish_update(&self, _: ScheduledActionUpdate) {}
}
-type Executor = InProcessExecutor<PgScheduledActionRepo, NoLiveUpdates, FakeRunner>;
+type ActionRepo = PgScheduledActionRepo<PgBotsRepo>;
+type Executor = InProcessExecutor<ActionRepo, NoLiveUpdates, FakeRunner>;
type Admission = EventAdmissionService<PgEventRunRepo, FakeAccess>;
type Dispatch = EventDispatchService<PgEventRunRepo, FakeAccess, Executor>;
struct Harness {
pool: PgPool,
app: Router,
- actions: Arc<PgScheduledActionRepo>,
+ actions: Arc<ActionRepo>,
runs: Arc<PgEventRunRepo>,
runner: Arc<FakeRunner>,
executor: Arc<Executor>,
@@ -215,7 +221,10 @@ impl Harness {
.execute(&pool)
.await
.unwrap();
- let actions = Arc::new(PgScheduledActionRepo::new(pool.clone()));
+ let actions = Arc::new(PgScheduledActionRepo::new(
+ pool.clone(),
+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone()))),
+ ));
let runs = Arc::new(PgEventRunRepo::new(pool.clone()));
let runner = Arc::new(runner);
let tracker = TaskTracker::new();
@@ -227,10 +236,15 @@ impl Harness {
CancellationToken::new(),
));
let (tx, notifications) = mpsc::channel(100);
- let service = ScheduledActionServiceImpl::new(actions.clone(), executor.clone(), tx)
- .with_event_management_enabled(true);
+ let access = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ pool.clone(),
+ )));
+ let service =
+ ScheduledActionServiceImpl::new(actions.clone(), executor.clone(), tx, access.clone())
+ .with_event_management_enabled(true);
let app = scheduled_action_router(ScheduledActionRouterState {
service: Arc::new(service),
+ access_service: access,
authorization_state: MacroAuthorizationState::new(Arc::new(FakeAuth)),
});
Self {
@@ -449,13 +463,7 @@ async fn legacy_cron_and_canonical_events_share_crud_and_manual_execution(pool:
request(&h.app, "DELETE", &url, Value::Null).await.0,
StatusCode::NO_CONTENT
);
- assert!(
- h.actions
- .get_action(&id, MacroUserIdStr::parse_from_str(USER).unwrap())
- .await
- .unwrap()
- .is_none()
- );
+ assert!(h.actions.get_action(&id).await.unwrap().is_none());
}
assert_eq!(h.count().await, 0);
let calls = h.runner.calls.lock().unwrap();
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index 7f13719bdd..c3dc883e3d 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -4299,7 +4299,7 @@ type GraphqlRepliedToDocumentCommentThreadMetadata {
}
"""
-An AI routine owned by the authenticated user.
+An AI routine the authenticated user can access.
"""
type GraphqlScheduledAction {
"""
@@ -6689,7 +6689,7 @@ type GraphqlUser {
"""
taskInitiativeReferences(taskIds: [ID!]!): [TaskInitiativeReference!]!
"""
- AI routines owned by the authenticated user.
+ AI routines the authenticated user can access.
"""
scheduledActions: [GraphqlScheduledAction!]!
"""