Mercurial > prosody-modules
comparison mod_aws_profile/mod_aws_profile.lua @ 3698:1d719d4ef18f
mod_aws_profile: New module for role-based access to AWS APIs
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Tue, 08 Oct 2019 17:32:50 +0100 |
parents | |
children | 616c0459aca7 |
comparison
equal
deleted
inserted
replaced
3697:a07bd12fe554 | 3698:1d719d4ef18f |
---|---|
1 local http = require "net.http"; | |
2 local json = require "util.json"; | |
3 local parse_timestamp = require "util.datetime".parse; | |
4 | |
5 module:set_global(); | |
6 | |
7 local current_credentials = module:shared("/*/aws_profile/credentials"); | |
8 | |
9 local function get_role_credentials(role_name, cb) | |
10 http.request("http://169.254.169.254/latest/meta-data/iam/security-credentials/"..role_name, nil, function (credentials_json) | |
11 local credentials = credentials_json and json.decode(credentials_json); | |
12 if not credentials or not (credentials.AccessKeyId and credentials.SecretAccessKey) then | |
13 module:log("warn", "Failed to fetch credentials for %q", role_name); | |
14 cb(nil); | |
15 return; | |
16 end | |
17 local expiry = parse_timestamp(credentials.Expiration); | |
18 local ttl = os.difftime(expiry, os.time()); | |
19 cb({ | |
20 access_key = credentials.AccessKeyId; | |
21 secret_key = credentials.SecretAccessKey; | |
22 ttl = ttl; | |
23 expiry = expiry; | |
24 }); | |
25 end); | |
26 end | |
27 | |
28 local function get_credentials(cb) | |
29 http.request("http://169.254.169.254/latest/meta-data/iam/security-credentials", nil, function (role_name) | |
30 role_name = role_name and role_name:match("%S+"); | |
31 if not role_name then | |
32 module:log("warn", "Unable to discover role name"); | |
33 cb(nil); | |
34 return; | |
35 end | |
36 get_role_credentials(role_name, cb); | |
37 end); | |
38 end | |
39 | |
40 function refresh_credentials(force) | |
41 if not force and current_credentials.expiry and current_credentials.expiry - os.time() > 300 then | |
42 return; | |
43 end | |
44 get_credentials(function (credentials) | |
45 if not credentials then | |
46 module:log("warn", "Failed to refresh credentials!"); | |
47 return; | |
48 end | |
49 current_credentials.access_key = credentials.access_key; | |
50 current_credentials.secret_key = credentials.secret_key; | |
51 current_credentials.expiry = credentials.expiry; | |
52 module:timer(credentials.ttl or 240, refresh_credentials); | |
53 module:fire_event("aws_profile/credentials-refreshed", current_credentials); | |
54 end); | |
55 end | |
56 | |
57 function module.load() | |
58 refresh_credentials(true); | |
59 end |