Calling a (Netlify) serverless function from a UDF safely

Say I need a serverless function to handle some stuff before/after calling a UDF that can’t be done in frontend code (i.e. sending emails with SendGrid would require exposing a sensitive API key in frontend code, so it must be handled by a backend/serverless function). How would you go about enforcing permissions and security in this scenario?

One way I thought of could be calling a UDF from the frontend that only acts as a security check by using Identity() to make sure that the user has the required permissions and then making a request to the serverless function from within that UDF. This obviously costs double though (2 UDF calls, one from frontend and one from serverless), and still doesn’t make me feel safe because the serverless endpoint could be discovered and used maliciously, bypassing the frontend check.

Another way could be making a request to the serverless function directly from frontend code and including something that the serverless function would then use to make the permissions check, but I’m stumped on what that would be. I’m guessing KeyFromSecret is what should be used in the serverless function to check that the token associated with the secret passed in belongs to the correct user, but is it safe to send the user’s secret?

You can make those requests that need side effects (eg. sending email) pass through your backend first, then call fauna from your backend checking user credentials and calling the UDF.

If the client is using Login and you have a user token client side

  1. Send the secret via authorization header
  2. get the secret from the header in the function
  3. create your new Client from the secret

If the secret is valid, all you technically need is to run client.query(true). If the promise resolves, then the token is valid. KeyFromSecret is unnecessary since the secret is valid by definition if the client works.

Of course if you want to do more to check if the particular user has the right credentials, then a more detailed query would be needed.

Netlify functions are all HTTPS, so it is relatively safe. The vulnerability more likely will be in how the secret is stored client side.

Side notes:

If you create tokens manually, i.e. with Create(Tokens(), ...) then you can add additional data, which could be retrieved from KeyFromSecret. But you would need to add a new login function to Netlify specifically for that.

This may be an interesting topic to you:

1 Like