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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
|
#
# -------------------------------------------------------------------------
# Copyright (c) 2015-2017 AT&T Intellectual Property
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# -------------------------------------------------------------------------
#
import six
import yaml
import base64
from yaml.constructor import ConstructorError
from notario import decorators
from notario.validators import types
from oslo_log import log
import pecan
from pecan_notario import validate
from conductor.api.controllers import error
from conductor.api.controllers import string_or_dict
from conductor.api.controllers import validator
from conductor.i18n import _, _LI
from oslo_config import cfg
from conductor.api.adapters.aaf import aaf_authentication as aaf_auth
CONF = cfg.CONF
LOG = log.getLogger(__name__)
CONDUCTOR_API_OPTS = [
cfg.StrOpt('server_url',
default='',
help='Base URL for plans.'),
cfg.StrOpt('username',
default='',
help='username for plans.'),
cfg.StrOpt('password',
default='',
help='password for plans.'),
cfg.BoolOpt('basic_auth_secure',
default=True,
help='auth toggling.'),
]
CONF.register_opts(CONDUCTOR_API_OPTS, group='conductor_api')
CREATE_SCHEMA = (
(decorators.optional('files'), types.dictionary),
(decorators.optional('id'), types.string),
(decorators.optional('limit'), types.integer),
(decorators.optional('name'), types.string),
(decorators.optional('num_solution'), types.string),
('template', string_or_dict),
(decorators.optional('template_url'), types.string),
(decorators.optional('timeout'), types.integer),
)
class PlansBaseController(object):
"""Plans Base Controller - Common Methods"""
def plan_link(self, plan_id):
return [
{
"href": "%(url)s/v1/%(endpoint)s/%(id)s" %
{
'url': pecan.request.application_url,
'endpoint': 'plans',
'id': plan_id,
},
"rel": "self"
}
]
def plans_get(self, plan_id=None):
auth_flag = CONF.conductor_api.basic_auth_secure or CONF.aaf_api.is_aaf_enabled
# TBD - is healthcheck properly supported?
if plan_id == 'healthcheck' or \
not auth_flag or \
(auth_flag and check_auth()):
return self.plan_getid(plan_id)
def plan_getid(self, plan_id):
ctx = {}
method = 'plans_get'
if plan_id:
args = {'plan_id': plan_id}
LOG.debug('Plan {} requested.'.format(plan_id))
else:
args = {}
LOG.debug('All plans requested.')
plans_list = []
client = pecan.request.controller
result = client.call(ctx, method, args)
plans = result and result.get('plans')
for the_plan in plans:
the_plan_id = the_plan.get('id')
the_plan['links'] = [self.plan_link(the_plan_id)]
plans_list.append(the_plan)
if plan_id:
if len(plans_list) == 1:
return plans_list[0]
else:
# For a single plan, we return None if not found
return None
else:
# For all plans, it's ok to return an empty list
return plans_list
def plan_create(self, args):
ctx = {}
method = 'plan_create'
# TODO(jdandrea): Enhance notario errors to use similar syntax
# valid_keys = ['files', 'id', 'limit', 'name',
# 'template', 'template_url', 'timeout']
# if not set(args.keys()).issubset(valid_keys):
# invalid = [name for name in args if name not in valid_keys]
# invalid_str = ', '.join(invalid)
# error('/errors/invalid',
# _('Invalid keys found: {}').format(invalid_str))
# required_keys = ['template']
# if not set(required_keys).issubset(args):
# required = [name for name in required_keys if name not in args]
# required_str = ', '.join(required)
# error('/errors/invalid',
# _('Missing required keys: {}').format(required_str))
LOG.debug('Plan creation requested (name "{}").'.format(
args.get('name')))
client = pecan.request.controller
transaction_id = pecan.request.headers.get('transaction-id')
if transaction_id:
args['template']['transaction-id'] = transaction_id
result = client.call(ctx, method, args)
plan = result and result.get('plan')
if plan:
plan_name = plan.get('name')
plan_id = plan.get('id')
plan['links'] = [self.plan_link(plan_id)]
LOG.info(_LI('Plan {} (name "{}") created.').format(
plan_id, plan_name))
return plan
def plan_delete(self, plan):
ctx = {}
method = 'plans_delete'
plan_name = plan.get('name')
plan_id = plan.get('id')
LOG.debug('Plan {} (name "{}") deletion requested.'.format(
plan_id, plan_name))
args = {'plan_id': plan_id}
client = pecan.request.controller
client.call(ctx, method, args)
LOG.info(_LI('Plan {} (name "{}") deleted.').format(
plan_id, plan_name))
class PlansItemController(PlansBaseController):
"""Plans Item Controller /v1/plans/{plan_id}"""
def __init__(self, uuid4):
"""Initializer."""
self.uuid = uuid4
self.plan = self.plans_get(plan_id=self.uuid)
if not self.plan:
error('/errors/not_found',
_('Plan {} not found').format(self.uuid))
pecan.request.context['plan_id'] = self.uuid
@classmethod
def allow(cls):
"""Allowed methods"""
return 'GET,DELETE'
@pecan.expose(generic=True, template='json')
def index(self):
"""Catchall for unallowed methods"""
message = _('The {} method is not allowed.').format(
pecan.request.method)
kwargs = {'allow': self.allow()}
error('/errors/not_allowed', message, **kwargs)
@index.when(method='OPTIONS', template='json')
def index_options(self):
"""Options"""
pecan.response.headers['Allow'] = self.allow()
pecan.response.status = 204
@index.when(method='GET', template='json')
def index_get(self):
"""Get plan"""
return {"plans": [self.plan]}
@index.when(method='DELETE', template='json')
def index_delete(self):
"""Delete a Plan"""
self.plan_delete(self.plan)
pecan.response.status = 204
class PlansController(PlansBaseController):
"""Plans Controller /v1/plans"""
@classmethod
def allow(cls):
"""Allowed methods"""
return 'GET,POST'
@pecan.expose(generic=True, template='json')
def index(self):
"""Catchall for unallowed methods"""
message = _('The {} method is not allowed.').format(
pecan.request.method)
kwargs = {'allow': self.allow()}
error('/errors/not_allowed', message, **kwargs)
@index.when(method='OPTIONS', template='json')
def index_options(self):
"""Options"""
pecan.response.headers['Allow'] = self.allow()
pecan.response.status = 204
@index.when(method='GET', template='json')
def index_get(self):
"""Get all the plans"""
plans = self.plans_get()
return {"plans": plans}
@index.when(method='POST', template='json')
@validate(CREATE_SCHEMA, '/errors/schema')
def index_post(self):
"""Create a Plan"""
# Look for duplicate keys in the YAML/JSON, first in the
# entire request, and then again if the template parameter
# value is itself an embedded JSON/YAML string.
where = "API Request"
try:
parsed = yaml.load(pecan.request.text, validator.UniqueKeyLoader)
if 'template' in parsed:
where = "Template"
template = parsed['template']
if isinstance(template, six.string_types):
yaml.load(template, validator.UniqueKeyLoader)
except ConstructorError as exc:
# Only bail on the duplicate key problem (problem and problem_mark
# attributes are available in ConstructorError):
if exc.problem is \
validator.UniqueKeyLoader.DUPLICATE_KEY_PROBLEM_MARK:
# ConstructorError messages have a two line snippet.
# Grab it, get rid of the second line, and strip any
# remaining whitespace so we can fashion a one line msg.
snippet = exc.problem_mark.get_snippet()
snippet = snippet.split('\n')[0].strip()
msg = _('{} has a duplicate key on line {}: {}')
error('/errors/invalid',
msg.format(where, exc.problem_mark.line + 1, snippet))
except Exception as exc:
# Let all others pass through for now.
pass
args = pecan.request.json
# Print request id from SNIOR at the beginning of API component
if args and args['name']:
LOG.info('Plan name: {}'.format(args['name']))
auth_flag = CONF.conductor_api.basic_auth_secure or CONF.aaf_api.is_aaf_enabled
# Create the plan only when the basic authentication is disabled or pass the authenticaiton check
if not auth_flag or \
(auth_flag and check_auth()):
plan = self.plan_create(args)
if not plan:
error('/errors/server_error', _('Unable to create Plan.'))
else:
pecan.response.status = 201
return plan
@pecan.expose()
def _lookup(self, uuid4, *remainder):
"""Pecan subcontroller routing callback"""
return PlansItemController(uuid4), remainder
def check_auth():
"""
Returns True/False if the username/password of Basic Auth match/not match
Will also check role-based access controls if AAF integration configured
:return boolean value
"""
try:
if pecan.request.headers['Authorization'] and verify_user(pecan.request.headers['Authorization']):
LOG.debug("Authorized username and password")
plan = True
else:
plan = False
auth_str = pecan.request.headers['Authorization']
user_pw = auth_str.split(' ')[1]
decode_user_pw = base64.b64decode(user_pw)
list_id_pw = decode_user_pw.split(':')
LOG.error("Incorrect username={} / password={}".format(list_id_pw[0], list_id_pw[1]))
except:
error('/errors/basic_auth_error', _('Unauthorized: The request does not '
'provide any HTTP authentication (basic authentication)'))
plan = False
if not plan:
error('/errors/authentication_error', _('Invalid credentials: username or password is incorrect'))
return plan
def verify_user(authstr):
"""
authenticate user as per config file or AAF authentication service
:param authstr:
:return boolean value
"""
user_dict = dict()
auth_str = authstr
user_pw = auth_str.split(' ')[1]
user_pw = user_pw.encode() # below function needs user_pw in bytes object in python 3 so converting that
decode_user_pw = base64.b64decode(user_pw)
list_id_pw = decode_user_pw.decode().split(':')
user_dict['username'] = str(list_id_pw[0])
user_dict['password'] = str(list_id_pw[1])
password = CONF.conductor_api.password
username = CONF.conductor_api.username
# print ("plans.verify_user(): Expected username/password: {}/{}".format(username, password))
# print ("plans.verify_user(): Provided username/password: {}/{}".format(user_dict['username'], user_dict['password']))
retVal = False
if CONF.aaf_api.is_aaf_enabled:
retVal = aaf_auth.authenticate(user_dict['username'], user_dict['password'])
else:
if username == user_dict['username'] and password == user_dict['password']:
retVal = True
return retVal
|