11"""
22Initialize roles and permissions in the database
33"""
4+
45import asyncio
56import base64
67from sqlalchemy .orm import Session
1819
1920def init_roles (db : Session ):
2021 """Initialize roles in the database"""
21-
22+
2223 role_definitions = {
2324 UserRole .SUPER_ADMIN : {
2425 "display_name" : "Super Administrator" ,
25- "description" : "Full system access with user management capabilities"
26+ "description" : "Full system access with user management capabilities" ,
2627 },
2728 UserRole .SECURITY_ADMIN : {
28- "display_name" : "Security Administrator" ,
29- "description" : "Security-focused administration without user management"
29+ "display_name" : "Security Administrator" ,
30+ "description" : "Security-focused administration without user management" ,
3031 },
3132 UserRole .SECURITY_ANALYST : {
3233 "display_name" : "Security Analyst" ,
33- "description" : "Day-to-day security operations and scan execution"
34+ "description" : "Day-to-day security operations and scan execution" ,
3435 },
3536 UserRole .COMPLIANCE_OFFICER : {
3637 "display_name" : "Compliance Officer" ,
37- "description" : "Compliance reporting and read-only access to results"
38+ "description" : "Compliance reporting and read-only access to results" ,
3839 },
3940 UserRole .AUDITOR : {
40- "display_name" : "Auditor" ,
41- "description" : "External audit support with read-only access"
41+ "display_name" : "Auditor" ,
42+ "description" : "External audit support with read-only access" ,
4243 },
4344 UserRole .GUEST : {
4445 "display_name" : "Guest" ,
45- "description" : "Limited read-only access to assigned resources"
46- }
46+ "description" : "Limited read-only access to assigned resources" ,
47+ },
4748 }
48-
49+
4950 try :
5051 for role_name , role_info in role_definitions .items ():
5152 # Check if role already exists
52- result = db .execute (text ("""
53+ result = db .execute (
54+ text (
55+ """
5356 SELECT id FROM roles WHERE name = :name
54- """ ), {"name" : role_name .value })
55-
57+ """
58+ ),
59+ {"name" : role_name .value },
60+ )
61+
5662 if result .fetchone ():
57- logger .info (f"Role { role_name .value } already exists, updating permissions..." )
63+ logger .info (
64+ f"Role { role_name .value } already exists, updating permissions..."
65+ )
5866 # Update existing role permissions
59- permissions_json = json .dumps ([p .value for p in ROLE_PERMISSIONS [role_name ]])
60- db .execute (text ("""
67+ permissions_json = json .dumps (
68+ [p .value for p in ROLE_PERMISSIONS [role_name ]]
69+ )
70+ db .execute (
71+ text (
72+ """
6173 UPDATE roles
6274 SET permissions = :permissions,
6375 display_name = :display_name,
6476 description = :description,
6577 updated_at = CURRENT_TIMESTAMP
6678 WHERE name = :name
67- """ ), {
68- "name" : role_name .value ,
69- "permissions" : permissions_json ,
70- "display_name" : role_info ["display_name" ],
71- "description" : role_info ["description" ]
72- })
79+ """
80+ ),
81+ {
82+ "name" : role_name .value ,
83+ "permissions" : permissions_json ,
84+ "display_name" : role_info ["display_name" ],
85+ "description" : role_info ["description" ],
86+ },
87+ )
7388 else :
7489 logger .info (f"Creating role { role_name .value } ..." )
7590 # Create new role
76- permissions_json = json .dumps ([p .value for p in ROLE_PERMISSIONS [role_name ]])
77- db .execute (text ("""
91+ permissions_json = json .dumps (
92+ [p .value for p in ROLE_PERMISSIONS [role_name ]]
93+ )
94+ db .execute (
95+ text (
96+ """
7897 INSERT INTO roles (name, display_name, description, permissions, is_active, created_at, updated_at)
7998 VALUES (:name, :display_name, :description, :permissions, true, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
80- """ ), {
81- "name" : role_name .value ,
82- "display_name" : role_info ["display_name" ],
83- "description" : role_info ["description" ],
84- "permissions" : permissions_json
85- })
86-
99+ """
100+ ),
101+ {
102+ "name" : role_name .value ,
103+ "display_name" : role_info ["display_name" ],
104+ "description" : role_info ["description" ],
105+ "permissions" : permissions_json ,
106+ },
107+ )
108+
87109 db .commit ()
88110 logger .info ("Roles initialized successfully" )
89-
111+
90112 except Exception as e :
91113 logger .error (f"Error initializing roles: { e } " )
92114 db .rollback ()
@@ -99,27 +121,37 @@ def create_default_super_admin(db: Session):
99121 # Check if there's already a user with ID 1
100122 result = db .execute (text ("SELECT id, role FROM users WHERE id = 1" ))
101123 existing_user = result .fetchone ()
102-
124+
103125 if existing_user :
104126 # Update existing user to super_admin role
105- if existing_user .role != ' super_admin' :
127+ if existing_user .role != " super_admin" :
106128 db .execute (text ("UPDATE users SET role = 'super_admin' WHERE id = 1" ))
107129 logger .info ("Updated existing user (ID=1) to super_admin role" )
108130 else :
109131 logger .info ("User with ID=1 already has super_admin role" )
110132 else :
111133 # Create new super admin user
112134 from .auth import pwd_context
113- hashed_password = pwd_context .hash ("admin123" ) # Default password - should be changed
114-
115- db .execute (text ("""
135+
136+ hashed_password = pwd_context .hash (
137+ "admin123"
138+ ) # Default password - should be changed
139+
140+ db .execute (
141+ text (
142+ """
116143 INSERT INTO users (id, username, email, hashed_password, role, is_active, created_at, failed_login_attempts, mfa_enabled)
117144 VALUES (1, 'admin', 'admin@example.com', :password, 'super_admin', true, CURRENT_TIMESTAMP, 0, false)
118- """ ), {"password" : hashed_password })
119- logger .info ("Created new super admin user (username: admin, password: admin123)" )
120-
145+ """
146+ ),
147+ {"password" : hashed_password },
148+ )
149+ logger .info (
150+ "Created new super admin user (username: admin, password: admin123)"
151+ )
152+
121153 db .commit ()
122-
154+
123155 except Exception as e :
124156 logger .error (f"Error creating default super admin: { e } " )
125157 db .rollback ()
@@ -130,62 +162,79 @@ def init_default_system_credentials(db: Session):
130162 """Initialize default system SSH credentials for frictionless onboarding"""
131163 try :
132164 # Check if any system credentials already exist
133- result = db .execute (text ("""
165+ result = db .execute (
166+ text (
167+ """
134168 SELECT COUNT(*) as count FROM system_credentials WHERE is_active = true
135- """ ))
136-
169+ """
170+ )
171+ )
172+
137173 existing_count = result .fetchone ().count
138-
174+
139175 if existing_count > 0 :
140- logger .info (f"Found { existing_count } existing system credentials, skipping initialization" )
176+ logger .info (
177+ f"Found { existing_count } existing system credentials, skipping initialization"
178+ )
141179 return
142-
143- logger .info ("No system credentials found - creating placeholder credentials for easy setup" )
144-
180+
181+ logger .info (
182+ "No system credentials found - creating placeholder credentials for easy setup"
183+ )
184+
145185 # Create placeholder credentials that guide users to configure actual credentials
146186 placeholder_description = (
147187 "Default placeholder credentials - PLEASE UPDATE with your actual SSH credentials. "
148188 "This entry provides a starting point for SSH-based scanning and monitoring. "
149189 "Update the username, password, or SSH key to match your environment."
150190 )
151-
191+
152192 current_time = datetime .utcnow ()
153193
154194 # Encrypt placeholder password using new encryption service
155195 settings = get_settings ()
156196 encryption_service = create_encryption_service (master_key = settings .master_key )
157197 encrypted_bytes = encryption_service .encrypt (b"CHANGE_ME_PLEASE" )
158- encrypted_password = base64 .b64encode (encrypted_bytes ).decode (' ascii' )
198+ encrypted_password = base64 .b64encode (encrypted_bytes ).decode (" ascii" )
159199
160200 # Insert placeholder credentials (no actual sensitive data)
161- db .execute (text ("""
201+ db .execute (
202+ text (
203+ """
162204 INSERT INTO system_credentials
163205 (name, description, username, auth_method, encrypted_password,
164206 encrypted_private_key, private_key_passphrase, is_default, is_active,
165207 created_by, created_at, updated_at)
166208 VALUES (:name, :description, :username, :auth_method, :encrypted_password,
167209 :encrypted_private_key, :private_key_passphrase, :is_default, :is_active,
168210 :created_by, :created_at, :updated_at)
169- """ ), {
170- "name" : "Setup Required - Default SSH Credentials" ,
171- "description" : placeholder_description ,
172- "username" : "root" ,
173- "auth_method" : "password" ,
174- "encrypted_password" : encrypted_password , # Obvious placeholder
175- "encrypted_private_key" : None ,
176- "private_key_passphrase" : None ,
177- "is_default" : True ,
178- "is_active" : True ,
179- "created_by" : 1 , # Created by default admin user
180- "created_at" : current_time ,
181- "updated_at" : current_time
182- })
183-
211+ """
212+ ),
213+ {
214+ "name" : "Setup Required - Default SSH Credentials" ,
215+ "description" : placeholder_description ,
216+ "username" : "root" ,
217+ "auth_method" : "password" ,
218+ "encrypted_password" : encrypted_password , # Obvious placeholder
219+ "encrypted_private_key" : None ,
220+ "private_key_passphrase" : None ,
221+ "is_default" : True ,
222+ "is_active" : True ,
223+ "created_by" : 1 , # Created by default admin user
224+ "created_at" : current_time ,
225+ "updated_at" : current_time ,
226+ },
227+ )
228+
184229 db .commit ()
185-
186- logger .info ("Created placeholder system credentials - users should update these in Settings" )
187- logger .warning ("SECURITY NOTICE: Default SSH credentials created with placeholder password. Users must update these credentials in Settings before performing SSH operations." )
188-
230+
231+ logger .info (
232+ "Created placeholder system credentials - users should update these in Settings"
233+ )
234+ logger .warning (
235+ "SECURITY NOTICE: Default SSH credentials created with placeholder password. Users must update these credentials in Settings before performing SSH operations."
236+ )
237+
189238 except Exception as e :
190239 logger .error (f"Error creating default system credentials: { e } " )
191240 db .rollback ()
@@ -197,7 +246,7 @@ async def initialize_rbac_system():
197246 try :
198247 # Ensure tables exist
199248 create_tables ()
200-
249+
201250 # Initialize roles and system components
202251 db = SessionLocal ()
203252 try :
@@ -207,12 +256,12 @@ async def initialize_rbac_system():
207256 logger .info ("RBAC system and default credentials initialized successfully" )
208257 finally :
209258 db .close ()
210-
259+
211260 except Exception as e :
212261 logger .error (f"Failed to initialize RBAC system: { e } " )
213262 raise
214263
215264
216265if __name__ == "__main__" :
217266 # Run initialization
218- asyncio .run (initialize_rbac_system ())
267+ asyncio .run (initialize_rbac_system ())
0 commit comments