Codebase list python-faraday / 4d84c3a server / models.py
4d84c3a

Tree @4d84c3a (Download .tar.gz)

models.py @4d84c3araw · history · blame

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
# Faraday Penetration Test IDE
# Copyright (C) 2016  Infobyte LLC (http://www.infobytesec.com/)
# See the file 'doc/LICENSE' for the license information
import operator
from datetime import datetime
from functools import partial

from sqlalchemy import (
    Boolean,
    CheckConstraint,
    Column,
    DateTime,
    Enum,
    Float,
    ForeignKey,
    Integer,
    String,
    Text,
    UniqueConstraint,
    event,
    text
)
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import relationship, undefer
from sqlalchemy.sql import select, text, table
from sqlalchemy.sql.expression import asc, case, join
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy import func
from sqlalchemy.orm import (
    backref,
    column_property,
    query_expression,
    with_expression
)
from sqlalchemy.schema import DDL
from sqlalchemy.ext.associationproxy import association_proxy, _AssociationSet
from sqlalchemy.ext.declarative import declared_attr
from flask_sqlalchemy import (
    SQLAlchemy as OriginalSQLAlchemy,
    _EngineConnector
)
from depot.fields.sqlalchemy import UploadedFileField

import server.config
from server.fields import FaradayUploadedFile
from flask_security import (
    RoleMixin,
    UserMixin,
)
from server.utils.database import (
    BooleanToIntColumn,
    get_object_type_for,
    is_unique_constraint_violation)

NonBlankColumn = partial(Column, nullable=False,
                         info={'allow_blank': False})
BlankColumn = partial(Column, nullable=False,
                      info={'allow_blank': True},
                      default='')

OBJECT_TYPES = [
    'vulnerability',
    'host',
    'credential',
    'service',
    'source_code',
    'comment',
    'executive_report',
    'workspace',
    'task'
]


class SQLAlchemy(OriginalSQLAlchemy):
    """Override to fix issues when doing a rollback with sqlite driver
    See http://docs.sqlalchemy.org/en/rel_1_0/dialects/sqlite.html#serializable-isolation-savepoints-transactional-ddl
    and https://bitbucket.org/zzzeek/sqlalchemy/issues/3561/sqlite-nested-transactions-fail-with
    for furhter information"""

    def make_connector(self, app=None, bind=None):
        """Creates the connector for a given state and bind."""
        return CustomEngineConnector(self, self.get_app(app), bind)


class CustomEngineConnector(_EngineConnector):
        """Used by overrided SQLAlchemy class to fix rollback issues.

        Also set case sensitive likes (in SQLite there are case
        insensitive by default)"""

        def get_engine(self):
            # Use an existent engine and don't register events if possible
            uri = self.get_uri()
            echo = self._app.config['SQLALCHEMY_ECHO']
            if (uri, echo) == self._connected_for:
                return self._engine

            # Call original metohd and register events
            rv = super(CustomEngineConnector, self).get_engine()
            if uri.startswith('sqlite://'):
                with self._lock:
                    @event.listens_for(rv, "connect")
                    def do_connect(dbapi_connection, connection_record):
                        # disable pysqlite's emitting of the BEGIN statement
                        # entirely.  also stops it from emitting COMMIT before any
                        # DDL.
                        dbapi_connection.isolation_level = None
                        cursor = dbapi_connection.cursor()
                        cursor.execute("PRAGMA case_sensitive_like=true")
                        cursor.close()

                    @event.listens_for(rv, "begin")
                    def do_begin(conn):
                        # emit our own BEGIN
                        conn.execute("BEGIN")
            return rv


db = SQLAlchemy()

SCHEMA_VERSION = 'W.3.0.0'


def _make_generic_count_property(parent_table, children_table, where=None):
    """Make a deferred by default column property that counts the
    amount of childrens of some parent object"""
    children_id_field = '{}.id'.format(children_table)
    parent_id_field = '{}.id'.format(parent_table)
    children_rel_field = '{}.{}_id'.format(children_table, parent_table)
    query = (select([func.count(text(children_id_field))]).
             select_from(table(children_table)).
             where(text('{} = {}'.format(
                 children_rel_field, parent_id_field))))
    if where is not None:
        query = query.where(where)
    return column_property(query, deferred=True)


def _make_command_created_related_object():
    query = select([BooleanToIntColumn("(count(*) = 0)")])
    query = query.select_from(text('command_object as command_object_inner'))
    where_expr = " command_object_inner.create_date < command_object.create_date and " \
                " (command_object_inner.object_id = command_object.object_id and " \
                " command_object_inner.object_type = command_object.object_type) and " \
                " command_object_inner.workspace_id = command_object.workspace_id "
    query = query.where(text(where_expr))
    return column_property(
        query,
    )


class DatabaseMetadata(db.Model):
    __tablename__ = 'db_metadata'
    id = Column(Integer, primary_key=True)
    option = Column(String(250), nullable=False)
    value = Column(String(250), nullable=False)


class Metadata(db.Model):
    __abstract__ = True

    @declared_attr
    def creator_id(cls):
        return Column(
            Integer,
            ForeignKey('faraday_user.id', ondelete="SET NULL"),
            nullable=True)

    @declared_attr
    def creator(cls):
        return relationship('User', foreign_keys=[cls.creator_id])

    @declared_attr
    def update_user_id(cls):
        return Column(
            Integer,
            ForeignKey('faraday_user.id', ondelete="SET NULL"),
            nullable=True)

    @declared_attr
    def update_user(cls):
        return relationship('User', foreign_keys=[cls.update_user_id])

    create_date = Column(DateTime, default=datetime.utcnow)
    update_date = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)


class SourceCode(Metadata):
    __tablename__ = 'source_code'
    id = Column(Integer, primary_key=True)
    filename = NonBlankColumn(Text)
    function = BlankColumn(Text)
    module = BlankColumn(Text)

    workspace_id = Column(Integer, ForeignKey('workspace.id'), index=True, nullable=False)
    workspace = relationship('Workspace', backref='source_codes')

    __table_args__ = (
        UniqueConstraint(filename, workspace_id, name='uix_source_code_filename_workspace'),
    )

    @property
    def parent(self):
        return


