Пример #1
0
def test_login_webauthn(live_server, selenium, test_user):  # pylint: disable=unused-argument
    """test login by webauthn"""

    device = SoftWebauthnDevice()
    device.cred_init(webauthn.rp.id, b'randomhandle')
    persist_and_detach(
        WebauthnCredential(user=test_user,
                           user_handle=device.user_handle,
                           credential_data=cbor.encode(
                               device.cred_as_attested().__dict__)))

    selenium.get(url_for('auth.login_route', _external=True))
    selenium.find_element_by_xpath(
        '//form//input[@name="username"]').send_keys(test_user.username)
    selenium.find_element_by_xpath('//form//input[@type="submit"]').click()

    # some javascript code must be emulated
    webdriver_waituntil(selenium, js_variable_ready('window.pkcro_raw'))
    pkcro = cbor.decode(
        b64decode(
            selenium.execute_script('return window.pkcro_raw;').encode(
                'utf-8')))
    assertion = device.get(pkcro, 'https://%s' % webauthn.rp.id)
    selenium.execute_script(
        'authenticate_assertion(CBOR.decode(Sner.base64_to_array_buffer("%s")));'
        % b64encode(cbor.encode(assertion)).decode('utf-8'))
    # and back to standard test codeflow

    webdriver_waituntil(
        selenium,
        EC.presence_of_element_located((By.XPATH, '//a[text()="Logout"]')))
Пример #2
0
def test_v1_scheduler_job_assign_route(client, apikey, test_queue):
    """job assign route test"""

    # assign from queue by id
    persist_and_detach(create_test_target(test_queue))
    response = client.get(url_for('api.v1_scheduler_job_assign_route',
                                  queue_ident=test_queue.id),
                          headers=apikey_header(apikey))
    assert response.status_code == HTTPStatus.OK
    assert isinstance(json.loads(response.body.decode('utf-8')), dict)
    assert len(Queue.query.get(test_queue.id).jobs) == 1

    # assign from queue by name
    persist_and_detach(create_test_target(test_queue))
    response = client.get(url_for('api.v1_scheduler_job_assign_route',
                                  queue_ident=test_queue.name),
                          headers=apikey_header(apikey))
    assert response.status_code == HTTPStatus.OK
    assert isinstance(json.loads(response.body.decode('utf-8')), dict)
    assert len(
        Queue.query.filter(Queue.name == test_queue.name).one().jobs) == 2

    # assign from non-existent queue
    response = client.get(
        url_for('api.v1_scheduler_job_assign_route', queue_id='notexist'),
        headers=apikey_header(apikey))  # should return response-nowork
    assert response.status_code == HTTPStatus.OK
    assert not json.loads(response.body.decode('utf-8'))

    # attempt without credentials
    response = client.get(url_for('api.v1_scheduler_job_assign_route'),
                          status='*')
    assert response.status_code == HTTPStatus.UNAUTHORIZED
Пример #3
0
def test_v1_scheduler_job_assign_route_priority(client, apikey, test_task):
    """job assign route test"""

    queue1 = Queue(name='queue1',
                   task=test_task,
                   group_size=1,
                   priority=10,
                   active=True)
    persist_and_detach(queue1)
    queue2 = Queue(name='queue2',
                   task=test_task,
                   group_size=1,
                   priority=20,
                   active=True)
    persist_and_detach(queue2)
    persist_and_detach(create_test_target(queue1))
    persist_and_detach(create_test_target(queue2))

    response = client.get(url_for('api.v1_scheduler_job_assign_route'),
                          headers=apikey_header(apikey))
    assert response.status_code == HTTPStatus.OK
    assert isinstance(json.loads(response.body.decode('utf-8')), dict)

    assert len(Queue.query.get(queue1.id).jobs) == 0
    assert len(Queue.query.get(queue2.id).jobs) == 1
Пример #4
0
def test_profile_webauthn_delete_route(cl_user):
    """profile delete webauthn credentials route test"""

    test_wncred = create_test_wncred(
        User.query.filter(User.username == 'pytest_user').one())
    persist_and_detach(test_wncred)

    form = cl_user.get(
        url_for('auth.profile_webauthn_delete_route',
                webauthn_id=test_wncred.id)).form
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    assert not WebauthnCredential.query.get(test_wncred.id)
Пример #5
0
def test_longrun_target(test_longrun_a):  # pylint: disable=redefined-outer-name
    """queue target fixture"""

    task = Task(name='test_task',
                module=test_longrun_a['module'],
                params=test_longrun_a['params'])
    persist_and_detach(task)
    queue = Queue(name='test_queue',
                  task=task,
                  group_size=1,
                  priority=10,
                  active=True)
    persist_and_detach(queue)
    target = Target(target=test_longrun_a['targets'][0], queue=queue)
    yield persist_and_detach(target)
