Skip to content

Commit

Permalink
Auto-merge with AWS updates and bug fix for orgid redirect in vince/v…
Browse files Browse the repository at this point in the history
…iews.py
  • Loading branch information
sei-vsarvepalli committed Apr 21, 2023
1 parent 6e12387 commit 3c90e20
Show file tree
Hide file tree
Showing 22 changed files with 242 additions and 80 deletions.
11 changes: 10 additions & 1 deletion bigvince/settings_.py
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,16 @@ def get_secret(secret_arn):
#If you choose to disable TLP statements in CSAF comment out the MAP dictionary below
CSAF_TLP_MAP = { "PUBLIC": "WHITE", "PRIVATE": "AMBER" }

#Choose alternate method to validate Session Tokens for non-AWS tokens
#and for writing Tests with mock sessions
def ALT_VERIFY_TOKEN(user,session):
"""
This verify_token method provides an alternate way to verify Session
Tokens for writing Tests with mock sessions. Add your alternate method
if preferred to help with automated tests.
"""
return False

#Added in SECTORS for VERSION 2.0.8
SECTORS = (
('Chemical', 'Chemical'),
Expand All @@ -840,4 +850,3 @@ def get_secret(secret_arn):
('Transportation Systems', 'Transportation Systems'),
('Water and Wastewater Systems', 'Water and Wastewater Systems')
)

8 changes: 4 additions & 4 deletions bigvince/storage_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class PrivateMediaStorage(S3Boto3Storage):
region_name=settings.AWS_REGION
#region_name = "us-east-1"
custom_domain=False
if not settings.LOCALSTACK:
if not (hasattr(settings,"LOCALSTACK") and settings.LOCALSTACK):
bucket_name = getattr(settings, 'PRIVATE_BUCKET_NAME')
acl='private'
default_acl = 'private'
Expand All @@ -48,7 +48,7 @@ class SharedMediaStorage(S3Boto3Storage):
region_name = settings.AWS_REGION
#region_name = "us-east-1"
custom_domain = False
if not settings.LOCALSTACK:
if not (hasattr(settings,"LOCALSTACK") and settings.LOCALSTACK):
bucket_name = getattr(settings, 'VINCE_SHARED_BUCKET')
acl = 'private'
default_acl = 'private'
Expand All @@ -58,7 +58,7 @@ class VRFReportsStorage(S3Boto3Storage):
file_overwrite = False
custom_domain=False
region_name = settings.AWS_REGION
if not settings.LOCALSTACK:
if not (hasattr(settings,"LOCALSTACK") and settings.LOCALSTACK):
bucket_name = getattr(settings, 'S3_INCOMING_REPORTS')
acl = 'private'
default_acl = 'private'
default_acl = 'private'
2 changes: 1 addition & 1 deletion bigvince/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ def get_cognito_pool_url():

# adjusted as localstack is currently setting the hostname for cognito as just "localhost"
def get_cognito_url():
if settings.LOCALSTACK:
if hasattr(settings,"LOCALSTACK") and settings.LOCALSTACK:
base_url = settings.BASE_URL
return f"http://{base_url}"
else:
Expand Down
22 changes: 14 additions & 8 deletions cogauth/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ def mfafilter(mfa_name):
class TokenMixin(AccessMixin):