class Host(Metadata):
    __tablename__ = 'host'
    id = Column(Integer, primary_key=True)
    ip = NonBlankColumn(Text)  # IP v4 or v6
    description = BlankColumn(Text)
    os = BlankColumn(Text)

    owned = Column(Boolean, nullable=False, default=False)

    default_gateway_ip = BlankColumn(Text)
    default_gateway_mac = BlankColumn(Text)

    mac = BlankColumn(Text)
    net_segment = BlankColumn(Text)

    services = relationship(
        'Service',
        order_by='Service.protocol,Service.port',
        cascade="all, delete-orphan"
    )

    workspace_id = Column(Integer, ForeignKey('workspace.id'), index=True,
                          nullable=False)
    workspace = relationship(
        'Workspace',
        foreign_keys=[workspace_id],
        backref=backref("hosts", cascade="all, delete-orphan")
        )

    open_service_count = _make_generic_count_property(
        'host', 'service', where=text("service.status = 'open'"))
    total_service_count = _make_generic_count_property('host', 'service')

    __host_vulnerabilities = (
        select([func.count(text('vulnerability.id'))]).
        select_from(text('vulnerability')).
        where(text('vulnerability.host_id = host.id')).
        as_scalar()
    )
    __service_vulnerabilities = (
        select([func.count(text('vulnerability.id'))]).
        select_from(text('vulnerability, service')).
        where(text('vulnerability.service_id = service.id and '
                   'service.host_id = host.id')).
        as_scalar()
    )
    vulnerability_count = column_property(
        # select(text('count(*)')).select_from(__host_vulnerabilities.subquery()),
        __host_vulnerabilities + __service_vulnerabilities,
        deferred=True)

    credentials_count = _make_generic_count_property('host', 'credential')

    __table_args__ = (
        UniqueConstraint(ip, workspace_id, name='uix_host_ip_workspace'),
    )

    vulnerability_info_count = query_expression()
    vulnerability_med_count = query_expression()
    vulnerability_high_count = query_expression()
    vulnerability_critical_count = query_expression()
    vulnerability_low_count = query_expression()
    vulnerability_unclassified_count = query_expression()
    vulnerability_total_count = query_expression()

    @classmethod
    def query_with_count(cls, confirmed, host_ids, workspace_name):
        query = cls.query.join(Workspace).filter(Workspace.name == workspace_name)
        if host_ids:
            query = query.filter(cls.id.in_(host_ids))
        return query.options(
            with_expression(
                cls.vulnerability_info_count,
                _make_vuln_count_property(
                    type_=None,
                    confirmed = confirmed,
                    use_column_property = False,
                    extra_query = "vulnerability.severity='informational'",
                    get_hosts_vulns = True
                )
            ),
            with_expression(
                cls.vulnerability_med_count,
                _make_vuln_count_property(
                    type_ = None,
                    confirmed = confirmed,
                    use_column_property = False,
                    extra_query = "vulnerability.severity='medium'",
                    get_hosts_vulns = True
                )
            ),
            with_expression(
                cls.vulnerability_high_count,
                _make_vuln_count_property(
                    type_ = None,
                    confirmed = confirmed,
                    use_column_property = False,
                    extra_query = "vulnerability.severity='high'",
                    get_hosts_vulns = True
                )
            ),
            with_expression(
                cls.vulnerability_critical_count,
                _make_vuln_count_property(
                    type_ = None,
                    confirmed = confirmed,
                    use_column_property = False,
                    extra_query = "vulnerability.severity='critical'",
                    get_hosts_vulns = True
                )
            ),
            with_expression(
                cls.vulnerability_low_count,
                _make_vuln_count_property(
                    type_ = None,
                    confirmed = confirmed,
                    use_column_property = False,
                    extra_query = "vulnerability.severity='low'",
                    get_hosts_vulns = True
                )
            ),
            with_expression(
                cls.vulnerability_unclassified_count,
                _make_vuln_count_property(
                    type_ = None,
                    confirmed = confirmed,
                    use_column_property = False,
                    extra_query = "vulnerability.severity='unclassified'",
                    get_hosts_vulns = True
                )
            ),
            with_expression(
                cls.vulnerability_total_count,
                _make_vuln_count_property(
                    type_ = None,
                    confirmed = confirmed,
                    use_column_property = False,
                    get_hosts_vulns = True
                )
            ),
        )

    @property
    def parent(self):
        return

    def set_hostnames(self, new_hostnames):
        """Override the host's hostnames. Take care of deleting old not
        used hostnames and to leave the sames the ones that weren't
        modified

        This function was thought to update existing objects, it shouldn't
        be used when creating!
        """
        return set_children_objects(self, new_hostnames,
                                    parent_field='hostnames',
                                    child_field='name')


def set_children_objects(instance, value, parent_field, child_field='id',
                         workspaced=True):
    """
    Override some kind of children of instance. This is useful in one
    to many relationships. It takes care of deleting not used children,
    adding new objects, and keeping the not modified ones the same.

    :param instance: instance of the parent object
    :param value: list of childs (values of the child_field)
    :param parent_field: the parent field's relationship to the children name
    :param child_field: the "lookup field" of the children model
    :param workspaced: indicates if the parent model has a workspace
    """
    # Get the class of the children. Inspired in
    # https://stackoverflow.com/questions/6843144/how-to-find-sqlalchemy-remote-side-objects-class-or-class-name-without-db-queri
    children_model = getattr(
        type(instance), parent_field).property.mapper.class_

    value = set(value)
    current_value = getattr(instance, parent_field)
    current_value_fields = set(map(operator.attrgetter(child_field),
                                   current_value))

    for existing_child in current_value_fields:
        if existing_child not in value:
            # It was removed
            removed_instance = next(
                inst for inst in current_value
                if getattr(inst, child_field) == existing_child)
            db.session.delete(removed_instance)

    for new_child in value:
        if new_child in current_value_fields:
            # it already exists
            continue
        kwargs = {child_field: new_child}
        if workspaced:
            kwargs['workspace'] = instance.workspace
        current_value.append(children_model(**kwargs))


class Hostname(Metadata):
    __tablename__ = 'hostname'
    id = Column(Integer, primary_key=True)
    name = NonBlankColumn(Text)

    host_id = Column(Integer, ForeignKey('host.id'), index=True, nullable=False)
    host = relationship('Host', backref=backref("hostnames", cascade="all, delete-orphan"))
    workspace_id = Column(Integer, ForeignKey('workspace.id'), index=True, nullable=False)
    workspace = relationship(
        'Workspace',
        backref='hostnames',
        foreign_keys=[workspace_id]
    )
    __table_args__ = (
        UniqueConstraint(name, host_id, workspace_id, name='uix_hostname_host_workspace'),
    )

    def __str__(self):
        return self.name

    @property
    def parent(self):
        return self.host


class Service(Metadata):
    STATUSES = [
        'open',
        'closed',
        'filtered'
    ]
    __tablename__ = 'service'
    id = Column(Integer, primary_key=True)
    name = BlankColumn(Text)
    description = BlankColumn(Text)
    port = Column(Integer, nullable=False)
    owned = Column(Boolean, nullable=False, default=False)

    protocol = NonBlankColumn(Text)
    status = Column(Enum(*STATUSES, name='service_statuses'), nullable=False)
    version = BlankColumn(Text)

    banner = BlankColumn(Text)

    host_id = Column(Integer, ForeignKey('host.id'), index=True, nullable=False)
    host = relationship(
        'Host',
        foreign_keys=[host_id],
    )

    workspace_id = Column(Integer, ForeignKey('workspace.id'), index=True, nullable=False)
    workspace = relationship(
        'Workspace',
        backref=backref('services', cascade="all, delete-orphan"),
        foreign_keys=[workspace_id]
    )

    vulnerability_count = _make_generic_count_property('service',
                                                       'vulnerability')
    credentials_count = _make_generic_count_property('service', 'credential')

    __table_args__ = (
        UniqueConstraint(port, protocol, host_id, workspace_id, name='uix_service_port_protocol_host_workspace'),
    )

    @property
    def parent(self):
        return self.host

    @property
    def summary(self):
        if self.version and self.version.lower() != "unknown":
            version = " (" + self.version + ")"
        else:
            version = ""
        return "(%s/%s) %s%s" % (self.port, self.protocol, self.name,
                                 version or "")


