gun icon indicating copy to clipboard operation
gun copied to clipboard

ACL, Authentication, Security, Permissions, Authorization, etc.

Open scottmas opened this issue 9 years ago • 34 comments

Hey, I've been fiddling around and after some time trying to get authentication to work, I discovered the rug had been pulled out from underneath me so to speak, since lib/wsp.js was never being used (as found in node_modules), but that actually lib/wsp/server.js was being used! The duplication of wsp functionality has been removed in the latest master, but there's still no way to do authentication as per the example at https://github.com/amark/gun/blob/master/examples/express-auth.js or on Stack Overflow stackoverflow.com/questions/38598391/jwt-authentication-with-gundb!

It's understandable that things are in flux with GunDB being such a young library, but it would be really nice if the code and the examples could be updated to reflect that, or at least commented informatively.

Also, is there any timeline on authentication? It essential for using GunDB on anything but trivial apps.

scottmas avatar Feb 22 '17 10:02 scottmas

Indeed, thank you for reporting this! Things have definitely been switched around and not updated, let me reply with some more details in a bit. How are you? What are you building?

amark avatar Feb 22 '17 19:02 amark

👍 Need documentation about that indeed ...

solisoft avatar Feb 22 '17 20:02 solisoft

Might be delayed... I need to do some client work which is prioritizing SQLite integration and indexing with gun over this. But it is definitely coming (including some example apps), I wanted to do a quick check:

Are you looking for P2P auth examples, or classic/traditional auth?

amark avatar Feb 22 '17 20:02 amark

I'll say both By the way I didn't find documentation about clustering... am i missing something?

solisoft avatar Feb 22 '17 21:02 solisoft

Oh ;) that is helpful - gonna start with the P2P auth first, the other one will take longer to get around too.

Clustering happens automatically between connected peers, so Gun(['http://localhost:8080/gun', 'http://localhost:8081/gun']) is something you can test pretty quickly. Spin up a couple gun servers on those ports, have browsers join, etc. :)

Or is there something specific about "clustering" you are wanting to do?

amark avatar Feb 22 '17 21:02 amark

I have this cool test I'm trying to pull into core... where I'l have browser <--> server <--> server <--> browser sync. So if anything goes wrong, let me know, last time I ran it it worked - trying to automate the tests on it in this v0.6.x series.

amark avatar Feb 22 '17 21:02 amark

I'll test it today I'll let you know, thanks

solisoft avatar Feb 23 '17 07:02 solisoft

Hey sorry to take a sec to respond, I should really be more up on my Github!

But I'm looking to create a more traditional auth app (a forum basically), where I tightly control all the data that gets written to my servers (and by extension S3).

What I'm really looking for (and what I think would be beautiful) would be a way to (1) be able to attach sessions to a websocket channel via JWT's and (2) be able to create auth handlers via regex globs. You'll have to forgive my lack of expertise with websockets, but something like this:

var gunWebsocket = wsp(httpServer); //initialize websocket 
gunWebsocket.authenticate(function(jwt){
  //Decode & verify jwt
  //Attach the decoded jwt data to every websocket request
})

gunWebsocket.onWrite('/users/*', function(incoming, existing, jwtSessionData){
   //`incoming` and `existing` are traversable objects beginning at where 
   //the glob begins, with an api similar to that exposed by the traverse
   //library at https://www.npmjs.com/package/traverse
      
   const userId = jwtSessionData.userId;
   const role = jwtSessionData.role;
   if(incoming.key === userId && existing.key === userId || role === 'admin'){      
       //I can modify the incoming data however I want. Obviously this would need
       // to get synced back to the client
       incoming.set('/_meta/lastUpdated', Date.now())
       
       if(role === 'admin'){
          incoming.set('/_meta/lastAdminUpdated', Date.now())
       }
       
       //before we write, verify the data is well structured
       throwIfNotValidStructure(incoming)

       return incoming  
   } else{
      throw new Error('Unauthenticated write!')
   }
})

