GraphQL implement "not permitted" - node.js

I have a GraphQL API that is governed by a permission system that I implemented.
I tried going with Graphql-shield but I didn't want to error out on the whole request if the client requests a forbidden field, so instead I implemented my own permission system.
Now, I need to solve a problem:
The way I implemented the permission system means that every field is checked if it is permitted and if it is not then null is returned. However, I would like to return some indication that the field was not actually null but that the field was "not permitted".
I thought about doing it in two ways:
During each check I append to some query-wide variable all fields that are not accessible and return it along with the query (probably in some middleware of some sort)
I extend all of the objects in my schema with a "permitted" field in which I return the value of the permission
Any suggestions ?

IMHO not worth the effort ... api faq or docs (available in graphiql/playground) can contain notice about 'unexpected null', ACL resons etc. It's enough for majority of use cases.
If you still want to include some [debug] info in response extensions are for that, f.e. https://github.com/apollographql/apollo-tracing , - in this case:
just attach a list of 'field access denied' [structured] notices;
collect them (in/from resolver) in some context object, attach in middleware (?), before overal response return;
Make it configurable (debug mode), too.

Related

Best way to validate DICOM connection request with pynetdicom

What is the preferred way to validate requested DICOM connection against a list of known hosts?
I can connect to the EVT_CONN_OPEN event. But in that, the event.assoc.requestor.info.ae_title element is always empty (b'').
I see from a TCP network analysis, that the name is transmitted. So, where is it?
What is the right way to validate the requesting host?
You could try using EVT_REQUESTED instead, it gets triggered after an association request is received/sent and the AE title information should be available at that point. Unfortunately EVT_CONN_OPEN is triggered on TCP connection which occurs prior to the association request.
If you don't like the host's details you can use the handler to send an association rejection message using event.assoc.acse.send_reject() or abort with event.assoc.abort().
If you're only interested in validating against the AE title you can use the AE.require_calling_aet property to restrict associations to those with matching AE titles.
For the benefit of anyone else looking this up, the correct stage to look this up is in the EVT_REQUESTED event. However you will likely find the details aren't filled in (they are populated AFTER the handler has been called).
So if you want to locate the callers AE in EVT_REQUESTED, you need to locate the A_ASSOCIATE primitive and read them from there. So for example in your handler you can do this to reject remotes:
def handle_request(event):
req_title = event.assoc.requestor.primitive.calling_ae_title.decode('ascii')
if req_title != 'MyAET':
event.assoc.acse.send_reject(0x01, 0x01, 0x03)
return
At least for 1.5.7.

How do I enforce a server-generated timestamp to a document in Firestore? [duplicate]

How do I check if user on client sided created document with only firebase.firestore.FieldValue.serverTimestamp()?
I have following:
allow create: if request.resource.data.timestamp == ??
What should I have instead of ??. I have tried serverTimestamp() firebase.firestore.FieldValue.serverTimestamp(), now or now() but it doesn't work.
It is possible to do it in Firebase like this:
".validate": "newData.child('timestamp').val() === now"
I am looking for the same solution. Any ideas? Thanks
You can access the current request timestamp in Security Rules using the request.time attribute (docs), which is the Firestore equivalent to the Realtime Databases's now. You'll therefore want something like:
allow create: if request.resource.data.timestamp == request.time;
For serverTimestamp() this should evaluate to true.
You should always validate client input in Security Rules, even if you're using serverTimestamp(). Security Rules doesn't automatically know the server input the value instead of the client, so without this check, a malicious client could create a different created at time.

web2py-sqlform can't check unique=True that use with requires=IS_LENGTH()

sqlform don't show error message when data have same value it accepted then error appear
error1
detail
ps. my goal is to create a field that contain 13 figure number which not same as other
i try delete requires=IS_LENGTH(maxsize=13,minsize=13) then the sqlform work fine but which these method i can't check either string is equal 13 or not
db.define_table('person',
Field('h_id_card',unique=True,requires=IS_LENGTH(maxsize=13,minsize=13))
)
def add():
form = SQLFORM(db.person).process()
return locals()
i expected sqlform will show error message instead of accepted
this is what i expect
From the book:
Notice that requires=... is enforced at the level of forms, required=True is enforced at the level of the DAL (insert), while notnull, unique and ondelete are enforced at the level of the database. While they sometimes may seem redundant, it is important to maintain the distinction when programming with the DAL.
Because unique=True translates to the UNIQUE SQL statement, when an insert/update violates the uniqueness constraint, you simply get an error from the database, which generates an exception in the database driver, which ultimately generates an exception in your app code if you don't catch it.
If you instead want to enable form validation for the uniqueness requirement, you should use the IS_NOT_IN_DB validator:
Field('h_id_card',
requires=[IS_LENGTH(maxsize=13, minsize=13), IS_NOT_IN_DB(db, 'person.h_id_card')])

Best practice to pass query conditions in ajax request