def dispatch(self, request, *args, **kwargs):
if hasattr(settings,'ALT_VERIFY_TOKEN') and settings.ALT_VERIFY_TOKEN(request.user,request.session):
""" If alternate token verify method provided for Automated
Tests, use it """
return super(TokenMixin, self).dispatch(request, *args, **kwargs)
if not request.session.get('REFRESH_TOKEN'):
return self.handle_no_permission()
try:
Expand Down Expand Up @@ -126,8 +130,7 @@ def get_user(self):
if (self.cognito is None):
self.cognito = get_cognito(self.request)
user = self.cognito.get_user(attr_map=settings.COGNITO_ATTR_MAPPING)
# BYPASSED with localstack
if settings.LOCALSTACK:
if hasattr(settings,'LOCALSTACK') and settings.LOCALSTACK:
user.phone_number_verified = True
user.mfa = "SMS"
return user
Expand All @@ -154,8 +157,7 @@ def test_func(self):
if self.request.user.vinceprofile.service:
return False
if self.request.user.vinceprofile.pending:
if settings.LOCALSTACK:
# BYPASSED with localstack
if hasattr(settings,'LOCALSTACK') and settings.LOCALSTACK:
self.request.user.vinceprofile.pending = False
return True
return False
Expand Down Expand Up @@ -602,9 +604,15 @@ def form_valid(self, form):
c = Cognito(settings.COGNITO_USER_POOL_ID, settings.COGNITO_APP_ID, user_pool_region=settings.COGNITO_REGION, username=form.cleaned_data['username'])
try:
c.initiate_forgot_password()
logger.warning("Initiate password reset for %s" % form.cleaned_data['username'])
except (Boto3Error, ClientError) as e:
logger.warning("User %s does not exist" % form.cleaned_data['username'])

#If the user_pool PreventUserExistenceErrors is NOT LEGACY
#there will be no exception thrown. Below two are for logging only
if not User.objects.using('vincecomm').filter(email__iexact=form.cleaned_data['username']):
logger.warning("User %s does not exist in VinceComm" % form.cleaned_data['username'])
if not User.objects.filter(email__iexact=form.cleaned_data['username']):
logger.warning("User %s does not exist in VinceTrack" % form.cleaned_data['username'])
self.request.session['RESETPASSWORD']=True
self.request.session['username']=form.cleaned_data['username']
return redirect("cogauth:passwordreset")
Expand Down Expand Up @@ -1034,14 +1042,12 @@ def get_context_data(self, **kwargs):
return context

def form_valid(self, form):
#Begin reCAPTCHA validation
#Begin reCAPTCHA validation
recaptcha_response = self.request.POST.get('g-recaptcha-response')

data = {
'secret' : settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}

r = requests.post(GOOGLE_VERIFY_URL, data=data)
result = r.json()
if result['success']:
Expand Down
20 changes: 16 additions & 4 deletions lib/vince/mutelib.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def mute_user(useremail,case_id,interactive=False):
print(l._get_settings())
return 1

