feat(phase-35): Jira + Tempo integration with internal worklogs
Some checks failed
Aegis CI / lint-and-test (push) Has been cancelled
Some checks failed
Aegis CI / lint-and-test (push) Has been cancelled
Full Jira/Tempo pipeline: link Aegis entities to Jira issues, auto-sync
status hourly, log time internally with integrity hashing, and optionally
push worklogs to Tempo.
- 1.1 JiraLink model + Worklog model: Alembic migration b020 with indexes,
enums (jiralinkentitytype, jirasyncdirection), and integrity_hash column
- 1.2 Jira service: atlassian-python-api wrapper with lazy singleton client,
search/create/sync operations, feature-flagged via JIRA_ENABLED
- 1.3 Jira router: CRUD endpoints for /jira/links, /jira/search,
/jira/create-issue with audit logging and entity-to-issue auto-creation
- 1.4 Tempo service: worklog push via tempo-api-python-client, auto-log from
test completions when TEMPO_ENABLED, graceful fallback on failure
- 1.5 Worklog service + router: immutable internal time records with SHA-256
integrity hash, CRUD at /worklogs, /worklogs/{id}/verify endpoint
- 1.6 Frontend: JiraLinkPanel component (search, link, sync, unlink) and
WorklogTimeline component (timeline view, manual log form) integrated into
TestDetailPage sidebar, CampaignDetailPage grid, TechniqueDetailPage
- 1.7 Jira sync job: APScheduler hourly job syncs all links from Jira,
registered in background scheduler alongside existing jobs
This commit is contained in:
@@ -43,6 +43,21 @@ class Settings(BaseSettings):
|
||||
# ── Re-testing ───────────────────────────────────────────────────
|
||||
MAX_RETEST_COUNT: int = 3 # maximum automatic retests per original test
|
||||
|
||||
# ── Jira Integration ────────────────────────────────────────────
|
||||
JIRA_ENABLED: bool = False
|
||||
JIRA_URL: str = ""
|
||||
JIRA_USERNAME: str = ""
|
||||
JIRA_API_TOKEN: str = ""
|
||||
JIRA_IS_CLOUD: bool = True
|
||||
JIRA_DEFAULT_PROJECT: str = ""
|
||||
JIRA_ISSUE_TYPE_TEST: str = "Task"
|
||||
JIRA_ISSUE_TYPE_CAMPAIGN: str = "Epic"
|
||||
|
||||
# ── Tempo Integration ─────────────────────────────────────────────
|
||||
TEMPO_ENABLED: bool = False
|
||||
TEMPO_API_TOKEN: str = ""
|
||||
TEMPO_DEFAULT_WORK_TYPE: str = "Red Team"
|
||||
|
||||
# ── Scoring weights (must sum to 100) ────────────────────────────
|
||||
SCORING_WEIGHT_TESTS: int = 40
|
||||
SCORING_WEIGHT_DETECTION_RULES: int = 20
|
||||
|
||||
37
backend/app/jobs/jira_sync_job.py
Normal file
37
backend/app/jobs/jira_sync_job.py
Normal file
@@ -0,0 +1,37 @@
|
||||
"""Scheduled job — syncs all Jira links hourly."""
|
||||
|
||||
import logging
|
||||
|
||||
from app.config import settings
|
||||
from app.database import SessionLocal
|
||||
from app.models.jira_link import JiraLink
|
||||
from app.services import jira_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def sync_all_jira_links() -> None:
|
||||
"""Pull latest status from Jira for every stored link.
|
||||
|
||||
Silently skips if ``JIRA_ENABLED`` is ``False``. Individual link
|
||||
failures are logged but do not abort the rest of the batch.
|
||||
"""
|
||||
if not settings.JIRA_ENABLED:
|
||||
return
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
links = db.query(JiraLink).all()
|
||||
synced = 0
|
||||
for link in links:
|
||||
try:
|
||||
jira_service.sync_jira_to_aegis(db, link)
|
||||
synced += 1
|
||||
except Exception as e:
|
||||
logger.warning("Jira sync failed for link %s: %s", link.id, e)
|
||||
db.commit()
|
||||
logger.info("Jira sync completed: %d/%d links updated", synced, len(links))
|
||||
except Exception:
|
||||
logger.exception("Jira sync batch job failed")
|
||||
finally:
|
||||
db.close()
|
||||
@@ -20,6 +20,7 @@ from app.services.intel_service import scan_intel
|
||||
from app.services.notification_service import cleanup_old_notifications
|
||||
from app.services.snapshot_service import create_snapshot, cleanup_old_snapshots
|
||||
from app.services.campaign_scheduler_service import check_and_run_recurring_campaigns
|
||||
from app.jobs.jira_sync_job import sync_all_jira_links
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -164,9 +165,17 @@ def start_scheduler() -> None:
|
||||
name="Recurring campaigns check (daily)",
|
||||
replace_existing=True,
|
||||
)
|
||||
scheduler.add_job(
|
||||
sync_all_jira_links,
|
||||
trigger="interval",
|
||||
hours=1,
|
||||
id="jira_sync",
|
||||
name="Jira link sync (hourly)",
|
||||
replace_existing=True,
|
||||
)
|
||||
scheduler.start()
|
||||
logger.info(
|
||||
"Background scheduler started — mitre_sync (24h), intel_scan (7d), "
|
||||
"notification_cleanup (24h), weekly_snapshot (Sundays 00:00), "
|
||||
"recurring_campaigns (daily)"
|
||||
"recurring_campaigns (daily), jira_sync (1h)"
|
||||
)
|
||||
|
||||
@@ -32,6 +32,8 @@ from app.routers import scores as scores_router
|
||||
from app.routers import operational_metrics as operational_metrics_router
|
||||
from app.routers import compliance as compliance_router
|
||||
from app.routers import snapshots as snapshots_router
|
||||
from app.routers import jira as jira_router
|
||||
from app.routers import worklogs as worklogs_router
|
||||
from app.domain.exceptions import DomainException
|
||||
from app.middleware.error_handler import domain_exception_handler
|
||||
from app.storage import ensure_bucket_exists
|
||||
@@ -110,6 +112,8 @@ app.include_router(scores_router.router, prefix="/api/v1")
|
||||
app.include_router(operational_metrics_router.router, prefix="/api/v1")
|
||||
app.include_router(compliance_router.router, prefix="/api/v1")
|
||||
app.include_router(snapshots_router.router, prefix="/api/v1")
|
||||
app.include_router(jira_router.router, prefix="/api/v1")
|
||||
app.include_router(worklogs_router.router, prefix="/api/v1")
|
||||
|
||||
|
||||
@app.get("/health", include_in_schema=False)
|
||||
|
||||
@@ -16,6 +16,8 @@ from app.models.test_detection_result import TestDetectionResult
|
||||
from app.models.campaign import Campaign, CampaignTest
|
||||
from app.models.compliance import ComplianceFramework, ComplianceControl, ComplianceControlMapping
|
||||
from app.models.coverage_snapshot import CoverageSnapshot, SnapshotTechniqueState
|
||||
from app.models.jira_link import JiraLink, JiraLinkEntityType, JiraSyncDirection
|
||||
from app.models.worklog import Worklog
|
||||
from app.models.enums import TechniqueStatus, TestState, TestResult, TeamSide
|
||||
|
||||
__all__ = [
|
||||
@@ -27,5 +29,7 @@ __all__ = [
|
||||
"Campaign", "CampaignTest",
|
||||
"ComplianceFramework", "ComplianceControl", "ComplianceControlMapping",
|
||||
"CoverageSnapshot", "SnapshotTechniqueState",
|
||||
"JiraLink", "JiraLinkEntityType", "JiraSyncDirection",
|
||||
"Worklog",
|
||||
"TechniqueStatus", "TestState", "TestResult", "TeamSide",
|
||||
]
|
||||
|
||||
57
backend/app/models/jira_link.py
Normal file
57
backend/app/models/jira_link.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""Jira integration models — link Aegis entities to Jira issues."""
|
||||
|
||||
import enum
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Column, String, DateTime, ForeignKey, Enum as SQLEnum, Index
|
||||
from sqlalchemy.dialects.postgresql import UUID, JSONB
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class JiraLinkEntityType(str, enum.Enum):
|
||||
test = "test"
|
||||
technique = "technique"
|
||||
campaign = "campaign"
|
||||
evidence = "evidence"
|
||||
|
||||
|
||||
class JiraSyncDirection(str, enum.Enum):
|
||||
aegis_to_jira = "aegis_to_jira"
|
||||
jira_to_aegis = "jira_to_aegis"
|
||||
bidirectional = "bidirectional"
|
||||
|
||||
|
||||
class JiraLink(Base):
|
||||
"""Associates an Aegis entity with a Jira issue for bidirectional sync."""
|
||||
|
||||
__tablename__ = "jira_links"
|
||||
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
entity_type = Column(SQLEnum(JiraLinkEntityType), nullable=False)
|
||||
entity_id = Column(UUID(as_uuid=True), nullable=False)
|
||||
jira_issue_key = Column(String(50), nullable=False)
|
||||
jira_issue_id = Column(String(50))
|
||||
jira_project_key = Column(String(20))
|
||||
jira_status = Column(String(100))
|
||||
jira_priority = Column(String(50))
|
||||
jira_assignee = Column(String(255))
|
||||
jira_story_points = Column(String(10))
|
||||
sync_direction = Column(
|
||||
SQLEnum(JiraSyncDirection), default=JiraSyncDirection.bidirectional
|
||||
)
|
||||
last_synced_at = Column(DateTime)
|
||||
sync_metadata = Column(JSONB, default={})
|
||||
created_by = Column(UUID(as_uuid=True), ForeignKey("users.id"))
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
creator = relationship("User", foreign_keys=[created_by])
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_jira_links_entity_id", "entity_id"),
|
||||
Index("ix_jira_links_issue_key", "jira_issue_key"),
|
||||
Index("ix_jira_links_entity_type_entity_id", "entity_type", "entity_id"),
|
||||
)
|
||||
44
backend/app/models/worklog.py
Normal file
44
backend/app/models/worklog.py
Normal file
@@ -0,0 +1,44 @@
|
||||
"""Worklog model — immutable internal time-tracking records."""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey, Text, Index
|
||||
from sqlalchemy.dialects.postgresql import UUID, JSONB
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class Worklog(Base):
|
||||
"""Internal worklog entry with integrity hash for audit compliance.
|
||||
|
||||
Each worklog is tied to an Aegis entity (test, campaign, etc.) and
|
||||
optionally synced to Tempo. The ``integrity_hash`` is a SHA-256 of
|
||||
the immutable fields so tampering can be detected.
|
||||
"""
|
||||
|
||||
__tablename__ = "worklogs"
|
||||
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
entity_type = Column(String(50), nullable=False)
|
||||
entity_id = Column(UUID(as_uuid=True), nullable=False)
|
||||
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
|
||||
activity_type = Column(String(100), nullable=False)
|
||||
started_at = Column(DateTime, nullable=False)
|
||||
ended_at = Column(DateTime)
|
||||
duration_seconds = Column(Integer, nullable=False)
|
||||
description = Column(Text)
|
||||
tempo_synced = Column(DateTime)
|
||||
tempo_worklog_id = Column(String(100))
|
||||
integrity_hash = Column(String(64))
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
extra_metadata = Column("metadata", JSONB, default={})
|
||||
|
||||
user = relationship("User", foreign_keys=[user_id])
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_worklogs_entity_id", "entity_id"),
|
||||
Index("ix_worklogs_user_id", "user_id"),
|
||||
Index("ix_worklogs_entity_type_entity_id", "entity_type", "entity_id"),
|
||||
)
|
||||
201
backend/app/routers/jira.py
Normal file
201
backend/app/routers/jira.py
Normal file
@@ -0,0 +1,201 @@
|
||||
"""Jira integration router — link, search, sync, create issues."""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import settings
|
||||
from app.database import get_db
|
||||
from app.dependencies.auth import get_current_user, require_role
|
||||
from app.domain.exceptions import EntityNotFoundError
|
||||
from app.models.jira_link import JiraLink, JiraLinkEntityType
|
||||
from app.models.test import Test
|
||||
from app.models.technique import Technique
|
||||
from app.models.campaign import Campaign
|
||||
from app.models.user import User
|
||||
from app.schemas.jira_schema import (
|
||||
JiraIssueResult,
|
||||
JiraLinkCreate,
|
||||
JiraLinkOut,
|
||||
)
|
||||
from app.services import jira_service, audit_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/jira", tags=["jira"])
|
||||
|
||||
|
||||
@router.get("/search", response_model=list[JiraIssueResult])
|
||||
def search_issues(
|
||||
q: str = Query(..., min_length=2),
|
||||
max_results: int = Query(10, le=50),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Search Jira issues by JQL or free text."""
|
||||
return jira_service.search_jira_issues(q, max_results)
|
||||
|
||||
|
||||
@router.post("/links", response_model=JiraLinkOut, status_code=201)
|
||||
def create_link(
|
||||
body: JiraLinkCreate,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Associate an Aegis entity with a Jira issue."""
|
||||
link = JiraLink(
|
||||
entity_type=body.entity_type,
|
||||
entity_id=body.entity_id,
|
||||
jira_issue_key=body.jira_issue_key,
|
||||
sync_direction=body.sync_direction,
|
||||
created_by=user.id,
|
||||
)
|
||||
db.add(link)
|
||||
db.flush()
|
||||
|
||||
# Pull initial data from Jira if enabled
|
||||
if settings.JIRA_ENABLED:
|
||||
try:
|
||||
jira_service.sync_jira_to_aegis(db, link)
|
||||
except Exception as e:
|
||||
logger.warning("Initial Jira sync failed for %s: %s", body.jira_issue_key, e)
|
||||
|
||||
db.commit()
|
||||
db.refresh(link)
|
||||
|
||||
audit_service.log_action(
|
||||
db,
|
||||
user_id=user.id,
|
||||
action="jira_link_created",
|
||||
entity_type="jira_link",
|
||||
entity_id=str(link.id),
|
||||
details={
|
||||
"linked_entity_type": body.entity_type.value,
|
||||
"linked_entity_id": str(body.entity_id),
|
||||
"jira_issue_key": body.jira_issue_key,
|
||||
},
|
||||
)
|
||||
return link
|
||||
|
||||
|
||||
@router.get("/links", response_model=list[JiraLinkOut])
|
||||
def list_links(
|
||||
entity_type: Optional[JiraLinkEntityType] = None,
|
||||
entity_id: Optional[UUID] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
"""List Jira links, optionally filtered by entity."""
|
||||
query = db.query(JiraLink)
|
||||
if entity_type:
|
||||
query = query.filter(JiraLink.entity_type == entity_type)
|
||||
if entity_id:
|
||||
query = query.filter(JiraLink.entity_id == entity_id)
|
||||
return query.order_by(JiraLink.created_at.desc()).all()
|
||||
|
||||
|
||||
@router.post("/links/{link_id}/sync")
|
||||
def sync_link(
|
||||
link_id: UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_role("admin")),
|
||||
):
|
||||
"""Force bidirectional sync for a specific Jira link."""
|
||||
link = db.query(JiraLink).filter(JiraLink.id == link_id).first()
|
||||
if not link:
|
||||
raise EntityNotFoundError("JiraLink", str(link_id))
|
||||
jira_service.sync_jira_to_aegis(db, link)
|
||||
db.commit()
|
||||
return {"message": "Sync completed", "jira_status": link.jira_status}
|
||||
|
||||
|
||||
@router.delete("/links/{link_id}", status_code=204)
|
||||
def delete_link(
|
||||
link_id: UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Remove a Jira link."""
|
||||
link = db.query(JiraLink).filter(JiraLink.id == link_id).first()
|
||||
if not link:
|
||||
raise EntityNotFoundError("JiraLink", str(link_id))
|
||||
db.delete(link)
|
||||
db.commit()
|
||||
audit_service.log_action(
|
||||
db,
|
||||
user_id=user.id,
|
||||
action="jira_link_deleted",
|
||||
entity_type="jira_link",
|
||||
entity_id=str(link_id),
|
||||
details={"jira_issue_key": link.jira_issue_key},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/create-issue")
|
||||
def create_issue_from_entity(
|
||||
entity_type: JiraLinkEntityType,
|
||||
entity_id: UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Auto-create a Jira issue from an Aegis entity and link them."""
|
||||
summary, description = _build_issue_data(db, entity_type, entity_id)
|
||||
result = jira_service.create_jira_issue(
|
||||
project_key=settings.JIRA_DEFAULT_PROJECT,
|
||||
summary=summary,
|
||||
description=description,
|
||||
labels=["aegis", entity_type.value],
|
||||
)
|
||||
link = JiraLink(
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
jira_issue_key=result["issue_key"],
|
||||
jira_issue_id=result["issue_id"],
|
||||
jira_project_key=settings.JIRA_DEFAULT_PROJECT,
|
||||
created_by=user.id,
|
||||
)
|
||||
db.add(link)
|
||||
db.commit()
|
||||
return {"issue_key": result["issue_key"], "link_id": str(link.id)}
|
||||
|
||||
|
||||
def _build_issue_data(
|
||||
db: Session,
|
||||
entity_type: JiraLinkEntityType,
|
||||
entity_id: UUID,
|
||||
) -> tuple[str, str]:
|
||||
"""Build Jira issue summary + 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))
|
||||
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'}",
|
||||
)
|
||||
elif entity_type == JiraLinkEntityType.campaign:
|
||||
entity = db.query(Campaign).filter(Campaign.id == entity_id).first()
|
||||
if not entity:
|
||||
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"Description: {entity.description or 'N/A'}",
|
||||
)
|
||||
elif entity_type == JiraLinkEntityType.technique:
|
||||
entity = db.query(Technique).filter(Technique.id == entity_id).first()
|
||||
if not entity:
|
||||
raise EntityNotFoundError("Technique", str(entity_id))
|
||||
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'}",
|
||||
)
|
||||
else:
|
||||
return f"[Aegis] Entity {entity_id}", f"Entity type: {entity_type.value}"
|
||||
119
backend/app/routers/worklogs.py
Normal file
119
backend/app/routers/worklogs.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""Worklog router — internal time-tracking records with integrity verification."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database import get_db
|
||||
from app.dependencies.auth import get_current_user
|
||||
from app.domain.exceptions import EntityNotFoundError
|
||||
from app.models.user import User
|
||||
from app.models.worklog import Worklog
|
||||
from app.services import worklog_service
|
||||
|
||||
router = APIRouter(prefix="/worklogs", tags=["worklogs"])
|
||||
|
||||
|
||||
# ── Schemas ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class WorklogCreate(BaseModel):
|
||||
entity_type: str = Field(..., max_length=50)
|
||||
entity_id: UUID
|
||||
activity_type: str = Field(..., max_length=100)
|
||||
started_at: datetime
|
||||
ended_at: Optional[datetime] = None
|
||||
duration_seconds: int = Field(..., gt=0)
|
||||
description: Optional[str] = None
|
||||
|
||||
|
||||
class WorklogOut(BaseModel):
|
||||
id: UUID
|
||||
entity_type: str
|
||||
entity_id: UUID
|
||||
user_id: UUID
|
||||
activity_type: str
|
||||
started_at: datetime
|
||||
ended_at: Optional[datetime] = None
|
||||
duration_seconds: int
|
||||
description: Optional[str] = None
|
||||
tempo_synced: Optional[datetime] = None
|
||||
integrity_hash: Optional[str] = None
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
# ── Endpoints ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.post("", response_model=WorklogOut, status_code=201)
|
||||
def create(
|
||||
body: WorklogCreate,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Create a manually-logged worklog entry."""
|
||||
wl = worklog_service.create_worklog(
|
||||
db,
|
||||
entity_type=body.entity_type,
|
||||
entity_id=body.entity_id,
|
||||
user_id=user.id,
|
||||
activity_type=body.activity_type,
|
||||
started_at=body.started_at,
|
||||
ended_at=body.ended_at,
|
||||
duration_seconds=body.duration_seconds,
|
||||
description=body.description,
|
||||
)
|
||||
return wl
|
||||
|
||||
|
||||
@router.get("", response_model=list[WorklogOut])
|
||||
def list_all(
|
||||
entity_type: Optional[str] = None,
|
||||
entity_id: Optional[UUID] = None,
|
||||
user_id: Optional[UUID] = None,
|
||||
db: Session = Depends(get_db),
|
||||
_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""List worklogs with optional filters."""
|
||||
return worklog_service.list_worklogs(
|
||||
db,
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{worklog_id}", response_model=WorklogOut)
|
||||
def get_one(
|
||||
worklog_id: UUID,
|
||||
db: Session = Depends(get_db),
|
||||
_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Get a single worklog by ID."""
|
||||
wl = db.query(Worklog).filter(Worklog.id == worklog_id).first()
|
||||
if not wl:
|
||||
raise EntityNotFoundError("Worklog", str(worklog_id))
|
||||
return wl
|
||||
|
||||
|
||||
@router.get("/{worklog_id}/verify")
|
||||
def verify_integrity(
|
||||
worklog_id: UUID,
|
||||
db: Session = Depends(get_db),
|
||||
_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Check whether a worklog's integrity hash is still valid."""
|
||||
wl = db.query(Worklog).filter(Worklog.id == worklog_id).first()
|
||||
if not wl:
|
||||
raise EntityNotFoundError("Worklog", str(worklog_id))
|
||||
return {
|
||||
"worklog_id": str(wl.id),
|
||||
"integrity_valid": worklog_service.verify_worklog_integrity(wl),
|
||||
}
|
||||
46
backend/app/schemas/jira_schema.py
Normal file
46
backend/app/schemas/jira_schema.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""Pydantic schemas for Jira integration endpoints."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.models.jira_link import JiraLinkEntityType, JiraSyncDirection
|
||||
|
||||
|
||||
class JiraLinkCreate(BaseModel):
|
||||
entity_type: JiraLinkEntityType
|
||||
entity_id: UUID
|
||||
jira_issue_key: str = Field(..., pattern=r"^[A-Z][A-Z0-9]+-\d+$")
|
||||
sync_direction: JiraSyncDirection = JiraSyncDirection.bidirectional
|
||||
|
||||
|
||||
class JiraLinkOut(BaseModel):
|
||||
id: UUID
|
||||
entity_type: JiraLinkEntityType
|
||||
entity_id: UUID
|
||||
jira_issue_key: str
|
||||
jira_issue_id: Optional[str] = None
|
||||
jira_project_key: Optional[str] = None
|
||||
jira_status: Optional[str] = None
|
||||
jira_priority: Optional[str] = None
|
||||
jira_assignee: Optional[str] = None
|
||||
jira_story_points: Optional[str] = None
|
||||
last_synced_at: Optional[datetime] = None
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class JiraIssueSearch(BaseModel):
|
||||
query: str
|
||||
|
||||
|
||||
class JiraIssueResult(BaseModel):
|
||||
issue_key: str
|
||||
summary: str
|
||||
status: str
|
||||
assignee: Optional[str] = None
|
||||
priority: Optional[str] = None
|
||||
105
backend/app/services/jira_service.py
Normal file
105
backend/app/services/jira_service.py
Normal file
@@ -0,0 +1,105 @@
|
||||
"""Jira integration service — wraps atlassian-python-api for Jira REST calls."""
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import settings
|
||||
from app.domain.exceptions import InvalidOperationError
|
||||
from app.models.jira_link import JiraLink
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_jira_client = None
|
||||
|
||||
|
||||
def get_jira_client():
|
||||
"""Return a lazily-initialised Jira client, or raise if disabled."""
|
||||
global _jira_client
|
||||
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,
|
||||
)
|
||||
return _jira_client
|
||||
|
||||
|
||||
def search_jira_issues(query: str, max_results: int = 10) -> list[dict]:
|
||||
"""Search Jira issues by JQL or free text."""
|
||||
jira = get_jira_client()
|
||||
jql = query if "=" in query or "~" in query else f'summary ~ "{query}"'
|
||||
results = jira.jql(jql, limit=max_results)
|
||||
return [
|
||||
{
|
||||
"issue_key": issue["key"],
|
||||
"summary": issue["fields"]["summary"],
|
||||
"status": issue["fields"]["status"]["name"],
|
||||
"assignee": (issue["fields"].get("assignee") or {}).get("displayName"),
|
||||
"priority": (issue["fields"].get("priority") or {}).get("name"),
|
||||
}
|
||||
for issue in results.get("issues", [])
|
||||
]
|
||||
|
||||
|
||||
def create_jira_issue(
|
||||
project_key: str,
|
||||
summary: str,
|
||||
description: str,
|
||||
issue_type: str = "Task",
|
||||
labels: Optional[list[str]] = None,
|
||||
custom_fields: Optional[dict] = None,
|
||||
) -> dict:
|
||||
"""Create a Jira issue and return its key + id."""
|
||||
jira = get_jira_client()
|
||||
fields: dict = {
|
||||
"project": {"key": project_key},
|
||||
"summary": summary,
|
||||
"description": description,
|
||||
"issuetype": {"name": issue_type},
|
||||
}
|
||||
if labels:
|
||||
fields["labels"] = labels
|
||||
if custom_fields:
|
||||
fields.update(custom_fields)
|
||||
|
||||
result = jira.issue_create(fields=fields)
|
||||
return {"issue_key": result["key"], "issue_id": result["id"]}
|
||||
|
||||
|
||||
def sync_jira_to_aegis(db: Session, link: JiraLink) -> None:
|
||||
"""Pull current status from Jira into the local link record."""
|
||||
jira = get_jira_client()
|
||||
issue = jira.issue(link.jira_issue_key)
|
||||
fields = issue.get("fields", {})
|
||||
link.jira_status = fields.get("status", {}).get("name")
|
||||
link.jira_priority = (fields.get("priority") or {}).get("name")
|
||||
link.jira_assignee = (fields.get("assignee") or {}).get("displayName")
|
||||
link.jira_story_points = str(fields.get("customfield_10016", ""))
|
||||
link.last_synced_at = datetime.utcnow()
|
||||
db.flush()
|
||||
|
||||
|
||||
def sync_aegis_to_jira(db: Session, link: JiraLink, entity_data: dict) -> None:
|
||||
"""Push an Aegis status update as a Jira comment."""
|
||||
jira = get_jira_client()
|
||||
comment_body = _build_sync_comment(entity_data)
|
||||
jira.issue_add_comment(link.jira_issue_key, comment_body)
|
||||
link.last_synced_at = datetime.utcnow()
|
||||
db.flush()
|
||||
|
||||
|
||||
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}")
|
||||
lines.append(f"\n_Synced at {datetime.utcnow().isoformat()}_")
|
||||
return "\n".join(lines)
|
||||
96
backend/app/services/tempo_service.py
Normal file
96
backend/app/services/tempo_service.py
Normal file
@@ -0,0 +1,96 @@
|
||||
"""Tempo time-tracking integration service."""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import settings
|
||||
from app.domain.exceptions import InvalidOperationError
|
||||
from app.models.jira_link import JiraLink
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_tempo_client():
|
||||
"""Return a Tempo API client, or raise if disabled."""
|
||||
if not settings.TEMPO_ENABLED:
|
||||
raise InvalidOperationError("Tempo integration is not enabled")
|
||||
try:
|
||||
from tempoapiclient import client_v4 as tempo_client
|
||||
|
||||
return tempo_client.Tempo(auth_token=settings.TEMPO_API_TOKEN)
|
||||
except ImportError:
|
||||
raise InvalidOperationError(
|
||||
"tempo-api-python-client is not installed. "
|
||||
"Install it with: pip install tempo-api-python-client"
|
||||
)
|
||||
|
||||
|
||||
def log_worklog(
|
||||
jira_issue_id: int,
|
||||
author_account_id: str,
|
||||
date: str,
|
||||
time_spent_seconds: int,
|
||||
description: str,
|
||||
) -> dict:
|
||||
"""Create a worklog entry in Tempo."""
|
||||
tempo = get_tempo_client()
|
||||
worklog = tempo.create_worklog(
|
||||
accountId=author_account_id,
|
||||
issueId=jira_issue_id,
|
||||
dateFrom=date,
|
||||
timeSpentSeconds=time_spent_seconds,
|
||||
description=description,
|
||||
)
|
||||
return worklog
|
||||
|
||||
|
||||
def auto_log_test_worklog(
|
||||
db: Session,
|
||||
test,
|
||||
user,
|
||||
activity_type: str,
|
||||
) -> Optional[dict]:
|
||||
"""If the test has a Jira link, log time to Tempo automatically.
|
||||
|
||||
Returns the Tempo worklog response, or None if skipped.
|
||||
"""
|
||||
if not settings.TEMPO_ENABLED:
|
||||
return None
|
||||
|
||||
link = (
|
||||
db.query(JiraLink)
|
||||
.filter(JiraLink.entity_id == test.id, JiraLink.entity_type == "test")
|
||||
.first()
|
||||
)
|
||||
|
||||
if not link or not link.jira_issue_id:
|
||||
logger.debug("No Jira link for test %s, skipping Tempo worklog", test.id)
|
||||
return None
|
||||
|
||||
duration = _calculate_duration(test, activity_type)
|
||||
if duration <= 0:
|
||||
return None
|
||||
|
||||
try:
|
||||
result = log_worklog(
|
||||
jira_issue_id=int(link.jira_issue_id),
|
||||
author_account_id=getattr(user, "jira_account_id", "") or "",
|
||||
date=test.created_at.strftime("%Y-%m-%d"),
|
||||
time_spent_seconds=duration,
|
||||
description=f"[Aegis] {activity_type}: {test.name}",
|
||||
)
|
||||
logger.info("Tempo worklog created for test %s, %ds", test.id, duration)
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.warning("Tempo worklog failed for test %s: %s", test.id, e, exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
def _calculate_duration(test, activity_type: str) -> int:
|
||||
"""Estimate duration in seconds based on test timestamps and activity type."""
|
||||
if activity_type == "execution" and test.execution_date and test.created_at:
|
||||
delta = test.execution_date - test.created_at
|
||||
return max(int(delta.total_seconds()), 0)
|
||||
return 3600 # default 1 hour if no timestamps available
|
||||
75
backend/app/services/worklog_service.py
Normal file
75
backend/app/services/worklog_service.py
Normal file
@@ -0,0 +1,75 @@
|
||||
"""Internal worklog service — CRUD with integrity hashing."""
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.worklog import Worklog
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def create_worklog(
|
||||
db: Session,
|
||||
*,
|
||||
entity_type: str,
|
||||
entity_id: UUID,
|
||||
user_id: UUID,
|
||||
activity_type: str,
|
||||
started_at: datetime,
|
||||
duration_seconds: int,
|
||||
ended_at: Optional[datetime] = None,
|
||||
description: Optional[str] = None,
|
||||
) -> Worklog:
|
||||
"""Create a worklog with an auto-computed integrity hash."""
|
||||
wl = Worklog(
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
user_id=user_id,
|
||||
activity_type=activity_type,
|
||||
started_at=started_at,
|
||||
ended_at=ended_at,
|
||||
duration_seconds=duration_seconds,
|
||||
description=description,
|
||||
)
|
||||
wl.integrity_hash = _compute_hash(wl)
|
||||
db.add(wl)
|
||||
db.commit()
|
||||
db.refresh(wl)
|
||||
return wl
|
||||
|
||||
|
||||
def list_worklogs(
|
||||
db: Session,
|
||||
*,
|
||||
entity_type: Optional[str] = None,
|
||||
entity_id: Optional[UUID] = None,
|
||||
user_id: Optional[UUID] = None,
|
||||
) -> list[Worklog]:
|
||||
"""List worklogs with optional filters."""
|
||||
query = db.query(Worklog)
|
||||
if entity_type:
|
||||
query = query.filter(Worklog.entity_type == entity_type)
|
||||
if entity_id:
|
||||
query = query.filter(Worklog.entity_id == entity_id)
|
||||
if user_id:
|
||||
query = query.filter(Worklog.user_id == user_id)
|
||||
return query.order_by(Worklog.started_at.desc()).all()
|
||||
|
||||
|
||||
def verify_worklog_integrity(wl: Worklog) -> bool:
|
||||
"""Return True if the worklog has not been tampered with."""
|
||||
return wl.integrity_hash == _compute_hash(wl)
|
||||
|
||||
|
||||
def _compute_hash(wl: Worklog) -> str:
|
||||
"""SHA-256 of the immutable fields for audit integrity."""
|
||||
data = (
|
||||
f"{wl.entity_type}:{wl.entity_id}:{wl.user_id}:"
|
||||
f"{wl.activity_type}:{wl.started_at}:{wl.duration_seconds}"
|
||||
)
|
||||
return hashlib.sha256(data.encode()).hexdigest()
|
||||
Reference in New Issue
Block a user