class VulnerabilityABC(Metadata):
    # revisar plugin nexpose, netspark para terminar de definir uniques. asegurar que se carguen bien
    EASE_OF_RESOLUTIONS = [
        'trivial',
        'simple',
        'moderate',
        'difficult',
        'infeasible'
    ]
    SEVERITIES = [
        'critical',
        'high',
        'medium',
        'low',
        'informational',
        'unclassified',
    ]

    __abstract__ = True
    id = Column(Integer, primary_key=True)

    data = BlankColumn(Text)
    description = BlankColumn(Text)
    ease_of_resolution = Column(Enum(*EASE_OF_RESOLUTIONS, name='vulnerability_ease_of_resolution'), nullable=True)
    name = NonBlankColumn(Text, nullable=False)
    resolution = BlankColumn(Text)
    severity = Column(Enum(*SEVERITIES, name='vulnerability_severity'), nullable=False)
    risk = Column(Float(3, 1), nullable=True)

    impact_accountability = Column(Boolean, default=False, nullable=False)
    impact_availability = Column(Boolean, default=False, nullable=False)
    impact_confidentiality = Column(Boolean, default=False, nullable=False)
    impact_integrity = Column(Boolean, default=False, nullable=False)

    __table_args__ = (
        CheckConstraint('1.0 <= risk AND risk <= 10.0',
                        name='check_vulnerability_risk'),
    )

    @property
    def parent(self):
        raise NotImplementedError('ABC property called')


class CustomAssociationSet(_AssociationSet):
    """
    A custom associacion set that passes the creator method the both
    the value and the instance of the parent object
    """

    # def __init__(self, lazy_collection, creator, getter, setter, parent):
    def __init__(self, lazy_collection, creator, value_attr, parent):
        """I have to override this method because the proxy_factory
        class takes different arguments than the hardcoded
        _AssociationSet one.
        In particular, the getter and the setter aren't passed, but
        since I have an instance of the parent (AssociationProxy
        instance) I do the logic here.
        The value_attr argument isn't relevant to this implementation
        """

        if getattr(parent, 'getset_factory', False):
            getter, setter = parent.getset_factory(
                parent.collection_class, parent)
        else:
            getter, setter = parent._default_getset(parent.collection_class)

        super(CustomAssociationSet, self).__init__(
            lazy_collection, creator, getter, setter, parent)

    def _create(self, value):
        if getattr(self.lazy_collection, 'ref', False):
            # for sqlalchemy previous to 1.3.0b1
            parent_instance = self.lazy_collection.ref()
        else:
            parent_instance = self.lazy_collection.parent
        session = db.session
        conflict_objs = session.new
        try:
            yield self.creator(value, parent_instance)
        except IntegrityError as ex:
            if not is_unique_constraint_violation(ex):
                raise
            # unique constraint failed at database
            # other process/thread won us on the commit
            # we need to fetch already created objs.
            session.rollback()
            for conflict_obj in conflict_objs:
                if not hasattr(conflict_obj, 'name'):
                    # The session can hold elements without a name (altough it shouldn't)
                    continue
                if conflict_obj.name == value:
                    continue
                persisted_conclict_obj = session.query(conflict_obj.__class__).filter_by(name=conflict_obj.name).first()
                if persisted_conclict_obj:
                    self.col.add(persisted_conclict_obj)
            yield self.creator(value, parent_instance)

    def add(self, value):
        if value not in self:
            for new_value in self._create(value):
                self.col.add(new_value)

def _build_associationproxy_creator(model_class_name):
    def creator(name, vulnerability):
        """Get or create a reference/policyviolation with the
        corresponding name. This must be workspace aware"""

        # Ugly hack to avoid the fact that Reference is defined after
        # Vulnerability
        model_class = globals()[model_class_name]

        assert (vulnerability.workspace and vulnerability.workspace.id
                is not None), "Unknown workspace id"
        child = model_class.query.filter(
            getattr(model_class, 'workspace') == vulnerability.workspace,
            getattr(model_class, 'name') == name,
        ).first()
        if child is None:
            # Doesn't exist
            child = model_class(name, vulnerability.workspace.id)
        return child

    return creator


def _build_associationproxy_creator_non_workspaced(model_class_name):
    def creator(name, vulnerability):
        """Get or create a reference/policyviolation with the
        corresponding name. This must be workspace aware"""

        # Ugly hack to avoid the fact that Reference is defined after
        # Vulnerability
        model_class = globals()[model_class_name]
        child = model_class.query.filter(
            getattr(model_class, 'name') == name,
        ).first()
        if child is None:
            # Doesn't exist
            child = model_class(name)
        return child

    return creator


class VulnerabilityTemplate(VulnerabilityABC):
    __tablename__ = 'vulnerability_template'

    __table_args__ = (
        UniqueConstraint('name', name='uix_vulnerability_template_name'),
    )

    # We use ReferenceTemplate and not Reference since Templates does not have workspace.

    reference_template_instances = relationship(
        "ReferenceTemplate",
        secondary="reference_template_vulnerability_association",
        lazy="joined",
        collection_class=set
    )

    references = association_proxy(
        'reference_template_instances',
        'name',
        proxy_factory=CustomAssociationSet,
        creator=_build_associationproxy_creator_non_workspaced('ReferenceTemplate')
    )

    policy_violation_template_instances = relationship(
        "PolicyViolationTemplate",
        secondary="policy_violation_template_vulnerability_association",
        lazy="joined",
        collection_class=set
    )

    policy_violations = association_proxy(
        'policy_violation_template_instances',
        'name',
        proxy_factory=CustomAssociationSet,
        creator=_build_associationproxy_creator_non_workspaced('PolicyViolationTemplate')
    )


class CommandObject(db.Model):
    __tablename__ = 'command_object'
    id = Column(Integer, primary_key=True)

    object_id = Column(Integer, nullable=False)
    object_type = Column(Enum(*OBJECT_TYPES, name='object_types'), nullable=False)

    command = relationship('Command', backref='command_objects')
    command_id = Column(Integer, ForeignKey('command.id'), index=True)

    workspace_id = Column(Integer, ForeignKey('workspace.id'), index=True, nullable=False)
    workspace = relationship(
        'Workspace',
        foreign_keys=[workspace_id],
        backref = backref('command_objects', cascade="all, delete-orphan")
    )

    create_date = Column(DateTime, default=datetime.utcnow)

    # the following properties are used to know if the command created the specified objects_type
    # remeber that this table has a row instances per relationship.
    # this created integer can be used to obtain the total object_type objects created.
    created = _make_command_created_related_object()

    # We are currently using the column property created. however to avoid losing information
    # we also store the a boolean to know if at the moment of created the object related to the
    # Command was created.
    created_persistent = Column(Boolean, nullable=False)

    __table_args__ = (
        UniqueConstraint('object_id', 'object_type', 'command_id', 'workspace_id',
                         name='uix_command_object_objid_objtype_command_id_ws'),
    )

    @property
    def parent(self):
        return self.command

    @classmethod
    def create(cls, obj, command, add_to_session=True, **kwargs):
        co = cls(obj, workspace=command.workspace, command=command,
                 created_persistent=True, **kwargs)
        if add_to_session:
            db.session.add(co)
        return co

    def __init__(self, object_=None, **kwargs):

        if object_ is not None:
            assert 'object_type' not in kwargs
            assert 'object_id' not in kwargs
            object_type = get_object_type_for(object_)

            # db.session.flush()
            assert object_.id is not None, "object must have an ID. Try " \
                "flushing the session"
            kwargs['object_id'] = object_.id
            kwargs['object_type'] = object_type
        return super(CommandObject, self).__init__(**kwargs)


