-
Notifications
You must be signed in to change notification settings - Fork 40
feat(backend): add ControlVerificationTemplate table and CRUD endpoints #229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
AaronAlijani
wants to merge
3
commits into
main
Choose a base branch
from
feature/26T1-BAC-AA-verification-templates
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
60 changes: 60 additions & 0 deletions
60
backend-api/alembic/versions/8a7b91ea95d9_add_control_verification_template.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| """add control verification template | ||
|
|
||
| Revision ID: 8a7b91ea95d9 | ||
| Revises: j1k2l3m4n567 | ||
| Create Date: 2026-05-08 09:22:25.327975 | ||
|
|
||
| """ | ||
| from typing import Sequence, Union | ||
|
|
||
| from alembic import op | ||
| import sqlalchemy as sa | ||
| from sqlalchemy.dialects import postgresql | ||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision: str = '8a7b91ea95d9' | ||
| down_revision: Union[str, Sequence[str], None] = 'j1k2l3m4n567' | ||
| branch_labels: Union[str, Sequence[str], None] = None | ||
| depends_on: Union[str, Sequence[str], None] = None | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| """Upgrade schema.""" | ||
| op.create_table( | ||
| 'control_verification_template', | ||
| sa.Column('id', sa.Integer(), nullable=False), | ||
| sa.Column('framework', sa.String(length=50), nullable=False), | ||
| sa.Column('benchmark', sa.String(length=100), nullable=False), | ||
| sa.Column('version', sa.String(length=20), nullable=False), | ||
| sa.Column('control_id', sa.String(length=50), nullable=False), | ||
| sa.Column('title', sa.String(length=200), nullable=False), | ||
| sa.Column('instructions', sa.Text(), nullable=False), | ||
| sa.Column('keywords', postgresql.JSONB(astext_type=sa.Text()), nullable=False), | ||
| sa.Column('severity', sa.String(length=20), nullable=False), | ||
| sa.Column('evidence_type', sa.String(length=50), nullable=True), | ||
| sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False), | ||
| sa.Column('updated_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False), | ||
| sa.PrimaryKeyConstraint('id'), | ||
| sa.UniqueConstraint( | ||
| 'framework', | ||
| 'benchmark', | ||
| 'version', | ||
| 'control_id', | ||
| name='uq_template_framework_benchmark_version_control', | ||
| ), | ||
| ) | ||
| op.create_index( | ||
| op.f('ix_control_verification_template_control_id'), | ||
| 'control_verification_template', | ||
| ['control_id'], | ||
| unique=False, | ||
| ) | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| """Downgrade schema.""" | ||
| op.drop_index( | ||
| op.f('ix_control_verification_template_control_id'), | ||
| table_name='control_verification_template', | ||
| ) | ||
| op.drop_table('control_verification_template') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,213 @@ | ||
| """CRUD endpoints for ControlVerificationTemplate. | ||
|
|
||
| Powers the manual control verification workflow: admins maintain the | ||
| templates that auditors see when verifying pending manual controls. | ||
|
|
||
| Identity: | ||
| Each template is uniquely identified by the | ||
| (framework, benchmark, version, control_id) tuple. This matches the | ||
| same tuple Scan already uses (see app/api/v1/scans.py) so the lookup | ||
| pattern is consistent end-to-end and the same control_id can carry | ||
| different instructions across benchmark versions and across frameworks. | ||
|
|
||
| Authorisation: | ||
| - POST / PATCH / DELETE: admin only (templates are GRC content; auditors | ||
| consume them but do not author them). | ||
| - GET endpoints: any authenticated user (auditors and viewers need read | ||
| access to surface instructions in the UI). | ||
| """ | ||
|
|
||
| from fastapi import APIRouter, Depends, HTTPException, status | ||
| from sqlalchemy import select | ||
| from sqlalchemy.ext.asyncio import AsyncSession | ||
|
|
||
| from app.core.auth import get_current_user | ||
| from app.core.permissions import require_admin | ||
| from app.db.session import get_async_session | ||
| from app.models.control_verification_template import ControlVerificationTemplate | ||
| from app.models.user import User | ||
| from app.schemas.control_verification_template import ( | ||
| ControlVerificationTemplateCreate, | ||
| ControlVerificationTemplateRead, | ||
| ControlVerificationTemplateUpdate, | ||
| ) | ||
|
|
||
| router = APIRouter( | ||
| prefix="/verification-templates", | ||
| tags=["Verification Templates"], | ||
| ) | ||
|
|
||
|
|
||
| # ── Internal helpers ──────────────────────────────────────────────────── | ||
|
|
||
|
|
||
| async def _get_template_or_404( | ||
| db: AsyncSession, | ||
| framework: str, | ||
| benchmark: str, | ||
| version: str, | ||
| control_id: str, | ||
| ) -> ControlVerificationTemplate: | ||
| """Fetch the template for the given tuple or raise 404.""" | ||
| result = await db.execute( | ||
| select(ControlVerificationTemplate).where( | ||
| ControlVerificationTemplate.framework == framework, | ||
| ControlVerificationTemplate.benchmark == benchmark, | ||
| ControlVerificationTemplate.version == version, | ||
| ControlVerificationTemplate.control_id == control_id, | ||
| ) | ||
| ) | ||
| template = result.scalar_one_or_none() | ||
| if template is None: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_404_NOT_FOUND, | ||
| detail=( | ||
| f"Template for {framework}/{benchmark}/{version}/{control_id} not found" | ||
| ), | ||
| ) | ||
| return template | ||
|
|
||
|
|
||
| # ── Endpoints ─────────────────────────────────────────────────────────── | ||
|
|
||
|
|
||
| @router.post( | ||
| "/", | ||
| response_model=ControlVerificationTemplateRead, | ||
| status_code=status.HTTP_201_CREATED, | ||
| summary="Create a verification template (admin only)", | ||
| ) | ||
| async def create_template( | ||
| data: ControlVerificationTemplateCreate, | ||
| db: AsyncSession = Depends(get_async_session), | ||
| _: User = Depends(require_admin), | ||
| ) -> ControlVerificationTemplate: | ||
| """Create a new verification template for a manual control. | ||
|
|
||
| Returns 409 Conflict if a template for the given | ||
| (framework, benchmark, version, control_id) tuple already exists. | ||
| """ | ||
| result = await db.execute( | ||
| select(ControlVerificationTemplate).where( | ||
| ControlVerificationTemplate.framework == data.framework, | ||
| ControlVerificationTemplate.benchmark == data.benchmark, | ||
| ControlVerificationTemplate.version == data.version, | ||
| ControlVerificationTemplate.control_id == data.control_id, | ||
| ) | ||
| ) | ||
| if result.scalar_one_or_none() is not None: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_409_CONFLICT, | ||
| detail=( | ||
| f"Template for {data.framework}/{data.benchmark}/" | ||
| f"{data.version}/{data.control_id} already exists" | ||
| ), | ||
| ) | ||
|
|
||
| template = ControlVerificationTemplate(**data.model_dump()) | ||
| db.add(template) | ||
| await db.commit() | ||
| await db.refresh(template) | ||
| return template | ||
|
|
||
|
|
||
| @router.get( | ||
| "/", | ||
| response_model=list[ControlVerificationTemplateRead], | ||
| summary="List verification templates", | ||
| ) | ||
| async def list_templates( | ||
| db: AsyncSession = Depends(get_async_session), | ||
| _: User = Depends(get_current_user), | ||
| framework: str | None = None, | ||
| benchmark: str | None = None, | ||
| version: str | None = None, | ||
| ) -> list[ControlVerificationTemplate]: | ||
| """List verification templates, optionally filtered by framework/benchmark/version. | ||
|
|
||
| Sorted by (framework, benchmark, version, control_id) so output is stable | ||
| across calls. Phase 2 seeding scripts can pass the tuple to fetch only | ||
| the templates for a single benchmark version. | ||
| """ | ||
| query = select(ControlVerificationTemplate) | ||
| if framework is not None: | ||
| query = query.where(ControlVerificationTemplate.framework == framework) | ||
| if benchmark is not None: | ||
| query = query.where(ControlVerificationTemplate.benchmark == benchmark) | ||
| if version is not None: | ||
| query = query.where(ControlVerificationTemplate.version == version) | ||
| query = query.order_by( | ||
| ControlVerificationTemplate.framework, | ||
| ControlVerificationTemplate.benchmark, | ||
| ControlVerificationTemplate.version, | ||
| ControlVerificationTemplate.control_id, | ||
| ) | ||
|
|
||
| result = await db.execute(query) | ||
| return list(result.scalars().all()) | ||
|
|
||
|
|
||
| @router.get( | ||
| "/{framework}/{benchmark}/{version}/{control_id}", | ||
| response_model=ControlVerificationTemplateRead, | ||
| summary="Get a verification template by (framework, benchmark, version, control_id)", | ||
| ) | ||
| async def get_template( | ||
| framework: str, | ||
| benchmark: str, | ||
| version: str, | ||
| control_id: str, | ||
| db: AsyncSession = Depends(get_async_session), | ||
| _: User = Depends(get_current_user), | ||
| ) -> ControlVerificationTemplate: | ||
| """Fetch the verification template for the given tuple.""" | ||
| return await _get_template_or_404(db, framework, benchmark, version, control_id) | ||
|
|
||
|
|
||
| @router.patch( | ||
| "/{framework}/{benchmark}/{version}/{control_id}", | ||
| response_model=ControlVerificationTemplateRead, | ||
| summary="Partially update a verification template (admin only)", | ||
| ) | ||
| async def update_template( | ||
| framework: str, | ||
| benchmark: str, | ||
| version: str, | ||
| control_id: str, | ||
| data: ControlVerificationTemplateUpdate, | ||
| db: AsyncSession = Depends(get_async_session), | ||
| _: User = Depends(require_admin), | ||
| ) -> ControlVerificationTemplate: | ||
| """Partially update a template. Only fields provided in the body are applied. | ||
|
|
||
| Explicit null values for non-nullable fields are rejected by the schema | ||
| validator (422), not allowed through to the DB. | ||
| """ | ||
| template = await _get_template_or_404(db, framework, benchmark, version, control_id) | ||
|
|
||
| update_fields = data.model_dump(exclude_unset=True) | ||
| for field, value in update_fields.items(): | ||
| setattr(template, field, value) | ||
|
|
||
| await db.commit() | ||
| await db.refresh(template) | ||
| return template | ||
|
|
||
|
|
||
| @router.delete( | ||
| "/{framework}/{benchmark}/{version}/{control_id}", | ||
| status_code=status.HTTP_204_NO_CONTENT, | ||
| summary="Delete a verification template (admin only)", | ||
| ) | ||
| async def delete_template( | ||
| framework: str, | ||
| benchmark: str, | ||
| version: str, | ||
| control_id: str, | ||
| db: AsyncSession = Depends(get_async_session), | ||
| _: User = Depends(require_admin), | ||
| ) -> None: | ||
| """Delete the verification template for the given tuple.""" | ||
| template = await _get_template_or_404(db, framework, benchmark, version, control_id) | ||
| await db.delete(template) | ||
| await db.commit() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| """ControlVerificationTemplate model. | ||
|
|
||
| Stores per-control auditor instructions, keywords, and severity for the manual | ||
| controls that AutoAudit cannot automate via the M365 collectors. Each row is | ||
| uniquely identified by the (framework, benchmark, version, control_id) tuple | ||
| so that the same control_id can carry different instructions across CIS | ||
| benchmark versions (e.g. "1.1.2" in v3.1.0 vs v6.0.0) and across frameworks | ||
| (e.g. CIS M365 vs future Azure benchmarks). | ||
|
|
||
| Powers the semi-automated manual verification workflow: the auditor opens a | ||
| pending manual control, sees the instructions, uploads evidence, and the | ||
| validator matches the keywords to suggest a verdict. | ||
|
|
||
| Keywords are stored as JSONB to match the patterns already used by | ||
| EvidenceValidation.matches_json and ScanResult.evidence. | ||
| """ | ||
|
|
||
| from datetime import datetime | ||
| from typing import Optional | ||
|
|
||
| from sqlalchemy import DateTime, Integer, String, Text, UniqueConstraint | ||
| from sqlalchemy.dialects.postgresql import JSONB | ||
| from sqlalchemy.orm import Mapped, mapped_column | ||
| from sqlalchemy.sql import func | ||
|
|
||
| from app.db.base import Base | ||
|
|
||
|
|
||
| class ControlVerificationTemplate(Base): | ||
| """Verification template for a single manual control within a framework/benchmark/version.""" | ||
|
|
||
| __tablename__ = "control_verification_template" | ||
|
|
||
| id: Mapped[int] = mapped_column(Integer, primary_key=True) | ||
|
|
||
| # Framework/benchmark/version tuple — mirrors Scan.framework/benchmark/version | ||
| # so the lookup pattern (and column types) are consistent across the schema. | ||
| framework: Mapped[str] = mapped_column(String(50), nullable=False) | ||
| benchmark: Mapped[str] = mapped_column(String(100), nullable=False) | ||
| version: Mapped[str] = mapped_column(String(20), nullable=False) | ||
|
|
||
| # CIS control identifier within the (framework, benchmark, version) above, | ||
| # e.g. "1.1.2". Must match scan_result.control_id for the same tuple. | ||
| control_id: Mapped[str] = mapped_column(String(50), nullable=False, index=True) | ||
|
|
||
| # Human-readable control title from the benchmark. | ||
| title: Mapped[str] = mapped_column(String(200), nullable=False) | ||
|
|
||
| # Numbered, portal-specific auditor instructions. | ||
| instructions: Mapped[str] = mapped_column(Text, nullable=False) | ||
|
|
||
| # List of keywords expected to appear in compliant evidence. | ||
| # JSONB so we can index/query individual keywords later if needed. | ||
| keywords: Mapped[list] = mapped_column(JSONB, nullable=False) | ||
|
|
||
| # Risk severity: "high" | "medium" | "low". Enforced at the API layer via | ||
| # the Pydantic Literal type on the Create/Update schemas. | ||
| severity: Mapped[str] = mapped_column(String(20), nullable=False) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The comment above shows what the values should be, but there's no actual enforcement that what's coming in here matches those values. If this is what we expect to see, we should enforce this - Pydantic supports the concept of a |
||
|
|
||
| # Expected evidence format: "screenshot" | "pdf_export" | "comment_only". | ||
| evidence_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True) | ||
|
|
||
| created_at: Mapped[datetime] = mapped_column( | ||
| DateTime, nullable=False, server_default=func.now() | ||
| ) | ||
| updated_at: Mapped[datetime] = mapped_column( | ||
| DateTime, nullable=False, server_default=func.now(), onupdate=func.now() | ||
| ) | ||
|
|
||
| __table_args__ = ( | ||
| UniqueConstraint( | ||
| "framework", | ||
| "benchmark", | ||
| "version", | ||
| "control_id", | ||
| name="uq_template_framework_benchmark_version_control", | ||
| ), | ||
| ) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a PATCH request explicitly sends
nullfor non-nullable fields such astitle,instructions,keywords, orseverity, the update schema accepts it andexclude_unset=Truestill includes that field, so this loop writesNoneto columns declarednullable=False. In that scenario the subsequent commit raises a database integrity error and returns a 500 instead of a client error; either disallowNonein the update schema or reject provided nulls before assigning.Useful? React with 👍 / 👎.