Пример #6
0
def test_profile_webauthn_list_json_route(cl_user):
    """profile webauthn credentials json route test"""

    test_wncred = create_test_wncred(
        User.query.filter(User.username == 'pytest_user').one())
    persist_and_detach(test_wncred)

    response = cl_user.post(url_for('auth.profile_webauthn_list_json_route'), {
        'draw': 1,
        'start': 0,
        'length': 1,
        'search[value]': test_wncred.name
    })
    assert response.status_code == HTTPStatus.OK
    response_data = json.loads(response.body.decode('utf-8'))
    assert response_data['data'][0]['name'] == test_wncred.name
Пример #7
0
def test_profile_webauthn_edit_route(cl_user):
    """profile edit webauthn credentials route test"""

    test_wncred = create_test_wncred(
        User.query.filter(User.username == 'pytest_user').one())
    persist_and_detach(test_wncred)

    form = cl_user.post(
        url_for('auth.profile_webauthn_edit_route',
                webauthn_id=test_wncred.id)).form
    form['name'] = form['name'].value + ' edited'
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    wncred = WebauthnCredential.query.get(test_wncred.id)
    assert wncred.name == form['name'].value
Пример #8
0
def test_job_completed(test_queue):  # pylint: disable=redefined-outer-name
    """persistent test job completed"""

    job = create_test_job(test_queue)
    job.retval = 0
    job.output = os.path.join('scheduler', 'queue-%s' % job.queue_id, job.id)
    os.makedirs(os.path.dirname(job.output_abspath), exist_ok=True)
    with open(job.output_abspath, 'wb') as job_file:
        with ZipFile(job_file, 'w') as zip_file:
            zip_file.writestr(json.dumps(job.assignment), 'assignment.json')
    job.time_end = datetime.utcnow()
    yield persist_and_detach(job)
Пример #9
0
def test_wncred(test_user):  # pylint: disable=redefined-outer-name
    """persistent test registered webauthn credential"""

    device = SoftWebauthnDevice()
    device.cred_init(webauthn.rp.ident, b'randomhandle')
    wncred = WebauthnCredential(user_id=test_user.id,
                                user=test_user,
                                user_handle=device.user_handle,
                                credential_data=cbor.encode(
                                    device.cred_as_attested().__dict__),
                                name='testcredential')
    yield persist_and_detach(wncred)
Пример #10
0
def test_service_cleanup_command(runner, test_host):
    """test service_cleanup command"""

    test_service1 = persist_and_detach(Service(host_id=test_host.id, proto='tcp', port=1, state='open:reason'))
    test_service2 = persist_and_detach(Service(host_id=test_host.id, proto='tcp', port=1, state='filtered:reason'))
    persist_and_detach(Note(host_id=test_host.id, service_id=test_service2.id, xtype='cleanuptest', data='atestdata'))

    result = runner.invoke(storage_command, ['service-cleanup', '--dry'])
    assert result.exit_code == 0

    assert repr(test_service1) not in result.output
    assert repr(test_service2) in result.output
    assert Service.query.count() == 2

    result = runner.invoke(storage_command, ['service-cleanup'])
    assert result.exit_code == 0

    assert Note.query.count() == 0
    services = Service.query.all()
    assert len(services) == 1
    assert services[0].id == test_service1.id
Пример #11
0
def test_v1_scheduler_job_assign_route_exlusion(client, apikey, test_queue,
                                                test_excl_network):
    """job assign route test cleaning up excluded hosts"""

    persist_and_detach(create_test_target(test_queue))
    persist_and_detach(
        Target(target=str(ip_network(test_excl_network.value).network_address),
               queue=test_queue))

    response = client.get(url_for('api.v1_scheduler_job_assign_route'),
                          headers=apikey_header(apikey))
    assert response.status_code == HTTPStatus.OK

    assert len(Queue.query.get(test_queue.id).jobs) == 1
    assert not Target.query.all()
    assignment = json.loads(response.body.decode('utf-8'))
    assert len(assignment['targets']) == 1

    persist_and_detach(
        Target(target=str(ip_network(test_excl_network.value).network_address),
               queue=test_queue))
    response = client.get(
        url_for('api.v1_scheduler_job_assign_route'),
        headers=apikey_header(apikey))  # shoudl return response-nowork
    assert response.status_code == HTTPStatus.OK
    assert not json.loads(response.body.decode('utf-8'))
