8000 Vendorize `cancan` with performance improvements by tommoor · Pull Request #7448 · outline/outline · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Vendorize cancan with performance improvements #7448

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion package.json
10000
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@
"babel-plugin-transform-class-properties": "^6.24.1",
"body-scroll-lock": "^4.0.0-beta.0",
"bull": "^4.12.2",
"cancan": "3.1.0",
"chalk": "^4.1.0",
"class-validator": "^0.14.1",
"command-score": "^0.1.2",
Expand Down
188 changes: 182 additions & 6 deletions server/policies/cancan.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,189 @@
import CanCan from "cancan";
import isObject from "lodash/isPlainObject";
import { Model } from "sequelize-typescript";
import { AuthorizationError } from "@server/errors";

type Constructor = new (...args: any) => any;

type Condition<T extends Constructor, P extends Constructor> = (
performer: InstanceType<P>,
target: InstanceType<T> | null,
options?: any
) => boolean;

type Ability = {
model: Constructor;
action: string;
target: Constructor | Model | string;
condition?: Condition<Constructor, Constructor>;
};

/**
* Class that provides a simple way to define and check authorization abilities.
* This is originally adapted from https://www.npmjs.com/package/cancan
*/
export class CanCan {
public abilities: Ability[] = [];

/**
* Define an authorized ability for a model, action, and target.
*
* @param model The model that the ability is for.
* @param actions The action or actions that are allowed.
* @param targets The target or targets that the ability applies to.
* @param condition The condition that must be met for the ability to apply
*/
public allow = <T extends Constructor, P extends Constructor>(
model: P,
actions: string | ReadonlyArray<string>,
targets: T | ReadonlyArray<T> | string | ReadonlyArray<string>,
condition?: Condition<T, P> | object
) => {
if (
typeof condition !== "undefined" &&
typeof condition !== "function" &&
!isObject(condition)
) {
throw new TypeError(
`Expected condition to be object or function, got ${typeof condition}`
);
}

if (condition && isObject(condition)) {
condition = this.getConditionFn(condition);
}

(this.toArray(actions) as string[]).forEach((action) => {
(this.toArray(targets) as T[]).forEach((target) => {
this.abilities.push({ model, action, target, condition } as Ability);
});
});
};

/**
* Check if a performer can perform an action on a target.
*
* @param performer The performer that is trying to perform the action.
* @param action The action that the performer is trying to perform.
* @param target The target that the action is upon.
* @param options Additional options to pass to the condition function.
* @returns Whether the performer can perform the action on the target.
*/
public can = (
performer: Model,
action: string,
target: Model | null | undefined,
options = {}
) => {
const matchingAbilities = this.abilities.filter(
(ability) =>
performer instanceof ability.model &&
(ability.target === "all" ||
target === ability.target ||
target instanceof (ability.target as any)) &&
(ability.action === "manage" || action === ability.action)
);

// Check conditions only for matching abilities
return matchingAbilities.some(
(ability) =>
!ability.condition ||
ability.condition(performer, target, options || {})
);
};

/**
* Check if a performer cannot perform an action on a target, which is the opposite of `can`.
*
* @param performer The performer that is trying to perform the action.
* @param action The action that the performer is trying to perform.
* @param target The target that the action is upon.
* @param options Additional options to pass to the condition function.
* @returns Whether the performer cannot perform the action on the target.
*/
public cannot = (
performer: Model,
action: string,
target: Model | null | undefined,
options = {}
) => !this.can(performer, action, target, options);

/**
* Guard if a performer can perform an action on a target, throwing an error if they cannot.
*
* @param performer The performer that is trying to perform the action.
* @param action The action that the performer is trying to perform.
* @param target The target that the action is upon.
* @param options Additional options to pass to the condition function.
* @throws AuthorizationError If the performer cannot perform the action on the target.
*/
public authorize = (
performer: Model,
action: string,
target: Model | null | undefined,
options = {}
): asserts target => {
if (this.cannot(performer, action, target, options)) {
throw AuthorizationError("Authorization error");
}
};

// Private methods

private get = (obj: object, key: string) =>
"get" in obj && typeof obj.get === "function" ? obj.get(key) : obj[key];

private isPartiallyEqual = (target: object, obj: object) =>
Object.keys(obj).every((key) => this.get(target, key) === obj[key]);

private getConditionFn =
(condition: object) => (performer: Model, target: Model) =>
this.isPartiallyEqual(target, condition);

private toArray = (value: unknown): unknown[] => {
if (value === null || value === undefined) {
return [];
}
if (Array.isArray(value)) {
return value;
}
if (typeof value === "string") {
return [value];
}
if (typeof value[Symbol.iterator] === "function") {
// @ts-expect-error - TS doesn't know that value is iterable
return [...value];
}

return [value];
};
}