def mute_case_not_affected(case_id,interactive=False):
def mute_case_not_affected(case_id,vendor_id=None,interactive=False):
""" Mute case for all users who are participating in a Case but
have already indicated that they are "Not Affected" - the assumption
is they do not want to hear about this Case any more due to their
Expand All @@ -51,10 +51,22 @@ def mute_case_not_affected(case_id,interactive=False):
vul = CaseVulnerability.objects.filter(case=c)
if not vul:
if interactive:
print("No Vulnerabilities for this Case found in VinceComm")
print("No Vulnerabilities for this Case found!")
return -1
x = CaseMemberStatus.objects.filter(vulnerability__in=vul,status=2)
f = CaseMember.objects.filter(id__in=x.values_list('member'))
x = CaseMemberStatus.objects.filter(vulnerability__in=vul,status=CaseMemberStatus.UNAFFECTED)
if vul.count() > 1:
#exclude members who may be AFFECTED or UNKNOWN for one of the vuls
nx = CaseMemberStatus.objects.filter(vulnerability__in=vul).exclude(status=CaseMemberStatus.UNAFFECTED)
x = x.exclude(member__in=nx.values('member'))
#f = CaseMember.objects.filter(id__in=y.values_list('member'))
if vendor_id:
f = CaseMember.objects.filter(id=vendor_id)
else:
f = CaseMember.objects.filter(id__in=x.values_list('member'))
if not f:
if interactive:
print("No Matching vendors found for this Case!")
return -1
user_list = User.objects.using('vincecomm').filter(groups__in=f.values_list('group'))
t = 'muted_cases'
updated = 0
Expand Down
1 change: 0 additions & 1 deletion vince/context_processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,5 @@ def vince_version(request):
'CASE_ID': settings.CASE_IDENTIFIER,
'REPORT_ID': settings.REPORT_IDENTIFIER}




1 change: 1 addition & 0 deletions vince/dbrouter.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


class DatabaseRouterMiddleware:

def __init__(self, get_response):
Expand Down
2 changes: 0 additions & 2 deletions vince/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1622,8 +1622,6 @@ def parse_attachment(message_part):
content_disposition = message_part.get("Content-Disposition", None)
except AttributeError:
return None
logger.debug("IN PARSE ATTACHMENT %s" % content_disposition)
logger.debug(message_part.get_content_type())
if message_part.get_content_type() == "application/pgp-signature":
# don't want pgp attachments
return
Expand Down
2 changes: 0 additions & 2 deletions vince/mailer.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,8 +441,6 @@ def send_updatecase_mail(action, new_user=None):
# new_user is the user recently assigned to the case
case = action.get_related_case

logger.debug(f"ACTION is {action.action_type}")

if not(emailable_action(action)):
return

Expand Down
2 changes: 1 addition & 1 deletion vince/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
class MultipleDomainMiddleware(MiddlewareMixin):

def process_request(self, request):
if settings.LOCALSTACK:
if hasattr(settings, 'LOCALSTACK') and settings.LOCALSTACK:
return
url_config = getattr(settings, 'MULTIURL_CONFIG', None)
if not url_config:
Expand Down
5 changes: 3 additions & 2 deletions vince/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3886,8 +3886,9 @@ class Meta:
unique_together = (('name', 'organization'),)

def save(self, *args, **kwargs):
if VendorProduct.objects.filter(organization=self.organization,
name__iexact=self.name):
dup = VendorProduct.objects.filter(organization=self.organization,
name__iexact=self.name)
if self._state.adding and dup:
logger.debug(f"Ignoring duplicate VendorProduct {self.name}")
return
return super(VendorProduct, self).save(*args, **kwargs)
Expand Down
2 changes: 2 additions & 0 deletions vince/static/vince/js/contactverify.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ function getEmails(e, taggle) {

$(document).ready(function() {

var original_email_body = $("#id_email_body").val();

$('form').on('submit', function (e) {
var $form = $(this);
Expand Down Expand Up @@ -96,6 +97,7 @@ $(document).ready(function() {

$(document).on('click', "#customize", function(e) {
e.preventDefault();
$("#id_email_body").val(original_email_body);
replaceVendor();
replaceEmail();
});
Expand Down
2 changes: 0 additions & 2 deletions vince/static/vince/js/cve.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ function org_auto(item) {
item = $('.affected_product').not('.ui-autocomplete-input');
}
item.closest('tr').find('.organization').on("change",function() {
console.log(this); console.log(arguments);
/* Clear all elements in the row on organization change */
$(this).closest('tr').find("input").val('');
$(this).closest('tr').find(".range_type")
Expand All @@ -68,7 +67,6 @@ function org_auto(item) {
disabled: false,
minLength: 2,
change: function(event, ui) {
console.log(arguments); console.log(this);
if(!ui.item)
$(event.target).after($("<small>")
.addClass("required rnew")
Expand Down
25 changes: 25 additions & 0 deletions vince/static/vince/js/editcase.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,28 @@ $( function() {
$("#caseform:disabled").removeAttr('disabled');
});
});

// The following 15 lines or so create a checkbox that the user can tick to leave the publication date TBD.
var checkboxDiv = '<div class="form-group">' +
'<label for="dateTBDCheckbox">Leave publication date TBD.</label>' +
'<input type="checkbox" name="dateTBDCheckbox" id="dateTBDCheckbox">' +
'</div>'

$(document).ready(function() {
$("#id_due_date").parent().after(checkboxDiv);
});

$(document).ready(function() {
var checkbox = document.getElementById("dateTBDCheckbox")
checkbox.addEventListener("click", function() {
if(checkbox.checked == true){
$('#id_due_date').attr("readonly", true);
$('#id_due_date').datepicker("destroy");
$('#id_due_date').val("");
}else{
$('#id_due_date').removeAttr('readonly')
$('#id_due_date').datepicker({dateFormat: 'yy-mm-dd', minDate: 0});
}
});
});

104 changes: 90 additions & 14 deletions vince/static/vince/js/vince.js
Original file line number Diff line number Diff line change
Expand Up @@ -566,22 +566,20 @@ $(function () {
contentType: 'application/json',
dataType: 'json'})
.done(function(ret) {
let m = [{output: ret},{input:cvedata}];
$('#cve5data').val(json_pretty(m));

let m = [{output: ret},{input:cvedata}];
$('#cve5data').val(json_pretty(m));
if("error" in ret) {
msg_card(el,"Error: "+ret.error,"bad");
$('#cve5data').addClass('is-invalid-input');
msg_card(el,"Error: "+ret.error,"bad");
$('#cve5data').addClass('is-invalid-input');
} else if("message" in ret) {
msg_card(el,"Result: "+ret.message,"good");
$('#cve5data').removeClass('is-invalid-input');

if('updated' in ret) {
$('#cve5data')
.data('cveservices',ret.updated);
load_cvedata('cveservices');
}

msg_card(el,"Result: "+ret.message,"good");
$('#cve5data').removeClass('is-invalid-input');
if('updated' in ret) {
$('#cve5data')
.data('cveservices',ret.updated);
load_cvedata('cveservices');
}

} else {
/* the card-cr class looks like warning*/
msg_card(el,"Result: "+ret.message,"cr")
Expand All @@ -601,5 +599,83 @@ $(function () {
}
});
});
function rgba_rand(r,g,b,a) {
let c = [0,0,0];
for(let i=0; i<3; i++) {
if(arguments[i] && (!isNaN(parseInt(arguments[i]))))
c[i] = arguments[i]
else
c[i] = parseInt(Math.random()*255)
}
a && parseFloat(a) ? c.push(a) : c.push(1);
return "rgba(" + c.join(",") + ")";
}
/* If userapprove element exists display it and create user approve rows*/
if($('#userapprove').data('href')) {
$.getJSON($('#userapprove').data('href')).done(function(data) {
if("uar" in data) {
let incomplete = data.uar.filter(function(x) {
return x.status < 0; });
if(incomplete.length) {
$('#userapprove').html(' [' +
String(incomplete.length) + ']' );
/* use pending/user/(?P<pk>[0-9]+)/addcontact/ and
create a prompt to start process */
if($('.uar-row').length) {
/* Create a new Ticket by submitting data
to Vendor Queue */
let divm = $('<div>').addClass('large-10 columns');
incomplete.forEach(function(rec) {
let name = rec.full_name + " " ;
let row = $("<p>")
.addClass("article-row-content-description")
.text(name).append($("<span>")
.addClass("email")
.text(rec.username));
let divrow = $("<div>")
.addClass("article-row-content")
.append(row);
let picdiv = $("<div>")
.addClass("profile-pic text-center")
.css({"background-color": rgba_rand(255)})
.append($("<span>").addClass("logo-initial")
.text(name[0]));

let div = $("<div>").addClass("row list-row")
.attr("data-rec",JSON.stringify(rec))
.append($("<div>").addClass("large-1 columns")
.append(picdiv))
.append($("<div>").addClass("large-7 columns")
.append(divrow));
$('.uar-row > .large-10').append(div);
});
let rec = {}
let vendor_queue = 13;
let vendor_associator = 5;
let csrf_token = getCookie('csrftoken');
let data = {searchbar: null,
csrfmiddlewaretoken: csrf_token,
vulnote_approval: null,
queue: vendor_queue,
title: "",
role: vendor_associator,
assigned_to: -2,
body: "",
due_date: null,
submitter_email: "",
priority: 3,
'case': null}
data.title = "Associate " + rec.username
+ " to Vendor "+ rec.vendor;
data.submitter_email = rec.username;
data.body = rec.justification;
/* GET this from ticket/url data-href*/
let ticket_url = $('.uar-row').data('newticket-url');
}
}

}
});

}
});
Loading

0 comments on commit 3c90e20

Please sign in to comment.