def _make_created_objects_sum(object_type_filter):
    where_conditions = ["command_object.object_type= '%s'" % object_type_filter]
    where_conditions.append("command_object.command_id = command.id")
    where_conditions.append("command_object.workspace_id = command.workspace_id")
    return column_property(
        select([func.sum(CommandObject.created)]).
        select_from(table('command_object')).
        where(text(' and '.join(where_conditions)))
    )


def _make_created_objects_sum_joined(object_type_filter, join_filters):
    """

    :param object_type_filter: can be any host, service, vulnerability, credential or any object created from commands.
    :param join_filters: Filter for vulnerability fields.
    :return: column property with sum of created objects.
    """
    where_conditions = ["command_object.object_type= '%s'" % object_type_filter]
    where_conditions.append("command_object.command_id = command.id")
    where_conditions.append("vulnerability.id = command_object.object_id ")
    where_conditions.append("command_object.workspace_id = vulnerability.workspace_id")
    for attr, filter_value in join_filters.items():
        where_conditions.append("vulnerability.{0} = {1}".format(attr, filter_value))
    return column_property(
        select([func.sum(CommandObject.created)]). \
            select_from(table('command_object')). \
            select_from(table('vulnerability')). \
            where(text(' and '.join(where_conditions)))
    )


class Command(Metadata):

    IMPORT_SOURCE = [
        'report',  # all the files the tools export and faraday imports it from the resports directory, gtk manual import or web import.
        'shell',  # command executed on the shell or webshell with hooks connected to faraday.
    ]

    __tablename__ = 'command'
    id = Column(Integer, primary_key=True)
    command = NonBlankColumn(Text)
    tool = NonBlankColumn(Text)
    start_date = Column(DateTime, nullable=False)
    end_date = Column(DateTime, nullable=True)
    ip = BlankColumn(String(250))  # where the command was executed
    hostname = BlankColumn(String(250))  # where the command was executed
    params = BlankColumn(Text)
    user = BlankColumn(String(250))  # os username where the command was executed
    import_source = Column(Enum(*IMPORT_SOURCE, name='import_source_enum'))

    workspace_id = Column(Integer, ForeignKey('workspace.id'), index=True, nullable=False)
    workspace = relationship(
        'Workspace',
        foreign_keys=[workspace_id],
        backref=backref('commands', cascade="all, delete-orphan")
    )

    sum_created_vulnerabilities = _make_created_objects_sum('vulnerability')

    sum_created_vulnerabilities_web = _make_created_objects_sum_joined('vulnerability', {'type': '\'vulnerability_web\''})

    sum_created_hosts = _make_created_objects_sum('host')

    sum_created_services = _make_created_objects_sum('service')

    sum_created_vulnerability_critical = _make_created_objects_sum_joined('vulnerability', {'severity': '\'critical\''})

    @property
    def parent(self):
        return


class VulnerabilityGeneric(VulnerabilityABC):
    STATUSES = [
        'open',
        'closed',
        're-opened',
        'risk-accepted'
    ]
    VULN_TYPES = [
        'vulnerability',
        'vulnerability_web',
        'vulnerability_code'
    ]

    __tablename__ = 'vulnerability'
    confirmed = Column(Boolean, nullable=False, default=False)
    status = Column(Enum(*STATUSES, name='vulnerability_statuses'), nullable=False, default="open")
    type = Column(Enum(*VULN_TYPES, name='vulnerability_types'), nullable=False)
    issuetracker = BlankColumn(Text)

    workspace_id = Column(
                        Integer,
                        ForeignKey('workspace.id'),
                        index=True,
                        nullable=False,
                        )
    workspace = relationship('Workspace', backref='vulnerabilities')

    reference_instances = relationship(
        "Reference",
        secondary="reference_vulnerability_association",
        lazy="joined",
        collection_class=set
    )

    references = association_proxy(
        'reference_instances', 'name',
        proxy_factory=CustomAssociationSet,
        creator=_build_associationproxy_creator('Reference'))

    policy_violation_instances = relationship(
        "PolicyViolation",
        secondary="policy_violation_vulnerability_association",
        lazy="joined",
        collection_class=set
    )

    policy_violations = association_proxy(
        'policy_violation_instances', 'name',
        proxy_factory=CustomAssociationSet,
        creator=_build_associationproxy_creator('PolicyViolation'))

    evidence = relationship(
        "File",
        primaryjoin="and_(File.object_id==VulnerabilityGeneric.id, "
                    "File.object_type=='vulnerability')",
        foreign_keys="File.object_id",
        cascade="all, delete-orphan"
    )

    tags = relationship(
        "Tag",
        secondary="tag_object",
        primaryjoin="and_(TagObject.object_id==VulnerabilityGeneric.id, "
                    "TagObject.object_type=='vulnerability')",
        collection_class=set,
    )

    creator_command_id = column_property(
        select([CommandObject.command_id])
        .where(CommandObject.object_type == 'vulnerability')
        .where(text('command_object.object_id = vulnerability.id'))
        .where(CommandObject.workspace_id == workspace_id)
        .order_by(asc(CommandObject.create_date))
        .limit(1),
        deferred=True)

    creator_command_tool = column_property(
        select([Command.tool])
        .select_from(join(Command, CommandObject,
                          Command.id == CommandObject.command_id))
        .where(CommandObject.object_type == 'vulnerability')
        .where(text('command_object.object_id = vulnerability.id'))
        .where(CommandObject.workspace_id == workspace_id)
        .order_by(asc(CommandObject.create_date))
        .limit(1),
        deferred=True
    )

    _host_ip_query = (
        select([Host.ip])
        .where(text('vulnerability.host_id = host.id'))
    )
    _service_ip_query = (
        select([text('host_inner.ip')])
        .select_from(text('host as host_inner, service'))
        .where(text('vulnerability.service_id = service.id and '
                    'host_inner.id = service.host_id'))
    )
    target_host_ip = column_property(
        case([
            (text('vulnerability.host_id IS NOT null'),
                _host_ip_query.as_scalar()),
            (text('vulnerability.service_id IS NOT null'),
                _service_ip_query.as_scalar())
        ]),
        deferred=True
    )

    _host_os_query = (
        select([Host.os])
        .where(text('vulnerability.host_id = host.id'))
    )
    _service_os_query = (
        select([text('host_inner.os')])
        .select_from(text('host as host_inner, service'))
        .where(text('vulnerability.service_id = service.id and '
                    'host_inner.id = service.host_id'))
    )
    target_host_os = column_property(
        case([
            (text('vulnerability.host_id IS NOT null'),
                _host_os_query.as_scalar()),
            (text('vulnerability.service_id IS NOT null'),
                _service_os_query.as_scalar())
        ]),
        deferred=True
    )

    __mapper_args__ = {
        'polymorphic_on': type
    }

    @property
    def attachments(self):
        return db.session.query(File).filter_by(
            object_id=self.id,
            object_type='vulnerability'
        )

    @hybrid_property
    def target(self):
        return self.target_host_ip


