summaryrefslogtreecommitdiffstats
path: root/src/fluent-bit/lib/librdkafka-2.1.0/tests/sasl_test.py
blob: 9cb7d194a13cb63648911cccd3097b7145f28400 (plain)
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
#!/usr/bin/env python3
#
#
# Run librdkafka regression tests on with different SASL parameters
# and broker verisons.
#
# Requires:
#  trivup python module
#  gradle in your PATH

from cluster_testing import (
    LibrdkafkaTestCluster,
    print_report_summary,
    print_test_report_summary,
    read_scenario_conf)
from LibrdkafkaTestApp import LibrdkafkaTestApp

import os
import sys
import argparse
import json
import tempfile


def test_it(version, deploy=True, conf={}, rdkconf={}, tests=None, debug=False,
            scenario="default"):
    """
    @brief Create, deploy and start a Kafka cluster using Kafka \\p version
    Then run librdkafka's regression tests.
    """

    cluster = LibrdkafkaTestCluster(
        version, conf, debug=debug, scenario=scenario)

    # librdkafka's regression tests, as an App.
    rdkafka = LibrdkafkaTestApp(cluster, version, _rdkconf, tests=tests,
                                scenario=scenario)
    rdkafka.do_cleanup = False
    rdkafka.local_tests = False

    if deploy:
        cluster.deploy()

    cluster.start(timeout=30)

    print(
        '# Connect to cluster with bootstrap.servers %s' %
        cluster.bootstrap_servers())
    rdkafka.start()
    print(
        '# librdkafka regression tests started, logs in %s' %
        rdkafka.root_path())
    try:
        rdkafka.wait_stopped(timeout=60 * 30)
        rdkafka.dbg(
            'wait stopped: %s, runtime %ds' %
            (rdkafka.state, rdkafka.runtime()))
    except KeyboardInterrupt:
        print('# Aborted by user')

    report = rdkafka.report()
    if report is not None:
        report['root_path'] = rdkafka.root_path()

    cluster.stop(force=True)

    cluster.cleanup()
    return report


def handle_report(report, version, suite):
    """ Parse test report and return tuple (Passed(bool), Reason(str)) """
    test_cnt = report.get('tests_run', 0)

    if test_cnt == 0:
        return (False, 'No tests run')

    passed = report.get('tests_passed', 0)
    failed = report.get('tests_failed', 0)
    if 'all' in suite.get('expect_fail', []) or version in suite.get(
            'expect_fail', []):
        expect_fail = True
    else:
        expect_fail = False

    if expect_fail:
        if failed == test_cnt:
            return (True, 'All %d/%d tests failed as expected' %
                    (failed, test_cnt))
        else:
            return (False, '%d/%d tests failed: expected all to fail' %
                    (failed, test_cnt))
    else:
        if failed > 0:
            return (False, '%d/%d tests passed: expected all to pass' %
                    (passed, test_cnt))
        else:
            return (True, 'All %d/%d tests passed as expected' %
                    (passed, test_cnt))


