Skip to content

Commit

Permalink
Summary API
Browse files Browse the repository at this point in the history
  • Loading branch information
Shamal Faily committed Jan 15, 2017
1 parent e8b037e commit b00fc3b
Show file tree
Hide file tree
Showing 6 changed files with 198 additions and 2 deletions.
80 changes: 80 additions & 0 deletions cairis/controllers/SummaryController.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

import httplib
from flask import session, request, make_response
from flask_restful_swagger import swagger
from flask_restful import Resource
from cairis.data.SummaryDAO import SummaryDAO
from cairis.tools.JsonConverter import json_serialize
from cairis.tools.MessageDefinitions import SummaryMessage
from cairis.tools.ModelDefinitions import SummaryModel
from cairis.tools.SessionValidator import get_session_id

__author__ = 'Shamal Faily'


class SummaryAPI(Resource):
#region Swagger Doc
@swagger.operation(
notes='Get summary table',
responseClass=SummaryModel.__name__,
nickname='summary-get',
parameters=[
{
"name": "dimension_name",
"description": "The relevant dimension name",
"required": True,
"allowMultiple": False,
"dataType": str.__name__,
"paramType": "query"
},
{
"name": "environment_name",
"description": "The relevant environment name",
"required": True,
"allowMultiple": False,
"dataType": str.__name__,
"paramType": "query"
},
{
"name": "session_id",
"description": "The ID of the user's session",
"required": False,
"allowMultiple": False,
"dataType": str.__name__,
"paramType": "query"
}
],
responseMessages=[
{
"code": httplib.BAD_REQUEST,
"message": "The database connection was not properly set up"
}
]
)
#endregion
def get(self,dimension_name,environment_name):
session_id = get_session_id(session, request)

dao = SummaryDAO(session_id)
sumRows = dao.get_summary(dimension_name,environment_name)
dao.close()

resp = make_response(json_serialize(sumRows, session_id=session_id))
resp.headers['Content-Type'] = "application/json"
return resp
5 changes: 4 additions & 1 deletion cairis/daemon/main/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
RequirementController, ResponseController, RiskController, RoleController, TaskController, ThreatController, \
UploadController, VulnerabilityController, ObstacleController, CountermeasureController, DomainPropertyController, UseCaseController, \
DependencyController, DocumentationController, FindController, ExternalDocumentController, DocumentReferenceController, \
PersonaCharacteristicController, ObjectDependencyController, ArchitecturalPatternController, ValueTypeController, TemplateGoalController, TemplateAssetController,TemplateRequirementController, LocationsController, RiskLevelController, TraceController
PersonaCharacteristicController, ObjectDependencyController, ArchitecturalPatternController, ValueTypeController, TemplateGoalController, TemplateAssetController,TemplateRequirementController, LocationsController, RiskLevelController, TraceController, SummaryController
from cairis.daemon.main import main, api

__author__ = 'Robin Quetin, Shamal Faily'
Expand Down Expand Up @@ -316,6 +316,9 @@ def get_image(path):
api.add_resource(RoleController.RolesByIdAPI, '/api/roles/id/<int:id>',endpoint='roles_id')
api.add_resource(RoleController.RoleEnvironmentPropertiesAPI, '/api/roles/name/<string:name>/properties',endpoint='role_properties')

# Summary routes
api.add_resource(SummaryController.SummaryAPI, '/api/summary/dimension/<string:dimension_name>/environment/<string:environment_name>',endpoint='summary')

# Task routes
api.add_resource(TaskController.TasksAPI, '/api/tasks',endpoint='tasks')
api.add_resource(TaskController.TaskByNameAPI, '/api/tasks/name/<string:name>',endpoint='task')
Expand Down
44 changes: 44 additions & 0 deletions cairis/data/SummaryDAO.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

from cairis.core.ARM import *
from cairis.core.Trace import Trace
from cairis.daemon.CairisHTTPError import ARMHTTPError
import cairis.core.armid
from cairis.data.CairisDAO import CairisDAO
from cairis.tools.ModelDefinitions import SummaryModel

__author__ = 'Shamal Faily'


class SummaryDAO(CairisDAO):
def __init__(self, session_id):
CairisDAO.__init__(self, session_id)

def get_summary(self,dimension_name,environment_name):
try:
sumRows = self.db_proxy.dimensionSummary(dimension_name,environment_name)
except DatabaseProxyException as ex:
self.close()
raise ARMHTTPError(ex)
except ARMException as ex:
self.close()
raise ARMHTTPError(ex)
smRows = []
for sumRow in sumRows:
smRows.append(SummaryModel(sumRow[0],sumRow[1]))
return smRows
54 changes: 54 additions & 0 deletions cairis/test/test_SummaryAPI.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

import logging
from urllib import quote
from StringIO import StringIO
import os
import jsonpickle
from cairis.test.CairisDaemonTestCase import CairisDaemonTestCase
from cairis.mio.ModelImport import importModelFile
from cairis.tools.JsonConverter import json_deserialize
import os

__author__ = 'Shamal Faily'

class SummaryAPITests(CairisDaemonTestCase):

@classmethod
def setUpClass(cls):
importModelFile(os.environ['CAIRIS_SRC'] + '/../examples/exemplars/NeuroGrid/NeuroGrid.xml',1,'test')


def setUp(self):
self.logger = logging.getLogger(__name__)

def test_get_summary(self):
method = 'test_get_summary'
url = '/api/summary/dimension/vulnerability/environment/Psychosis?session_id=test'
self.logger.info('[%s] URL: %s', method, url)
rv = self.app.get(url)
sumRows = jsonpickle.decode(rv.data)
self.assertIsNotNone(sumRows, 'No results after deserialization')
self.logger.info('[%s] Rows: %d', method, len(sumRows))
self.assertEquals(len(sumRows),3)
self.assertEquals(sumRows[0]['theLabel'],'Catastrophic')
self.assertEquals(sumRows[0]['theValue'],1)
self.assertEquals(sumRows[1]['theLabel'],'Critical')
self.assertEquals(sumRows[1]['theValue'],2)
self.assertEquals(sumRows[2]['theLabel'],'Marginal')
self.assertEquals(sumRows[2]['theValue'],1)
5 changes: 4 additions & 1 deletion cairis/tools/MessageDefinitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,11 +421,14 @@ class TraceMessage(DefaultMessage):
)
# endregion


class TemplateRequirementMessage(DefaultMessage):
resource_fields = gen_message_fields(ModelDefinitions.TemplateRequirementModel)
required = DefaultMessage.required

class CountermeasureTaskMessage(DefaultMessage):
resource_fields = fields.List(fields.Nested(ModelDefinitions.CountermeasureTask.resource_fields))
required = DefaultMessage.required

class SummaryMessage(DefaultMessage):
resource_fields = gen_message_fields(ModelDefinitions.SummaryModel)
required = DefaultMessage.required
12 changes: 12 additions & 0 deletions cairis/tools/ModelDefinitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1243,6 +1243,18 @@ class LocationsModel(object):
obj_id_field : gen_class_metadata(Locations)
}

@swagger.model
class SummaryModel(object):
resource_fields = {
"theLabel": fields.String,
"theValue": fields.String
}
required = resource_fields.keys()

def __init__(self,lbl,val):
self.theLabel = lbl
self.theValue = val

@swagger.model
class TraceModel(object):
resource_fields = {
Expand Down

0 comments on commit b00fc3b

Please sign in to comment.