class Vulnerability(VulnerabilityGeneric):
    __tablename__ = None
    host_id = Column(Integer, ForeignKey(Host.id), index=True)
    host = relationship(
        'Host',
        backref=backref("vulnerabilities", cascade="all, delete-orphan"),
        foreign_keys=[host_id],
    )

    @declared_attr
    def service_id(cls):
        return VulnerabilityGeneric.__table__.c.get('service_id', Column(Integer, db.ForeignKey('service.id'),
                                                                         index=True))

    @declared_attr
    def service(cls):
        return relationship('Service', backref=backref("vulnerabilities", cascade="all, delete-orphan"))

    @property
    def hostnames(self):
        if self.host is not None:
            return self.host.hostnames
        elif self.service is not None:
            return self.service.host.hostnames
        raise ValueError("Vulnerability has no service nor host")

    @property
    def parent(self):
        return self.host or self.service

    __mapper_args__ = {
        'polymorphic_identity': VulnerabilityGeneric.VULN_TYPES[0]
    }


class VulnerabilityWeb(VulnerabilityGeneric):
    __tablename__ = None
    method = BlankColumn(Text)
    parameters = BlankColumn(Text)
    parameter_name = BlankColumn(Text)
    path = BlankColumn(Text)
    query_string = BlankColumn(Text)
    request = BlankColumn(Text)
    response = BlankColumn(Text)
    website = BlankColumn(Text)
    status_code = Column(Integer, nullable=True)

    @declared_attr
    def service_id(cls):
        return VulnerabilityGeneric.__table__.c.get(
            'service_id', Column(Integer, db.ForeignKey('service.id'),
                                 nullable=False))

    @declared_attr
    def service(cls):
        return relationship('Service', backref=backref("vulnerabilities_web", cascade="all, delete-orphan"))

    @property
    def parent(self):
        return self.service

    @property
    def hostnames(self):
        return self.service.host.hostnames

    __mapper_args__ = {
        'polymorphic_identity': VulnerabilityGeneric.VULN_TYPES[1]
    }


class VulnerabilityCode(VulnerabilityGeneric):
    __tablename__ = None
    code = BlankColumn(Text)
    start_line = Column(Integer, nullable=True)
    end_line = Column(Integer, nullable=True)

    source_code_id = Column(Integer, ForeignKey(SourceCode.id), index=True)
    source_code = relationship(
        SourceCode,
        backref='vulnerabilities',
        foreign_keys=[source_code_id]
    )

    __mapper_args__ = {
        'polymorphic_identity': VulnerabilityGeneric.VULN_TYPES[2]
    }

    @property
    def hostnames(self):
        return []

    @property
    def parent(self):
        return self.source_code


class ReferenceTemplate(Metadata):
    __tablename__ = 'reference_template'
    id = Column(Integer, primary_key=True)
    name = NonBlankColumn(Text)

    __table_args__ = (
        UniqueConstraint('name', name='uix_reference_template_name'),
    )

    def __init__(self, name=None, **kwargs):
        super(ReferenceTemplate, self).__init__(name=name,
                                        **kwargs)


class Reference(Metadata):
    __tablename__ = 'reference'
    id = Column(Integer, primary_key=True)
    name = NonBlankColumn(Text)

    workspace_id = Column(
        Integer,
        ForeignKey('workspace.id'),
        index=True,
        nullable=False
    )
    workspace = relationship(
        'Workspace',
        backref=backref("references",
                        cascade="all, delete-orphan"),
        foreign_keys=[workspace_id],
    )

    __table_args__ = (
        UniqueConstraint('name', 'workspace_id', name='uix_reference_name_vulnerability_workspace'),
    )

    def __init__(self, name=None, workspace_id=None, **kwargs):
        super(Reference, self).__init__(name=name,
                                        workspace_id=workspace_id,
                                        **kwargs)

    @property
    def parent(self):
        # TODO: fix this propery
        return


class ReferenceVulnerabilityAssociation(db.Model):

    __tablename__ = 'reference_vulnerability_association'

    vulnerability_id = Column(Integer, ForeignKey('vulnerability.id'), primary_key=True)
    reference_id = Column(Integer, ForeignKey('reference.id'), primary_key=True)

    reference = relationship("Reference",
                             backref=backref(
                                 "reference_associations",
                                 cascade="all, delete-orphan"),
                             foreign_keys=[reference_id])
    vulnerability = relationship("Vulnerability",
                                 backref=backref("reference_vulnerability_associations",
                                                 cascade="all, delete-orphan"),
                                 foreign_keys=[vulnerability_id])


class PolicyViolationVulnerabilityAssociation(db.Model):

    __tablename__ = 'policy_violation_vulnerability_association'

    vulnerability_id = Column(Integer, ForeignKey('vulnerability.id'), primary_key=True)
    policy_violation_id = Column(Integer, ForeignKey('policy_violation.id'), primary_key=True)

    policy_violation = relationship("PolicyViolation", backref="policy_violation_associations", foreign_keys=[policy_violation_id])
    vulnerability = relationship("Vulnerability", backref=backref("policy_violationvulnerability_associations", cascade="all, delete-orphan"),
                                 foreign_keys=[vulnerability_id])


class ReferenceTemplateVulnerabilityAssociation(db.Model):

    __tablename__ = 'reference_template_vulnerability_association'

    vulnerability_id = Column(Integer, ForeignKey('vulnerability_template.id'), primary_key=True)
    reference_id = Column(Integer, ForeignKey('reference_template.id'), primary_key=True)

    reference = relationship(
        "ReferenceTemplate",
        foreign_keys=[reference_id],
        backref=backref('reference_template_associations', cascade="all, delete-orphan")
    )
    vulnerability = relationship(
        "VulnerabilityTemplate",
        backref=backref('reference_template_vulnerability_associations',
                        cascade="all, delete-orphan"),
        foreign_keys=[vulnerability_id]
    )


class PolicyViolationTemplateVulnerabilityAssociation(db.Model):

    __tablename__ = 'policy_violation_template_vulnerability_association'

    vulnerability_id = Column(Integer, ForeignKey('vulnerability_template.id'), primary_key=True)
    policy_violation_id = Column(Integer, ForeignKey('policy_violation_template.id'), primary_key=True)

    policy_violation = relationship("PolicyViolationTemplate", backref="policy_violation_template_associations", foreign_keys=[policy_violation_id])
    vulnerability = relationship("VulnerabilityTemplate", backref="policy_violation_template_vulnerability_associations",
                                 foreign_keys=[vulnerability_id])


class PolicyViolationTemplate(Metadata):
    __tablename__ = 'policy_violation_template'
    id = Column(Integer, primary_key=True)
    name = NonBlankColumn(Text)

    __table_args__ = (
        UniqueConstraint(
                        'name',
                        name='uix_policy_violation_template_name'),
    )

    def __init__(self, name=None, **kwargs):
        super(PolicyViolationTemplate, self).__init__(name=name,
                                        **kwargs)


