Skip to content
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

3.17: Module editRole and publishRole aren't correctly followed #3719

Open
ytilis opened this issue Apr 20, 2022 · 6 comments
Open

3.17: Module editRole and publishRole aren't correctly followed #3719

ytilis opened this issue Apr 20, 2022 · 6 comments
Labels

Comments

@ytilis
Copy link

ytilis commented Apr 20, 2022

To Reproduce

  1. Create a custom piece-type
  2. Set the following module options:
    editRole: 'contributor',
    publishRole: 'contributor',
  1. Contributors will not be able to publish, despite setting the publishRole to contributor

Expected behavior

editRole and publishRole options on a module should be followed by the permissions logic

Describe the bug

There are several related issues in the way permissions are handled, in and around this section of the permissions module.

The feedback I got on my initial report in the Discord channel from @boutell was as follows:

Hi @ytilis , those currently work well enough to allow image pieces to be published by contributors (implicitly), and to restrict editing of users to admins. I haven’t dug into the issue you were reporting but I wouldn’t say those options don’t work at all. I also wouldn’t say they’re guaranteed to work for every possible UI situation that could come up as a result of experimenting with them at the moment.

And this was a good question, since I'm positive those flags aren't actually working correctly, so I did a bunch of digging to find out why they appeared to be working in those scenarios, and here's what I've found, which does a better job explaining the issue than my original report:

Why it appears to work for images

Publishing Images works for contributors purely because of the autopublish flag. There's a code comment here on the doc-type module here that says:

If options.autopublishing is true, then the edit permission is sufficient, otherwise the publish permission is checked for

What this means is that by setting editRole: 'contributor', on @apostrophecms/image, you can in fact upload/publish images, BUT, if you then try to then edit an uploaded image, you can't due to the following code:

if (manager && manager.options.editRole && (ranks[role] < ranks[manager.options.editRole])) {
  return false;
} else if (mode === 'draft') {
  return (role === 'contributor') || (role === 'editor');
} else {
  return role === 'editor';
}

Since the initial image upload takes place in draft mode, autopublish's check that you can edit passes purely because contributors are allowed to edit drafts. But once it's published, even if publishRole and editRole are both set to contributor, the checks will still return false because after passing the module configured role checks, they're failing against the hardcoded roles in the subsequent elseif checks.

Why it appears to work for users

This is actually a pretty interesting, and very complicated, scenario for a few reasons, and can easily illustrate this bug, because setting edit and publish roles to editor on @apostrophecms/user works as expected, but setting them to contributor doesn't.

The fundamental issue is that you can raise any permission to editor or above, since a higher module specified role will fail the initial if statement and immediately return false, but you can never lower any permission below editor for editing or publishing, because once they pass the initial if statement, the else-ifs will continue enforcing the default assumed permission model.

Additionally it should be noted that admins short-circuit this entire permissions check group, as seen here so the hard checks against roles never effect them.

Proposed Solution

After looking more closely at this logic, I think my initial assumption and suggestion in Discord was actually incorrect. I assumed that the editRole and publishRole should've been the sole determiner, but I think this issue arose because the code was written to accommodate a lack of those options so it makes default assumptions. The trouble is those defaults always run when the module role check passes, effectively overriding the module configured permissions. My proposed solution is that if a publishRole, editRole, or viewRole is provided, the statement should simply return the role comparison, and if none is provided, then it should continue through the fallback else-ifs. So for example, the new editRole logic I mention above would instead look like this:

if (manager && manager.options.editRole) {
  return (ranks[role] >= ranks[manager.options.editRole]);
} else if (mode === 'draft') {
  return (role === 'contributor') || (role === 'editor');
} else {
  return role === 'editor';
}

Note the flipped < to >= and returning the comparison directly instead of false, thereby preventing the subsequent elseif checks from running.

A similar change would have to be made for publishRole and viewRole as well, which suffer from the same issues.

Details

Version of Node.js:
v14.18.3

Server Operating System:
macOS Monterey v12.3.1

