loopback icon indicating copy to clipboard operation
loopback copied to clipboard

Disable all remote methods and enable only selected ones (white-list)

Open voitau opened this issue 12 years ago • 75 comments

There is a bunch of existing open/closed issues with questions how to hide the method of the model. My question is about how can all the methods be disabled first and then enabled only those which are necessary? (basically, duplicates this comment: https://github.com/strongloop/loopback/issues/465#issuecomment-54851858)

Here is the simple function which hides all the methods of the model:

/**
 * Hides all the methods besides those in 'methods'.
 *
 * @param Model model to be updated.
 * @param methods array of methods to expose, e.g.: ['find', 'updateAttributes'].
 */
var setMethodsVisibility = function(Model, methods) {
  methods = methods || [];
  Model.sharedClass.methods().forEach(function(method) {
    method.shared = methods.indexOf(method.name) > -1;
  });
};

However, it doesn't hide two groups:

  • remote methods, which have to be hidden like this: Model.disableRemoteMethod(name, isStatic)
  • custom methods, like User.login or User.resetPassword (didn't find any way to hide them at all);

Could you please advise what would be the correct way to hide everything (without specific call for each method by its name explicitly) and allow only the methods which are necessary?

voitau avatar Oct 15 '14 19:10 voitau

@ericprieto sure, thank you for your code.

ratik avatar Jan 26 '16 07:01 ratik

@ratik thanks mate :)

ghost avatar Jan 26 '16 20:01 ghost

@ericprieto thanks!

leolannenmaki avatar Jan 29 '16 09:01 leolannenmaki

@ericprieto hey thanks for the code man!!, works great and saved me a lot of time!! ;P

Alons-Oh avatar Feb 03 '16 20:02 Alons-Oh

@ericprieto works great. I used the @ratik mixin variant though. That way I could define what methods are expose in the model.json files.

christiaanwesterbeek avatar Mar 12 '16 22:03 christiaanwesterbeek

try this loopback-remote-routing

JoeShi avatar May 10 '16 11:05 JoeShi

Rather than separately defining the defined methods, I wanted to only include methods supported by my model's ACLs. So, building on @ericprieto's solution, I added:

function disableUnauthorizedMethods (model) {
  const acls = model.definition.settings.acls || [];
  let authorizedMethods = [];

  acls.forEach((acl) => {
    if (acl.permission === 'ALLOW' && acl.property) {
      if (Array.isArray(acl.property)) {
        authorizedMethods = authorizedMethods.concat(acl.property);
      }
      else if (acl.property !== '*') {
        authorizedMethods.push(acl.property);
      }
    }
  });

  disableAllMethods(model, authorizedMethods);
}

Hope that helps someone. If anyone has a scenario where you wouldn't always want the available methods to map to the ACL definitions, I'd be interested to hear it (I'm fairly new to Loopback and may have overlooked something!).


Edited

Rather than call disableUnauthorizedMethods from JS, you can add it as a mixin:

const {disableUnauthorizedMethods} = require('../services/model');

module.exports = (Model) => { // eslint-disable-line
  Model.on('attached', () => disableUnauthorizedMethods(Model));
};

Or, you can add it your boot script and run it for all models:

const {disableUnauthorizedMethods} = require('../services/model');

module.exports = (app) => {
  Object.keys(app.models).forEach((modelName) => {
    const model = app.models[modelName];
    disableUnauthorizedMethods(model);
  });
};

The latter example does disable the methods, but they will still appear in the Swagger output as the boot script is run after the Swagger stuff is generated. Not sure how to get around this so instead I've created a base model SPersistedModel, activated the mixin for the base class, and extended this for my own custom classes.

PaddyMann avatar May 17 '16 07:05 PaddyMann

I had the same problem.

My first solution was to manually update the "public":true items in server/model-configuration.json but it was overridden anytime I used the Swagger tool to refresh the LoopBack API (with slc loopback:swagger myswaggerfilename command from the project root).

I finally wrote a Grunt task as a reliable workaround.

  • Run it just after a slc loopback:swagger generation or just before running the API live.
  • you just have to specify the names of the paths I want to expose in the javascript array list_of_REST_path_to_EXPOSE
  • and make sure you are happy with the backup folder for the original /server/model-config.json file.

I wanted to share it with you in case you would be interested :

https://github.com/FranckVE/grunt-task-unexpose-rest-path-loopback-swagger

FranckVE avatar May 23 '16 12:05 FranckVE

I have an idea: how about adding a model-level setting to control the default behaviour (all methods are public, all methods are private) and then allow models to provide overrides in the "methods" section. These overrides can change not only method visibility, but also other metadata like the description used by swagger generator - IIRC there is an issue asking for this feature, but I cannot find it right now :(

Example of a model definition that exposed only "find" method:

{
  name: "Car",
  defaultMethodVisibility: "private", // or "public"
  methods: {
    find: {
      public: true,
      description: "custom description"
    }
  }
}

bajtos avatar Jun 02 '16 08:06 bajtos

I'm keen to see a better standard here, but I feel there's a confusing overlap between whether not you can see a route exists (visibility) and whether or not you can use that route:

  • We already had ACLs to define whether or not a route can be accessed. It's really weird that a route I've defined as being completely inaccessibly in my ACLs would require a separate configuration to say that I don't want it to appear in Swagger (of course I don't!). And the same applies for routes are accessible - if I've set up an ACL saying it's accessible, I don't want to have to also configure that it should be visible.
  • There's also a real risk that beginners will mark a route as private, see that it's not in Swigger, and then assume that it's secure.

I think the default behaviour should be that routes that are completely inaccessibly in the ACLs are hidden in Swagger, and all other routes are displayed. This encourages good design and makes it much easier to review your ACLs are working when quickly prototyping.

I understand there's a use-case for making a route 'private' (or, to borrow a better term from CSS, 'hidden'), but suggest a solution where this is still configured using ACLs.


Suggested solution

In my model (using existing behaviour):

"name": "Project",
"plural": "projects",
"acls": [
  {
    "principalType": "ROLE",
    "principalId": "siteAdmin",
    "permission": "ALLOW",
    "property": [
      "updateById"
    ]
  },
  {
    "principalType": "ROLE",
    "principalId": "$authenticated",
    "permission": "ALLOW",
    "property": [
      "find",
      "findById"
    ]
  },
  {
    "accessType": "*",
    "principalType": "ROLE",
    "principalId": "$everyone",
    "permission": "DENY",
    "property": "*"
  }
],

In config.json (this is new - feel free to adapt the terms and where this config sits to better fit into the loopback ecosystem):

{
  "swagger": {
    "hiddenAclPrincipleIds": [
      "siteAdmin"
    ]
  }
}

Resulting behaviour:

  • Swagger shows GET /projects and GET /projects/:id - these are accessible to all logged in users
  • Swagger does not show PUT /projects/:id. It's accessible to site admins (thanks to our role resolver), but hidden by the config setting
  • Swagger does not show any other routes. There's no way to access them thanks to our DENY $everyone

Thoughts?

PaddyMann avatar Jun 02 '16 12:06 PaddyMann

+1

cgole avatar Jun 03 '16 21:06 cgole

@bajtos Maybe server/model-config.json is a better place to allow such customizations.

IMO, there are multiple aspects:

  1. What methods are defined to be remoteable? (With remoting metadata)
  2. What remote methods should be exposed to REST? (By default, all remoteable methods are)
  3. What remote methods should be exposed to Swagger? (By default. all remote methods from 2)
  4. How does ACL play a role in the visibility?

raymondfeng avatar Jun 03 '16 21:06 raymondfeng

I believe we shouldn't use ACL to do this, as it can be dynamic and it will make it harder to reason about.

faridnsh avatar Jun 04 '16 03:06 faridnsh

Perhaps... though:

  1. Surely the security of whether or not the routes can be called is the most important bit? (so if it's difficult to reason about this because the ACLs can be dynamic, then perhaps that's an issue in itself and is more important to resolve)
  2. If the ACLs and the visibility are totally disconnected, then I'm betting that's going even be an even bigger headache for reasoning about
  3. Normally we wouldn't have Swagger to generate the result of the dynamic rules. The beauty here is that we do, and so it would become very easy to review the result of these (and reason with the result)

That said, I'm not suggesting that my way is best. It'd be great if someone would review how the other frameworks do it (Rails, Yii2, Django, Laravel, etc.) and work out what the consensus is / what works best.

PaddyMann avatar Jun 07 '16 15:06 PaddyMann

+1

gxvigo avatar Jun 09 '16 00:06 gxvigo

FWIW, as of https://github.com/strongloop/loopback/pull/1667, one can white/black-list methods in the model-config by setting

"options": {
  "remoting": {
    "sharedMethods": {
      "*": false, // disable all methods
      "create": true // enable (white-list) create only
    }
  }
}

bajtos avatar Oct 13 '16 07:10 bajtos

@voitau: as described by @bajtos in above solution, you can white/black list methods for a particular model in server/model-config.json file; it will look like, for a model named MyModel:

server/model-config.json

  "MyModel": {
    "dataSource": "db",
    "public": true,
    "options":{
      "remoting": {
      "sharedMethods": {
        "*": false,
        "create": true
      }
     }
    }
  },

Closing now. Should you need any further assistance, please comment here and I'll be happy to help. Thank you.

gunjpan avatar Oct 13 '16 13:10 gunjpan

@bajtos @gunjpan Using this:

"MyModel": {
    "dataSource": "db",
    "public": true,
    "options":{
      "remoting": {
      "sharedMethods": {
        "*": false,
        "create": true
      }
     }
    }
  }

I can hide the related models end points like for example __get__tags because I have tried this:

"MyModel": {
    "dataSource": "db",
    "public": true,
    "options":{
      "remoting": {
      "sharedMethods": {
        "*": false,
        "create": true,
        "__get__tags": false
      }
     }
    }
  }

And it is now working?!

ahmed-abdulmoniem avatar Oct 14 '16 10:10 ahmed-abdulmoniem

@ahmed-abdulmoniem : Hi, I tried to reproduce it and found that this functionality is limited to the model's methods only ATM. I'll create a new issue to expand the coverage of this feature to methods attached to model by applying relations.

Thank you for reporting. And, please feel free to submit a patch for this and we will help along the way to get it landed.

gunjpan avatar Oct 14 '16 13:10 gunjpan

@gunjpan Thank you.

ahmed-abdulmoniem avatar Oct 14 '16 14:10 ahmed-abdulmoniem