feat(refactor): PEP8, type annotations, docstrings and PyJWT security fix
This commit is contained in:
@@ -28,22 +28,44 @@ creates the Jira ticket and stores the link.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# Import logging
|
||||
import logging
|
||||
|
||||
# Import datetime from datetime
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
# Import Any, Optional from typing
|
||||
from typing import Any, Optional
|
||||
|
||||
# Import UUID from uuid
|
||||
from uuid import UUID
|
||||
|
||||
# Import Session from sqlalchemy.orm
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# Import settings from app.config
|
||||
from app.config import settings
|
||||
|
||||
# Import EntityNotFoundError from app.domain.errors
|
||||
from app.domain.errors import EntityNotFoundError
|
||||
|
||||
# Import InvalidOperationError from app.domain.exceptions
|
||||
from app.domain.exceptions import InvalidOperationError
|
||||
|
||||
# Import Campaign from app.models.campaign
|
||||
from app.models.campaign import Campaign
|
||||
|
||||
# Import JiraLink, JiraLinkEntityType, JiraSyncDirection from app.models.jira_link
|
||||
from app.models.jira_link import JiraLink, JiraLinkEntityType, JiraSyncDirection
|
||||
|
||||
# Import Technique from app.models.technique
|
||||
from app.models.technique import Technique
|
||||
|
||||
# Import Test from app.models.test
|
||||
from app.models.test import Test
|
||||
from app.models.user import User
|
||||
|
||||
# Assign logger = logging.getLogger(__name__)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -624,6 +646,7 @@ def get_jira_client():
|
||||
Prefer ``get_user_jira_client()`` for new code.
|
||||
"""
|
||||
if not settings.JIRA_ENABLED:
|
||||
# Raise InvalidOperationError
|
||||
raise InvalidOperationError("Jira integration is not enabled")
|
||||
if not settings.JIRA_URL or not settings.JIRA_USERNAME or not settings.JIRA_API_TOKEN:
|
||||
raise InvalidOperationError(
|
||||
@@ -639,75 +662,121 @@ def get_jira_client():
|
||||
)
|
||||
|
||||
|
||||
# Define function search_jira_issues
|
||||
def search_jira_issues(query: str, max_results: int = 10) -> list[dict]:
|
||||
"""Search Jira issues by JQL or free text (uses global credentials)."""
|
||||
jira = get_jira_client()
|
||||
# Assign jql = query if "=" in query or "~" in query else f'summary ~ "{query}"'
|
||||
jql = query if "=" in query or "~" in query else f'summary ~ "{query}"'
|
||||
# Assign results = jira.jql(jql, limit=max_results)
|
||||
results = jira.jql(jql, limit=max_results)
|
||||
# Return [
|
||||
return [
|
||||
{
|
||||
# Literal argument value
|
||||
"issue_key": issue["key"],
|
||||
# Literal argument value
|
||||
"summary": issue["fields"]["summary"],
|
||||
# Literal argument value
|
||||
"status": issue["fields"]["status"]["name"],
|
||||
# Literal argument value
|
||||
"assignee": (issue["fields"].get("assignee") or {}).get("displayName"),
|
||||
# Literal argument value
|
||||
"priority": (issue["fields"].get("priority") or {}).get("name"),
|
||||
}
|
||||
for issue in results.get("issues", [])
|
||||
]
|
||||
|
||||
|
||||
# Define function create_jira_issue
|
||||
def create_jira_issue(
|
||||
# Entry: project_key
|
||||
project_key: str,
|
||||
# Entry: summary
|
||||
summary: str,
|
||||
# Entry: description
|
||||
description: str,
|
||||
# Entry: issue_type
|
||||
issue_type: str = "Task",
|
||||
# Entry: labels
|
||||
labels: Optional[list[str]] = None,
|
||||
# Entry: custom_fields
|
||||
custom_fields: Optional[dict] = None,
|
||||
) -> dict:
|
||||
"""Create a Jira issue and return its key + id (uses global credentials)."""
|
||||
jira = get_jira_client()
|
||||
# Assign fields = {
|
||||
fields: dict = {
|
||||
# Literal argument value
|
||||
"project": {"key": project_key},
|
||||
# Literal argument value
|
||||
"summary": summary,
|
||||
# Literal argument value
|
||||
"description": description,
|
||||
# Literal argument value
|
||||
"issuetype": {"name": issue_type},
|
||||
}
|
||||
# Check: labels
|
||||
if labels:
|
||||
# Assign fields["labels"] = labels
|
||||
fields["labels"] = labels
|
||||
# Check: custom_fields
|
||||
if custom_fields:
|
||||
# Call fields.update()
|
||||
fields.update(custom_fields)
|
||||
|
||||
# Assign result = jira.issue_create(fields=fields)
|
||||
result = jira.issue_create(fields=fields)
|
||||
# Return {"issue_key": result["key"], "issue_id": result["id"]}
|
||||
return {"issue_key": result["key"], "issue_id": result["id"]}
|
||||
|
||||
|
||||
# Define function sync_jira_to_aegis
|
||||
def sync_jira_to_aegis(db: Session, link: JiraLink) -> None:
|
||||
"""Pull current status from Jira into the local link record (global creds)."""
|
||||
jira = get_jira_client()
|
||||
# Assign issue = jira.issue(link.jira_issue_key)
|
||||
issue = jira.issue(link.jira_issue_key)
|
||||
# Assign fields = issue.get("fields", {})
|
||||
fields = issue.get("fields", {})
|
||||
# Assign link.jira_status = fields.get("status", {}).get("name")
|
||||
link.jira_status = fields.get("status", {}).get("name")
|
||||
# Assign link.jira_priority = (fields.get("priority") or {}).get("name")
|
||||
link.jira_priority = (fields.get("priority") or {}).get("name")
|
||||
# Assign link.jira_assignee = (fields.get("assignee") or {}).get("displayName")
|
||||
link.jira_assignee = (fields.get("assignee") or {}).get("displayName")
|
||||
# Assign link.jira_story_points = str(fields.get("customfield_10016", ""))
|
||||
link.jira_story_points = str(fields.get("customfield_10016", ""))
|
||||
# Assign link.last_synced_at = datetime.utcnow()
|
||||
link.last_synced_at = datetime.utcnow()
|
||||
# Flush changes to DB without committing the transaction
|
||||
db.flush()
|
||||
|
||||
|
||||
# Define function sync_aegis_to_jira
|
||||
def sync_aegis_to_jira(db: Session, link: JiraLink, entity_data: dict) -> None:
|
||||
"""Push an Aegis status update as a Jira comment (global creds)."""
|
||||
jira = get_jira_client()
|
||||
# Assign comment_body = _build_sync_comment(entity_data)
|
||||
comment_body = _build_sync_comment(entity_data)
|
||||
# Call jira.issue_add_comment()
|
||||
jira.issue_add_comment(link.jira_issue_key, comment_body)
|
||||
# Assign link.last_synced_at = datetime.utcnow()
|
||||
link.last_synced_at = datetime.utcnow()
|
||||
# Flush changes to DB without committing the transaction
|
||||
db.flush()
|
||||
|
||||
|
||||
# Define function _build_sync_comment
|
||||
def _build_sync_comment(data: dict) -> str:
|
||||
lines = ["h3. Aegis Sync Update", ""]
|
||||
# Iterate over data.items()
|
||||
for key, value in data.items():
|
||||
# Call lines.append()
|
||||
lines.append(f"*{key}:* {value}")
|
||||
# Call lines.append()
|
||||
lines.append(f"\n_Synced at {datetime.utcnow().isoformat()}_")
|
||||
# Return "\n".join(lines)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
@@ -715,60 +784,94 @@ def _build_sync_comment(data: dict) -> str:
|
||||
|
||||
|
||||
def create_link(
|
||||
# Entry: db
|
||||
db: Session,
|
||||
*,
|
||||
# Entry: entity_type
|
||||
entity_type: JiraLinkEntityType,
|
||||
# Entry: entity_id
|
||||
entity_id: UUID,
|
||||
# Entry: jira_issue_key
|
||||
jira_issue_key: str,
|
||||
# Entry: sync_direction
|
||||
sync_direction: JiraSyncDirection,
|
||||
# Entry: created_by
|
||||
created_by: UUID,
|
||||
) -> JiraLink:
|
||||
link = JiraLink(
|
||||
# Keyword argument: entity_type
|
||||
entity_type=entity_type,
|
||||
# Keyword argument: entity_id
|
||||
entity_id=entity_id,
|
||||
# Keyword argument: jira_issue_key
|
||||
jira_issue_key=jira_issue_key,
|
||||
# Keyword argument: sync_direction
|
||||
sync_direction=sync_direction,
|
||||
# Keyword argument: created_by
|
||||
created_by=created_by,
|
||||
)
|
||||
# Stage new record(s) for database insertion
|
||||
db.add(link)
|
||||
# Flush changes to DB without committing the transaction
|
||||
db.flush()
|
||||
|
||||
# Check: settings.JIRA_ENABLED
|
||||
if settings.JIRA_ENABLED:
|
||||
# Attempt the following; catch errors below
|
||||
try:
|
||||
# Call sync_jira_to_aegis()
|
||||
sync_jira_to_aegis(db, link)
|
||||
# Handle Exception
|
||||
except Exception as e:
|
||||
# Log warning: "Initial Jira sync failed for %s: %s", jira_issue_
|
||||
logger.warning("Initial Jira sync failed for %s: %s", jira_issue_key, e)
|
||||
|
||||
# Return link
|
||||
return link
|
||||
|
||||
|
||||
# Define function list_links
|
||||
def list_links(
|
||||
# Entry: db
|
||||
db: Session,
|
||||
*,
|
||||
# Entry: entity_type
|
||||
entity_type: Optional[JiraLinkEntityType] = None,
|
||||
# Entry: entity_id
|
||||
entity_id: Optional[UUID] = None,
|
||||
entity_ids: Optional[list[UUID]] = None,
|
||||
) -> list[JiraLink]:
|
||||
query = db.query(JiraLink)
|
||||
# Check: entity_type
|
||||
if entity_type:
|
||||
# Assign query = query.filter(JiraLink.entity_type == entity_type)
|
||||
query = query.filter(JiraLink.entity_type == entity_type)
|
||||
# Check: entity_id
|
||||
if entity_id:
|
||||
# Assign query = query.filter(JiraLink.entity_id == entity_id)
|
||||
query = query.filter(JiraLink.entity_id == entity_id)
|
||||
elif entity_ids:
|
||||
query = query.filter(JiraLink.entity_id.in_(entity_ids))
|
||||
return query.order_by(JiraLink.created_at.desc()).all()
|
||||
|
||||
|
||||
# Define function get_link_or_raise
|
||||
def get_link_or_raise(db: Session, link_id: UUID) -> JiraLink:
|
||||
link = db.query(JiraLink).filter(JiraLink.id == link_id).first()
|
||||
# Check: not link
|
||||
if not link:
|
||||
# Raise EntityNotFoundError
|
||||
raise EntityNotFoundError("JiraLink", str(link_id))
|
||||
# Return link
|
||||
return link
|
||||
|
||||
|
||||
# Define function delete_link
|
||||
def delete_link(db: Session, link_id: UUID) -> JiraLink:
|
||||
link = get_link_or_raise(db, link_id)
|
||||
# Mark record for deletion on next commit
|
||||
db.delete(link)
|
||||
# Return link
|
||||
return link
|
||||
|
||||
|
||||
@@ -776,43 +879,64 @@ def build_issue_data(
|
||||
db: Session, entity_type: JiraLinkEntityType, entity_id: UUID
|
||||
) -> tuple[str, str]:
|
||||
"""Build Jira issue summary and description from an Aegis entity."""
|
||||
# Check: entity_type == JiraLinkEntityType.test
|
||||
if entity_type == JiraLinkEntityType.test:
|
||||
# Assign entity = db.query(Test).filter(Test.id == entity_id).first()
|
||||
entity = db.query(Test).filter(Test.id == entity_id).first()
|
||||
# Check: not entity
|
||||
if not entity:
|
||||
# Raise EntityNotFoundError
|
||||
raise EntityNotFoundError("Test", str(entity_id))
|
||||
technique = db.query(Technique).filter(Technique.id == entity.technique_id).first()
|
||||
return (
|
||||
f"[Aegis] {technique.mitre_id if technique else 'N/A'} — {entity.name}",
|
||||
_build_test_description(entity, technique),
|
||||
)
|
||||
# Alternative: entity_type == JiraLinkEntityType.campaign
|
||||
elif entity_type == JiraLinkEntityType.campaign:
|
||||
# Assign entity = db.query(Campaign).filter(Campaign.id == entity_id).first()
|
||||
entity = db.query(Campaign).filter(Campaign.id == entity_id).first()
|
||||
# Check: not entity
|
||||
if not entity:
|
||||
# Raise EntityNotFoundError
|
||||
raise EntityNotFoundError("Campaign", str(entity_id))
|
||||
# Return (
|
||||
return (
|
||||
f"[Aegis Campaign] {entity.name}",
|
||||
f"Campaign: {entity.name}\nType: {entity.type}\nStatus: {entity.status}\n"
|
||||
f"Description: {entity.description or 'N/A'}",
|
||||
)
|
||||
# Alternative: entity_type == JiraLinkEntityType.technique
|
||||
elif entity_type == JiraLinkEntityType.technique:
|
||||
# Assign entity = db.query(Technique).filter(Technique.id == entity_id).first()
|
||||
entity = db.query(Technique).filter(Technique.id == entity_id).first()
|
||||
# Check: not entity
|
||||
if not entity:
|
||||
# Raise EntityNotFoundError
|
||||
raise EntityNotFoundError("Technique", str(entity_id))
|
||||
# Return (
|
||||
return (
|
||||
f"[Aegis Technique] {entity.mitre_id} - {entity.name}",
|
||||
f"MITRE ID: {entity.mitre_id}\nName: {entity.name}\n"
|
||||
f"Tactic: {entity.tactic or 'N/A'}\n"
|
||||
f"Description: {entity.description or 'N/A'}",
|
||||
)
|
||||
# Fallback: handle remaining cases
|
||||
else:
|
||||
# Return f"[Aegis] Entity {entity_id}", f"Entity type: {entity_type.value}"
|
||||
return f"[Aegis] Entity {entity_id}", f"Entity type: {entity_type.value}"
|
||||
|
||||
|
||||
# Define function create_issue_and_link
|
||||
def create_issue_and_link(
|
||||
# Entry: db
|
||||
db: Session,
|
||||
*,
|
||||
# Entry: entity_type
|
||||
entity_type: JiraLinkEntityType,
|
||||
# Entry: entity_id
|
||||
entity_id: UUID,
|
||||
# Entry: created_by
|
||||
created_by: UUID,
|
||||
) -> dict:
|
||||
"""Create a Jira issue from an Aegis entity and link them (global creds)."""
|
||||
@@ -821,16 +945,25 @@ def create_issue_and_link(
|
||||
result = create_jira_issue(
|
||||
project_key=project_key,
|
||||
summary=summary,
|
||||
# Keyword argument: description
|
||||
description=description,
|
||||
# Keyword argument: labels
|
||||
labels=["aegis", entity_type.value],
|
||||
)
|
||||
# Assign link = JiraLink(
|
||||
link = JiraLink(
|
||||
# Keyword argument: entity_type
|
||||
entity_type=entity_type,
|
||||
# Keyword argument: entity_id
|
||||
entity_id=entity_id,
|
||||
# Keyword argument: jira_issue_key
|
||||
jira_issue_key=result["issue_key"],
|
||||
# Keyword argument: jira_issue_id
|
||||
jira_issue_id=result["issue_id"],
|
||||
jira_project_key=project_key,
|
||||
created_by=created_by,
|
||||
)
|
||||
# Stage new record(s) for database insertion
|
||||
db.add(link)
|
||||
# Return {"issue_key": result["issue_key"], "link_id": str(link.id)}
|
||||
return {"issue_key": result["issue_key"], "link_id": str(link.id)}
|
||||
|
||||
Reference in New Issue
Block a user