feat(jira): pause/hold status mapping, RT/BT dates, TTP, attack_success 3-value field, hours

This commit is contained in:
kitos
2026-07-06 16:19:39 +02:00
parent 19c4866103
commit 022c1c756a
13 changed files with 433 additions and 22 deletions
+1 -1
View File
@@ -105,7 +105,7 @@ def get_tests_analytics(
# Literal argument value
"tool_used": t.tool_used,
# Literal argument value
"attack_success": t.attack_success,
"attack_success": t.attack_success.value if t.attack_success else None,
# Literal argument value
"remediation_status": t.remediation_status,
}
@@ -35,7 +35,7 @@ from typing import Any
import requests
from sqlalchemy.orm import Session
from app.models.enums import TestState, TestResult
from app.models.enums import AttackSuccessResult, TestState, TestResult
from app.models.evaluation_import import EvaluationImport
from app.models.technique import Technique
from app.models.test import Test
@@ -625,7 +625,7 @@ def import_evaluation_round(
procedure_text=procedure_text,
created_by=current_user.id,
state=TestState.in_review,
attack_success=True,
attack_success=AttackSuccessResult.successful,
red_summary=red_summary,
red_validation_status="approved",
red_validated_by=current_user.id,
@@ -305,7 +305,10 @@ def build_test_results_report(
# Literal argument value
"platform": t.platform,
# Literal argument value
"attack_success": t.attack_success,
"attack_success": (
t.attack_success.value if t.attack_success and hasattr(t.attack_success, "value")
else str(t.attack_success) if t.attack_success else None
),
# Literal argument value
"detection_result": (
t.detection_result.value if t.detection_result and hasattr(t.detection_result, "value")
+179 -8
View File
@@ -65,6 +65,33 @@ from app.models.technique import Technique
from app.models.test import Test
from app.models.user import User
# ---------------------------------------------------------------------------
# Custom field IDs (project-specific — see System Settings → Jira Configuration)
# ---------------------------------------------------------------------------
JIRA_FIELD_RT_START_DATE = "customfield_11803"
JIRA_FIELD_RT_END_DATE = "customfield_11804"
JIRA_FIELD_BT_START_DATE = "customfield_11805"
JIRA_FIELD_BT_END_DATE = "customfield_11806"
JIRA_FIELD_TTP = "customfield_11807"
JIRA_FIELD_SEVERITY = "customfield_10098"
JIRA_FIELD_ATTACK_SUCCESS = "customfield_11815"
JIRA_FIELD_ATTACK_DETECTED = "customfield_11809"
JIRA_FIELD_TIME_TO_DETECT = "customfield_11810"
JIRA_FIELD_TIME_TO_CONTAIN = "customfield_11811"
_ATTACK_SUCCESS_TO_JIRA = {
"successful": "Yes",
"not_successful": "No",
"partially_successful": "Partial",
}
_DETECTION_TO_JIRA = {
"detected": "Yes",
"not_detected": "No",
"partially_detected": "Partial",
}
# Assign logger = logging.getLogger(__name__)
logger = logging.getLogger(__name__)
@@ -388,7 +415,7 @@ def _build_state_comment(
lines += [
"Red Team has finished execution and submitted evidence for Blue Team evaluation.",
"",
f"*Attack Success:* {test.attack_success if test.attack_success is not None else 'N/A'}",
f"*Attack Success:* {_enum_value(test.attack_success) or 'N/A'}",
]
if test.red_summary:
lines += ["", "h4. Red Team Summary", test.red_summary]
@@ -627,6 +654,7 @@ def auto_create_test_issue(
issue_type = settings.JIRA_ISSUE_TYPE_TEST # always Task
poc = test.procedure_text or "N/A"
severity = _technique_severity(technique).capitalize()
fields: dict = {
"project": {"key": project_key},
"summary": f"[Aegis] {mitre_id}{test.name}",
@@ -635,6 +663,8 @@ def auto_create_test_issue(
"labels": ["aegis", "security-test", mitre_id.replace(".", "-")],
# customfield_10309 = Proof of Concept field (required by team's Jira config)
"customfield_10309": f"{{code}}{poc}{{code}}",
JIRA_FIELD_TTP: mitre_id,
JIRA_FIELD_SEVERITY: severity,
}
# Inherit campaign start date if available, otherwise use today
@@ -803,20 +833,67 @@ def push_hold_event(
f"h3. ▶ Test Resumed\n\n"
f"*Resumed by:* {actor.username}\n"
f"*At:* {ts}\n\n"
f"_The test has been taken off hold and is active again._"
f"_The test has been unblocked and is active again._"
)
try:
jira.set_issue_status(link.jira_issue_key, "In Progress")
except Exception as exc_t:
logger.warning("Could not transition %s off hold: %s", link.jira_issue_key, exc_t)
logger.warning("Could not transition %s off blocked: %s", link.jira_issue_key, exc_t)
else:
comment = (
f"h3. Test Placed On Hold\n\n"
f"*Placed on hold by:* {actor.username}\n"
f"h3. 🚫 Test Blocked\n\n"
f"*Blocked by:* {actor.username}\n"
f"*At:* {ts}\n"
f"*Reason:* {reason or 'No reason provided'}\n\n"
f"_This test has been paused. No action required until it is resumed._"
f"_This test is blocked. No action required until it is resumed._"
)
try:
jira.set_issue_status(link.jira_issue_key, "Blocked")
except Exception as exc_t:
logger.warning("Could not transition %s to Blocked: %s", link.jira_issue_key, exc_t)
jira.issue_add_comment(link.jira_issue_key, comment)
link.last_synced_at = datetime.utcnow()
db.flush()
logger.info("Posted hold event to Jira %s (resuming=%s)", link.jira_issue_key, resuming)
except Exception as exc:
logger.warning("Failed to push hold event for test %s: %s", test.id, exc, exc_info=True)
def push_pause_event(db: Session, test, actor, *, resuming: bool = False) -> None:
"""Post a timer pause/resume comment to Jira and toggle 'On Hold' / 'In Progress'.
Distinct from :func:`push_hold_event` — a short timer pause (the
operator stepping away briefly) maps to "On Hold", while an explicit
hold (something external blocking progress) maps to "Blocked".
Non-fatal — any Jira error is logged and swallowed.
"""
if not has_admin_jira_configured(db):
return
link = (
db.query(JiraLink)
.filter(
JiraLink.entity_type == JiraLinkEntityType.test,
JiraLink.entity_id == test.id,
)
.first()
)
if not link:
return
try:
jira = get_admin_jira_client(db)
ts = datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")
if resuming:
comment = f"h3. ▶ Timer Resumed\n\n*Resumed by:* {actor.username}\n*At:* {ts}"
try:
jira.set_issue_status(link.jira_issue_key, "In Progress")
except Exception as exc_t:
logger.warning("Could not transition %s off On Hold: %s", link.jira_issue_key, exc_t)
else:
comment = f"h3. ⏸ Timer Paused\n\n*Paused by:* {actor.username}\n*At:* {ts}"
try:
jira.set_issue_status(link.jira_issue_key, "On Hold")
except Exception as exc_t:
@@ -825,9 +902,103 @@ def push_hold_event(
jira.issue_add_comment(link.jira_issue_key, comment)
link.last_synced_at = datetime.utcnow()
db.flush()
logger.info("Posted hold event to Jira %s (resuming=%s)", link.jira_issue_key, resuming)
logger.info("Posted pause event to Jira %s (resuming=%s)", link.jira_issue_key, resuming)
except Exception as exc:
logger.warning("Failed to push hold event for test %s: %s", test.id, exc, exc_info=True)
logger.warning("Failed to push pause event for test %s: %s", test.id, exc, exc_info=True)
# ---------------------------------------------------------------------------
# RT/BT date + result custom-field sync
# ---------------------------------------------------------------------------
def _enum_value(v) -> Optional[str]:
"""Return the plain string value of an enum member, or the value itself."""
if v is None:
return None
return v.value if hasattr(v, "value") else str(v)
def _compute_hours(start: Optional[datetime], end: Optional[datetime]) -> Optional[float]:
"""Return the elapsed time between two timestamps in hours, or None if unavailable."""
if not start or not end:
return None
delta_hours = (end - start).total_seconds() / 3600
return round(delta_hours, 2) if delta_hours >= 0 else None
def _update_test_fields(db: Session, test: Test, fields: dict) -> None:
"""Best-effort update of custom fields on the Jira issue linked to *test*.
Non-fatal — any Jira error is logged and swallowed so it never blocks
the test workflow.
"""
if not fields or not has_admin_jira_configured(db):
return
link = (
db.query(JiraLink)
.filter(
JiraLink.entity_type == JiraLinkEntityType.test,
JiraLink.entity_id == test.id,
)
.first()
)
if not link:
return
try:
jira = get_admin_jira_client(db)
jira.update_issue_field(link.jira_issue_key, fields=fields)
link.last_synced_at = datetime.utcnow()
db.flush()
logger.info("Updated Jira fields %s on %s", list(fields.keys()), link.jira_issue_key)
except Exception as exc:
logger.warning(
"Failed to update Jira fields for test %s: %s", test.id, exc, exc_info=True
)
def push_rt_started(db: Session, test: Test) -> None:
"""Set the RT Start Date field — called when the operator hits Start Execution."""
_update_test_fields(db, test, {
JIRA_FIELD_RT_START_DATE: datetime.utcnow().strftime("%Y-%m-%d"),
})
def push_rt_submitted(db: Session, test: Test) -> None:
"""Set the RT End Date + Attack Success fields — called when Red submits for review."""
fields: dict = {JIRA_FIELD_RT_END_DATE: datetime.utcnow().strftime("%Y-%m-%d")}
attack_success = _enum_value(test.attack_success)
if attack_success in _ATTACK_SUCCESS_TO_JIRA:
fields[JIRA_FIELD_ATTACK_SUCCESS] = _ATTACK_SUCCESS_TO_JIRA[attack_success]
_update_test_fields(db, test, fields)
def push_bt_started(db: Session, test: Test) -> None:
"""Set the BT Start Date field — called when Blue picks up the test to evaluate."""
_update_test_fields(db, test, {
JIRA_FIELD_BT_START_DATE: datetime.utcnow().strftime("%Y-%m-%d"),
})
def push_bt_submitted(db: Session, test: Test) -> None:
"""Set BT End Date, Attack Detected, and time-to-detect/contain — Blue submits for review."""
fields: dict = {JIRA_FIELD_BT_END_DATE: datetime.utcnow().strftime("%Y-%m-%d")}
detection_result = _enum_value(test.detection_result)
if detection_result in _DETECTION_TO_JIRA:
fields[JIRA_FIELD_ATTACK_DETECTED] = _DETECTION_TO_JIRA[detection_result]
time_to_detect = _compute_hours(test.execution_end_time, test.detection_time)
if time_to_detect is not None:
fields[JIRA_FIELD_TIME_TO_DETECT] = time_to_detect
time_to_contain = _compute_hours(test.detection_time, test.containment_time)
if time_to_contain is not None:
fields[JIRA_FIELD_TIME_TO_CONTAIN] = time_to_contain
_update_test_fields(db, test, fields)
# ---------------------------------------------------------------------------
@@ -223,6 +223,12 @@ def start_execution(db: Session, test: Test, user: User) -> Test:
except Exception as e:
logger.warning("Jira push failed for test %s: %s", test.id, e, exc_info=True)
try:
from app.services.jira_service import push_rt_started
push_rt_started(db, test)
except Exception as e:
logger.warning("Jira RT start date push failed for test %s: %s", test.id, e, exc_info=True)
return test
@@ -314,6 +320,12 @@ def submit_red_evidence(db: Session, test: Test, user: User) -> Test:
except Exception as e:
logger.warning("Jira push failed for test %s: %s", test.id, e, exc_info=True)
try:
from app.services.jira_service import push_rt_submitted
push_rt_submitted(db, test)
except Exception as e:
logger.warning("Jira RT end date push failed for test %s: %s", test.id, e, exc_info=True)
return test
@@ -410,6 +422,12 @@ def start_blue_work(db: Session, test: Test, user: User) -> Test:
except Exception as e:
logger.warning("Notification failed for test %s: %s", test.id, e, exc_info=True)
try:
from app.services.jira_service import push_bt_started
push_bt_started(db, test)
except Exception as e:
logger.warning("Jira BT start date push failed for test %s: %s", test.id, e, exc_info=True)
return test
@@ -494,6 +512,12 @@ def submit_blue_evidence(db: Session, test: Test, user: User) -> Test:
except Exception as e:
logger.warning("Jira push failed for test %s: %s", test.id, e, exc_info=True)
try:
from app.services.jira_service import push_bt_submitted
push_bt_submitted(db, test)
except Exception as e:
logger.warning("Jira BT end date push failed for test %s: %s", test.id, e, exc_info=True)
return test
@@ -637,6 +661,13 @@ def pause_timer(db: Session, test: Test, user: User) -> Test:
# Keyword argument: details
details={"state": test.state.value},
)
try:
from app.services.jira_service import push_pause_event
push_pause_event(db, test, user, resuming=False)
except Exception as e:
logger.warning("Jira pause push failed for test %s: %s", test.id, e, exc_info=True)
# Return test
return test
@@ -692,6 +723,13 @@ def resume_timer(db: Session, test: Test, user: User) -> Test:
# Keyword argument: details
details={"paused_seconds": paused_seconds, "state": test.state.value},
)
try:
from app.services.jira_service import push_pause_event
push_pause_event(db, test, user, resuming=True)
except Exception as e:
logger.warning("Jira resume push failed for test %s: %s", test.id, e, exc_info=True)
# Return test
return test