const cancan = new CanCan();

export const _can = cancan.can;
export const { allow, can, cannot, abilities } = cancan;

// This is exported separately as a workaround for the following issue:
// https://github.com/microsoft/TypeScript/issues/36931
export const authorize: typeof cancan.authorize = cancan.authorize;

// The MIT License (MIT)

export const _authorize = cancan.authorize;
// Copyright (c) Vadim Demedes <vdemedes@gmail.com> (github.com/vadimdemedes)

export const _cannot = cancan.cannot;
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

export const _abilities = cancan.abilities;
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

export const allow = cancan.allow;
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
2 changes: 1 addition & 1 deletion server/policies/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import invariant from "invariant";
import some from "lodash/some";
import { CollectionPermission, DocumentPermission } from "@shared/types";
import { Collection, User, Team } from "@server/models";
import { allow, _can as can } from "./cancan";
import { allow, can } from "./cancan";
import { and, isTeamAdmin, isTeamModel, isTeamMutable, or } from "./utils";

allow(User, "createCollection", Team, (actor, team) =>
Expand Down
2 changes: 1 addition & 1 deletion server/policies/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
TeamPreference,
} from "@shared/types";
import { Document, Revision, User, Team } from "@server/models";
import { allow, _cannot as cannot, _can as can } from "./cancan";
import { allow, cannot, can } from "./cancan";
import { and, isTeamAdmin, isTeamModel, isTeamMutable, or } from "./utils";

allow(User, "createDocument", Team, (actor, document) =>
Expand Down
70 changes: 13 additions & 57 deletions server/policies/index.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,11 @@
import type {
ApiKey,
Attachment,
AuthenticationProvider,
Collection,
Comment,
Document,
FileOperation,
Integration,
Pin,
SearchQuery,
Share,
Star,
Subscription,
User,
Team,
Group,
WebhookSubscription,
Notification,
UserMembership,
} from "@server/models";
import { _abilities, _can, _cannot, _authorize } from "./cancan";
import type { Model } from "sequelize-typescript";
import type { User } from "@server/models";
import { abilities, can } from "./cancan";

// export everything from cancan
export * from "./cancan";

// Import all policies
import "./apiKey";
import "./attachment";
import "./authenticationProvider";
Expand All @@ -42,48 +28,18 @@ import "./userMembership";

type Policy = Record<string, boolean>;

// this should not be needed but is a workaround for this TypeScript issue:
// https://github.com/microsoft/TypeScript/issues/36931
export const authorize: typeof _authorize = _authorize;

export const can = _can;

export const cannot = _cannot;

export const abilities = _abilities;

/*
* Given a user and a model – output an object which describes the actions the
* user may take against the model. This serialized policy is used for testing
* and sent in API responses to allow clients to adjust which UI is displayed.
*/
export function serialize(
model: User,
target:
| ApiKey
| Attachment
| AuthenticationProvider
| Collection
| Comment
| Document
| FileOperation
| Integration
| Pin
| SearchQuery
| Share
| Star
| Subscription
| User
| Team
| Group
| WebhookSubscription
| Notification
| UserMembership
| null
): Policy {
export function serialize(model: User, target: Model | null): Policy {
const output = {};
abilities.forEach((ability) => {
if (model instanceof ability.model && target instanceof ability.target) {
if (
model instanceof ability.model &&
target instanceof (ability.target as any)
) {
let response = true;

try {
Expand Down
2 changes: 1 addition & 1 deletion server/policies/share.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Share, Team, User } from "@server/models";
import { allow, _can as can } from "./cancan";
import { allow, can } from "./cancan";
import { and, isOwner, isTeamModel, isTeamMutable, or } from "./utils";

allow(User, "createShare", Team, (actor, team) =>
Expand Down
59 changes: 0 additions & 59 deletions server/typings/cancan.d.ts

This file was deleted.

Loading
Loading
0