6
0
mirror of https://github.com/FirebirdSQL/firebird-qa.git synced 2025-02-02 02:40:42 +01:00

Added/Updated functional\syspriv\test_trace_any_attachment.py: Checked on 4.0.1.2692, 5.0.0.497.

This commit is contained in:
zotov 2022-05-25 14:28:57 +03:00
parent eaa605b920
commit 5da35c2d91

View File

@ -5,197 +5,87 @@ ID: syspriv.trace-any-attachment
TITLE: Check ability to trace any attachment by non-sysdba user who is granted with necessary system privileges
DESCRIPTION:
FBTEST: functional.syspriv.trace_any_attachment
NOTES:
[25.05.2022] pzotov
Test creates two user:
1) 'tmp_syspriv_user', who has grant for trace any attachment;
2) 'tmp_stock_manager', common non-privileged user.
User 'tmp_syspriv_user' is granted with system privilege via role 'tmp_role_trace_any_attachment'.
Then we launch trace by tmp_syspriv_user with making it watch for connections.
Finally, we establish two new connections to test DB: one from non-privileged user and second from SYSDBA.
Both of these connections must reflect in trace which was lcunched by tmp_syspriv_user.
Checked on 4.0.1.2692, 5.0.0.497.
"""
import pytest
import locale
import re
from firebird.qa import *
init_script = """
set wng off;
set bail on;
create or alter user sys_tracer_for_anyone password '123' revoke admin role;
revoke all on all from sys_tracer_for_anyone;
commit;
-- Trace other users' attachments
create role role_for_trace_any_attachment
set system privileges to TRACE_ANY_ATTACHMENT;
commit;
grant default role_for_trace_any_attachment to user sys_tracer_for_anyone;
commit;
recreate table test_trace_any_attachment(id int);
commit;
"""
db = db_factory(init=init_script)
db = db_factory()
tmp_user = user_factory('db', name='tmp_syspriv_user', password='123')
tmp_role = role_factory('db', name='tmp_role_trace_any_attachment')
tmp_usr2 = user_factory('db', name='tmp_stock_manager', password='123')
act = python_act('db')
expected_stdout = """
FOUND SYSDBA ATTACHMENT.
FOUND SYSDBA STATEMENT.
"""
@pytest.mark.skip('FIXME: Not IMPLEMENTED')
@pytest.mark.version('>=4.0')
def test_1(act: Action):
pytest.fail("Not IMPLEMENTED")
def test_1(act: Action, tmp_user: User, tmp_role: Role, tmp_usr2: User, capsys):
# test_script_1
#---
#
# import os
# import subprocess
# from subprocess import Popen
# import time
#
# os.environ["ISC_USER"] = user_name
# os.environ["ISC_PASSWORD"] = user_password
#
# db_file=os.path.basename(db_conn.database_name)
# db_conn.close()
#
# #--------------------------------------------
#
# def flush_and_close( file_handle ):
# # https://docs.python.org/2/library/os.html#os.fsync
# # If you're starting with a Python file object f,
# # first do f.flush(), and
# # then do os.fsync(f.fileno()), to ensure that all internal buffers associated with f are written to disk.
# global os
#
# file_handle.flush()
# if file_handle.mode not in ('r', 'rb') and file_handle.name != os.devnull:
# # otherwise: "OSError: [Errno 9] Bad file descriptor"!
# os.fsync(file_handle.fileno())
# file_handle.close()
#
# #--------------------------------------------
#
# def cleanup( f_names_list ):
# global os
# for f in f_names_list:
# if type(f) == file:
# del_name = f.name
# elif type(f) == str:
# del_name = f
# else:
# print('Unrecognized type of element:', f, ' - can not be treated as file.')
# del_name = None
#
# if del_name and os.path.isfile( del_name ):
# os.remove( del_name )
#
# #--------------------------------------------
#
# trace_options = '''# Trace config, format for 3.0 and above. Generated auto, do not edit!
# database=%%[\\\\\\\\/]%(db_file)s
# {
# enabled = true
# log_initfini = false
# log_errors = true
# time_threshold = 0
# log_statement_start = true
# log_statement_finish = true
# print_perf = true
# max_sql_length = 16384
# }
# ''' % locals()
#
# f_trccfg=open( os.path.join(context['temp_directory'],'tmp_syspriv_trace_any_attacmhent.cfg'), 'w')
# f_trccfg.write(trace_options)
# flush_and_close( f_trccfg )
#
# # Starting trace session in new child process (async.):
# #######################################################
#
# f_trclog=open( os.path.join(context['temp_directory'],'tmp_syspriv_trace_any_attacmhent.log'), 'w')
# f_trcerr=open( os.path.join(context['temp_directory'],'tmp_syspriv_trace_any_attacmhent.err'), 'w')
#
# # Execute a child program in a new process, redirecting STDERR to the same target as of STDOUT:
# p_trace=Popen([context['fbsvcmgr_path'], "localhost:service_mgr",
# "user", "sys_tracer_for_anyone", "password", "123",
# "action_trace_start",
# "trc_cfg", f_trccfg.name],
# stdout=f_trclog,
# stderr=f_trcerr
# )
#
#
# time.sleep(1)
#
# #####################################################
# # Getting ID of launched trace session and STOP it:
#
# # Save active trace session info into file for further parsing it and obtain session_id back (for stop):
# f_trclst=open( os.path.join(context['temp_directory'],'tmp_trace_5273.lst'), 'w')
# subprocess.call([context['fbsvcmgr_path'], "localhost:service_mgr",
# "user", "sys_tracer_for_anyone", "password", "123",
# "action_trace_list"],
# stdout=f_trclst,
# stderr=subprocess.STDOUT
# )
# flush_and_close( f_trclst )
#
# trcssn=0
# with open( f_trclst.name,'r') as f:
# for line in f:
# i=1
# if 'Session ID' in line:
# for word in line.split():
# if i==3:
# trcssn=word
# i=i+1
# break
#
# # Result: `trcssn` is ID of active trace session. Now we have to terminate it:
#
# runProgram('isql',[dsn, '-q', '-n'], 'insert into test_trace_any_attachment(id) values(123456789);')
# time.sleep(1)
#
# # REQUEST TRACE TO STOP:
# ########################
# f_trclst=open(f_trclst.name,'a')
# f_trclst.seek(0,2)
# subprocess.call([context['fbsvcmgr_path'], "localhost:service_mgr",
# "user", "sys_tracer_for_anyone", "password", "123",
# "action_trace_stop",
# "trc_id",trcssn],
# stdout=f_trclst, stderr=subprocess.STDOUT
# )
# flush_and_close( f_trclst )
#
# time.sleep(2)
#
# # Terminate child process of launched trace session (though it should already be killed):
# p_trace.terminate()
# flush_and_close( f_trclog )
# flush_and_close( f_trcerr )
#
#
# # Must be EMPTY:
# with open( f_trcerr.name,'r') as f:
# for line in f:
# print(line)
#
# # Must contain info about SYSDBA activity (this was traced by non-sysdba user):
#
# found_sysdba_attachment, found_sysdba_statement = False, False
# with open( f_trclog.name,'r') as f:
# for line in f:
# if 'SYSDBA:NONE' in line:
# if not found_sysdba_attachment:
# print('FOUND SYSDBA ATTACHMENT.')
# found_sysdba_attachment = True
# if '123456789' in line:
# if not found_sysdba_statement:
# print('FOUND SYSDBA STATEMENT.')
# found_sysdba_statement = True
#
# runProgram('isql',[dsn], 'drop user sys_tracer_for_anyone;')
#
# # Cleanup:
# ##########
# time.sleep(1)
# cleanup( (f_trclst,f_trcerr,f_trclog, f_trccfg) )
#---
expected_stdout = f"""
ATTACH/1:{act.db.user} : FOUND
ATTACH/2:{tmp_usr2.name} : FOUND
DETACH/1:{act.db.user} : FOUND
DETACH/2:{tmp_usr2.name} : FOUND
"""
init_script = f"""
set wng off;
set bail on;
alter user {tmp_user.name} revoke admin role;
revoke all on all from {tmp_user.name};
commit;
-- Trace other users' attachments
alter role {tmp_role.name}
set system privileges to TRACE_ANY_ATTACHMENT;
commit;
grant default {tmp_role.name} to user {tmp_user.name};
commit;
recreate table test_trace_any_attachment(id int);
commit;
"""
act.isql(switches=['-q'], input=init_script)
trace_cfg_items = [
'log_connections = true',
'log_errors = true',
]
with act.trace(db_events = trace_cfg_items, encoding=locale.getpreferredencoding(), user = tmp_user.name, password = tmp_user.password, role = tmp_role.name):
# We establish two attachments (for non-priv user {tmp_usr2} and for SYSDBA).
# BOTH of them must be seen in the trace that is generated for user {tmp_user}
# who has apropriate system privilege:
try:
with act.db.connect(user = tmp_usr2.name, password = tmp_usr2.password) as con1, \
act.db.connect(user = act.db.user, password = act.db.password) as con2:
pass
except DatabaseError:
pass
att_ptn = re.compile( '\\)\\s+(ATTACH|DETACH)_DATABASE')
row_bak = ''
found_events = {}
for line in act.trace_log:
if att_ptn.search(row_bak):
evt_name = 'ATTACH' if 'ATTACH' in row_bak else 'DETACH'
evt_user = '2:'+tmp_usr2.name if tmp_usr2.name in line else '1:'+act.db.user
found_events [ evt_name, evt_user ] = 'FOUND'
row_bak = line
for k,v in sorted(found_events.items()):
print( '/'.join(k), ':', v)
act.expected_stdout = expected_stdout
act.stdout = capsys.readouterr().out
assert act.clean_stdout == act.clean_expected_stdout