forked from monetate/ectou-metadata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.py
223 lines (163 loc) · 5.98 KB
/
service.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
"""
Mock subset of instance metadata service.
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
"""
import datetime
import json
import os
import boto3.session
import botocore.session
import bottle
import dateutil.tz
_refresh_timeout = datetime.timedelta(minutes=5)
_role_arn = None
_conf_dir = None
_credential_map = {}
def _lookup_ip_role_arn(source_ip):
try:
if _conf_dir and source_ip:
with open(os.path.join(_conf_dir, source_ip)) as f:
return f.readline().strip()
except IOError:
pass # no such file
def _get_role_arn():
"""
Return role arn from X-Role-ARN header,
lookup role arn from source IP,
or fall back to command line default.
"""
role_arn = bottle.request.headers.get('X-Role-ARN')
if not role_arn:
role_arn = _lookup_ip_role_arn(bottle.request.environ.get('REMOTE_ADDR'))
if not role_arn:
role_arn = _role_arn
return role_arn
def _format_iso(dt):
"""
Format UTC datetime as iso8601 to second resolution.
"""
return datetime.datetime.strftime(dt, "%Y-%m-%dT%H:%M:%SZ")
def _index(items):
"""
Format index list pages.
"""
bottle.response.content_type = 'text/plain'
return "\n".join(items)
@bottle.route("/latest")
@bottle.route("/latest/meta-data")
@bottle.route("/latest/meta-data/iam")
@bottle.route("/latest/meta-data/iam/security-credentials")
@bottle.route("/latest/meta-data/placement")
def slashify():
bottle.redirect(bottle.request.path + "/", 301)
@bottle.route("/")
def root():
return _index(["latest"])
@bottle.route("/latest/")
def latest():
return _index(["meta-data"])
@bottle.route("/latest/meta-data/")
def meta_data():
return _index(["ami-id",
"iam/",
"instance-id",
"instance-type",
"local-ipv4",
"placement/",
"public-hostname",
"public-ipv4"])
@bottle.route("/latest/meta-data/iam/")
def iam():
return _index(["security-credentials/"])
@bottle.route("/latest/meta-data/iam/security-credentials/")
def security_credentials():
return _index(["role-name"])
@bottle.route("/latest/meta-data/iam/security-credentials/role-name")
def security_credentials_role_name():
role_arn = _get_role_arn()
credentials = _credential_map.get(role_arn)
# Refresh credentials if going to expire soon.
now = datetime.datetime.now(tz=dateutil.tz.tzutc())
if not credentials or credentials['Expiration'] < now + _refresh_timeout:
try:
# Use any boto3 credential provider except the instance metadata provider.
botocore_session = botocore.session.Session()
botocore_session.get_component('credential_provider').remove('iam-role')
session = boto3.session.Session(botocore_session=botocore_session)
credentials = session.client('sts').assume_role(RoleArn=role_arn,
RoleSessionName="ectou-metadata")['Credentials']
credentials['LastUpdated'] = now
_credential_map[role_arn] = credentials
except Exception as e:
bottle.response.status = 404
bottle.response.content_type = 'text/plain' # EC2 serves json as text/plain
return json.dumps({
'Code': 'Failure',
'Message': e.message,
}, indent=2)
# Return current credential.
bottle.response.content_type = 'text/plain' # EC2 serves json as text/plain
return json.dumps({
'Code': 'Success',
'LastUpdated': _format_iso(credentials['LastUpdated']),
"Type": "AWS-HMAC",
'AccessKeyId': credentials['AccessKeyId'],
'SecretAccessKey': credentials['SecretAccessKey'],
'Token': credentials['SessionToken'],
'Expiration': _format_iso(credentials['Expiration'])
}, indent=2)
@bottle.route("/latest/meta-data/instance-id")
def instance_id():
bottle.response.content_type = 'text/plain'
return "i-deadbeef"
@bottle.route("/latest/meta-data/instance-type")
def instance_type():
bottle.response.content_type = 'text/plain'
return "m1.small"
@bottle.route("/latest/meta-data/ami-id")
def ami_id():
bottle.response.content_type = 'text/plain'
return "ami-deadbeef"
@bottle.route("/latest/meta-data/local-ipv4")
def local_ipv4():
bottle.response.content_type = 'text/plain'
return "127.0.0.1"
@bottle.route("/latest/meta-data/placement/")
def placement():
return _index(["availability-zone"])
@bottle.route("/latest/meta-data/placement/availability-zone")
def availability_zone():
bottle.response.content_type = 'text/plain'
return "us-east-1x"
@bottle.route("/latest/meta-data/public-hostname")
def public_hostname():
bottle.response.content_type = 'text/plain'
return "localhost"
@bottle.route("/latest/meta-data/public-ipv4")
def public_ipv4():
bottle.response.content_type = 'text/plain'
return "127.0.0.1"
@bottle.route("/latest/dynamic/instance-identity<slashes:re:/*>")
def instance_identity_index(slashes):
bottle.response.content_type = 'text/plain'
return 'document'
@bottle.route("/latest/dynamic/instance-identity<slashes1:re:/+>document<slashes2:re:/*>")
def instance_identity_document(slashes1, slashes2):
bottle.response.content_type = 'text/plain'
return '{"region": "us-east-1"}'
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--host', default="169.254.169.254")
parser.add_argument('--port', default=80)
parser.add_argument('--role-arn', help="Default role ARN.")
parser.add_argument('--conf-dir', help="Directory containing configuration files named by source ip.")
args = parser.parse_args()
global _role_arn
_role_arn = args.role_arn
global _conf_dir
_conf_dir = args.conf_dir
app = bottle.default_app()
app.run(host=args.host, port=args.port)
if __name__ == "__main__":
main()