code
stringlengths 41
2.04k
| label_name
stringclasses 2
values | label
int64 0
1
|
---|---|---|
def show_unit_extensions(request, course_id):
"""
Shows all of the students which have due date extensions for the given unit.
"""
course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
unit = find_unit(course, request.GET.get('url'))
return JsonResponse(dump_module_extensions(course, unit)) | CWE-352 | 0 |
def test_rescore_problem_single_from_uname(self, act):
""" Test rescoring of a single student. """
url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'unique_student_identifier': self.student.username,
})
self.assertEqual(response.status_code, 200)
self.assertTrue(act.called) | CWE-352 | 0 |
def rescore_problem(request, course_id):
"""
Starts a background process a students attempts counter. Optionally deletes student state for a problem.
Limited to instructor access.
Takes either of the following query paremeters
- problem_to_reset is a urlname of a problem
- unique_student_identifier is an email or username
- all_students is a boolean
all_students and unique_student_identifier cannot both be present.
"""
course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
problem_to_reset = strip_if_string(request.GET.get('problem_to_reset'))
student_identifier = request.GET.get('unique_student_identifier', None)
student = None
if student_identifier is not None:
student = get_student_from_identifier(student_identifier)
all_students = request.GET.get('all_students') in ['true', 'True', True]
if not (problem_to_reset and (all_students or student)):
return HttpResponseBadRequest("Missing query parameters.")
if all_students and student:
return HttpResponseBadRequest(
"Cannot rescore with all_students and unique_student_identifier."
)
try:
module_state_key = course_id.make_usage_key_from_deprecated_string(problem_to_reset)
except InvalidKeyError:
return HttpResponseBadRequest("Unable to parse problem id")
response_payload = {}
response_payload['problem_to_reset'] = problem_to_reset
if student:
response_payload['student'] = student_identifier
instructor_task.api.submit_rescore_problem_for_student(request, module_state_key, student)
response_payload['task'] = 'created'
elif all_students:
instructor_task.api.submit_rescore_problem_for_all_students(request, module_state_key)
response_payload['task'] = 'created'
else:
return HttpResponseBadRequest()
return JsonResponse(response_payload) | CWE-352 | 0 |
def test_post_broken_body():
response = client.post("/items/", data={"name": "Foo", "price": 50.5})
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"ctx": {
"colno": 1,
"doc": "name=Foo&price=50.5",
"lineno": 1,
"msg": "Expecting value",
"pos": 0,
},
"loc": ["body", 0],
"msg": "Expecting value: line 1 column 1 (char 0)",
"type": "value_error.jsondecode",
}
]
}
with patch("json.loads", side_effect=Exception):
response = client.post("/items/", json={"test": "test2"})
assert response.status_code == 400, response.text
assert response.json() == {"detail": "There was an error parsing the body"} | CWE-352 | 0 |
def test_certificates_features_group_by_mode(self):
"""
Test for certificate csv features against mode. Certificates should be group by 'mode' in reponse.
"""
url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})
# firstly generating downloadable certificates with 'honor' mode
certificate_count = 3
for __ in xrange(certificate_count):
self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)
response = self.client.get(url)
res_json = json.loads(response.content)
self.assertIn('certificates', res_json)
self.assertEqual(len(res_json['certificates']), 1)
# retrieve the first certificate from the list, there should be 3 certificates for 'honor' mode.
certificate = res_json['certificates'][0]
self.assertEqual(certificate.get('total_issued_certificate'), 3)
self.assertEqual(certificate.get('mode'), 'honor')
self.assertEqual(certificate.get('course_id'), str(self.course.id))
# Now generating downloadable certificates with 'verified' mode
for __ in xrange(certificate_count):
self.generate_certificate(
course_id=self.course.id,
mode='verified',
status=CertificateStatuses.downloadable
)
response = self.client.get(url)
res_json = json.loads(response.content)
self.assertIn('certificates', res_json)
# total certificate count should be 2 for 'verified' mode.
self.assertEqual(len(res_json['certificates']), 2)
# retrieve the second certificate from the list
certificate = res_json['certificates'][1]
self.assertEqual(certificate.get('total_issued_certificate'), 3)
self.assertEqual(certificate.get('mode'), 'verified') | CWE-352 | 0 |
def test_list_email_with_no_successes(self, task_history_request):
task_info = FakeContentTask(0, 0, 10, 'expected')
email = FakeEmail(0)
email_info = FakeEmailInfo(email, 0, 10)
task_history_request.return_value = [task_info]
url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})
with patch('instructor.views.api.CourseEmail.objects.get') as mock_email_info:
mock_email_info.return_value = email
response = self.client.get(url, {})
self.assertEqual(response.status_code, 200)
self.assertTrue(task_history_request.called)
returned_info_list = json.loads(response.content)['emails']
self.assertEqual(len(returned_info_list), 1)
returned_info = returned_info_list[0]
expected_info = email_info.to_dict()
self.assertDictEqual(expected_info, returned_info) | CWE-352 | 0 |
def get_problem_responses(request, course_id):
"""
Initiate generation of a CSV file containing all student answers
to a given problem.
Responds with JSON
{"status": "... status message ..."}
if initiation is successful (or generation task is already running).
Responds with BadRequest if problem location is faulty.
"""
course_key = CourseKey.from_string(course_id)
problem_location = request.GET.get('problem_location', '')
try:
problem_key = UsageKey.from_string(problem_location)
# Are we dealing with an "old-style" problem location?
run = problem_key.run
if not run:
problem_key = course_key.make_usage_key_from_deprecated_string(problem_location)
if problem_key.course_key != course_key:
raise InvalidKeyError(type(problem_key), problem_key)
except InvalidKeyError:
return JsonResponseBadRequest(_("Could not find problem with this location."))
try:
instructor_task.api.submit_calculate_problem_responses_csv(request, course_key, problem_location)
success_status = _(
"The problem responses report is being created."
" To view the status of the report, see Pending Tasks below."
)
return JsonResponse({"status": success_status})
except AlreadyRunningError:
already_running_status = _(
"A problem responses report generation task is already in progress. "
"Check the 'Pending Tasks' table for the status of the task. "
"When completed, the report will be available for download in the table below."
)
return JsonResponse({"status": already_running_status}) | CWE-352 | 0 |
def change_due_date(request, course_id):
"""
Grants a due date extension to a student for a particular unit.
"""
course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
student = require_student_from_identifier(request.GET.get('student'))
unit = find_unit(course, request.GET.get('url'))
due_date = parse_datetime(request.GET.get('due_datetime'))
set_due_date_extension(course, unit, student, due_date)
return JsonResponse(_(
'Successfully changed due date for student {0} for {1} '
'to {2}').format(student.profile.name, _display_unit(unit),
due_date.strftime('%Y-%m-%d %H:%M'))) | CWE-352 | 0 |
def test_modify_access_allow(self):
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_user.email,
'rolename': 'staff',
'action': 'allow',
})
self.assertEqual(response.status_code, 200) | CWE-352 | 0 |
def test_list_background_email_tasks(self, act):
"""Test list of background email tasks."""
act.return_value = self.tasks
url = reverse('list_background_email_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})
mock_factory = MockCompletionInfo()
with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:
mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info
response = self.client.get(url, {})
self.assertEqual(response.status_code, 200)
# check response
self.assertTrue(act.called)
expected_tasks = [ftask.to_dict() for ftask in self.tasks]
actual_tasks = json.loads(response.content)['tasks']
for exp_task, act_task in zip(expected_tasks, actual_tasks):
self.assertDictEqual(exp_task, act_task)
self.assertEqual(actual_tasks, expected_tasks) | CWE-352 | 0 |
def test_get_problem_responses_successful(self):
"""
Test whether get_problem_responses returns an appropriate status
message if CSV generation was started successfully.
"""
url = reverse(
'get_problem_responses',
kwargs={'course_id': unicode(self.course.id)}
)
problem_location = ''
response = self.client.get(url, {'problem_location': problem_location})
res_json = json.loads(response.content)
self.assertIn('status', res_json)
status = res_json['status']
self.assertIn('is being created', status)
self.assertNotIn('already in progress', status) | CWE-352 | 0 |
def test_modify_access_bad_role(self):
""" Test with an invalid action parameter. """
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_staff.email,
'rolename': 'robot-not-a-roll',
'action': 'revoke',
})
self.assertEqual(response.status_code, 400) | CWE-352 | 0 |
def call_add_users_to_cohorts(self, csv_data, suffix='.csv', method='POST'):
"""
Call `add_users_to_cohorts` with a file generated from `csv_data`.
"""
# this temporary file will be removed in `self.tearDown()`
__, file_name = tempfile.mkstemp(suffix=suffix, dir=self.tempdir)
with open(file_name, 'w') as file_pointer:
file_pointer.write(csv_data.encode('utf-8'))
with open(file_name, 'r') as file_pointer:
url = reverse('add_users_to_cohorts', kwargs={'course_id': unicode(self.course.id)})
if method == 'POST':
return self.client.post(url, {'uploaded-file': file_pointer})
elif method == 'GET':
return self.client.get(url, {'uploaded-file': file_pointer}) | CWE-352 | 0 |
def show_student_extensions(request, course_id):
"""
Shows all of the due date extensions granted to a particular student in a
particular course.
"""
student = require_student_from_identifier(request.GET.get('student'))
course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
return JsonResponse(dump_student_extensions(course, student)) | CWE-352 | 0 |
def test_create_registration_code_without_invoice_and_order(self):
"""
test generate detailed enrollment report,
used a registration codes which has been created via invoice or bulk
purchase scenario.
"""
course_registration_code = CourseRegistrationCode.objects.create(
code='abcde',
course_id=self.course.id.to_deprecated_string(),
created_by=self.instructor,
mode_slug='honor'
)
test_user1 = UserFactory()
self.register_with_redemption_code(test_user1, course_registration_code.code)
CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
self.client.login(username=self.instructor.username, password='test')
url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {})
self.assertIn('The detailed enrollment report is being created.', response.content) | CWE-352 | 0 |
def rescore_entrance_exam(request, course_id):
"""
Starts a background process a students attempts counter for entrance exam.
Optionally deletes student state for a problem. Limited to instructor access.
Takes either of the following query parameters
- unique_student_identifier is an email or username
- all_students is a boolean
all_students and unique_student_identifier cannot both be present.
"""
course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
course = get_course_with_access(
request.user, 'staff', course_id, depth=None
)
student_identifier = request.GET.get('unique_student_identifier', None)
student = None
if student_identifier is not None:
student = get_student_from_identifier(student_identifier)
all_students = request.GET.get('all_students') in ['true', 'True', True]
if not course.entrance_exam_id:
return HttpResponseBadRequest(
_("Course has no entrance exam section.")
)
if all_students and student:
return HttpResponseBadRequest(
_("Cannot rescore with all_students and unique_student_identifier.")
)
try:
entrance_exam_key = course_id.make_usage_key_from_deprecated_string(course.entrance_exam_id)
except InvalidKeyError:
return HttpResponseBadRequest(_("Course has no valid entrance exam section."))
response_payload = {}
if student:
response_payload['student'] = student_identifier
else:
response_payload['student'] = _("All Students")
instructor_task.api.submit_rescore_entrance_exam_for_student(request, entrance_exam_key, student)
response_payload['task'] = 'created'
return JsonResponse(response_payload) | CWE-352 | 0 |
def test_unicode_encode_error(self, mocker):
url = QUrl('file:///tmp/foo')
req = QNetworkRequest(url)
err = UnicodeEncodeError('ascii', '', 0, 2, 'foo')
mocker.patch('os.path.isdir', side_effect=err)
reply = filescheme.handler(req)
assert reply is None | CWE-352 | 0 |
def _access_endpoint(self, endpoint, args, status_code, msg):
"""
Asserts that accessing the given `endpoint` gets a response of `status_code`.
endpoint: string, endpoint for instructor dash API
args: dict, kwargs for `reverse` call
status_code: expected HTTP status code response
msg: message to display if assertion fails.
"""
url = reverse(endpoint, kwargs={'course_id': self.course.id.to_deprecated_string()})
if endpoint in ['send_email', 'students_update_enrollment', 'bulk_beta_modify_access']:
response = self.client.post(url, args)
else:
response = self.client.get(url, args)
self.assertEqual(
response.status_code,
status_code,
msg=msg
) | CWE-352 | 0 |
def test_list_course_role_members_bad_rolename(self):
""" Test with an invalid rolename parameter. """
url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'rolename': 'robot-not-a-rolename',
})
self.assertEqual(response.status_code, 400) | CWE-352 | 0 |
def test_rescore_problem_single(self, act):
""" Test rescoring of a single student. """
url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'unique_student_identifier': self.student.email,
})
self.assertEqual(response.status_code, 200)
self.assertTrue(act.called) | CWE-352 | 0 |
def test_coupon_redeem_count_in_ecommerce_section(self):
"""
Test that checks the redeem count in the instructor_dashboard coupon section
"""
# add the coupon code for the course
coupon = Coupon(
code='test_code', description='test_description', course_id=self.course.id,
percentage_discount='10', created_by=self.instructor, is_active=True
)
coupon.save()
# Coupon Redeem Count only visible for Financial Admins.
CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
PaidCourseRegistration.add_to_order(self.cart, self.course.id)
# apply the coupon code to the item in the cart
resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': coupon.code})
self.assertEqual(resp.status_code, 200)
# URL for instructor dashboard
instructor_dashboard = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()})
# visit the instructor dashboard page and
# check that the coupon redeem count should be 0
resp = self.client.get(instructor_dashboard)
self.assertEqual(resp.status_code, 200)
self.assertIn('Number Redeemed', resp.content)
self.assertIn('<td>0</td>', resp.content)
# now make the payment of your cart items
self.cart.purchase()
# visit the instructor dashboard page and
# check that the coupon redeem count should be 1
resp = self.client.get(instructor_dashboard)
self.assertEqual(resp.status_code, 200)
self.assertIn('Number Redeemed', resp.content)
self.assertIn('<td>1</td>', resp.content) | CWE-352 | 0 |
def require_query_params(*args, **kwargs):
"""
Checks for required paremters or renders a 400 error.
(decorator with arguments)
`args` is a *list of required GET parameter names.
`kwargs` is a **dict of required GET parameter names
to string explanations of the parameter
"""
required_params = []
required_params += [(arg, None) for arg in args]
required_params += [(key, kwargs[key]) for key in kwargs]
# required_params = e.g. [('action', 'enroll or unenroll'), ['emails', None]]
def decorator(func): # pylint: disable=missing-docstring
def wrapped(*args, **kwargs): # pylint: disable=missing-docstring
request = args[0]
error_response_data = {
'error': 'Missing required query parameter(s)',
'parameters': [],
'info': {},
}
for (param, extra) in required_params:
default = object()
if request.GET.get(param, default) == default:
error_response_data['parameters'].append(param)
error_response_data['info'][param] = extra
if len(error_response_data['parameters']) > 0:
return JsonResponse(error_response_data, status=400)
else:
return func(*args, **kwargs)
return wrapped
return decorator | CWE-352 | 0 |
def test_rescore_entrance_exam_all_student(self):
""" Test rescoring for all students. """
url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url, {
'all_students': True,
})
self.assertEqual(response.status_code, 200) | CWE-352 | 0 |
def test_reset_student_attempts_all(self, act):
""" Test reset all student attempts. """
url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'all_students': True,
})
self.assertEqual(response.status_code, 200)
self.assertTrue(act.called) | CWE-352 | 0 |
def test_get_students_features(self):
"""
Test that some minimum of information is formatted
correctly in the response to get_students_features.
"""
for student in self.students:
student.profile.city = "Mos Eisley {}".format(student.id)
student.profile.save()
url = reverse('get_students_features', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertIn('students', res_json)
for student in self.students:
student_json = [
x for x in res_json['students']
if x['username'] == student.username
][0]
self.assertEqual(student_json['username'], student.username)
self.assertEqual(student_json['email'], student.email)
self.assertEqual(student_json['city'], student.profile.city)
self.assertEqual(student_json['country'], "") | CWE-352 | 0 |
def handler(request):
"""Handler for a file:// URL.
Args:
request: QNetworkRequest to answer to.
Return:
A QNetworkReply for directories, None for files.
"""
path = request.url().toLocalFile()
try:
if os.path.isdir(path):
data = dirbrowser_html(path)
return networkreply.FixedDataNetworkReply(
request, data, 'text/html')
return None
except UnicodeEncodeError:
return None | CWE-352 | 0 |
def __init__(self):
field_infos = [
FieldInfo.factory(key)
for key in list(request.form.keys()) + list(request.files.keys())
]
# important to sort them so they will be in expected order on command line
self.field_infos = list(sorted(field_infos))
| CWE-352 | 0 |
def test_get_problem_responses_already_running(self):
"""
Test whether get_problem_responses returns an appropriate status
message if CSV generation is already in progress.
"""
url = reverse(
'get_problem_responses',
kwargs={'course_id': unicode(self.course.id)}
)
with patch('instructor_task.api.submit_calculate_problem_responses_csv') as submit_task_function:
error = AlreadyRunningError()
submit_task_function.side_effect = error
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertIn('status', res_json)
self.assertIn('already in progress', res_json['status']) | CWE-352 | 0 |
def test_reset_student_attempts_nonsense(self):
""" Test failure with both unique_student_identifier and all_students. """
url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'unique_student_identifier': self.student.email,
'all_students': True,
})
self.assertEqual(response.status_code, 400) | CWE-352 | 0 |
def test_reset_student_attempts_missingmodule(self):
""" Test reset for non-existant problem. """
url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': 'robot-not-a-real-module',
'unique_student_identifier': self.student.email,
})
self.assertEqual(response.status_code, 400) | CWE-352 | 0 |
def test_get_student_exam_results(self):
"""
Test whether get_proctored_exam_results returns an appropriate
status message when users request a CSV file.
"""
url = reverse(
'get_proctored_exam_results',
kwargs={'course_id': unicode(self.course.id)}
)
# Successful case:
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertIn('status', res_json)
self.assertNotIn('currently being created', res_json['status'])
# CSV generation already in progress:
with patch('instructor_task.api.submit_proctored_exam_results_report') as submit_task_function:
error = AlreadyRunningError()
submit_task_function.side_effect = error
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertIn('status', res_json)
self.assertIn('currently being created', res_json['status']) | CWE-352 | 0 |
def test_get_problem_responses_invalid_location(self):
"""
Test whether get_problem_responses returns an appropriate status
message when users submit an invalid problem location.
"""
url = reverse(
'get_problem_responses',
kwargs={'course_id': unicode(self.course.id)}
)
problem_location = ''
response = self.client.get(url, {'problem_location': problem_location})
res_json = json.loads(response.content)
self.assertEqual(res_json, 'Could not find problem with this location.') | CWE-352 | 0 |
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/json");
final PrintWriter out = resp.getWriter();
HttpSession session = req.getSession(false);
if (session != null) {
Subject subject = (Subject) session.getAttribute("subject");
if (subject == null) {
LOG.warn("No security subject stored in existing session, invalidating");
session.invalidate();
Helpers.doForbidden(resp);
}
returnPrincipals(subject, out);
return;
}
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
if (subject == null) {
Helpers.doForbidden(resp);
return;
}
Set<Principal> principals = subject.getPrincipals();
String username = null;
if (principals != null) {
for (Principal principal : principals) {
if (principal.getClass().getSimpleName().equals("UserPrincipal")) {
username = principal.getName();
LOG.debug("Authorizing user {}", username);
}
}
}
session = req.getSession(true);
session.setAttribute("subject", subject);
session.setAttribute("user", username);
session.setAttribute("org.osgi.service.http.authentication.remote.user", username);
session.setAttribute("org.osgi.service.http.authentication.type", HttpServletRequest.BASIC_AUTH);
session.setAttribute("loginTime", GregorianCalendar.getInstance().getTimeInMillis());
if (timeout != null) {
session.setMaxInactiveInterval(timeout);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Http session timeout for user {} is {} sec.", username, session.getMaxInactiveInterval());
}
returnPrincipals(subject, out);
} | CWE-352 | 0 |
public void initWithCustomLogHandler() throws Exception {
servlet = new AgentServlet();
config = createMock(ServletConfig.class);
context = createMock(ServletContext.class);
HttpTestUtil.prepareServletConfigMock(config, new String[]{ConfigKey.LOGHANDLER_CLASS.getKeyValue(), CustomLogHandler.class.getName()});
HttpTestUtil.prepareServletContextMock(context,null);
expect(config.getServletContext()).andReturn(context).anyTimes();
expect(config.getServletName()).andReturn("jolokia").anyTimes();
replay(config, context);
servlet.init(config);
servlet.destroy();
assertTrue(CustomLogHandler.infoCount > 0);
} | CWE-352 | 0 |
public void accessDenied() {
expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(false);
replay(backend);
handler.checkClientIPAccess("localhost","127.0.0.1");
} | CWE-352 | 0 |
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
String oldName = request.getParameter("groupName");
String newName = request.getParameter("newName");
if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {
m_groupRepository.renameGroup(oldName, newName);
}
return listGroups(request, response);
} | CWE-352 | 0 |
public void preflightCheck() {
String origin = "http://bla.com";
String headers ="X-Data: Test";
expect(backend.isCorsAccessAllowed(origin)).andReturn(true);
replay(backend);
Map<String,String> ret = handler.handleCorsPreflightRequest(origin, headers);
assertEquals(ret.get("Access-Control-Allow-Origin"),origin);
} | CWE-352 | 0 |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session == null) {
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
if (subject == null) {
Helpers.doForbidden(response);
return;
}
session = request.getSession(true);
session.setAttribute("subject", subject);
} else {
Subject subject = (Subject) session.getAttribute("subject");
if (subject == null) {
session.invalidate();
Helpers.doForbidden(response);
return;
}
}
String encoding = request.getHeader("Accept-Encoding");
boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
SessionTerminal st = (SessionTerminal) session.getAttribute("terminal");
if (st == null || st.isClosed()) {
st = new SessionTerminal(getCommandProcessor(), getThreadIO());
session.setAttribute("terminal", st);
}
String str = request.getParameter("k");
String f = request.getParameter("f");
String dump = st.handle(str, f != null && f.length() > 0);
if (dump != null) {
if (supportsGzip) {
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Content-Type", "text/html");
try {
GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
gzos.write(dump.getBytes());
gzos.close();
} catch (IOException ie) {
LOG.info("Exception writing response: ", ie);
}
} else {
response.getOutputStream().write(dump.getBytes());
}
}
} | CWE-352 | 0 |
public void withRestrictor() throws InvalidSyntaxException, MalformedObjectNameException {
setupRestrictor(new InnerRestrictor(true,false,true,false,true,false,true));
assertTrue(restrictor.isHttpMethodAllowed(HttpMethod.GET));
assertFalse(restrictor.isTypeAllowed(RequestType.EXEC));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
assertFalse(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
assertTrue(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Memory"), "gc"));
assertFalse(restrictor.isRemoteAccessAllowed("localhost", "127.0.0.1"));
assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
} | CWE-352 | 0 |
public boolean isCorsAccessAllowed(String pOrigin) {
return restrictor.isCorsAccessAllowed(pOrigin);
} | CWE-352 | 0 |
public boolean isCorsAccessAllowed(String pOrigin) {
return isAllowed;
} | CWE-352 | 0 |
public void preflightCheckNegative() {
String origin = "http://bla.com";
String headers ="X-Data: Test";
expect(backend.isCorsAccessAllowed(origin)).andReturn(false);
replay(backend);
Map<String,String> ret = handler.handleCorsPreflightRequest(origin, headers);
assertNull(ret.get("Access-Control-Allow-Origin"));
} | CWE-352 | 0 |
public void initWithAgentDiscoveryAndUrlCreationAfterGet() throws ServletException, IOException {
checkMulticastAvailable();
prepareStandardInitialisation(ConfigKey.DISCOVERY_ENABLED.getKeyValue(), "true");
try {
StringWriter sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
String url = "http://pirx:9876/jolokia";
StringBuffer buf = new StringBuffer();
buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getRequestURL()).andReturn(buf);
expect(request.getRequestURI()).andReturn(buf.toString());
expect(request.getContextPath()).andReturn("/jolokia");
expect(request.getAuthType()).andReturn("BASIC");
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
JolokiaDiscovery discovery = new JolokiaDiscovery("test",LogHandler.QUIET);
List<JSONObject> in = discovery.lookupAgents();
assertTrue(in.size() > 0);
for (JSONObject json : in) {
if (json.get("url") != null && json.get("url").equals(url)) {
assertTrue((Boolean) json.get("secured"));
return;
}
}
fail("Failed, because no message had an URL");
} finally {
servlet.destroy();
}
} | CWE-352 | 0 |
public RechnungCostEditTablePanel(final String id)
{
super(id);
feedbackPanel = new FeedbackPanel("feedback");
ajaxComponents.register(feedbackPanel);
add(feedbackPanel);
this.form = new Form<AbstractRechnungsPositionDO>("form");
add(form);
rows = new RepeatingView("rows");
form.add(rows);
} | CWE-352 | 0 |
public void corsEmpty() {
InputStream is = getClass().getResourceAsStream("/allow-origin3.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.consol.de"));
} | CWE-352 | 0 |
public void setupRoutes() {
path(controllerBasePath(), () -> {
before("", mimeType, this::setContentType);
// change the line below to enable appropriate security
before("", mimeType, this.apiAuthenticationHelper::checkAdminUserAnd403);
get("", mimeType, this::show);
post("", mimeType, this::createOrUpdate);
put("", mimeType, this::createOrUpdate);
delete("", mimeType, this::deleteBackupConfig);
});
} | CWE-352 | 0 |
public void debug() throws IOException, ServletException {
servlet = new AgentServlet();
initConfigMocks(new String[]{ConfigKey.DEBUG.getKeyValue(), "true"},null,"No access restrictor found",null);
context.log(find("URI:"));
context.log(find("Path-Info:"));
context.log(find("Request:"));
context.log(find("time:"));
context.log(find("Response:"));
context.log(find("TestDetector"),isA(RuntimeException.class));
expectLastCall().anyTimes();
replay(config, context);
servlet.init(config);
StringWriter sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
servlet.destroy();
} | CWE-352 | 0 |
public void corsWildCard() {
InputStream is = getClass().getResourceAsStream("/allow-origin2.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.consol.de"));
} | CWE-352 | 0 |
public boolean isCorsAccessAllowed(String pOrigin) {
return corsChecker.check(pOrigin);
} | CWE-352 | 0 |
private Runnable getStandardRequestSetup() {
return new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andReturn(null);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getParameterMap()).andReturn(null);
}
};
} | CWE-352 | 0 |
private void returnPrincipals(Subject subject, PrintWriter out) {
Map<String, Object> answer = new HashMap<String, Object>();
List<Object> principals = new ArrayList<Object>();
for (Principal principal : subject.getPrincipals()) {
Map<String, String> data = new HashMap<String, String>();
data.put("type", principal.getClass().getName());
data.put("name", principal.getName());
principals.add(data);
}
List<Object> credentials = new ArrayList<Object>();
for (Object credential : subject.getPublicCredentials()) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("type", credential.getClass().getName());
data.put("credential", credential);
}
answer.put("principals", principals);
answer.put("credentials", credentials);
ServletHelpers.writeObject(converters, options, out, answer);
} | CWE-352 | 0 |
public boolean check(String pArg) {
if (patterns == null || patterns.size() == 0) {
return true;
}
for (Pattern pattern : patterns) {
if (pattern.matcher(pArg).matches()) {
return true;
}
}
return false;
} | CWE-352 | 0 |
public CorsChecker(Document pDoc) {
NodeList corsNodes = pDoc.getElementsByTagName("cors");
if (corsNodes.getLength() > 0) {
patterns = new ArrayList<Pattern>();
for (int i = 0; i < corsNodes.getLength(); i++) {
Node corsNode = corsNodes.item(i);
NodeList nodes = corsNode.getChildNodes();
for (int j = 0;j <nodes.getLength();j++) {
Node node = nodes.item(j);
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
assertNodeName(node,"allow-origin");
String p = node.getTextContent().trim().toLowerCase();
p = Pattern.quote(p).replace("*","\\E.*\\Q");
patterns.add(Pattern.compile("^" + p + "$"));
}
}
}
} | CWE-352 | 0 |
public void checkClientIPAccess(String pHost, String pAddress) {
if (!backendManager.isRemoteAccessAllowed(pHost,pAddress)) {
throw new SecurityException("No access from client " + pAddress + " allowed");
}
} | CWE-352 | 0 |
public void simpleGetWithUnsupportedGetParameterMapCall() throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks(
new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andReturn(null);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameterMap()).andThrow(new UnsupportedOperationException(""));
Vector params = new Vector();
params.add("debug");
expect(request.getParameterNames()).andReturn(params.elements());
expect(request.getParameterValues("debug")).andReturn(new String[] {"false"});
}
},
getStandardResponseSetup());
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);
replay(request,response);
servlet.doGet(request,response);
servlet.destroy();
} | CWE-352 | 0 |
private void checkCorsGetOrigin(final String in, final String out) throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks(
new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andReturn(in);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getParameterMap()).andReturn(null);
}
},
new Runnable() {
public void run() {
response.setHeader("Access-Control-Allow-Origin", out);
response.setHeader("Access-Control-Allow-Credentials","true");
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setStatus(200);
}
}
);
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
replay(request, response);
servlet.doGet(request, response);
servlet.destroy();
} | CWE-352 | 0 |
public void cors() {
InputStream is = getClass().getResourceAsStream("/allow-origin1.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
assertFalse(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
assertTrue(restrictor.isCorsAccessAllowed("https://www.consol.de"));
} | CWE-352 | 0 |
public CsrfTokenHandler(final Form< ? > form)
{
form.add(csrfTokenField = new HiddenField<String>("csrfToken", Model.of(getCsrfSessionToken())));
} | CWE-352 | 0 |
private void initConfigMocks(String[] pInitParams, String[] pContextParams,String pLogRegexp, Class<? extends Exception> pExceptionClass) {
config = createMock(ServletConfig.class);
context = createMock(ServletContext.class);
String[] params = pInitParams != null ? Arrays.copyOf(pInitParams,pInitParams.length + 2) : new String[2];
params[params.length - 2] = ConfigKey.DEBUG.getKeyValue();
params[params.length - 1] = "true";
HttpTestUtil.prepareServletConfigMock(config,params);
HttpTestUtil.prepareServletContextMock(context, pContextParams);
expect(config.getServletContext()).andReturn(context).anyTimes();
expect(config.getServletName()).andReturn("jolokia").anyTimes();
if (pExceptionClass != null) {
context.log(find(pLogRegexp),isA(pExceptionClass));
} else {
if (pLogRegexp != null) {
context.log(find(pLogRegexp));
} else {
context.log((String) anyObject());
}
}
context.log((String) anyObject());
expectLastCall().anyTimes();
context.log(find("TestDetector"),isA(RuntimeException.class));
} | CWE-352 | 0 |
public Map<String, String> handleCorsPreflightRequest(String pOrigin, String pRequestHeaders) {
Map<String,String> ret = new HashMap<String, String>();
if (pOrigin != null && backendManager.isCorsAccessAllowed(pOrigin)) {
// CORS is allowed, we set exactly the origin in the header, so there are no problems with authentication
ret.put("Access-Control-Allow-Origin","null".equals(pOrigin) ? "*" : pOrigin);
if (pRequestHeaders != null) {
ret.put("Access-Control-Allow-Headers",pRequestHeaders);
}
// Fix for CORS with authentication (#104)
ret.put("Access-Control-Allow-Credentials","true");
// Allow for one year. Changes in access.xml are reflected directly in the cors request itself
ret.put("Access-Control-Allow-Max-Age","" + 3600 * 24 * 365);
}
return ret;
} | CWE-352 | 0 |
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
String oldName = request.getParameter("groupName");
String newName = request.getParameter("newName");
if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {
m_groupRepository.renameGroup(oldName, newName);
}
return listGroups(request, response);
} | CWE-352 | 0 |
public void corsAccessCheck() {
BackendManager backendManager = new BackendManager(config,log);
assertTrue(backendManager.isCorsAccessAllowed("http://bla.com"));
backendManager.destroy();
} | CWE-352 | 0 |
private void handle(ServletRequestHandler pReqHandler,HttpServletRequest pReq, HttpServletResponse pResp) throws IOException {
JSONAware json = null;
try {
// Check access policy
requestHandler.checkClientIPAccess(pReq.getRemoteHost(),pReq.getRemoteAddr());
// Remember the agent URL upon the first request. Needed for discovery
updateAgentUrlIfNeeded(pReq);
// Dispatch for the proper HTTP request method
json = pReqHandler.handleRequest(pReq,pResp);
} catch (Throwable exp) {
json = requestHandler.handleThrowable(
exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
} finally {
setCorsHeader(pReq, pResp);
String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue());
String answer = json != null ?
json.toJSONString() :
requestHandler.handleThrowable(new Exception("Internal error while handling an exception")).toJSONString();
if (callback != null) {
// Send a JSONP response
sendResponse(pResp, "text/javascript", callback + "(" + answer + ");");
} else {
sendResponse(pResp, getMimeType(pReq),answer);
}
}
} | CWE-352 | 0 |
public String extractCorsOrigin(String pOrigin) {
if (pOrigin != null) {
// Prevent HTTP response splitting attacks
String origin = pOrigin.replaceAll("[\\n\\r]*","");
if (backendManager.isCorsAccessAllowed(origin)) {
return "null".equals(origin) ? "*" : origin;
} else {
return null;
}
}
return null;
} | CWE-352 | 0 |
def add_acl_usergroup(session, acl_role_id, user_group, name)
if (user_group == "user") or (user_group == "group")
stdout, stderr, retval = run_cmd(
session, PCS, "acl", user_group, "create", name.to_s, acl_role_id.to_s
)
if retval == 0
return ""
end
if not /^error: (user|group) #{name.to_s} already exists$/i.match(stderr.join("\n").strip)
return stderr.join("\n").strip
end
end
stdout, stderror, retval = run_cmd(
session, PCS, "acl", "role", "assign", acl_role_id.to_s, name.to_s
)
if retval != 0
if stderror.empty?
return "Error adding #{user_group}"
else
return stderror.join("\n").strip
end
end
return ""
end | CWE-384 | 1 |
def remote_add_node(params, request, session, all=false)
if not allowed_for_local_cluster(session, Permissions::FULL)
return 403, 'Permission denied'
end
auto_start = false
if params[:auto_start] and params[:auto_start] == "1"
auto_start = true
end
if params[:new_nodename] != nil
node = params[:new_nodename]
if params[:new_ring1addr] != nil
node += ',' + params[:new_ring1addr]
end
retval, output = add_node(session, node, all, auto_start)
end
if retval == 0
return [200, JSON.generate([retval, get_corosync_conf()])]
end
return [400,output]
end | CWE-384 | 1 |
def get_configs_cluster(nodes, cluster_name)
data = {
'cluster_name' => cluster_name,
}
$logger.debug 'Fetching configs from the cluster'
threads = []
node_configs = {}
nodes.each { |node|
threads << Thread.new {
code, out = send_request_with_token(
@session, node, 'get_configs', false, data
)
if 200 == code
begin
parsed = JSON::parse(out)
if 'ok' == parsed['status'] and cluster_name == parsed['cluster_name']
node_configs[node], _ = Cfgsync::sync_msg_to_configs(parsed)
end
rescue JSON::ParserError
end
end
}
}
threads.each { |t| t.join }
return node_configs
end | CWE-384 | 1 |
def auth(params, request, session)
token = PCSAuth.validUser(params['username'],params['password'], true)
# If we authorized to this machine, attempt to authorize everywhere
node_list = []
if token and params["bidirectional"]
params.each { |k,v|
if k.start_with?("node-")
node_list.push(v)
end
}
if node_list.length > 0
pcs_auth(
session, node_list, params['username'], params['password'],
params["force"] == "1"
)
end
end
return token
end | CWE-384 | 1 |
def add_node_attr_remote(params, request, session)
if not allowed_for_local_cluster(session, Permissions::WRITE)
return 403, 'Permission denied'
end
retval = add_node_attr(
session, params["node"], params["key"], params["value"]
)
# retval = 2 if removing attr which doesn't exist
if retval == 0 or retval == 2
return [200, "Successfully added attribute to node"]
else
return [400, "Error adding attribute to node"]
end
end | CWE-384 | 1 |
def add_fence_level(session, level, devices, node, remove = false)
if not remove
stdout, stderr, retval = run_cmd(
session, PCS, "stonith", "level", "add", level, node, devices
)
return retval,stdout, stderr
else
stdout, stderr, retval = run_cmd(
session, PCS, "stonith", "level", "remove", level, node, devices
)
return retval,stdout, stderr
end
end | CWE-384 | 1 |
def authorize_params
super.tap do |params|
%w[display state scope].each do |v|
if request.params[v]
params[v.to_sym] = request.params[v]
# to support omniauth-oauth2's auto csrf protection
session['omniauth.state'] = params[:state] if v == 'state'
end
end
params[:scope] ||= DEFAULT_SCOPE
end
end | CWE-352 | 0 |
def resource_cleanup(params, request, session)
if not allowed_for_local_cluster(session, Permissions::WRITE)
return 403, 'Permission denied'
end
stdout, stderr, retval = run_cmd(
session, PCS, "resource", "cleanup", params[:resource]
)
if retval == 0
return JSON.generate({"success" => "true"})
else
return JSON.generate({"error" => "true", "stdout" => stdout, "stderror" => stderr})
end
end | CWE-384 | 1 |
def save_tokens(params, request, session)
# pcsd runs as root thus always returns hacluster's tokens
if not allowed_for_local_cluster(session, Permissions::FULL)
return 403, "Permission denied"
end
new_tokens = {}
params.each{|nodes|
if nodes[0].start_with?"node:" and nodes[0].length > 5
node = nodes[0][5..-1]
token = nodes[1]
new_tokens[node] = token
end
}
tokens_cfg = Cfgsync::PcsdTokens.from_file('')
sync_successful, sync_responses = Cfgsync::save_sync_new_tokens(
tokens_cfg, new_tokens, get_corosync_nodes(), $cluster_name
)
if sync_successful
return [200, JSON.generate(read_tokens())]
else
return [400, "Cannot update tokenfile."]
end
end | CWE-384 | 1 |
def add_acl_permission(session, acl_role_id, perm_type, xpath_id, query_id)
stdout, stderror, retval = run_cmd(
session, PCS, "acl", "permission", "add", acl_role_id.to_s, perm_type.to_s,
xpath_id.to_s, query_id.to_s
)
if retval != 0
if stderror.empty?
return "Error adding permission"
else
return stderror.join("\n").strip
end
end
return ""
end | CWE-384 | 1 |
def enable_cluster(session)
stdout, stderror, retval = run_cmd(session, PCS, "cluster", "enable")
return false if retval != 0
return true
end | CWE-384 | 1 |
def cluster_start(params, request, session)
if params[:name]
code, response = send_request_with_token(
session, params[:name], 'cluster_start', true
)
else
if not allowed_for_local_cluster(session, Permissions::WRITE)
return 403, 'Permission denied'
end
$logger.info "Starting Daemons"
output = `#{PCS} cluster start`
$logger.debug output
return output
end
end | CWE-384 | 1 |
def resource_ungroup(params, request, session)
if not allowed_for_local_cluster(session, Permissions::WRITE)
return 403, 'Permission denied'
end
unless params[:group_id]
return [400, 'group_id has to be specified.']
end
_, stderr, retval = run_cmd(
session, PCS, 'resource', 'ungroup', params[:group_id]
)
if retval != 0
return [400, 'Unable to ungroup group ' +
"'#{params[:group_id]}': #{stderr.join('')}"
]
end
return 200
end | CWE-384 | 1 |
def remove_constraint_rule_remote(params, request, session)
if not allowed_for_local_cluster(session, Permissions::WRITE)
return 403, 'Permission denied'
end
if params[:rule_id]
retval = remove_constraint_rule(session, params[:rule_id])
if retval == 0
return "Constraint rule #{params[:rule_id]} removed"
else
return [400, "Error removing constraint rule: #{params[:rule_id]}"]
end
else
return [400, "Bad Constraint Rule Options"]
end
end | CWE-384 | 1 |
def add_constraint_set_remote(params, request, session)
if not allowed_for_local_cluster(session, Permissions::WRITE)
return 403, 'Permission denied'
end
case params["c_type"]
when "ord"
retval, error = add_order_set_constraint(
session,
params["resources"].values, params["force"], !params['disable_autocorrect']
)
else
return [400, "Unknown constraint type: #{params["c_type"]}"]
end | CWE-384 | 1 |
def send_cluster_request_with_token(session, cluster_name, request, post=false, data={}, remote=true, raw_data=nil)
$logger.info("SCRWT: " + request)
nodes = get_cluster_nodes(cluster_name)
return send_nodes_request_with_token(
session, nodes, request, post, data, remote, raw_data
)
end | CWE-384 | 1 |
def cluster_status_remote(params, request, session)
if not allowed_for_local_cluster(session, Permissions::READ)
return 403, 'Permission denied'
end
cluster_name = $cluster_name
# If node is not in a cluster, return empty data
if not cluster_name or cluster_name.empty?
overview = {
:cluster_name => nil,
:error_list => [],
:warning_list => [],
:quorate => nil,
:status => 'unknown',
:node_list => [],
:resource_list => [],
}
return JSON.generate(overview)
end
cluster_nodes = get_nodes().flatten
status = cluster_status_from_nodes(session, cluster_nodes, cluster_name)
unless status
return 403, 'Permission denied'
end
return JSON.generate(status)
end | CWE-384 | 1 |
def get_avail_resource_agents(params, request, session)
if not allowed_for_local_cluster(session, Permissions::READ)
return 403, 'Permission denied'
end
agents = getResourceAgents(session)
return JSON.generate(agents)
end | CWE-384 | 1 |
def get_permissions_remote(params, request, session)
if not allowed_for_local_cluster(session, Permissions::GRANT)
return 403, 'Permission denied'
end
pcs_config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text())
data = {
'user_types' => Permissions::get_user_types(),
'permission_types' => Permissions::get_permission_types(),
'permissions_dependencies' => Permissions::permissions_dependencies(),
'users_permissions' => pcs_config.permissions_local.to_hash(),
}
return [200, JSON.generate(data)]
end | CWE-384 | 1 |
def add_location_constraint_rule(
session, resource, rule, score, force=false, autocorrect=true
)
cmd = [PCS, "constraint", "location", resource, "rule"]
if score != ''
if is_score(score.upcase)
cmd << "score=#{score.upcase}"
else
cmd << "score-attribute=#{score}"
end
end
cmd.concat(rule.shellsplit())
cmd << '--force' if force
cmd << '--autocorrect' if autocorrect
stdout, stderr, retval = run_cmd(session, *cmd)
return retval, stderr.join(' ')
end | CWE-384 | 1 |
def getAllSettings(session, cib_dom=nil)
unless cib_dom
cib_dom = get_cib_dom(session)
end
ret = {}
if cib_dom
cib_dom.elements.each('/cib/configuration/crm_config//nvpair') { |e|
ret[e.attributes['name']] = e.attributes['value']
}
end
return ret
end | CWE-384 | 1 |
def add_acl_role(session, name, description)
cmd = [PCS, "acl", "role", "create", name.to_s]
if description.to_s != ""
cmd << "description=#{description.to_s}"
end
stdout, stderror, retval = run_cmd(session, *cmd)
if retval != 0
return stderror.join("\n").strip
end
return ""
end | CWE-384 | 1 |
def add_constraint_rule_remote(params, request, session)
if not allowed_for_local_cluster(session, Permissions::WRITE)
return 403, 'Permission denied'
end
if params["c_type"] == "loc"
retval, error = add_location_constraint_rule(
session,
params["res_id"], params["rule"], params["score"], params["force"],
!params['disable_autocorrect']
)
else
return [400, "Unknown constraint type: #{params["c_type"]}"]
end
if retval == 0
return [200, "Successfully added constraint"]
else
return [400, "Error adding constraint: #{error}"]
end
end | CWE-384 | 1 |
def self.loginByPassword(session, username, password)
if validUser(username, password)
session[:username] = username
success, groups = getUsersGroups(username)
session[:usergroups] = success ? groups : []
return true
end
return false
end | CWE-384 | 1 |
def get_configs(params, request, session)
if not allowed_for_local_cluster(session, Permissions::FULL)
return 403, 'Permission denied'
end
if not $cluster_name or $cluster_name.empty?
return JSON.generate({'status' => 'not_in_cluster'})
end
if params[:cluster_name] != $cluster_name
return JSON.generate({'status' => 'wrong_cluster_name'})
end
out = {
'status' => 'ok',
'cluster_name' => $cluster_name,
'configs' => {},
}
Cfgsync::get_configs_local.each { |name, cfg|
out['configs'][cfg.class.name] = {
'type' => 'file',
'text' => cfg.text,
}
}
return JSON.generate(out)
end | CWE-384 | 1 |
def config_backup(params, request, session)
if params[:name]
code, response = send_request_with_token(
session, params[:name], 'config_backup', true
)
else
if not allowed_for_local_cluster(session, Permissions::FULL)
return 403, 'Permission denied'
end
$logger.info "Backup node configuration"
stdout, stderr, retval = run_cmd(session, PCS, "config", "backup")
if retval == 0
$logger.info "Backup successful"
return [200, stdout]
end
$logger.info "Error during backup: #{stderr.join(' ').strip()}"
return [400, "Unable to backup node: #{stderr.join(' ')}"]
end
end | CWE-384 | 1 |
def get_local_node_id()
if ISRHEL6
out, errout, retval = run_cmd(
PCSAuth.getSuperuserSession, COROSYNC_CMAPCTL, "cluster.cman"
)
if retval != 0
return ""
end
match = /cluster\.nodename=(.*)/.match(out.join("\n"))
if not match
return ""
end
local_node_name = match[1]
out, errout, retval = run_cmd(
PCSAuth.getSuperuserSession,
CMAN_TOOL, "nodes", "-F", "id", "-n", local_node_name
)
if retval != 0
return ""
end
return out[0].strip()
end
out, errout, retval = run_cmd(
PCSAuth.getSuperuserSession,
COROSYNC_CMAPCTL, "-g", "runtime.votequorum.this_node_id"
)
if retval != 0
return ""
else
return out[0].split(/ = /)[1].strip()
end
end | CWE-384 | 1 |
def send_nodes_request_with_token(session, nodes, request, post=false, data={}, remote=true, raw_data=nil)
out = ""
code = 0
$logger.info("SNRWT: " + request)
# If we're removing nodes, we don't send this to one of the nodes we're
# removing, unless we're removing all nodes
if request == "/remove_nodes"
new_nodes = nodes.dup
data.each {|k,v|
if new_nodes.include? v
new_nodes.delete v
end
}
if new_nodes.length > 0
nodes = new_nodes
end
end
for node in nodes
$logger.info "SNRWT Node: #{node} Request: #{request}"
code, out = send_request_with_token(
session, node, request, post, data, remote, raw_data
)
# try next node if:
# - current node does not support the request (old version of pcsd?) (404)
# - an exception or other error occurred (5xx)
# - we don't have a token for the node (401, notoken)
# - we didn't get a response form the node (e.g. an exception occurred)
# - pacemaker is not running on the node
# do not try next node if
# - node returned 400 - it means the request cannot be processed because of
# invalid arguments or another known issue, no node would be able to
# process the request (e.g. removing a non-existing resource)
# - node returned 403 - permission denied, no node should allow to process
# the request
log = "SNRWT Node #{node} Request #{request}"
if (404 == code) or (code >= 500 and code <= 599)
$logger.info("#{log}: HTTP code #{code}")
next
end
if (401 == code) or ('{"notoken":true}' == out)
$logger.info("#{log}: Bad or missing token")
next
end
if '{"pacemaker_not_running":true}' == out
$logger.info("#{log}: Pacemaker not running")
next
end
if '{"noresponse":true}' == out
$logger.info("#{log}: No response")
next
end
$logger.info("#{log}: HTTP code #{code}")
break
end
return code, out
end | CWE-384 | 1 |
def remove_constraint_rule(session, rule_id)
stdout, stderror, retval = run_cmd(
session, PCS, "constraint", "rule", "remove", rule_id
)
$logger.info stdout
return retval
end | CWE-384 | 1 |
def add_location_constraint(
session, resource, node, score, force=false, autocorrect=true
)
if node == ""
return "Bad node"
end
if score == ""
nodescore = node
else
nodescore = node + "=" + score
end
cmd = [PCS, "constraint", "location", resource, "prefers", nodescore]
cmd << '--force' if force
cmd << '--autocorrect' if autocorrect
stdout, stderr, retval = run_cmd(session, *cmd)
return retval, stderr.join(' ')
end | CWE-384 | 1 |
def allowed_for_superuser(session)
$logger.debug(
"permission check superuser username=#{session[:username]} groups=#{session[:groups]}"
)
if SUPERUSER != session[:username]
$logger.debug('permission denied')
return false
end
$logger.debug('permission granted for superuser')
return true
end | CWE-384 | 1 |
def add_acl_role_remote(params, request, session)
if not allowed_for_local_cluster(session, Permissions::GRANT)
return 403, 'Permission denied'
end
retval = add_acl_role(session, params["name"], params["description"])
if retval == ""
return [200, "Successfully added ACL role"]
else
return [
400,
retval.include?("cib_replace failed") ? "Error adding ACL role" : retval
]
end
end | CWE-384 | 1 |
def setup_cluster(params, request, session)
if not allowed_for_superuser(session)
return 403, 'Permission denied'
end
$logger.info("Setting up cluster: " + params.inspect)
nodes_rrp = params[:nodes].split(';')
options = []
myoptions = JSON.parse(params[:options])
transport_udp = false
options_udp = []
myoptions.each { |o,v|
if ["wait_for_all", "last_man_standing", "auto_tie_breaker"].include?(o)
options << "--" + o + "=1"
end
options << "--" + o + "=" + v if [
"token", "token_coefficient", "join", "consensus", "miss_count_const",
"fail_recv_const", "last_man_standing_window",
].include?(o)
if o == "transport" and v == "udp"
options << "--transport=udp"
transport_udp = true
end
if o == "transport" and v == "udpu"
options << "--transport=udpu"
transport_udp = false
end
if ["addr0", "addr1", "mcast0", "mcast1", "mcastport0", "mcastport1", "ttl0", "ttl1"].include?(o)
options_udp << "--" + o + "=" + v
end
if ["broadcast0", "broadcast1"].include?(o)
options_udp << "--" + o
end
if o == "ipv6"
options << "--ipv6"
end
}
if transport_udp
nodes = []
nodes_rrp.each { |node| nodes << node.split(',')[0] }
else
nodes = nodes_rrp
end
nodes_options = nodes + options
nodes_options += options_udp if transport_udp
stdout, stderr, retval = run_cmd(
session, PCS, "cluster", "setup", "--enable", "--start",
"--name", params[:clustername], *nodes_options
)
if retval != 0
return [
400,
(stdout + [''] + stderr).collect { |line| line.rstrip() }.join("\n")
]
end
return 200
end | CWE-384 | 1 |
def remote_node_available(params, request, session)
if (not ISRHEL6 and File.exist?(Cfgsync::CorosyncConf.file_path)) or (ISRHEL6 and File.exist?(Cfgsync::ClusterConf.file_path)) or File.exist?("/var/lib/pacemaker/cib/cib.xml")
return JSON.generate({:node_available => false})
end
return JSON.generate({:node_available => true})
end | CWE-384 | 1 |
def remote_remove_node(params, request, session)
if not allowed_for_local_cluster(session, Permissions::FULL)
return 403, 'Permission denied'
end
if params[:remove_nodename] != nil
retval, output = remove_node(session, params[:remove_nodename])
else
return 400, "No nodename specified"
end
if retval == 0
return JSON.generate([retval, get_corosync_conf()])
end
return JSON.generate([retval,output])
end | CWE-384 | 1 |
def run_auth_requests(session, nodes_to_send, nodes_to_auth, username, password, force=false, local=true)
data = {}
nodes_to_auth.each_with_index { |node, index|
data["node-#{index}"] = node
}
data['username'] = username
data['password'] = password
data['bidirectional'] = 1 if not local
data['force'] = 1 if force
auth_responses = {}
threads = []
nodes_to_send.each { |node|
threads << Thread.new {
code, response = send_request(session, node, 'auth', true, data)
if 200 == code
token = response.strip
if '' == token
auth_responses[node] = {'status' => 'bad_password'}
else
auth_responses[node] = {'status' => 'ok', 'token' => token}
end
else
auth_responses[node] = {'status' => 'noresponse'}
end
}
}
threads.each { |t| t.join }
return auth_responses
end | CWE-384 | 1 |