if __name__ == '__main__':

    parser = argparse.ArgumentParser(
        description='Run librdkafka test suit using SASL on a '
        'trivupped cluster')

    parser.add_argument('--conf', type=str, dest='conf', default=None,
                        help='trivup JSON config object (not file)')
    parser.add_argument('--rdkconf', type=str, dest='rdkconf', default=None,
                        help='trivup JSON config object (not file) '
                        'for LibrdkafkaTestApp')
    parser.add_argument('--scenario', type=str, dest='scenario',
                        default='default',
                        help='Test scenario (see scenarios/ directory)')
    parser.add_argument('--tests', type=str, dest='tests', default=None,
                        help='Test to run (e.g., "0002")')
    parser.add_argument('--no-ssl', action='store_false', dest='ssl',
                        default=True,
                        help='Don\'t run SSL tests')
    parser.add_argument('--no-sasl', action='store_false', dest='sasl',
                        default=True,
                        help='Don\'t run SASL tests')
    parser.add_argument('--no-oidc', action='store_false', dest='oidc',
                        default=True,
                        help='Don\'t run OAuth/OIDC tests')
    parser.add_argument('--no-plaintext', action='store_false',
                        dest='plaintext', default=True,
                        help='Don\'t run PLAINTEXT tests')

    parser.add_argument('--report', type=str, dest='report', default=None,
                        help='Write test suites report to this filename')
    parser.add_argument('--debug', action='store_true', dest='debug',
                        default=False,
                        help='Enable trivup debugging')
    parser.add_argument('--suite', type=str, default=None,
                        help='Only run matching suite(s) (substring match)')
    parser.add_argument('versions', type=str, default=None,
                        nargs='*', help='Limit broker versions to these')
    args = parser.parse_args()

    conf = dict()
    rdkconf = dict()

    if args.conf is not None:
        conf.update(json.loads(args.conf))
    if args.rdkconf is not None:
        rdkconf.update(json.loads(args.rdkconf))
    if args.tests is not None:
        tests = args.tests.split(',')
    else:
        tests = None

    conf.update(read_scenario_conf(args.scenario))

    # Test version,supported mechs + suite matrix
    versions = list()
    if len(args.versions):
        for v in args.versions:
            versions.append(
                (v, ['SCRAM-SHA-512', 'PLAIN', 'GSSAPI', 'OAUTHBEARER']))
    else:
        versions = [('3.1.0',
                     ['SCRAM-SHA-512', 'PLAIN', 'GSSAPI', 'OAUTHBEARER']),
                    ('2.1.0',
                     ['SCRAM-SHA-512', 'PLAIN', 'GSSAPI', 'OAUTHBEARER']),
                    ('0.10.2.0', ['SCRAM-SHA-512', 'PLAIN', 'GSSAPI']),
                    ('0.9.0.1', ['GSSAPI']),
                    ('0.8.2.2', [])]
    sasl_plain_conf = {'sasl_mechanisms': 'PLAIN',
                       'sasl_users': 'myuser=mypassword'}
    sasl_scram_conf = {'sasl_mechanisms': 'SCRAM-SHA-512',
                       'sasl_users': 'myuser=mypassword'}
    ssl_sasl_plain_conf = {'sasl_mechanisms': 'PLAIN',
                           'sasl_users': 'myuser=mypassword',
                           'security.protocol': 'SSL'}
    sasl_oauthbearer_conf = {'sasl_mechanisms': 'OAUTHBEARER',
                             'sasl_oauthbearer_config':
                             'scope=requiredScope principal=admin'}
    sasl_oauth_oidc_conf = {'sasl_mechanisms': 'OAUTHBEARER',
                            'sasl_oauthbearer_method': 'OIDC'}
    sasl_kerberos_conf = {'sasl_mechanisms': 'GSSAPI',
                          'sasl_servicename': 'kafka'}
    suites = [{'name': 'SASL PLAIN',
               'run': (args.sasl and args.plaintext),
               'conf': sasl_plain_conf,
               'tests': ['0001'],
               'expect_fail': ['0.9.0.1', '0.8.2.2']},
              {'name': 'SASL SCRAM',
               'run': (args.sasl and args.plaintext),
               'conf': sasl_scram_conf,
               'expect_fail': ['0.9.0.1', '0.8.2.2']},
              {'name': 'PLAINTEXT (no SASL)',
               'run': args.plaintext,
               'tests': ['0001']},
              {'name': 'SSL (no SASL)',
               'run': args.ssl,
               'conf': {'security.protocol': 'SSL'},
               'expect_fail': ['0.8.2.2']},
              {'name': 'SASL_SSL PLAIN',
               'run': (args.sasl and args.ssl and args.plaintext),
               'conf': ssl_sasl_plain_conf,
               'expect_fail': ['0.9.0.1', '0.8.2.2']},
              {'name': 'SASL PLAIN with wrong username',
               'run': (args.sasl and args.plaintext),
               'conf': sasl_plain_conf,
               'rdkconf': {'sasl_users': 'wrongjoe=mypassword'},
               'tests': ['0001'],
               'expect_fail': ['all']},
              {'name': 'SASL OAUTHBEARER',
               'run': args.sasl,
               'conf': sasl_oauthbearer_conf,
               'tests': ['0001'],
               'expect_fail': ['0.10.2.0', '0.9.0.1', '0.8.2.2']},
              {'name': 'SASL OAUTHBEARER with wrong scope',
               'run': args.sasl,
               'conf': sasl_oauthbearer_conf,
               'rdkconf': {'sasl_oauthbearer_config': 'scope=wrongScope'},
               'tests': ['0001'],
               'expect_fail': ['all']},
              {'name': 'OAuth/OIDC',
               'run': args.oidc,
               'tests': ['0001', '0126'],
               'conf': sasl_oauth_oidc_conf,
               'minver': '3.1.0',
               'expect_fail': ['2.8.1', '2.1.0', '0.10.2.0',
                               '0.9.0.1', '0.8.2.2']},
              {'name': 'SASL Kerberos',
               'run': args.sasl,
               'conf': sasl_kerberos_conf,
               'expect_fail': ['0.8.2.2']}]

    pass_cnt = 0
    fail_cnt = 0
    for version, supported in versions:
        if len(args.versions) > 0 and version not in args.versions:
            print('### Skipping version %s' % version)
            continue

        for suite in suites:
            if not suite.get('run', True):
                continue

            if args.suite is not None and suite['name'].find(args.suite) == -1:
                print(
                    f'# Skipping {suite["name"]} due to --suite {args.suite}')
                continue

            if 'minver' in suite:
                minver = [int(x) for x in suite['minver'].split('.')][:3]
                this_version = [int(x) for x in version.split('.')][:3]
                if this_version < minver:
                    print(
                        f'# Skipping {suite["name"]} due to version {version} < minimum required version {suite["minver"]}')  # noqa: E501
                    continue

            _conf = conf.copy()
            _conf.update(suite.get('conf', {}))
            _rdkconf = _conf.copy()
            _rdkconf.update(rdkconf)
            _rdkconf.update(suite.get('rdkconf', {}))

            if 'version' not in suite:
                suite['version'] = dict()

            # Disable SASL broker config if broker version does
            # not support the selected mechanism
            mech = suite.get('conf', dict()).get('sasl_mechanisms', None)
            if mech is not None and mech not in supported:
                print('# Disabled SASL for broker version %s' % version)
                _conf.pop('sasl_mechanisms', None)

            # Run tests
            print(
                '#### Version %s, suite %s: STARTING' %
                (version, suite['name']))
            if tests is None:
                tests_to_run = suite.get('tests', None)
            else:
                tests_to_run = tests
            report = test_it(version, tests=tests_to_run, conf=_conf,
                             rdkconf=_rdkconf,
                             debug=args.debug, scenario=args.scenario)

            # Handle test report
            report['version'] = version
            passed, reason = handle_report(report, version, suite)
            report['PASSED'] = passed
            report['REASON'] = reason

            if passed:
                print('\033[42m#### Version %s, suite %s: PASSED: %s\033[0m' %
                      (version, suite['name'], reason))
                pass_cnt += 1
            else:
                print('\033[41m#### Version %s, suite %s: FAILED: %s\033[0m' %
                      (version, suite['name'], reason))
                print_test_report_summary('%s @ %s' %
                                          (suite['name'], version), report)
                fail_cnt += 1
            print('#### Test output: %s/stderr.log' % (report['root_path']))

            suite['version'][version] = report

    # Write test suite report JSON file
    if args.report is not None:
        test_suite_report_file = args.report
        f = open(test_suite_report_file, 'w')
    else:
        fd, test_suite_report_file = tempfile.mkstemp(prefix='test_suite_',
                                                      suffix='.json',
                                                      dir='.')
        f = os.fdopen(fd, 'w')

    full_report = {'suites': suites, 'pass_cnt': pass_cnt,
                   'fail_cnt': fail_cnt, 'total_cnt': pass_cnt + fail_cnt}

    f.write(json.dumps(full_report))
    f.close()

    print('\n\n\n')
    print_report_summary(full_report)
    print('#### Full test suites report in: %s' % test_suite_report_file)

    if pass_cnt == 0 or fail_cnt > 0:
        sys.exit(1)
    else:
        sys.exit(0)