Limit an API Key to Read-Only Access?

Context

I have a Swift Mac app built with Realm 10.41.0. I’m using Device Sync. This is an enterprise app with, say, 20 different customers. For security, each customer has a completely separate database in MongoDB—a separate cluster and separate Realm App.

Each Realm App has email/password authentication turned on and the customer will create user accounts for their employees. These user accounts will obviously have access to only the database associated with their company.

Question

Given a user’s email address, the Mac app needs to look up the correct Atlas App ID to use so that it opens a Realm to the correct MongoDB App (and therefore the correct database). To accomplish this, I have an additional Atlas App with a separate cluster/database/collection that keeps a universal mapping of email address --> appID. This database gets updated via a server-side function anytime a customer adds/edits/removes a user to their separate Atlas App.

My Mac app needs to access this “master database”. I’ve chosen to do that via API key, but since the API key can be easily dumped from the app binary, I want to make sure this API Key has read-only access to the database. No malicious user should ever be able to dump the API key and use it to edit the “master list” of users.

How can I specify that the API key is read-only?

I did find this: Data API: Restrict access to read/write to collection, but it’s using the “Data API” rather than Swift Framework. Thanks!

1 Like

Hi, the best way to do this is to lean on the permissions system for Atlas App Services. When you define a rule, you can define a set of “roles” that have a waterfall like evaluation where they use the apply_when expression to choose the first role that applies to a user. Therefore, you can detect an API Key user with the %%user expansion to detect the provider type like:

{ "%%user.identities.providerType": api-key}

See here for more details: https://www.mongodb.com/docs/atlas/app-services/rules/expressions/#mongodb-json-expansion---user

Then, for that role, you can define { read: true, write: false } and it should give you read-only permissions.

Best,
Tyler

1 Like

Mmm, the editor didn’t like that. I can’t figure out if this textfield is supposed to be just the expression of the apply_when field, or if I need to provide a more complete JSON object for each document in my collections, as shown in the docs.

But it does not seem to approve of “api-key” as a raw value. Did you mean to make that a string?

Yes, that should be a string. My apologies

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.