Пример #1
0
    def log(self, request, response, time):
        query = dict(request.query)
        body = request.get("body", dict())
        if 'password' in query:
            query['password'] = '******'
        if 'password' in body:
            body['password'] = '******'
        if 'key' in body and '/agents' in request.path:
            body['key'] = '****'
        # With permanent redirect, not found responses or any response with no token information,
        # decode the JWT token to get the username
        user = request.get('user', '')
        if not user:
            try:
                user = decode_token(
                    request.headers["authorization"][7:])["sub"]
            except Unauthorized:
                user = UNKNOWN_USER_STRING

        self.logger.info(
            f'{user} '
            f'{request.remote} '
            f'"{request.method} {request.path}" '
            f'with parameters {json.dumps(query)} and body {json.dumps(body)} '
            f'done in {time:.3f}s: {response.status}')
Пример #2
0
def test_decode_token(mock_raise_if_exc, mock_distribute_function, mock_dapi, mock_generate_secret, mock_decode):
    mock_decode.return_value = payload
    mock_raise_if_exc.side_effect = [WazuhResult({'valid': True}), WazuhResult(security_conf)]

    result = authentication.decode_token('test_token')
    assert result == payload

    # Check all functions are called with expected params
    calls = [call(f=ANY, f_kwargs={'username': payload['sub'], 'token_iat_time': payload['iat']},
                  request_type='local_master', is_async=False, wait_for_complete=True, logger=ANY),
             call(f=ANY, request_type='local_master', is_async=False, wait_for_complete=True, logger=ANY)]
    mock_dapi.assert_has_calls(calls)
    mock_generate_secret.assert_called_once()
    mock_decode.assert_called_once_with('test_token', 'test_secret_token', algorithms=['HS256'])
    assert mock_distribute_function.call_count == 2
    assert mock_raise_if_exc.call_count == 2
Пример #3
0
def test_decode_token(mock_raise_if_exc, mock_submit, mock_distribute_function,
                      mock_dapi, mock_generate_secret, mock_decode):
    mock_decode.return_value = deepcopy(original_payload)
    mock_raise_if_exc.side_effect = [
        WazuhResult({
            'valid': True,
            'policies': {
                'value': 'test'
            }
        }),
        WazuhResult(security_conf)
    ]

    result = authentication.decode_token('test_token')
    assert result == decoded_payload

    # Check all functions are called with expected params
    calls = [
        call(f=ANY,
             f_kwargs={
                 'username': original_payload['sub'],
                 'token_nbf_time': original_payload['nbf'],
                 'run_as': False,
                 'roles': tuple(original_payload['rbac_roles']),
                 'origin_node_type': 'master'
             },
             request_type='local_master',
             is_async=False,
             wait_for_complete=False,
             logger=ANY),
        call(f=ANY,
             request_type='local_master',
             is_async=False,
             wait_for_complete=False,
             logger=ANY)
    ]
    mock_dapi.assert_has_calls(calls)
    mock_generate_secret.assert_called_once()
    mock_decode.assert_called_once_with('test_token',
                                        'test_secret_token',
                                        algorithms=['HS256'],
                                        audience='Wazuh API REST')
    assert mock_distribute_function.call_count == 2
    assert mock_raise_if_exc.call_count == 2
Пример #4
0
def test_decode_token_ko(mock_generate_secret, mock_raise_if_exc, mock_submit, mock_distribute_function):
    """Assert exceptions are handled as expected inside decode_token()"""
    with pytest.raises(Unauthorized):
        authentication.decode_token(token='test_token')

    with patch('api.authentication.jwt.decode') as mock_decode:
        with patch('api.authentication.generate_secret', return_value='test_secret_token'):
            with patch('wazuh.core.cluster.dapi.dapi.DistributedAPI.__init__', return_value=None):
                with patch('wazuh.core.cluster.dapi.dapi.DistributedAPI.distribute_function'):
                    with patch('api.authentication.raise_if_exc') as mock_raise_if_exc:
                        mock_decode.return_value = deepcopy(original_payload)

                        with pytest.raises(Unauthorized):
                            mock_raise_if_exc.side_effect = [WazuhResult({'valid': False})]
                            authentication.decode_token(token='test_token')

                        with pytest.raises(Unauthorized):
                            mock_raise_if_exc.side_effect = [WazuhResult({'valid': True, 'policies': {'value': 'test'}}),
                                                             WazuhResult({'auth_token_exp_timeout': 3600,
                                                                          'rbac_mode': 'white'})]
                            authentication.decode_token(token='test_token')