feat(jira): per-user auth, lifecycle hooks, admin config endpoints
Some checks failed
Aegis CI / lint-and-test (push) Has been cancelled

- Add jira_api_token field to User model + migration b042
- Per-user Jira client: user's corporate email + personal Atlassian token
- Admin-configurable Jira URL/project via system_configs (GET/PATCH /system/jira-config + POST /system/jira-test)
- Auto-create Jira ticket when a test is created (non-fatal)
- Push lifecycle comments on every state transition: draft→red_executing→blue_evaluating→in_review→validated/rejected→draft
- Rich ticket descriptions with technique, MITRE ID, priority from severity, labels
- UserOut.jira_token_set (bool) instead of exposing raw token
- PATCH /users/me/preferences now accepts jira_api_token

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
kitos
2026-05-26 15:56:28 +02:00
parent 8bed3abc08
commit c780ad1e78
8 changed files with 631 additions and 46 deletions

View File

@@ -0,0 +1,25 @@
"""Add jira_api_token to users table.
Revision ID: b042
Revises: b041_operational_alerts
Create Date: 2026-05-26
"""
from alembic import op
import sqlalchemy as sa
revision = "b042"
down_revision = "b041_operational_alerts"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column(
"users",
sa.Column("jira_api_token", sa.String(500), nullable=True),
)
def downgrade() -> None:
op.drop_column("users", "jira_api_token")

View File

@@ -30,3 +30,4 @@ class User(Base):
last_login = Column(DateTime, nullable=True)
notification_preferences = Column(JSONB, nullable=True, server_default='{"email_on_test_validated": true, "email_on_campaign_completed": true, "email_on_new_mitre_techniques": false, "in_app_all": true}')
jira_account_id = Column(String(100), nullable=True)
jira_api_token = Column(String(500), nullable=True) # personal Atlassian token

View File