class PolicyViolation(Metadata):
    __tablename__ = 'policy_violation'
    id = Column(Integer, primary_key=True)
    name = NonBlankColumn(Text)

    workspace_id = Column(
                        Integer,
                        ForeignKey('workspace.id'),
                        index=True,
                        nullable=False
                        )
    workspace = relationship(
                            'Workspace',
                            backref=backref("policy_violations",
                                            cascade="all, delete-orphan"),
                            foreign_keys=[workspace_id],
                            )

    __table_args__ = (
        UniqueConstraint(
                        'name',
                        'workspace_id',
                        name='uix_policy_violation_template_name_vulnerability_workspace'),
    )

    def __init__(self, name=None, workspace_id=None, **kwargs):
        super(PolicyViolation, self).__init__(name=name,
                                        workspace_id=workspace_id,
                                        **kwargs)

    @property
    def parent(self):
        # TODO: Fix this property
        return


class Credential(Metadata):
    __tablename__ = 'credential'
    id = Column(Integer, primary_key=True)
    username = BlankColumn(Text)
    password = BlankColumn(Text)
    description = BlankColumn(Text)
    name = BlankColumn(Text)

    host_id = Column(Integer, ForeignKey(Host.id), index=True, nullable=True)
    host = relationship(
        'Host',
        backref=backref("credentials", cascade="all, delete-orphan"),
        foreign_keys=[host_id])

    service_id = Column(Integer, ForeignKey(Service.id), index=True, nullable=True)
    service = relationship(
        'Service',
        backref=backref('credentials', cascade="all, delete-orphan"),
        foreign_keys=[service_id],
        )

    workspace_id = Column(Integer, ForeignKey('workspace.id'), index=True, nullable=False)
    workspace = relationship(
        'Workspace',
        backref=backref('credentials', cascade="all, delete-orphan"),
        foreign_keys=[workspace_id],
    )

    __table_args__ = (
        CheckConstraint('(host_id IS NULL AND service_id IS NOT NULL) OR '
                        '(host_id IS NOT NULL AND service_id IS NULL)',
                        name='check_credential_host_service'),
        UniqueConstraint(
                        'username',
                        'host_id',
                        'service_id',
                        'workspace_id',
                        name='uix_credential_username_host_service_workspace'
                        ),
    )

    @property
    def parent(self):
        return self.host or self.service


def _make_vuln_count_property(type_=None, confirmed=None,
                              use_column_property=True, extra_query=None, get_hosts_vulns=False):
    from_clause = table('vulnerability')

    if get_hosts_vulns:
        from_clause = from_clause.join(
            Service, Vulnerability.service_id == Service.id,
            isouter=True
        )

    query = (select([func.count(text('distinct(vulnerability.id)'))]).
             select_from(from_clause)
             )
    if get_hosts_vulns:
        query = query.where(text('(vulnerability.host_id = host.id OR host.id = service.host_id)'))
    else:
        query = query.where(text('vulnerability.workspace_id = workspace.id'))

    if type_:
        # Don't do queries using this style!
        # This can cause SQL injection vulnerabilities
        # In this case type_ is supplied from a whitelist so this is safe
        query = query.where(text("vulnerability.type = '%s'" % type_))
    if confirmed:
        if db.session.bind.dialect.name == 'sqlite':
            # SQLite has no "true" expression, we have to use the integer 1
            # instead
            query = query.where(text("vulnerability.confirmed = 1"))
        elif db.session.bind.dialect.name == 'postgresql':
            # I suppose that we're using PostgreSQL, that can't compare
            # booleans with integers
            query = query.where(text("vulnerability.confirmed = true"))
    elif confirmed == False:
        if db.session.bind.dialect.name == 'sqlite':
            # SQLite has no "true" expression, we have to use the integer 1
            # instead
            query = query.where(text("vulnerability.confirmed = 0"))
        elif db.session.bind.dialect.name == 'postgresql':
            # I suppose that we're using PostgreSQL, that can't compare
            # booleans with integers
            query = query.where(text("vulnerability.confirmed = false"))

    if extra_query:
        query = query.where(text(extra_query))
    if use_column_property:
        return column_property(query, deferred=True)
    else:
        return query


class Workspace(Metadata):
    __tablename__ = 'workspace'
    id = Column(Integer, primary_key=True)
    customer = BlankColumn(String(250))  # TBI
    description = BlankColumn(Text)
    active = Column(Boolean(), nullable=False, default=True)  # TBI
    end_date = Column(DateTime(), nullable=True)
    name = NonBlankColumn(String(250), unique=True, nullable=False)
    public = Column(Boolean(), nullable=False, default=False)  # TBI
    start_date = Column(DateTime(), nullable=True)

    credential_count = _make_generic_count_property('workspace', 'credential')
    host_count = _make_generic_count_property('workspace', 'host')
    open_service_count = _make_generic_count_property(
        'workspace', 'service', where=text("service.status = 'open'"))
    total_service_count = _make_generic_count_property('workspace', 'service')

    vulnerability_web_count = query_expression()
    vulnerability_code_count = query_expression()
    vulnerability_standard_count = query_expression()
    vulnerability_total_count = query_expression()

    workspace_permission_instances = relationship(
        "WorkspacePermission",
        cascade="all, delete-orphan")

    @classmethod
    def query_with_count(cls, confirmed, active=None, workspace_name=None):
        """
        Add count fields to the query.

        If confirmed is True/False, it will only show the count for confirmed / not confirmed
        vulnerabilities. Otherwise, it will show the count of all of them
        """
        query = """
                SELECT
                (SELECT COUNT(credential.id) AS count_1
                    FROM credential
                    WHERE credential.workspace_id = workspace.id
                ) AS credentials_count,
                (SELECT COUNT(host.id) AS count_2
                    FROM host
                    WHERE host.workspace_id = workspace.id
                ) AS host_count,
                p_4.count_3 as open_services,
                p_4.count_4 as total_service_count,
                p_5.count_5 as vulnerability_web_count,
                p_5.count_6 as vulnerability_code_count,
                p_5.count_7 as vulnerability_standard_count,
                p_5.count_8 as vulnerability_total_count,
                workspace.create_date AS workspace_create_date,
                workspace.update_date AS workspace_update_date,
                workspace.id AS workspace_id,
                workspace.customer AS workspace_customer,
                workspace.description AS workspace_description,
                workspace.active AS workspace_active,
                workspace.end_date AS workspace_end_date,
                workspace.name AS workspace_name,
                workspace.public AS workspace_public,
                workspace.start_date AS workspace_start_date,
                workspace.update_user_id AS workspace_update_user_id,
                workspace.creator_id AS workspace_creator_id,
                (SELECT {concat_func}(scope.name, ',') FROM scope where scope.workspace_id=workspace.id) as scope_raw
            FROM workspace
            LEFT JOIN (SELECT w.id as wid, COUNT(case when service.id IS NOT NULL and service.status = 'open' then 1 else null end) as count_3, COUNT(case when service.id IS NOT NULL then 1 else null end) AS count_4
                    FROM service
                    RIGHT JOIN workspace w ON service.workspace_id = w.id
                    GROUP BY w.id
                ) AS p_4 ON p_4.wid = workspace.id
            LEFT JOIN (SELECT w.id as w_id, COUNT(case when vulnerability.type = 'vulnerability_web' then 1 else null end) as count_5, COUNT(case when vulnerability.type = 'vulnerability_code' then 1 else null end) AS count_6, COUNT(case when vulnerability.type = 'vulnerability' then 1 else null end) as count_7, COUNT(case when vulnerability.id IS NOT NULL then 1 else null end) AS count_8
                    FROM vulnerability
                    RIGHT JOIN workspace w ON vulnerability.workspace_id = w.id
                    WHERE 1=1 {0}
                    GROUP BY w.id
                ) AS p_5 ON p_5.w_id = workspace.id
        """
        concat_func = 'string_agg'
        if db.engine.dialect.name == 'sqlite':
            concat_func = 'group_concat'
        filters = []
        params = {}

        confirmed_vuln_filter = ''
        if confirmed is not None:
            if confirmed:
                confirmed_vuln_filter = " AND vulnerability.confirmed "
            else:
                confirmed_vuln_filter = " AND NOT vulnerability.confirmed "
        query = query.format(confirmed_vuln_filter, concat_func=concat_func)

        if active is not None:
            filters.append(" workspace.active = :active ")
            params['active'] = active
        if workspace_name:
            filters.append(" workspace.name = :workspace_name ")
            params['workspace_name'] = workspace_name
        if filters:
            query += ' WHERE ' + ' AND '.join(filters)
        #query += " GROUP BY workspace.id "
        query += " ORDER BY workspace.name ASC"
        return db.engine.execute(text(query), params)

    def set_scope(self, new_scope):
        return set_children_objects(self, new_scope,
                                    parent_field='scope',
                                    child_field='name',
                                    workspaced=False)

    def activate(self):
        # if Checks active count
        if not self.active:
            self.active = True
            return True
        return False
        # else:
        # raise Cannot exceed or return false


    def deactivate(self):
        if self.active is not False:
            self.active = False
            return True
        return False


