moleculerjs / moleculer-web

:earth_africa: Official API Gateway service for Moleculer framework
http://moleculer.services/docs/moleculer-web.html
MIT License
291 stars 118 forks source link

sanitize properties from response #218

Closed mariusbackes closed 3 years ago

mariusbackes commented 3 years ago

On your moleculer action you can set the sanitize property. It is an array of strings or objects, which is used to sanitize the REST response. If the parameter in the array is a string, it will be removed from the response. If the parameter is an object the property name will be updated from the old one to the new one.

For example: You have an user object. And on this object, the password from the user is present. But you don't want to send it back to the user:

let user = {
  id: "userId",
  name: "name",
  password: "super-secret-password"
}

In your moleculer action, provide the sanitize param, to know which properties should be removed or updated.

actions: {
  getUser: {
    ...
    sanitize: ["password", {from: "id", to: "userId"}]
    handler(ctx) { ... }
  }
}

The response looks like this:

let user = {
  userId: "userId",
  name: "name"
}

If the response is an array, the sanitizing is done for each object.

It works also with nested objects:

let user = {
  id: "userId",
  name: "name",
  password: "super-secret-password",
  setting: {
    id: "settingId",
    privateKey: "super-secret-private-key"
  }
}

For nested object, the nested string is given by dot-notation:

actions: {
  getUser: {
    ...
    sanitize: ["password", {from: "id", to: "userId"}, "setting.privateKey", {from: "setting.id", to: "setting.settingId"}]
    handler(ctx) { ... }
  }
}
coveralls commented 3 years ago

Pull Request Test Coverage Report for Build 533


Changes Missing Coverage Covered Lines Changed/Added Lines %
src/index.js 17 18 94.44%
<!-- Total: 17 18 94.44% -->
Totals Coverage Status
Change from base Build 530: -0.03%
Covered Lines: 721
Relevant Lines: 745

💛 - Coveralls
AndreMaz commented 3 years ago

Hey @mariusbackes Thank you very much for your effort. Unfortunately I think that the proposed approach introduces some issues. I will try to explain what I mean.

I think that each service should be responsible for cleaning/filtering its own data. In other words, data cleaning should be responsibility of the "data owner" (i.e., the service) not the gateway. Your approach solves the problem of "leaking" sensible data via the gateway but it doesn't solve for "regular" calls from other services.

I also think that this approach adds additional load for the transporter and especially for the api gateway.

Finally, I think that the desired behavior can be easily achieved with the actions after hooks.