@@ -201,6 +201,109 @@ def scheduler_status(
}
# ---------------------------------------------------------------------------
# Jira config endpoints (admin only)
# ---------------------------------------------------------------------------
class JiraConfigOut(BaseModel):
enabled: bool
url: str
project_key: str
# Credentials are never returned
class JiraConfigUpdate(BaseModel):
enabled: Optional[bool] = None
url: Optional[str] = None
project_key: Optional[str] = None
_JIRA_KEYS = {
"enabled": "jira.enabled",
"url": "jira.url",
"project_key": "jira.project_key",
}
@router.get("/jira-config", response_model=JiraConfigOut)
def get_jira_config(
db: Session = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""Return current Jira configuration (merged DB + env).
**Requires** the ``admin`` role. Credentials are never returned.
"""
from app.services.jira_service import get_jira_url, get_jira_project_key, is_jira_enabled
return JiraConfigOut(
enabled=is_jira_enabled(db),
url=get_jira_url(db) or "",
project_key=get_jira_project_key(db) or "",
)
@router.patch("/jira-config", response_model=JiraConfigOut)
def update_jira_config(
payload: JiraConfigUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""Update Jira configuration and persist to DB.
**Requires** the ``admin`` role. Only provided fields are updated.
"""
from app.services.jira_service import (
upsert_jira_config, get_jira_url, get_jira_project_key, is_jira_enabled,
)
update_data = payload.model_dump(exclude_unset=True)
for field, val in update_data.items():
db_key = _JIRA_KEYS.get(field)
if db_key:
upsert_jira_config(db, db_key, str(val))
db.commit()
return JiraConfigOut(
enabled=is_jira_enabled(db),
url=get_jira_url(db) or "",
project_key=get_jira_project_key(db) or "",
)
@router.post("/jira-test")
def test_jira_connection(
db: Session = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""Test the Jira connection using the current user's credentials.
Requires the admin to have a personal Jira API token configured in their
profile settings.
"""
from app.services.jira_service import get_user_jira_client, get_jira_url
jira_url = get_jira_url(db)
if not jira_url:
raise HTTPException(status_code=400, detail="Jira URL not configured.")
try:
jira = get_user_jira_client(current_user, db)
# Lightweight call: get current user info
myself = jira.myself()
return {
"status": "ok",
"connected_as": myself.get("displayName") or myself.get("emailAddress", "unknown"),
"jira_url": jira_url,
}
except Exception as exc:
raise HTTPException(
status_code=502,
detail=f"Jira connection failed: {exc}",
)
# ---------------------------------------------------------------------------
# GET /system/email-config
# ---------------------------------------------------------------------------

View File

@@ -145,6 +145,14 @@ def create_test(
uow.commit()
db.refresh(test)
# Auto-create Jira ticket (non-fatal — any failure is logged, not raised)
try:
from app.services.jira_service import auto_create_test_issue
auto_create_test_issue(db, test, current_user)
db.commit()
except Exception:
pass # jira_service already logs warnings internally
return test
@@ -191,6 +199,14 @@ def create_test_from_template(
uow.commit()
db.refresh(test)
# Auto-create Jira ticket (non-fatal)
try:
from app.services.jira_service import auto_create_test_issue
auto_create_test_issue(db, test, current_user)
db.commit()
except Exception:
pass
return test

View File

@@ -33,10 +33,18 @@ def update_my_preferences(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Update the current user's notification preferences and Jira account ID."""
"""Update the current user's notification preferences, Jira account ID and Jira API token.
Send ``jira_api_token: ""`` to clear a previously stored token.
The token is never returned in any response.
"""
update_data = payload.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(current_user, field, value)
if field == "jira_api_token":
# Empty string means "clear token"
setattr(current_user, field, value if value else None)
else:
setattr(current_user, field, value)
db.commit()
db.refresh(current_user)
return current_user

View File

@@ -122,10 +122,13 @@ class PasswordChange(BaseModel):
class UserPreferencesUpdate(BaseModel):
"""Payload for updating current user's notification preferences and Jira account."""
"""Payload for updating current user's notification preferences and Jira settings."""
notification_preferences: dict | None = None
jira_account_id: str | None = None
# Personal Jira API token (Atlassian token) — write-only, stored encrypted at rest.
# Set to empty string "" to clear the token.
jira_api_token: str | None = None
class UserOut(BaseModel):
@@ -141,5 +144,15 @@ class UserOut(BaseModel):
last_login: datetime | None = None
notification_preferences: dict | None = None
jira_account_id: str | None = None
# Never return the raw token — just indicate whether it is configured.
jira_token_set: bool = False
model_config = ConfigDict(from_attributes=True)
@classmethod
def model_validate(cls, obj, *args, **kwargs): # type: ignore[override]
instance = super().model_validate(obj, *args, **kwargs)
# Derive jira_token_set from the ORM object without exposing the value
if hasattr(obj, "jira_api_token"):
instance.jira_token_set = bool(obj.jira_api_token)
return instance

View File

@@ -1,4 +1,31 @@
"""Jira integration service — wraps atlassian-python-api for Jira REST calls."""
"""Jira integration service.
Authentication model
--------------------
Each Aegis user authenticates to Jira with their own corporate email
(``user.email``) and their personal Atlassian API token
(``user.jira_api_token``). This way every Jira action is traceable to a
real person rather than a shared service account.
Admin configuration
-------------------
The Jira URL and default project key are stored in the ``system_configs``
table (keys ``jira.url`` and ``jira.project_key``) so the admin can update
them at runtime without redeploying. These values override the legacy
``settings.JIRA_URL`` / ``settings.JIRA_DEFAULT_PROJECT`` env-vars which are
kept for backwards-compatibility only.
Lifecycle hooks
---------------
``push_test_event()`` is the single entry-point called from the test-workflow
service on every state transition. It posts a rich comment to the linked
Jira issue (if one exists) using the acting user's credentials.
``auto_create_test_issue()`` is called once after a test is created; it
creates the Jira ticket and stores the link.
"""
from __future__ import annotations
import logging
from datetime import datetime
@@ -14,31 +41,394 @@ from app.models.campaign import Campaign
from app.models.jira_link import JiraLink, JiraLinkEntityType, JiraSyncDirection
from app.models.technique import Technique
from app.models.test import Test
from app.models.user import User
logger = logging.getLogger(__name__)
_jira_client = None
# ---------------------------------------------------------------------------
# System-config helpers (admin-configurable Jira settings)
# ---------------------------------------------------------------------------
_JIRA_KEYS = {
"url": "jira.url",
"project_key": "jira.project_key",
"enabled": "jira.enabled",
}
def _read_system_config(db: Session, key: str) -> Optional[str]:
"""Return a value from system_configs, or None if not set."""
from app.models.system_config import SystemConfig # avoid circular at import time
row = db.query(SystemConfig).filter(SystemConfig.key == key).first()
return row.value if row else None
def get_jira_url(db: Session) -> Optional[str]:
"""Return the admin-configured Jira URL, falling back to the env-var."""
return _read_system_config(db, _JIRA_KEYS["url"]) or settings.JIRA_URL or None
def get_jira_project_key(db: Session) -> Optional[str]:
"""Return the admin-configured default project key, falling back to env-var."""
return (
_read_system_config(db, _JIRA_KEYS["project_key"])
or settings.JIRA_DEFAULT_PROJECT
or None
)
def is_jira_enabled(db: Session) -> bool:
"""Return True if Jira integration is enabled (DB setting or env-var)."""
db_val = _read_system_config(db, _JIRA_KEYS["enabled"])
if db_val is not None:
return db_val.lower() in ("true", "1", "yes")
return settings.JIRA_ENABLED
def upsert_jira_config(db: Session, key: str, value: str) -> None:
"""Persist a Jira config key-value pair."""
from app.models.system_config import SystemConfig
row = db.query(SystemConfig).filter(SystemConfig.key == key).first()
if row:
row.value = value
else:
db.add(SystemConfig(key=key, value=value))
# ---------------------------------------------------------------------------
# Per-user Jira client
# ---------------------------------------------------------------------------
def get_user_jira_client(user: User, db: Session):
"""Build an Atlassian Jira client authenticated as *user*.
Raises ``InvalidOperationError`` when configuration is incomplete so
callers can surface meaningful error messages.
"""
jira_url = get_jira_url(db)
if not jira_url:
raise InvalidOperationError(
"Jira URL is not configured. Ask your administrator to set it in "
"System Settings → Jira Configuration."
)
if not user.email:
raise InvalidOperationError(
"Your account has no email address. Set one in your profile before "
"using the Jira integration."
)
if not user.jira_api_token:
raise InvalidOperationError(
"You have not configured a Jira API token. "
"Go to Settings → Integrations and add your personal Atlassian token."
)
from atlassian import Jira
return Jira(
url=jira_url,
username=user.email,
password=user.jira_api_token,
cloud=True,
)
def has_jira_configured(user: User, db: Session) -> bool:
"""Return True if *user* has everything needed to call Jira."""
return bool(get_jira_url(db) and user.email and user.jira_api_token)
# ---------------------------------------------------------------------------
# Ticket content builders (inspired by the pentest-to-Jira script)
# ---------------------------------------------------------------------------
_SEVERITY_TO_PRIORITY: dict[str, str] = {
"critical": "Highest",
"high": "High",
"medium": "Medium",
"low": "Low",
"informational": "Lowest",
}
_STATE_EMOJI: dict[str, str] = {
"draft": "📝 Draft",
"red_executing": "🔴 Red Team Executing",
"blue_evaluating": "🔵 Blue Team Evaluating",
"in_review": "📋 In Review",
"validated": "✅ Validated",
"rejected": "❌ Rejected",
}
def _technique_severity(technique: Optional[Technique]) -> str:
"""Return a lowercase severity string from the technique, defaulting to medium."""
if technique and hasattr(technique, "severity") and technique.severity:
return technique.severity.lower()
return "medium"
def _build_test_description(test: Test, technique: Optional[Technique]) -> str:
"""Build the initial Jira ticket description for a newly created test."""
mitre_id = technique.mitre_id if technique else "N/A"
tech_name = technique.name if technique else "N/A"
tactic = technique.tactic if technique else "N/A"
severity = _technique_severity(technique).capitalize()
lines = [
"h2. Aegis Security Test",
"",
f"*Test Name:* {test.name}",
f"*MITRE Technique:* [{mitre_id}|https://attack.mitre.org/techniques/{mitre_id.replace('.', '/')}] — {tech_name}",
f"*Tactic:* {tactic}",
f"*Platform:* {test.platform or 'N/A'}",
f"*Severity:* {severity}",
f"*Data Classification:* {test.data_classification or 'N/A'}",
"",
"h3. Description",
test.description or "_No description provided._",
"",
"h3. Procedure",
f"{{code}}{test.procedure_text or 'N/A'}{{code}}",
"",
f"*Tool:* {test.tool_used or 'N/A'}",
"",
"----",
f"_Created via Aegis at {datetime.utcnow().strftime('%Y-%m-%d %H:%M')} UTC_",
]
return "\n".join(lines)
def _build_state_comment(
test: Test,
new_state: str,
actor: User,
extra: dict | None = None,
) -> str:
"""Build a Jira comment body for a test state transition."""
label = _STATE_EMOJI.get(new_state, new_state)
lines = [
f"h3. {label}",
"",
f"*Changed by:* {actor.username} ({actor.email or 'no email'})",
f"*At:* {datetime.utcnow().strftime('%Y-%m-%d %H:%M')} UTC",
"",
]
if new_state == "red_executing":
lines += [
"Red Team has started the attack execution.",
]
elif new_state == "blue_evaluating":
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'}",
]
if test.red_summary:
lines += ["", "h4. Red Team Summary", test.red_summary]
elif new_state == "in_review":
lines += [
"Blue Team has completed evaluation. Test is awaiting lead validation.",
"",
f"*Detection Result:* {test.detection_result or 'N/A'}",
]
if test.blue_summary:
lines += ["", "h4. Blue Team Summary", test.blue_summary]
if test.remediation_steps:
lines += ["", "h4. Remediation Steps", test.remediation_steps]
elif new_state == "validated":
lines += [
"Test has been *validated* by both leads.",
"",
f"*Red Lead Status:* {test.red_validation_status or 'N/A'}",
f"*Blue Lead Status:* {test.blue_validation_status or 'N/A'}",
]
if test.red_validation_notes:
lines += ["", f"*Red Lead Notes:* {test.red_validation_notes}"]
if test.blue_validation_notes:
lines += ["", f"*Blue Lead Notes:* {test.blue_validation_notes}"]
elif new_state == "rejected":
lines += [
"Test has been *rejected* and must be reworked.",
"",
f"*Red Lead Status:* {test.red_validation_status or 'N/A'}",
f"*Blue Lead Status:* {test.blue_validation_status or 'N/A'}",
]
if test.red_validation_notes:
lines += ["", f"*Red Lead Notes:* {test.red_validation_notes}"]
if test.blue_validation_notes:
lines += ["", f"*Blue Lead Notes:* {test.blue_validation_notes}"]
elif new_state == "draft":
lines += ["Test has been reopened for re-execution."]
# Any caller-supplied extra data
if extra:
lines.append("")
for k, v in extra.items():
lines.append(f"*{k}:* {v}")
lines.append("")
lines.append("_Synced from [Aegis|https://aegis.undiamagico.es]_")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Public lifecycle hooks
# ---------------------------------------------------------------------------
def auto_create_test_issue(
db: Session,
test: Test,
actor: User,
*,
technique: Optional[Technique] = None,
) -> Optional[str]:
"""Create a Jira issue for *test* and store the link.
Returns the Jira issue key on success, or ``None`` if Jira is not
configured for *actor* or if the operation fails (non-fatal).
Called once right after a test is committed to the database.
"""
if not has_jira_configured(actor, db):
return None
project_key = get_jira_project_key(db)
if not project_key:
logger.warning("Jira project key not configured; skipping auto-create for test %s", test.id)
return None
# Resolve technique if not supplied
if technique is None:
technique = db.query(Technique).filter(Technique.id == test.technique_id).first()
severity = _technique_severity(technique)
mitre_id = technique.mitre_id if technique else "N/A"
try:
jira = get_user_jira_client(actor, db)
fields: dict = {
"project": {"key": project_key},
"summary": f"[Aegis] {mitre_id}{test.name}",
"description": _build_test_description(test, technique),
"issuetype": {"name": settings.JIRA_ISSUE_TYPE_TEST},
"priority": {"name": _SEVERITY_TO_PRIORITY.get(severity, "Medium")},
"labels": ["aegis", "security-test", mitre_id.replace(".", "-")],
}
result = jira.issue_create(fields=fields)
issue_key = result["key"]
issue_id = result.get("id", "")
link = JiraLink(
entity_type=JiraLinkEntityType.test,
entity_id=test.id,
jira_issue_key=issue_key,
jira_issue_id=issue_id,
jira_project_key=project_key,
sync_direction=JiraSyncDirection.aegis_to_jira,
created_by=actor.id,
)
db.add(link)
db.flush()
logger.info("Auto-created Jira issue %s for test %s", issue_key, test.id)
return issue_key
except Exception as exc:
# Non-fatal: Jira failures must never break the test creation flow
logger.warning(
"Failed to auto-create Jira issue for test %s: %s",
test.id, exc, exc_info=True,
)
return None
def push_test_event(
db: Session,
test: Test,
actor: User,
new_state: str,
*,
extra: dict | None = None,
) -> None:
"""Post a lifecycle comment to the Jira issue linked to *test*.
Called from ``test_workflow_service`` after every state transition.
Completely non-fatal — any Jira error is logged and swallowed so it
never blocks the test workflow.
"""
if not has_jira_configured(actor, 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_user_jira_client(actor, db)
comment = _build_state_comment(test, new_state, actor, extra)
jira.issue_add_comment(link.jira_issue_key, comment)
link.last_synced_at = datetime.utcnow()
db.flush()
logger.info(
"Posted Jira comment to %s for test %s state=%s",
link.jira_issue_key, test.id, new_state,
)
except Exception as exc:
logger.warning(
"Failed to push Jira event for test %s (state=%s): %s",
test.id, new_state, exc, exc_info=True,
)
# ---------------------------------------------------------------------------
# Legacy / generic helpers (kept for existing routes)
# ---------------------------------------------------------------------------
def get_jira_client():
"""Return a lazily-initialised Jira client, or raise if disabled."""
global _jira_client
"""Return a shared Jira client using global credentials (legacy path).
Raises ``InvalidOperationError`` when Jira is disabled or unconfigured.
Prefer ``get_user_jira_client()`` for new code.
"""
if not settings.JIRA_ENABLED:
raise InvalidOperationError("Jira integration is not enabled")
if _jira_client is None:
from atlassian import Jira
_jira_client = Jira(
url=settings.JIRA_URL,
username=settings.JIRA_USERNAME,
password=settings.JIRA_API_TOKEN,
cloud=settings.JIRA_IS_CLOUD,
if not settings.JIRA_URL or not settings.JIRA_USERNAME or not settings.JIRA_API_TOKEN:
raise InvalidOperationError(
"Jira is enabled but JIRA_URL / JIRA_USERNAME / JIRA_API_TOKEN are not set"
)
return _jira_client
from atlassian import Jira
return Jira(
url=settings.JIRA_URL,
username=settings.JIRA_USERNAME,
password=settings.JIRA_API_TOKEN,
cloud=settings.JIRA_IS_CLOUD,
)
def search_jira_issues(query: str, max_results: int = 10) -> list[dict]:
"""Search Jira issues by JQL or free text."""
"""Search Jira issues by JQL or free text (uses global credentials)."""
jira = get_jira_client()
jql = query if "=" in query or "~" in query else f'summary ~ "{query}"'
results = jira.jql(jql, limit=max_results)
@@ -62,7 +452,7 @@ def create_jira_issue(
labels: Optional[list[str]] = None,
custom_fields: Optional[dict] = None,
) -> dict:
"""Create a Jira issue and return its key + id."""
"""Create a Jira issue and return its key + id (uses global credentials)."""
jira = get_jira_client()
fields: dict = {
"project": {"key": project_key},
@@ -80,7 +470,7 @@ def create_jira_issue(
def sync_jira_to_aegis(db: Session, link: JiraLink) -> None:
"""Pull current status from Jira into the local link record."""
"""Pull current status from Jira into the local link record (global creds)."""
jira = get_jira_client()
issue = jira.issue(link.jira_issue_key)
fields = issue.get("fields", {})
@@ -93,7 +483,7 @@ def sync_jira_to_aegis(db: Session, link: JiraLink) -> None:
def sync_aegis_to_jira(db: Session, link: JiraLink, entity_data: dict) -> None:
"""Push an Aegis status update as a Jira comment."""
"""Push an Aegis status update as a Jira comment (global creds)."""
jira = get_jira_client()
comment_body = _build_sync_comment(entity_data)
jira.issue_add_comment(link.jira_issue_key, comment_body)
@@ -102,7 +492,6 @@ def sync_aegis_to_jira(db: Session, link: JiraLink, entity_data: dict) -> None:
def _build_sync_comment(data: dict) -> str:
"""Build a formatted Jira comment from entity data."""
lines = ["h3. Aegis Sync Update", ""]
for key, value in data.items():
lines.append(f"*{key}:* {value}")
@@ -110,7 +499,7 @@ def _build_sync_comment(data: dict) -> str:
return "\n".join(lines)
# ── Link CRUD ────────────────────────────────────────────────────────
# ── Link CRUD ────────────────────────────────────────────────────────────
def create_link(
@@ -122,7 +511,6 @@ def create_link(
sync_direction: JiraSyncDirection,
created_by: UUID,
) -> JiraLink:
"""Create a Jira link and optionally pull initial data from Jira."""
link = JiraLink(
entity_type=entity_type,
entity_id=entity_id,
@@ -148,7 +536,6 @@ def list_links(
entity_type: Optional[JiraLinkEntityType] = None,
entity_id: Optional[UUID] = None,
) -> list[JiraLink]:
"""List Jira links with optional filters."""
query = db.query(JiraLink)
if entity_type:
query = query.filter(JiraLink.entity_type == entity_type)
@@ -158,7 +545,6 @@ def list_links(
def get_link_or_raise(db: Session, link_id: UUID) -> JiraLink:
"""Get a Jira link by ID or raise EntityNotFoundError."""
link = db.query(JiraLink).filter(JiraLink.id == link_id).first()
if not link:
raise EntityNotFoundError("JiraLink", str(link_id))
@@ -166,23 +552,23 @@ def get_link_or_raise(db: Session, link_id: UUID) -> JiraLink:
def delete_link(db: Session, link_id: UUID) -> JiraLink:
"""Delete a Jira link. Returns the deleted link (for audit)."""
link = get_link_or_raise(db, link_id)
db.delete(link)
return link
def build_issue_data(db: Session, entity_type: JiraLinkEntityType, entity_id: UUID) -> tuple[str, str]:
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."""
if entity_type == JiraLinkEntityType.test:
entity = db.query(Test).filter(Test.id == entity_id).first()
if not entity:
raise EntityNotFoundError("Test", str(entity_id))
technique = db.query(Technique).filter(Technique.id == entity.technique_id).first()
return (
f"[Aegis Test] {entity.name}",
f"Test: {entity.name}\n"
f"State: {entity.state.value if entity.state else 'draft'}\n"
f"Description: {entity.description or 'N/A'}",
f"[Aegis] {technique.mitre_id if technique else 'N/A'} {entity.name}",
_build_test_description(entity, technique),
)
elif entity_type == JiraLinkEntityType.campaign:
entity = db.query(Campaign).filter(Campaign.id == entity_id).first()
@@ -190,8 +576,7 @@ def build_issue_data(db: Session, entity_type: JiraLinkEntityType, entity_id: UU
raise EntityNotFoundError("Campaign", str(entity_id))
return (
f"[Aegis Campaign] {entity.name}",
f"Campaign: {entity.name}\n"
f"Type: {entity.type}\nStatus: {entity.status}\n"
f"Campaign: {entity.name}\nType: {entity.type}\nStatus: {entity.status}\n"
f"Description: {entity.description or 'N/A'}",
)
elif entity_type == JiraLinkEntityType.technique:
@@ -215,10 +600,11 @@ def create_issue_and_link(
entity_id: UUID,
created_by: UUID,
) -> dict:
"""Create a Jira issue from an Aegis entity and link them."""
"""Create a Jira issue from an Aegis entity and link them (global creds)."""
summary, description = build_issue_data(db, entity_type, entity_id)
project_key = settings.JIRA_DEFAULT_PROJECT
result = create_jira_issue(
project_key=settings.JIRA_DEFAULT_PROJECT,
project_key=project_key,
summary=summary,
description=description,
labels=["aegis", entity_type.value],
@@ -228,7 +614,7 @@ def create_issue_and_link(
entity_id=entity_id,
jira_issue_key=result["issue_key"],
jira_issue_id=result["issue_id"],
jira_project_key=settings.JIRA_DEFAULT_PROJECT,
jira_project_key=project_key,
created_by=created_by,
)
db.add(link)

View File

@@ -108,12 +108,7 @@ def transition_state(
def start_execution(db: Session, test: Test, user: User) -> Test:
"""Move from ``draft`` → ``red_executing``.
Typically called by a **red_tech** when they begin the attack.
Delegates to :meth:`TestEntity.start_execution` which handles the
state transition and sets ``execution_date`` / ``red_started_at``.
"""
"""Move from ``draft`` → ``red_executing``."""
entity = TestEntity.from_orm(test)
entity.start_execution()
entity.apply_to(test)
@@ -138,6 +133,12 @@ def start_execution(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_test_event
push_test_event(db, test, user, "red_executing")
except Exception as e:
logger.warning("Jira push failed for test %s: %s", test.id, e, exc_info=True)
return test
@@ -176,6 +177,13 @@ def submit_red_evidence(db: Session, test: Test, user: User) -> Test:
# Start Blue Team timer
test.blue_started_at = now
test.blue_paused_seconds = 0
try:
from app.services.jira_service import push_test_event
push_test_event(db, test, user, "blue_evaluating")
except Exception as e:
logger.warning("Jira push failed for test %s: %s", test.id, e, exc_info=True)
return test
@@ -210,6 +218,12 @@ def submit_blue_evidence(db: Session, test: Test, user: User) -> Test:
description=f"Blue Team evaluation: {test.name}",
)
try:
from app.services.jira_service import push_test_event
push_test_event(db, test, user, "in_review")
except Exception as e:
logger.warning("Jira push failed for test %s: %s", test.id, e, exc_info=True)
return test
@@ -355,7 +369,7 @@ def validate_as_red_lead(
},
)
_dispatch_dual_validation_effects(db, test, entity)
_dispatch_dual_validation_effects(db, test, entity, actor=user)
return test
@@ -390,7 +404,7 @@ def validate_as_blue_lead(
},
)
_dispatch_dual_validation_effects(db, test, entity)
_dispatch_dual_validation_effects(db, test, entity, actor=user)
return test
@@ -409,9 +423,9 @@ def check_dual_validation(db: Session, test: Test) -> Test:
def _dispatch_dual_validation_effects(
db: Session, test: Test, entity: TestEntity
db: Session, test: Test, entity: TestEntity, actor: User | None = None
) -> None:
"""Dispatch side effects (notifications, cache) based on domain events."""
"""Dispatch side effects (notifications, cache, Jira) based on domain events."""
for event in entity.events:
if event.name == "dual_validation_approved":
try:
@@ -426,6 +440,13 @@ def _dispatch_dual_validation_effects(
"Notification failed for test %s (validated): %s",
test.id, e, exc_info=True,
)
if actor:
try:
from app.services.jira_service import push_test_event
push_test_event(db, test, actor, "validated")
except Exception as e:
logger.warning("Jira push failed for test %s: %s", test.id, e, exc_info=True)
elif event.name == "dual_validation_rejected":
try:
notify_test_state_change(db, test, "rejected")
@@ -434,6 +455,12 @@ def _dispatch_dual_validation_effects(
"Notification failed for test %s (rejected): %s",
test.id, e, exc_info=True,
)
if actor:
try:
from app.services.jira_service import push_test_event
push_test_event(db, test, actor, "rejected")
except Exception as e:
logger.warning("Jira push failed for test %s: %s", test.id, e, exc_info=True)
def handle_remediation_completed(db: Session, test: Test, user: User) -> Test | None:
@@ -588,4 +615,10 @@ def reopen_test(db: Session, test: Test, user: User) -> Test:
test.red_paused_seconds = 0
test.blue_paused_seconds = 0
try:
from app.services.jira_service import push_test_event
push_test_event(db, test, user, "draft")
except Exception as e:
logger.warning("Jira push failed for test %s: %s", test.id, e, exc_info=True)
return test