moleculerjs / moleculer-db

:battery: Database access service mixins for Moleculer
https://moleculer.services/
MIT License
152 stars 121 forks source link

Should we allow custom populate params? #311

Open 0x0a0d opened 2 years ago

0x0a0d commented 2 years ago

Hi @icebob,

Currently, how populate receive & send params, is predefined on settings.populates, I wonder if we can make it more flexible. Instead of populate: string[], we can accept populate as object like

{
  fields: ["dynamic-limited-fields"]
}

Example: I only need populate user.get with field name but sometime need field username

0x0a0d commented 2 years ago

I think we can allow to custom fields and mapping

image

0x0a0d commented 2 years ago

Custom mapping may crash app because it returns object instead array

In fact, caller can change return from fields populate by set ctx.params.fields likes

{
"fields": "user.username", // only return username on user populate
}

but if users is an array, ctx.params.fields can not use to filter fields (both on web api call and broker call) So if we can flexible like this

{
  populate: [{
    populate: "user",
    fields: ["username", "name"]
  }, "another-old-style-populate"]
}

will amazing :D

icebob commented 2 years ago

I planned it sometimes about it in the past but always dropped the idea because it can leak sensitive data if the user can change the returned fields. E.g. you have a posts service that has a populated field "author". The author's email address is sensitive data, so posts listing action must not access this field.

So it can work only if there is an "allowed populate fields" which contains all available fields and the caller can't add fields which is not allowed.

0x0a0d commented 2 years ago

Please check my code If settings.populates[X] has a fields, we will call authorizeFields to limit populate fields of caller

0x0a0d commented 2 years ago

https://github.com/moleculerjs/moleculer-db/blob/024e74066528b61797011935425b70747c14a8d1/packages/moleculer-db/src/index.js#L647 Is this bug? Rule does not have populate, if user want to populate, he must put it in params.populate

Document https://moleculer.services/docs/0.14/moleculer-db.html#Populating