I'm writing a REST api in node js that will execute a sql query and send the results;
in the request I need to send the WHERE conditions; ex:
GET 127.0.0.1:5007/users //gets the list of users
GET 127.0.0.1:5007/users
id = 1 //gets the user with id 1
Right now the conditions are passed from the client to the rest api in the request's headers.
In the API I'm using sequelize, an ORM that needs to receive WHERE conditions in a particular form (an object); ex: having the condition:
(x=1 AND (y=2 OR z=3)) OR (x=3 AND y=1)
this needs to be formatted as a nested object:
-- x=1
-- AND -| -- y=2
| -- OR ----|
| -- z=3
-- OR -|
|
| -- x=3
-- AND -|
-- y=1
so the object would be:
Sequelize.or (
Sequelize.and (
{x=1},
Sequelize.or(
{y=2},
{z=3}
)
),
Sequelize.and (
{x=3},
{y=1}
)
)
Now I'm trying to pass a simple string (like "(x=1 AND (y=2 OR z=3)) OR (x=3 AND y=1)"), but then I will need a function on the server that can convert the string in the needed object (this method in my opinion has the advantage that the developer writing the client, can pass the where conditions in a simple way, like using sql, and this method is also indipendent from the used ORM, with no need to change the client if we need to change the server or use a different ORM);
The function to read and convert the conditions' string into an object is giving me headache (I'm trying to write one without success, so if you have some examples about how to do something like this...)
What I would like to get is a route capable of executing almost any kind of sql query and give the results:
now I have a different route for everything:
127.0.0.1:5007/users //to get all users
127.0.0.1:5007/users/1 //to get a single user
127.0.0.1:5007/lastusers //to get user registered in the last month
and so on for the other tables i need to query (one route for every kind of request I need in the client);
instead I would like to have only one route, something like:
127.0.0.1:5007/request
(when calling this route I will pass the table name and the conditions' string)
Do you think this solution would be a good solution or you generally use other ways to handle this kind of things?
Do you have any idea on how to write a function to convert the conditions' string into the desired object?
Any suggestion would be appreciated ;)
I would strongly advise you not to expose any part of your database model to your clients. Doing so means you can't change anything you expose without the risk of breaking the clients. One suggestion as far as what you've supplied is that you can and should use query parameters to cut down on the number of endpoints you've got.
GET /users //to get all users
GET /users?registeredInPastDays=30 //to get user registered in the last month
GET /users/1 //to get a single user
Obviously "registeredInPastDays" should be renamed to something less clumsy .. it's just an example.
As far as the conditions string, there ought to be plenty of parsers available online. The grammar looks very straightforward.
IMHO the main disadvantage of your solution is that you are creating just another API for quering data. Why create sthm from scratch if it is already created? You should use existing mature query API and focus on your business logic rather then inventing sthm new.
For example, you can take query syntax from Odata. Many people have been developing that standard for a long time. They have already considered different use cases and obstacles for query API.
Resources are located with a URI. You can use or mix three ways to address them:
Hierarchically with a sequence of path segments:
/users/john/posts/4711
Non hierarchically with query parameters:
/users/john/posts?minVotes=10&minViews=1000&tags=java
With matrix parameters which affect only one path segment:
/users;country=ukraine/posts
This is normally sufficient enough but it has limitations like the maximum length. In your case a problem is that you can't easily describe and and or conjunctions with query parameters. But you can use a custom or standard query syntax. For instance if you want to find all cars or vehicles from Ford except the Capri with a price between $10000 and $20000 Google uses the search parameter
q=cars+OR+vehicles+%22ford%22+-capri+%2410000..%2420000
(the %22 is a escaped ", the %24 a escaped $).
If this does not work for your case and you want to pass data outside of the URI the format is just a matter of your taste. Adding a custom header like X-Filter may be a valid approach. I would tend to use a POST. Although you just want to query data this is still RESTful if you treat your request as the creation of a search result resource:
POST /search HTTP/1.1
your query-data
Your server should return the newly created resource in the Location header:
HTTP/1.1 201 Created
Location: /search/3
The result can still be cached and you can bookmark it or send the link. The downside is that you need an additional POST.

What are all the ways CouchDB reponses fail?

I'm building a Node.js application on the express.js framework with CouchDB as a database. I'm utilizing CouchDB's session api for maintaining session state, and various databases for different sections of data.
On essentially every request my application code makes a request to Couch and then if there's an error (with Node) I can respond appropriately, by logging the error and redirecting to a 404 page or something like that. But if I get a CouchDB error, Node wouldn't consider it an error, it would consider that data. Now that's totally fine with me as long as CouchDB can only return this format:
{
"error": "illegal_database_name",
"reason": "Only lowercase characters (a-z), digits (0-9), and any of the characters _, $, (, ), +, -, and / are allowed. Must begin with a letter."
}
A JSON doc with two properties, error and reason. That's fine I can parse it and return the appropriate message; quite gracefully actually.
BUT! Is that all I can expect from CouchDB, or is there another way Couch might fail, that wouldn't yield a JSON doc with those two fields (properties)?
dscape's information of relying on the response codes is correct, and in most situations you will get an object with error and reason. The bulk-document errors are the only place I can think of where neither of these will be true. If just one document fails then you'll still get a 200, but you'll get the error/reason within the array element corresponding to the document that failed. See the docs for more info on that.

Resources