class Scope(Metadata):
    __tablename__ = 'scope'
    id = Column(Integer, primary_key=True)
    name = NonBlankColumn(Text)

    workspace_id = Column(
                        Integer,
                        ForeignKey('workspace.id'),
                        index=True,
                        nullable=False
                        )

    workspace = relationship(
        'Workspace',
         backref=backref('scope', cascade="all, delete-orphan"),
         foreign_keys=[workspace_id],
         )

    __table_args__ = (
        UniqueConstraint('name', 'workspace_id',
                         name='uix_scope_name_workspace'),
    )

    @property
    def parent(self):
        return


class WorkspacePermission(db.Model):
    __tablename__ = "workspace_permission_association"
    id = Column(Integer, primary_key=True)
    workspace_id = Column(
        Integer, ForeignKey('workspace.id'), nullable=False)
    workspace = relationship('Workspace')

    user_id = Column(Integer, ForeignKey('faraday_user.id'), nullable=False)
    user = relationship('User',
                        foreign_keys=[user_id])

    @property
    def parent(self):
        return


def is_valid_workspace(workspace_name):
    return db.session.query(server.models.Workspace).filter_by(name=workspace_name).first() is not None


def get(workspace_name):
    return db.session.query(Workspace).filter_by(name=workspace_name).first()


class User(db.Model, UserMixin):

    __tablename__ = 'faraday_user'
    ROLES = ['admin', 'pentester', 'client']

    id = Column(Integer, primary_key=True)
    username = NonBlankColumn(String(255), unique=True)
    password = Column(String(255), nullable=True)
    email = Column(String(255), unique=True, nullable=True)  # TBI
    name = BlankColumn(String(255))  # TBI
    is_ldap = Column(Boolean(), nullable=False, default=False)
    last_login_at = Column(DateTime())  # flask-security
    current_login_at = Column(DateTime())  # flask-security
    last_login_ip = BlankColumn(String(100))  # flask-security
    current_login_ip = BlankColumn(String(100))  # flask-security
    login_count = Column(Integer)  # flask-security
    active = Column(Boolean(), default=True, nullable=False)  # TBI flask-security
    confirmed_at = Column(DateTime())
    role = Column(Enum(*ROLES, name='user_roles'),
                  nullable=False, default='client')
    # TODO: add  many to many relationship to add permission to workspace

    workspace_permission_instances = relationship(
        "WorkspacePermission",
        cascade="all, delete-orphan")

    def __init__(self, *args, **kwargs):
        # added for compatibility with flask security
        try:
            kwargs.pop('roles')
        except KeyError:
            pass
        super(User, self).__init__(*args, **kwargs)

    def __repr__(self):
        return '<%sUser: %s>' % ('LDAP ' if self.is_ldap else '',
                                 self.username)

    def get_security_payload(self):
        return {
            "username": self.username,
            "name": self.email
        }


class File(Metadata):
    __tablename__ = 'file'

    id = Column(Integer, autoincrement=True, primary_key=True)
    name = BlankColumn(Text)  # TODO migration: check why blank is allowed
    filename = NonBlankColumn(Text)
    description = BlankColumn(Text)
    content = Column(UploadedFileField(upload_type=FaradayUploadedFile),
                     nullable=False)  # plain attached file
    object_id = Column(Integer, nullable=False)
    object_type = Column(Enum(*OBJECT_TYPES, name='object_types'), nullable=False)


class UserAvatar(Metadata):
    __tablename_ = 'user_avatar'

    id = Column(Integer, autoincrement=True, primary_key=True)
    name = BlankColumn(Text, unique=True)
    # photo field will automatically generate thumbnail
    # if the file is a valid image
    photo = Column(UploadedFileField(upload_type=FaradayUploadedFile))
    user_id = Column('user_id', Integer(), ForeignKey('faraday_user.id'))
    user = relationship('User', foreign_keys=[user_id])


class MethodologyTemplate(Metadata):
    # TODO: reset template_id in methodologies when deleting meth template
    __tablename__ = 'methodology_template'
    id = Column(Integer, primary_key=True)
    name = NonBlankColumn(Text)


class Methodology(Metadata):
    # TODO: add unique constraint -> name, workspace
    __tablename__ = 'methodology'
    id = Column(Integer, primary_key=True)
    name = NonBlankColumn(Text)

    template = relationship(
        'MethodologyTemplate',
        backref=backref('methodologies')
    )
    template_id = Column(
                    Integer,
                    ForeignKey('methodology_template.id',
                               ondelete="SET NULL"),
                    index=True,
                    nullable=True,
                    )

    workspace = relationship(
        'Workspace',
        backref=backref('methodologies', cascade="all, delete-orphan"),
    )
    workspace_id = Column(Integer, ForeignKey('workspace.id'), index=True, nullable=False)

    @property
    def parent(self):
        return


class TaskABC(Metadata):
    __abstract__ = True

    id = Column(Integer, primary_key=True)
    name = NonBlankColumn(Text)
    description = BlankColumn(Text)


class TaskTemplate(TaskABC):
    __tablename__ = 'task_template'
    id = Column(Integer, primary_key=True)

    __mapper_args__ = {
        'concrete': True
    }

    template = relationship(
        'MethodologyTemplate',
        backref=backref('tasks', cascade="all, delete-orphan"))
    template_id = Column(
                    Integer,
                    ForeignKey('methodology_template.id'),
                    index=True,
                    nullable=False,
                    )

    # __table_args__ = (
    #     UniqueConstraint(template_id, name='uix_task_template_name_desc_template_delete'),
    # )


