This repository has been archived by the owner on Jun 5, 2023. It is now read-only.
/
dao.py
executable file
·338 lines (274 loc) · 12.5 KB
/
dao.py
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
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# Licensed 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.
"""Provides the data access object (DAO)."""
from MySQLdb import DataError
from MySQLdb import IntegrityError
from MySQLdb import InternalError
from MySQLdb import NotSupportedError
from MySQLdb import OperationalError
from MySQLdb import ProgrammingError
from MySQLdb import cursors
from google.cloud.security.common.data_access import _db_connector
from google.cloud.security.common.data_access import csv_writer
from google.cloud.security.common.data_access import load_data_sql_provider
from google.cloud.security.common.data_access.errors import MySQLError
from google.cloud.security.common.data_access.errors import NoResultsError
from google.cloud.security.common.data_access.sql_queries import create_tables
from google.cloud.security.common.data_access.sql_queries import select_data
from google.cloud.security.common.util import log_util
LOGGER = log_util.get_logger(__name__)
CREATE_TABLE_MAP = {
# appengine
'appengine': create_tables.CREATE_APPENGINE_TABLE,
# appengine services
'appengine_services': create_tables.CREATE_APPENGINE_SERVICES_TABLE,
# appengine versions
'appengine_versions': create_tables.CREATE_APPENGINE_VERSIONS_TABLE,
# appengine instances
'appengine_instances': create_tables.CREATE_APPENGINE_INSTANCES_TABLE,
# backend services
'backend_services': create_tables.CREATE_BACKEND_SERVICES_TABLE,
# bigquery
'bigquery_datasets': create_tables.CREATE_BIGQUERY_DATASETS_TABLE,
# buckets
'buckets': create_tables.CREATE_BUCKETS_TABLE,
'raw_buckets': create_tables.CREATE_RAW_BUCKETS_TABLE,
'buckets_acl': create_tables.CREATE_BUCKETS_ACL_TABLE,
# cloudsql
'cloudsql_instances': create_tables.CREATE_CLOUDSQL_INSTANCES_TABLE,
'cloudsql_ipaddresses': create_tables.CREATE_CLOUDSQL_IPADDRESSES_TABLE,
'cloudsql_ipconfiguration_authorizednetworks':\
create_tables.CREATE_CLOUDSQL_IPCONFIGURATION_AUTHORIZEDNETWORKS,
# folders
'folders': create_tables.CREATE_FOLDERS_TABLE,
'folder_iam_policies': create_tables.CREATE_FOLDER_IAM_POLICIES_TABLE,
'raw_folder_iam_policies': (
create_tables.CREATE_RAW_FOLDER_IAM_POLICIES_TABLE),
# load balancer
'forwarding_rules': create_tables.CREATE_FORWARDING_RULES_TABLE,
# firewall_rules
'firewall_rules': create_tables.CREATE_FIREWALL_RULES_TABLE,
# groups
'groups': create_tables.CREATE_GROUPS_TABLE,
'group_members': create_tables.CREATE_GROUP_MEMBERS_TABLE,
# instances
'instances': create_tables.CREATE_INSTANCES_TABLE,
# instance groups
'instance_groups': create_tables.CREATE_INSTANCE_GROUPS_TABLE,
# instance templates
'instance_templates': create_tables.CREATE_INSTANCE_TEMPLATES_TABLE,
# instance group managers
'instance_group_managers': (
create_tables.CREATE_INSTANCE_GROUP_MANAGERS_TABLE),
# organizations
'organizations': create_tables.CREATE_ORGANIZATIONS_TABLE,
'org_iam_policies': create_tables.CREATE_ORG_IAM_POLICIES_TABLE,
'raw_org_iam_policies': create_tables.CREATE_RAW_ORG_IAM_POLICIES_TABLE,
# projects
'projects': create_tables.CREATE_PROJECT_TABLE,
'project_iam_policies': create_tables.CREATE_PROJECT_IAM_POLICIES_TABLE,
'raw_project_iam_policies':
create_tables.CREATE_RAW_PROJECT_IAM_POLICIES_TABLE,
# IAM
'service_accounts': create_tables.CREATE_SERVICE_ACCOUNTS_TABLE,
# rule violations
'violations': create_tables.CREATE_VIOLATIONS_TABLE,
}
SNAPSHOT_STATUS_FILTER_CLAUSE = ' where status in ({})'
class Dao(_db_connector.DbConnector):
"""Data access object (DAO)."""
@staticmethod
def map_row_to_object(object_class, row):
"""Instantiate an object from database row.
TODO: Make this go away when we start using an ORM.
Args:
object_class (object): The object class to create.
row (row): The database row to map.
Returns:
obj_class: A new "obj_class", created from the row.
"""
return object_class(**row)
def create_snapshot_table(self, resource_name, timestamp):
"""Creates a snapshot table.
Args:
resource_name (str): String of the resource name.
timestamp (str): String of timestamp, formatted as
YYYYMMDDTHHMMSSZ.
Returns:
str: String of the created snapshot table.
"""
snapshot_table_name = self._create_snapshot_table_name(
resource_name, timestamp)
create_table_sql = CREATE_TABLE_MAP[resource_name]
create_snapshot_sql = create_table_sql.format(snapshot_table_name)
cursor = self.conn.cursor()
cursor.execute(create_snapshot_sql)
return snapshot_table_name
@staticmethod
def _create_snapshot_table_name(resource_name, timestamp):
"""Create the snapshot table if it doesn't exist.
Args:
resource_name (str): String of the resource name.
timestamp (str): String of timestamp, formatted as
YYYYMMDDTHHMMSSZ.
Returns:
str: String of the created snapshot table name.
"""
return resource_name + '_' + timestamp
def _get_snapshot_table(self, resource_name, timestamp):
"""Returns a snapshot table name.
Args:
resource_name (str): String of the resource name.
timestamp (str): String of timestamp, formatted as YYYYMMDDTHHMMSSZ.
Returns:
str: String of the created snapshot table.
"""
try:
snapshot_table_name = self.create_snapshot_table(
resource_name, timestamp)
except OperationalError:
# TODO: find a better way to handle this. I want this method
# to be resilient when the table has already been created
# so that it can support inserting new data. This will catch
# a sql 'table already exist' error and alter the flow.
snapshot_table_name = self._create_snapshot_table_name(
resource_name, timestamp)
return snapshot_table_name
def load_data(self, resource_name, timestamp, data):
"""Load data into a snapshot table.
Args:
resource_name (str): String of the resource name.
timestamp (str): String of timestamp, formatted as
YYYYMMDDTHHMMSSZ.
data (iterable): An iterable or a list of data to be uploaded.
Raises:
MySQLError: When an error has occured while executing the query.
"""
with csv_writer.write_csv(resource_name, data) as csv_file:
try:
snapshot_table_name = self._create_snapshot_table_name(
resource_name, timestamp)
load_data_sql = load_data_sql_provider.provide_load_data_sql(
resource_name, csv_file.name, snapshot_table_name)
LOGGER.debug('SQL: %s', load_data_sql)
cursor = self.conn.cursor()
cursor.execute(load_data_sql)
self.conn.commit()
# TODO: Return the snapshot table name so that it can be tracked
# in the main snapshot table.
except (DataError, IntegrityError, InternalError,
NotSupportedError, OperationalError,
ProgrammingError) as e:
raise MySQLError(resource_name, e)
def select_record_count(self, resource_name, timestamp):
"""Select the record count from a snapshot table.
Args:
resource_name (str): String of the resource name, which is
embedded in the table name.
timestamp (str): String of timestamp, formatted as
YYYYMMDDTHHMMSSZ.
Returns:
int: Integer of the record count in a snapshot table.
Raises:
MySQLError: When an error has occured while executing the query.
"""
try:
record_count_sql = select_data.RECORD_COUNT.format(
resource_name, timestamp)
cursor = self.conn.cursor()
cursor.execute(record_count_sql)
return cursor.fetchone()[0]
except (DataError, IntegrityError, InternalError, NotSupportedError,
OperationalError, ProgrammingError) as e:
raise MySQLError(resource_name, e)
def select_group_ids(self, resource_name, timestamp):
"""Select the group ids from a snapshot table.
Args:
resource_name (str): String of the resource name.
timestamp (str): String of timestamp, formatted as
YYYYMMDDTHHMMSSZ.
Returns:
list: A list of group ids.
Raises:
MySQLError: When an error has occured while executing the query.
"""
try:
group_ids_sql = select_data.GROUP_IDS.format(timestamp)
cursor = self.conn.cursor(cursorclass=cursors.DictCursor)
cursor.execute(group_ids_sql)
rows = cursor.fetchall()
return [row['group_id'] for row in rows]
except (DataError, IntegrityError, InternalError, NotSupportedError,
OperationalError, ProgrammingError) as e:
raise MySQLError(resource_name, e)
def execute_sql_with_fetch(self, resource_name, sql, values):
"""Executes a provided sql statement with fetch.
Args:
resource_name (str): String of the resource name.
sql (str): String of the sql statement.
values (tuple): Tuple of string for sql placeholder values.
Returns:
list: A list of dict representing rows of sql query result.
Raises:
MySQLError: When an error has occured while executing the query.
"""
try:
cursor = self.conn.cursor(cursorclass=cursors.DictCursor)
cursor.execute(sql, values)
return cursor.fetchall()
except (DataError, IntegrityError, InternalError, NotSupportedError,
OperationalError, ProgrammingError) as e:
raise MySQLError(resource_name, e)
def execute_sql_with_commit(self, resource_name, sql, values):
"""Executes a provided sql statement with commit.
Args:
resource_name (str): String of the resource name.
sql (str): String of the sql statement.
values (tuple): Tuple of string for sql placeholder values.
Raises:
MySQLError: When an error has occured while executing the query.
"""
try:
cursor = self.conn.cursor()
cursor.execute(sql, values)
self.conn.commit()
except (DataError, IntegrityError, InternalError, NotSupportedError,
OperationalError, ProgrammingError) as e:
raise MySQLError(resource_name, e)
def get_latest_snapshot_timestamp(self, statuses):
"""Select the latest timestamp of the completed snapshot.
Args:
statuses (tuple): The tuple of snapshot statuses to filter on.
Returns:
str: The string timestamp of the latest complete snapshot.
Raises:
MySQLError: When no rows are found.
"""
# Build a dynamic parameterized query string for filtering the
# snapshot statuses
if not isinstance(statuses, tuple):
statuses = ('SUCCESS',)
status_params = ','.join(['%s']*len(statuses))
filter_clause = SNAPSHOT_STATUS_FILTER_CLAUSE.format(status_params)
try:
cursor = self.conn.cursor()
cursor.execute(
select_data.LATEST_SNAPSHOT_TIMESTAMP + filter_clause, statuses)
row = cursor.fetchone()
if row:
return row[0]
raise NoResultsError('No snapshot cycle found.')
except (DataError, IntegrityError, InternalError, NotSupportedError,
OperationalError, ProgrammingError, NoResultsError) as e:
raise MySQLError('snapshot_cycles', e)