Пример #12
0
def test_webauthn_login_route(client, test_user):
    """test login by webauthn"""

    device = SoftWebauthnDevice()
    device.cred_init(webauthn.rp.ident, b'randomhandle')
    persist_and_detach(
        WebauthnCredential(user=test_user,
                           user_handle=device.user_handle,
                           credential_data=cbor.encode(
                               device.cred_as_attested().__dict__)))

    form = client.get(url_for('app.login_route')).form
    form['username'] = test_user.username
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    response = response.follow()
    # some javascript code muset be emulated
    pkcro = cbor.decode(
        b64decode(
            client.post(url_for('app.webauthn_pkcro_route'), {
                'csrf_token': get_csrf_token(client)
            }).body))
    assertion = device.get(pkcro, 'https://%s' % webauthn.rp.ident)
    assertion_data = {
        'credentialRawId': assertion['rawId'],
        'authenticatorData': assertion['response']['authenticatorData'],
        'clientDataJSON': assertion['response']['clientDataJSON'],
        'signature': assertion['response']['signature'],
        'userHandle': assertion['response']['userHandle']
    }
    form = response.form
    form['assertion'] = b64encode(cbor.encode(assertion_data))
    response = form.submit()
    # and back to standard test codeflow
    assert response.status_code == HTTPStatus.FOUND

    response = client.get(url_for('app.index_route'))
    assert response.lxml.xpath('//a[text()="Logout"]')
Пример #13
0
def test_host_cleanup_command(runner):
    """test host_cleanup command"""

    test_host1 = persist_and_detach(Host(address='127.127.127.135', os='identified'))
    test_host2 = persist_and_detach(Host(address='127.127.127.134'))
    persist_and_detach(Service(host_id=test_host2.id, proto='tcp', port=1, state='anystate:reason'))
    test_host3 = persist_and_detach(Host(address='127.127.127.133', hostname='xxx', os=''))

    result = runner.invoke(storage_command, ['host-cleanup', '--dry'])
    assert result.exit_code == 0

    assert repr(test_host1) not in result.output
    assert repr(test_host2) not in result.output
    assert repr(test_host3) in result.output
    assert Host.query.count() == 3

    result = runner.invoke(storage_command, ['host-cleanup'])
    assert result.exit_code == 0

    hosts = Host.query.all()
    assert len(hosts) == 2
    assert test_host3.id not in [x.id for x in hosts]
Пример #14
0
def test_task():
    """persistent test task"""

    yield persist_and_detach(create_test_task())
Пример #15
0
def test_user(app):  # pylint: disable=unused-argument,redefined-outer-name
    """persistent test user"""
    return persist_and_detach(User(username='******',
                                   password=PWS().generate()))
Пример #16
0
def test_host():
    """persistent test host"""

    yield persist_and_detach(create_test_host())
Пример #17
0
def test_note(test_host, test_service):  # pylint: disable=redefined-outer-name
    """persistent test note"""

    yield persist_and_detach(create_test_note(test_host, test_service))
Пример #18
0
def test_user(app):
    """persistent test user"""

    yield persist_and_detach(create_test_user())
Пример #19
0
def test_job(test_queue):  # pylint: disable=redefined-outer-name
    """persistent test job assigned"""

    yield persist_and_detach(create_test_job(test_queue))
Пример #20
0
def test_target(test_queue):  # pylint: disable=redefined-outer-name
    """persistent test queue"""

    yield persist_and_detach(create_test_target(test_queue))
Пример #21
0
def test_wncred(test_user):
    """persistent test registered webauthn credential"""

    yield persist_and_detach(create_test_wncred(test_user))
Пример #22
0
def test_excl_regex():
    """persistent test regex exclusion"""

    yield persist_and_detach(create_test_excl_regex())
Пример #23
0
def test_excl_network():
    """persistent test network exclusion"""

    yield persist_and_detach(create_test_excl_network())