How do I efficiently configure AWS IoT rules to write data to a device specific Timestream database? - aws-iot

I want to store IoT device data in a device specific table in a Timestream database. This will allow us to give users access to their particular device data only based on a specific IAM or Cognito policy.
Data from the devices would look something like this with the id being a Timestream dimension and temperature a measure.
{
"ts": 1619815725,
"id": "device_12345",
"temperature": 47.2
}
and it will be published to the topic
devices/data/device_12345
There is a Timestream database device_data and in that a table for each device, in this case device_12345
Now we can create a rule which pushes the data from that device to the particular table, like this:
which selects the relevant data from the exact endpoint. The action looks like this:
The role is configured to only allow writes to the specific table in the Timestream database. A policy can be attached to the device to allow only the specific device to write to that particular MQTT endpoint (which prevents other device accidentally writing to it).
A policy can then be configured for a user to only allow read access to that table to query data from their device only.
In this case the following have to be in place for each device:
A policy which limits the MQTT publish endpoint to the device end point (in this case devices/data/device_12345
A rule which pushes the data to Timestream which has the specific device endpoint as well as the specific device database table set correctly
A IAM policy which allows that rule to write data to the device specific table in the database
Now the questions:
Is it possible to configure a generic rule which looks at the device ID, or some information about the IoT thing and pushes it to the correct database table based on this info? e.g. can the rule look at the id dimension and based on that push it to the correct table?
How can this be automated if we have to set up each of those items for every one of the millions of devices?
Is having millions of device specific policies and rules the most effective/efficient way to do this?

It is possible to configure a set of policies and rules which can be attached to the IoT thing and user to bound the access that devices have as well as the the access that an end user has.
On a high level the following can be done:
The IoT thing has a certificate which is uniquely linked to a device
A policy can be linked to the certificate which only allows the device to publish to particular topics
A IoT code rule can be set up to push data to a device specific Timestream database based on the topic the device publishes to
An end user can be given read rights to access a specific Timestream table
The smallest IAM resource resolution for a Timestream database is a table (see https://docs.aws.amazon.com/timestream/latest/developerguide/security_iam_service-with-iam.html), so the only way to limit user access to their own data is to contain device data within its own table and then give the user access rights to the tables with their device(s) data.
1. IoT certificate
This is part of the basic AWS IoT core thing setup. Once the device has a private key and certificate it can connect to IoT core and publish/subscribe according to the policy attached to the certificate
2. Set up a generic policy using IoT Thing policy variables
AWS IoT Thing policy variables info can be found here: https://docs.aws.amazon.com/iot/latest/developerguide/thing-policy-variables.html
The following policy can be attached to any certificate and will only allow the device to publish to the devices/data/device_12345 topic. The thing policy variable ${iot:Connection.Thing.ThingName} is substituted with the actual thing name. This is a minimal policy which allows connecting and publishing only to the one topic.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:Connect",
"Resource": "arn:aws:iot:us-east-1:123456789:client/${iot:Connection.Thing.ThingName}"
},
{
"Effect": "Allow",
"Action": "iot:Publish",
"Resource": "arn:aws:iot:us-east-1:123456789:topic/devices/data/${iot:Connection.Thing.ThingName}"
}
]
}
Any device with this policy attached to its certificate will only be able to publish to the topic with its own thing name. This is a generic policy which can be attached to any Thing due to the policy variable substitution.
3. Configure an IoT core rule to push data to a Timestream database table
You will need to create a Timestream database and device specific table where the table has the same name as the Thing, e.g. database device_data with a table device_12345
The first thing to define is the IoT SQL query that will select the data to be pushed to the Timestream action in the rule. In this case the SQL will be,
SELECT temperature FROM 'devices/data/+'
The + is a wildcard which selects a single topic level, i.e. it will match data on devices/data/device_12345 but not devices/data/device_12345/more_data. This will select the data from published data from any device.
In the Timestream action the database will be device_data and the tableName uses the SQL function topic() (which is available in the contact of the action) to obtain the device name.
This rule must be set up using the CLI, as substitution templates are only available through the AWS CLI or API.
The JSON for setting the rule is,
{
"sql": "SELECT temperature FROM 'devices/data/+'",
"actions": [
{
"timestream": {
"roleArn": "arn:aws:iam::123456789:role/service-role/devices_to_timestream",
"databaseName": "device_data",
"tableName": "${topic(3)}",
"dimensions": [
{
"name": "id",
"value": "${id}"
}
],
"timestamp": {
"value": "${ts}",
"unit": "SECONDS"
}
}
}
],
"ruleDisabled": false,
"awsIotSqlVersion": "2015-10-08"
}
Note that an IAM role is needed to provide write access to the database tables and this must be set up before configuring the rule. Create a role devices_to_timestream_role and attached a custom policy to allow writing to the tables of the database. The policy is
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "timestream:WriteRecords",
"Resource": "arn:aws:timestream:us-east-1:123456789:database/device_data/table/*"
},
{
"Effect": "Allow",
"Action": "timestream:DescribeEndpoints",
"Resource": "*"
}
]
}
This policy allows writing to any table as it will be used by many different Things to write data. Although this policy allows writing to any table, the Thing certificate policy and the rule query limit which table a particular Thing can write to.
The IoT Rule can be written from the command line using this command:
aws iot create-topic-rule --rule-name devices_to_timestream --topic-rule-payload file://devices_to_timestream.json
where devices_to_timestream.json has the contents of the rule listed above.
4. Give the user access to their data
An access policy can be attached to a user identity to give the end user access to their device data following the pattern in the Timesteam identity based policy examples.
In summary:
This configuration provides,
One generic policy which can be attached to any Thing to allow it to publish to a topic with a Thing specific name
One generic rule which pushes all data to Thing specific tables in a Timestream database
User access to only the Thing data linked to their AWS identity
Beyond what is described here you would need,
An automated method to create new tables when a new Thing is created or connects for the first time
A mechanism to attached access rights to users identities

