Skip to content

Commit fbe478d

Browse files
remyluslosiusclaude
andcommitted
style(backend): Format Python code with Black 24.10.0 [skip-format]
Applied Black formatting to 7 Python files to match CI expectations: - health_monitoring.py - Import and alignment formatting - init_roles.py - Import formatting - authorization_middleware.py - Import and f-string formatting - monitoring.py - Import formatting - credentials.py - Import formatting - compliance_justification_engine.py - Import and enum formatting - system_settings.py - Import formatting This resolves the CI Black formatting failures by using Black 24.10.0 (matching CI version) in a fresh Docker container. Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 46bb65c commit fbe478d

7 files changed

Lines changed: 1896 additions & 915 deletions

File tree

backend/app/api/v1/endpoints/health_monitoring.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,9 @@ async def get_service_health(
4747
health_data = await health_service.get_latest_service_health()
4848

4949
# If no data or data is older than 5 minutes, collect fresh
50-
if not health_data or (datetime.utcnow() - health_data.health_check_timestamp) > timedelta(
51-
minutes=5
52-
):
50+
if not health_data or (
51+
datetime.utcnow() - health_data.health_check_timestamp
52+
) > timedelta(minutes=5):
5353
health_data = await health_service.collect_service_health()
5454
await health_service.save_service_health(health_data)
5555

@@ -84,9 +84,9 @@ async def get_content_health(
8484
health_data = await health_service.get_latest_content_health()
8585

8686
# If no data or data is older than 1 hour, collect fresh
87-
if not health_data or (datetime.utcnow() - health_data.health_check_timestamp) > timedelta(
88-
hours=1
89-
):
87+
if not health_data or (
88+
datetime.utcnow() - health_data.health_check_timestamp
89+
) > timedelta(hours=1):
9090
health_data = await health_service.collect_content_health()
9191
await health_service.save_content_health(health_data)
9292

backend/app/init_roles.py

100644100755
Lines changed: 124 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
Initialize roles and permissions in the database
33
"""
4+
45
import asyncio
56
import base64
67
from sqlalchemy.orm import Session
@@ -18,75 +19,96 @@
1819

1920
def 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

216265
if __name__ == "__main__":
217266
# Run initialization
218-
asyncio.run(initialize_rbac_system())
267+
asyncio.run(initialize_rbac_system())

0 commit comments

Comments
 (0)