@ytilis ytilis added the bug label Apr 20, 2022
@ytilis
Copy link
Author

ytilis commented Apr 20, 2022

Update

I wrote a project-level module to patch the issue I described above, and wound up running into another permissions issue downstream.

The MongoDB criteria defined in the permissions module restrict database edit queries to draft states only. This means that even with both edit and publish permission on the module level, contributors cannot actually edit content after publishing it, because they will get a database error from MongoDB due to the criteria restriction.

For example, trying to edit a published post won't return a document for the query in the publish function here because contributors are blocked from searching for documents they have edit rights to which aren't in the draft state. So when they trigger a publish due to their module-level permissions, it doesn't see the existing published document, resulting in an attempt to insert a new document with the same ID, which throws a MongoError: E11000 duplicate key error collection

Sorry if that explanation is difficult to follow, I admit I'm not the best at troubleshooting MongoDB query logic so this took me a bit of trial and error to diagnose.

@boutell
Copy link
Member

boutell commented Apr 21, 2022

Thanks for the clarification, I appreciate it.

@ytilis
Copy link
Author

ytilis commented Apr 22, 2022

So to fix this issue for our project in the short-term, I created a local override at modules/@apostrophecms/permission/index.js with the following content:

// Copied from the original file, since it's not exported
const ranks = {
  guest: 0,
  contributor: 1,
  editor: 2,
  admin: 3,
};

const checkRank = (userRole, minimumRole) => {
  return ranks[userRole] >= ranks[minimumRole];
};

module.exports = {
  extendMethods(self) {
    return {
      // Patches https://github.com/apostrophecms/apostrophe/issues/3719#issue-1209207160
      can(_super, req, action, docOrType, mode) {
        const defaultPermissions = _super(req, action, docOrType, mode);

        // Below vars use the same logic at the beginning of the default super function
        mode = mode || req.mode;
        const role = req.user && req.user.role;
        const type = docOrType && (docOrType.type || docOrType);
        const manager = type && self.apos.doc.getManager(type);

        // Explicitly recheck the module role level for the action if it exists
        const minimumRole = manager && manager.options[`${action}Role`];
        if (minimumRole) {
          return checkRank(role, minimumRole);
        }

        // Otherwise use the default return
        return defaultPermissions;
      },

      // Patches https://github.com/apostrophecms/apostrophe/issues/3719#issuecomment-1104457929
      criteria(_super, req, action) {
        const defaultCriteria = _super(req, action);

        // If there are no mode retrictions, we're fine with what we've already got
        if (!defaultCriteria.aposMode || !req.route) {
          return defaultCriteria;
        }

        // Only place to get the type right now is from the url as far as I can tell
        const apiPrefix = '/api/v1/';
        const { path } = req.route;
        const type = path.slice(
          path.indexOf(apiPrefix) + apiPrefix.length,
          path.indexOf('/:_id'),
        );
        const manager = type && self.apos.doc.getManager(type);

        const role = req.user && req.user.role;

        if (action === 'edit') {
          if (role === 'contributor') {
            // Explicitly recheck the module publish role to see if we can edit those
            const minimumRole = manager && manager.options.publishRole;
            if (minimumRole && checkRank(role, minimumRole)) {
              delete defaultCriteria.aposMode;
            }
          }
        }

        return defaultCriteria;
      },
    };
  },
};

Not sure if there's a better way to get which piece-type is being checked, as the only place I was seeing it in the request was in the url itself. Any suggestions are welcome, as to be honest I'm not entirely happy with the way I'm handling the db criteria change right now.

@boutell
Copy link
Member

boutell commented Oct 11, 2022 via email

@itsajay1029
Copy link

Hey @boutell , can you assign me this issue so that I can get started working on it ?

@boutell
Copy link
Member

boutell commented Nov 7, 2022

@itsajay1029 there's quite a bit of work here already on this ticket, I think it might make more sense for us to internally review what @ytilis has done. We have also shipped @apostrophecms-pro/advanced-permission, you can learn more about that here:

https://apostrophecms.com/extensions/advanced-permission

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants