class Query(ObjectType): update_json_key = JSONString(required=True, json_input=JSONString(required=True), key=String(required=True), value=String(required=True)) def resolve_update_json_key(root, info, json_input, key, value): #assert json_input == {"name": "John"} json_input[key] = value return json_input
class Resource(ObjectType): """ GraphQL Entity for Project Resources """ project_name = '' repositories = JSONString() environments = JSONString() files = JSONString() def __init__(self, project_name): self.project_name = project_name self.repositories = [] self.environments = [] self.files = [] project_exist = integrates_dao.get_project_attributes_dynamo( project_name.lower(), ['project_name']) if project_exist: project_info = integrates_dao.get_project_attributes_dynamo( project_name.lower(), ['repositories', 'environments', 'files']) if project_info: self.repositories = project_info.get('repositories', []) self.environments = project_info.get('environments', []) self.files = project_info.get('files', []) else: # Project does not have resources pass else: raise InvalidProject def __str__(self): return self.project_name + '_resources' @get_entity_cache def resolve_repositories(self, info): """ Resolve repositories of the given project """ del info return self.repositories @get_entity_cache def resolve_environments(self, info): """ Resolve environments of the given project """ del info return self.environments @get_entity_cache def resolve_files(self, info): """ Resolve files of the given project """ del info return self.files
class Mutations(ObjectType): generate_upload_data = JSONString(name=String()) @staticmethod async def resolve_generate_upload_data(root, info, name): request = info.context['request'] await check_authorized(request) app = request.app api_config: Config.APIConfig = app['config'].api s3_config: Config.S3Config = app['config'].s3 document = await app['db'][VIDEO_MONGO_COLLECTION].insert_one( {'title': name}) _id = str(document.inserted_id) site_url = api_config.absolute_url success_action_redirect = str( site_url.join(app.router['upload_callback'].url_for(id=_id))) presigned = await app['s3'].generate_presigned_post( s3_config.bucket, f'{VIDEO_S3_FOLDER}/{_id}', Fields={'success_action_redirect': success_action_redirect}, Conditions=[{ 'success_action_redirect': success_action_redirect }], ) return presigned
class Resource(ObjectType): """ GraphQL Entity for Project Resources """ project_name = String() repositories = JSONString() environments = JSONString() files = JSONString() def __init__(self, project_name: str): self.project_name: str = project_name self.repositories: _List[Dict[str, Any]] = [] self.environments: _List[Dict[str, Any]] = [] self.files: _List[Dict[str, Any]] = [] project_exist = project_domain.get_attributes(project_name.lower(), ['project_name']) if project_exist: project_info = project_domain.get_attributes( project_name.lower(), ['repositories', 'environments', 'files']) if project_info: self.repositories = project_info.get('repositories', []) self.environments = project_info.get('environments', []) self.files = project_info.get('files', []) else: # Project does not have resources pass else: raise InvalidProject def __str__(self) -> str: return self.project_name + '_resources' @get_entity_cache def resolve_repositories(self, info: Any) -> JSONString: """ Resolve repositories of the given project """ del info return self.repositories @get_entity_cache def resolve_environments(self, info: Any) -> JSONString: """ Resolve environments of the given project """ del info return self.environments @get_entity_cache def resolve_files(self, info: Any) -> JSONString: """ Resolve files of the given project """ del info return self.files
class GremlinEdgeMutationSchema: create_edge = Field(GrapheneEdgeType, inv=String(required=True), outv=String(required=True), label=String(required=True), name=String(), properties=JSONString()) update_edge_by_id = Field(GrapheneEdgeType, id=AnyField(required=True), properties=JSONString(required=True)) remove_edge_by_id = String(id=AnyField(required=True)) remove_edges = String(label=String(), namespace=String(), query=JSONString()) def resolve_create_edge(self, info: ResolveInfo, label: str, namespace: str, properties: str, inv: str, outv: str): return info.context['request'].app.state.gremlin_client.edge.create( outv=outv, inv=inv, label=label, namespace=namespace, properties=properties) def resolve_update_edge_by_id(self, info: ResolveInfo, id: str, properties: str): data = info.context['request'].app.state.gremlin_client.edge.update( id, properties=properties) return data.__dict__() if data else None def resolve_remove_edge_by_id(self, info: ResolveInfo, id: str): data = info.context[ 'request'].app.state.gremlin_client.edge.delete_one(id) return data.__dict__() if data else None def resolve_remove_edges(self, info: ResolveInfo, label: str = None, namespace: str = None, query: str = None): info.context['request'].app.state.gremlin_client.edge.delete_many( label=label, namespace=namespace, query=query) return None
class GremlinVertexMutationSchema: create_vertex = Field(GrapheneVertexType, label=String(required=True), namespace=String(), properties=JSONString(required=True)) update_vertex_by_id = Field(GrapheneVertexType, id=AnyField(required=True), properties=JSONString(required=True)) remove_vertex_by_id = String(id=AnyField(required=True)) remove_vertices = String(label=String(), namespace=String(), query=JSONString()) def resolve_create_vertex(self, info: ResolveInfo, label: str, namespace: str, properties: str): data = info.context['request'].app.state.gremlin_client.vertex.create( label=label, namespace=namespace, properties=properties) return data.__dict__() if data else None def resolve_update_vertex_by_id(self, info: ResolveInfo, id: str, properties: str): data = info.context['request'].app.state.gremlin_client.vertex.update( id, properties=properties) return data.__dict__() if data else None def resolve_remove_vertex_by_id(self, info: ResolveInfo, id: str): data = info.context[ 'request'].app.state.gremlin_client.vertex.delete_one(id) return data.__dict__() if data else None def resolve_remove_vertices(self, info: ResolveInfo, label: str = None, namespace: str = None, query: str = None): info.context['request'].app.state.gremlin_client.vertex.delete_many( label=label, namespace=namespace, query=query) return None
class User(ObjectType): username = String() password = String() last_update = Int() portfolio = List(UserBalance, coin_id=graphene.String()) subscription = JSONString() loop_state = String() accounts = List(Account) wallets = List(Wallet) events = List(Event) portfolio_value = Float() def resolve_password(root, info, **kwargs): return '***************'
class NotesInput(InputObjectType): id = ID() url = String() notes = JSONString()
class Arguments(): file = Upload(required=True) files_data = JSONString() project_name = String()
class Error(ObjectType): path = List(String) type = String() context = JSONString()
def convert_jsonb_to_string(field, registry=None): return JSONString(description=field.help_text, required=not field.null)
class Finding(ObjectType): # noqa pylint: disable=too-many-instance-attributes """Finding Class.""" actor = String() affected_systems = String() age = Int() analyst = String() attack_vector_desc = String() bts_url = String() closed_vulnerabilities = Int() comments = List(Comment) compromised_attributes = String() compromised_records = Int() current_state = String() cvss_version = String() cwe_url = String() description = String() evidence = GenericScalar() exploit = String() id = String() # noqa pylint: disable=invalid-name is_exploitable = Boolean() last_vulnerability = Int() observations = List(Comment) open_vulnerabilities = Int() project_name = String() recommendation = String() records = JSONString() release_date = String() new_remediated = Boolean() remediated = Boolean() verified = Boolean() report_date = String() requirements = String() risk = String() scenario = String() severity = GenericScalar() severity_score = Float() state = String() historic_state = List(GenericScalar) historic_treatment = List(GenericScalar) threat = String() title = String() tracking = List(GenericScalar) type = String() vulnerabilities = List(Vulnerability, vuln_type=String(), state=String(), approval_status=String()) def __str__(self): return self.id + '_finding' def resolve_id(self, info): """Resolve id attribute.""" del info return self.id def resolve_project_name(self, info): """Resolve project_name attribute.""" del info return self.project_name @get_entity_cache def resolve_vulnerabilities(self, info, vuln_type='', state='', approval_status=''): """Resolve vulnerabilities attribute.""" vulns_loader = info.context.loaders['vulnerability'] vuln_filtered = vulns_loader.load(self.id) if vuln_type: vuln_filtered = vuln_filtered.then(lambda vulns: [ vuln for vuln in vulns if vuln.vuln_type == vuln_type and (vuln.current_approval_status != 'PENDING' or vuln. last_approved_status) ]) if state: vuln_filtered = vuln_filtered.then(lambda vulns: [ vuln for vuln in vulns if vuln_domain.get_current_state(vuln) == state and (vuln.current_approval_status != 'PENDING' or vuln .last_approved_status) ]) if approval_status: vuln_filtered = vuln_filtered.then(lambda vulns: [ vuln for vuln in vulns if vuln.current_approval_status == approval_status ]) return vuln_filtered @get_entity_cache def resolve_open_vulnerabilities(self, info): """Resolve open vulnerabilities attribute.""" vulns_loader = info.context.loaders['vulnerability'] vulns = vulns_loader.load(self.id) self.open_vulnerabilities = vulns.then(lambda vulns: len([ vuln for vuln in vulns if vuln_domain.get_current_state(vuln) == 'open' and (vuln.current_approval_status != 'PENDING' or vuln. last_approved_status) ])) return self.open_vulnerabilities def resolve_release_date(self, info): """Resolve release date attribute.""" del info return self.release_date @get_entity_cache def resolve_closed_vulnerabilities(self, info): """Resolve closed vulnerabilities attribute.""" vulns_loader = info.context.loaders['vulnerability'] vulns = vulns_loader.load(self.id) self.closed_vulnerabilities = vulns.then(lambda vulns: len([ vuln for vuln in vulns if vuln_domain.get_current_state(vuln) == 'closed' and (vuln.current_approval_status != 'PENDING' or vuln. last_approved_status) ])) return self.closed_vulnerabilities @get_entity_cache def resolve_tracking(self, info): """Resolve tracking attribute.""" if self.release_date: vulns_loader = info.context.loaders['vulnerability'] vulns = vulns_loader.load(self.id).then(lambda vulns: vulns).get() self.tracking = finding_domain.get_tracking_vulnerabilities(vulns) else: self.tracking = [] return self.tracking @get_entity_cache def resolve_records(self, info): """ Resolve compromised records attribute """ del info if self.records['url']: self.records = finding_utils.get_records_from_file( self.project_name, self.id, self.records['url']) else: self.records = [] return self.records def resolve_severity(self, info): """ Resolve severity values from Formstack """ del info return self.severity def resolve_cvss_version(self, info): """ Resolve cvss version value from Formstack """ del info return self.cvss_version @get_entity_cache def resolve_exploit(self, info): """ Resolve exploit attribute """ del info if self.exploit['url']: self.exploit = finding_utils.get_exploit_from_file( self.project_name, self.id, self.exploit['url']) else: self.exploit = '' return self.exploit @get_entity_cache def resolve_evidence(self, info): """ Resolve evidence attribute """ del info return self.evidence def resolve_comments(self, info): """ Resolve comments attribute """ user_data = util.get_jwt_content(info.context) curr_user_role = get_user_role(user_data) self.comments = [ Comment(**comment) for comment in comment_domain.get_comments(self.id, curr_user_role) ] return self.comments @enforce_authz @get_entity_cache def resolve_historic_state(self, info): """ Resolve submission history of a draft """ del info return self.historic_state @enforce_authz def resolve_observations(self, info): """ Resolve observations attribute """ user_data = util.get_jwt_content(info.context) curr_user_role = get_user_role(user_data) self.observations = [ Comment(**obs) for obs in comment_domain.get_observations(self.id, curr_user_role) ] return self.observations def resolve_title(self, info): """ Resolve title attribute """ del info return self.title def resolve_scenario(self, info): """ Resolve scenario attribute """ del info return self.scenario def resolve_actor(self, info): """ Resolve actor attribute """ del info return self.actor def resolve_description(self, info): """ Resolve description attribute """ del info return self.description def resolve_requirements(self, info): """ Resolve requirements attribute """ del info return self.requirements def resolve_attack_vector_desc(self, info): """ Resolve attack vector description attribute """ del info return self.attack_vector_desc def resolve_threat(self, info): """ Resolve threat attribute """ del info return self.threat def resolve_recommendation(self, info): """ Resolve recommendation attribute """ del info return self.recommendation def resolve_affected_systems(self, info): """ Resolve affected_systems attribute """ del info return self.affected_systems def resolve_compromised_attributes(self, info): """ Resolve compromised_attributes attribute """ del info return self.compromised_attributes def resolve_compromised_records(self, info): """ Resolve compromised_records attribute """ del info return self.compromised_records def resolve_cwe_url(self, info): """ Resolve cwe_url attribute """ del info return self.cwe_url def resolve_bts_url(self, info): """ Resolve bts_url attribute """ del info return self.bts_url def resolve_risk(self, info): """ Resolve risk attribute """ del info return self.risk @get_entity_cache def resolve_state(self, info): """ Resolve state attribute """ vulns_loader = info.context.loaders['vulnerability'] vulns = vulns_loader.load(self.id) self.state = vulns.then(lambda vulns: 'open' if [ vuln for vuln in vulns if vuln_domain.get_last_approved_status(vuln) == 'open' ] else 'closed') return self.state def resolve_remediated(self, info): """ Resolve remediated attribute """ del info return self.remediated def resolve_type(self, info): """ Resolve type attribute """ del info return self.type def resolve_age(self, info): """ Resolve age attribute """ del info return self.age def resolve_last_vulnerability(self, info): """ Resolve days since last report """ del info last_vuln_date = util.calculate_datediff_since(self.last_vulnerability) self.last_vulnerability = last_vuln_date.days return self.last_vulnerability def resolve_is_exploitable(self, info): """ Resolve is_exploitable attribute """ del info return self.is_exploitable def resolve_severity_score(self, info): """ Resolve precalculated severity score """ del info return self.severity_score def resolve_report_date(self, info): """ Resolve report date """ del info return self.report_date @enforce_authz def resolve_analyst(self, info): """ Resolve analyst attribute """ del info return self.analyst def resolve_historic_treatment(self, info): del info return self.historic_treatment def resolve_current_state(self, info): """Resolve vulnerabilities attribute.""" del info return self.current_state def resolve_new_remediated(self, info): """ Resolve new_remediated attribute """ del info return self.new_remediated def resolve_verified(self, info): """ Resolve verified attribute """ del info return self.verified
class TemplateSectionInput(InputObjectType): name = String() render_type = String() default_params = JSONString()
class Position(ObjectType): held_currency = String() amount = Float() date = DateTime() type = String() full_info = JSONString()
class GremlinEdgeQuerySchema: get_edge_by_id = Field(GrapheneEdgeType, id=String(required=True)) filter_edge = Field(List(GrapheneEdgeType), label=String(), query=JSONString(), limit=Int(default_value=default_pagination_size), skip=Int()) filter_edge_and_get_neighbor_vertices = Field( List(GrapheneEdgeType), label=String(), query=JSONString(), limit=Int(default_value=default_pagination_size), skip=Int()) get_or_create_edge = Field(GrapheneEdgeType, label=String(), namespace=String(), properties=JSONString()) def resolve_get_edge_by_id(self, info: ResolveInfo, id: str): data = info.context['request'].app.state.gremlin_client.edge.read_one( id) return data.__dict__() if data else None def resolve_filter_edge(self, info: ResolveInfo, label: str = None, namespace: str = None, query: str = None, limit: int = default_pagination_size, skip: int = 0): data = info.context['request'].app.state.gremlin_client.edge.read_many( label=label, namespace=namespace, query=query, limit=limit, skip=skip) return [datum.__dict__() for datum in data] def resolve_filter_edge_and_get_neighbor_vertices( self, info: ResolveInfo, label: str = None, namespace: str = None, query: str = None, limit: int = default_pagination_size, skip: int = 0): data = info.context[ 'request'].app.state.gremlin_client.edge.filter_edge_and_get_neighbor_vertices( label=label, namespace=namespace, query=query, limit=limit, skip=skip) # return [datum.__dict__() for datum in data] def resolve_get_or_create_edge(self, info: ResolveInfo, label: str = None, namespace: str = None, properties: str = None): return info.context[ 'request'].app.state.gremlin_client.edge.get_or_create( label=label, namespace=namespace, properties=properties)
class FindingType(ObjectType): # noqa pylint: disable=too-many-instance-attributes id = String() # noqa pylint: disable=invalid-name success = Boolean() error_message = String() state = String() vulnerabilities = List(Vulnerability, vuln_type=String(), state=String()) open_vulnerabilities = Int() closed_vulnerabilities = Int() project_name = String() release_date = String() records = JSONString() tracking = List(GenericScalar) severity = GenericScalar() exploit = String() evidence = GenericScalar() comments = List(GenericScalar) observations = List(GenericScalar) report_level = String() title = String() scenario = String() actor = String() description = String() requirements = String() attack_vector_desc = String() threat = String() recommendation = String() affected_systems = String() compromised_attributes = String() compromised_records = Int() cwe_url = String() bts_url = String() kb_url = String() treatment = String() treatment_manager = String() treatment_justification = String() remediated = Boolean() type = String() cvss_version = String() age = Int() last_vulnerability = Int() severity_score = Float() is_exploitable = Boolean() report_date = String() where = String() # Additional attributes of detailed findings client_code = String() client_project = String() probability = Int() detailed_severity = Int() risk = String() risk_level = String() ambit = String() category = String() def __init__(self): super(FindingType, self).__init__() self.id = '' # noqa pylint: disable=invalid-name self.vulnerabilities = [] self.success = False self.error_message = '' self.open_vulnerabilities = 0 self.closed_vulnerabilities = 0 self.project_name = '' self.release_date = '' self.records = {} self.severity = {} self.tracking = [] self.comments = [] self.observations = [] self.report_level = '' self.title = '' self.scenario = '' self.actor = '' self.description = '' self.requirements = '' self.attack_vector_desc = '' self.threat = '' self.recommendation = '' self.affected_systems = '' self.compromised_attributes = '' self.compromised_records = 0 self.cwe_url = '' self.bts_url = '' self.treatment = '' self.treatment_manager = '' self.treatment_justification = '' self.type = '' self.cvss_version = '' self.exploit = '' self.age = 0 self.last_vulnerability = 0 self.severity_score = 0.0 self.is_exploitable = False self.remediated = '' self.report_date = '' self.where = ''
class FormConfigType(graphene.ObjectType): field = JSONString()
class TopicListQuery(ObjectType): topics = Field( TopicList, slug=String(required=True), year=Int(), page=Int(), search_keys=String(), refresh=Boolean(), tab=String(), exclusions=List(String), extra=JSONString(), ) @staticmethod def resolve_topics(_parent, info, slug, **kwargs): # Convert string query parameters to actual dictionary to use it in TopicListHandler search_keys = dict(parse_qsl( kwargs.get("search_keys"))) if kwargs.get("search_keys") else {} manager = TopicListManager( slug, info.context.user, kwargs.get("year"), search_keys, kwargs.get("tab"), kwargs.get("exclusions"), extra=kwargs.get("extra"), ) if kwargs.get("refresh"): manager.delete_cache(delimiter=True) frame = LeftFrame(manager, kwargs.get("page")) page = frame.page # May raise PermissionDenied or Http404 object_list = [ Topic(title=t["title"], slug=t["slug"], count=humanize_count(t.get("count"))) for t in page["object_list"] ] paginator = { "num_pages": page["paginator"]["num_pages"], "page_range": page["paginator"]["page_range"] } tabs = (Tabs( current=frame.tabs["current"], available=[ Tab(name=key, safename=value) for key, value in frame.tabs["available"].items() ], ) if frame.tabs else None) exclusions = (Exclusions(active=frame.exclusions["active"], available=frame.exclusions["available"]) if frame.exclusions else None) extra = [ Extra(name=key, value=value) for key, value in frame.extra.items() ] if frame.extra else None page_data = { "has_next": page.get("has_next"), "has_other_pages": page.get("has_other_pages"), "has_previous": page.get("has_previous"), "number": page.get("number"), "object_list": object_list, "paginator": Paginator(**paginator), } data = { "page": Page(**page_data), "parameters": frame.parameters, "refresh_count": frame.refresh_count, "year": frame.year, "year_range": frame.year_range, "safename": frame.safename, "slug": frame.slug, "slug_identifier": frame.slug_identifier, "tabs": tabs, "exclusions": exclusions, "extra": extra, } return TopicList(**data)
class Arguments(object): resources_data = JSONString() project_name = String()
class Arguments(object): repository_data = JSONString() project_name = String()
class Arguments(): project_name = String(required=True) tags = JSONString()
class Arguments(): files_data = JSONString() project_name = String()
class QuestionInput(InputObjectType): text = String() choices = JSONString()
class Arguments(): resource_data = JSONString() project_name = String() res_type = String()