class TaskAssignedTo(db.Model):
    __tablename__ = "task_assigned_to_association"
    id = Column(Integer, primary_key=True)
    task_id = Column(
        Integer, ForeignKey('task.id'), nullable=False)
    task = relationship('Task')

    user_id = Column(Integer, ForeignKey('faraday_user.id'), nullable=False)
    user = relationship(
        'User',
        foreign_keys=[user_id],
        backref=backref('assigned_tasks', cascade="all, delete-orphan"))


class Task(TaskABC):
    STATUSES = [
        'new',
        'in progress',
        'review',
        'completed',
    ]

    __tablename__ = 'task'
    id = Column(Integer, primary_key=True)

    due_date = Column(DateTime, nullable=True)
    status = Column(Enum(*STATUSES, name='task_statuses'), nullable=True)

    __mapper_args__ = {
        'concrete': True
    }

    assigned_to = relationship(
        "User",
        secondary="task_assigned_to_association")

    methodology_id = Column(
                    Integer,
                    ForeignKey('methodology.id'),
                    index=True,
                    nullable=False,
                    )
    methodology = relationship(
        'Methodology',
        backref=backref('tasks', cascade="all, delete-orphan")
    )

    template_id = Column(
                    Integer,
                    ForeignKey('task_template.id'),
                    index=True,
                    nullable=True,
                    )
    template = relationship('TaskTemplate', backref='tasks')

    workspace = relationship(
        'Workspace',
        backref=backref('tasks', cascade="all, delete-orphan")
    )
    workspace_id = Column(Integer, ForeignKey('workspace.id'), index=True, nullable=False)

    # __table_args__ = (
    #     UniqueConstraint(TaskABC.name, methodology_id, workspace_id, name='uix_task_name_desc_methodology_workspace'),
    # )

    @property
    def parent(self):
        return self.methodology


class License(Metadata):
    __tablename__ = 'license'
    id = Column(Integer, primary_key=True)
    product = NonBlankColumn(Text)
    start_date = Column(DateTime, nullable=False)
    end_date = Column(DateTime, nullable=False)

    type = BlankColumn(Text)
    notes = BlankColumn(Text)

    __table_args__ = (
        UniqueConstraint('product', 'start_date', 'end_date', name='uix_license_product_start_end_dates'),
    )


class Tag(Metadata):
    __tablename__ = 'tag'
    id = Column(Integer, primary_key=True)
    name = NonBlankColumn(Text, unique=True)
    slug = NonBlankColumn(Text, unique=True)


class TagObject(db.Model):
    __tablename__ = 'tag_object'
    id = Column(Integer, primary_key=True)

    object_id = Column(Integer, nullable=False)
    object_type = Column(Enum(*OBJECT_TYPES, name='object_types'), nullable=False)
    tag = relationship('Tag', backref='tagged_objects')
    tag_id = Column(Integer, ForeignKey('tag.id'), index=True)


class Comment(Metadata):
    __tablename__ = 'comment'
    id = Column(Integer, primary_key=True)

    text = BlankColumn(Text)

    reply_to_id = Column(Integer, ForeignKey('comment.id'))
    reply_to = relationship(
        'Comment',
        remote_side=[id],
        foreign_keys=[reply_to_id]
    )

    workspace_id = Column(Integer, ForeignKey('workspace.id'), index=True,
                          nullable=False)
    workspace = relationship(
        'Workspace',
        foreign_keys=[workspace_id],
        backref=backref('comments', cascade="all, delete-orphan"),
    )

    object_id = Column(Integer, nullable=False)
    object_type = Column(Enum(*OBJECT_TYPES, name='object_types'), nullable=False)

    @property
    def parent(self):
        return


class ExecutiveReport(Metadata):
    STATUSES = [
        'created',
        'error',
        'processing',
    ]
    __tablename__ = 'executive_report'
    id = Column(Integer, primary_key=True)

    grouped = Column(Boolean, nullable=False, default=False)
    name = NonBlankColumn(Text, index=True)
    status = Column(Enum(*STATUSES, name='executive_report_statuses'), nullable=False, default='processing')
    template_name = NonBlankColumn(Text)

    conclusions = BlankColumn(Text)
    enterprise = BlankColumn(Text)
    objectives = BlankColumn(Text)
    recommendations = BlankColumn(Text)
    scope = BlankColumn(Text)
    summary = BlankColumn(Text)
    title = BlankColumn(Text)
    confirmed = Column(Boolean, nullable=False, default=False)
    vuln_count = Column(Integer, default=0)  # saves the amount of vulns when the report was generated.

    workspace_id = Column(Integer, ForeignKey('workspace.id'), index=True, nullable=False)
    workspace = relationship(
        'Workspace',
        backref=backref('reports', cascade="all, delete-orphan"),
        foreign_keys=[workspace_id]
    )
    tags = relationship(
        "Tag",
        secondary="tag_object",
        primaryjoin="and_(TagObject.object_id==ExecutiveReport.id, "
                    "TagObject.object_type=='executive_report')",
        collection_class=set,
    )
    @property
    def parent(self):
        return

    @property
    def attachments(self):
        return db.session.query(File).filter_by(
            object_id=self.id,
            object_type='executive_report'
        )


# This constraint uses Columns from different classes
# Since it applies to the table vulnerability it should be adVulnerability.ded to the Vulnerability class
# However, since it contains columns from children classes, this cannot be done
# This is a workaround suggested by SQLAlchemy's creator
CheckConstraint('((Vulnerability.host_id IS NOT NULL)::int+'
                '(Vulnerability.service_id IS NOT NULL)::int+'
                '(Vulnerability.source_code_id IS NOT NULL)::int)=1',
                name='check_vulnerability_host_service_source_code',
                table=VulnerabilityGeneric.__table__)

vulnerability_uniqueness = DDL(
    "CREATE UNIQUE INDEX uix_vulnerability ON %(fullname)s "
    "(md5(name), md5(description), type, COALESCE(host_id, -1), COALESCE(service_id, -1), "
    "COALESCE(md5(method), ''), COALESCE(md5(parameter_name), ''), COALESCE(md5(path), ''), "
    "COALESCE(md5(website), ''), workspace_id, COALESCE(source_code_id, -1));"
)

vulnerability_uniqueness_sqlite = DDL(
    "CREATE UNIQUE INDEX uix_vulnerability ON %(fullname)s "
    "(name, description, type, COALESCE(host_id, -1), COALESCE(service_id, -1), "
    "COALESCE(method, ''), COALESCE(parameter_name, ''), COALESCE(path, ''), "
    "COALESCE(website, ''), workspace_id, COALESCE(source_code_id, -1));"
)


event.listen(
    VulnerabilityGeneric.__table__,
    'after_create',
    vulnerability_uniqueness.execute_if(dialect='postgresql')
)

event.listen(
    VulnerabilityGeneric.__table__,
    'after_create',
    vulnerability_uniqueness_sqlite.execute_if(dialect='sqlite')
)

# We have to import this after all models are defined
import server.events