Skip to content

Commit

Permalink
Merge pull request #83 from lahirumenik/main
Browse files Browse the repository at this point in the history
automate attaching policy on thing connection
  • Loading branch information
lahirumenik authored Jan 13, 2024
2 parents 040c5df + a665bf0 commit cb66416
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
65 changes: 65 additions & 0 deletions backend/serverless/Lambda/thingreg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const AWS = require('aws-sdk');

exports.handler = async (event, context, callback) => {
const region = "ap-southeast-1";
const accountId = event.awsAccountId.toString().trim();
console.log(event);

const iot = new AWS.Iot({ 'region': region, apiVersion: '2015-05-28' });
const certificateId = event.certificateId.toString().trim();
const topicName = `${certificateId}`;
const certificateARN = `arn:aws:iot:${region}:${accountId}:cert/${certificateId}`;
const policyName = `Policy_${certificateId}`;

const policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iot:Connect"],
"Resource": `arn:aws:iot:${region}:${accountId}:client/${certificateId}`
},
{
"Effect": "Allow",
"Action": ["iot:Publish", "iot:Receive"],
"Resource": `arn:aws:iot:${region}:${accountId}:topic/*`
},
{
"Effect": "Allow",
"Action": ["iot:Subscribe"],
"Resource": `arn:aws:iot:${region}:${accountId}:topicfilter/${topicName}/#`
}
]
};

try {
console.log("Started creating policy");
const policyResult = await iot.createPolicy({
policyDocument: JSON.stringify(policy),
policyName: policyName
}).promise();

console.log("Policy created:", policyResult);

console.log("Attaching policy to certificate");
const attachPolicyResult = await iot.attachPrincipalPolicy({
policyName: policyName,
principal: certificateARN
}).promise();

console.log("Policy attached to certificate:", attachPolicyResult);

console.log("Activating certificate");
const activateCertificateResult = await iot.updateCertificate({
certificateId: certificateId,
newStatus: 'ACTIVE'
}).promise();

console.log("Certificate activated:", activateCertificateResult);

callback(null, "Success, created, attached policy, and activated the certificate " + certificateId);
} catch (err) {
console.error("Error:", err);
callback(err);
}
};
Empty file.
10 changes: 10 additions & 0 deletions backend/serverless/testing/thingreg.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"certificateId": "dd65ef7b374ec529e169aeead5f712a6a5d54653447d6eb04325e5a9261f8cf5",
"caCertificateId": "213adfc300a3f9841bd3c5aac09dcacf354171039c8be383ffd5914f600d3f4c",
"timestamp": "1705156374335",
"certificateStatus": "PENDING_ACTIVATION",
"awsAccountId": "782538749135",
"certificateRegistrationTimestamp": "1705146021287",
"sourceIp": "2402:d000:a400:f6c1:2625:20e0:d648:c4cf"
}

0 comments on commit cb66416

Please sign in to comment.