Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(permission): support batch object policies (#7640)

Univer76208a4204d7
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index d0d1c46b74..5d60e3f372 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -110,9 +110,16 @@ export { ObjectPermissionRuleModel } from './services/permission/object-permissi
export type {
IObjectPermissionRule,
ISetObjectPermissionRuleMutationParams,
+ ISetObjectPermissionRulesMutationParams,
} from './services/permission/object-permission-rule.model';
export { OBJECT_PERMISSION_CONFIG_KEY, ObjectPermissionService } from './services/permission/object-permission.service';
-export type { IObjectPermissionPolicy, IObjectPermissionTarget } from './services/permission/object-permission.service';
+export type {
+ IObjectPermissionBatchResult,
+ IObjectPermissionChange,
+ IObjectPermissionPolicy,
+ IObjectPermissionTarget,
+ ISetObjectPermissionsCommandParams,
+} from './services/permission/object-permission.service';
export { PermissionService } from './services/permission/permission.service';
export { IPermissionService, PermissionStatus } from './services/permission/type';
export type { IPermissionParam } from './services/permission/type';
diff --git a/packages/core/src/services/permission/__tests__/object-permission.service.spec.ts b/packages/core/src/services/permission/__tests__/object-permission.service.spec.ts
index 9605f30629..cdb9b80ba3 100644
--- a/packages/core/src/services/permission/__tests__/object-permission.service.spec.ts
+++ b/packages/core/src/services/permission/__tests__/object-permission.service.spec.ts
@@ -20,7 +20,10 @@ import type {
IListPermPointResponse,
IUpdatePermPointRequest,
} from '@univerjs/protocol';
-import type { ISetObjectPermissionRuleMutationParams } from '../object-permission-rule.model';
+import type {
+ ISetObjectPermissionRuleMutationParams,
+ ISetObjectPermissionRulesMutationParams,
+} from '../object-permission-rule.model';
import { ObjectScope, UnitAction, UnitObject, UnitRole } from '@univerjs/protocol';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { UniverInstanceType } from '../../../common/unit';
@@ -78,7 +81,8 @@ function createClient(authz: ReturnType<typeof createAuthz>['authz'], enabled =
const service = injector.get(ObjectPermissionService);
const commands = injector.get(ICommandService);
commands.registerCommand({ id: 'test.mutation.permission', type: CommandType.MUTATION, handler: (_, params: ISetObjectPermissionRuleMutationParams) => model.setRule(params.unitId, params.objectType, params.objectId, params.rule) });
- roots.forEach((root) => service.registerRuleModel(root, model, 'test.mutation.permission'));
+ commands.registerCommand({ id: 'test.mutation.permissions', type: CommandType.MUTATION, handler: (_, params: ISetObjectPermissionRulesMutationParams) => model.setRules(params.unitId, params.rules) });
+ roots.forEach((root) => service.registerRuleModel(root, model, 'test.mutation.permission', 'test.mutation.permissions'));
injector.get(IConfigService).setConfig(OBJECT_PERMISSION_CONFIG_KEY, enabled ? [...types, ...roots] : []);
univer.createUnit(UniverInstanceType.UNIVER_DOC, { id: 'unit', body: { dataStream: '\r\n' } });
injector.get(IUniverInstanceService).focusUnit('unit');
@@ -271,3 +275,90 @@ describe('ObjectPermissionService', () => {
expect(client.service.getPolicies('unit')).toEqual([]);
});
});
+
+describe('ObjectPermissionService batches', () => {
+ it.each(types)('creates multiple policies, edits and removes them, and undoes only the binding changes (%s)', async (objectType) => {
+ const backend = createAuthz();
+ const client = createClient(backend.authz);
+ const a = target(objectType, 'a');
+ const b = target(objectType, 'b');
+ expect(await client.service.saveMany([{ ...a, policy: restriction }, { ...b, policy: restriction }])).toEqual({ succeeded: ['a', 'b'], failed: [] });
+ const original = client.model.getRules('unit');
+ const creation = client.history.pitchTopUndoElement()!;
+ expect(creation.undoMutations).toHaveLength(1);
+ await client.commands.executeCommand(creation.undoMutations[0].id, creation.undoMutations[0].params);
+ expect(client.model.getRules('unit')).toEqual([]);
+ await client.commands.executeCommand(creation.redoMutations[0].id, creation.redoMutations[0].params);
+ expect(client.model.getRules('unit')).toEqual(original);
+ const peer = createClient(backend.authz);
+ peer.resources.loadResources('unit', client.resources.getResources('unit', UniverInstanceType.UNIVER_DOC));
+ expect(peer.model.getRules('unit')).toEqual(original);
+ expect(await client.service.saveMany([{ ...a, policy: { ...restriction, edit: 'all' } }, { ...b, policy: null }])).toEqual({ succeeded: ['a', 'b'], failed: [] });
+ expect(backend.authz.update).toHaveBeenCalledWith(expect.objectContaining({ objectID: original[0].permissionId }));
+ expect(client.model.getRules('unit')).toEqual([original[0]]);
+ const removal = client.history.pitchTopUndoElement()!;
+ await client.commands.executeCommand(removal.undoMutations[0].id, removal.undoMutations[0].params);
+ expect(client.model.getRules('unit')).toEqual(original);
+ expect((await client.service.read(a)).edit).toBe('all');
+ expect(backend.authz.create).toHaveBeenCalledTimes(2);
+ });
+
+ it('reports failed writes without losing successful bindings or their undo entry', async () => {
+ const backend = createAuthz();
+ const client = createClient(backend.authz);
+ backend.authz.create.mockRejectedValueOnce(new Error('Offline'));
+ const result = await client.service.saveMany(['a', 'b', 'c'].map((id) => ({ ...target(UnitObject.BoardElement, id), policy: restriction })));
+ expect(result.succeeded).toEqual(['b', 'c']);
+ expect(result.failed).toEqual([{ objectId: 'a', error: expect.any(Error) }]);
+ expect(client.model.getRules('unit').map((rule) => rule.objectId)).toEqual(['b', 'c']);
+ const undo = client.history.pitchTopUndoElement()!;
+ expect(undo.undoMutations).toHaveLength(1);
+ await client.commands.executeCommand(undo.undoMutations[0].id, undo.undoMutations[0].params);
+ expect(client.model.getRules('unit')).toEqual([]);
+ });
+
+ it('does not overwrite a concurrent binding while the batch waits for Authz', async () => {
+ const backend = createAuthz();
+ const client = createClient(backend.authz);
+ const a = target(UnitObject.BoardElement, 'a');
+ let finish!: (id: string) => void;
+ backend.authz.create.mockImplementationOnce(() => new Promise((resolve) => {
+ finish = resolve;
+ }));
+ const pending = client.service.saveMany([{ ...a, policy: restriction }, { ...target(UnitObject.BoardElement, 'b'), policy: restriction }]);
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));
+ const concurrent = { objectId: a.objectId, objectType: a.objectType, permissionId: 'concurrent' };
+ client.model.setRule('unit', a.objectType, a.objectId, concurrent);
+ finish('late-response');
+ const result = await pending;
+ expect(result.succeeded).toEqual(['b']);
+ expect(result.failed).toEqual([{ objectId: 'a', error: expect.any(Error) }]);
+ expect(client.model.getRule('unit', a.objectType, a.objectId)).toEqual(concurrent);
+ });
+
+ it('rejects duplicate targets before writing and checks authorization per object', async () => {
+ const backend = createAuthz();
+ const client = createClient(backend.authz);
+ const change = { ...target(UnitObject.BoardElement), policy: restriction };
+ await expect(client.service.saveMany([change, change])).rejects.toThrow('Invalid');
+ expect(backend.authz.create).not.toHaveBeenCalled();
+ backend.authz.allowed.mockResolvedValue([{ action: UnitAction.CreatePermissionObject, allowed: false }]);
+ const result = await client.service.saveMany([change]);
+ expect(result.succeeded).toEqual([]);
+ expect(result.failed).toEqual([{ objectId: change.objectId, error: expect.any(Error) }]);
+ expect(backend.authz.create).not.toHaveBeenCalled();
+ expect(client.history.pitchTopUndoElement()).toBeNull();
+ });
+});
+
+it('returns successful writes when the final permission refresh fails', async () => {
+ const backend = createAuthz();
+ const client = createClient(backend.authz);
+ backend.authz.batchAllowed.mockRejectedValue(new Error('Readback offline'));
+ const result = await client.service.saveMany([{ ...target(UnitObject.BoardElement, 'a'), policy: restriction }]);
+ expect(result.succeeded).toEqual(['a']);
+ expect(result.failed).toEqual([]);
+ expect(result.refreshError).toEqual(expect.any(Error));
+ expect(client.model.getRules('unit')).toHaveLength(1);
+ expect(backend.authz.create).toHaveBeenCalledTimes(1);
+});
diff --git a/packages/core/src/services/permission/object-permission-rule.model.ts b/packages/core/src/services/permission/object-permission-rule.model.ts
index 5af25dcad2..d1e496287c 100644
--- a/packages/core/src/services/permission/object-permission-rule.model.ts
+++ b/packages/core/src/services/permission/object-permission-rule.model.ts
@@ -34,6 +34,11 @@ export interface ISetObjectPermissionRuleMutationParams {
rule: IObjectPermissionRule | null;
}
+export interface ISetObjectPermissionRulesMutationParams {
+ unitId: string;
+ rules: Omit<ISetObjectPermissionRuleMutationParams, 'unitId'>[];
+}
+
/** Shared storage only; each product owns its rule type, resource name and mutation. */
export abstract class ObjectPermissionRuleModel<T extends IObjectPermissionRule = IObjectPermissionRule> extends Disposable {
private readonly _rules = new Map<string, Map<string, T>>();
@@ -79,20 +84,38 @@ export abstract class ObjectPermissionRuleModel<T extends IObjectPermissionRule
}
setRule(unitId: string, objectType: UnitObject, objectId: string, rule: T | null): boolean {
- if (!unitId || !objectId || !this._objectTypes.includes(objectType) || (rule !== null &&
- (!rule || rule.objectId !== objectId || rule.objectType !== objectType || typeof rule.permissionId !== 'string' || !rule.permissionId))) {
+ return this.setRules(unitId, [{ objectId, objectType, rule }]);
+ }
+
+ /** Validate the whole batch before changing any binding or publishing a resource change. */
+ setRules(unitId: string, updates: { objectId: string; objectType: UnitObject; rule: T | null }[]): boolean {
+ if (typeof unitId !== 'string' || !unitId || !Array.isArray(updates) || updates.length === 0) {
return false;
}
- let rules = this._rules.get(unitId);
- if (!rules) {
- rules = new Map();
- this._rules.set(unitId, rules);
+ const keys = new Set<string>();
+ for (const update of updates) {
+ if (!update) {
+ return false;
+ }
+ const { objectId, objectType, rule } = update;
+ const key = this._key(objectType, objectId);
+ if (typeof objectId !== 'string' || !objectId || !this._objectTypes.includes(objectType) || keys.has(key) || (rule !== null &&
+ (!rule || rule.objectId !== objectId || rule.objectType !== objectType ||
+ typeof rule.permissionId !== 'string' || !rule.permissionId))) {
+ return false;
+ }
+ keys.add(key);
}
- if (rule) {
- rules.set(this._key(objectType, objectId), Tools.deepClone(rule));
- } else {
- rules.delete(this._key(objectType, objectId));
+ const clonedUpdates = Tools.deepClone(updates);
+ const rules = this._rules.get(unitId) ?? new Map<string, T>();
+ for (const { objectId, objectType, rule } of clonedUpdates) {
+ if (rule) {
+ rules.set(this._key(objectType, objectId), rule);
+ } else {
+ rules.delete(this._key(objectType, objectId));
+ }
}
+ this._rules.set(unitId, rules);
this._changes.next(unitId);
return true;
}
diff --git a/packages/core/src/services/permission/object-permission.service.ts b/packages/core/src/services/permission/object-permission.service.ts
index 04125d0517..89a3b13bad 100644
--- a/packages/core/src/services/permission/object-permission.service.ts
+++ b/packages/core/src/services/permission/object-permission.service.ts
@@ -16,7 +16,11 @@
import type { IBatchAllowedResponse, ICollaborator, ICreateRequest, IListPermPointResponse } from '@univerjs/protocol';
import type { IDisposable } from '../../common/di';
-import type { IObjectPermissionRule, ObjectPermissionRuleModel } from './object-permission-rule.model';
+import type {
+ IObjectPermissionRule,
+ ISetObjectPermissionRulesMutationParams,
+ ObjectPermissionRuleModel,
+} from './object-permission-rule.model';
import type { IPermissionPoint } from './type';
import { ObjectScope, UnitAction, UnitObject, UnitRole } from '@univerjs/protocol';
import { BehaviorSubject, Subject } from 'rxjs';
@@ -43,6 +47,24 @@ export interface IObjectPermissionPolicy {
strategies: IListPermPointResponse['objects'][number]['strategies'];
}
+export interface IObjectPermissionChange {
+ objectId: string;
+ /** null removes protection and restores inheritance; it never deletes the object. */
+ policy: IObjectPermissionPolicy | null;
+}
+
+export interface ISetObjectPermissionsCommandParams {
+ unitId: string;
+ changes: IObjectPermissionChange[];
+}
+
+export interface IObjectPermissionBatchResult {
+ succeeded: string[];
+ failed: { objectId: string; error: unknown }[];
+ /** Writes have already completed; a refresh failure must not cause successful objects to be retried. */
+ refreshError?: unknown;
+}
+
/** Frontend opt-in; does not change the Authz service interface or existing local setters. */
export const OBJECT_PERMISSION_CONFIG_KEY = 'objectPermissionTypes';
@@ -67,7 +89,7 @@ const ROOT_OBJECT_TYPES: Partial<Record<UnitObject, UnitObject>> = {
/** Coordinates Authz policy writes and the current user's effective permission cache. */
export class ObjectPermissionService extends Disposable {
- private readonly _models = new Map<UnitObject, { model: ObjectPermissionRuleModel; mutationId: string }>();
+ private readonly _models = new Map<UnitObject, { model: ObjectPermissionRuleModel; mutationId: string; batchMutationId?: string }>();
private readonly _initialized = new Set<string>();
private readonly _policies = new Map<string, IListPermPointResponse['objects'][number][]>();
private readonly _generations = new Map<string, number>();
@@ -104,11 +126,11 @@ export class ObjectPermissionService extends Disposable {
return this._injector.get(IAuthzIoService);
}
- registerRuleModel(rootType: UnitObject, model: ObjectPermissionRuleModel, mutationId: string): IDisposable {
+ registerRuleModel(rootType: UnitObject, model: ObjectPermissionRuleModel, mutationId: string, batchMutationId?: string): IDisposable {
if (this._models.has(rootType)) {
throw new Error('Object permission rule model already registered.');
}
- this._models.set(rootType, { model, mutationId });
+ this._models.set(rootType, { model, mutationId, batchMutationId });
const subscription = model.changed$.subscribe((unitId) => {
this._generations.delete(unitId);
this._policies.delete(unitId);
@@ -302,8 +324,16 @@ export class ObjectPermissionService extends Disposable {
/** Must be called from a product permission Command. */
async save(target: IObjectPermissionTarget, policy: IObjectPermissionPolicy): Promise<void> {
- this._assertSupported(target);
const permissionId = this._getRule(target)?.permissionId;
+ const rule = await this._writePolicy(target, policy, permissionId);
+ if (rule) {
+ await this._commitRule(target, rule, permissionId);
+ }
+ await this.refreshUnit(target.unitId);
+ }
+
+ private async _writePolicy(target: IObjectPermissionTarget, policy: IObjectPermissionPolicy, permissionId: string | undefined): Promise<IObjectPermissionRule | undefined> {
+ this._assertSupported(target);
if (!await this.canManage(target)) {
throw new Error('Object permission management denied.');
}
@@ -323,6 +353,9 @@ export class ObjectPermissionService extends Disposable {
editScope = ObjectScope.OneSelf;
}
const scope = { read: previous?.scope?.read ?? ObjectScope.AllCollaborator, edit: editScope };
+ if (this._getRule(target)?.permissionId !== permissionId) {
+ throw new Error('Object permission binding changed during the request.');
+ }
let objectID = this._getAuthzId(target);
if (!objectID) {
const payload = {
@@ -352,11 +385,8 @@ export class ObjectPermissionService extends Disposable {
if (!objectID) {
throw new Error('Authz did not return a permission ID.');
}
- await this._commitRule(target, { objectId: target.objectId, objectType: target.objectType, permissionId: objectID }, permissionId);
+ return { objectId: target.objectId, objectType: target.objectType, permissionId: objectID };
} else {
- if (this._getRule(target)?.permissionId !== permissionId) {
- throw new Error('Object permission binding changed during the request.');
- }
await this._authz.update({
unitID: target.unitId,
objectID,
@@ -368,8 +398,85 @@ export class ObjectPermissionService extends Disposable {
collaborators: target.objectId === target.unitId ? undefined : { collaborators: policy.edit === 'members' ? policy.collaborators : [] },
});
}
- // Never use the requested boolean as this user's result: owners and collaborators differ.
- await this.refreshUnit(target.unitId);
+ return undefined;
+ }
+
+ /**
+ * Called by product Commands. Authz writes remain per object, so failures are reported per object.
+ * Successful binding changes share one undo entry; updates to existing remote policies are not undoable.
+ */
+ async saveMany(changes: (IObjectPermissionTarget & { policy: IObjectPermissionPolicy | null })[]): Promise<IObjectPermissionBatchResult> {
+ const first = changes[0];
+ const registration = first && this._models.get(ROOT_OBJECT_TYPES[first.objectType]!);
+ if (!first || !registration?.batchMutationId || changes.some((target) =>
+ target.unitId !== first.unitId || target.objectId === first.unitId ||
+ ROOT_OBJECT_TYPES[target.objectType] !== ROOT_OBJECT_TYPES[first.objectType] || !this.supports(target)) ||
+ new Set(changes.map((target) => `${target.objectType}/${target.objectId}`)).size !== changes.length) {
+ throw new Error('Invalid object permission batch.');
+ }
+ const result: IObjectPermissionBatchResult = { succeeded: [], failed: [] };
+ const pending: { target: IObjectPermissionTarget; rule: IObjectPermissionRule | null; previous: IObjectPermissionRule | null }[] = [];
+ for (const target of changes) {
+ const previous = this._getRule(target) ?? null;
+ try {
+ let rule: IObjectPermissionRule | null | undefined;
+ if (target.policy === null) {
+ if (!await this.canDelete(target)) {
+ throw new Error('Object permission deletion denied.');
+ }
+ rule = null;
+ } else {
+ rule = await this._writePolicy(target, target.policy, previous?.permissionId);
+ }
+ if (rule === undefined) {
+ if (this._getRule(target)?.permissionId !== previous?.permissionId) {
+ throw new Error('Object permission binding changed during the request.');
+ }
+ result.succeeded.push(target.objectId);
+ } else {
+ pending.push({ target, rule, previous });
+ }
+ } catch (error) {
+ result.failed.push({ objectId: target.objectId, error });
+ }
+ }
+ // A concurrent binding write must not be overwritten by a late network response.
+ const applicable = pending.filter(({ target, previous }) => {
+ if (this._getRule(target)?.permissionId === previous?.permissionId) {
+ return true;
+ }
+ result.failed.push({ objectId: target.objectId, error: new Error('Object permission binding changed during the request.') });
+ return false;
+ });
+ if (applicable.length) {
+ const params: ISetObjectPermissionRulesMutationParams = {
+ unitId: first.unitId,
+ rules: applicable.map(({ target, rule }) => ({ objectId: target.objectId, objectType: target.objectType, rule })),
+ };
+ const undoParams: ISetObjectPermissionRulesMutationParams = {
+ unitId: first.unitId,
+ rules: applicable.map(({ target, previous }) => ({ objectId: target.objectId, objectType: target.objectType, rule: previous })),
+ };
+ try {
+ if (!await this._commands.executeCommand(registration.batchMutationId, params)) {
+ throw new Error('Could not update the object permission bindings.');
+ }
+ this._injector.get(IUndoRedoService).pushUndoRedo({
+ unitID: first.unitId,
+ redoMutations: [{ id: registration.batchMutationId, params }],
+ undoMutations: [{ id: registration.batchMutationId, params: undoParams }],
+ });
+ result.succeeded.push(...applicable.map(({ target }) => target.objectId));
+ } catch (error) {
+ result.failed.push(...applicable.map(({ target }) => ({ objectId: target.objectId, error })));
+ }
+ }
+ try {
+ await this.refreshUnit(first.unitId);
+ } catch (error) {
+ result.refreshError = error;
+ }
+ return result;
}
async refreshUnit(unitId: string): Promise<void> {
diff --git a/packages/docs/src/commands/commands/__tests__/set-document-permissions.command.spec.ts b/packages/docs/src/commands/commands/__tests__/set-document-permissions.command.spec.ts
new file mode 100644
index 0000000000..7d5fc5699f
--- /dev/null
+++ b/packages/docs/src/commands/commands/__tests__/set-document-permissions.command.spec.ts
@@ -0,0 +1,111 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type {
+ IAllowedRequest,
+ ICreateRequest,
+ IListPermPointResponse,
+ IUpdatePermPointRequest,
+} from '@univerjs/protocol';
+import {
+ IAuthzIoService,
+ ICommandService,
+ IConfigService,
+ IPermissionService,
+ IUndoRedoService,
+ IUniverInstanceService,
+ OBJECT_PERMISSION_CONFIG_KEY,
+ ObjectPermissionService,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { ObjectScope, UnitAction, UnitObject, UnitRole } from '@univerjs/protocol';
+import { afterEach, expect, it, vi } from 'vitest';
+import { FDocumentPermission } from '../../../facade/f-document-permission';
+import { DocumentPermissionRuleModel } from '../../../services/permission/document-permission-rule.model';
+import { SetDocumentPermissionRuleMutation } from '../../mutations/set-document-permission-rule.mutation';
+import { SetDocumentPermissionRulesMutation } from '../../mutations/set-document-permission-rules.mutation';
+import { SetDocumentPermissionsCommand } from '../set-document-permissions.command';
+
+const univers: Univer[] = [];
+afterEach(() => univers.splice(0).forEach((univer) => univer.dispose()));
+function setup() {
+ let sequence = 0;
+ const policies: IListPermPointResponse['objects'] = [];
+ const authz = {
+ create: vi.fn(async (request: ICreateRequest) => {
+ const payload = request.documentObject ?? request.slideObject ?? request.baseObject ?? request.boardObject!;
+ const objectID = `permission-${++sequence}`;
+ policies.push({ ...payload, objectID, objectType: request.objectType, creator: undefined, actions: [], shareOn: false, shareRole: UnitRole.Reader, shareScope: 0 });
+ return objectID;
+ }),
+ list: async ({ objectIDs }: { objectIDs: string[] }) => policies.filter((policy) => objectIDs.includes(policy.objectID)),
+ allowed: async ({ actions }: IAllowedRequest) => actions.map((action) => ({ action, allowed: true })),
+ batchAllowed: async (requests: IAllowedRequest[]) => requests.map((request) => ({ ...request, actions: request.actions.map((action) => ({ action, allowed: action !== UnitAction.Edit })) })),
+ update: vi.fn(async (request: IUpdatePermPointRequest) => {
+ Object.assign(policies.find((policy) => policy.objectID === request.objectID)!, request);
+ }),
+ };
+ const univer = new Univer({ override: [[IAuthzIoService, { useValue: authz }]] });
+ univers.push(univer);
+ const injector = univer.__getInjector();
+ injector.add([DocumentPermissionRuleModel]);
+ const model = injector.get(DocumentPermissionRuleModel);
+ univer.createUnit(UniverInstanceType.UNIVER_DOC, { id: 'unit', body: { dataStream: '\r\n' } });
+ injector.get(IUniverInstanceService).focusUnit('unit');
+ const commands = injector.get(ICommandService);
+ commands.registerCommand(SetDocumentPermissionRulesMutation);
+ commands.registerCommand(SetDocumentPermissionsCommand);
+ injector.get(ObjectPermissionService).registerRuleModel(UnitObject.Document, model, SetDocumentPermissionRuleMutation.id, SetDocumentPermissionRulesMutation.id);
+ injector.get(IConfigService).setConfig(OBJECT_PERMISSION_CONFIG_KEY, [UnitObject.DocumentParagraph]);
+ const permission = new FDocumentPermission('unit', commands, injector.get(IPermissionService));
+ return { model, commands, permission, authz, policies, permissions: injector.get(IPermissionService), history: injector.get(IUndoRedoService) };
+}
+
+it('uses Authz IDs across batch creation, policy updates, removal, and one-step binding undo', async () => {
+ const { permission, model, authz, policies, permissions, history, commands } = setup();
+ const first = 'paragraph//a';
+ const second = 'paragraph//b';
+ const policy = { edit: 'owner' as const, collaborators: [], strategies: [] };
+ expect(await permission.setObjectPermissions([{ objectId: first, policy }, { objectId: second, policy }])).toEqual({ succeeded: [first, second], failed: [] });
+ const rules = model.getRules('unit');
+ expect(rules).toHaveLength(2);
+ expect(permissions.getPermissionPoint(`${UnitObject.DocumentParagraph}.${UnitAction.Edit}_unit_${first}`)?.value).toBe(false);
+ expect(await permission.setObjectPermissions([{ objectId: first, policy: { ...policy, edit: 'all' } }, { objectId: second, policy: null }])).toEqual({ succeeded: [first, second], failed: [] });
+ expect(authz.update).toHaveBeenCalledWith(expect.objectContaining({ objectID: rules[0].permissionId }));
+ expect(policies[0].scope?.edit).toBe(ObjectScope.AllCollaborator);
+ expect(model.getRules('unit')).toEqual([rules[0]]);
+ const undo = history.pitchTopUndoElement()!;
+ expect(undo.undoMutations).toHaveLength(1);
+ await commands.executeCommand(undo.undoMutations[0].id, undo.undoMutations[0].params);
+ expect(model.getRules('unit')).toEqual(rules);
+ expect(authz.create).toHaveBeenCalledTimes(2);
+});
+
+it('validates every policy before writes and reports partial Authz failures through the facade', async () => {
+ const { permission, model, authz } = setup();
+ const policy = { edit: 'owner' as const, collaborators: [], strategies: [] };
+ await expect(permission.setObjectPermissions([
+ { objectId: 'paragraph//a', policy },
+ { objectId: 'paragraph//b', policy: { ...policy, strategies: [{ action: UnitAction.Copy, role: UnitRole.Owner }] } },
+ ])).rejects.toThrow('Invalid');
+ expect(authz.create).not.toHaveBeenCalled();
+ authz.create.mockRejectedValueOnce(new Error('Forbidden'));
+ const result = await permission.setObjectPermissions([{ objectId: 'paragraph//a', policy }, { objectId: 'paragraph//b', policy }]);
+ expect(result.succeeded).toEqual(['paragraph//b']);
+ expect(result.failed).toEqual([{ objectId: 'paragraph//a', error: expect.any(Error) }]);
+ expect(model.getRules('unit').map((rule) => rule.objectId)).toEqual(['paragraph//b']);
+});
diff --git a/packages/docs/src/commands/commands/set-document-permissions.command.ts b/packages/docs/src/commands/commands/set-document-permissions.command.ts
new file mode 100644
index 0000000000..5617c126d6
--- /dev/null
+++ b/packages/docs/src/commands/commands/set-document-permissions.command.ts
@@ -0,0 +1,38 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand, IObjectPermissionBatchResult, ISetObjectPermissionsCommandParams } from '@univerjs/core';
+import { CommandType, ObjectPermissionService } from '@univerjs/core';
+import { UnitAction } from '@univerjs/protocol';
+import { createDocumentPermissionPoint } from '../../services/permission/document-permission';
+
+export const SetDocumentPermissionsCommand: ICommand<ISetObjectPermissionsCommandParams, IObjectPermissionBatchResult> = {
+ type: CommandType.COMMAND,
+ id: 'doc.command.set-permissions',
+ async handler(accessor, params) {
+ if (!params?.unitId || !Array.isArray(params.changes) || !params.changes.length || params.changes.some((change) =>
+ !change?.objectId || change.objectId === params.unitId || (change.policy !== null &&
+ (!change.policy || !['all', 'owner', 'members'].includes(change.policy.edit) ||
+ !Array.isArray(change.policy.collaborators) || !Array.isArray(change.policy.strategies) ||
+ change.policy.strategies.some((strategy) => strategy.action !== UnitAction.Edit))))) {
+ throw new Error('Invalid object permission batch.');
+ }
+ return accessor.get(ObjectPermissionService).saveMany(params.changes.map((change) => {
+ const point = createDocumentPermissionPoint(params.unitId, change.objectId, UnitAction.Edit);
+ return { unitId: params.unitId, objectId: change.objectId, objectType: point.type, policy: change.policy };
+ }));
+ },
+};
diff --git a/packages/docs/src/commands/mutations/__tests__/set-document-permission-rules.mutation.spec.ts b/packages/docs/src/commands/mutations/__tests__/set-document-permission-rules.mutation.spec.ts
new file mode 100644
index 0000000000..7ad41e2d1d
--- /dev/null
+++ b/packages/docs/src/commands/mutations/__tests__/set-document-permission-rules.mutation.spec.ts
@@ -0,0 +1,74 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ICommandService, IResourceManagerService, Univer, UniverInstanceType } from '@univerjs/core';
+import { UnitObject } from '@univerjs/protocol';
+import { afterEach, expect, it, vi } from 'vitest';
+import { DocumentPermissionRuleModel } from '../../../services/permission/document-permission-rule.model';
+import { SetDocumentPermissionRulesMutation } from '../set-document-permission-rules.mutation';
+
+const univers: Univer[] = [];
+afterEach(() => univers.splice(0).forEach((univer) => univer.dispose()));
+function setup() {
+ const univer = new Univer();
+ univers.push(univer);
+ const injector = univer.__getInjector();
+ injector.add([DocumentPermissionRuleModel]);
+ const model = injector.get(DocumentPermissionRuleModel);
+ univer.createUnit(UniverInstanceType.UNIVER_DOC, { id: 'unit', body: { dataStream: '\r\n' } });
+ const commands = injector.get(ICommandService);
+ commands.registerCommand(SetDocumentPermissionRulesMutation);
+ return { univer, model, commands, resources: injector.get(IResourceManagerService) };
+}
+const objectType = UnitObject.DocumentParagraph;
+function binding(objectId: string, permissionId: string) {
+ return { objectId, objectType, rule: { objectId, objectType, permissionId } };
+}
+
+it('replays a mixed batch through the product resource and publishes one change', () => {
+ const first = setup();
+ const initial = { unitId: 'unit', rules: [binding('a', 'permission-a'), binding('b', 'permission-b')] };
+ first.commands.syncExecuteCommand(SetDocumentPermissionRulesMutation.id, initial);
+ const changed = vi.fn();
+ const subscription = first.model.changed$.subscribe(changed);
+ const batch = { unitId: 'unit', rules: [binding('a', 'replacement'), { objectId: 'b', objectType, rule: null }, binding('c', 'permission-c')] };
+ expect(first.commands.syncExecuteCommand(SetDocumentPermissionRulesMutation.id, batch)).toBe(true);
+ expect(changed).toHaveBeenCalledTimes(1);
+ subscription.unsubscribe();
+ const second = setup();
+ second.resources.loadResources('unit', first.resources.getResources('unit', UniverInstanceType.UNIVER_DOC));
+ expect(second.model.getRules('unit')).toEqual([binding('a', 'replacement').rule, binding('c', 'permission-c').rule]);
+ expect(second.commands.syncExecuteCommand(SetDocumentPermissionRulesMutation.id, batch)).toBe(true);
+ expect(second.model.getRules('unit')).toEqual(first.model.getRules('unit'));
+});
+
+it('rejects an invalid or duplicate entry without applying the valid prefix', () => {
+ const { model, commands } = setup();
+ const original = binding('a', 'original');
+ commands.syncExecuteCommand(SetDocumentPermissionRulesMutation.id, { unitId: 'unit', rules: [original] });
+ const changed = vi.fn();
+ const subscription = model.changed$.subscribe(changed);
+ for (const rules of [
+ [binding('a', 'replacement'), binding('b', '')],
+ [binding('a', 'replacement'), binding('a', 'duplicate')],
+ [],
+ ]) {
+ expect(commands.syncExecuteCommand(SetDocumentPermissionRulesMutation.id, { unitId: 'unit', rules })).toBe(false);
+ expect(model.getRules('unit')).toEqual([original.rule]);
+ }
+ expect(changed).not.toHaveBeenCalled();
+ subscription.unsubscribe();
+});
diff --git a/packages/docs/src/commands/mutations/set-document-permission-rules.mutation.ts b/packages/docs/src/commands/mutations/set-document-permission-rules.mutation.ts
new file mode 100644
index 0000000000..352429613d
--- /dev/null
+++ b/packages/docs/src/commands/mutations/set-document-permission-rules.mutation.ts
@@ -0,0 +1,30 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IMutation, ISetObjectPermissionRulesMutationParams } from '@univerjs/core';
+import { CommandType, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { DocumentPermissionRuleModel } from '../../services/permission/document-permission-rule.model';
+
+export const SetDocumentPermissionRulesMutation: IMutation<ISetObjectPermissionRulesMutationParams> = {
+ id: 'doc.mutation.set-permission-rules',
+ type: CommandType.MUTATION,
+ handler: (accessor, params) => {
+ if (!params || !accessor.get(IUniverInstanceService).getUnit(params.unitId, UniverInstanceType.UNIVER_DOC)) {
+ return false;
+ }
+ return accessor.get(DocumentPermissionRuleModel).setRules(params.unitId, params.rules);
+ },
+};
diff --git a/packages/docs/src/controllers/doc-permission.controller.ts b/packages/docs/src/controllers/doc-permission.controller.ts
index 1060a5a72e..fe47d9e567 100644
--- a/packages/docs/src/controllers/doc-permission.controller.ts
+++ b/packages/docs/src/controllers/doc-permission.controller.ts
@@ -51,6 +51,7 @@ import { UnitAction, UnitObject } from '@univerjs/protocol';
import { DeleteTextCommand, InsertTextCommand, UpdateTextCommand } from '../commands/commands/core-editing.command';
import { CreateHeaderFooterCommand } from '../commands/commands/create-header-footer.command';
import { SetDocumentPermissionCommand } from '../commands/commands/set-document-permission.command';
+import { SetDocumentPermissionsCommand } from '../commands/commands/set-document-permissions.command';
import { SetSectionHeaderFooterLinkCommand } from '../commands/commands/set-section-header-footer-link.command';
import { UpdateDocumentParagraphStyleCommand } from '../commands/commands/update-document-paragraph-style.command';
import {
@@ -82,6 +83,7 @@ import { getTopLevelSectionBreaks } from '../utils/sections';
const NON_EDIT_DOCUMENT_COMMAND_IDS = new Set([
SetDocumentPermissionCommand.id,
+ SetDocumentPermissionsCommand.id,
'doc.command.open-header-footer-panel',
'doc.command.close-header-footer',
'doc.command.select-all',
diff --git a/packages/docs/src/facade/f-document-permission.ts b/packages/docs/src/facade/f-document-permission.ts
index 16ea03d32b..08e373ce78 100644
--- a/packages/docs/src/facade/f-document-permission.ts
+++ b/packages/docs/src/facade/f-document-permission.ts
@@ -14,9 +14,20 @@
* limitations under the License.
*/
-import type { ICommandService, IPermissionService } from '@univerjs/core';
+import type {
+ ICommandService,
+ IObjectPermissionBatchResult,
+ IObjectPermissionChange,
+ IPermissionService,
+ ISetObjectPermissionsCommandParams,
+} from '@univerjs/core';
import type { DocumentUnitPermissionAction } from '@univerjs/docs';
-import { canEditDocumentTargets, getDocumentPermissionValue, SetDocumentPermissionCommand } from '@univerjs/docs';
+import {
+ canEditDocumentTargets,
+ getDocumentPermissionValue,
+ SetDocumentPermissionCommand,
+ SetDocumentPermissionsCommand,
+} from '@univerjs/docs';
import { UnitAction } from '@univerjs/protocol';
/**
@@ -30,6 +41,61 @@ export class FDocumentPermission {
private readonly _permissionService: IPermissionService
) {}
+ /**
+ * Creates or updates child-object edit policies in this unit; policy: null removes protection and restores inheritance.
+ *
+ * Requires Authz support and objectPermissionTypes configured for every target type. File and parent restrictions
+ * still apply. Use the exported permission object ID helpers, not raw object IDs or server permission IDs.
+ * The batch must be nonempty, contain distinct objects, and belong to this unit; file-wide policies are excluded.
+ * Other targets use getDocumentSectionPermissionObjectId and getDocumentEntityPermissionObjectId.
+ *
+ * edit: 'all' allows Unit editors, 'owner' restricts editing to the object owner, and 'members' selects existing
+ * Unit collaborators. Pass their collaborator records from the member service; this does not invite new users.
+ * Use strategies: [] for the default Edit strategy; child-object strategies support only UnitAction.Edit.
+ *
+ * Authz writes execute per object and can partially succeed. Inspect failed before retrying only those objects.
+ * refreshError means writes finished but permission readback failed; do not retry succeeded objects for that error.
+ * Successful binding changes share one undo entry; existing remote policy edits are not undoable.
+ * @param {IObjectPermissionChange[]} changes Permission object IDs and policies to apply.
+ * @returns {Promise<IObjectPermissionBatchResult>} Successful object IDs, per-object failures, and optional readback error.
+ * @throws {Error} Invalid batches or unsupported object types are rejected before Authz writes.
+ * @example Set owner/member editing and remove protection in one batch
+ * ```ts
+ * import type { ICollaborator } from '@univerjs/protocol';
+ * import { getDocumentParagraphPermissionObjectId } from '@univerjs/docs';
+ *
+ * // selectedMembers comes from the existing Unit collaborator picker/service.
+ * async function applyPermissions(selectedMembers: ICollaborator[]) {
+ * if (!selectedMembers.length) throw new Error('Select at least one Unit collaborator.');
+ * const document = univerAPI.getActiveDocument();
+ * if (!document) throw new Error('No active document.');
+ * const objects = document.getParagraphs().slice(0, 3);
+ * const objectIds = objects.map((paragraph) =>
+ * getDocumentParagraphPermissionObjectId(paragraph.getSegmentId(), paragraph.getId()));
+ * if (objectIds.length < 3) throw new Error('This example requires three paragraphs.');
+ * const result = await document.getPermission().setObjectPermissions([
+ * { objectId: objectIds[0], policy: { edit: 'owner', collaborators: [], strategies: [] } },
+ * { objectId: objectIds[1], policy: { edit: 'members', collaborators: selectedMembers, strategies: [] } },
+ * { objectId: objectIds[2], policy: null },
+ * ]);
+ * // A policy creates protection if absent, or updates the existing policy when already configured.
+ * for (const failure of result.failed) {
+ * console.error(failure.objectId, failure.error);
+ * }
+ * if (result.refreshError) {
+ * console.error(result.refreshError);
+ * }
+ * return result;
+ * }
+ * ```
+ */
+ async setObjectPermissions(changes: IObjectPermissionChange[]): Promise<IObjectPermissionBatchResult> {
+ return this._commandService.executeCommand<ISetObjectPermissionsCommandParams, IObjectPermissionBatchResult>(
+ SetDocumentPermissionsCommand.id,
+ { unitId: this._unitId, changes }
+ );
+ }
+
/**
* Sets one Document unit permission through the command system.
*
diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.ts
index 5d22fbed55..fd6f571a23 100644
--- a/packages/docs/src/index.ts
+++ b/packages/docs/src/index.ts
@@ -35,6 +35,7 @@ export { SetDocumentNameCommand } from './commands/commands/set-document-name.co
export type { ISetDocumentNameCommandParams } from './commands/commands/set-document-name.command';
export { SetDocumentPermissionCommand } from './commands/commands/set-document-permission.command';
export type { ISetDocumentPermissionCommandParams } from './commands/commands/set-document-permission.command';
+export { SetDocumentPermissionsCommand } from './commands/commands/set-document-permissions.command';
export { SetSectionHeaderFooterLinkCommand } from './commands/commands/set-section-header-footer-link.command';
export type { ISetSectionHeaderFooterLinkCommandParams } from './commands/commands/set-section-header-footer-link.command';
export { UpdateDocumentParagraphStyleCommand } from './commands/commands/update-document-paragraph-style.command';
@@ -43,6 +44,7 @@ export type { IDeleteDocumentSectionBreakCommandParams, IDocumentSectionConfig,
export { DocHistoryAction, RichTextEditingMutation, transformDocumentTextRanges } from './commands/mutations/core-editing.mutation';
export type { IRichTextEditingMutationParams } from './commands/mutations/core-editing.mutation';
export { SetDocumentPermissionRuleMutation } from './commands/mutations/set-document-permission-rule.mutation';
+export { SetDocumentPermissionRulesMutation } from './commands/mutations/set-document-permission-rules.mutation';
export { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';
export type { ISetTextSelectionsOperationParams } from './commands/operations/text-selection.operation';
export type { IUniverDocsConfig } from './config/config';
diff --git a/packages/docs/src/plugin.ts b/packages/docs/src/plugin.ts
index 541fb34ffd..d8ede39f14 100644
--- a/packages/docs/src/plugin.ts
+++ b/packages/docs/src/plugin.ts
@@ -34,6 +34,7 @@ import {
} from './commands/commands/set-document-default-paragraph-style.command';
import { SetDocumentNameCommand } from './commands/commands/set-document-name.command';
import { SetDocumentPermissionCommand } from './commands/commands/set-document-permission.command';
+import { SetDocumentPermissionsCommand } from './commands/commands/set-document-permissions.command';
import { SetSectionHeaderFooterLinkCommand } from './commands/commands/set-section-header-footer-link.command';
import { UpdateDocumentParagraphStyleCommand } from './commands/commands/update-document-paragraph-style.command';
import {
@@ -45,6 +46,7 @@ import {
import { RichTextEditingMutation } from './commands/mutations/core-editing.mutation';
import { DocsRenameMutation } from './commands/mutations/docs-rename.mutation';
import { SetDocumentPermissionRuleMutation } from './commands/mutations/set-document-permission-rule.mutation';
+import { SetDocumentPermissionRulesMutation } from './commands/mutations/set-document-permission-rules.mutation';
import { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';
import { defaultPluginConfig, DOCS_PLUGIN_CONFIG_KEY } from './config/config';
import { DocCustomRangeController } from './controllers/custom-range.controller';
@@ -83,10 +85,12 @@ export class UniverDocsPlugin extends Plugin {
override onStarting(): void {
this._injector.add([DocumentPermissionRuleModel]);
this.disposeWithMe(this._injector.get(ICommandService).registerCommand(SetDocumentPermissionRuleMutation));
+ this.disposeWithMe(this._injector.get(ICommandService).registerCommand(SetDocumentPermissionRulesMutation));
this.disposeWithMe(this._injector.get(ObjectPermissionService).registerRuleModel(
UnitObject.Document,
this._injector.get(DocumentPermissionRuleModel),
- SetDocumentPermissionRuleMutation.id
+ SetDocumentPermissionRuleMutation.id,
+ SetDocumentPermissionRulesMutation.id
));
this._initializeDependencies();
this._initializeCommands();
@@ -100,6 +104,7 @@ export class UniverDocsPlugin extends Plugin {
UpdateTextCommand,
CreateHeaderFooterCommand,
SetDocumentPermissionCommand,
+ SetDocumentPermissionsCommand,
SetDocumentDefaultParagraphStyleCommand,
SetDocumentNameCommand,
SetSectionHeaderFooterLinkCommand,