Related

Logic Apps and Configuring Office 365 Email

Configuring a new service connection to Office 365 from the "Send email via Office 365 Outlook" connector in Logic Apps is failing on Save with the following error -
Failing to save logic app . The client has
permission to perform action 'Microsoft/.Logic/workflows/write' on
scope , however, it does not have permission
to perform action 'join/action' on the linked scope
'/providers/microsoft.web/connections/office365'.
If I am asking for the permissions for the second part what role is that? It seems to be something in Office 365.
When you using the Office 365 connecter in the logic app(login your user account to auth successfully), it will create a office365 API connection (i.e. microsoft.web/connections/office365 mentioned in the error) in your resource group.
So to solve the issue, you also need permission at resource group/subscription level, not only at logic app level, just navigate to the resource group/subscription which the logic app located -> Access control (IAM) -> add an RBAC role e.g. Contributor like below.
Update:
For the specific error in your question, the least permission is Microsoft.Web/connections/Join/Action with no doubt, but if you want to do your stuff successfully, the permission I recommend is Microsoft.Web/connections/*, it is small enough, it includes the permissions below, source.
Of course, you can only use Microsoft.Web/connections/Join/Action, but it may raise another permission error, then you need to fix it again, all depend on your requirements.
To create the custom role, follow this doc, in the step 6, use the json like below.
{
"properties": {
"roleName": "LogicAPIConnRole",
"description": "test",
"assignableScopes": [
"/subscriptions/xxxxx"
],
"permissions": [
{
"actions": [
"Microsoft.Web/connections/*"
],
"notActions": [],
"dataActions": [],
"notDataActions": []
}
]
}
}
After the creation, assign the role at the office365 API connection scope, it will work fine.

Using MongoDB for multi-tenant applications

How can you use MongoDB in a multi-tenant environment? By multi-tenant I mean, one MongoDB instance used by multiple organizational apps.
As such, we can have App A, App B, and App C use the same MongoDB instance with each application isolated from here other, meaning, for example, a "User" Collection for App A cannot be accessed by App B and vice-versa.
There seems to be no concept of "Namespace" with MongoDB that can be used to assign for each application.
You can have role based access control, and can control which user is allowed to do what on each resource.
From your question, it looks like you are interested in collection level control. Please refer this. Please make sure you are looking at the right version for MongoDB.
So you will end up with different credentials per tenant.
Caveat; you can't throttle noisy neighbours in this design.
For example, a user defined role can contain the following privileges:
privileges: [
{ resource: { db: "products", collection: "inventory" }, actions: [ "find", "update", "insert" ] },
{ resource: { db: "products", collection: "orders" }, actions: [ "find" ] }
]
Another option is to create separate database per tenant. But that increases your management (CI/CD/DevOps) costs. For eg. a change in an index will have to be applied per tenant. And you will need to make sure that change is applied correctly.
It depends on how many tenants. For a small number it is ok.
For large number, would be better to be pure SaaS based, and have tenantId as part of every document you store, retrieve, delete etc.

How to assign an application role to a managed identity in the ARM template

I have the following scenario.
My application registration defines a set of application roles
I dynamically deploy a scaleset with a System assigned managed identity via ARM template
During the deployment i want to assign that identity to one of the specific application role defined above
I update my deployment template with the following resource
{
"type": "Microsoft.Authorization/roleAssignments",
"apiVersion": "2017-09-01",
"name": "<random Guid>",
"dependsOn": [
"[concat('Microsoft.Compute/virtualMachineScaleSets/', '<scaleset name>')]"
],
"properties": {
"roleDefinitionId": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', '<app role guid>')]",
"principalId": "[reference(resourceId('Microsoft.Compute/virtualMachineScaleSets', '<scaleset name>'), '2019-07-01', 'Full').Identity.principalId]",
"scope": "[resourceGroup().id]"
}
}
However the deployment fails with the following exception
The specified role definition with ID '<app role guid>' does not exist.
My assumption is that the application role definition id is no correctly formatted but i could not find any examples of this kind approle assignment in an ARM template.
Is this even possible ?
here is an example of how you would do this
https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-template#new-service-principal
you will need to add a principalType of Serviceprincipal, this is because as per the docs, there can easily be a delay when creating a new serviceprincipal, so it will fail if you don't do this.
Edit: I'm sorry, i didn't realize you were trying to do an app role assignment.
I don't believe this is currently supported in arm templates. the rbac roles that you can assign using roleassignment are not app roles. eg. you cannot assign app roles in an arm template currently only for azure built in roles for azure resources, not for apps or azure ad roles.
for reference https://github.com/MicrosoftDocs/azure-docs/issues/51914#issuecomment-612867662
the only way you may be able to work around and do something like this is probably through a deployment script that runs powershell commands in the arm template if at all possible.

How to work with Azure Active Directory Schema Extensions in Multi-Tenant Scenario

I want to use an Azure AD schema extension to extend one property, I have successfully created a schema extension with id "myverifiedaaddomain_extensionid".
Schema Extension :
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#schemaExtensions/$entity",
"id": "myverifiedaaddomain_extensionid",
"description": "myverifiedaaddomain_extensionid",
"targetTypes": [
"User"
],
"status": "InDevelopment",
"owner": "owner",
"properties": [
{
"name": "isExtended",
"type": "Boolean"
}
]
}
NOTE: It is working perfectly fine in single tenant scenario.
Multi-tenant scenario :
Scenario -
I have a host tenant T1
Registered multi-tenant AAD AAP A1 (in T1
with all required permissions)
I want to on-board tenant T2
Register schema extension on T2 after successful on-boarding
When I on-board T2, all schema extensions from T1 where owner is A1 get's imported in T2's directory without any notification or prompt.
So currently It is working in multi-tenant scenario as well but I am not sure about getting all schema extensions exported to partner tenant(T2), is it expected behaviour or a bug?
There is no clear documentation available here https://learn.microsoft.com/en-us/graph/extensibility-overview or https://learn.microsoft.com/en-us/graph/api/resources/schemaextension?view=graph-rest-1.0
Apart from this there is no clear documentation on permissions as well, for example :
https://learn.microsoft.com/en-us/graph/extensibility-overview#permissions
They mentioned that, in order to read/update extended data, you need all permissions mentioned on that resource permission page. For User resource we will need to have all permissions mentioned here https://learn.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0#permissions
This is not working, I am not able to read extended data via other AAD apps(A2, A3 etc.) which has all permissions mentioned in above page(https://learn.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0#permissions).
Sorry for some of the challenges you are coming across here. Just to double check - have you used Azure AD Directory Schema extensions in the past? I'm asking because it seems like you have some preconceptions about how extensions work - and they behave a little differently in Microsoft Graph.
In terms of documentation - it is documented in the section about schema extension lifecycle in https://learn.microsoft.com/en-us/graph/extensibility-overview#schema-extensions. Maybe we can do a better job of providing a full on scenario. But here's the relevant bit when setting the schema definition state to Available:
The schema extension is available for use by all apps in any tenant.
After the owner app sets the extension to Available, any app can
simply add custom data to instances of those resource types specified
in the extension (as long as the app has permissions to that
resource). The app can assign custom data when creating a new
instance or updating an existing instance.
Only the owner app can
update the extension definition with additive changes. No app can
delete the extension definition in this state.
The owner app can
move the schema extension from Available to the Deprecated state.
In terms of the permissions not working, what permissions were granted to the multi-tenant application, or the other apps A2 and A3? What response are you seeing (can you provide the request as well please)?
Hope this helps,

When creating a custom role in Azure AD, what do the parameters in "Actions" really do?

I'm looking into creating a custom Azure AD role to use as part of [Authorization] in an Azure web app service. When you include a list of "Actions", are you creating Permissions as well within that role?
Can the "Actions" be empty? Lets say I just want to test a Role in a controller and then control the data access from there? Do I really need anything in the "Actions" section?
There are two very different concepts:
Custom Roles in Azure (for Role based access control of Azure resources)
Application Roles in Azure AD (for authorization in an application that uses Azure AD)
Based on your question, you need to be looking closely into the 2nd one, i.e. Application Roles. They don't have any list of "Actions" as part of their definition. I'll try to give a little more detail on both 1 and 2 below to make it clear.
Custom Roles in Azure (they have "Actions" list, but won't be helpful in implementing authorization logic in your web application)
Microsoft Documentation - Custom Roles in Azure
Purpose - Azure already provides built-in roles as part of Azure Portal to manage access to your resources in Azure Portal based on assigned roles. If you have a scenario where none of the built in roles meet your requirement, you can create a custom role, but the purpose is still that you will assign this custom role to someone in order for them to be able to manage/work with provisioned resources in Azure. E.g. Owner or Reader for an Azure SQL database server or one or more virtual machines. You will use these roles from Azure portal/PowerShell/CLI etc.
These roles are very helpful in a big organization, where everyone cannot be an owner/administrator at the Azure Subscription level, but can still be given access at a granular level to only some of the Azure Subscription Resources (like databases, vms, logic apps, storage accounts or anything available in Azure subscription for that matter). This is done through Role-based Access Control through portal/PowerShell/CLI.
Example
{
"Name": "Virtual Machine Operator",
"Id": "88888888-8888-8888-8888-888888888888",
"IsCustom": true,
"Description": "Can monitor and restart virtual machines.",
"Actions": [
"Microsoft.Storage/*/read",
"Microsoft.Network/*/read",
"Microsoft.Compute/*/read",
"Microsoft.Compute/virtualMachines/start/action",
"Microsoft.Compute/virtualMachines/restart/action",
"Microsoft.Authorization/*/read",
"Microsoft.Resources/subscriptions/resourceGroups/read",
"Microsoft.Insights/alertRules/*",
"Microsoft.Insights/diagnosticSettings/*",
"Microsoft.Support/*"
],
"NotActions": [
],
"DataActions": [
],
"NotDataActions": [
],
"AssignableScopes": [
"/subscriptions/{subscriptionId1}",
"/subscriptions/{subscriptionId2}",
"/subscriptions/{subscriptionId3}"
]
}
Application Roles in Azure AD (these don't have "Actions" list, but are meant to be used for Authorization logic in your application)
Microsoft Documentation - Application Roles
Purpose - These roles are defined in the Application Manifest for an application that your organization is developing and that is registered in your Azure Active Directory. These roles are very specific to your application and can be used in application's code to implement Authorization logic for the authenticated users.
Using the "allowedMemberTypes" you can control who can be assigned these roles (to Users, Groups or even Applications).
You can then assign roles from Azure Portal or programmatically.
One simple way would be like shown in screenshot below -
When trying to implement your Authorization logic, these roles will be available as role "claims". So you will be able to check for roles with code like below
if (context.User.HasClaim(ClaimTypes.Role, "Admin")) { ... }
Sample Application that creates application roles and then uses them for Authorization
Authorization in a web app using Azure AD application roles & role claims
Example
This is the JSON that will go as part of your application manifest.
"appRoles": [
{
"allowedMemberTypes": [
"User"
],
"description": "Creators can create Surveys",
"displayName": "SurveyCreator",
"id": "1b4f816e-5eaf-48b9-8613-7923830595ad",
"isEnabled": true,
"value": "SurveyCreator"
},
{
"allowedMemberTypes": [
"User"
],
"description": "Administrators can manage the Surveys in their tenant",
"displayName": "SurveyAdmin",
"id": "c20e145e-5459-4a6c-a074-b942bbd4cfe1",
"isEnabled": true,
"value": "SurveyAdmin"
}
]

Resources