Skip to content

TaskView is a self-hosted project and task management platform focused on clarity, ownership, and control. TaskView is built for teams that want a transparent, self-hosted alternative to SaaS task managers.

fix: execute automation as the project owner.

Nikolai Gimanf8ba2afc2d00
diff --git a/api/src/tv-modules/automations/AutomationActorFactory.ts b/api/src/tv-modules/automations/AutomationActorFactory.ts
index 6b026f7..95c3a52 100644
--- a/api/src/tv-modules/automations/AutomationActorFactory.ts
+++ b/api/src/tv-modules/automations/AutomationActorFactory.ts
@@ -1,7 +1,16 @@
import { AppUser } from '../../core/AppUser';
+import { GoalsRepository } from '../goals/GoalsRepository';
export class AutomationActorFactory {
- async forUser(userId: number): Promise<AppUser | null> {
+ private readonly goalsRepository = new GoalsRepository();
+
+ async forGoalOwner(goalId: number): Promise<AppUser | null> {
+ const goal = await this.goalsRepository.findGoalById(goalId);
+ if (!goal) return null;
+ return this.forUser(goal.owner);
+ }
+
+ private async forUser(userId: number): Promise<AppUser | null> {
const user = await new AppUser().authManager.repository.fetchUserById(userId);
if (!user || user.block !== 0) return null;
diff --git a/api/src/tv-modules/automations/AutomationEngine.ts b/api/src/tv-modules/automations/AutomationEngine.ts
index c052a76..34a0d78 100644
--- a/api/src/tv-modules/automations/AutomationEngine.ts
+++ b/api/src/tv-modules/automations/AutomationEngine.ts
@@ -122,15 +122,15 @@ export class AutomationEngine {
const task = await this.tasksRepository.fetchTaskByIdNew(job.taskId);
if (!task || task.goalId !== rule.goalId) return;
- const actor = await this.actorFor({ chain: args.chain, userId: rule.creatorId });
+ const actor = await this.actorFor({ chain: args.chain, goalId: rule.goalId });
if (!actor) {
- $logger.info(`[Automations] rule=${rule.id} skipped: creator ${rule.creatorId} is unavailable`);
+ $logger.warn(`[Automations] rule=${rule.id} skipped: the owner of goal=${rule.goalId} is unavailable`);
return;
}
const allowed = await AutomationPermissions.canRun({ actor, goalId: rule.goalId, action });
if (!allowed) {
- $logger.info(`[Automations] rule=${rule.id} skipped: creator ${rule.creatorId} lacks permissions`);
+ $logger.warn(`[Automations] rule=${rule.id} skipped: the owner of goal=${rule.goalId} lacks permissions`);
return;
}
@@ -141,10 +141,10 @@ export class AutomationEngine {
}
private actorFor(args: AutomationActorForArgs): Promise<AppUser | null> {
- let actor = args.chain.actors.get(args.userId);
+ let actor = args.chain.actors.get(args.goalId);
if (!actor) {
- actor = this.actorFactory.forUser(args.userId);
- args.chain.actors.set(args.userId, actor);
+ actor = this.actorFactory.forGoalOwner(args.goalId);
+ args.chain.actors.set(args.goalId, actor);
}
return actor;
}
diff --git a/api/src/tv-modules/automations/__tests__/AutomationEngine.spec.ts b/api/src/tv-modules/automations/__tests__/AutomationEngine.spec.ts
index 86ff00a..9891719 100644
--- a/api/src/tv-modules/automations/__tests__/AutomationEngine.spec.ts
+++ b/api/src/tv-modules/automations/__tests__/AutomationEngine.spec.ts
@@ -120,7 +120,7 @@ function setup(rules: AutomationRuleRow[], fetched: Partial<TasksSchemaTypeForSe
dataSources: {},
} as unknown as AutomationModuleDefinition;
- const forUser = vi.fn(async () => actor);
+ const forGoalOwner = vi.fn(async () => actor);
const enqueue = vi.fn(async (job: AutomationRunJob) => {
jobs.push(job);
});
@@ -133,7 +133,7 @@ function setup(rules: AutomationRuleRow[], fetched: Partial<TasksSchemaTypeForSe
);
const fetchTaskByIdNew = vi.fn(async (id: number) => (fetched === null ? null : task({ id, ...fetched })));
vi.mocked(TasksRepository).mockImplementation(() => ({ fetchTaskByIdNew }) as any);
- vi.mocked(AutomationActorFactory).mockImplementation(() => ({ forUser }) as any);
+ vi.mocked(AutomationActorFactory).mockImplementation(() => ({ forGoalOwner }) as any);
vi.mocked(AutomationPermissions.canRun).mockResolvedValue(true);
engine = new AutomationEngine({ catalog: new AutomationCatalog([module]), queue: { enqueue } as unknown as AutomationRunQueue });
@@ -149,7 +149,7 @@ function setup(rules: AutomationRuleRow[], fetched: Partial<TasksSchemaTypeForSe
await drain();
}
- return { engine, executed, jobs, enqueue, forUser, drain, emit };
+ return { engine, executed, jobs, enqueue, forGoalOwner, drain, emit };
}
describe('AutomationEngine', () => {
@@ -212,7 +212,7 @@ describe('AutomationEngine', () => {
expect(executed).toEqual([]);
});
- it('skips the rule when its creator lost the permissions', async () => {
+ it('skips the rule when the project owner lacks the permissions', async () => {
const { executed, emit } = setup([rule({ actionParams: { n: 42 } })]);
vi.mocked(AutomationPermissions.canRun).mockResolvedValue(false);
await emit({ ping: true });
@@ -254,15 +254,23 @@ describe('AutomationEngine', () => {
expect(executed).toEqual([42, 42]);
});
- it('loads every creator once per job', async () => {
- const { executed, forUser, emit } = setup([
+ it('runs every rule as the project owner, loaded once per job, whoever authored it', async () => {
+ const { executed, forGoalOwner, emit } = setup([
rule({ id: 1, actionParams: { n: 1 } }),
rule({ id: 2, actionParams: { n: 2 } }),
rule({ id: 3, creatorId: 8, actionParams: { n: 3 } }),
]);
await emit({ ping: true });
expect(executed).toEqual([1, 2, 3]);
- expect(forUser.mock.calls).toEqual([[CREATOR_ID], [8]]);
+ expect(forGoalOwner.mock.calls).toEqual([[GOAL_ID]]);
+ });
+
+ it('skips the rule when the project owner is unavailable', async () => {
+ const { executed, forGoalOwner, emit } = setup([rule({ actionParams: { n: 42 } })]);
+ forGoalOwner.mockResolvedValue(null as any);
+ await emit({ ping: true });
+ expect(executed).toEqual([]);
+ expect($logger.warn).toHaveBeenCalledWith(expect.stringContaining('owner of goal=10 is unavailable'));
});
it('logs an action that failed without retrying the job', async () => {
diff --git a/api/src/tv-modules/automations/catalog/AutomationCatalog.ts b/api/src/tv-modules/automations/catalog/AutomationCatalog.ts
index 3d571ad..e12deae 100644
--- a/api/src/tv-modules/automations/catalog/AutomationCatalog.ts
+++ b/api/src/tv-modules/automations/catalog/AutomationCatalog.ts
@@ -47,7 +47,7 @@ export class AutomationCatalog {
modules: this.modules.map((module) => ({
name: module.name,
events: module.events.map((event) => ({ name: event.name, params: event.params })),
- actions: module.actions.map((action) => ({ name: action.name, params: action.params })),
+ actions: module.actions.map((action) => ({ name: action.name, params: action.params, requiredPermissions: action.requiredPermissions })),
})),
};
}
diff --git a/api/src/tv-modules/automations/types.ts b/api/src/tv-modules/automations/types.ts
index 92808b7..4981a4c 100644
--- a/api/src/tv-modules/automations/types.ts
+++ b/api/src/tv-modules/automations/types.ts
@@ -137,7 +137,7 @@ export type AutomationCatalogForClient = {
modules: {
name: AutomationModuleName;
events: { name: string; params: AutomationCatalogParamForClient[] }[];
- actions: { name: string; params: AutomationCatalogParamForClient[] }[];
+ actions: { name: string; params: AutomationCatalogParamForClient[]; requiredPermissions: GoalPermissionType[] }[];
}[];
};
@@ -192,7 +192,7 @@ export type AutomationRuleMatchArgs = {
export type AutomationActorForArgs = {
chain: AutomationChain;
- userId: number;
+ goalId: number;
};
export type AutomationErrorCode = 'not_found' | 'forbidden' | 'invalid' | 'cycle' | 'limit_reached';
diff --git a/taskview-packages/taskview-api/src/api/__tests__/automations.access.test.ts b/taskview-packages/taskview-api/src/api/__tests__/automations.access.test.ts
index e2db654..c44bdba 100644
--- a/taskview-packages/taskview-api/src/api/__tests__/automations.access.test.ts
+++ b/taskview-packages/taskview-api/src/api/__tests__/automations.access.test.ts
@@ -6,10 +6,6 @@ import { initApi } from './init-api'
import { createAutomationsProject, createTask, expectApiError, shareGoalWith, waitFor } from './automations-test-helpers'
import type { AutomationsTestProject } from './automations-test-helpers.types'
-/**
- * Automation rules act on behalf of their author, so every permission a rule
- * relies on is checked both when the rule is saved and every time it runs.
- */
describe('Automations permission boundaries', () => {
let ownerApi: TvApi
let memberApi: TvApi
@@ -104,7 +100,7 @@ describe('Automations permission boundaries', () => {
expect(allowed.enabled).toBe(true)
})
- it('stops running the rules of an author who lost the right to manage automations', async () => {
+ it('keeps running the rules of an author who lost the right to manage automations', async () => {
const p = await project()
const { roleId } = await share(p.goalId, [TvPermissions.AUTOMATION_CAN_MANAGE, TvPermissions.TASK_CAN_EDIT_TAGS])
await memberApi.automations.createRule(createdAddsTag(p, p.tagBId))
@@ -119,11 +115,17 @@ describe('Automations permission boundaries', () => {
expect(revoked?.add).toBe(false)
const after = await createTask({ api: ownerApi, goalId: p.goalId })
- expect(await waitFor(async () => (await taskTags(after)).includes(p.tagAId))).toBe(true)
- expect(await taskTags(after)).not.toContain(p.tagBId)
+ expect(await waitFor(async () => {
+ const tags = await taskTags(after)
+ return tags.includes(p.tagAId) && tags.includes(p.tagBId)
+ })).toBe(true)
+ await expectApiError({
+ request: memberApi.automations.createRule(createdAddsTag(p, p.tagAId)),
+ status: 403,
+ })
})
- it('makes the editor the author, so a rule never runs with someone else\'s rights', async () => {
+ it('checks the editor\'s permissions and records them as the author', async () => {
const p = await project()
const rule = await ownerApi.automations.createRule(createdAddsTag(p, p.tagAId))
await share(p.goalId, [TvPermissions.AUTOMATION_CAN_MANAGE, TvPermissions.TASK_CAN_EDIT_TAGS])
diff --git a/taskview-packages/taskview-api/src/api/__tests__/automations.test.ts b/taskview-packages/taskview-api/src/api/__tests__/automations.test.ts
index be443e3..5672944 100644
--- a/taskview-packages/taskview-api/src/api/__tests__/automations.test.ts
+++ b/taskview-packages/taskview-api/src/api/__tests__/automations.test.ts
@@ -66,18 +66,20 @@ describe('Automations', () => {
{ name: 'task.movedToColumn', params: [{ key: 'statusId', source: 'kanban.statuses' }] },
])
expect(byName.get('kanban')?.actions).toEqual([
- { name: 'change.status', params: [{ key: 'statusId', source: 'kanban.statuses' }] },
+ { name: 'change.status', params: [{ key: 'statusId', source: 'kanban.statuses' }], requiredPermissions: ['kanban_can_manage'] },
])
expect(byName.get('tags')?.events).toEqual([
{ name: 'tag.addedToTask', params: [{ key: 'tagId', source: 'tags.goalTags' }] },
{ name: 'tag.removedFromTask', params: [{ key: 'tagId', source: 'tags.goalTags' }] },
])
- expect(byName.get('tags')?.actions).toEqual([{ name: 'add.tag', params: [{ key: 'tagId', source: 'tags.goalTags' }] }])
+ expect(byName.get('tags')?.actions).toEqual([
+ { name: 'add.tag', params: [{ key: 'tagId', source: 'tags.goalTags' }], requiredPermissions: ['task_can_edit_tags'] },
+ ])
expect(byName.get('lists')?.events).toEqual([
{ name: 'task.addedToList', params: [{ key: 'goalListId', source: 'lists.goalLists' }] },
])
expect(byName.get('lists')?.actions).toEqual([
- { name: 'move.toList', params: [{ key: 'goalListId', source: 'lists.goalLists' }] },
+ { name: 'move.toList', params: [{ key: 'goalListId', source: 'lists.goalLists' }], requiredPermissions: ['component_can_watch_content'] },
])
})
diff --git a/taskview-packages/taskview-api/src/api/automations.types.ts b/taskview-packages/taskview-api/src/api/automations.types.ts
index b538804..2275118 100644
--- a/taskview-packages/taskview-api/src/api/automations.types.ts
+++ b/taskview-packages/taskview-api/src/api/automations.types.ts
@@ -17,6 +17,7 @@ export type AutomationCatalogEvent = {
export type AutomationCatalogAction = {
name: string;
params: AutomationParamDefinition[];
+ requiredPermissions: string[];
};
export type AutomationCatalogModule = {
diff --git a/web/src/components/features/automations/parts/AutomationRuleStepFields.vue b/web/src/components/features/automations/parts/AutomationRuleStepFields.vue
index 0405070..cdadda5 100644
--- a/web/src/components/features/automations/parts/AutomationRuleStepFields.vue
+++ b/web/src/components/features/automations/parts/AutomationRuleStepFields.vue
@@ -48,9 +48,10 @@
<script setup lang="ts">
import { computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
-import type { AutomationCatalogModule, AutomationParams } from 'taskview-api'
+import type { AutomationCatalogAction, AutomationCatalogEvent, AutomationCatalogModule, AutomationParams, GoalPermissions } from 'taskview-api'
import AutomationParamSelect from './AutomationParamSelect.vue'
import { useAutomationLabels } from '@/composables/useAutomationLabels'
+import { useGoalsStore } from '@/stores/goals.store'
import type { AutomationSelectItem, AutomationSetParamArgs } from '@/types/automations.types'
const props = defineProps<{
@@ -66,6 +67,7 @@ const params = defineModel<AutomationParams>('params', { required: true })
const { t } = useI18n()
const { moduleLabel, eventLabel, actionLabel } = useAutomationLabels()
+const goalsStore = useGoalsStore()
const itemsOf = (module: AutomationCatalogModule) => (props.kind === 'event' ? module.events : module.actions)
@@ -77,11 +79,22 @@ const moduleItems = computed<AutomationSelectItem[]>(() =>
const selectedModule = computed(() => props.modules.find((module) => module.name === moduleName.value) ?? null)
+function isAvailable(item: AutomationCatalogEvent | AutomationCatalogAction): boolean {
+ if (!('requiredPermissions' in item)) return true
+ const permissions = goalsStore.goalMap.get(props.goalId)?.permissions
+ return item.requiredPermissions.every((permission) => !!permissions?.[permission as keyof GoalPermissions])
+}
+
const stepItems = computed<AutomationSelectItem[]>(() =>
- (selectedModule.value ? itemsOf(selectedModule.value) : []).map((item) => ({
- label: props.kind === 'event' ? eventLabel(item.name) : actionLabel(item.name),
- value: item.name,
- })),
+ (selectedModule.value ? itemsOf(selectedModule.value) : []).map((item) => {
+ const available = isAvailable(item)
+ return {
+ label: props.kind === 'event' ? eventLabel(item.name) : actionLabel(item.name),
+ value: item.name,
+ disabled: !available,
+ description: available ? undefined : t('automations.actionUnavailable'),
+ }
+ }),
)
const selectedItem = computed(() =>
diff --git a/web/src/locales/de.ts b/web/src/locales/de.ts
index 77e817e..37ae956 100644
--- a/web/src/locales/de.ts
+++ b/web/src/locales/de.ts
@@ -1564,6 +1564,7 @@ export default {
enabled: 'Aktiv',
runsAsHint: 'Aktionen laufen mit den Rechten der Person, die die Regel zuletzt gespeichert hat.',
unavailableOption: 'gelöschter Wert',
+ actionUnavailable: 'Ihnen fehlen die Rechte dafür in diesem Projekt',
broken: 'Funktioniert nicht',
brokenHint: 'Eine ausgewählte Spalte, ein Tag oder eine Liste wurde gelöscht, daher wurde die Regel deaktiviert. Bearbeiten Sie sie und wählen Sie einen neuen Wert.',
fields: {
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index f387f76..f331647 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -1578,6 +1578,7 @@ export default {
enabled: 'Enabled',
runsAsHint: 'Actions run with the permissions of the person who last saved the rule.',
unavailableOption: 'deleted value',
+ actionUnavailable: 'You lack the permissions for this in this project',
broken: 'Not working',
brokenHint: 'A selected column, tag or list was deleted, so the rule was turned off. Edit it and pick a new value.',
fields: {
diff --git a/web/src/locales/es.ts b/web/src/locales/es.ts
index c87bb73..4798675 100644
--- a/web/src/locales/es.ts
+++ b/web/src/locales/es.ts
@@ -1564,6 +1564,7 @@ export default {
enabled: 'Activada',
runsAsHint: 'Las acciones se ejecutan con los permisos de la persona que guardó la regla por última vez.',
unavailableOption: 'valor eliminado',
+ actionUnavailable: 'No tienes permisos para esto en este proyecto',
broken: 'No funciona',
brokenHint: 'Se eliminó una columna, etiqueta o lista seleccionada, por lo que la regla se desactivó. Edítala y elige un nuevo valor.',
fields: {
diff --git a/web/src/locales/pt-br.ts b/web/src/locales/pt-br.ts
index 040a73a..ec72ca5 100644
--- a/web/src/locales/pt-br.ts
+++ b/web/src/locales/pt-br.ts
@@ -1575,6 +1575,7 @@ export default {
enabled: 'Ativada',
runsAsHint: 'As ações são executadas com as permissões de quem salvou a regra por último.',
unavailableOption: 'valor excluído',
+ actionUnavailable: 'Você não tem permissão para isso neste projeto',
broken: 'Não funciona',
brokenHint: 'Uma coluna, tag ou lista selecionada foi excluída, então a regra foi desativada. Edite-a e escolha um novo valor.',
fields: {
diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.ts
index cba77a0..8369d5f 100644
--- a/web/src/locales/ru.ts
+++ b/web/src/locales/ru.ts
@@ -1513,6 +1513,7 @@ export default {
enabled: 'Включено',
runsAsHint: 'Действия выполняются с правами того, кто последним сохранил правило.',
unavailableOption: 'удалённое значение',
+ actionUnavailable: 'Нет прав на это действие в проекте',
broken: 'Не работает',
brokenHint: 'Выбранная колонка, тег или список удалены, поэтому правило выключено. Отредактируйте его и выберите новое значение.',
fields: {
diff --git a/web/src/types/automations.types.ts b/web/src/types/automations.types.ts
index a0f1835..8bb0aec 100644
--- a/web/src/types/automations.types.ts
+++ b/web/src/types/automations.types.ts
@@ -71,4 +71,6 @@ export type AutomationStepDescription = {
export type AutomationSelectItem = {
label: string
value: string
+ disabled?: boolean
+ description?: string
}