I don't know enough of Gun's internals to even know if this is possible, but to my mind a system like this is simply a hugely improved and more fine grained version of Firebase security rules, and would go a looooong way towards making GunDB my go to db instead of Firebase (which I've used a lot).

scottmas avatar Feb 24 '17 16:02 scottmas

Also, it's super important to protect certain data from being exposed to the client. And I have no clue how you would implement this given the auto syncing nature of GunDB, but something like the following would also be hugely important:

gunWebsocket.onRead('/users/:userId/secret/*', function(existingData, jwtSessionData){
   const userId = jwtSessionData.userId;
   const role = jwtSessionData.role;
   if(existingData.parent().key === userId  || role === 'admin'){      
     //Let the current user or admin see the secret data
     return existingData;
   } else{
     //Everyone else only sees the public information
     return null;
   }
})

scottmas avatar Feb 24 '17 16:02 scottmas

@scottmas thanks so much for laying out your ideal, that will be helpful.

I'm so sorry I still haven't been able to reply to this yet - my wife is defending her PhD today, and things have been hectic.

Want to drop just a few notes - but I will need to re-read your comments in full to reply better. So apology for the lacking response:

I just wrote a new websocket adapter here: https://github.com/amark/gun/blob/master/lib/uws.js , it is actually pretty simple and if you look at the receive function you can easily add your own conditional security logic before calling gun.on('in' (or reject calling it). Any code you write there should be compatible with the long term solution we provide.

For the non-centralized setup, it is really important that people check out our security series: http://gun.js.org/explainers/data/security.html , and somebody already wrote a prototype login system here: https://github.com/swifty/gun-p2p-auth .

So there is actually a lot of work going on for this stuff already. It is just kinda scattered right now and that is why this issue should stay open - until we bring it all together in documentation.

Will reply more later.

amark avatar Feb 24 '17 19:02 amark

@scottmas I like for the most part your ideal, one "problem" though is that in a graph:

var mark = {name: "Mark"};
var cat = {name: "Timber", species: "kitty"};
mark.boss = cat;
cat.slave = mark;

if both mark and cat are accessible via gun.get('mark') and gun.get('cat') we have a "problem".

The data is accessible through 2 routes. gun.get('mark').get('boss').on(cb) gives me the cat, and gun.get('cat').on(cb) gives me the cat. Likewise for mark.

So:

(1) For a auth system, do we force people to strictly have hierarchal data?

(2) If not, how should auth be specified? On a per-record basis? Some other way?

These are actual open questions I'd be curious to hear from people.

amark avatar Feb 25 '17 00:02 amark

@amark That's a good point, a node might have multiple paths leading to it so it's not safe to just protest the path.

I think a protected node (or maybe data in the node?) would be the way to go. That way you don't accidentally expose data that should not be public.

Now the question becomes: where does the logic live to show/hide this sensitive data?

The example from @scottmas is more like the traditional server endpoint auth which would prevent the sync.

Another way might be defining the OnRead function on the node itself so that it can be blocked, regardless of the path used to reach the node. However I don't know when Gun actually performs a sync between server/client. So this solution may not be possible.

styfle avatar Feb 26 '17 13:02 styfle

@styfle yeah this is what I'm thinking as well.

For the non-P2P approach, you'd flip on "secure" mode and NOTHING would sync by default.

In order for anything to sync, you'd have to add to every single node (object) a read/write token. Then on sync (which yes, works between server/client) there would be a callback for every node which would let you conditionally whitelist the node if the session token and the read/write token matches in whatever way you define.

For the P2P approach, you'd flip on "secure" and EVERYTHING would be ENCRYPTED but any data could still sync - and the encryption logic itself would determine read/write access.

amark avatar Feb 27 '17 01:02 amark

@amark When does the sync happen? Presumably the entire graph is not synced to every client until the node is accessed right?

styfle avatar Feb 27 '17 14:02 styfle

Having the security be on the route rather than the data is a feature I think, rather than a bug. For instance, I can temporarily give a user read only access to otherwise protected data. Traditional REST api's also do security like this, on a per route basis, rather than living with the data.

Is per route security simply not easily implementable though in a graph database? Is there meta information attached to each node in GunDB? Could that be purposed to implement it?

I hesitate to advocate a non-route based security approach. For better or for worse, the route based approach is what people are used to, and arguably it's the easiest for programmers to reason about when they're building applications.

scottmas avatar Feb 27 '17 17:02 scottmas

@styfle correct, only data that the client requests is what gets loaded. (Although note: the ad hoc mesh network does relay data, but this is at the "network" level not the "app" level, and was easy to turn off if necessary)

@scottmas so maybe the assumption is even though there might be multiple ways to load the data in a graph, unless you load it THROUGH the known route then it won't authenticate? (yes meta data exists on each node).

Agreed that it is the easiest, but you would loose a ton of useful functionality - but that would just be a tradeoff? Unless we get a paid request for this (like we have on other features) it will probably be a very low priority on my personal list because a "graph enabled" authentication model will ultimately be more useful/powerful/flexible (even if :( initially not as "easy", easy can be added later). More than happy to help you out on how to build a route based system though, if you are up for contributing?

amark avatar Mar 01 '17 18:03 amark

I think that a solution for server based authorization is absolutely critical before using Gun is a production application. The P2P encryption solution is interesting, but could be difficult to apply in most applications.

I agree that it would be a shame to loose the graph capabilities of Gun so I'm hoping that a solution can be developed on top of the full power of Gun.

In my experience there are two levels of authorization needed in the central model.

  1. Tenant separation

A tenant could be a customer or even a user in some systems. Essentially there should be hard lines drawn in the data that would prevent access to unauthorized nodes in the graph. The system for this should be dead simple and hard for a developer to miss a node and cause a security breach.

In Postgres this might mean making a separate schema under a database. In PouchDB/CouchDB the solution is to create separate databases. Maybe each tenant needs a separate Gun instance but I hope not.

I think that there should be simple way to apply a "locker id" to every node in the graph so that every write adds the locker id and every read checks for it. Maybe this is at the level of the module API?

  1. Application logic

There are some really complex scenarios that I think are not going to be served by simply adding some metadata to each node in the graph.

Let's say Bobby Manager leads a team and is responsible for assigning tasks. His organization has a structure of teams with a subset of users in each team. He should only be able to read the tasks of his team, and can only edit the assingee attribute on those task nodes. He can only set the assignee to members of his team.

This kind of scenario would normally be handled by the application server rather than the database. But it's also important enough that we wouldn't want to leave it to the JavaScript in the browser. From the videos I get the sense that Gun is trying to merge the concept of the database and the application server.

Maybe this could be handled by the module API as well, but I'm curious how we could make this easier. Handling validation failure in the distributed system would also be an interesting discussion.

acarl avatar Mar 10 '17 12:03 acarl

What would also be helpful if people could post examples of other systems they've worked with. Firebase's JSON strings, etc. if we pool enough examples of existing literature and experience out there, I think that will give us insight/intuition on "what is the best" approach.

amark avatar Mar 12 '17 01:03 amark

Hi @amark,

Thought i'd add some more info for everyone here.

Firebase data security documentation can be found here. You can also find additional information about Firebase Security Rules and Authentication Strategies.

A per-record basis sounds right, which is something i've seen implemented a lot. A document should be completely self contained, with all the required information available for any application level decision making.

Firebase take the following approach per document/record which I think is a good fit.

Rule Types
.read Describes if and when data is allowed to be read by users
.write Describes if and when data is allowed to written
.validate Defines what a correctly formatted value will look like, whether it has child attributes, and the data type

Note .validate is a seperate issue but worth considering.

The following security rule allows read/write access globally to the node /foo.

{
  "rules": {
    "foo": {
      ".read": true,
      ".write": true,
    }
  }
}

Here is an example of a cascading rule;

{
  "rules": {
     "foo": {
        ".read": "data.child('baz').val() === true",
        "bar": {
          ".read": false
        }
     }
  }
}

The above security rule allows /bar/ to be read from whenever /foo/ contains a child baz with the value true. The ".read": false rule under /foo/bar/ has no effect here, since access cannot be revoked by a child path.

The above structure would allow very complex access privileges to be implemented with minimal effort and would cater to a wide variety of use cases.

The above is a small snippet of the Firebase implementation for more information please visit the security-data docs.

I hope this proves useful Mark 😄

mindvox avatar Jul 27 '17 08:07 mindvox

Graphql rule has some great patterns for access control. It is much more flexible than Firebase rules, since it allows you to write arbitrary scripts and pass arbitrary session identifiers. https://github.com/joonhocho/graphql-rule

scottmas avatar Jul 28 '17 10:07 scottmas