Implements file except handler for patchsets
[releng-anteater.git] / anteater / src / patch_scan.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 ##############################################################################
4 # Copyright (c) 2017 Luke Hinds <lhinds@redhat.com>, Red Hat
5 #
6 # All rights reserved. This program and the accompanying materials
7 # are made available under the terms of the Apache License, Version 2.0
8 # which accompanies this distribution, and is available at
9 # http://www.apache.org/licenses/LICENSE-2.0
10 ##############################################################################
11
12 """
13     Accepts the --patchset argument and iterates through each line of the
14     patchset file to perform various checks such as if the file is a binary, or
15     contains a blacklisted string. If any violations are found, the script
16     exits with code 1 and logs the violation(s) found.
17 """
18
19 from __future__ import division, print_function, absolute_import
20 from binaryornot.check import is_binary
21 import logging
22 import hashlib
23 import six.moves.configparser
24 import sys
25 import re
26
27 from . import get_lists
28
29 logger = logging.getLogger(__name__)
30 config = six.moves.configparser.RawConfigParser()
31 config.read('anteater.conf')
32 reports_dir = config.get('config', 'reports_dir')
33 failure = False
34 hasher = hashlib.sha256()
35
36
37 def prepare_patchset(project, patchset):
38     """ Create black/white lists and default / project waivers
39         and iterates over patchset file """
40
41     # Get Various Lists / Project Waivers
42     lists = get_lists.GetLists()
43     # Get binary white list
44     binary_list = lists.binary_list(project)
45
46     # Get file name black list and project waivers
47     file_audit_list, file_audit_project_list = lists.file_audit_list(project)
48
49     # Get file content black list and project waivers
50     file_content_list, \
51         file_content_project_list = lists.file_content_list(project)
52
53     # Get Licence Lists
54     licence_ext = lists.licence_extensions()
55     licence_ignore = lists.licence_ignore()
56
57     # Open patch set to get file list
58     try:
59         fo = open(patchset, 'r')
60         lines = fo.readlines()
61     except IOError:
62         logger.error('%s does not exist', patchset)
63         sys.exit(1)
64
65     for line in lines:
66         patch_file = line.strip('\n')
67         # Perform binary and file / content checks
68         scan_patch(project, patch_file, binary_list,
69                    file_audit_list, file_audit_project_list,
70                    file_content_list, file_content_project_list, licence_ext,
71                    licence_ignore)
72
73     # Process each file in patch set using waivers generated above
74     # Process final result
75     process_failure()
76
77
78 def scan_patch(project, patch_file, binary_list, file_audit_list,
79                file_audit_project_list, file_content_list,
80                file_content_project_list, licence_ext, licence_ignore):
81     """ Scan actions for each commited file in patch set """
82     global failure
83     if is_binary(patch_file):
84         hashlist = get_lists.GetLists()
85         binary_hash = hashlist.binary_hash(project, patch_file)
86         if not binary_list.search(patch_file):
87             with open(patch_file, 'rb') as afile:
88                 buf = afile.read()
89                 hasher.update(buf)
90             if hasher.hexdigest() in binary_hash:
91                 logger.info('Found matching file hash for file: %s',
92                             patch_file)
93             else:
94                 logger.error('Non Whitelisted Binary file: %s',
95                              patch_file)
96                 logger.error('Submit patch with the following hash: %s',
97                              hasher.hexdigest())
98             failure = True
99             with open(reports_dir + "binaries-" + project + ".log", "a") \
100                     as gate_report:
101                 gate_report.write('Non Whitelisted Binary file: {0}\n'.
102                                   format(patch_file))
103     else:
104         # Check file names / extensions
105         if file_audit_list.search(patch_file) and not \
106                     file_audit_project_list.search(patch_file):
107             match = file_audit_list.search(patch_file)
108             logger.error('Blacklisted file: %s', patch_file)
109             logger.error('Matched String: %s', match.group())
110             failure = True
111             with open(reports_dir + "file-names_" + project + ".log", "a") \
112                     as gate_report:
113                 gate_report.write('Blacklisted file: {0}\n'.
114                                   format(patch_file))
115                 gate_report.write('Matched String: {0}'.
116                                   format(match.group()))
117
118         # Open file to check for blacklisted content
119         fo = open(patch_file, 'r')
120         lines = fo.readlines()
121
122         for line in lines:
123             if file_content_list.search(line) and not \
124                     file_content_project_list.search(line):
125                 match = file_content_list.search(line)
126                 logger.error('File contains violation: %s', patch_file)
127                 logger.error('Flagged Content: %s', line.rstrip())
128                 logger.error('Matched String: %s', match.group())
129                 failure = True
130                 with open(reports_dir + "contents_" + project + ".log",
131                           "a") as gate_report:
132                     gate_report.write('File contains violation: {0}\n'.
133                                       format(patch_file))
134                     gate_report.write('Flagged Content: {0}'.
135                                       format(line))
136                     gate_report.write('Matched String: {0}\n'.
137                                       format(match.group()))
138
139         # Run license check
140         licence_check(project, licence_ext, licence_ignore, patch_file)
141
142
143 def licence_check(project, licence_ext,
144                   licence_ignore, patch_file):
145     """ Performs licence checks """
146     global failure
147     if patch_file.endswith(tuple(licence_ext)) \
148             and patch_file not in licence_ignore:
149         fo = open(patch_file, 'r')
150         content = fo.read()
151         # Note: Hardcoded use of 'copyright' & 'spdx' is the result
152         # of a decision made at 2017 plugfest to limit searches to
153         # just these two strings.
154         patterns = ['copyright', 'spdx',
155                     'http://creativecommons.org/licenses/by/4.0']
156         if any(i in content.lower() for i in patterns):
157             logger.info('Contains needed Licence string: %s', patch_file)
158         else:
159             logger.error('Licence header missing in file: %s', patch_file)
160             failure = True
161             with open(reports_dir + "licence-" + project + ".log", "a") \
162                     as gate_report:
163                 gate_report.write('Licence header missing in file: {0}\n'.
164                                   format(patch_file))
165
166
167 def process_failure():
168     """ If any scan operations register a failure, sys.exit(1) is called
169         to allow jjb to register a failure"""
170     if failure:
171         logger.error('Please visit: https://wiki.opnfv.org/x/5oey')
172         sys.exit(1)