Remove hasTemplateEntityRefs and only keep hasCreatedBy
Signed-off-by: Kashish Mittal <kmittal@redhat.com>
This commit is contained in:
@@ -6,4 +6,7 @@
|
||||
'@backstage/plugin-scaffolder': minor
|
||||
---
|
||||
|
||||
BREAKING : Added two new scaffolder rules for `scaffolder.task.read` and `scaffolder.task.cancel` to allow for conditional permission policies such as restricting access to tasks and task events based on creators (`hasCreatedBy`) and granting template owners visibility into all runs of their templates (`hasTemplateEntityRefs`).
|
||||
BREAKING :
|
||||
|
||||
- Converted `scaffolder.task.read` and `scaffolder.task.cancel` into Resource Permissions.
|
||||
- Added a new scaffolder rule `hasCreatedBy` for `scaffolder.task.read` and `scaffolder.task.cancel` to allow for conditional permission policies such as restricting access to tasks and task events based on task creators.
|
||||
|
||||
@@ -176,7 +176,7 @@ class ExamplePermissionPolicy implements PermissionPolicy {
|
||||
|
||||
### Authorizing scaffolder tasks
|
||||
|
||||
The scaffolder plugin also exposes permissions that can restrict access to tasks, task logs, task creation, and task cancellation. This can be useful if you want to control who has access to these areas of the scaffolder. You can configure policies to restrict access to tasks to only their creators, while also granting specific users the permission to view all tasks. Additionally, template owners can be granted permissions to view all runs of their templates.
|
||||
The scaffolder plugin also exposes permissions that can restrict access to tasks, task logs, task creation, and task cancellation. This can be useful if you want to control who has access to these areas of the scaffolder. You can configure policies to restrict access to tasks to only their creators, while also granting specific users the permission to view all tasks.
|
||||
|
||||
The following is a simple example of how to do this:
|
||||
|
||||
@@ -201,35 +201,9 @@ import {
|
||||
createScaffolderTaskConditionalDecision,
|
||||
scaffolderTaskConditions,
|
||||
} from '@backstage/plugin-scaffolder-backend/alpha';
|
||||
import { CatalogClient } from '@backstage/catalog-client';
|
||||
/* highlight-add-end */
|
||||
|
||||
class ExamplePermissionPolicy implements PermissionPolicy {
|
||||
private readonly catalogClient: CatalogClient;
|
||||
|
||||
constructor(catalogClient: CatalogClient) {
|
||||
this.catalogClient = catalogClient;
|
||||
}
|
||||
|
||||
// Fetches all templates owned by the user from the catalog API.
|
||||
async getUserOwnedTemplates(userRef: string): Promise<string[]> {
|
||||
if (!userRef) return [];
|
||||
|
||||
const response = await this.catalogClient.getEntities({
|
||||
filter: {
|
||||
kind: ['Template'],
|
||||
'relations.ownedBy': [userRef],
|
||||
},
|
||||
});
|
||||
|
||||
return response.items.map(
|
||||
item =>
|
||||
`${item.kind.toLocaleLowerCase()}:${item.metadata.namespace}/${
|
||||
item.metadata.name
|
||||
}`,
|
||||
);
|
||||
}
|
||||
|
||||
async handle(
|
||||
request: PolicyQuery,
|
||||
user?: PolicyQueryUser,
|
||||
@@ -243,24 +217,13 @@ class ExamplePermissionPolicy implements PermissionPolicy {
|
||||
};
|
||||
}
|
||||
|
||||
// Retrieve templates that the user owns
|
||||
const userOwnedTemplates = await this.getUserOwnedTemplates(
|
||||
user?.info.userEntityRef || '',
|
||||
// Allow users to read tasks they created
|
||||
return createScaffolderTaskConditionalDecision(
|
||||
request.permission,
|
||||
scaffolderTaskConditions.hasCreatedBy({
|
||||
createdBy: user?.info.userEntityRef ? [user?.info.userEntityRef] : [],
|
||||
}),
|
||||
);
|
||||
|
||||
// Allow users to read tasks they created or task runs of templates they own
|
||||
return createScaffolderTaskConditionalDecision(request.permission, {
|
||||
anyOf: [
|
||||
scaffolderTaskConditions.hasCreatedBy({
|
||||
createdBy: user?.info.userEntityRef
|
||||
? [user?.info.userEntityRef]
|
||||
: [],
|
||||
}),
|
||||
scaffolderTaskConditions.hasTemplateEntityRefs({
|
||||
templateEntityRefs: userOwnedTemplates,
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
if (isPermission(request.permission, taskCreatePermission)) {
|
||||
@@ -311,7 +274,6 @@ class ExamplePermissionPolicy implements PermissionPolicy {
|
||||
In the provided example permission policy, we only grant the user `bob` permissions to perform/access the following actions/resources:
|
||||
|
||||
- Read scaffolder tasks and their associated events/logs for tasks created by `bob`.
|
||||
- Read scaffolder task runs of templates owned by `bob`
|
||||
- Cancel ongoing scaffolder tasks created by `bob`.
|
||||
- Trigger software templates, which effectively creates new scaffolder tasks.
|
||||
|
||||
@@ -324,7 +286,6 @@ On the other hand, the user `alice` is granted:
|
||||
All other users are granted permissions to perform/access the following actions/resources:
|
||||
|
||||
- Read scaffolder tasks and their associated events/logs for tasks created by the user.
|
||||
- Read scaffolder task runs of the templates owned by the user
|
||||
|
||||
Although the rules exported by the scaffolder are simple, combining them can help you achieve more complex use cases.
|
||||
|
||||
|
||||
@@ -97,17 +97,6 @@ export const scaffolderTaskConditions: Conditions<{
|
||||
createdBy: string[];
|
||||
}
|
||||
>;
|
||||
hasTemplateEntityRefs: PermissionRule<
|
||||
SerializedTask,
|
||||
{
|
||||
property: TaskFilter['property'];
|
||||
values: any;
|
||||
},
|
||||
'scaffolder-task',
|
||||
{
|
||||
templateEntityRefs: string[];
|
||||
}
|
||||
>;
|
||||
}>;
|
||||
|
||||
// @alpha
|
||||
|
||||
@@ -501,6 +501,7 @@ export interface TaskStore {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
};
|
||||
permissionFilters?: PermissionCriteria<TaskFilters>;
|
||||
order?: {
|
||||
order: 'asc' | 'desc';
|
||||
field: string;
|
||||
|
||||
@@ -237,66 +237,51 @@ describe('DatabaseTaskStore', () => {
|
||||
const { store } = await createStore();
|
||||
|
||||
await store.createTask({
|
||||
spec: {
|
||||
templateInfo: { entityRef: 'template:default/three' },
|
||||
} as TaskSpec,
|
||||
spec: {} as TaskSpec,
|
||||
createdBy: 'user:default/one',
|
||||
});
|
||||
|
||||
await store.createTask({
|
||||
spec: {
|
||||
templateInfo: { entityRef: 'template:default/four' },
|
||||
} as TaskSpec,
|
||||
spec: {} as TaskSpec,
|
||||
createdBy: 'user:default/two',
|
||||
});
|
||||
|
||||
await store.createTask({
|
||||
spec: {
|
||||
templateInfo: { entityRef: 'template:default/one' },
|
||||
} as TaskSpec,
|
||||
spec: {} as TaskSpec,
|
||||
createdBy: 'user:default/three',
|
||||
});
|
||||
|
||||
await store.createTask({
|
||||
spec: {
|
||||
templateInfo: { entityRef: 'template:default/two' },
|
||||
} as TaskSpec,
|
||||
createdBy: 'user:default/three',
|
||||
spec: {} as TaskSpec,
|
||||
createdBy: 'user:default/one',
|
||||
});
|
||||
|
||||
await store.createTask({
|
||||
spec: {
|
||||
templateInfo: { entityRef: 'template:default/three' },
|
||||
} as TaskSpec,
|
||||
createdBy: 'user:default/three',
|
||||
spec: {} as TaskSpec,
|
||||
createdBy: 'user:default/four',
|
||||
});
|
||||
|
||||
const permissionFilters: PermissionCriteria<TaskFilters> = {
|
||||
anyOf: [
|
||||
{
|
||||
property: 'createdBy',
|
||||
values: ['user:default/one', 'user:default/two'],
|
||||
},
|
||||
{
|
||||
property: 'templateEntityRefs',
|
||||
values: ['template:default/one', 'template:default/two'],
|
||||
},
|
||||
],
|
||||
not: {
|
||||
property: 'createdBy',
|
||||
values: ['user:default/three', 'user:default/four'],
|
||||
},
|
||||
};
|
||||
|
||||
const { tasks, totalTasks } = await store.list({
|
||||
permissionFilters: permissionFilters,
|
||||
});
|
||||
|
||||
expect(totalTasks).toBe(4);
|
||||
console.log(JSON.stringify);
|
||||
|
||||
expect(tasks).not.toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
createdBy: 'user:default/three',
|
||||
spec: { templateInfo: { entityRef: 'template:default/three' } },
|
||||
}),
|
||||
]),
|
||||
expect(totalTasks).toBe(3);
|
||||
|
||||
const createdByList = tasks.map(task => task.createdBy);
|
||||
expect(createdByList).toEqual(
|
||||
expect.arrayContaining(['user:default/one', 'user:default/two']),
|
||||
);
|
||||
expect(createdByList).not.toEqual(
|
||||
expect.arrayContaining(['user:default/three', 'user:default/four']),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -216,6 +216,7 @@ export class DatabaseTaskStore implements TaskStore {
|
||||
): Knex.QueryBuilder {
|
||||
// handle not criteria
|
||||
if (isNotCriteria(filter)) {
|
||||
console.log(`reached here: ${JSON.stringify(filter)}`);
|
||||
return this.parseFilter(filter.not, query, db, !negate);
|
||||
}
|
||||
|
||||
@@ -223,24 +224,13 @@ export class DatabaseTaskStore implements TaskStore {
|
||||
const values: string[] = compact(filter.values) ?? [];
|
||||
|
||||
if (filter.property === 'createdBy') {
|
||||
query.whereIn('created_by', [...new Set(values)]);
|
||||
}
|
||||
|
||||
if (filter.property === 'templateEntityRefs' && values.length > 0) {
|
||||
const dbClient = this.db.client.config.client;
|
||||
const placeholders = values.map(() => '?').join(', ');
|
||||
if (dbClient === 'pg') {
|
||||
query.whereRaw(
|
||||
`spec::jsonb->'templateInfo'->>'entityRef' IN (${placeholders})`,
|
||||
values,
|
||||
);
|
||||
} else if (dbClient === 'better-sqlite3') {
|
||||
query.whereRaw(
|
||||
`json_extract(spec, '$.templateInfo.entityRef') IN (${placeholders})`,
|
||||
values,
|
||||
);
|
||||
if (negate) {
|
||||
query.whereNotIn('created_by', [...new Set(values)]);
|
||||
} else {
|
||||
query.whereIn('created_by', [...new Set(values)]);
|
||||
}
|
||||
}
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
@@ -300,6 +290,8 @@ export class DatabaseTaskStore implements TaskStore {
|
||||
this.parseFilter(combinedPermissionFilters, queryBuilder, this.db);
|
||||
}
|
||||
|
||||
console.log(`Parse FIlters: ${queryBuilder}`);
|
||||
|
||||
if (status || filters?.status) {
|
||||
const arr: TaskStatus[] = flattenParams<TaskStatus>(
|
||||
status,
|
||||
|
||||
@@ -23,7 +23,9 @@ import {
|
||||
SerializedTaskEvent,
|
||||
SerializedTask,
|
||||
TaskStatus,
|
||||
TaskFilters,
|
||||
} from '@backstage/plugin-scaffolder-node';
|
||||
import { PermissionCriteria } from '@backstage/plugin-permission-common';
|
||||
|
||||
/**
|
||||
* TaskStoreEmitOptions
|
||||
@@ -131,6 +133,7 @@ export interface TaskStore {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
};
|
||||
permissionFilters?: PermissionCriteria<TaskFilters>;
|
||||
order?: { order: 'asc' | 'desc'; field: string }[];
|
||||
}): Promise<{ tasks: SerializedTask[]; totalTasks?: number }>;
|
||||
|
||||
|
||||
@@ -23,7 +23,6 @@ import {
|
||||
hasStringProperty,
|
||||
hasTag,
|
||||
hasCreatedBy,
|
||||
hasTemplateEntityRefs,
|
||||
} from './rules';
|
||||
import { createConditionAuthorizer } from '@backstage/plugin-permission-node';
|
||||
import { RESOURCE_TYPE_SCAFFOLDER_ACTION } from '@backstage/plugin-scaffolder-common/alpha';
|
||||
@@ -601,84 +600,3 @@ describe('hasCreatedBy', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasTemplateEntityRefs', () => {
|
||||
describe('apply', () => {
|
||||
const task: SerializedTask = {
|
||||
id: 'a-random-id',
|
||||
spec: {
|
||||
templateInfo: { entityRef: 'template:default/test-1' },
|
||||
} as TaskSpec,
|
||||
status: 'completed',
|
||||
createdAt: '',
|
||||
};
|
||||
it('returns false when templateEntityRefs is an empty array', () => {
|
||||
expect(
|
||||
hasTemplateEntityRefs.apply(task, {
|
||||
templateEntityRefs: [],
|
||||
}),
|
||||
).toEqual(false);
|
||||
});
|
||||
it('returns false when templateEntityRef is not matched (single entityRef in templateEntityRefs)', () => {
|
||||
expect(
|
||||
hasTemplateEntityRefs.apply(task, {
|
||||
templateEntityRefs: ['template:default/not-matched'],
|
||||
}),
|
||||
).toEqual(false);
|
||||
});
|
||||
it('returns true when templateEntityRef matches (single entityRef in templateEntityRefs)', () => {
|
||||
expect(
|
||||
hasTemplateEntityRefs.apply(task, {
|
||||
templateEntityRefs: ['template:default/test-1'],
|
||||
}),
|
||||
).toEqual(true);
|
||||
});
|
||||
it('returns false when templateEntityRefs is not matched (multiple entitRefs in templateEntityRefs)', () => {
|
||||
expect(
|
||||
hasTemplateEntityRefs.apply(task, {
|
||||
templateEntityRefs: [
|
||||
'template:default/test-2',
|
||||
'template:default/test-3',
|
||||
'template:default/test-4',
|
||||
],
|
||||
}),
|
||||
).toEqual(false);
|
||||
});
|
||||
it('returns true when templateEntityRefs matches (multiple entityRefs in templateEntityRefs)', () => {
|
||||
expect(
|
||||
hasTemplateEntityRefs.apply(task, {
|
||||
templateEntityRefs: [
|
||||
'template:default/test-2',
|
||||
'template:default/test-1',
|
||||
'template:default/test-3',
|
||||
],
|
||||
}),
|
||||
).toEqual(true);
|
||||
});
|
||||
});
|
||||
describe('toQuery', () => {
|
||||
it('returns the correct query filter with values (single entityRef in templateEntityRefs)', () => {
|
||||
expect(
|
||||
hasTemplateEntityRefs.toQuery({
|
||||
templateEntityRefs: ['template:default/test-1'],
|
||||
}),
|
||||
).toEqual({
|
||||
property: 'templateEntityRefs',
|
||||
values: ['template:default/test-1'],
|
||||
});
|
||||
});
|
||||
});
|
||||
it('returns the correct query filter with values (multiple entityRefs in templateEntityRefs)', () => {
|
||||
expect(
|
||||
hasTemplateEntityRefs.toQuery({
|
||||
templateEntityRefs: [
|
||||
'template:default/test-1',
|
||||
'template:default/test-2',
|
||||
],
|
||||
}),
|
||||
).toEqual({
|
||||
property: 'templateEntityRefs',
|
||||
values: ['template:default/test-1', 'template:default/test-2'],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -167,31 +167,6 @@ export const hasCreatedBy = createTaskPermissionRule({
|
||||
},
|
||||
});
|
||||
|
||||
export const hasTemplateEntityRefs = createTaskPermissionRule({
|
||||
name: 'HAS_TEMPLATE_ENTITY_REFS',
|
||||
description: 'Match tasks with the given template entity refs',
|
||||
resourceType: RESOURCE_TYPE_SCAFFOLDER_TASK,
|
||||
paramsSchema: z.object({
|
||||
templateEntityRefs: z
|
||||
.array(z.string())
|
||||
.describe(
|
||||
'List of template entity refs; only tasks related to these templates will be viewable',
|
||||
),
|
||||
}),
|
||||
apply: (resource, { templateEntityRefs }) => {
|
||||
if (!resource.spec.templateInfo) {
|
||||
return false;
|
||||
}
|
||||
return templateEntityRefs.includes(resource.spec.templateInfo.entityRef);
|
||||
},
|
||||
toQuery: ({ templateEntityRefs }) => {
|
||||
return {
|
||||
property: 'templateEntityRefs' as TaskFilter['property'],
|
||||
values: templateEntityRefs,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const scaffolderTemplateRules = { hasTag };
|
||||
export const scaffolderActionRules = {
|
||||
hasActionId,
|
||||
@@ -199,4 +174,4 @@ export const scaffolderActionRules = {
|
||||
hasNumberProperty,
|
||||
hasStringProperty,
|
||||
};
|
||||
export const scaffolderTaskRules = { hasCreatedBy, hasTemplateEntityRefs };
|
||||
export const scaffolderTaskRules = { hasCreatedBy };
|
||||
|
||||
@@ -468,7 +468,7 @@ export type TaskEventType = 'completion' | 'log' | 'cancelled' | 'recovered';
|
||||
|
||||
// @public
|
||||
export type TaskFilter = {
|
||||
property: 'createdBy' | 'templateEntityRefs';
|
||||
property: 'createdBy';
|
||||
values: Array<string> | undefined;
|
||||
};
|
||||
|
||||
|
||||
@@ -110,7 +110,7 @@ export type TaskBrokerDispatchOptions = {
|
||||
* @public
|
||||
*/
|
||||
export type TaskFilter = {
|
||||
property: 'createdBy' | 'templateEntityRefs';
|
||||
property: 'createdBy';
|
||||
values: Array<string> | undefined;
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user